query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Counts the how many rows belong to each class in a dataset. | def classCounts(rows):
counts = {}
for row in rows:
# in our data set format, the label is always the last column
label = row[-1]
if label not in counts:
counts[label] = 1
else:
counts[label] += 1
return counts | [
"def get_class_counts(data):\n y = data['class']\n num_pos = np.count_nonzero(y == 1)\n num_neg = np.count_nonzero(y == 0)\n return (num_neg, num_pos)",
"def count(self, cls=None):\n all_classes = classes.values()\n if cls:\n counter = len(models.storage.all(cls).values())\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if a value is numeric. | def isNumeric(value):
return isinstance(value, int) or isinstance(value, float) | [
"def _is_numeric(v):\n try:\n float(v)\n return True\n except ValueError:\n return False",
"def is_numeric(x) -> bool:\n try:\n x = float(x)\n return True\n except ValueError:\n return False",
"def is_numeric(x):\n \n try:\n float(x)\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the Gini Impurity for a list of rows. | def gini(rows):
counts = classCounts(rows)
impurity = 1
for label in counts:
labelProbability = counts[label] / float(len(rows))
impurity -= labelProbability ** 2
return impurity | [
"def findImpurity(self, rows):\n isEntropy = self.criterion == 'entropy'\n counts = class_counts(rows)\n impurity = 0 if isEntropy else 1\n #Gini = 1 - sum(pi**2)\n if isEntropy:\n for lbl in counts:\n prob_of_lbl = counts[lbl] / float(len(rows))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns list of tuples (article_id, prediction, label). Predicts tensorflow dataset in batches. | def batch_predict(tf_ds, batch_size, prediction_func):
evaluation_data = []
for aids, inps, lbls in tf_ds.batch(batch_size).as_numpy_iterator():
ps = prediction_func(inps)
evaluation_data += zip(aids, ps, lbls)
return evaluation_data | [
"def get_train_data(self, batch_size):\n train = self._get_pickle('train')\n batch_a, batch_l = [], []\n questions, answers, labels = [], [], []\n\n for item in train:\n for answer_id in item['answers']:\n batch_a.append(self._get_answer(answer_id))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test new and current version functions. | def test_versions(self):
self.assertEqual(Project.objects.current_version("test3"), 2)
self.assertEqual(Project.objects.next_version("test3"), 3)
self.assertEqual(Project.objects.current_version("dne"), 0)
self.assertEqual(Project.objects.next_version("dne"), 1) | [
"def test_versions(self):\n versions = self._project.versions()\n self.assertTrue(\"0.1\" in versions)",
"def test_version_matches_expected():\n assert __version__ == \"0.1.0\"",
"def test_show_version(self):\n version = 'Iteration ' + __init__.__version__\n self.assertEqual(news_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return an integer, being x rounded towards positive infinity. | def ceil(x) -> int:
pass | [
"def floor(x) -> int:\n pass",
"def floor(x):\n return 0.0",
"def iround(x):\n return int(round(x))",
"def int_of_x(x):\n try:\n return int(x)\n\n except Exeption:\n return -1",
"def floor(n: float) -> int:\n return (int(n//1))",
"def ifloor(x):\n\n return np.flo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return an integer, being x rounded towards negative infinity. | def floor(x) -> int:
pass | [
"def ceil(x) -> int:\n pass",
"def int_of_x(x):\n try:\n return int(x)\n\n except Exeption:\n return -1",
"def iround(x):\n return int(round(x))",
"def floor(x):\n return 0.0",
"def floor(n: float) -> int:\n return (int(n//1))",
"def ifloor(x):\n\n return np.floo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if x is finite. | def isfinite(x) -> bool:
pass | [
"def isFinite(self) -> bool:\n if np.isfinite(self.data).all():\n return True\n return False",
"def is_finite(self):\r\n return not self._is_special",
"def is_finite(val):\n return type(val) in (float,int) and val not in (infinity, -infinity, nan)",
"def is_finite(self):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the base2 logarithm of x. | def log2(x):
pass | [
"def log2(x):\n ln2 = torch.log(torch.FloatTensor([2.0]))\n if x.is_cuda:\n ln2 = ln2\n return torch.log(x) / ln2",
"def log(x, base=e):\n return 1.0",
"def base_two_log(n):\n if n < 2:\n return 0\n else:\n return 1+base_two_log(n//2)",
"def log2(num):\n if is_power_o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns x to the power of y. | def pow(x, y):
pass | [
"def pow(x, y):\n return 1.0",
"def pow2(x, y=None):\n if y is None:\n z = (2. * np.ones(len(x))) ** x\n else:\n z = x * ((2. * np.ones(len(y))) ** y)\n\n return z",
"def bprop_scalar_pow(x, y, out, dout):\n return (scalar_mul(dout, scalar_mul(y, scalar_pow(x, scalar_sub(y, 1)))),\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sum the contents of the vector. >>> v = ... >>> s = v.abssum() | def _ve_asum_ ( s ) :
return Ostap.Math.abssum ( s ) | [
"def sum(x):\n\treturn np.sum(x)",
"def get_vsum(vk, skm, omega):\n summand = 0.5*vk*skm\n vsum = 1/omega* summand.sum()\n return vsum",
"def summation(values: np.array) -> float:\n value = np.sum(values)\n return value",
"def sum(sequence):\n return __builtin__.sum(sequence)",
"def back_sub... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Equality for ValueWithError objects >>> a = VE( ... ) >>> b = VE( ... ) >>> print a == b | def _ve_eq_ ( self , other ) :
if isinstance ( other , VE ) :
v1 = self .value()
v2 = other.value()
return _is_equal_ ( v1 , v2 ) and _is_equal_ ( self.cov2() , other.cov2() )
elif _is_zero_ ( self.cov2() ) :
return _is_equal_ ( float ( self ) , float ( other ) )
else :
... | [
"def same_values(self, v1, v2):\n return v1 == v2",
"def __eq__(self, other):\n if not isinstance(other, self._uflclass):\n return isinstance(other, (int,float)) and other == self._value\n else:\n return self._value == other._value",
"def myEqu(self, other):\n resul... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Inequality for ValueWithError objects >>> a = VE( ... ) >>> b = VE( ... ) >>> print a != b | def _ve_ne_ ( self , other ) :
try:
return not self == other
except NotImplementedError :
raise NotImplementedError ( ' Inequality for %s and %s is not implemented' % ( self , other ) ) | [
"def test_notequal(self):\r\n f1 = Fraction(1, 3)\r\n f2 = Fraction(1, 7)\r\n f3 = Fraction(-3, -9)\r\n self.assertFalse(f1 != f1)\r\n self.assertTrue(f1 != f2)\r\n self.assertFalse(f1 != f3)\r\n self.assertTrue(f2 != f3)\r\n self.assertTrue(f1 != Fraction(-1,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
HAshing function for VE objecte >>> v = VE ( ... ) >>> h = hash ( v ) | def _ve_hash_ ( v ) :
return hash ( ( v.value() , v.cov2() ) ) | [
"def get_hash(self, descriptor):",
"def hash(self, object):\r\n # TODO: can we add overflow support for collisions?\r\n return md5.new(repr(object)).hexdigest()",
"def hash_vector(self, v, querying=False):\n raise NotImplementedError",
"def __hash__(self):\n # we assume the largest... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the gaussian random number >>> v = ... the number with error get 100 random numbers | def _ve_gauss_ ( s , accept = lambda a : True , nmax = 1000 ) :
#
if 0 >= s.cov2() or iszero ( s.cov2 () ) : return s.value() ## return
#
v = s.value ()
e = s.error ()
#
for i in range ( nmax ) :
r = _gauss ( v , e )
if accept ( r ) : return r
logger.war... | [
"def gaussian( x, mu, var):\n\treturn np.exp(-np.power(x - mu, 2.) / (2 * np.power(var, 2.)))",
"def SpecialGauss(self,mean, sigma):\n rand = 10.0 * sigma\n while abs(rand) > 2.0 * sigma:\n rand = random.gauss(0,sigma)\n return(rand + mean)",
"def gaussian(x, mu, sigma):\r\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a host group. | def get(self, group_name):
g = self.request.mongo_connection.shinken.hostgroups.find_one(
{"hostgroup_name": group_name}, {'_id': 0}
)
return hostgroup.HostGroup(**g) | [
"def get_hostgroup_by_name(self, name):\n group = self.db_session.query(HostGroup)\\\n .filter(HostGroup.name == name)\\\n .first()\n return group",
"def get_hostgroup(hostgroup, limit = None, columns = None, extra_filter = None):\n return query(\"GET hostgroups\\nFilter: na... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify an existing host group. | def update(self, group_name, group):
group_dict = group.as_dict()
if "hostgroup_name" not in group_dict.keys():
group_dict['hostgroup_name'] = group_name
self.request.mongo_connection.shinken.hostgroups.update(
{"hostgroup_name": group_name},
group_dict
... | [
"def modify_host_group(self, host_group_id, name=None,\n remove_host_ids=None,\n add_host_ids=None, description=None):\n LOG.info(\"Modifying hostgroup: '%s'\" % host_group_id)\n payload = self._prepare_modify_host_group_payload(\n name, rem... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete existing host group. | def delete(self, group_name):
self.request.mongo_connection.shinken.hostgroups.remove(
{"hostgroup_name": group_name}
) | [
"def test_delete_host_group(self):\n pass",
"def delete_hgrp(self, name):\n return self.host_group_manager.delete_object(name)",
"def test_delete_host_from_group(self):\n pass",
"def delete_host_group(self, host_group_id):\n LOG.info(\"Deleting hostgroup: '%s'\" % host_group_id)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new host group. | def create(self, group):
self.request.mongo_connection.shinken.hostgroups.insert(
group.as_dict()
) | [
"def _create_hostgroup(self, hostgroupname):\n cli_cmd = 'createhostgroup -n %(name)s' % {'name': hostgroupname}\n out = self._execute_cli(cli_cmd)\n\n self._assert_cli_operate_out('_create_hostgroup',\n ('Failed to Create hostgroup %s.'\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return all host groups. | def get_all(self):
hostgroups = [g for g
in self.request.mongo_connection.
shinken.hostgroups.find(
{"register": {"$ne": "0"}},
{'_id': 0}
)]
hostgroups = [hostgroup.HostGroup(**g) for g... | [
"def list_server_groups(self):\n return self.__get('/v1/groups')",
"def get_all_servicegroups(self):\n\n return self.make_request('get_all_servicegroups')",
"def getgrall():\r\n groups = []\r\n while True:\r\n group = _posix_impl.getgrent()\r\n if not group:\r\n brea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test default password store discovery in command line interface. | def test_cli_defaults(self):
with MockedHomeDirectory() as home:
touch(os.path.join(home, ".password-store", "the-only-entry.gpg"))
returncode, output = run_cli(main, "-l")
assert returncode == 0
entries = output.splitlines(False)
assert entries == ["t... | [
"def test_password_prompt(self, fake_getpass, fake_stderr):\n cli_args = ['--clusters', 'myCluster', '--location', '/foo', '--username', 'pat']\n\n iiqtools_cluster_backup.parse_args(cli_args)\n\n fake_getpass.assert_called()",
"def test_config_nopass_askpass(fakeClient, tmpconfigfile, monkey... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test error handling of invalid command line options. | def test_cli_invalid_option(self):
returncode, output = run_cli(main, "-x", merged=True)
assert returncode != 0
assert "Error:" in output | [
"def test_check_options_exception(self, hp, opts):\n with pytest.raises(ValueError, match=\"XXX\"):\n check_is_in_options(hp, opts, msg=\"XXX\")",
"def test_cli_option_errors(self):\n stderr = self.getCliErrorMessages(\n args=[\"__non_existent_wrapper__\", \"__non_existent_scri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the output of ``qpass list``. | def test_cli_list(self):
with TemporaryDirectory() as directory:
touch(os.path.join(directory, "foo.gpg"))
touch(os.path.join(directory, "foo/bar.gpg"))
touch(os.path.join(directory, "Also with spaces.gpg"))
returncode, output = run_cli(main, "--password-store=%s"... | [
"def test_list(self):\n stdout = six.StringIO()\n Switch.objects.create(name='switch1', active=True)\n Switch.objects.create(name='switch2', active=False)\n\n call_command('waffle_switch', list_switches=True, stdout=stdout)\n expected = 'Switches:\\nswitch1: on\\nswitch2: off'\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the output of ``qpass exclude=... list``. | def test_cli_exclude(self):
with TemporaryDirectory() as directory:
touch(os.path.join(directory, "foo.gpg"))
touch(os.path.join(directory, "foo/bar.gpg"))
touch(os.path.join(directory, "Also with spaces.gpg"))
returncode, output = run_cli(main, "--password-store=... | [
"def test_3_exclude():\n run_main_and_compare([\"scrapbook_test_data\", \"tmp/test-exclude.rdf\", \"--exclude\", \"1\", \"4\"],\n \"samples/standard_1_4_excluded.rdf\", \"tmp/test-exclude.rdf\")",
"def test_exclude_filelist(self):\n self.ParseTest([(\"--exclude-filelist\", \"file... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the command line usage message. | def test_cli_usage(self):
for options in [], ["-h"], ["--help"]:
returncode, output = run_cli(main, *options)
assert "Usage:" in output | [
"def usage():\n if len(sys.argv) < 2 or sys.argv[1] == '-h' or sys.argv[1] == '--help':\n print(usageMsg)\n exit(0)",
"def usage (usageString):\n command = os.path.basename (sys.argv[0])\n if (usageString):\n sys.stderr.write ('usage: %s %s\\n' % (command, usageString))\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the detection whether the clipboard should be used. | def test_clipboard_enabled(self):
# Make sure the clipboard is enabled by default on macOS.
if platform.system().lower() == "darwin":
assert is_clipboard_supported() is True
else:
# Make sure the clipboard is used when $DISPLAY is set.
with PatchedItem(os.envi... | [
"def can_copy(self):\n return self._control.textCursor().hasSelection()",
"def enablePaste(self) -> bool:\n ...",
"def canPaste(self, availableFlavors: List[java.awt.datatransfer.DataFlavor]) -> bool:\n ...",
"def can_paste(self):\n if self._control.textInteractionFlags() & QtCore.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test editing of an entry on the command line. | def test_edit_entry(self):
# Create a fake password store that we can test against.
with TemporaryDirectory() as directory:
touch(os.path.join(directory, "Personal", "Zabbix.gpg"))
touch(os.path.join(directory, "Work", "Zabbix.gpg"))
# Make sure we're not running the ... | [
"def test_command_edit(self):\n pass",
"def test_admin_edit_approved_entry(self):\r\n self.client.logout()\r\n self.login_user(self.superuser)\r\n\r\n url, entry, data = self.edit_entry_helper()\r\n\r\n response = self.client.get(url)\r\n self.assertEqual(response.status_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the EmptyPasswordStoreError exception. | def test_empty_password_store_error(self):
with TemporaryDirectory() as directory:
program = PasswordStore(directory=directory)
self.assertRaises(EmptyPasswordStoreError, program.smart_search) | [
"def test_missing_password_store_error(self):\n with TemporaryDirectory() as directory:\n missing = os.path.join(directory, \"missing\")\n program = PasswordStore(directory=missing)\n self.assertRaises(MissingPasswordStoreError, program.ensure_directory_exists)",
"def test_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test human friendly formatting of password store entries. | def test_format_text(self):
entry = PasswordEntry(name="some/random/password", store=object())
set_property(entry, "text", random_string())
self.assertEquals(
# We enable ANSI escape sequences but strip them before we
# compare the generated string. This may seem rather p... | [
"def test_get_password(self):\n random_password = random_string()\n entry = PasswordEntry(name=\"some/random/password\", store=object())\n set_property(entry, \"text\", \"\\n\".join([random_password, \"\", \"This is the description\"]))\n self.assertEquals(random_password, entry.password... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test getting a password from an entry. | def test_get_password(self):
random_password = random_string()
entry = PasswordEntry(name="some/random/password", store=object())
set_property(entry, "text", "\n".join([random_password, "", "This is the description"]))
self.assertEquals(random_password, entry.password) | [
"def test_password_field(self):\n\n rv = self.client.get('/register')\n assert 'Password' in rv.data",
"def test_ask_question__password(self, _):\n input_value = self.user_manager.ask_question('field', password=True)\n\n self.assertEqual(input_value, 'password')",
"def test_check_pw_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the MissingPasswordStoreError exception. | def test_missing_password_store_error(self):
with TemporaryDirectory() as directory:
missing = os.path.join(directory, "missing")
program = PasswordStore(directory=missing)
self.assertRaises(MissingPasswordStoreError, program.ensure_directory_exists) | [
"def test_empty_password_store_error(self):\n with TemporaryDirectory() as directory:\n program = PasswordStore(directory=directory)\n self.assertRaises(EmptyPasswordStoreError, program.smart_search)",
"def test_no_matching_password_error(self):\n with TemporaryDirectory() as d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the NoMatchingPasswordError exception. | def test_no_matching_password_error(self):
with TemporaryDirectory() as directory:
touch(os.path.join(directory, "Whatever.gpg"))
program = PasswordStore(directory=directory)
self.assertRaises(NoMatchingPasswordError, program.smart_search, "x") | [
"def test_incorrect_password_login(self):\n self.reg_data['password'] = 'wrongpas'\n self.login(code=401, msg='Invalid password: Enter right password to login')",
"def test_incorrectPassword(self):\n response = base64.encodestring('%s:%s' % (\n self.username, 'incorrectPassword'))\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test interactive password selection. | def test_select_entry_interactive(self):
with TemporaryDirectory() as directory:
touch(os.path.join(directory, "foo.gpg"))
touch(os.path.join(directory, "bar.gpg"))
touch(os.path.join(directory, "baz.gpg"))
# Select entries using the command line filter 'a' and th... | [
"def test_ask_question__password(self, _):\n input_value = self.user_manager.ask_question('field', password=True)\n\n self.assertEqual(input_value, 'password')",
"def test_password_prompt(self, fake_getpass, fake_stderr):\n cli_args = ['--clusters', 'myCluster', '--location', '/foo', '--usern... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the element (x) to be pushed in greater than self.min, append to stack If the element (x) to be pushed is smaller than self.min, then append 2x self.min into stack and update self.min | def push(self,x):
if not self.stack:
self.stack.append(x)
self.min = x
return
if x >= self.min:
self.stack.append(x)
else:
self.stack.append((2*x) - self.min)
self.min = x
print("After pushing element {}: {}, min is ... | [
"def pop(self):\n if not self.stack:\n return\n\n top = self.stack[-1]\n self.stack.pop()\n if top < self.min:\n self.min = (2*self.min) - top\n\n print(\"After popping element {}: {}, min is {}\".format(top, self.stack, self.min), end='\\n\\n')",
"def stac... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the popped element(y) is greater than self.min then do nothing If the popped element(y) is smaller than self.min then update self.min = 2self.min y | def pop(self):
if not self.stack:
return
top = self.stack[-1]
self.stack.pop()
if top < self.min:
self.min = (2*self.min) - top
print("After popping element {}: {}, min is {}".format(top, self.stack, self.min), end='\n\n') | [
"def push(self,x):\n if not self.stack:\n self.stack.append(x)\n self.min = x\n return\n if x >= self.min:\n self.stack.append(x)\n else:\n self.stack.append((2*x) - self.min)\n self.min = x\n print(\"After pushing element... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
minstack = MinStackBruteForce() minstack.push(0) minstack.push(5) minstack.push(1) minstack.push(6) minstack.push(0) minstack.push(3) print(minstack.get_min()) minstack.pop() print(minstack.get_min()) minstack.pop() print(minstack.get_min()) sample = [10, 5, 0, 1, 0, 1, 0] print(" Using Bruteforce solution ") | def main():
minstack = MinStackOptimal()
# minstack.push(0)
minstack.push(5)
minstack.push(1)
minstack.push(6)
minstack.push(0)
minstack.push(3)
print(minstack.get_min())
minstack.pop()
print(minstack.get_min())
minstack.pop()
print(minstack.get_min())
print("Printin... | [
"def stack_min(self):\n if not self.next_min[-1]: return self.stack[-1]\n return min(self.next_min[-1], self.stack[-1])",
"def pop(self):\n if not self.stack:\n return\n\n top = self.stack[-1]\n self.stack.pop()\n if top < self.min:\n self.min = (2*s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
wraps the jenkins head configuration and substitute the server alias with one of the server configuration provided by serverAliasesList headConfiguration the configuration of one jenkins head serverAliasesList a list with server configurations | def __init__(self, headConfiguration, serverAliasesList: list):
self.__checkHeadConfiguration(headConfiguration)
self.__checkRequiredServerConfiguration(headConfiguration, serverAliasesList)
self.__mHeadConfiguration = headConfiguration
self.__mServerConfiguration = self.__removeUnneces... | [
"def _expand_variables(self, config, hostname):\n\n if 'hostname' in config:\n config['hostname'] = config['hostname'].replace('%h', hostname)\n else:\n config['hostname'] = hostname\n\n if 'port' in config:\n port = config['port']\n else:\n po... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorator that handles authenticated users (restrict access to the 'sign up', 'login', etc.). | def restrict_authenticated_users(view_func):
@wraps(view_func)
def wrapper_func(view, *args, **kwargs):
if view.request.user.is_authenticated:
return redirect(reverse('posts:all'))
else:
return view_func(view, *args, **kwargs)
return wrapper_func | [
"def _decorator(request, *args, **kwargs):\n is_authenticated = request.user.is_authenticated\n authenticated = is_authenticated if isinstance(is_authenticated, bool)\\\n else is_authenticated()\n if authenticated:\n return func(request, *args, **kwargs)\n if 'HTTP_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the reward/regret for action a for the simple bandit. Use self.q_star (see reset) | def bandit_step(self, a):
# TODO: 2 lines missing.
raise NotImplementedError("")
return reward, regret | [
"def reward(self, state, action):\n return self.reward_matrix[state][action]",
"def reward(self, s = None):\n s = self.state(as_tuple=True) if s == None else s\n s = s if isinstance(s, tuple) else self.legal_states[s]\n return self.rewards[s]",
"def reward(self):\n return self._r_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts arff to pandas dataframe. | def arff2df(data):
arff = liacarff.loads(str(data))
attr = [a[0] for a in arff['attributes']]
return pd.DataFrame(data=arff['data'], columns=attr) | [
"def convert_to_pandas_df(self):\n\n self.fsample = pd.DataFrame(self.fsample)\n self.fevent = pd.DataFrame(self.fevent)\n self.rec = pd.DataFrame(self.rec)",
"def df2arff(df):\n from loaders_savers import load_csv # Imported here because of circular dependencies\n path = 'tmp_tmp432tmp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts pandas dataframe to arff data. | def df2arff(df):
from loaders_savers import load_csv # Imported here because of circular dependencies
path = 'tmp_tmp432tmp123_tm_p_blabla3da.csv' # Stupid name to "ensure" we do not override something
df.to_csv(path, index=False)
try:
data = load_csv(path)
finally:
remove(path)
... | [
"def pandas2arff(df,filename,wekaname = \"pandasdata\",cleanstringdata=False,cleannan=True):\n\n import re\n\n def cleanstring(s):\n if s!=\"?\":\n return re.sub('[^A-Za-z0-9]+', \"_\", str(s))\n else:\n return \"?\"\n\n dfcopy = df #all cleaning operations get done on t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a new section of a class, useful because there may be multiple sections of, say, CSCI1300 | def add_section(class_id, course_title, section_number):
new_section = Section.objects.get_or_create(class_id = class_id)[0]
new_section.course_title = course_title
new_section.section_number = section_number
new_section.save()
return new_section | [
"def new_section(self, doc, *args, **kwargs):\n\n section = Section(doc, *args, **kwargs)\n if section.identifier:\n if section.identifier in self.sections:\n print(f'section identifier {section.identifier!r} already used')\n else:\n self.sections[se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enable creation of a new user, Return the newly added student. | def add_student(student_id, first_name, last_name, password, email_address, course_list, view_url, pic_url):
new_User = User.objects.get_or_create(email = email_address)[0]
new_User.first_name = first_name
new_User.last_name = last_name
new_User.password = password
new_User.username = username
n... | [
"def add_student(conf, backend, args):\n try:\n add_to_roster(\n conf, backend, conf.roster, args.name, args.username, args.section, args.force\n )\n except DuplicateUserError:\n logger.error(\"Student already exists in roster!\")",
"def create(self, *args, **kwargs):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process items to display to be wrapped according to current terminal size. | def item_strings_formatted(self):
#if self._item_strings_formatted and self.width == terminal.width:
# return self._item_strings_formatted
# Reset current wrapped item info
self._item_strings_formatted = []
self.item_onscreenlocs = []
# Take each item to display by ... | [
"def update_terminal_width(*ignored):\n w, h = shutil.get_terminal_size()\n config = IPython.get_ipython().config\n config.PlainTextFormatter.max_width = w - 1\n shell = IPython.core.interactiveshell.InteractiveShell.instance()\n shell.init_display_formatter()\n\n if 'numpy' in sys.modules:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Safely update selected item index. | def item_selected(self, potential_item_selected):
if 0 <= potential_item_selected < len(self.items):
self._item_selected = potential_item_selected | [
"def select(self, item):\n if not item.selected:\n item.selected=True\n self._total_selected+=1\n debug('*** total_selected={}'.format(self._total_selected))",
"def update_selected_slot(self):\n if is_deleted(self): return\n new_selected = self.getSelectedFilt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implements a Dense convolution where radius_idx represents the indexes of the points in x and pos to be agragated into the new feature for each point in new_pos | def conv(self, x, pos, new_pos, radius_idx, scale_idx):
assert scale_idx < len(self.mlps)
new_features = self._prepare_features(x, pos, new_pos, radius_idx, scale_idx)
new_features = self.mlps[scale_idx](new_features) # (B, mlp[-1], npoint, nsample)
new_features = F.max_pool2d(new_featu... | [
"def resnetb_strided_block(layer_ind, inputs, features, radius, fdim, config, training):\n\n with tf.variable_scope('conv1'):\n w = weight_variable([int(features.shape[1]), fdim // 2])\n x = conv_ops.unary_convolution(features, w)\n x = leaky_relu(batch_norm(x,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Display the labels of each grid on the PyGame Screen | def display_grid_labels() -> None:
board1_label = label_font.render('Ship Board', False, (255, 255, 255))
board2_label = label_font.render('Firing Board', False, (255, 255, 255))
escape = instruction_font.render('HIT ESC TO RETURN TO THE MAIN MENU OR TO RESET THE GAME', False,
... | [
"def display_lab(self):\n\n x = 0\n for row in self.config:\n y = 0\n for column in row:\n if column == 'm':\n self.screen.blit(self.wall, (x*20, y*20),\n (100, 0, 20, 20))\n if column == 'x':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Display all the ships on the game board | def display_ships_hidden(game: game_code.BattleshipGame, player_1: bool) -> None:
for cell_number in range(0, 8):
for cell_letter in range(0, 8):
piece = game.get_board()[cell_number][cell_letter]
if piece is not None:
cell = game_visualize.index_to_algebraic((ce... | [
"def get_ships(game):\n return game.me.get_ships()",
"def print_grid(self):\n\n print('\\n'.join([' '.join(it) for it in self.game_grid]))",
"def __printHeatMap__(ships, p2board, mode, diff):\n if mode == \"search\":\n search(diff, ships, p2board)\n else:\n target(ships)\n a = A... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Display the ship based on the user's mouse taking into account that a user's mouse might not be on the grid. In which case the ship is displayed the farthest it can possibly be displayed on the grid While the amount of lines may look intimidating, there are simply a lot of possibilities when the user mouse is | def display_ship_placement(click: bool, length: int, orientation: bool, color: Tuple[int, int, int],
ship_type: str) -> None:
mouse_x, mouse_y = pygame.mouse.get_pos()
global user_game_board, ships_on_board
# check mouse position based on a horizontal ship orientation
i... | [
"def _draw_ship(self):\n self.__screen.draw_ship(*self.__spaceship.get_draw_data())",
"def mouse_moved(self, pos_x, pos_y):\n self.emit(\"mouseMoved\", pos_x, pos_y)\n self.mouse_position[0] = pos_x\n self.mouse_position[1] = pos_y\n if self.in_centring_state:\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the file name for this neural network attached to this instance. | def get_filename(self):
return self.net.filename | [
"def file_name(self):\n ret = self._get_attr(\"fileName\")\n return ret",
"def network_name(self):\n ret = self._get_attr(\"networkName\")\n return ret",
"def name(self):\n self.filename = self.model.name+\"_\"\n for k,p in self.params.items():\n self.filenam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The user can input a list of images if they like to create static masks as well as optional values for static_sig and inputDict. The configObj.cfg file will set the defaults and then override them with the user options. | def createMask(input=None, static_sig=4.0, group=None, editpars=False, configObj=None, **inputDict):
if input is not None:
inputDict["static_sig"]=static_sig
inputDict["group"]=group
inputDict["updatewcs"]=False
inputDict["input"]=input
else:
print >> sys.stderr, "Please... | [
"def process_model_config(model_cfg: mmengine.Config,\n imgs: Union[Sequence[str], Sequence[np.ndarray]],\n input_shape: Optional[Sequence[int]] = None):\n if isinstance(imgs[0], np.ndarray):\n # set loading pipeline type\n model_cfg.test_pipeline[0].... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates empty numpy array for static mask array signature. | def _buildMaskArray(self,signature):
return np.ones(signature[1],dtype=np.int16) | [
"def getmaskarray(self):\n return Array._from_apply(\"wf.maskedarray.getmaskarray\", self)",
"def _create_mask(self, data):\n sequence_lengths = [len(sample) for sample in data]\n max_sequence_length = max(sequence_lengths)\n mask = np.zeros((max_sequence_length, len(data)), dtype=conf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the appropriate StaticMask array for the image. | def getMaskArray(self, signature):
if signature in self.masklist:
mask = self.masklist[signature]
else:
mask = None
return mask | [
"def getmaskarray(self):\n return Array._from_apply(\"wf.maskedarray.getmaskarray\", self)",
"def mrcnn_masks(self):\n masks = []\n klasses = []\n for b in self.buildings:\n if b.color() == 5:\n continue\n img = np.zeros(S.MASKSHAPE[:2], dtype=np.ui... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the name of the output mask file that should reside on disk for the given signature. | def getFilename(self,signature):
filename=constructFilename(signature)
if(fileutil.checkFileExists(filename)):
return filename
else:
print("\nmMask file for ", str(signature), " does not exist on disk", file=sys.stderr)
return None | [
"def _get_output_file_name(self):\n datetime_suffix = datetime.now().strftime('%Y%m%d_%H%M%S')\n\n # Only select the non-empty strings from the file name parts\n output_file_name = '_'.join([a for a in\n [self.output_file_name_prefix, self.output_file_name,\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete just the mask that matches the signature given. | def deleteMask(self,signature):
if signature in self.masklist:
self.masklist[signature] = None
else:
log.warning("No matching mask") | [
"def seam_removal_mask(self, remove_pix, mask):\n m, n = mask.shape\n output = np.zeros((m, n - 1))\n for row in range(m):\n col = remove_pix[row]\n output[row, :] = np.delete(mask[row, :], [col])\n mask = np.copy(output)\n return mask",
"def delete_masked_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saves the static mask to a file it uses the signatures associated with each mask to contruct the filename for the output mask image. | def saveToFile(self,imageObjectList):
virtual = imageObjectList[0].inmemory
for key in self.masklist.keys():
#check to see if the file already exists on disk
filename = self.masknames[key]
#create a new fits image with the mask array and a standard header
... | [
"def save_mask(self, i: int, mask: PIL.Image.Image) -> None:\n mask.save(self.mask_filepath(i))",
"def save_masked_images(self, sframe, file_name):\n blurred_image = _visualization.draw_bounding_boxes(sframe['images'], sframe['annotations'])\n try:\n os.mkdir(self.save_dir + '/anon... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the featurized representation for a state. | def featurize_state(state):
scaled = scaler.transform([state])
featurized = featurizer.transform(scaled)
#print("this featurized",featurized)
#print("this is featurized[0]",featurized[0])
return featurized[0] | [
"def state_description(self):\n return self._state_description",
"def __str__(self):\n\t\tret = self.name + \"\\n\"\n\t\tfor k,v in self.states.items():\n\t\t\tret += v.__str__() + \"\\n\"\n\t\treturn ret",
"def to_json(self):\n\n return self.belief_state.to_json()",
"def state_string(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return length of longest suffix of 'a' matching a prefix of 'b' that is at least 'min_length' characters long. If no such overlap exists, return 0. | def overlap(a, b, min_length=3):
start = 0 # start all the way at the left
while True:
start = a.find(b[:min_length], start) # look for b's prefix in a
if start == -1: # no more occurrences to right
return 0
# found occurrence; check for full suffix/prefix match
if... | [
"def longest_common_prefix_len(a, b):\n for i, (x, y) in enumerate(zip(a, b)):\n if x != y:\n return i\n return i + 1",
"def find_longest(self, s1, s2):\n min_l = min(len(s1), len(s2))\n l_common_prefix = 0\n for i in range(min_l):\n if s1[i] == s2[i]:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves a custom event formatter helper. | def GetEventFormatterHelper(cls, identifier):
identifier = identifier.lower()
return cls._custom_formatter_helpers.get(identifier) | [
"def custom_template_formatter(self):\n return self.FORMATTER_DELIMITER.join(self.custom_template_formatters)",
"def RegisterEventFormatterHelper(cls, formatter_helper_class):\n identifier = formatter_helper_class.IDENTIFIER.lower()\n if identifier in cls._custom_formatter_helpers:\n raise KeyEr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registers a custom event formatter helper. The custom event formatter helpers are identified based on their lower case identifier. | def RegisterEventFormatterHelper(cls, formatter_helper_class):
identifier = formatter_helper_class.IDENTIFIER.lower()
if identifier in cls._custom_formatter_helpers:
raise KeyError((
'Custom event formatter helper already set for identifier: '
'{0:s}.').format(formatter_helper_class.ID... | [
"def GetEventFormatterHelper(cls, identifier):\n identifier = identifier.lower()\n return cls._custom_formatter_helpers.get(identifier)",
"def RegisterEventFormatterHelpers(cls, formatter_helper_classes):\n for formatter_helper_class in formatter_helper_classes:\n cls.RegisterEventFormatterHelper(fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registers custom event formatter helpers. The formatter classes are identified based on their lower case data type. | def RegisterEventFormatterHelpers(cls, formatter_helper_classes):
for formatter_helper_class in formatter_helper_classes:
cls.RegisterEventFormatterHelper(formatter_helper_class) | [
"def RegisterEventFormatterHelper(cls, formatter_helper_class):\n identifier = formatter_helper_class.IDENTIFIER.lower()\n if identifier in cls._custom_formatter_helpers:\n raise KeyError((\n 'Custom event formatter helper already set for identifier: '\n '{0:s}.').format(formatter_helpe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new ``SlashCommandCategory`` with the given parameters. | def __new__(cls, slasher_application_command, deepness):
if deepness > APPLICATION_COMMAND_CATEGORY_DEEPNESS_MAX:
raise RuntimeError('Cannot add anymore sub-category under sub-categories.')
self = object.__new__(cls)
self.name = slasher_application_command.name
self.... | [
"def new(ws, **kwargs):\n assert 'command_id' not in kwargs, \"New commands should not be given a command_id yet\"\n assert 'type' not in kwargs, \"New commands don't need to be passed a type parameter, one will be assigned.\"\n data = {'command_id': str(uuid.uuid1()),\n 'type': ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls the respective auto completion function of the command. This method is a coroutine. | async def invoke_auto_completion(self, client, interaction_event, auto_complete_option):
auto_complete_option_type = auto_complete_option.type
if (
(auto_complete_option_type is APPLICATION_COMMAND_OPTION_TYPE_SUB_COMMAND) or
(auto_complete_option_type is APPLICATION_COMMAND_OPTI... | [
"def ctxCompletion():\n pass",
"def ctxCompletion(*args, **kwargs):\n\n pass",
"def completion(ctx, shell=None):\n completer = pycomplete.Completer(ctx)\n print(completer.render(shell))",
"def auto_command(self, cmd, uuser, cchannel, suggesting=True):\n if cmd==\"\":\n return cmd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the slash command category as an application command option. Returns | def as_option(self):
sub_commands = self._sub_commands
if sub_commands:
options = [sub_command.as_option() for sub_command in sub_commands.values()]
else:
options = None
return ApplicationCommandOption(
self.name,
self.description,... | [
"def getCategory(cmd):\n\tf = lookForCommand(cmd)\n\tif f is None:\n\t\treturn (None, None)\n\n\ttry:\n\t\tcategory = re.findall( r\"# (\\S+)\", f.__doc__ )[0]\n\texcept:\n\t\tcategory = \"other\"\n\t\n\treturn (category, category_description[category][1])",
"def _category_key(command: commands.Command) -> str:\r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registers an autocomplete function. | def _add_autocomplete_function(self, parameter_names, function):
if isinstance(function, SlashCommandParameterAutoCompleter):
function = function._command
auto_completer = SlashCommandParameterAutoCompleter(
function,
parameter_names,
self._deepne... | [
"def _register_autocomplete(self, autocomplete):\n self[autocomplete.__name__] = autocomplete",
"def py_autocomplete():\n\n return get_all_users()",
"def enable_autocomplete(self, ):\n return self._set_one_attribute(self.AttributeNames.AUTOCOMPLETE, 'on')",
"def autocomplete(self, str):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Margin on lines = SP@ (100 %discount) CP@ Profit Margin % on lines = (SP@ (100 %discount) CP@) / SP@ Profit Margin % TOTAL = sum all lines. | def _crea8s_product_margin_percent(self, cursor, user, ids, field_name, arg, context=None):
result = {}
for sale in self.browse(cursor, user, ids, context=context):
result[sale.id] = 0.0
for line in sale.order_line:
result[sale.id] += line.crea8s_profit_... | [
"def _compute_margin(self, cursor, user, ids, field_name, arg, context = None):\n logger = logging.getLogger('product_standard_margin')\n if context is None:\n context = {}\n res = {}\n if not ids:\n return res\n for product in ids:\n res[product] ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Generate html or LaTex tables provided (lists of) of models. The function can create publication quality tables in various formats from statsmodels or estimagic results. It allows for extensive customization via optional arguments and almost limitless flexibility when using a twostage approach where the ``return_ty... | def estimation_table(
models,
*,
return_type="dataframe",
render_options=None,
show_col_names=True,
show_col_groups=None,
show_index_names=False,
show_inference=True,
show_stars=True,
show_footer=True,
custom_param_names=None,
custom_col_names=None,
custom_col_groups=... | [
"def show_table(models: typing.List[Model]):\n if not models:\n click.echo(\"Empty!\")\n return\n\n headers = list(flatten_dict(models[0].to_dict()).keys())\n table = Texttable(MAX_TABLE_WIDTH)\n\n table.add_rows([headers] + [_convert_model_values(md) for md in models])\n click.echo(tab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create body and footer blocs with significance stars and inference values. Applies number formatting to parameters and summary statitistics. Concatinates infere values to parameter values if applicable, Adds significance stars if applicable. | def _get_estimation_table_body_and_footer(
models,
column_names,
column_groups,
custom_param_names,
custom_index_names,
significance_levels,
stats_options,
show_col_names,
show_col_groups,
show_stars,
show_inference,
confidence_intervals,
number_format,
add_traili... | [
"def _build_estimation_table_footer(\n models,\n stats_options,\n significance_levels,\n show_stars,\n number_format,\n add_trailing_zeros,\n max_trail,\n):\n to_concat = [\n _create_statistics_sr(\n mod,\n stats_options,\n significance_levels,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create footer bloc of estimation table. Applies number formatting to parameters and summary statitistics. Concatinates infere values to parameter values if applicable, Adds significance stars if applicable. | def _build_estimation_table_footer(
models,
stats_options,
significance_levels,
show_stars,
number_format,
add_trailing_zeros,
max_trail,
):
to_concat = [
_create_statistics_sr(
mod,
stats_options,
significance_levels,
show_stars,
... | [
"def generate_footer_html(self):\n footer = '<td colspan=\"' + str(self.num_models + 1) + '\" style=\"border-bottom: 1px solid black\"></td></tr>'\n\n if not self.show_footer:\n return footer\n footer += self.generate_observations_html()\n footer += self.generate_r2_html()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reindex all params DataFrames with a common index and apply number formatting. | def _reindex_and_float_format_params(
models, show_inference, confidence_intervals, number_format, add_trailing_zeros
):
dfs = _get_params_frames_with_common_index(models)
cols_to_format = _get_cols_to_format(show_inference, confidence_intervals)
formatted_frames, max_trail = _apply_number_formatting_fr... | [
"def _re_number(self):\n new_dataset_indices = []\n for g, graph in enumerate(self.graphs):\n graph._force_index(g)\n for s, graph_set in enumerate(graph.sets):\n graph_set._force_index(s)\n new_dataset_indices.append((g,s))\n for i, dataset i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of params frames, reindexed with a common index. | def _get_params_frames_with_common_index(models):
dfs = [model["params"] for model in models]
common_index = _get_common_index(dfs)
out = [model["params"].reindex(common_index) for model in models]
return out | [
"def get_param_indices(state, modes, opcode_ix):\n return [state.intcode[opcode_ix+i] if mode == PARAM_MODE_POSITION else\n opcode_ix+i if mode == PARAM_MODE_IMMEDIATE else\n state.relative_base + state.intcode[opcode_ix+i]\n for i, mode in enumerate(modes, 1)]",
"def getFrameL... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get common index from a list of DataFrames. | def _get_common_index(dfs):
common_index = []
for d_ in dfs:
common_index += [ind for ind in d_.index.to_list() if ind not in common_index]
return common_index | [
"def ensure_same_indices(df1, df2): \n df1.index = df1.index.astype(int)\n df2.index = df2.index.astype(int)\n\n intersection_ = df1.index.intersection(df2.index)\n\n if len(intersection_) == 0: \n raise ValueError('DataFrames do not contain any shared years')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the list of names of columns that need to be formatted. By default, formatting is applied to parameter values. If inference values need to displayed, adds confidence intervals or standard erros to the list. | def _get_cols_to_format(show_inference, confidence_intervals):
cols = ["value"]
if show_inference:
if confidence_intervals:
cols += ["ci_lower", "ci_upper"]
else:
cols.append("standard_error")
return cols | [
"def colnames(self):\n return list(self)",
"def _colNames(self):\n self.mjdCol = 'expMJD'\n self.fieldIdCol = 'fieldID'\n self.raCol = 'fieldRA'\n self.decCol = 'fieldDec'\n self.propIdCol = 'propID'\n self.propConfCol = 'propConf'\n self.propNameCol = 'prop... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the value of show_col_groups to False or True given column_groups. Updates the default None to True if column_groups is not None. Sets to False otherwise. | def _update_show_col_groups(show_col_groups, column_groups):
if show_col_groups is None:
if column_groups is not None:
show_col_groups = True
else:
show_col_groups = False
return show_col_groups | [
"def _customize_col_groups(default_col_groups, custom_col_groups):\n if custom_col_groups:\n if not default_col_groups:\n if not isinstance(custom_col_groups, list):\n raise ValueError(\n \"\"\"With unique model names, multiple models can't be grouped\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check identically named models are adjacent. | def _check_order_of_model_names(model_names):
group_to_col_index = _create_group_to_col_position(model_names)
for positions in group_to_col_index.values():
if positions != list(range(positions[0], positions[-1] + 1)):
raise ValueError(
"If there are repetitions in model_names... | [
"def _same_namedtuples(nest1, nest2):\n if nest1._fields != nest2._fields:\n return False\n if nest1.__class__.__name__ != nest2.__class__.__name__:\n return False\n return True",
"def __has_conflicting_node_names(self):\n # check length of sets to determine if overlap exists\n return \\\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change default (inferred) column group titles using custom column groups. | def _customize_col_groups(default_col_groups, custom_col_groups):
if custom_col_groups:
if not default_col_groups:
if not isinstance(custom_col_groups, list):
raise ValueError(
"""With unique model names, multiple models can't be grouped
under ... | [
"def _update_show_col_groups(show_col_groups, column_groups):\n if show_col_groups is None:\n if column_groups is not None:\n show_col_groups = True\n else:\n show_col_groups = False\n return show_col_groups",
"def group_names_for_display(self):\n return self.demog... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change default (inferred) column names using custom column names. | def _customize_col_names(default_col_names, custom_col_names):
if not custom_col_names:
col_names = default_col_names
elif isinstance(custom_col_names, dict):
col_names = list(pd.Series(default_col_names).replace(custom_col_names))
elif isinstance(custom_col_names, list):
if not len(... | [
"def change_column_names(data, new_names):\n old_names = data.columns\n if isinstance(new_names, list):\n mapping = dict(zip(old_names, new_names))\n else:\n mapping = new_names\n\n transformed_data = data.select([col(c).alias(mapping.get(c, c)) for c in data.columns])\n return transfor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get mapping from column groups to column positions. | def _create_group_to_col_position(column_groups):
if column_groups is not None:
group_to_col_index = {group: [] for group in list(set(column_groups))}
for i, group in enumerate(column_groups):
group_to_col_index[group].append(i)
else:
group_to_col_index = None
return grou... | [
"def _get_column_mapping(cls) -> Dict[str, str]:\n pass",
"def header_col_number_mapping(worksheet_lol):\n header_col_number_dict = dict()\n for col in range(len(worksheet_lol)):\n header_col_number_dict[worksheet_lol[col][0]] = col\n return header_col_number_dict",
"def get_group_positio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Merge value and inference series. Return string series with parameter values and precision values below respective param values. | def _combine_series(value_sr, inference_sr):
value_df = value_sr.to_frame(name="")
original_cols = value_df.columns
value_df.reset_index(drop=False, inplace=True)
index_names = [item for item in value_df.columns if item not in original_cols]
# set the index to even numbers, starting at 0
value_d... | [
"def round(self, decimals: int) -> Series:",
"def get_integrated_benchmarking_fields_series_for_setFilters_df(df):\n\n # get a df where each row is one df\n df_best_filters = df.groupby(\"svtype\").apply(get_best_less_conservative_row_df_benchmark)\n\n # debug when there are filters_dict\n if \"filter... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate the LaTex script of the notes section. | def _generate_notes_latex(
append_notes, notes_label, significance_levels, custom_notes, df
):
n_levels = df.index.nlevels
n_columns = len(df.columns)
significance_levels = sorted(significance_levels)
notes_text = ""
if append_notes:
notes_text += "\\midrule\n"
notes_text += "\\t... | [
"def generate_note(stem: str) -> str:\n note = f\"\"\"\n.. note::\n An *xml* file containing the defaults for the `{stem}` calculator can be created via `-p {stem} -o FILENAME` command line options `\n\"\"\"\n return note",
"def gen_readme():\n\n doc = '''\n=== README for Tornastrap ===\n\nApplications... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate the html script of the notes section of the estimation table. | def _generate_notes_html(
append_notes, notes_label, significance_levels, custom_notes, df
):
n_levels = df.index.nlevels
n_columns = len(df.columns)
significance_levels = sorted(significance_levels)
notes_text = """<tr><td colspan="{}" style="border-bottom: 1px solid black">
</td></tr>""".f... | [
"def _generate_notes_latex(\n append_notes, notes_label, significance_levels, custom_notes, df\n):\n n_levels = df.index.nlevels\n n_columns = len(df.columns)\n significance_levels = sorted(significance_levels)\n notes_text = \"\"\n if append_notes:\n notes_text += \"\\\\midrule\\n\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert statsmodels like estimation result to estimagic like params dataframe. | def _extract_params_from_sm(model):
to_concat = []
params_list = ["params", "pvalues", "bse"]
for col in params_list:
to_concat.append(getattr(model, col))
to_concat.append(model.conf_int())
params_df = pd.concat(to_concat, axis=1)
params_df.columns = ["value", "p_value", "standard_error... | [
"def net_parameters_to_dataframe(self, stringify_index=False):\n interactions, values = self.free_parameters, self.parameters.get_value()\n # now put everything in dataframe\n return pd.DataFrame({\n 'interaction': interactions,\n 'value': values\n }).set_index('int... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply number format if the number string is not in scientific format. | def _format_non_scientific_numbers(number_string, format_string):
if "e" in number_string:
out = number_string
else:
out = format_string.format(float(number_string))
return out | [
"def format_scientific(self, number):\n return __format_obj().scientific(number)",
"def set_scientific(self, b):\n self._scientific = bool(b)",
"def _set_isScientificNotationUsed(self, *args) -> \"bool\" :\n return _core.UnitAndValuePreferences__set_isScientificNotationUsed(self, *args)",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the maximum number of digits after a decimal point in a DataFrame. | def _get_digits_after_decimal(df):
max_trail = 0
for c in df.columns:
try:
trail_length = (
(
df[c][~df[c].astype("str").str.contains("e")]
.astype("str")
.str.split(".", expand=True)[1]
.astype("... | [
"def _get_min_significant_precision(df: pd.DataFrame):\n\n # Count number of rows\n num_rows = df.shape[0]\n # Get significance of single row, save as string\n row_significance_string = str(1.0 / num_rows)\n # Parse string and count number of leading, significant zeros\n start_index = row_signific... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Align integer numbers and strings at the center of model column. | def _center_align_integers_and_non_numeric_strings(sr):
sr = deepcopy(sr)
for i in sr.index:
if _is_integer(sr[i]):
sr[i] = f"\\multicolumn{{1}}{{c}}{{{str(int(float(sr[i])))}}}"
else:
string_without_stars = sr[i].split("$", 1)[0]
if not string_without_stars.r... | [
"def align_decimal(number, width):\n number = unicode(number)\n return figurespace_padding(number, width) + number",
"def align_columns(self, alignment):\n for cid, anchor in enumerate(alignment):\n self.Widget.column(cid, anchor=anchor)",
"def align_labels(widgets):\n for widget in w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return pandas.Styler object based ont the data and styling options. | def _get_updated_styler(
df, show_index_names, show_col_names, show_col_groups, escape_special_characters
):
styler = df.style
if not show_index_names:
styler = styler.hide(names=True)
if not show_col_names:
styler = styler.hide(axis=1)
if not show_col_groups:
styler = styler... | [
"def _pandas_style_to_css(style_type, style, uuid, separator=\"\"):\n declarations = []\n for css_property, css_value in style[\"props\"]:\n declaration = css_property.strip() + \": \" + css_value.strip()\n declarations.append(declaration)\n\n table_selector = \"#T_\" + str(uuid)\n\n # In ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if number is an integer (including a float with only zeros as digits) | def _is_integer(num):
try:
out = int(float(num)) == float(num)
except ValueError:
out = False
return out | [
"def isinteger(value):\n try:\n return value == int(value)\n except TypeError:\n return False",
"def _is_number(value):\n if isinstance(value, int) or isinstance(value, float):\n return True\n return False",
"def is_number(n):\n try:\n int(n)\n except Va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the number of explores in the project, excluding skipped explores. | def count_explores(self) -> int:
return len([explore for explore in self.iter_explores() if not explore.skipped]) | [
"def getUnprofitableCount(self):\n\t\treturn len(self.__losses)",
"def get_num_attacks_per_day():",
"def n_experiences(self):\n\n return len(self.heap.track)",
"def total_projects(self) -> int:\n return Project.objects.filter(client=self).count()",
"def num_ignored(self):\n return self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates Dimension objects for all dimensions in a given explore. | async def build_explore_dimensions(
client: LookerClient,
explore: Explore,
ignore_hidden_fields: bool = False,
) -> None:
dimensions_json = await client.get_lookml_dimensions(
explore.model_name, explore.name
)
dimensions: List[Dimension] = []
for dimension_json in dimensions_json:... | [
"def builddimensions(self):\r\n e = self.experiment # synonym\r\n\r\n # find unique dimension values across variables. Dim values could be 0, 5, 5, 5, 2, 666, -74,...\r\n dims = list(np.unique([ var.dim for var in e.variables ])) # np.unique returns sorted values\r\n\r\n # renumber dimen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Init a configuration flow. | def init_config_flow(hass):
config_flow.register_flow_implementation(
hass,
DOMAIN,
client_id="id",
client_secret="secret",
api_key="123",
redirect_uri="http://example.com",
sensors=None,
)
flow = config_flow.LogiCircleFlowHandler()
flow._get_autho... | [
"def init(args):\n Configuration.load_config(vars(args).get(\"config\"))",
"def __init__(self, config='config.json'):\n self.read_config(config)",
"def __init__(self):\n\n self.config = {\n 'debug': False,\n 'enable': False,\n 'secret': '',\n 'tim... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test we prompt user to follow link if previously prompted. | async def test_we_reprompt_user_to_follow_link(hass: HomeAssistant) -> None:
flow = init_config_flow(hass)
result = await flow.async_step_auth("dummy")
assert result["errors"]["base"] == "follow_link" | [
"def testNewUserContinueUrl(self):\n response = self.request_fetcher.get('/')\n m = re.search(r'<A HREF=\"(/settings[^\"]*)\">', response.body)\n continue_url = m.group(1)\n\n settings_response = self.request_fetcher.get(continue_url)\n self.assertIn('name=\"redirect_to\" value=\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test we bypass picking implementation if we have one flow_imp. | async def test_not_pick_implementation_if_only_one(hass: HomeAssistant) -> None:
flow = init_config_flow(hass)
result = await flow.async_step_user()
assert result["type"] == data_entry_flow.FlowResultType.FORM
assert result["step_id"] == "auth" | [
"def HasIMP(self):\n return self.__has('IMP')",
"def test_case_pocket_insane_none(self):\n\t\ttheResult = True\n\t\ttry:\n\t\t\tfrom .context import piaplib\n\t\t\tif piaplib.__name__ is None:\n\t\t\t\ttheResult = False\n\t\t\tfrom piaplib import pocket\n\t\t\tif pocket.__name__ is None:\n\t\t\t\ttheResult... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test generating authorize URL from Logi Circle API. | async def test_gen_auth_url(hass: HomeAssistant, mock_logi_circle) -> None:
config_flow.register_flow_implementation(
hass,
"test-auth-url",
client_id="id",
client_secret="secret",
api_key="123",
redirect_uri="http://example.com",
sensors=None,
)
flow ... | [
"def make_authorization_url(request):\n api_url = \"https://ssl.reddit.com/api/v1/authorize?\"\n request.session[\"oauth_reddit_state\"] = str(uuid4())\n params = urlencode(\n {\n \"client_id\": settings.OAUTH_REDDIT_CLIENT_ID,\n \"response_type\": \"code\",\n \"stat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the auth callback view rejects requests with no code. | async def test_callback_view_rejects_missing_code(hass: HomeAssistant) -> None:
view = LogiCircleAuthCallbackView()
resp = await view.get(MockRequest(hass, {}))
assert resp.status == HTTPStatus.BAD_REQUEST | [
"def test_unauthorized_view_fails(self):\n response = self.api_client.get('/account/', format='json')\n self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)",
"def unauthorized_callback():\n return redirect(url_for('auth.login'))",
"def test_raise_func_false(self):\n user... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the auth callback view handles requests with auth code. | async def test_callback_view_accepts_code(
hass: HomeAssistant, mock_logi_circle
) -> None:
init_config_flow(hass)
view = LogiCircleAuthCallbackView()
resp = await view.get(MockRequest(hass, {"code": "456"}))
assert resp.status == HTTPStatus.OK
await hass.async_block_till_done()
mock_logi_... | [
"async def test_callback_view_rejects_missing_code(hass: HomeAssistant) -> None:\n view = LogiCircleAuthCallbackView()\n resp = await view.get(MockRequest(hass, {}))\n\n assert resp.status == HTTPStatus.BAD_REQUEST",
"def test_auth(self):\n pass",
"def authentication_callback(request):\n code... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
if frames do not have I3TriggerHierarchy put it there by clipping in time | def ClipTriggerHierarchy(frame):
qth = frame[TriggerHierarchyName]
tw = frame["TriggerSplitterLaunchWindow"]
th = IceHive.clip_TriggerHierarchy(qth, tw, [1011, 1006,1007,21001]) #SMT8, SMT3, String, Volume-trigger
frame.Put("I3TriggerHierarchy", th) | [
"def _clipchanged(self):\n if not self._parent or not self._onscreen_wid:\n return\n self._zapclip()\n self._buttonschanged()\n self._zapregions()",
"def GetClipRegion(self):\n ...",
"def _clipchanged(self):\n if not self._parent or not self._onscreen_wid:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a class_element and converts it into a sourcecode string. | def class_to_python(class_element):
lines = []
attrs = class_element.attrs
for attr_nm, type_ref in attrs.iteritems():
lines.append(class_annotation(attr_nm, type_ref))
extends = class_element.extends
name = class_element.name
if not extends is None:
lines.append('@extendi... | [
"def _compile_class(self) -> None:\n self.file_obj.write(\" \" * self.indent + \"<class>\\n\")\n self._increase_indent()\n self._eat(\"class\")\n self._compile_class_name()\n self._eat(\"{\")\n self._compile_class_var_dec()\n self._compile_subroutine_dec()\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the class property annotation for the given name and type_ref. This function dispatches the call based on whether the type_ref is a builtin primitive or if it is a complex datatype (either list, map or custom class). | def class_annotation(nm, type_ref):
if type_ref.type_ in python_primitives:
return simple_attr_annotation(nm, type_ref)
else:
return complex_attr_annotation(nm,type_ref) | [
"def complex_attr_annotation(nm, type_ref):\n marshalfun, unmarshalfun = type_ref_marshal_funs(type_ref)\n return '@cprop.%s(%s, %s)' % (nm, marshalfun, unmarshalfun)",
"def simple_attr_annotation(nm, type_ref):\n assert type_ref.type_ in python_primitives\n return '@sprop.%s #%s' % (nm, type_ref.type... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a simple class property annotation for the given name and type_ref. | def simple_attr_annotation(nm, type_ref):
assert type_ref.type_ in python_primitives
return '@sprop.%s #%s' % (nm, type_ref.type_) | [
"def class_annotation(nm, type_ref):\n if type_ref.type_ in python_primitives:\n return simple_attr_annotation(nm, type_ref)\n else:\n return complex_attr_annotation(nm,type_ref)",
"def complex_attr_annotation(nm, type_ref):\n marshalfun, unmarshalfun = type_ref_marshal_funs(type_ref)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a complex class property annotation for the given name and type ref. | def complex_attr_annotation(nm, type_ref):
marshalfun, unmarshalfun = type_ref_marshal_funs(type_ref)
return '@cprop.%s(%s, %s)' % (nm, marshalfun, unmarshalfun) | [
"def class_annotation(nm, type_ref):\n if type_ref.type_ in python_primitives:\n return simple_attr_annotation(nm, type_ref)\n else:\n return complex_attr_annotation(nm,type_ref)",
"def simple_attr_annotation(nm, type_ref):\n assert type_ref.type_ in python_primitives\n return '@sprop.%s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |