query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Mix an image by a constant base color. The base color should be a 1by3 arraylike object representing an RGB color in [0, 255]^3 space. For example, to mix with orange, the transformation RGBTransform().mix_with((255, 127, 0)) might be used. The factor controls the strength of the color to be added. If the factor is 1.0... | def mix_with(self, base_color, factor=1.0):
base_color = _to_rgb(base_color, "base_color")
operation = _embed44((1 - factor) * np.eye(3))
operation[:3, 3] = factor * base_color
return self._then(operation) | [
"def mix(\n self,\n color: ColorInput,\n percent: float = util.DEF_MIX,\n *,\n in_place: bool = False,\n **interpolate_args: Any\n ) -> 'Color':\n\n # Mix really needs to be between 0 and 1 or steps will break\n domain = interpolate_args.get('domain')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply this transformation to a copy of the given RGB image. The image should be a PIL image with at least three channels. Specifically, the RGB and RGBA modes are both supported, but L is not. Any channels past the first three will pass through unchanged. The original image will not be modified; a new image of the same... | def applied_to(self, image):
# PIL.Image.convert wants the matrix as a flattened 12-tuple.
# (The docs claim that they want a 16-tuple, but this is wrong;
# cf. _imaging.c:767 in the PIL 1.1.7 source.)
matrix = tuple(self.get_matrix().flatten())
channel_names = image.getbands()... | [
"def convert_image_to_rgb(self):\n self.image = self.image.convert('RGB')",
"def __enhance_image(self, img):\n\n blue = self.g.clahe.apply(img[:,:,0])\n green = self.g.clahe.apply(img[:,:,1])\n red = self.g.clahe.apply(img[:,:,2])\n img[:,:,0] = blue\n img[:,:,1] = green\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Embed a 4by4 or smaller matrix in the upperleft of I_4. | def _embed44(matrix):
result = np.eye(4)
r, c = matrix.shape
result[:r, :c] = matrix
return result | [
"def as4Matrix(self):\n return numpy.array([[ self._w, self._v[0], self._v[1], self._v[2]],\n [-self._v[0], self._w, -self._v[2], self._v[1]],\n [-self._v[1], self._v[2], self._w, -self._v[0]],\n [-self._v[2], -self._v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This will first try to load the specified module from the pyrominfo package using the current module search path. If it can't be found, then the parent directory is added to the module search path and the import attempt is repeated. | def loadModule(mod):
try:
# from pyrominfo import gameboy, etc
pyrominfo = __import__("pyrominfo", globals(), locals(), [mod])
except ImportError:
import os
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.insert(0, parentdir)
py... | [
"def _find_module(self, name, path, parent=None):\n\n if parent is not None:\n # assert path is not None\n fullname = parent.identifier + '.' + name\n else:\n fullname = name\n\n node = self.findNode(fullname)\n if node is not None:\n self.msg(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attach disk to VM by reconfiguration. | def attach_disk_to_vm(self, vm_ref, instance_name,
adapter_type, disk_type, vmdk_path=None,
disk_size=None, linked_clone=False,
controller_key=None, unit_number=None,
device_name=None):
client_factory = self.... | [
"def attach_disk_to_vm(self, vm_ref, instance,\n adapter_type, disk_type, vmdk_path=None,\n disk_size=None, linked_clone=False,\n device_name=None, disk_io_limits=None):\n instance_name = instance.name\n client_factory = self._... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Detach disk from VM by reconfiguration. | def detach_disk_from_vm(self, vm_ref, instance_name, device):
client_factory = self._session._get_vim().client.factory
vmdk_detach_config_spec = vm_util.get_vmdk_detach_config_spec(
client_factory, device)
disk_key = device.key
LOG.debug(_("Reconfiguri... | [
"def disk_detach(vmdk_path, vm):\n\n device = findDeviceByPath(vmdk_path, vm)\n\n if not device:\n # Could happen if the disk attached to a different VM - attach fails\n # and docker will insist to sending \"unmount/detach\" which also fails.\n msg = \"*** Detach failed: disk={0} not foun... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return volume connector information. | def get_volume_connector(self, instance):
iqn = volume_util.get_host_iqn(self._session, self._cluster)
return {
'ip': CONF.vmwareapi_host_ip,
'initiator': iqn,
'host': CONF.vmwareapi_host_ip
} | [
"def get_volume_connector(self, instance):\n try:\n vm_ref = vm_util.get_vm_ref(self._session, instance)\n except exception.InstanceNotFound:\n vm_ref = None\n iqn = self._iscsi_get_host_iqn(instance)\n connector = {'ip': CONF.vmware.host_ip,\n '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check that columns_lst is tbset of self.df.columns.names | def validate_col_lst(self, df, columns_lst):
if columns_lst == []:
raise ValueError("column_lst is empty")
col_set = set(columns_lst)
df_col_set = set(list(df))
if col_set - df_col_set != set():
msg = "col_lst has columns name that does not exists in the DataFrame... | [
"def verify_columns_in_dataframe(df, columns):\n\n if not isinstance(columns, list):\n columns = [columns]\n return set(columns).issubset(df.columns)",
"def _has_cols(trj: TrajaDataFrame, cols: list):\n return set(cols).issubset(trj.columns)",
"def _check_columns(df: pd.DataFrame, names: typing.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given an OU, find all the OUs within that OU... | def get_child_ous(logger, org_client, org_unit):
logger.debug("Getting OUs for: %s", org_unit)
result = [org_unit]
# for this OU, get all the children...
args = dict(ParentId=org_unit["Id"])
children = utils.generic_paginator(logger, org_client.list_organizational_units_for_parent,
... | [
"def search_ou(self, unit):\n if unit.startswith(\"ou=\"):\n ret = self.conn.search_s(\n unit,\n ldap.SCOPE_BASE,\n \"objectClass=organizationalUnit\"\n )\n else:\n ret = self.conn.search_s(\n ajan.config.ldap... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given a path, traverse Organizations OUs to locate the required OU... | def get_ou_from_path(logger, org_client, path):
logger.debug("Getting OU from path: %s", path)
current_ou = org_client.list_roots()["Roots"][0]["Id"]
if path == "/":
return {"Id":current_ou, "Path":path}
for dir_name in path.split("/")[1:]:
logger.debug("Getting OU from path: %s, looki... | [
"def get_accounts_for_ou(logger, options, org_client, path):\n logger.debug(\"Getting accounts for OU: %s\", path)\n org_unit = get_ou_from_path(logger, org_client, path)\n ous = []\n if options.no_recursive:\n ous.append(org_unit)\n else:\n ous.extend(get_child_ous(logger, org_client, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given a path, get all the AWS accounts within that part of an Organization... | def get_accounts_for_ou(logger, options, org_client, path):
logger.debug("Getting accounts for OU: %s", path)
org_unit = get_ou_from_path(logger, org_client, path)
ous = []
if options.no_recursive:
ous.append(org_unit)
else:
ous.extend(get_child_ous(logger, org_client, org_unit))
... | [
"def organizations(self):\n return self.get('{}/orgs'.format(ApiVersion.A1.value))",
"def get_aws_customers_account(self):\n filters = dict()\n filters['customer_id__in'] = self.get_customers_based_on_partner()\n filters['type'] = 'AWS'\n filters['active'] = 1\n\n return Clou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks globals() and builtins for the existence of the object name (used for StuWareSoftSystems' bootstrap) | def checkObjectInNameSpace(objectName):
if objectName is None or not isinstance(objectName, basestring) or objectName == u"": return False
if objectName in globals(): return True
return objectName in dir(builtins) | [
"def _is_builtin(obj):\n\treturn obj.__class__.__module__ == 'builtins'",
"def test_magicGlobalsBuiltins(self):\r\n self.flakes('__builtins__')",
"def missing_global(name):\n return name not in globals()",
"def _exists(name):\n return name in globals()",
"def test_magicGlobalsName(self):\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pass a string in the format 'x.x.x'. Will check that this MacOSX version is at least that version. The 3rd micro number is optional | def isOSXVersionAtLeast(compareVersion):
# type: (basestring) -> bool
try:
if not Platform.isOSX(): return False
def convertVersion(convertString):
_os_major = _os_minor = _os_micro = 0
_versionNumbers = []
for versionPart in Str... | [
"def check_legitimate_ver(version):\n return re.match(\"^[0-9.]+$\", version)",
"def check_regex(regex, version):\n os_version = version.split(' ')[0]\n os_version = os_version.split('-')[0]\n # If a version number is incomplete, extend it with zeros (e.g. 8 -> 8.0.0)\n dots = os_ve... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Detect Intel x86 32bit system | def isIntelX86_32bit():
return String(System.getProperty("os.arch", "null").strip()).toLowerCase(Locale.ROOT) == "x86" | [
"def is_32bit(self):\n return self.machine in ['i386', 'i586', 'i686']",
"def osarch_is_32_bit():\n return osarch_match(\"32-bit\")",
"def osarch_is_32_bit():\n return osarch_match(\"32-bit\")",
"def is_32bit(self) -> bool:\n return kernel32.IsWow64Process(self.handle)",
"def osarch_is_ia3... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Grabs the MD defaultText font, reduces default size down to below 18, sets UIManager defaults (if runtime extension, will probably error, so I catch and skip) | def setDefaultFonts():
if MD_REF_UI is None: return
# If a runtime extension, then this may fail, depending on timing... Just ignore and return...
try:
myFont = MD_REF.getUI().getFonts().defaultText
except:
myPrint("B","ERROR trying to call .getUI().getFonts().de... | [
"def get_default_font():\r\n return _font_defaultname",
"def _set_default_font(cls):\n if platform.system() == \"Linux\":\n for family in (\"DejaVu Sans\", \"Noto Sans\", \"Nimbus Sans\"):\n if family in tk.font.families():\n logger.debug(\"Setting default fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sets up Client Properties for JFileChooser() to behave as required >> Mac only | def setJFileChooserParameters(_jf, lReportOnly=False, lDefaults=False, lPackagesT=None, lApplicationsT=None, lOptionsButton=None, lNewFolderButton=None):
myPrint("D", "In ", inspect.currentframe().f_code.co_name, "()")
if not Platform.isOSX(): return
if not isinstance(_jf, JFileChooser): retur... | [
"def setFileDialogParameters(lReportOnly=False, lDefaults=False, lSelectDirectories=None, lPackagesT=None):\n\n myPrint(\"D\", \"In \", inspect.currentframe().f_code.co_name, \"()\")\n\n if not Platform.isOSX(): return\n\n _TRUE = \"true\"\n _FALSE = \"false\"\n\n _DIRS_FD = \"app... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sets up System Properties for FileDialog() to behave as required >> Mac only | def setFileDialogParameters(lReportOnly=False, lDefaults=False, lSelectDirectories=None, lPackagesT=None):
myPrint("D", "In ", inspect.currentframe().f_code.co_name, "()")
if not Platform.isOSX(): return
_TRUE = "true"
_FALSE = "false"
_DIRS_FD = "apple.awt.fileDialogForDirec... | [
"def system_settings(open_files_list: Any, config: Config) -> None:\r\n\r\n try:\r\n if open_files_list.selectedItems()[0].text() != 'No DAT files added yet':\r\n config.system_name = dat_details[open_files_list.selectedItems()[0].text()]['system_name']\r\n main_windo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This triggers MD to firePreferencesUpdated().... Hopefully refreshing Home Screen Views too | def fireMDPreferencesUpdated():
myPrint("DB", "In ", inspect.currentframe().f_code.co_name, "()" )
class FPSRunnable(Runnable):
def __init__(self): pass
def run(self):
myPrint("DB",".. Inside FPSRunnable() - calling firePreferencesUpdated()...")
... | [
"def on_show_prefs(self):\n self.init_tv_trackers()\n client.updatorr.get_config().addCallback(self.config_to_ui)",
"def on_apply_prefs(self):\n trackers_settings = {}\n\n for row in self.trackers_data_model:\n trackers_settings[row[0]] = {'login': row[2], 'password': row[3]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Will detect and then run the codeblock on the EDT | def genericSwingEDTRunner(ifOffEDTThenRunNowAndWait, ifOnEDTThenRunNowAndWait, codeblock, *args):
isOnEDT = SwingUtilities.isEventDispatchThread()
# myPrint("DB", "** In .genericSwingEDTRunner(), ifOffEDTThenRunNowAndWait: '%s', ifOnEDTThenRunNowAndWait: '%s', codeblock: '%s', args: '%s'" %(ifOffEDTThe... | [
"def takeControl(self):\n mainloop()",
"def swingRun(self, isCancelled: bool) -> None:\n ...",
"def run(self) -> None:\n self.mainloop()",
"def mainloop(self):\n self.window.mainloop()",
"def run():\n gui = GUI()\n gui.mainloop()",
"def main_loop(self):\n\n self.wi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implement your canvas drawing logic here, returning False will stop the rendering, returning True will continue it | def draw(self, canvas) -> bool:
return False | [
"def on_draw(self, widget, cr):\n #print \"starting to draw\"\n if self.double_buffer is not None:\n self.draw_tiles()\n cr.set_source_surface(self.double_buffer, 0.0, 0.0)\n cr.paint()\n else:\n print('Invalid double buffer')\n #print \"done d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implement your canvas animation drawing logic here, returning False will stop the rendering, returning True will continue it | def draw_animation(self, canvas, animation_tick) -> bool:
return False | [
"def draw(self, canvas) -> bool:\n return False",
"def draw(self):\r\n if not self.stopped:\r\n super().draw()\r\n self.next_frame()",
"def on_draw(self, widget, cr):\n #print \"starting to draw\"\n if self.double_buffer is not None:\n self.draw_tiles... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Respond to theme load ins here | def load_theme_values(self):
pass | [
"def manageTheme():",
"def on_load_theme (self):\n\n\t\tif self.has_started:\n\t\t\tself.init_buffers()\n\t\t\tself.redraw_background()\n\t\t\tself.redraw_foreground()",
"def setup(self, theme: Theme):",
"def onStartup(event):\n\n plugins = getPlugins()\n\n for themeDirectory in iterDirectoriesOfType(TH... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Starts a setup mode that is used for moving, resizing and other various changes that the user might setup | def start_setup(self, setup_type):
# Persist the user preferences when we end our setup
if (self.setup_type != "" and not setup_type):
self.setup_type = setup_type
rect = self.canvas.get_rect()
self.x = int(rect.x)
self.y = int(rect.y)
self.wi... | [
"def start_setup(self):\n self.all_buttons_inactive()\n self.b1.active = True\n self.b6.active = True\n self.b7.active = True\n self.all_dice_inactive()\n self.all_dice_roll()",
"def _setup(self):\n # Start the application (if not already running).\n if not ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract bbox info from file name. | def get_bbox(fname):
fname = fname.split('_') # fname -> list
i = fname.index('bbox')
return map(float, fname[i+1:i+5]) # m
| [
"def get_bbox(fname):\r\n fname = fname.split('_') # fname -> list\r\n i = fname.index('bbox')\r\n return list(map(float, fname[i+1:i+5])) # m\r",
"def format_bbox_file(self, img_name, data):\r\n\r\n with open(self.bboxes_local, 'w+') as fbbox:\r\n # remove path\r\n bboxes ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract EPSG number from file name. | def get_proj(fname):
fname = fname.split('_') # fname -> list
i = fname.index('epsg')
return fname[i+1] | [
"def extract_document_name(file_name):\n lines = reader.read_file_line('data/458/ids/' + file_name)\n name = converter.convert_to_latin(lines[1])\n return name.split(':')[0]",
"def visit_from_file_name(filename):\n expr = re.compile(r\"\\d{4}(?:\\d+)\")\n res = expr.search(filename)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return all 2d '/variable' names in the HDF5. | def get_grid_names(fname):
with h5py.File(fname, 'r') as f:
vnames = [k for k in f.keys() if f[k].ndim == 2]
return vnames | [
"def load_varnames_from_hdf5(fname, h5path='/'):\n def walk(group, node_type=h5py.Dataset):\n for node in list(group.values()):\n if isinstance(node, node_type):\n yield node\n\n h5file = h5py.File(fname, mode='r')\n varlist = []\n try:\n h5group = h5file.require... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that initializing a Matern1/2 kernel with 0 lengthscale raises an exception | def test_matern_zero_lengthscale(matern):
with pytest.raises(ValueError) as exp:
matern(lengthscale=0.0, variance=1.0, output_dim=1)
assert exp.value.args[0].find("lengthscale must be positive.") >= 0 | [
"def testZeroInput(self):\n nb.rescale_length(2.0)\n nb.rescale_length(0)\n self.assertEqual(2.0, nb.rscale)",
"def test_nonpositive_nu_raises_exception(nu):\n with pytest.raises(ValueError):\n kernels.Matern(input_dim=1, nu=nu)",
"def test_ard_init_scalar(D):\n kernel_1 = gpfl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that initializing a Matern1/2 kernel with 0 variance raises an exception | def test_matern12_zero_variance(matern):
with pytest.raises(ValueError) as exp:
matern(lengthscale=1.0, variance=0.0, output_dim=1)
assert exp.value.args[0].find("variance must be positive.") >= 0 | [
"def test_nonpositive_nu_raises_exception(nu):\n with pytest.raises(ValueError):\n kernels.Matern(input_dim=1, nu=nu)",
"def test_sample_zero_cov(self):\n for mean, cov in self.normal_params:\n with self.subTest():\n dist = prob.Normal(mean=mean, cov=0 * cov, random_stat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the assertion fires for a negative delta time | def test_to_delta_time_positive_difference(with_tf_random_seed, np_time_points):
time_points = tf.constant(np_time_points, dtype=default_float())
with pytest.raises(InvalidArgumentError) as exp:
to_delta_time(time_points)
assert exp.value.message.find("Condition x >= y") >= 0 | [
"def testNegative(self):\n self.assertRaises(hf.NegativeDeltaError, hf.humanize, \n datetime(2011, 12, 31, 23, 59, 0),\n datetime(2012, 1, 1, 0, 0, 0))\n self.assertRaises(hf.NegativeDeltaError, hf.humanize,\n datetime(2012, 1, 1, 11, 59, 0),\n datetime(2012... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the derivative of the logpdf with respect to the parameters. | def log_pdf_derivative(x):
return gs.autodiff.jacobian(log_pdf_at_x(x))(base_point) | [
"def log_derivative(x):\n der = derivative(log,x,dx=1e-9)\n return der",
"def logpdf(self, x):\n reg = self(x)\n nelem = tf.cast(tf.size(x), x.dtype)\n logz = nelem * (-math.log(self.stddev) - 0.5*math.log(2.0*math.pi))\n ll = -reg + self.weight*logz # weight already in reg\n\n return ll",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Compute the derivative of the innerproduct matrix. Compute the derivative of the innerproduct matrix of the Fisher information metric at the tangent space at base point. | def inner_product_derivative_matrix(self, base_point):
def pdf(x):
"""Compute pdf at a fixed point on the support.
Parameters
----------
x : float, shape (,)
Point on the support of the distribution
"""
return lambda point... | [
"def inner_product_derivative_matrix(self, base_point=None):\n return gs.autodiff.jacobian_vec(self.metric_matrix)(base_point)",
"def inner_product_derivative_matrix(self, base_point):\n\n def pdf(x):\n \"\"\"Compute pdf at a fixed point on the support.\n\n Parameters\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the cost function given a set of features / values, and the values for our thetas. | def compute_cost(features, values, theta):
# your code here
error = (values - features.dot(theta))
cost = error.dot(error)
return cost | [
"def compute_cost(features, values, theta):\n m = len(values)\n sum_of_square_errors = numpy.square(numpy.dot(features, theta) - values).sum()\n cost = sum_of_square_errors / (2*m)\n\n return cost",
"def calculate_cost_function(self, test_set, theta_list, regularizar=True):\n n = len(test_set.i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate yj = rj + gamma argmaxQ or yj = rj (terminating state) This is the target value used to train the neural network and it uses the target network to make predictions | def get_target(self, batch):
# initialise array to store yj values
target = np.zeros((len(batch[0]), self.num_actions))
# loop over samples in the minibatch
for j in range(len(batch[0])):
a0_i = self.action_str2idx(batch[1][j])
r0 = batch[2][j]
done ... | [
"def calc_target_q(self, **kwargs):\n feed_dict = {\n self.obs_input: kwargs['obs'],\n self.feat_input: kwargs['feature']\n }\n\n \n t_q, e_q = self.sess.run([self.t_q, self.e_q], feed_dict=feed_dict)\n act_idx = np.argmax(e_q, axis=1)\n q_values = t_q... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Small function to build the correct argtypes for the LibXC computers | def _build_comute_argtype(num_nd, num_nd_write):
ret = [_xc_func_p, ctypes.c_size_t]
ret += [_ndptr] * num_nd
ret += [_ndptr_w] * num_nd_write
return tuple(ret) | [
"def _cast_types(args):\n\targs.x_val = None if args.x_val == 'None' else int(args.x_val)\n\targs.test_size = float(args.test_size)\n\targs.alpha = float(args.alpha)\n\targs.fit_prior = (args.fit_prior in ['True', \"True\", 'true', \"true\"])\n\n\t# class_prior - array like type (problem to convert)\n\tif args.clas... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the LibXCFunctional family. | def get_family(self):
return self._family | [
"def device_family(self):\n return self._dll.JLINKARM_GetDeviceFamily()",
"def get_device_family(self, strict = False):\r\n\t\tc = self.get_device_category(self.category_device_family, strict)\r\n\t\tif c == None:\r\n\t\t\treturn None\r\n\t\treturn c.get_value()",
"def read_device_family(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the VV10 (b, C) coefficients | def get_vv10_coef(self):
if self._nlc_b is False:
raise ValueError("get_vv10_coeff can only be called on -V functionals.")
return (self._nlc_b, self._nlc_C) | [
"def coefficients(self):\n\t return self.coef_['x']",
"def coefficients(self):\r\n return self.coef_['x']",
"def coefficients(self) :\n raise NotImplementedError",
"def b_coefficients(x1,x2,x3,y1,y2,y3,CCoefficients,DCoefficients):\n\tBCoefficients = np.array([\t((y2-y1)/(x2-x1)-CCoefficients... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the names of all external parameters | def get_ext_param_names(self):
num_param = core.xc_func_info_get_n_ext_params(self.xc_func_info)
ret = []
for p in range(num_param):
tmp = core.xc_func_info_get_ext_params_name(self.xc_func_info, p)
ret.append(tmp.decode("UTF-8"))
return ret | [
"def param_names(self) -> List[str]:",
"def _getAllParamNames(self):\r\n names=copy.deepcopy(self._paramNamesSoFar)\r\n #get names (or identifiers) for all contained loops\r\n for thisLoop in self.loops:\r\n theseNames, vals = self._getLoopInfo(thisLoop)\r\n for name in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the descriptions of all external parameters | def get_ext_param_descriptions(self):
num_param = core.xc_func_info_get_n_ext_params(self.xc_func_info)
ret = []
for p in range(num_param):
tmp = core.xc_func_info_get_ext_params_description(self.xc_func_info, p)
ret.append(tmp.decode("UTF-8"))
return ret | [
"def get_resource_params():\n return Parameter.list()",
"def print_params():\n\n help_out = convert_phil_to_text(master_phil, att_level=1)\n txt_out = convert_phil_to_text(master_phil)\n\n return help_out, txt_out",
"def show_parameters(self):\n print(self.mk_summary())",
"def get_param... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the default values of all external parameters. | def get_ext_param_default_values(self):
num_param = core.xc_func_info_get_n_ext_params(self.xc_func_info)
ret = []
for p in range(num_param):
tmp = core.xc_func_info_get_ext_params_default_value(self.xc_func_info, p)
ret.append(tmp)
return ret | [
"def parameters_default(cls):\n return cls._Parameters.__new__.__defaults__",
"def initDefaults(self):\n return _libsbml.Parameter_initDefaults(self)",
"def get_default_values(self, entity, params):\n return entity.default_values",
"def get_default_values(self, *args):\n def _getde... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the density threshold below which the functional will not be evaluated. | def set_dens_threshold(self, dens_threshold):
if dens_threshold < 0:
raise ValueError("The density threshold cannot be smaller than 0.")
core.xc_func_set_dens_threshold(self.xc_func, ctypes.c_double(dens_threshold)) | [
"def update_threshold(self, threshold):\n self.mf.set_threshold(self.cm.estimate)",
"def setThreshold(self, threshold): # real signature unknown; restored from __doc__\n pass",
"def setDropThreshold(self, dropThreshold): # real signature unknown; restored from __doc__\n pass",
"def clear_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the number of columns and rows required to divide an image into ``n`` parts. Return a tuple of integers in the format (num_columns, num_rows) | def calc_columns_rows(n):
num_columns = int(ceil(sqrt(n)))
num_rows = int(ceil(n / float(num_columns)))
return (num_columns, num_rows) | [
"def compute_nrows_ncolumns(nplots):\n n_rows = int(np.sqrt(nplots)) + (np.sqrt(nplots) != int(np.sqrt(nplots))) * 1\n n_columns = int(nplots / n_rows) + (nplots / n_rows != int(nplots / n_rows)) * 1\n return n_rows, n_columns",
"def get_fig_dimension(n_subplots):\n if int(np.sqrt(n_subplots) + 0.5) *... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate combined size of tiles. | def get_combined_size(tiles):
# TODO: Refactor calculating layout to avoid repetition.
columns, rows = calc_columns_rows(len(tiles))
tile_size = tiles[0].image.size
return (tile_size[0] * columns, tile_size[1] * rows) | [
"def tile_size_2d(self):\n return 32.0, 32.0",
"def poss_tile_sizes(self):\n\n path_raw = self.raw_path\n\n for img in os.listdir(path_raw + \"/image\"):\n read_img = cv2.imread(path_raw + \"/image/\" + img, -1)\n y,x = read_img.shape\n\n break\n\n size... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
``tiles`` Tuple of ``Image`` instances. ``width`` Optional, width of combined image. ``height`` Optional, height of combined image. ``Image`` instance. | def join(tiles, width=0, height=0):
# Don't calculate size if width and height are provided
# this allows an application that knows what the
# combined size should be to construct an image when
# pieces are missing.
if width > 0 and height > 0:
im = Image.new("RGBA", (width, height), None)
... | [
"def combine_images(images: list) -> Image:\n img_width = images[0][0].width\n img_height = images[0][0].height\n new_size = (img_width * len(images[0]), img_height * len(images))\n new_image = Image.new('RGB', new_size)\n\n # Add all the images from the grid to the new, blank image\n for rowindex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Determine column and row position for filename. | def get_image_column_row(filename):
row, column = os.path.splitext(filename)[0][-5:].split("_")
return (int(column) - 1, int(row) - 1) | [
"def position(file_, pattern):\n pattern = pattern[1:-1]\n pattern = pattern.replace('(', '\\(')\n pattern = pattern.replace(')', '\\)')\n file_obj = open(file_, 'rU')\n for line_number, line in enumerate(file_obj):\n m = re.search(pattern, line)\n if m is not None:\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Open all images in a directory. Return tuple of Tile instances. | def open_images_in(directory):
files = [
filename
for filename in os.listdir(directory)
if "_" in filename and not filename.startswith("joined")
]
tiles = []
if len(files) > 0:
i = 0
for file in files:
pos = get_image_column_row(file)
im =... | [
"def get_images(directory=None): #import from mask.py\n \n if directory == None:\n directory = os.getcwd() # Use working directory if unspecified\n \n image_list = [] # Initialize aggregaotrs\n file_list = []\n \n directory_list = os.listdir(directory) # Get list of files\n for en... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If a resource has a title, it should be included in the string representation. | def test_str_with_title(media_resource_factory):
resource = media_resource_factory(title="Test Resource")
assert str(resource) == f"{resource.id} ({resource.title})" | [
"def get_resource_title(self, context):\n resource = context.resource\n if resource is None:\n return ''\n if resource['Title']:\n return resource['Title'].value\n else:\n return 'Resource: %s' % resource['LinkID'].value",
"def resource_link_title(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Media resources should be ordered by creation time, ascending. | def test_ordering(media_resource_factory):
m1 = media_resource_factory()
m2 = media_resource_factory()
assert list(models.MediaResource.objects.all()) == [m1, m2] | [
"def get_recent_media(self):\n medialist = get(self.token,\n '/users/{}/media/recent'.format(self.id))\n for data in medialist:\n media = Media(data)\n yield media",
"def sort(self):\n cfg = config.ConfigSingleton()\n\n working_dir = cfg.get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If a media resource has both an image and YouTube video ID specified then cleaning it should throw an error. | def test_clean_both_image_and_youtube_id(image):
resource = models.MediaResource(image=image, youtube_id="dQw4w9WgXcQ")
with pytest.raises(ValidationError):
resource.clean() | [
"def test_clean_no_image_or_youtube_id():\n resource = models.MediaResource()\n\n with pytest.raises(ValidationError):\n resource.clean()",
"def test_clean_only_youtube_id():\n resource = models.MediaResource(youtube_id=\"dQw4w9WgXcQ\")\n\n resource.clean()",
"def test_clean_only_image(image)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If a media resource does not encapsulate any media, cleaning it should throw an error. | def test_clean_no_image_or_youtube_id():
resource = models.MediaResource()
with pytest.raises(ValidationError):
resource.clean() | [
"def _handle_removed_media(self):\r\n if self.has_media():\r\n try:\r\n image = str(self.image)\r\n os.remove(image)\r\n except OSError:\r\n raise('Failure trying to remove image from filesystem.')\r\n return True",
"def test_clean_o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cleaning a media resource that only has an image should do nothing. | def test_clean_only_image(image):
resource = models.MediaResource(image=image)
resource.clean() | [
"def _handle_removed_media(self):\r\n if self.has_media():\r\n try:\r\n image = str(self.image)\r\n os.remove(image)\r\n except OSError:\r\n raise('Failure trying to remove image from filesystem.')\r\n return True",
"def test_clean_n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cleaning a media resource that only has a YouTube video ID should do nothing. | def test_clean_only_youtube_id():
resource = models.MediaResource(youtube_id="dQw4w9WgXcQ")
resource.clean() | [
"def test_clean_no_image_or_youtube_id():\n resource = models.MediaResource()\n\n with pytest.raises(ValidationError):\n resource.clean()",
"def test_clean_both_image_and_youtube_id(image):\n resource = models.MediaResource(image=image, youtube_id=\"dQw4w9WgXcQ\")\n\n with pytest.raises(Validat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If a media resource has an image, its type property should indicate it's an image. | def test_type_image(image):
resource = models.MediaResource(image=image)
assert resource.type == models.MediaResource.TYPE_IMAGE | [
"def is_image(media_node):\n return media_node['__typename'] == JinstaScrape.IMAGE_TYPENAME",
"def is_image(content_type):\n return content_type == \"image/jpeg\" or content_type == \"image/png\"",
"def isphoto(self):\n return self.media_type == Photos.PHAssetMediaTypeImage",
"def test_get_media_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If a media resource has a YouTube video ID, its type property should indicate it's a YouTube video. | def test_type_youtube():
resource = models.MediaResource(youtube_id="dQw4w9WgXcQ")
assert resource.type == models.MediaResource.TYPE_YOUTUBE | [
"def video_type(self):\n\t\treturn 'movie'",
"def play_youtube(self, media_id):\n pass",
"def isYouTube(self):\n if 'youtube' in self.link.split('.'):\n return True\n return None",
"def play_youtube(self, media_id):\n raise NotImplementedError()",
"def is_video(media_n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract text and other things from the raw_html for this document. | def extract(self, doc, raw_html):
super(KenyaTodayCrawler, self).extract(doc, raw_html)
soup = BeautifulSoup(raw_html)
# gather title
doc.title = soup.find(attrs={"property":"og:title"})['content']
#gather publish date
date = self.extract_plaintext(soup.select("main.co... | [
"def extract(self, doc, raw_html):\n super(ImzansiCrawler, self).extract(doc, raw_html)\n\n soup = BeautifulSoup(raw_html)\n\n # gather title\n doc.title = self.extract_plaintext(soup.select(\".content .post h1.post-title\"))\n\n #gather publish date\n date = self.extract_p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
phase5 requires a 4edge combo where none of the edges are in the zplane. phase4 will put a 4edge combo into that state. There are 12!/(4!8!) or 495 different 4edge combinations. Try them all and see which one has the lowest phase4 cost. | def find_first_four_edges_to_pair(self):
original_state = self.state[:]
original_solution = self.solution[:]
original_solution_len = len(self.solution)
results = []
for wing_str_index, wing_str_combo in enumerate(itertools.combinations(wing_strs_all, 4)):
wing_str_co... | [
"def test_fk5_galactic():\n\n fk5 = FK5(ra=1*u.deg, dec=2*u.deg)\n\n direct = fk5.transform_to(Galactic)\n indirect = fk5.transform_to(FK4).transform_to(Galactic)\n\n assert direct.separation(indirect).degree < 1.e-10\n\n direct = fk5.transform_to(Galactic)\n indirect = fk5.transform_to(FK4NoETerm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
phase1 stages the centers on sides L and R phase2 stages the centers on sides F and B and put the LR centers in one of 495 states that can be solved without L L' R R'...this is prep work for phase 3 TODO this needs more work BLBFRUFRDDFBUULBRLBRRLDLDLFURFLUBUDRRRDDFDFBBLUFRUFFBBFBLLLDBDFBDBLFDUUFRFBLDUDDURFDRBBDFUUFUBF... | def group_centers_phase1_and_2(self) -> None:
self.rotate_U_to_U()
self.rotate_F_to_F()
if self.centers_staged():
return
original_state = self.state[:]
original_solution = self.solution[:]
tmp_solution_len = len(self.solution)
# find multiple phase1... | [
"def chain_corrections():\n \n #read the files\n sample_4m=read_sample(map_files('sample_4m'))\n empty_cell_4m=read_sample(map_files('empty_cell_4m'))\n empty_4m=read_sample(map_files('empty_4m'))\n transmission_sample_cell_4m=read_sample(map_files('trans_sample_4m'))\n transmission_empty_cell_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a column number into a column letter (3 > 'C') Right shift the column col_idx by 26 to find column letters in reverse order. These numbers are 1based, and can be converted to ASCII ordinals by adding 64. | def _get_column_letter(col_idx):
# these indicies corrospond to A -> ZZZ and include all allowed
# columns
if not 1 <= col_idx <= 18278:
raise ValueError("Invalid column index {0}".format(col_idx))
letters = []
while col_idx > 0:
col_idx, remainder = divmod(col_idx, 26)
# che... | [
"def get_column_alphabetical_index_from_zero_indexed_num(col_idx: int) -> str:\n num_letters_alphabet = 26\n\n def get_letter_from_zero_indexed_idx(idx: int):\n ascii_start = 65\n return chr(ascii_start + idx)\n\n prefix_str = ''\n if col_idx < num_letters_alphabet:\n return get_let... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a head of LinkedList, delete from that linkedList index j and skip index i iterative | def skip_i_delete_j(head, i, j):
if i == 0:
return None
if head is None or j < 0 or i < 0:
return head
current = head
previous = None
while current:
# skip (i - 1) nodes
for _ in range(i - 1):
if current is None:
return head
... | [
"def deleteAtIndex(self, index):\n cur = self.head\n if cur == None:\n return\n elif index == 0:\n self.head = cur.next\n\n cur, i = self.head, 1\n while cur and i != index:\n cur = cur.next\n i += 1\n if cur.next == None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform a context visibility test. Creates a (fake) image with the specified owner and is_public attributes, then creates a context with the given keyword arguments and expects exp_res as the result of an is_image_visible() call on the context. | def do_visible(self, exp_res, img_owner, img_public, **kwargs):
img = FakeImage(img_owner, img_public)
ctx = context.RequestContext(**kwargs)
self.assertEqual(ctx.is_image_visible(img), exp_res) | [
"def test_public_image_visibility(self, images_steps):\n images_steps.check_public_image_visible(config.HORIZON_TEST_IMAGE)",
"def test_image_privacy(self, glance_steps, images_steps,\n auth_steps):\n image = glance_steps.create_images(\n utils.get_file_path(conf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform a context sharability test. Creates a (fake) image with the specified owner and is_public attributes, then creates a context with the given keyword arguments and expects exp_res as the result of an is_image_sharable() call on the context. If membership is not None, its value will be passed in as the 'membership... | def do_sharable(self, exp_res, img_owner, membership=None, **kwargs):
img = FakeImage(img_owner, True)
ctx = context.RequestContext(**kwargs)
sharable_args = {}
if membership is not None:
sharable_args['membership'] = membership
self.assertEqual(ctx.is_image_sharab... | [
"def do_visible(self, exp_res, img_owner, img_public, **kwargs):\n\n img = FakeImage(img_owner, img_public)\n ctx = context.RequestContext(**kwargs)\n\n self.assertEqual(ctx.is_image_visible(img), exp_res)",
"def fake_willow_image(self, create, extracted, **kwargs): # pylint: disable=unused-... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that an empty context (with is_admin set to True) can access an owned image with is_public set to True. | def test_empty_public_owned(self):
self.do_visible(True, 'pattieblack', True, is_admin=True) | [
"def test_empty_private_owned(self):\n self.do_visible(True, 'pattieblack', False, is_admin=True)",
"def do_visible(self, exp_res, img_owner, img_public, **kwargs):\n\n img = FakeImage(img_owner, img_public)\n ctx = context.RequestContext(**kwargs)\n\n self.assertEqual(ctx.is_image_vis... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that an empty context (with is_admin set to True) can access an owned image with is_public set to False. | def test_empty_private_owned(self):
self.do_visible(True, 'pattieblack', False, is_admin=True) | [
"def test_empty_public_owned(self):\n self.do_visible(True, 'pattieblack', True, is_admin=True)",
"def do_visible(self, exp_res, img_owner, img_public, **kwargs):\n\n img = FakeImage(img_owner, img_public)\n ctx = context.RequestContext(**kwargs)\n\n self.assertEqual(ctx.is_image_visib... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that an authenticated context (with is_admin set to False) cannot share an image it does not own even if it is shared with it, but with can_share = False. | def test_auth_sharable_cannot_share(self):
self.do_sharable(False, 'pattieblack', FakeMembership(False),
tenant='froggy') | [
"def cant_share_photo(request, ttl=None,*args, **kwargs):\n\tif ttl:\n\t\ttry:\n\t\t\tttl = int(ttl)\n\t\texcept ValueError:\n\t\t\tttl = None\n\tphoto_id = request.session.get(\"personal_group_shared_photo_id\",None)\n\torigin = request.session.get(\"personal_group_shared_photo_origin\",None)\n\tphoto_url = reques... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
loads file FILTER, returns filter matrix | def load_filter():
if not os.path.isfile(FILTER):
print('no filter found, creating square grid')
return []
with open(FILTER, 'r') as ff:
reader = csv.reader(ff)
l = list(reader)
ar = numpy.asarray(l)
# ar = numpy.transpose(ar, (0, 1))
# ar = numpy.flip(ar,... | [
"def load_filter_file(filter_file):\n df = pd.DataFrame()\n # if\n if filter_file:\n with open(filter_file,'rb') as csvfile:\n df = pd.read_csv(csvfile)\n return df",
"def load_filter(self, dataset, args):\n attitude_filter_path = osp.join(args.root_dir, dataset, \"attitude.tx... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns boolean, whether xy is occupied in filter matrix | def filtered(filter, xy):
try:
x, y = xy
return bool(filter[x][y])
except IndexError:
return False | [
"def xy_occupied(xy, board):\n return True if board[xy[0]][xy[1]] else False",
"def in_map(self, x, y):\n return 0 <= x < self._width and 0 <= y < self._height",
"def __collides_w_used(self, x, y, wi, he):\n for j in range(y, y + he):\n for i in range(x, x + wi):\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write the matrix to a csv table | def write_out(matrix, filename):
with open(filename, 'w') as csvfile:
writer = csv.writer(csvfile)
for r in matrix:
writer.writerow(r)
print(filename + ' writen!') | [
"def write_matrix_into_csv(file_address, matrix):\n num_of_elems = len(matrix)\n with open(file_address, \"w\") as file:\n for i in range(num_of_elems):\n for j in range(num_of_elems):\n if j == num_of_elems - 1:\n file.write(str(round(matrix[i][j], 6)))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construct a DCEL from the output of matplotlib.delaunay.delaunay. | def from_delaunay_triangulation(cls, xl, yl, triangles, circumcentres):
def add_containing_face_to_dcel():
containing_face_edges = [edge for edge in dcel.edges if not edge.nxt]
edge = containing_face_edges.pop()
face = Face(outer_component=None, inner_components=[edge])
... | [
"def delaunay_triples( # pylint: disable=too-many-arguments,too-many-locals\n data=None,\n x=None,\n y=None,\n z=None,\n output_type=\"pandas\",\n outfile=None,\n projection=None,\n verbose=None,\n binary=None,\n nodata=None,\n find=None,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add an edge to DCEL if it doesn't already exists, otherwise return the existing edge. | def add_edge(self, edge):
try:
edge_idx = self.edges.index(edge)
return self.edges[edge_idx]
except Exception:
self.edges.append(edge)
return edge | [
"def add_edge(self, e):\n\n # Just add egde.\n self.Edges.append(e)\n\n return e",
"def add_edge(self, edge: e.Edge) -> None:\n if edge not in self.edges:\n self.edges.append(edge)\n self.num_edges = self.num_edges + 1",
"def add_edge(self, edge):\n chrom... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add vertex to DCEL if it doesn't already exists, otherwise return the existing vertex. | def add_vertex(self, vertex):
try:
vertex_idx = self.vertices.index(vertex)
# print "{} already in {}".format(vertex, self.vertices)
return self.vertices[vertex_idx]
except Exception:
self.vertices.append(vertex)
# print "adding {} to {}".forma... | [
"def add_vertex(self, key):\n\n if key in self.vert_dict:\n print(f'Vertex {key} already exists')\n return\n\n # create a new vertex\n new_vertex = Vertex(key)\n self.vert_dict[key] = new_vertex\n self.num_vertices += 1\n\n return new_vertex",
"def _... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a face to DCEL if it doesn't already exists, otherwise return the existing face. | def add_face(self, face):
try:
face_idx = self.faces.index(face)
return self.faces[face_idx]
except Exception:
self.faces.append(face)
return face | [
"def add_face(self, face):\n\n if face.uuid is None:\n face.uuid = self._generate_uuid()\n\n if face.uuid in self._faces:\n error_str = \"Trying to add an already existing face with uuid: \"\\\n + str(face.uuid)\n raise KeyError(error_str)\n\n sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a list of vertices that form the outer boundary of finite faces of the DCEL. | def get_outer_boundary_of_voronoi(self):
edge = [edge for edge in self.edges if not edge.nxt][0]
# next(obj for obj in objs if obj.val==5)
first_vertex = edge.origin
outer_boundary = []
while (not edge.get_destination() == first_vertex):
if(edge.get_destination().is_i... | [
"def boundary_vertices():\n\n from searchspace.geometry import Point\n\n boundary_vertices = list()\n boundary_vertices.append(Point(18.1, -37.1))\n boundary_vertices.append(Point(18.1, -37.0))\n boundary_vertices.append(Point(18.0, -37.0))\n boundary_vertices.append(Point(18.0, -37.1))\n\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the dual of the current DCEL. | def dual(self):
def set_twins():
for edge_idx in range(0, len(dual_dcel.edges), 2):
dual_dcel.edges[edge_idx].twin = dual_dcel.edges[edge_idx + 1]
dual_dcel.edges[edge_idx + 1].twin = dual_dcel.edges[edge_idx]
def set_next_and_previous():
for face... | [
"def dual(self):\n return self.getdual()",
"def get_dual(self, offset=-1):\n return self.primary_axis.get_dual(self.dual_level + offset)",
"def dual(self):\n return dual_array(self)",
"def get_dual(self, offset=-1):\n if offset == 0:\n return self\n dual = self.__... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Printfriendly representation of the DCEL object. | def __repr__(self):
return (
'<DCEL ('
'vertices:\n {obj.vertices},\n'
'edges:\n {obj.edges},\n'
'faces:\n {obj.faces}>'.format(obj=self)
) | [
"def toString(self):\n return PyVDF.formatData(self.__data)",
"def __repr__( self ) :\n\n s = \"\"\n for v in self.data : s = s + endl1dmathmisc.endl1d_repr_xFormat % v + \"\\n\"\n return s",
"def __repr__(self):\n values = ', '.join(f'{k}={v}' for k, v in self.variables.items())\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Store the camera intrinsics. We need this for the calibration matrices from the Tango | def new_camera_intrinsics_callback(self, new_camera_info):
self.camera_intrinsics = new_camera_info
self.k_mat = np.matrix(
np.array(self.camera_intrinsics.K).reshape((3, 3))
)
self.k_inv = self.k_mat.I | [
"def save_intrinsics(self, save_dir):\n if not osp.isfile(\n osp.join(save_dir, 'intrinsics', 'intrinsics.npy')):\n np.save(osp.join(\n save_dir, 'intrinsics', 'intrinsics'), self.camera_model.K)",
"def _extract_extrinsics(self, kwargs, cloud_idx) ->Tuple[torch.Tens... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add padding for unet of given depth | def _pad(x, depth=4):
divisor = np.power(2, depth)
remainder = x.shape[0] % divisor
# no padding because already of even shape
if remainder == 0:
return x
# add zero rows after 1D feature
elif len(x.shape) == 2:
return np.pad(x, [(0, divisor - remainder), (0, 0)], "constant")
... | [
"def padding_depth(self):\n\t\treturn self.paddings_shape_param('D')",
"def _print_padded(string, depth):\n padding = \" \" * depth if depth else \"\"\n print(f\"{padding}{string}\")",
"def zero_pad_features(features, depth):\n\n n = int(features.get_shape().dims[-1])\n extra_feature_count = depth ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns a normalized url to path relative from root | def relative_url(path, root):
try:
url = os.path.relpath(path, root)
except:
error('Unable to make a relative url:', url, root)
url = url.replace('\\', '/') if os.sep == '\\' else url
return urllib.parse.quote(url) | [
"def full_url(self, path):\n if path[0] == '/':\n path = path[1:]\n return urljoin(self.absolute_root, path)",
"def normalize_url(path: str, page: Page | None = None, base: str = '') -> str:\n path, relative_level = _get_norm_url(path)\n if relative_level == -1:\n return path... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate Post objects from markdown. Date must be present in each post and posts must be ordrered by date. | def parse_markdown(filename):
if not os.path.exists(filename):
error('File not found', filename)
posts = list()
with open(filename, encoding='utf-8') as f:
line = next(f)
if line.startswith('# '):
title = line[2:].strip()
record = []
next(f)
... | [
"def markdown_post(post):\n post['entry'] = markdown(post['entry'].replace(\"\\n\",\" \\n\"), output=\"html5\")\n return post",
"def parse_joint_markdown(md_str):\n list_posts = []\n # each element does not contain \\n at the end\n lines = md_str.split('\\n')\n # line index\n prev_end_sec_in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Purge root dir from irrelevant html files | def purge_htmlfiles(args, posts):
htmlist = list_of_htmlfiles(args, posts)
html_to_remove = list()
for fullname in glob.glob(os.path.join(args.root, '*.htm*')):
if fullname not in htmlist:
html_to_remove.append(fullname)
if len(html_to_remove) > args.thumbnails.threshold_htmlfiles:
... | [
"def clean(self) -> None:\n dist = self.root / \"dist\"\n shutil.rmtree(dist, ignore_errors=True)",
"def cleanup():\n assert root_dir.remove(False)\n assert not root_dir.exists()",
"def html_clean(options):\r\n remake_directories(options.sphinx.doctrees, options.html.outdir)\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Purge thumbnail dir from irrelevant thumbnails | def purge_thumbnails(args, thumbdir, posts, diary=False):
thumblist = list_of_thumbnails(posts, diary)
thumbs_to_remove = list()
for fullname in glob.glob(os.path.join(thumbdir, '*.jpg')):
if os.path.basename(fullname) not in thumblist:
thumbs_to_remove.append(fullname)
if len(thumb... | [
"def clear_thumbnails(self):",
"def delete_thumbs_tmp():\n all_nodes = nuke.allNodes(\"Read\")\n for read in all_nodes:\n file_path = read[\"file\"].value()\n last = os.path.basename(file_path)\n if last == \"Thumbs.db\" or last[-4:] == \".tmp\":\n nuke.delete(read)",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the list of full paths for pictures and movies in source directory plus subdirectories containing media | def list_of_medias_ext(args, sourcedir):
result = list()
listdir = sorted_listdir(os.listdir(sourcedir))
if '.nomedia' not in listdir:
for basename in listdir:
fullname = os.path.join(sourcedir, basename)
if os.path.isdir(fullname) and basename != '$RECYCLE.BIN' and contains_... | [
"def get_file_paths(source):\n print(\"Gathering files please wait....\")\n file_endings = [\"mp4\", \"avi\", \"mpg\", \"wmv\", \"mov\", \"mkv\"]\n files = [file for file in source.glob(\"**/*\")\n if file.is_file() and any([file.name.endswith(ending) for ending in file_endings])]\n return f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compose html with blogger image urls | def compose_blogger_html(args, title, posts, imgdata, online_videos):
for post in posts:
for media in post.medias:
if type(media) is PostImage:
if media.uri not in imgdata:
print('Image missing: ', media.uri)
else:
img_url, ... | [
"def doImg(bunch, text, env):\n if bunch.get(\"align\", None) is not None:\n align = \" align='%s'\" % bunch[\"align\"]\n else:\n align = \"\"\n if bunch.get(\"width\", None) is not None:\n width = \" width='%s'\" % bunch[\"width\"]\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Export blogger html to clipboard. If full, export complete html, otherwise export html extract ready to paste into blogger edit mode. | def prepare_for_blogger(args):
title, posts = parse_markdown(os.path.join(args.root, 'index.md'))
online_images, online_videos = online_images_url(args)
if args.check_images and check_images(args, posts, online_images) is False:
pass
html = compose_blogger_html(args, title, posts, online_image... | [
"def copy_content_of_cleandump_to_downloadedthread(self):\n \n shutil.copy(tm.CLEAN_DUMP_PATH, tm.ECLIPSE_DOWNLOADED_PAGE_FILE)\n \n print \"Dumped to {0}\".format( tm.ECLIPSE_DOWNLOADED_PAGE_FILE )",
"def pastebin():\r\n\r\n fdirpb = \"/media/preto/DESCARGAS/pastebins/\" # Directo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Made after reading config file. Check for ffmpeg in path. Create .thumbnails dir if necessary and create .nomedia in it. Copy photobox file to destination dir. Handle priority between command line and config file. | def setup_part2(args):
if args.update:
args.sourcedir = args.source.sourcedir
args.bydir = args.source.bydir
args.bydate = args.source.bydate
args.diary = args.source.diary
args.recursive = args.source.recursive
args.dates = args.source.dates
args.github_pages... | [
"def create_thumbnails(fsrc):\n job_update(JobStatus.RUNNING, 'Generating recording thumbnails.')\n THUMBNAIL_COMMAND = 'ffmpegthumbnailer'\n EXTENSION = 'png'\n task = MythTV.System(path=THUMBNAIL_COMMAND)\n task.append('-q9') # quality level 0-10\n task.append('-t10') # seek percentage or time... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the q'th percentile of the distribution given in the argument 'data'. Uses the 'precision' parameter to control the noise level. | def Quantile(data, q, precision=1.0):
N, bins = np.histogram(data, bins=precision*np.sqrt(len(data)))
norm_cumul = 1.0*N.cumsum() / len(data)
for i in range(0, len(norm_cumul)):
if norm_cumul[i] > q:
return bins[i] | [
"def Quartiles(data):\n q = np.percentile(data, [25, 50, 75])\n\n return q[0], q[1], q[2]",
"def test__quantile(self):\r\n # regular cases\r\n sample_data = array(range(25, 42))\r\n assert_almost_equal(_quantile(sample_data, 0.5), median(sample_data))\r\n\r\n # sorted data is ass... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Downloads a YouTube video by its unique id. | def youtube_download_by_id(id, title=None, output_dir='.', merge=True, info_only=False):
raw_video_info = get_content('http://www.youtube.com/get_video_info?video_id=%s' % id)
video_info = parse.parse_qs(raw_video_info)
if video_info['status'] == ['ok'] and ('use_cipher_signature' not in video_inf... | [
"def download(idd, path):\n print(f'[{script}]: Downloading YT video \"{idd}\"...') if verbosity >= 1 else None\n\n try:\n yt = pytube.YouTube(\"https://www.youtube.com/watch?v=\" + idd)\n stream = yt.streams.filter(progressive=True).first()\n stream.download(path, filename=idd)\n exce... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that user_data is a dict and that key is in there | def has_user_data(self, key):
return isinstance(self._user_data, dict) and key in self._user_data | [
"def check_for_dict(check):",
"def can_insert(data):\n return isinstance(data, dict)",
"def _is_key_value(data):\n if data is None:\n return False\n return all(x in data for x in ['key', 'value'])",
"def test_is_dict(input):\n return isinstance(input, dict)",
"def isDict(d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return key from user_data if it's a dict | def get_user_data(self, key, default=None):
if not isinstance(self._user_data, dict):
return default
return self._user_data.get(key) | [
"def key(data, key_name):\n return data.get(key_name)",
"def get(self, username):\n return self.keys[username].key",
"def _get_string(self, data, key):\n return data.get(key)",
"def __is_key_in_json(self, key=str, json_dict=json):\n if key in json_dict:\n # noinspection PyUnreso... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to test add furniture functionality. | def test_add_furniture(self):
add_furniture('invoice.csv', 'Elisa Miles', 'LR04', 'Leather Sofa', 25)
add_furniture('invoice.csv', 'Edward Data', 'KT78', 'Kitchen Table', 10)
add_furniture('invoice.csv', 'Alex Gonzales', 'BR02', 'Queen Mattress', 17)
# Generate list of rentals
... | [
"def test_add_data():\n add_furniture(\"invoice_file.csv\", \"Elisa Miles\", \"LR04\", \"Leather Sofa\", 25.00)\n add_furniture(\"invoice_file.csv\", \"Edward Data\", \"KT78\", \"Kitchen Table\", 10.00)\n add_furniture(\"invoice_file.csv\", \"Alex Gonzales\", \"BR02\", \"Queen Mattress\", 17.00)",
"def s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
runs an automatic check to see if any transcriptions need to be started or are already finished and need to be reuploded\n\n Needs dbConnection & an integer representing the max concurrent transcriptons that can be ran at a time\n\n This is a function that you dont want to parse and upload files from the 'transcripts' ... | def runAutoCheck(dbConnection, maxConcurrent):
# checks if any shows are pending.
fileContent = DatabaseInteract.checkPre(dbConnection)
if(len(fileContent) > 0 and Tools.numRunningProcesses() < maxConcurrent):
cursor = dbConnection.cursor()
cursor.execute("UPDATE transcri... | [
"def check_transcripts(request):\r\n transcripts_presence = {\r\n 'html5_local': [],\r\n 'html5_equal': False,\r\n 'is_youtube_mode': False,\r\n 'youtube_local': False,\r\n 'youtube_server': False,\r\n 'youtube_diff': True,\r\n 'current_item_subs': None,\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Waits for the running transcription processes to end (2 min intervals). \n Then deletes everything in the 'podcasts' folder, parses all transcripts, and updates the databases | def resetScript(dbConnection, maxConcurrent):
while (Tools.numRunningProcesses() != 0): # wait for the transcriptions to end. Pings every 2 mins
time.sleep(120)
emptyPodcastFolder = Tools.cleanupFolder("podcasts")
DatabaseInteract.refreshDatabase(dbConnection) | [
"def transcribe_proc():\n while True:\n # Get result of transcription\n transcribe_result = transcriber.transcribe_stream(\n audio_stream(), sample_rate, sample_width, channels\n )\n\n _LOGGER.debug(\"Transcription result: %s\", transcribe_result)\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This parses the content of nohup. The size of nohup is basically unlimited but each line has to be under 300000 characters(?). This then returns the following...\n\n index 0 a list of all the occurences of realTimeFactor\n index 1 a list of all the occurences of transcriptions\n index 2 a list of all the occurences of ... | def nohupTranscriptionContent(filePath):
try:
continu = True
fileContent = ""
f = open(filePath, 'r')
while (continu):
temp = f.readline(900000)
if(len(temp) == 0):
continu = False
else:
... | [
"def fileTranscriptionContent(filePath):\n try:\n continu = True\n f = open(filePath, 'r')\n fileContent = \"\"\n while (continu):\n temp = f.readline(300000)\n if(len(temp) == 0):\n continu = False\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This parses the content of the transcription file. The size of the file can basically be unlimited but each line has to be under 300000 characters(?). This then returns the following...\n\n index 0 url\n index 1 realTimeFactor\n index 2 transcription\n | def fileTranscriptionContent(filePath):
try:
continu = True
f = open(filePath, 'r')
fileContent = ""
while (continu):
temp = f.readline(300000)
if(len(temp) == 0):
continu = False
else:
... | [
"def nohupTranscriptionContent(filePath):\n try:\n continu = True\n fileContent = \"\"\n f = open(filePath, 'r')\n while (continu):\n temp = f.readline(900000)\n if(len(temp) == 0):\n continu = False\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
deletes all contents of the specified folder (but not the folder itself).\n returns true if successful. False if an error was thrown or the number of running processes is not = 0 | def cleanupFolder(folderName):
try:
if(Tools.numRunningProcesses() == 0):
process = subprocess.call('rm -r ./' + folderName + '/*', shell=True)
return True
else:
return False
except Exception as e:
Tools.writeException("... | [
"def del_folder(folder):\n if os.path.exists(folder):\n print 'Deleted: ' + folder\n shutil.rmtree(folder)\n else:\n print 'Not exist: ' + folder",
"def empty_trash():\n drive_service().files().emptyTrash().execute()\n\n return True",
"def directoryDeleteContent (\n \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets the number of runnning transcription processes | def numRunningProcesses():
try:
proc = subprocess.run("ps -Af|grep -i \"online2-wav-nnet3-latgen-faster\"", stdout=subprocess.PIPE, shell=True)
np = (len(str(proc.stdout).split("\\n")) - 3)
if(np == None):
np = 0
return np
except Exception ... | [
"def getRunningTaskCount():",
"def num_processes():\n return 1",
"def get_runs(self) -> int:",
"def getWaitingTaskCount():",
"def run_count(self) -> int:\n return self._run_count",
"def run_count(self):\n return self._run_count",
"def GetNumberOfResultsProcessed(self) -> int:\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Does everything you need to transcribe a podcast given the filename\n Download podcast, wait 40 seconds, change podcast to .wav, wait 10 seconds, remove the .mp3 file, run the transcription | def transcribeAll(service, url, fileName):
if(service == "omny.fm"):
url = url.replace(".mp3","") + ".mp3"
subprocess.Popen("wget -c -O ./podcasts/" + fileName + ".mp3 " + url + " && sleep 40 && ffmpeg -i ./podcasts/"
+ fileName + ".mp3 -acodec pcm_s16le -ac 1 -ar 8000 ./podcasts... | [
"def say_something(self, text, directory='/tmp/', in_background=True):\n print(\"[ICUB][ACAPELA] Downloading the mp3 file...\")\n\n tts_acapela = acapela.Acapela(self.acapela_account_login, self.acapela_application_login,\n self.acapela_application_password, self.a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
audiourl > url of the transcriptions mp3 is stored here (NOT NULL)\n PodcastName > THe name of the show (references podcast(name))\n Description > The provided summary of that days podcast\n Date > The date that podcast aired (parsed to mmddyyyy\n Title > The title of that specific podcast\n Duration > the running time... | def insertClip(dbConnection, audiourl, podcastName, description, parsedDate, title):
try:
cursor = dbConnection.cursor()
title = title.replace("'", "''")
cursor.execute("INSERT INTO transcriptions(audiourl, realtimefactor, podcastname, transcription, description, date, title,... | [
"def podcast_generate(date):\n c.execute('SELECT id, title, url, program, local_file, duration FROM article WHERE date = ?', (date, ))\n rows = c.fetchall()\n id, title, url, program, local_file, sduration = ([] for i in range(6))\n for row in rows:\n id.append(row[0])\n title.append(row[1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks the database for empty transcription entries, returns a list with \n\n index 0 audiourl\n index 1 id\n index 2 podcast name\n index 3 service of podcast | def checkPre(dbConnection):
cursor = dbConnection.cursor()
cursor.execute("SELECT audiourl, T.id, podcastName, source FROM transcriptions AS T JOIN podcasts as P ON P.name = T.podcastname WHERE COALESCE(T.transcription, '') = '' AND pending = FALSE LIMIT 1;")
entry = cursor.fetchone()
cu... | [
"def empty(cls) -> \"Transcription\":\n return Transcription(text=\"\", likelihood=0, transcribe_seconds=0, wav_seconds=0)",
"async def get_not_sent(self) -> List[TradeRecord]:\n\n cursor = await self.db_connection.execute(\n \"SELECT * from trade_records WHERE sent<? and confirmed=?\",\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given title, if the podcast is in the database already return true. False if the podcast does not exist in the database | def checkIfExists(dbconnection, title):
cursor = dbconnection.cursor()
output = ""
title = title.replace("'", "''")
try:
cursor.execute("SELECT * FROM transcriptions WHERE title = '" + title + "';")
dbconnection.commit()
output = cursor.fetchone()
... | [
"def check_if_entry_exists(title: str) -> bool:\n conn = sqlite3.connect('rss.db')\n c = conn.cursor()\n try:\n c.execute(\n \"\"\"select * from entries where title = ?\"\"\",\n (title,)\n )\n records = c.fetchall()\n return len(records) > 0\n except... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generate the CUSPARSE FFI definition | def generate_cffi_cdef(
cuda_include_path=cuda_include_path, cusparse_header=cusparse_header,
cffi_out_file=None):
with open(cusparse_header, 'r') as f:
cusparse_hdr = f.readlines()
# in some version cusparse_v2.h just points to cusparse.h, so read it
# instead
for line in cusp... | [
"def make_c_header(self):\n res = \\\n\"\"\"PyThreadState* ___madz_LANG_python_thread_state; //Holds Thread State for this interpreter\nPyObject *___madz_LANG_python_wrapper_module; //Hold Pointer to the _madz.py file representing this plugin\ntypedef struct{{\n{function_pointers}\n}}___madz_LANG_python_TYPE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set up the Opple light platform. | def setup_platform(
hass: HomeAssistant,
config: ConfigType,
add_entities: AddEntitiesCallback,
discovery_info: DiscoveryInfoType | None = None,
) -> None:
name = config[CONF_NAME]
host = config[CONF_HOST]
entity = OppleLight(name, host)
add_entities([entity])
_LOGGER.debug("Init l... | [
"def platform_start(self):\n self.platform.start()",
"def setup_platform(\n hass: HomeAssistant,\n config: ConfigType,\n add_entities: AddEntitiesCallback,\n discovery_info: DiscoveryInfoType | None = None,\n) -> None:\n lights = []\n for channel, device_config in config[CONF_DEVICES].ite... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |