query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Test upgrade of a link which is an external URL | def test_upgrade_link_external(self):
document = self.root.document
editable = document.get_editable()
editable.content = ParsedXML(
'content',
"""<?xml version="1.0" encoding="utf-8"?>
<doc>
<p type="normal">
<link target="_blank" url="http://infrae.com#top">Infrae... | [
"def test_upgrade_link(self):\n document = self.root.document\n editable = document.get_editable()\n editable.content = ParsedXML(\n 'content',\n \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<doc>\n <p type=\"normal\">\n <link target=\"_blank\" url=\"./publication... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test upgrade of an image, regular without any link | def test_upgrade_image(self):
document = self.root.document
editable = document.get_editable()
editable.content = ParsedXML(
'content',
"""<?xml version="1.0" encoding="utf-8"?>
<doc>
<p type="normal">
<image alignment="image-left" title="" width="600" image_title="... | [
"def test_update_image(self):\r\n image = Image.objects.create(\r\n archive=self.archive,\r\n name='image',\r\n info='40세 남자, 증상 심한 편'\r\n )\r\n\r\n data = {\r\n 'name': 'revised image',\r\n 'info': '30세 여자, 가벼운 기침'\r\n }\r\n\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test to upgrade an image that contains a link to a hires version of itself. | def test_upgrade_image_link_to_hires(self):
document = self.root.document
editable = document.get_editable()
editable.content = ParsedXML(
'content',
"""<?xml version="1.0" encoding="utf-8"?>
<doc>
<p type="normal">
<image alignment="image-left" title="Big Chocobo" ... | [
"def test_upgrade_image_broken_link(self):\n document = self.root.document\n editable = self.root.document.get_editable()\n editable.content = ParsedXML(\n 'content',\n \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<doc>\n <p type=\"normal\">\n <image alignment=\"i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test to upgrade an image that contains a link to a different content in Silva. | def test_upgrade_image_link(self):
document = self.root.document
editable = document.get_editable()
editable.content = ParsedXML(
'content',
"""<?xml version="1.0" encoding="utf-8"?>
<doc>
<p type="normal">
<image alignment="image-left" title="Pub" width="600" image... | [
"def test_upgrade_image_broken_link(self):\n document = self.root.document\n editable = self.root.document.get_editable()\n editable.content = ParsedXML(\n 'content',\n \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<doc>\n <p type=\"normal\">\n <image alignment=\"i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test to upgrade an missing image that contains a link to a different content in Silva. | def test_upgrade_image_broken_link(self):
document = self.root.document
editable = self.root.document.get_editable()
editable.content = ParsedXML(
'content',
"""<?xml version="1.0" encoding="utf-8"?>
<doc>
<p type="normal">
<image alignment="image-left" title="Pub" ... | [
"def test_upgrade_image_link_broken(self):\n document = self.root.document\n editable = document.get_editable()\n editable.content = ParsedXML(\n 'content',\n \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<doc>\n <p type=\"normal\">\n <image alignment=\"image-left\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test to upgrade an image that contains a link to a different missing content in Silva. This would be the same for link with external URLs. | def test_upgrade_image_link_broken(self):
document = self.root.document
editable = document.get_editable()
editable.content = ParsedXML(
'content',
"""<?xml version="1.0" encoding="utf-8"?>
<doc>
<p type="normal">
<image alignment="image-left" title="Pub" width="600... | [
"def test_upgrade_image_broken_link(self):\n document = self.root.document\n editable = self.root.document.get_editable()\n editable.content = ParsedXML(\n 'content',\n \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<doc>\n <p type=\"normal\">\n <image alignment=\"i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the last defined status of a given account at a given date. | def get_last_account_status(self, account_id: int, end_date: date = None) -> StatusDbo:
status = self.__entity_manager.query(StatusDbo).filter(StatusDbo.account_id == account_id)
status = status.order_by(desc(StatusDbo.date))
if end_date is not None:
status = status.filter(StatusDbo.... | [
"def get_info_at_date(self, date: datetime) -> LoanStatus:\n iterator_balance: Decimal = Decimal(0)\n iterator_date: Optional[datetime] = None\n interest: Decimal = Decimal(0)\n amount_to_capital: Decimal = Decimal(0)\n for account in self.subaccounts:\n account_status ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Configure the model_directory in DBTTestUtils using the directory structure of the macro under test. | def dbt_test_utils(request):
test_path = Path(request.fspath.strpath)
macro_folder = test_path.parent.name
macro_under_test = test_path.stem.split('test_')[1]
request.cls.dbt_test_utils = DBTTestUtils(model_directory=f"{macro_folder}/{macro_under_test}") | [
"def model_dir(self, model_dir):\n self._model_dir = model_dir",
"def models_dir():\n return _mkifnotexists(\"configs\")",
"def set_model_dir(self) -> None:\n model_dir = os.path.join(self.material_root_dir, \"models\")\n if not os.path.isdir(model_dir):\n os.mkdir(model_dir)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construct an IosCatalogManager object from a TestEnvironmentCatalog. | def __init__(self, catalog=None):
self.catalog = catalog or util.GetIosCatalog()
models = self.catalog.models
versions = self.catalog.versions
locales = self.catalog.runtimeConfiguration.locales
orientations = self.catalog.runtimeConfiguration.orientations
self._model_ids = [m.id for m in model... | [
"def create(container):\n return CatalogModule(\n logger=container.logger(),\n listing_repository=container.listing_repository(),\n )",
"def initCatalog(parametro):\n catalog = model.newCatalog(parametro) \n return catalog",
"def initFromCatalogue(cls, catalogue, **kwar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the default model listed in the iOS environment catalog. | def GetDefaultModel(self):
model = (self._default_model if self._default_model else
self._FindDefaultDimension(self.catalog.models))
if not model:
raise exceptions.DefaultDimensionNotFoundError(_MODEL_DIMENSION)
return model | [
"def default_model_config(self) -> Optional[Dict]:\n return self.model_configs.get(\"default\")",
"def _get_model_name(self):\n sysinfo = SystemInfo()\n model_name = sysinfo.get_model_name()\n return model_name",
"def get_Model(self):\n return self.GetStringDescriptor(StringDe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the default iOS orientation. | def GetDefaultOrientation(self):
orientations = self.catalog.runtimeConfiguration.orientations
orientation = (
self._default_orientation if self._default_orientation else
self._FindDefaultDimension(orientations))
if not orientation:
raise exceptions.DefaultDimensionNotFoundError(_ORIEN... | [
"def get_orientation(self):\n if -4.9 < accelerometer.acceleration[0] < 4.9:\n self.orientation = 0\n else:\n self.orientation = 1",
"def getOrientation(self):\n return self.getTag(\"Orientation#\", 1)",
"def orientation(self):\r\n tag=self.readinfo('Image Orien... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates that a matrix dimension has a valid name and value. | def ValidateDimensionAndValue(self, dim_name, dim_value):
if dim_name == _MODEL_DIMENSION:
if dim_value not in self._model_ids:
raise exceptions.ModelNotFoundError(dim_value)
elif dim_name == _VERSION_DIMENSION:
if dim_value not in self._version_ids:
raise exceptions.VersionNotFoundE... | [
"def __validate_dim(self, ind, name):\n if not isinstance(ind, int):\n raise TypeError('Dimension must be an integer')\n if (0 > ind) or (ind >= self.ndim):\n raise IndexError('Dimension must be an integer between 0 and {}'\n ''.format(self.ndim-1))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates that an Xcode version is in the TestEnvironmentCatalog. | def ValidateXcodeVersion(self, xcode_version):
if xcode_version not in [xv.version for xv in self.catalog.xcodeVersions]:
raise exceptions.XcodeVersionNotFoundError(xcode_version) | [
"def verify(self):\n installed_version_output = subprocess.check_output(['/usr/bin/xcrun', 'xcodebuild', \"-version\"])\n installed_version_re = re.compile(r\"^Xcode\\s(?P<version_text>[\\d/.]+)\")\n match = installed_version_re.match(installed_version_output)\n if not match:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List the reward 'tickets' a user has. | async def showRewards(self, ctx, *args):
self.processTimeouts()
pargs = self.parse_args(args, ctx)
num = pargs['num']
userID = pargs['recipient']
if self.isOwlCoEmployee(ctx.message.author.id) or userID == ctx.message.author.id:
userRewards = self.getUserRewards(userID)
if len(userRewards) > 0:
... | [
"def review_buy_requests():\n\n current_user = User.objects(id = session['user']['id']).first()\n\n my_items = Item.objects(user = current_user)\n \n my_buy_requests = []\n\n for item in my_items:\n \n my_buy_requests.append(BuyRequest.objects(item = item))\n\n return render_temp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows the effects active for a user. \nUser is optional & must be specified in format. | async def examine(self, ctx, *args):
pargs = self.parse_args(args, ctx)
userid = pargs['recipient']
effects = self.get_user_effects(userid)
o = ""
userGender = self.getUserGender(userid)
if userGender == "M":
o += "<@{}> is currently Male.\n\n".format(userid)
elif userGender == "F":
o += "<@{}> i... | [
"async def shade(self, ctx: commands.Context, user: discord.Member = None) -> None:\n msg = \" \"\n if user:\n if user.id == self.bot.user.id:\n user = ctx.message.author\n bot_msg: List[str] = [\n _(\"Hey, I appreciate the shade! :rofl:\"),\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Conveys randomlychosen effects onto a user! \nUser is optional & must be specified in format. \nAlso accepts an optional number for of effects rendered! | async def effect(self, ctx, *args):
if ctx.message.guild is None:
await ctx.send("Issuing of effects is not allowed in private chat!")
return
pargs = self.parse_args(args, ctx)
num = pargs['num']
recipient = pargs['recipient']
gender = self.getUserGender(recipient)
if gender is None:
awa... | [
"async def examine(self, ctx, *args):\n\t\t\n\t\tpargs = self.parse_args(args, ctx)\n\t\tuserid = pargs['recipient']\n\t\teffects = self.get_user_effects(userid)\n\t\to = \"\"\n\t\tuserGender = self.getUserGender(userid)\n\t\tif userGender == \"M\":\n\t\t\to += \"<@{}> is currently Male.\\n\\n\".format(userid)\n\t\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given adjacent matrix A, partition a graph to its disconnected subgraphs. Arguments | def partition(A):
# TODO(2020-01-10 kvtsang) Check A = A.T
A = np.asarray(A)
n = len(A)
active = [True] * n
idx = np.arange(n)
groups = []
# make boolean adjacent matrix
B = (A != 0)
# self connected
np.fill_diagonal(B, True)
while np.any(active):
# first active ... | [
"def A(G):\n partition_list = []\n # for i in set(combinations(G.nodes, 2)) - set(G.edges): # set of tuples\n for i in set(nx.non_edges(G)):\n partition = []\n partition.append(set(i))\n for v in set(G.nodes) - set(i):\n partition.append({v})\n partition_list.app... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
move latest uploaded file path and create 4 new images | def post(self, path):
### move latest uploaded image ###
file_path = self.get_argument('file.path')
file_name = self.get_argument('file.name').replace(" ", "-").lower()
if not os.path.exists(config['upload']+"/"+path):
os.makedirs(config['upload']+"/"+path)
... | [
"def stage_images(self):\n if not os.path.exists(self.data_dir):\n os.mkdir(self.data_dir)\n for x in self.image_files():\n shutil.move(x, self.data_dir)",
"def rename_imgs(path):",
"def upload_image():\n global destination\n target = os.path.join(APP_ROOT, 'static/pics/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add an atom to the structure Checks to see if an existing atom exists at the position we are trying to add an atom, then if the position is empty. The atom is added then added to the list of interstitials. | def add_atom(self, symbol, position):
is_atom_exists = self.check_if_atom_exists_at_position(symbol,position)
if is_atom_exists is True:
err_msg = "Tried to add {} @ {} an atom already there"
err_msg = err_msg.format(symbol,position)
raise ValueError(err_msg)
... | [
"def add_atom(self, atom):\n self.atoms.append(atom)\n atomname = atom.name\n self.map[atomname] = atom\n try:\n atom.reference = self.reference.map[atomname]\n for bond in atom.reference.bonds:\n if self.has_atom(bond):\n bondatom ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
remove an atom from the structure This method checks for atom at the position, if an atom exists. It is removed from the structure then the position is recorded as a vacancy. | def remove_atom(self,symbol, position):
for i,a in enumerate(self._atoms):
if (a.symbol == symbol):
diff = [abs(position[j]-a.position[j]) for j in range(3)]
print(diff)
is_atom = True
for j in range(3):
if diff[j] >... | [
"def RemoveAtom(self, aobj):\n if aobj in self.atomlist:\n self.atomlist.remove(aobj)\n if self.atomdicfa.has_key((aobj.residuenumber, aobj.atomname)):\n del(self.atomdicfa[(aobj.residuenumber, aobj.atomname)])",
"def remove_atom(self, atom):\n return self.remove_vertex(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
makes a supercell from a given cell | def make_super_cell(structure, sc):
supercell = Structure()
supercell.structure_comment = "{}x{}x{}".format(sc[0],sc[1],sc[2])
# set lattice parameter
supercell.lattice_parameter = structure.lattice_parameter
# set h_matrix
h = np.zeros(shape=[3,3])
for i in range(3):
h[i,:] = ... | [
"def supercell_lattice(lattice, nx, ny, nz):\n a, b, c, alpha, beta, gamma = cl.cell_to_cellpar(lattice)\n sup_A = a * nx\n sup_B = b * ny\n sup_C = c * nz\n SUP_cellpar = sup_A, sup_B, sup_C, alpha, beta, gamma\n SUP_cell = cl.cellpar_to_cell(SUP_cellpar, ab_normal=(0, 0, 1),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If `public` is `False`, `allow_comments` must be `False` too. If `allow_comments` is `False`, `allow_anonymous_comments` must be `False` too. | def save(self, *args, **kwargs):
if not self.public:
self.allow_comments = False
if not self.allow_comments:
self.allow_anonymous_comments = False
return super(PostedModel, self).save(*args, **kwargs) | [
"def user_can_access_comment(self, user):\n return user.is_staff",
"def IsPublic(self) -> bool:",
"def get_block_public_access_configuration():\n pass",
"def testWillBePostedSignalModifyComment(self):\n def receive(sender, **kwargs):\n # a bad but effective spam filter :)...\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if string is a fourdigit integer. | def _four_digit(string):
try:
return len(string) == 4 and int(string) == float(string)
except ValueError:
return False | [
"def bigger_than_four(value):\n return int(value, 10) > 4",
"def is_int(string) -> bool:\n\n try:\n int(string)\n return True\n except ValueError:\n return False",
"def is_int(string: Text) -> bool:\n \n try:\n int(string)\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make a slug, avoiding to use a "forbidden slug" title and a fourdigit integer (to avoid clashing with years). | def _make_slug(title):
if title in constants.FORBIDDEN_SLUGS or _four_digit(title):
title += constants.SLUG_MODIFIER
return slugify(title) | [
"def _make_unique_slug(self, **kwargs):\n if self.slug:\n slug = self.slug[:50]\n else:\n slug = slugify(self.title)[:50]\n using = kwargs['using'] if 'using' in kwargs else 'default'\n existing = Submission.objects.using(using).filter(slug=slug)\n if (not ex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If comment belongs to a registered user, empty `guest_name`. | def save(self, *args, **kwargs):
if self.user is not None:
self.guest_name = ''
super(Comment, self).save(*args, **kwargs) | [
"def guest_login(self, guest_login):\n \n self._guest_login = guest_login",
"def get_full_name(self):\n # The user is identified by their email address\n if self.first_name == \"\" and self.last_name == \"\": \n return self.email\n return self.first_name + \" \" + s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load template image (needle) and the large example image (haystack), generate matching score per pixel, plot the results. | def main():
img_haystack = skiutil.img_as_float(data.camera()) # the image in which to search
img_needle = img_haystack[140:190, 220:270] # the template to search for
img_sad = np.zeros(img_haystack.shape) # score image
height_h, width_h = img_haystack.shape
height_n, width_n = img_needle.shape
... | [
"def testMatch(im1_fname=r\"chickenbroth_01.jpg\", im2_fname=r\"chickenbroth_02.jpg\",\n match_ratio=MATCH_RATIO):\n # Load first image\n im1 = cv2.imread(str(DATA_FOLDER / im1_fname))\n # Fully perform SIFT detection and BRIEF description\n locs1, desc1 = briefLite(im1)\n\n # Load secon... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the sum of absolute differences between two image patches. | def sad(img1, img2):
return np.sum(np.abs(img1 - img2)) | [
"def ImageDelta (image1, image2, mask = False):\n img1_factor = np.mean(image1)\n img2_factor = np.mean(image2)\n\n img1 = np.clip(image1/(img1_factor/10000),0,64000)\n img2 = np.clip(image2/(img2_factor/10000),0,64000)\n\n contrast_image = np.absolute(img1 - img2)\n raw_contrast_image = np.absolu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Amazon DynamoDB Class Constructor. Don't use it directly, call through a Session(). e.g. wr.redshift.your_method() | def __init__(self, session: "Session"):
self._session: "Session" = session
self._client_dynamodb: client = session.boto3_session.client(service_name="dynamodb",
use_ssl=True,
... | [
"def __init__(self, temboo_session):\n super(BatchGetItem, self).__init__(temboo_session, '/Library/Amazon/DynamoDB/BatchGetItem')",
"def initDynamoDb(self):\n if self._awsProfileName is not None:\n print('Using AWS profile', self._awsProfileName)\n sess = boto3.session.Session... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read all files of a project | def get(self, project_uuid):
results = read_all_files(FOLDER + project_uuid)
return results | [
"def read_all_raw_files():\n pass",
"def project_files(self):\n return map(lambda p: p[2], self.projects)",
"def files(site):\n build_path = os.path.join(PATH, '.build')\n print fileList(build_path, relative=True)\n return [File(site, p) for p in fileList(build_path, relative=True... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Craetes and returns datetime.date variable with age in years, months and days | def form_age(days_lived):
age_year, age_month = divmod(days_lived, 365)
age_month, age_day = divmod(age_month, 30)
return datetime.date(age_year, age_month, age_day) | [
"def determine_age(dob, date):\n age = date.year - dob.year - ((dob.month, dob.day) > (date.month, date.day))\n\n # age = abs((date – dob)).days / 365.25\n\n return age",
"def age_calc(self):\n if self.professor_dob is not False:\n self.age = (datetime.today().date()-datetime.strptime(\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if an object is contained within another via ``lhs_val in rhs_val``. Raises ``TestFailure`` if not. | def assert_in(lhs_val: Any, rhs_val: Any, assert_msg: str) -> None:
if lhs_val not in rhs_val:
error_line_no = _prev_frame().f_lineno
raise TestAssertionFailure(
f"{lhs_val} is not in {rhs_val}",
lhs=lhs_val,
rhs=rhs_val,
error_line=error_line_no,
... | [
"def assert_not_in(lhs_val: Any, rhs_val: Any, assert_msg: str) -> None:\n if lhs_val in rhs_val:\n error_line_no = _prev_frame().f_lineno\n raise TestAssertionFailure(\n f\"{lhs_val} is in {rhs_val}\",\n lhs=lhs_val,\n rhs=rhs_val,\n error_line=error_lin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if an object is not contained within another via ``lhs_val not in rhs_val``. Raises ``TestFailure`` if lhs is contained within rhs. | def assert_not_in(lhs_val: Any, rhs_val: Any, assert_msg: str) -> None:
if lhs_val in rhs_val:
error_line_no = _prev_frame().f_lineno
raise TestAssertionFailure(
f"{lhs_val} is in {rhs_val}",
lhs=lhs_val,
rhs=rhs_val,
error_line=error_line_no,
... | [
"def assert_in(lhs_val: Any, rhs_val: Any, assert_msg: str) -> None:\n if lhs_val not in rhs_val:\n error_line_no = _prev_frame().f_lineno\n raise TestAssertionFailure(\n f\"{lhs_val} is not in {rhs_val}\",\n lhs=lhs_val,\n rhs=rhs_val,\n error_line=error... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check the object identity via ``lhs_val is rhs_val``. Raises ``TestFailure`` if not identical. | def assert_is(lhs_val: Any, rhs_val: Any, assert_msg: str) -> None:
if lhs_val is not rhs_val:
error_line_no = _prev_frame().f_lineno
raise TestAssertionFailure(
f"{lhs_val} is not {rhs_val}",
lhs=lhs_val,
rhs=rhs_val,
error_line=error_line_no,
... | [
"def assert_is_not(lhs_val: Any, rhs_val: Any, assert_msg: str) -> None:\n if lhs_val is rhs_val:\n error_line_no = _prev_frame().f_lineno\n raise TestAssertionFailure(\n f\"{lhs_val} is {rhs_val}\",\n lhs=lhs_val,\n rhs=rhs_val,\n error_line=error_line_n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check the object identity via ``lhs_val is not rhs_val``. Raises ``TestFailure`` if identical. | def assert_is_not(lhs_val: Any, rhs_val: Any, assert_msg: str) -> None:
if lhs_val is rhs_val:
error_line_no = _prev_frame().f_lineno
raise TestAssertionFailure(
f"{lhs_val} is {rhs_val}",
lhs=lhs_val,
rhs=rhs_val,
error_line=error_line_no,
... | [
"def assert_is(lhs_val: Any, rhs_val: Any, assert_msg: str) -> None:\n if lhs_val is not rhs_val:\n error_line_no = _prev_frame().f_lineno\n raise TestAssertionFailure(\n f\"{lhs_val} is not {rhs_val}\",\n lhs=lhs_val,\n rhs=rhs_val,\n error_line=error_li... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check lhs_val is less than the rhs_val via ``lhs_val < rhs_val``. Raises ``TestFailure`` if not. | def assert_less_than(lhs_val: Any, rhs_val: Any, assert_msg: str) -> None:
if lhs_val >= rhs_val:
error_line_no = _prev_frame().f_lineno
raise TestAssertionFailure(
f"{lhs_val} >= {rhs_val}",
lhs=lhs_val,
rhs=rhs_val,
error_line=error_line_no,
... | [
"def assert_less_than_equal_to(lhs_val: Any, rhs_val: Any, assert_msg: str) -> None:\n if lhs_val > rhs_val:\n error_line_no = _prev_frame().f_lineno\n raise TestAssertionFailure(\n f\"{lhs_val} > {rhs_val}\",\n lhs=lhs_val,\n rhs=rhs_val,\n error_line=er... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check lhs_val is less than or equal to the rhs_val via ``lhs_val <= rhs_val``. Raises ``TestFailure`` if not. | def assert_less_than_equal_to(lhs_val: Any, rhs_val: Any, assert_msg: str) -> None:
if lhs_val > rhs_val:
error_line_no = _prev_frame().f_lineno
raise TestAssertionFailure(
f"{lhs_val} > {rhs_val}",
lhs=lhs_val,
rhs=rhs_val,
error_line=error_line_no,
... | [
"def assert_less_than(lhs_val: Any, rhs_val: Any, assert_msg: str) -> None:\n if lhs_val >= rhs_val:\n error_line_no = _prev_frame().f_lineno\n raise TestAssertionFailure(\n f\"{lhs_val} >= {rhs_val}\",\n lhs=lhs_val,\n rhs=rhs_val,\n error_line=error_lin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check lhs_val is greater than the rhs_val via ``lhs_val > rhs_val``. Raises ``TestFailure`` if not. | def assert_greater_than(lhs_val: Any, rhs_val: Any, assert_msg: str) -> None:
if lhs_val <= rhs_val:
error_line_no = _prev_frame().f_lineno
raise TestAssertionFailure(
f"{lhs_val} <= {rhs_val}",
lhs=lhs_val,
rhs=rhs_val,
error_line=error_line_no,
... | [
"def assert_greater_than_equal_to(lhs_val: Any, rhs_val: Any, assert_msg: str) -> None:\n if lhs_val < rhs_val:\n error_line_no = _prev_frame().f_lineno\n raise TestAssertionFailure(\n f\"{lhs_val} < {rhs_val}\",\n lhs=lhs_val,\n rhs=rhs_val,\n error_line... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check lhs_val is greater than or equal to the rhs_val via ``lhs_val >= rhs_val``. Raises ``TestFailure`` if not. | def assert_greater_than_equal_to(lhs_val: Any, rhs_val: Any, assert_msg: str) -> None:
if lhs_val < rhs_val:
error_line_no = _prev_frame().f_lineno
raise TestAssertionFailure(
f"{lhs_val} < {rhs_val}",
lhs=lhs_val,
rhs=rhs_val,
error_line=error_line_no... | [
"def assert_greater_than(lhs_val: Any, rhs_val: Any, assert_msg: str) -> None:\n if lhs_val <= rhs_val:\n error_line_no = _prev_frame().f_lineno\n raise TestAssertionFailure(\n f\"{lhs_val} <= {rhs_val}\",\n lhs=lhs_val,\n rhs=rhs_val,\n error_line=error_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return previous stack frame of where this func is called. | def _prev_frame() -> FrameType:
this_frame = inspect.currentframe()
if not this_frame:
sys.exit(
"ERROR: Ward requires an interpreter with Python stack frame support\n"
)
caller_frame = this_frame.f_back
assert caller_frame, "the frame where _prev_frame was called must exist"... | [
"def currentframe():\n try:\n raise Exception\n except:\n return sys.exc_traceback.tb_frame.f_back",
"def previous_field(self):\n self.stack[-1].previous()",
"def findCallerPatch():\n\n frame = currentframe()\n if frame is not None:\n frame = frame.f_back\n\n backFrame... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs a linear combination of two loss functions. | def make_composite_loss(y_true, y_hat, loss_a, loss_b, w_a, w_b):
return loss_a(y_true, y_hat) * w_a + loss_b(y_true, y_hat) * w_b | [
"def make_loss_function(network_apply_fun, basic_loss_fun, regularization_fun):\n\n def total_loss_fun(params, batch):\n \"\"\"\n Maps network parameters and training batch to a loss value.\n\n Args:\n batch: a dictionary with keys ['inputs', 'index', 'labels']\n 'inputs': sequence of inputs w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the model of this ModelApiSpecSerializer. | def model(self, model):
if model is None:
raise ValueError("Invalid value for `model`, must not be `None`") # noqa: E501
self._model = model | [
"def set_model(self, model):\n self.set_abstract_item(\"General\", \"Model\", model)",
"def setModel(self, model):\n\n self.model = model\n self.model.dataChanged.connect(self.fetchData)",
"def setModel(engine,model):\n engine.model = model",
"def set_model_id(self, model_id):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the hardware of this ModelApiSpecSerializer. | def hardware(self):
return self._hardware | [
"def hardware(self) -> str:\n self._logger.info(\"Retrieving device hardware version...\")\n return self._device_info().get(\"hardware\")",
"def get_hardware(self):\n return self._hardware_list",
"def hardware_data(self):\n return self._hardware_data",
"def hardware_profile(self) -... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the hardware of this ModelApiSpecSerializer. | def hardware(self, hardware):
if hardware is None:
raise ValueError("Invalid value for `hardware`, must not be `None`") # noqa: E501
self._hardware = hardware | [
"def setHardwareID(self, hwid):\n self.hwid = hwid",
"def _set_hardware_port(self, v, load=False):\n if hasattr(v, \"_utype\"):\n v = v._utype(v)\n try:\n t = YANGDynClass(v,base=ReferenceType(referenced_path='/oc-platform:components/oc-platform:component/oc-platform:name', caller=self._pat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the stage of this ModelApiSpecSerializer. | def stage(self):
return self._stage | [
"def stage_number(self):\n return self._stage_number",
"def stage_id(self) -> str:\n return self._stage_id",
"def get_stage(self):\n return self.get_prev_state().value - 99",
"def get_stage(cls, name):\n return cls.pipeline_stages[name][0]",
"def _find_stage(self):\n try:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the stage of this ModelApiSpecSerializer. | def stage(self, stage):
self._stage = stage | [
"def stage_number(self, stage_number):\n\n self._stage_number = stage_number",
"def set_stage_num(self, request, pk=None):\n try:\n serializer = IntegerSerializer(data=request.data)\n if serializer.is_valid():\n # Update the document.\n workspace =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load all human evaluation data cached on CodaLab into a single dictionary | def _load_humaneval(self, eval_cache_path: str) -> Dict:
if "cnndm" in self.task:
dataset = "cnndm"
elif "xsum" in self.task:
dataset = "xsum"
else:
raise ValueError
all_humaneval_scores = dict()
for shots in [0, 5]:
score_analyzer... | [
"def _load_r_dicts(self):\n pass",
"def dump_preprocessed(self) -> None:\n instances = list(Instance.instance_hash.values())\n predictions = defaultdict(list)\n for i in instances:\n for p in i.get_entry(\"predictions\"):\n predictions[p.model].append(p)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Dumps pairwise model comparison results (based on paired bootstrap test) into a json file. | def dump_test_result(self, output_file_path: str):
assert self.faithfulness
assert self.coherence
assert self.relevance
output_pvalues = defaultdict(list)
avg_faithful_scores = self._compute_average(self.faithfulness)
sorted_models, _ = zip(*sorted(avg_faithful_scores, ... | [
"def save_results(mean_gbps, stddev_gbps):\n filename = args.traffic.split('/')[-1]\n outfile = OUTDIR + filename\n\n if os.path.isfile(outfile):\n # Append to existing json; don't clobber\n with open(outfile, 'r') as f:\n results = json.load(f)\n\n os.remove(outfile)\n e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generator iterating over these rule's cssRules. | def __iter__(self):
for rule in self._cssRules:
yield rule | [
"def _get_global_rules(self):\n for ruleset in ['pre_default', 'default', 'pre_zone']:\n rules = {}\n\n try:\n rules = self.config['global']['rules'][ruleset]\n except KeyError:\n pass\n\n for rule in self._get_rules(rules):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return serialized property cssText. | def _getCssText(self):
return cssutils.ser.do_CSSMediaRule(self) | [
"def _getCssText(self):\r\n return cssutils.ser.do_CSSStyleRule(self)",
"def css_property(self, prop):\n\n return self.element().value_of_css_property(str(prop)) if self.exists() else ''",
"def __serialize_style(cls, obj):\n return {\n \"type\": \"CssStylesheet\",\n \"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete the rule at `index` from the media block. | def deleteRule(self, index):
self._checkReadonly()
try:
self._cssRules[index]._parentRule = None # detach
del self._cssRules[index] # remove from @media
except IndexError:
raise xml.dom.IndexSizeErr(
u'CSSMediaRule: %s is not a valid i... | [
"def remove_rule_by_index(self, rule_head, rule_index):\n self.nonterminals.get(str(rule_head.tag)).remove_by_index(rule_index)",
"def deleteAtIndex(self, index: int) -> None:\n if index >= self.length:\n return\n if index == 0:\n self.first = self.first.next\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add `rule` to end of this mediarule. | def add(self, rule):
self.insertRule(rule, index=None) | [
"def add_rule(self, *args):\n return _wali.EWPDS_add_rule(self, *args)",
"def add_egress_rule(self, rule):\n self.egress_rules.append(rule)",
"def add_rule(self, predicate, target, action=None):\n self.rules.append((predicate, target, action))",
"def set_rule(self, rule):\n self.ru... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert `rule` into the media block. | def insertRule(self, rule, index=None):
self._checkReadonly()
# check position
if index is None:
index = len(self._cssRules)
elif index < 0 or index > self._cssRules.length:
raise xml.dom.IndexSizeErr(
u'CSSMediaRule: Invalid index %s for ... | [
"def add(self, rule):\r\n self.insertRule(rule, index=None)",
"def set_rule(self, rule):\n self.rule = rule # pragma: no cover",
"def add_ruleset(self, selector, declaration):\n self._list_rules.append((selector, declaration))",
"def add_ingress_rule(self, rule):\n self.ingress_ru... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
clone attributes of close words / synonyms which aren't yet into the database, or which lacks informations. | def clone_attributes():
_clone_attributes(utils.get_sentiwordnet_groups(SENTIWORDNET_FILE))
_clone_attributes(utils.get_e_lemma_groups(E_LEMMA_FILE)) | [
"def replicate_attributes(self):\n changed = False\n if getattr(self, 'phonology', None):\n changed = self.set_attr('word_boundary_symbol', self.phonology.word_boundary_symbol, changed)\n changed = self.set_attr('morpheme_delimiters', self.morphology.morpheme_delimiters, changed)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
convert a sentence in a corresponding list of bases | def _sentence2bases(sentence):
return tuple(word.get_types() for word in sentence2words(sentence)) | [
"def ambiguous_bases(seq):\n ambig_bases = ['y', 'Y']\n ambig_dict = {'Y':'[tcTC]', 'y': '[tcTC]'}\n bases=[]\n for base in seq:\n if base in ambig_bases:\n\n bases.append(ambig_dict[base])\n else: bases.append(base)\n\n return \"\".join(bases)",
"def rna_translate(bases):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks how well the given solution satisfied the differential equaitons. Returns a number [W] that is a measure of well the functions satisfy the differential equations, lower is better. | def checkSolution(Hw, Hpb):
Tw = [getTW(H) for H in Hw]
Tpb = [getTPb(H) for H in Hpb]
discrepancyQW = []
discrepancyQPb = []
for i in range(1, N):
deltaHW = Hw[i] - Hw[i-1]
discrepancy = deltaHW - dHWdz(Tpb[i], Tw[i], Hw[i])*dz
discrepancyQW.append(getQW(discrepancy)*1e6)
for i in range(1, N):
deltaHPb =... | [
"def getBestSolutionValue(self) -> float:",
"def get_solution(self):\n # TODO: enter your code here\n solution = 0.0\n f = domain[:, 0]\n for idx, item in enumerate(self.x):\n if self.v[idx][0] >= self.v_min and self.f[idx][0] > f:\n f = self.f[idx][0]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sorts a dictionary where key is addr and value is numerical. | def sort_addr_dict(self, addr_dict, get_list=False, reverse=True):
sorted_addrs, _ = zip(*sorted(addr_dict.items(), key=itemgetter(1), reverse=reverse))
if get_list:
return sorted_addrs
return sorted_addrs[0] | [
"def sort_counts(counts_dict):\n return sorted(counts_dict.items(), key=lambda item: item[1], reverse=True)",
"def sort_dict_values(family_dict: Dict[str, List[str]]) -> Dict[str, List[str]]:\n\n for last_name in family_dict:\n family_dict[last_name].sort()\n\n return family_dict",
"def sort_by_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Estimate value the SGD model. Returns the estimate and individual values for different features. | def _sgd_estimate(self, addr, features):
assert self.std != None, 'std not set'
vals = np.zeros(self.num_of_features)
for i in range(self.num_of_features):
vals[i] = gaus_pdf(features[i], self.centroids[addr][i], self.std) / self.max
estimate = np.sum(self.sgd_weights[addr] ... | [
"def Estimate(self):\n\n #Different estimates:\n #Could do mode, median, mean, or other.\n #Bayesian MMSE estimator is just weighted arithmetic mean of particle states:\n \n #Get the WEIGHTED array of particle states to use in both calculations:\n weights_repeat = np.repeat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the Qvalue for state, addr pair. | def update_q(self, value, addr, state, learning_factor=0.9):
old_value = self.q_vals[state][addr]
self.q_vals[state][addr] += learning_factor * (value - old_value) | [
"def update(self, eqstate):\n raise NotImplementedError",
"def update_address(self, address_details):\n pass",
"def _update_q_value_sequence(self, state_list, reward):\n # updates the Q-value for the last state pair (update taking place in the reverse order)\n self._update_q_value(st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of addresses in order of highest to lowest average evaluation of the artifacts. Sorting is based on a list of multiple artifacts. | def linear_choose_multi(self, artifacts):
addrs = list(self.linear_weights.keys())
if np.random.random() < self.e:
return self.get_random_addr(get_list=True)
estimate_dict = {}
for addr in addrs:
estimate_dict[addr] = 0
for artifact in artifacts:
... | [
"def _sorted_artifacts(self, artifact):\n raise NotImplementedError",
"def get_analysed_sorted(self):\n\n\t\treturn sorted(self.analysed, key = lambda a: a.address)",
"def __avg_proxy_link(self, data, alpha, nb_proxies):\n data = self.__pair_sim(data, alpha)\n data = data.groupby(['exec.id.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the states in order of sum for top n addrs. | def get_best_top_n_state(self, states, n):
state_vals = {}
for state in states:
vals = sorted(self.q_vals[state].values(), reverse=True)
state_vals[state] = sum(vals[:n])
states_sorted = sorted(state_vals.items(), key=itemgetter(1), reverse=True)
return states_sor... | [
"def get_states_with_most_rows(gdf, n):\r\n counts = gdf.groupby('state').size().reset_index(name='counts') \\\r\n .sort_values('counts').tail(n)['state'].values\r\n\r\n return counts",
"def get_top_n_nodes(nodes, n=10, nx=False):\n top = OrderedDict(sorted(nodes.items(), key=lambda kv: kv[1],... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a set of states where no addr has its highest value and a set of the states where some addr has its highest value. | def filter_states(self):
occupied = set()
for addr in self.addrs:
vals = [(state, self.q_vals[state][addr]) for state in self.q_vals.keys()]
best_state = sorted(vals, key=itemgetter(1), reverse=True)[0][0]
occupied.add(best_state)
free = set(self.q_vals.keys()... | [
"def get_best_top_n_state(self, states, n):\n state_vals = {}\n for state in states:\n vals = sorted(self.q_vals[state].values(), reverse=True)\n state_vals[state] = sum(vals[:n])\n states_sorted = sorted(state_vals.items(), key=itemgetter(1), reverse=True)\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
MinMax CutMix boundingbox Inspired by Darknet cutmix impl, generates a random rectangular bbox based on min/max percent values applied to each dimension of the input image. Typical defaults for minmax are usually in the .2.3 for min and .8.9 range for max. | def rand_bbox_minmax(img_shape: Tuple, minmax: Union[Tuple, List], count: Optional[int]=None):
assert len(minmax) == 2
img_h, img_w = img_shape[-2:]
cut_h = np.random.randint(
int(img_h * minmax[0]), int(img_h * minmax[1]), size=count)
cut_w = np.random.randint(
int(img_w * minmax[0]), i... | [
"def rand_bbox_minmax(img_shape, minmax, count=None):\n assert len(minmax) == 2\n img_h, img_w = img_shape[-2:]\n cut_h = np.random.randint(int(img_h * minmax[0]), int(img_h * minmax[1]), size=count)\n cut_w = np.random.randint(int(img_w * minmax[0]), int(img_w * minmax[1]), size=count)\n yl = np.ran... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A decorator for model methods that require training before being run. | def requires_training_wheels(method):
def wrapper(model, *args, **kwargs):
if not model.is_trained:
raise TypeError("the model needs training first")
return method(model, *args, **kwargs)
return wrapper | [
"def trainModel(self, Model) -> None:\n ...",
"def _requires_fit(method):\n @functools.wraps(method)\n def method_wrapped(self, *args, **kwargs):\n if not self._is_fitted:\n raise ModelNotFit(\"This model has not been fit yet\")\n\n return method(self, *ar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A decorator for model methods that require some part of a model description. | def requires_model_description(*args):
def decorator(method):
"""
A decorator for model methods that require a full model description.
:param method:
A method belonging to a sub-class of BaseCannonModel.
"""
def wrapper(model, *args, **kwargs):
... | [
"def decorator(method):\n \n def wrapper(model, *args, **kwargs):\n for attr in descriptors or model._descriptive_attributes:\n if getattr(model, attr) is None:\n raise TypeError(\"the model requires a {} term\".format(\n attr.lstrip(\"_\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A decorator for model methods that require a full model description. | def decorator(method):
def wrapper(model, *args, **kwargs):
for attr in descriptors or model._descriptive_attributes:
if getattr(model, attr) is None:
raise TypeError("the model requires a {} term".format(
attr.lstrip("_")))
... | [
"def requires_model_description(*args):\n\n def decorator(method):\n \"\"\"\n A decorator for model methods that require a full model description.\n\n :param method:\n A method belonging to a sub-class of BaseCannonModel.\n \"\"\"\n \n def wrapper(model, *args, **... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the labelled set data attributes. | def _init_data_attributes(self, labelled_set, normalized_flux,
normalized_ivar, mode="c", dtype=float):
is_path = lambda p: isinstance(p, string_types) and path.exists(p)
if is_path(normalized_flux):
normalized_flux = np.memmap(normalized_flux, mode=mode, dtype=dtype)
no... | [
"def test_initialization(data_and_labels):\n labeled_data = LabeledData(*data_and_labels)\n\n assert hasattr(labeled_data, \"_data\")\n assert hasattr(labeled_data, \"_label\")",
"def __init__(self, original_dataset, mislabel_ratio):\n self.dataset = original_dataset\n self.mislabel_ratio =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clear any attributes that have been trained upon. | def reset(self):
for attribute in self._trained_attributes:
setattr(self, attribute, None)
return None | [
"def clear_node_attributes(self):\n for node in self.nodes():\n self.node_attr[node] = []",
"def clean(self):\n self.prediction = None\n self.prediction_labels = None\n self.current_pipeline = None",
"def clear_trajectories(self):\n for attr in ['system', 'times', '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the normalized fluxes of pixels for stars in the labelled set. | def normalized_flux(self):
return self._normalized_flux | [
"def flux(self):\n #flux = self.data[self.select]['flux'] * self.units['flux']\n flux = self.data['flux'][self.select].compressed() * self.units['flux']\n if self.normed and self.co_is_set:\n # Avoid dividing by zero\n co = self.data['co'][self.select].compressed()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the vectorizer for this Cannon model. | def vectorizer(self):
return self._vectorizer | [
"def vectorizer(self, vectorizer):\n if vectorizer is None:\n self._vectorizer = None\n return None\n\n if not isinstance(vectorizer, BaseVectorizer):\n raise TypeError(\"vectorizer must be \"\n \"a sub-class of vectorizers.BaseVectorizer\")\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the vectorizer for this Cannon model. | def vectorizer(self, vectorizer):
if vectorizer is None:
self._vectorizer = None
return None
if not isinstance(vectorizer, BaseVectorizer):
raise TypeError("vectorizer must be "
"a sub-class of vectorizers.BaseVectorizer")
self._ve... | [
"def _vectorize(self):\n vect = TfidfVectorizer(stop_words='english', tokenizer=self.tokenizer,\n max_features=self.max_features)\n vector_matrix = vect.fit_transform(self.reviews)\n\n self.vectors = vector_matrix.toarray()\n self.cols = vect.get_feature_nam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return whether the provided labels are inside a complex hull constructed from the labelled set. | def in_convex_hull(self, labels):
labels = np.atleast_2d(labels)
if labels.shape[1] != self.labels_array.shape[1]:
raise ValueError("expected {} labels; got {}".format(
self.labels_array.shape[1], labels.shape[1]))
hull = Delaunay(self.labels_array)
return ... | [
"def inside_hull(self, labels):\n L = flatten_struct(self.training_labels, use_labels=self.used_labels)\n l = flatten_struct(labels, use_labels=self.used_labels)\n hull = Delaunay(L.T)\n return hull.find_simplex(l.T) >= 0",
"def contains_labeled_atom(self, label):\n cython.decla... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return an array of all the label values in the labelled set which contribute to the design matrix. | def labels_array(self):
return self.get_labels_array(self.labelled_set) | [
"def get_labels(self):\n return np.unique(self.labeled_feature[self.labeled_feature != 0])",
"def get_labels(self):\n return [\"0\",\"1\"]",
"def label_vector(self):\n labels = np.array(self.label.get_fdata().flatten(), dtype=int)\n labels = np.array(labels == 47, dtype=int) + np.arr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the percent by multiplying, the reason by appending. Return self so we can call this and return in one line. | def update(self, percent, reason):
self.percent *= percent / 100.0
if self.reason:
self.reason += " " + reason
else:
self.reason = reason
return self | [
"def giveRise(self, percent, bonus = 0.1):\n self.pay *= (1.0 + percent + bonus)",
"def apply_percent_coupon(self):\r\n return self.price - self.price*self.coupon.percent_amount",
"def update(self, pbar):\n return '%3d%%' % pbar.percentage()",
"def percent(self) -> float:\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate L1 bit rate with a given fps and packet size. Note that 'packet' size is number of bytes in the L2 (Ethernet) frame. Speed returned is L1 bps assuming ethernet with 20 bytes of preamble/fcs. | def calc_speed(Fps, AvgPacketSize):
frame_size = AvgPacketSize + 20
return frame_size * 8 * Fps | [
"def transmission_delay (packetLength_bytes, rate_bps):\n packetLength_bits = packetLength_bytes * 8\n return packetLength_bits / rate_bps",
"def frames_per_second():\r\n global _time_prev, _fps\r\n time_now = time.time() * 1000.0\r\n dt = time_now - _time_prev\r\n _time_prev = time_now\r\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return (fps, streamCount, packetSize) for the given profile | def get_traffic_info(profile):
fps = profile.get('avgFramesPerSecond', None)
streamCount = profile.get('streamCount', None)
packetSize = profile.get('avgPacketSize', None)
return (fps, streamCount, packetSize) | [
"def ffprobe_stream_information(self, stream_url):\n width, height, fps, codec, audio_codec = 0, 0, 0, None, None\n streams = self.run_ffprobe(stream_url)\n\n video_stream = None\n audio_stream = None\n for stream in streams[\"streams\"]:\n if video_stream and audio_str... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
True if the given profile has traffic configured. | def has_traffic(profile):
return all(get_traffic_info(profile)) | [
"def check_profile(profile, remote):\n\n return profile in get_profiles(remote)",
"def isProfileSetting(name):\n\tglobal settingsDictionary\n\tif name in settingsDictionary and settingsDictionary[name].isProfile():\n\t\treturn True\n\treturn False",
"def verify_profile_availability(self, profile):\n p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the average rate does not exceed the maximum speed. Returns a conf. of 100.0 (avg max) Note there is no scaling and we don't compare the expected maximum, just the expected average. | def check_max_speed(Fps, AvgPacketSize, max_speed, confidence=None):
if confidence is None:
confidence = Confidence()
avg_speed = calc_speed(Fps, AvgPacketSize)
if avg_speed > max_speed:
speed_str = port_info.convert_val_to_speed(max_speed)
return confidence.update(0, "Configured pac... | [
"def check_rate_advice(Fps, max_fps):\n if max_fps <= 1:\n return (\"The stream count and/or average packet size must be lowered \"\n \"in order to support any frame rate without predicted loss.\")\n\n factor = float(Fps) / max_fps\n if factor >= 1.5:\n return (\"The frame rate... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the Fps is valid given the StreamCount and AvgPacketSize. Returns a number from 100.0 (should def. work) to 0.0 (likely won't work). | def check_rate(Fps, StreamCount, AvgPacketSize, baseline_factor,
confidence=None):
if confidence is None:
confidence = Confidence()
max_fps = baseline_factor * calc_max_fps(StreamCount, AvgPacketSize)
if Fps <= max_fps * SAFETY_FACTOR:
# should be fine, return confidence unch... | [
"def check_rate_advice(Fps, max_fps):\n if max_fps <= 1:\n return (\"The stream count and/or average packet size must be lowered \"\n \"in order to support any frame rate without predicted loss.\")\n\n factor = float(Fps) / max_fps\n if factor >= 1.5:\n return (\"The frame rate... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate advice based on the requested Fps and max predicted fps. | def check_rate_advice(Fps, max_fps):
if max_fps <= 1:
return ("The stream count and/or average packet size must be lowered "
"in order to support any frame rate without predicted loss.")
factor = float(Fps) / max_fps
if factor >= 1.5:
return ("The frame rate of %d is approxi... | [
"def calculate_output_fps(self):\n max_interval_fps = 1 / min(\n [decoder.interval for decoder in self.decoders.values()]\n )\n self.output_fps = round(min([max_interval_fps, self.fps]))",
"def create_optical_flow(raw_frames, freq_of_motion=1):\n frame_set = dict()\n frame_se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the total memory is enough for the given StreamCount, AvgPktSz. Returns a number from 100.0 (should def. work) to 0.0 (likely won't work). | def check_mem(total_mem, StreamCount, AvgPacketSize, confidence=None):
if confidence is None:
confidence = Confidence()
mem_required = calc_mem_used(StreamCount, AvgPacketSize)
if mem_required <= total_mem * SAFETY_FACTOR:
# should be fine, return confidence unchanged
return confide... | [
"def test_enough_memory(self):\n import psutil\n mem = psutil.virtual_memory()\n mem_total_gib = mem.total * (2**-30)\n self.assertGreaterEqual(mem_total_gib, self.minimum_mem_gib,\n msg=\"The total available memory of this system\"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the baseline factor for the given location. This is calculated by comparing the preflight value just returned with the one stored locally (from the ports used to calculate the params above). If the given port is more powerful than the base, we do nothing (because we can't be sure if the extra power actually help... | def calc_baseline_factor(port_map, location):
loc_preflight = port_map.memo(location)["preflight"]
if loc_preflight >= BASE_PREFLIGHT:
return 1.0
else:
return float(loc_preflight) / BASE_PREFLIGHT | [
"def setBase(self):\n self.base = self.rp[0]*pow(10, self.rp[1])",
"def regular_percentage_above_base(self) -> Optional[pulumi.Input[int]]:\n return pulumi.get(self, \"regular_percentage_above_base\")",
"def base_capacity(self) -> pulumi.Output[int]:\n return pulumi.get(self, \"base_capacit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the total memory for the given location. Retrieved during the preflight test and stored in the port_map. | def get_total_mem(port_map, location):
return port_map.memo(location)["memtotal"] | [
"def get_memory(self):\n return self.__memories[self.__server_specific_name]",
"def get_memory():\n with open('/proc/meminfo') as f:\n return sum(map(lambda x: int(x.split()[1]),\n filter(re_mem.match, f.readlines())))",
"def total_memory_info() -> str:\n if GetOS.OS ==... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing whitespace is removed | def test_remove_with_whitespace():
assert remove("Don't worry my friends.", string.whitespace) == "Don'tworrymyfriends." | [
"def test_remove_spaces():\n test_string = \"a b c\"\n expected_string = \"abc\"\n\n subbed_string = search_spaces.sub('', test_string)\n assert subbed_string == expected_string",
"def test_whitespace_features():\n # -- WhitespaceCount ------------------------------------------------------\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing remove with exclude as a set or list | def test_remove_with_list_and_set():
assert remove("example", ['e', 'x']) == "ampl"
assert remove("example", set(['e', 'x'])) == "ampl" | [
"def remove_excluded_item(target):",
"def test_excludes(self):\n\n self.assertFalse(isiterable([], exclude=(list,) + string_types))",
"def avoid(self, excludes): \n if excludes is None or len(excludes) == 0: return self.shallow_copy(excludes=None)\n result = self.shallow_copy(excludes=excludes)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing splitting and combining 1 column text works | def test_columns_length_1():
text = "example"
split = split_columns(text, 1)
assert split == [text]
assert combine_columns(split) == text | [
"def test_columns_same_length():\n text = \"example\"\n split = split_columns(text, len(text))\n\n assert split == list(text)\n assert combine_columns(split) == text",
"def test_columns_lower_length():\n text = \"example\"\n split = split_columns(text, 4)\n\n assert split == ['ep', 'xl', 'ae'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing split and combine columns where n_columns is less than the length of text | def test_columns_lower_length():
text = "example"
split = split_columns(text, 4)
assert split == ['ep', 'xl', 'ae', 'm']
assert combine_columns(split) == text | [
"def test_columns_length_1():\n text = \"example\"\n split = split_columns(text, 1)\n\n assert split == [text]\n assert combine_columns(split) == text",
"def test_columns_same_length():\n text = \"example\"\n split = split_columns(text, len(text))\n\n assert split == list(text)\n assert co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing split and combine where n_columns = len(text) | def test_columns_same_length():
text = "example"
split = split_columns(text, len(text))
assert split == list(text)
assert combine_columns(split) == text | [
"def test_columns_length_1():\n text = \"example\"\n split = split_columns(text, 1)\n\n assert split == [text]\n assert combine_columns(split) == text",
"def test_columns_lower_length():\n text = \"example\"\n split = split_columns(text, 4)\n\n assert split == ['ep', 'xl', 'ae', 'm']\n ass... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing split columns with invalid lengths raise ValueError | def test_split_columns_invalid_values():
with pytest.raises(ValueError):
split_columns("example", -1)
with pytest.raises(ValueError):
split_columns("example", -200)
with pytest.raises(ValueError):
split_columns("example", 0)
with pytest.raises(ValueError):
split_column... | [
"def test_columns_same_length():\n text = \"example\"\n split = split_columns(text, len(text))\n\n assert split == list(text)\n assert combine_columns(split) == text",
"def test_columns_length_1():\n text = \"example\"\n split = split_columns(text, 1)\n\n assert split == [text]\n assert co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing iterating ngrams works | def test_iterate_ngrams():
assert list(iterate_ngrams("example", 4)) == ['exam', 'xamp', 'ampl', 'mple'] | [
"def test_iterate_ngrams_empty():\n assert list(iterate_ngrams(\"\", 1)) == []",
"def testA():\n print(\"Test the ngrams functions.\")\n input=\"aa bb cc dd bb aa cc bb\"\n output=ngrammodel.ngrams(input, 2)\n print(output)",
"def ngrams(n, s):\n\n\t# we loop each word from i = 0 to len(s) - n + ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing empty string returns no ngrams | def test_iterate_ngrams_empty():
assert list(iterate_ngrams("", 1)) == [] | [
"def testA():\n print(\"Test the ngrams functions.\")\n input=\"aa bb cc dd bb aa cc bb\"\n output=ngrammodel.ngrams(input, 2)\n print(output)",
"def test_ngrams():\n l1 = [1,2,3,4]\n assert string_distance_measures.ngrams(l1, 2) == [(1,2), (2,3), (3,4)]\n\n l2 = []\n assert string_distanc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing group with even length string | def test_group_even_length():
assert group("test", 2) == ['te', 'st'] | [
"def test_group_odd_length():\n assert group(\"example\", 2) == ['ex', 'am', 'pl', 'e']",
"def check_for_pattern(input_string):\n if len(input_string) < 2:\n return False\n\n length_of_division = 1\n limit = len(input_string)//2\n\n while length_of_division < limit + 1:\n divisions = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing group with odd length string | def test_group_odd_length():
assert group("example", 2) == ['ex', 'am', 'pl', 'e'] | [
"def test_group_even_length():\n assert group(\"test\", 2) == ['te', 'st']",
"def check_for_pattern(input_string):\n if len(input_string) < 2:\n return False\n\n length_of_division = 1\n limit = len(input_string)//2\n\n while length_of_division < limit + 1:\n divisions = equal_divisio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function to add search terms (keys and values) to the search dictionary. Takes the ID from the student_dictionary to be used as value in search_dict, and "value" which would be the search term to be used as a key in search_dict. | def helper_add(value, id):
# If key does not already exist:
if value not in search_dict:
search_dict[value] = [id] # Add to search_dict
else: # If key already exists
search_dict[value].append(id) # Append to existing list | [
"def add_to_curr_search_dict(term, count, results, curr_search_dict):\n \n curr_search_dict[term] = {'total_count' : count,\n 'countdown' : count,\n 'num_avail_shirts' : len(results),\n 'API_requests' : 1,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve one page of users in this domain. | def RetrievePageOfUsers(self, start_username=None):
uri = self._userURL()
if start_username is not None:
uri += '?startUsername=%s' % start_username
return self.GetFeed(uri, desired_class=gdata.apps.data.UserFeed) | [
"def getUser(self, user):\n return defer.succeed(self.users.get(user, \"No such user\"))\n # return client.getPage(self.prefix+user)",
"def get_users(self):\r\n sql = \"SELECT * FROM user WHERE auth <> 'root' LIMIT \" + str(self.user_per_page) + \" OFFSET \" + str(self.offset)\r\n self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a nickname for a user. | def CreateNickname(self, user_name, nickname):
uri = self._nicknameURL()
nickname_entry = gdata.apps.data.NicknameEntry()
nickname_entry.login = gdata.apps.data.Login(user_name=user_name)
nickname_entry.nickname = gdata.apps.data.Nickname(name=nickname)
return self.Post(nickname_entry, uri) | [
"def test_add_user_existing_nickname(self):\n print('(' + self.test_add_user_existing_nickname.__name__ + ')', self.test_add_user_existing_nickname.__doc__)\n request_data = ADD_USER_VALID_DATA.copy()\n request_data['nickname'] = 'Mystery'\n resp = self.client.post(resources.api.url_for(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve nicknames of the user. | def RetrieveNicknames(self, user_name):
uri = '%s?username=%s' % (self._nicknameURL(), user_name)
ret = self.GetFeed(uri, desired_class=gdata.apps.data.NicknameFeed)
# pagination
return self.RetrieveAllPages(ret, gdata.apps.data.NicknameFeed) | [
"def GetNicknames(self, domain, username):\n try:\n client = AppsClient(domain=domain)\n client.auth_token = self.Get2loToken()\n client.ssl = True\n feed = client.RetrieveNicknames(username)\n nicknames = []\n for entry in feed.entry:\n nicknames.append(entry.nickname.name)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Configures specific elements of the QTimers. | def configure_timers(self):
self.timer_plot = QTimer()
self.timer_plot.timeout.connect(self.update_plot) | [
"def _configure_timers(self):\n self._timer_plot = QtCore.QTimer(self)\n self._timer_plot.timeout.connect(self._update_plot)\n # self.timer = QtCore.QTimer()",
"def set_timers(self):\n pygame.time.set_timer(USEREVENTS.TIMER_ONE_SEC, 1000) #Each second",
"def set_timer(self, timer):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Append the region to the end of the list of regions. | def append(self, region):
self.regions.append(region) | [
"def extend(self, regions):\n self.regions.extend(regions)",
"def add_region(self, acc, start, end):\n if not self._finalised:\n self._regions[acc].append((start, end))\n self._signatures = {}\n else:\n raise RuntimeError()",
"def addRegion(self,newRange,ifC... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extend the list of regions by appending elements from the input regions. | def extend(self, regions):
self.regions.extend(regions) | [
"def extend(self, list):",
"def append(self, region):\n self.regions.append(region)",
"def extend(self, iterable):\r\n self._ranges = RangeSet._merge_ranges(\r\n self._ranges + (Range(r) for r in iterable)\r\n )",
"def addRegion(self,newRange,ifCreateNewRegion=False):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert the region before index. | def insert(self, index, region):
self.regions.insert(index, region) | [
"def insert_before(self, func, index):\n self.procedure.insert(index, func)",
"def start_region(self) -> None:\n self.current_region += 1",
"def insert(self, index, plot):\n super().insert(index, plot)",
"def insert_before(self, *nodes):\n self.parent_node.insert(self.index(), ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |