query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
The 'org' part of the course_id. | def course_org(self):
return self.course_key.org | [
"def user_org_id(self) -> str:\n return self._user_org_id",
"def organization_id(self) -> str:\n return pulumi.get(self, \"organization_id\")",
"def org_urn(self):\n return f\"psc:org:{self.credentials.org_key}\"",
"def get_full_course(self):\n return \"/\".join((self.course_org, s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The 'num' (aka 'course') part of the course_id. | def course_num(self):
return self.course_key.course | [
"def get_id_course_by_id_number(self, id_number):\n s = \"SELECT id\" \\\n \" FROM {entete}course\" \\\n \" WHERE idnumber = %(id)s\" \\\n .format(entete=self.entete)\n self.mark.execute(s, params={'id': id_number})\n ligne = self.safe_fetchone()\n if lig... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The 'run' part of the course_id. | def course_run(self):
return self.course_key.run | [
"def run_id(self) -> str:\n return self._step_execution_context.run_id",
"def getRunId(self):\n return self.runid",
"def id(self):\n return self.run[\"runId\"]",
"def getRunId (self):\n return self.uuidrun",
"def run_id() -> int:\n return sg_covid_impact.config[\"flows\"][\"gl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Accessor for the CourseData instance we're configured to test with. | def course_data(self):
course_data_name = self._get_course_setting('course_data')
return getattr(course_data, course_data_name) | [
"def course(self):\n return self._course",
"def course(self):\n return self.section.course",
"def course(self):\n return self.lesson.course",
"def get_courses_metadata(self):\n return Metadata(**settings.METADATA['course_ids'])",
"def get_courses(self) -> Dict[str, Course]:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Accessor for a setting specific to the current course. | def _get_course_setting(self, setting):
return settings.data['courses'][self.course_id][setting] | [
"def get_setting_value(self, title, setting):\r\n return self.parser.get(title, setting)",
"def get_setting(self, setting):\n return self.do_rpc(\"get_setting\", key=key)",
"def find_setting(self):\n return str(self._sqt.stringSetting(AM.AsterModule.name, self.key))",
"def get_setting(set... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads subclasses of Particle. | def import_particles(particles=None):
this_dir = os.path.dirname(__file__)
particles_dir = os.path.join(this_dir, "particles")
from_list = ["particle"]
if particles is not None:
from_list.extend(particles)
else:
for root, dirs, files in os.walk(particles_dir):
for file_ ... | [
"def childs(cls, forceLoad: bool = True) -> list:\n if forceLoad:\n ModuleLoader.loadModules(cls.__module__)\n\n return type.__subclasses__(cls)",
"def __init__(self, particles):\n self.particles = particles",
"def load(self):\n for name, item in itertools.chain(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new note | def create_a_note(self, data):
return self.client._post("/notes", json=data) | [
"def CreateNote(self):",
"def create_note(self, owner, title, text, note_type, important):\r\n note = self.create(owner=owner, title=title, text=text, note_type=note_type, important=important)\r\n return note",
"def create_note():\n curtime = datetime.now().strftime(\"%Y-%m-%d %H%M%S\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve an existing note | def retrieve_a_note(self, note_id):
return self.client._get("/notes/{}".format(note_id)) | [
"def get_note(self, note_id: int) -> note.Note:\n self.conn = sqlite3.connect(self.db_name)\n cursor = self.conn.cursor()\n cursor.execute(f\"SELECT * FROM {self.table_name} WHERE id = {note_id}\")\n tmp = cursor.fetchone()\n self.conn.commit()\n self.conn.close()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert that resolution is calculated correctly when using the xarray rasterio backend. | def test_calc_res():
with xr.open_rasterio(TEST_RASTER_PATH) as src:
xr_res = ds.utils.calc_res(src)
with rasterio.open(TEST_RASTER_PATH) as src:
rio_res = src.res
assert np.allclose(xr_res, rio_res) | [
"def test_resolution_set_03():\n with Image(filename='rose:', resolution=(100, 100)) as img:\n assert img.resolution == (100, 100)",
"def test_spatialresolutions_get(self):\n pass",
"def test_resolution_set_02(fx_asset):\n with Image(filename=str(fx_asset.joinpath('mona-lisa.jpg'))) as img:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert that bounding boxes are calculated correctly when using the xarray rasterio backend. | def test_calc_bbox():
with xr.open_rasterio(TEST_RASTER_PATH) as src:
xr_res = ds.utils.calc_res(src)
xr_bounds = ds.utils.calc_bbox(src.x.values, src.y.values, xr_res)
with rasterio.open(TEST_RASTER_PATH) as src:
rio_bounds = src.bounds
assert np.allclose(xr_bounds, rio_bounds, atol... | [
"def test_get_bounding_box(self):\n\n # Note there are two possible correct values of bbox depending on\n # the version of gdal:\n # http://trac.osgeo.org/gdal/wiki/rfc33_gtiff_pixelispoint\n\n # Get gdal version number\n x = gdal.VersionInfo('').replace('dev', '').split()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert raster with ascending x and ycoordinates and a partial canvas range is aggregated correctly. | def test_raster_both_ascending_partial_range():
xs = np.arange(10)
ys = np.arange(5)
arr = xs*ys[np.newaxis].T
xarr = xr.DataArray(arr, coords={'X': xs, 'Y': ys}, dims=['Y', 'X'])
cvs = ds.Canvas(7, 3, x_range=(.5, 7.5), y_range=(.5, 3.5))
agg = cvs.raster(xarr)
assert np.allclose(agg.data,... | [
"def test_raster_x_ascending_y_descending():\n xs = np.arange(10)\n ys = np.arange(5)[::-1]\n arr = xs*ys[np.newaxis].T\n xarr = xr.DataArray(arr, coords={'X': xs, 'Y': ys}, dims=['Y', 'X'])\n cvs = ds.Canvas(10, 5, x_range=(-.5, 9.5), y_range=(-.5, 4.5))\n agg = cvs.raster(xarr)\n\n assert np.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert raster with ascending x and descending ycoordinates is aggregated correctly. | def test_raster_x_ascending_y_descending():
xs = np.arange(10)
ys = np.arange(5)[::-1]
arr = xs*ys[np.newaxis].T
xarr = xr.DataArray(arr, coords={'X': xs, 'Y': ys}, dims=['Y', 'X'])
cvs = ds.Canvas(10, 5, x_range=(-.5, 9.5), y_range=(-.5, 4.5))
agg = cvs.raster(xarr)
assert np.allclose(agg.... | [
"def test_raster_x_descending_y_ascending():\n xs = np.arange(10)[::-1]\n ys = np.arange(5)\n arr = xs*ys[np.newaxis].T\n xarr = xr.DataArray(arr, coords={'X': xs, 'Y': ys}, dims=['Y', 'X'])\n cvs = ds.Canvas(10, 5, x_range=(-.5, 9.5), y_range=(-.5, 4.5))\n agg = cvs.raster(xarr)\n\n assert np.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert raster with descending x and ascending ycoordinates is aggregated correctly. | def test_raster_x_descending_y_ascending():
xs = np.arange(10)[::-1]
ys = np.arange(5)
arr = xs*ys[np.newaxis].T
xarr = xr.DataArray(arr, coords={'X': xs, 'Y': ys}, dims=['Y', 'X'])
cvs = ds.Canvas(10, 5, x_range=(-.5, 9.5), y_range=(-.5, 4.5))
agg = cvs.raster(xarr)
assert np.allclose(agg.... | [
"def test_raster_x_ascending_y_descending():\n xs = np.arange(10)\n ys = np.arange(5)[::-1]\n arr = xs*ys[np.newaxis].T\n xarr = xr.DataArray(arr, coords={'X': xs, 'Y': ys}, dims=['Y', 'X'])\n cvs = ds.Canvas(10, 5, x_range=(-.5, 9.5), y_range=(-.5, 4.5))\n agg = cvs.raster(xarr)\n\n assert np.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assert that an error is raised when incorrect upsample and/or downsample methods are provided to cvs.raster(). | def test_resample_methods():
with xr.open_rasterio(TEST_RASTER_PATH) as src:
try:
cvs.raster(src, upsample_method='santaclaus', downsample_method='toothfairy')
except ValueError:
pass
else:
assert False
try:
cvs.raster(src, upsample_me... | [
"def test_rasterize_exception_raised(self, error_msg, *shapes):\n self.assert_exception_is_raised(_proxy_rasterize, error_msg, shapes)",
"def test_grdfilter_fails():\n with pytest.raises(GMTInvalidInput):\n grdfilter(np.arange(10).reshape((5, 2)))",
"def test_distort_error():\n with Image(filena... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate all formats and versions of the Continuous Performance Trending and Analysis. | def generate_cpta(spec, data):
logging.info("Generating the Continuous Performance Trending and Analysis "
"...")
ret_code = _generate_all_charts(spec, data)
cmd = HTML_BUILDER.format(
date=datetime.utcnow().strftime('%Y-%m-%d %H:%M UTC'),
working_dir=spec.environment["pa... | [
"def main():\n reportSample = CompatibilityReportSample()\n reportSample.run()",
"def main():\n # process command line args\n try:\n pa = ProcessArgs()\n except ProcessArgsError, e:\n sys.stderr.writelines( str(e) )\n return\n \n if pa.genNewSw:\n __deleteOldOutp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate all charts specified in the specification file. | def _generate_all_charts(spec, input_data):
def _generate_chart(_, data_q, graph):
"""Generates the chart.
"""
logs = list()
logging.info(" Generating the chart '{0}' ...".
format(graph.get("title", "")))
logs.append(("INFO", " Generating the chart '... | [
"def render(self, chart):\n chart.create_visualization_files(self.__outputpath)",
"def create_figures():\n for fname in glob.glob('fig-*.py'):\n subprocess.check_call(['python', './' + fname])",
"def melanieSimsetGenerateCharts():\n # in/out directories\n # fileDir = '/Users/ivan/Document... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compare three elements in comp_els according to specific implementation in inheriter's method. | def compare(self, comp_els):
pass | [
"def _ComponentCompare(comp_cls, values, op_for_values):\n def _IsMatch(value):\n return any(\n [value.Matches(name) for name in context.bom.components[comp_cls]])\n\n context = GetContext()\n\n # Always treat as comparing failed if the specified component class is not\n # recorded in the BOM object.\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
source_svc is a string vdisk is a dictionary for a vdisk | def remove_vdisk_from_svc(svc, vdisk):
svc_ssh = openSSH(svc, getpass.getuser())
## First we need to unmap from the host
print "Removing the mapping between %s on %s..." % (vdisk["name"],
vdisk["hostlist"][0])
command = "rmvdiskhostmap -host %... | [
"def update_dvs(dvs_dict, dvs, service_instance=None):\n # Remove ignored properties\n log.trace(\"Updating dvs '{}' with dict = {}\".format(dvs, dvs_dict))\n for prop in [\"product_info\", \"capability\", \"uplink_names\", \"name\"]:\n if prop in dvs_dict:\n del dvs_dict[prop]\n proxy... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the CRC24 used by OpenPGP Message Format | def opgp_crc24(data: bytes) -> int:
crc = 0xB704CE
for byte in data:
crc ^= byte << 16
for _ in range(8):
crc <<= 1
if (crc & 0x1000000) != 0:
crc ^= 0x1864CFB
assert 0 <= crc <= 0xFFFFFF
return crc | [
"def opgp_crc24_b64(data: bytes) -> str:\n crc = opgp_crc24(data)\n return \"=\" + base64.b64encode(crc.to_bytes(3, \"big\")).decode(\"ascii\")",
"def crcsender(data, key):\n # Define Sub-Functions\n def xor(a, b):\n # initialize result\n result = []\n\n # Traverse all bits, if bi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the CRC24 used by OpenPGP Message Format, encoded in base64 | def opgp_crc24_b64(data: bytes) -> str:
crc = opgp_crc24(data)
return "=" + base64.b64encode(crc.to_bytes(3, "big")).decode("ascii") | [
"def opgp_crc24(data: bytes) -> int:\n crc = 0xB704CE\n for byte in data:\n crc ^= byte << 16\n for _ in range(8):\n crc <<= 1\n if (crc & 0x1000000) != 0:\n crc ^= 0x1864CFB\n assert 0 <= crc <= 0xFFFFFF\n return crc",
"def crcsender(data, key):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encode some data using the zbase32 encoding This encoding is specified for ZRTP protocol in | def zbase32_encode(data: bytes) -> str:
result = ""
for idx in range(0, len(data), 5):
result += ZBASE32_ALPHABET[(data[idx] & 0xF8) >> 3]
if idx + 1 == len(data):
result += ZBASE32_ALPHABET[(data[idx] & 0x07) << 2]
break
result += ZBASE32_ALPHABET[((data[idx] & 0... | [
"def bech32_encode(hrp, data):\n combined = data + bech32_create_checksum(hrp, data)\n return hrp + '1' + ''.join([CHARSET[d] for d in combined])",
"def encoder(data):\n strpackage = '2020' + '%002x' % len(data) + '19'\n for elem in data:\n strpackage = strpackage + '%002x' % int(elem)\n\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify that the algorithm computing WKD URLs work | def self_check() -> None:
assert len(ZBASE32_ALPHABET) == 32
# Test vector from https://github.com/matusf/z-base-32/blob/0.1.2/src/lib.rs
assert zbase32_encode(b"asdasd") == "cf3seamuco"
assert zbase32_decode("cf3seamuco") == b"asdasd"
# Test vector from https://www.uriports.com/blog/setting-up-op... | [
"def test_hash_url(self):\r\n url = u'http://google.com'\r\n hashed = generate_hash(url)\r\n self.assertEqual('aa2239c17609b2', hashed)",
"def test(self):\n\n string = \"abcdefghijklmnopqrstuvwxyz\"\n check_string = \"\"\"%61%62%63%64%65%66%67%68%69%6A%6B%6C%6D%6E%6F%70%71%72%73... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the identifier of a key, using GnuPG | def get_pgp_key_id(raw_key: bytes) -> str:
# Flush stdout and stderr to prevent interleaving messages from a subprocess
sys.stdout.flush()
sys.stderr.flush()
with tempfile.TemporaryDirectory(prefix="gnupghome") as tmpdir:
# Create an empty public keyring to avoid a GnuPG message
with (Pa... | [
"def identifier(self):\n listing = execute(' '.join([self.gpg_command, '--list-keys', '--with-colons']), capture=True)\n parsed_listing = [line.split(':') for line in listing.splitlines()]\n # Look for an 'fpr:*' line with a key fingerprint.\n for fields in parsed_listing:\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fits a model according to the given test_ids and data. | def fit(model, data, test_ids, exp_name, train_ids=None):
if model.model_type == 'torch':
size = len(data[0])
else:
size = data[0].shape[0]
if train_ids == None:
train_ids = [i for i in range(size) if i not in test_ids]
scaler = pka_scaler(data[1][train_ids])
if... | [
"def fit(model, data, test_ids, exp_name, datasets):\n if model.model_type == 'torch':\n size = len(data[0])\n else:\n size = data[0].shape[0]\n \n train_ids = [i for i in range(size) if i not in test_ids]\n scaler = pka_scaler(data[1][train_ids])\n if model.data_type == 'descrip... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if the lock is currently held. The lock is held if the PID file for this lock exists. | def is_locked(self):
result = pidfile_exists(self.path)
return result | [
"def i_am_locking(self):\n result = False\n current_pid = os.getpid()\n pidfile_pid = self.read_pid()\n if current_pid == pidfile_pid:\n result = True\n return result",
"def HasLock(self):\r\n return self._lock is not None",
"def own_lock(self):\n lockinfo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test if the lock is held by the current process. Returns ``True`` if the current process ID matches the number stored in the PID file. | def i_am_locking(self):
result = False
current_pid = os.getpid()
pidfile_pid = self.read_pid()
if current_pid == pidfile_pid:
result = True
return result | [
"def is_locked(self):\n result = pidfile_exists(self.path)\n return result",
"def own_lock(self):\n lockinfo = self._get_lockinfo()\n return lockinfo == self.pid",
"def is_locked(self, dynamixel_id):\n byte_seq = self.read_data(dynamixel_id, pk.LOCK, 1)\n return byte_se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Acquire the lock. Creates the PID file for this lock, or raises an error if the lock was already held. | def acquire(self):
if pidfile_exists(self.path):
error = AlreadyLocked()
raise error
try:
write_pid_to_pidfile(self.path)
except OSError:
error = LockFailed()
raise error | [
"def acquire(self):\n if self._ctx is not None:\n return\n self._ctx = self.atomicfile.locked(blocking=False)\n try:\n self._ctx.__enter__() # pylint: disable=unnecessary-dunder-call\n except OSError:\n self._ctx = None\n try:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Release the lock. Removes the PID file to release the lock, or raises an error if the current process does not hold the lock. | def release(self):
if not self.is_locked():
error = NotLocked()
raise error
if not self.i_am_locking():
error = NotMyLock()
raise error
remove_existing_pidfile(self.path) | [
"def unlock(self):\n self.remove_pid_file()",
"def release(lockfile):\n\t# Must be called _only_ if the lockfile was successfully obtained\n\tos.unlink(lockfile)",
"def unlock(self, lockfd, Verbose=False):\n\n # Release the lockfile\n if lockfd != None:\n os.unlink(self.lockfile)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Break an existing lock. Removes the PID file if it already exists, otherwise does nothing. | def break_lock(self):
remove_existing_pidfile(self.path) | [
"def unlock(self):\n self.remove_pid_file()",
"def _break_foreign_lock(self):\n # If the foreign process did not crash and just takes a bit longer\n # than expected, this may pull the rug from under their feet by\n # removing the lock they think they're perfectly fine with. As\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if the named PID file exists on the filesystem. | def pidfile_exists(pidfile_path):
result = os.path.exists(pidfile_path)
return result | [
"def file_exist() -> bool:\n pass",
"def file_exists(filename):\n return os.path.exists(filename)",
"def is_process_running(pid):\n return os.path.exists(\"/proc/%s\" % pid)",
"def is_locked(self):\n result = pidfile_exists(self.path)\n return result",
"def is_file_exists(self):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get junction in front of ego vehicle by exploring route. | def get_junction_by_route(self, start_waypoint):
# get start waypoint
waypoint = start_waypoint
reached_junction = False
sampling_radius = 1.
while not reached_junction:
wp_choice = waypoint.next(sampling_radius)
waypoint = wp_choice[0]
if w... | [
"def get_junction(accident, roads):\n key = accident[field_names.road1], accident[field_names.road2]\n junction = roads.get(key, None)\n return junction.decode(content_encoding) if junction else None",
"def get_route(self, junction_center, route_option='left'):\n # junction\n junction = sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a route for the scenario. Route is determined by class attribute turning_flag. | def get_route(self,
spawn_location,
distance: float = 10.,
turning_flag=-1, # left -> -1, straight -> 0, right -> 1
resolution: float = 1.):
waypoint_route = []
transform_route = []
location_route = []
spawn_waypo... | [
"def generate_route(self, start_waypoint, turn_flag=-1):\n # we set a small gap between spawn point and route beginning waypoint\n self.spawn_waypoint = start_waypoint\n # plot route start waypoint\n draw_waypoint(self.world, self.spawn_waypoint, color=(magenta, magenta))\n\n dist... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construct from `allnlp.Archive`'s file. | def from_archive(
cls, archive_path: Pathlike, dataset_reader_to_load: str = VALIDATION
):
# Uses lazy import because allennlp is an extra requirements.
from allennlp.data import DatasetReader
from allennlp.models.archival import load_archive
archive = load_archive(str(archi... | [
"def from_archive(cls, file, uploader):\n try:\n tar = tarfile.open(mode=\"r:gz\", fileobj=file)\n changelog = Readme.from_archive(tar, name='CHANGELOG')\n readme = Readme.from_archive(tar)\n pubspec = Pubspec.from_archive(tar)\n name = pubspec.required(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Getting each extension of our files. | def get_file_extensions():
my_files_ext = []
for file in os.listdir(os.getcwd()):
if os.path.isfile(file):
file_info = os.path.splitext(file)
file_ext = file_info[1]
my_files_ext.append(file_ext)
return [file for file in my_files_ext] | [
"def _get_extensions(self):\n return [file.split('.')[-1] for file in self.files]",
"def getFilesAndExtensions():\n\n paths = os.walk(os.curdir)\n files_plus_ext = []\n print(\"Retrieving files and their extensions\")\n for p in paths:\n files = [\"{0}/{1}\".format(\n os.path.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks to see if the extensions of our current files are in the dictionary if so, it moves them to the according folder | def check_and_move_files(my_files, my_files_ext):
for key, value in file_types.items():
for filename, ext in zip(my_files, my_files_ext):
if ext in value:
# print(downloads_path + '\\' + filename)
folder_name = key
create_folders(folder_name)
... | [
"def move_files_with_extension(self, extension: str):\n\n while True:\n files_with_extension = self.collect_files_with_extensions(extension)\n print(files_with_extension)\n folders_containing = set(\n [\n os.path.basename(os.path.dirname(file... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verifies all movements are returned when calling endpoint without paramaters | def test_movements_no_params(api_client):
MovementFactory(date=datetime.date(2000, 2, 11))
MovementFactory(date=datetime.date(2010, 2, 18))
MovementFactory(date=datetime.date(2017, 1, 15))
MovementFactory(date=datetime.date(2017, 5, 24))
response = api_client.get(reverse("api:movements-list"))
... | [
"def test_trucks_api_empty_food(self):\n resp = self.app.get('/trucks?bounds=37.74552131083975,-122.45653323673707,37.74552131083975,-122.45653323673707')\n self.assertEqual(resp.status_code, 200)\n\n expected = '{ \"resp\": [] }'\n self.assertEqual(expected.split(), resp.data.split())",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verifies correct movements are returned when calling endpoint with date_from parameter | def test_movements_date_from(api_client):
MovementFactory(date=datetime.date(2017, 2, 10))
MovementFactory(date=datetime.date(2017, 2, 11))
response = api_client.get(
reverse("api:movements-list"), {"date_from": "2017-02-11"}
)
assert response.status_code == 200
assert len(response.da... | [
"def test_movements_date_from_date_to(api_client):\n\n MovementFactory(date=datetime.date(2017, 2, 9))\n MovementFactory(date=datetime.date(2017, 2, 10))\n MovementFactory(date=datetime.date(2017, 2, 11))\n MovementFactory(date=datetime.date(2017, 2, 12))\n\n response = api_client.get(\n rever... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verifies correct movements are returned when calling endpoint with date_to parameter | def test_movements_date_to(api_client):
MovementFactory(date=datetime.date(2017, 2, 10))
MovementFactory(date=datetime.date(2017, 2, 11))
response = api_client.get(reverse("api:movements-list"), {"date_to": "2017-02-10"})
assert response.status_code == 200
assert len(response.data) == 1
asser... | [
"def test_movements_date_from_date_to(api_client):\n\n MovementFactory(date=datetime.date(2017, 2, 9))\n MovementFactory(date=datetime.date(2017, 2, 10))\n MovementFactory(date=datetime.date(2017, 2, 11))\n MovementFactory(date=datetime.date(2017, 2, 12))\n\n response = api_client.get(\n rever... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verifies correct movements are returned when calling endpoint with date_from and date_to parameter | def test_movements_date_from_date_to(api_client):
MovementFactory(date=datetime.date(2017, 2, 9))
MovementFactory(date=datetime.date(2017, 2, 10))
MovementFactory(date=datetime.date(2017, 2, 11))
MovementFactory(date=datetime.date(2017, 2, 12))
response = api_client.get(
reverse("api:movem... | [
"def test_movements_date_from(api_client):\n\n MovementFactory(date=datetime.date(2017, 2, 10))\n MovementFactory(date=datetime.date(2017, 2, 11))\n\n response = api_client.get(\n reverse(\"api:movements-list\"), {\"date_from\": \"2017-02-11\"}\n )\n\n assert response.status_code == 200\n a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verifies correct movements are returned when calling endpoint with amount_from parameter | def test_movements_amount_from(api_client):
MovementFactory(amount=Money(-10.00, "EUR"))
MovementFactory(amount=Money(50.00, "EUR"))
response = api_client.get(reverse("api:movements-list"), {"amount_from": -7})
assert response.status_code == 200
assert len(response.data) == 1
assert response.... | [
"def test_movements_amount_from_amount_to(api_client):\n\n MovementFactory(amount=Money(-300.00, \"EUR\"))\n MovementFactory(amount=Money(-10.00, \"EUR\"))\n MovementFactory(amount=Money(50.00, \"EUR\"))\n MovementFactory(amount=Money(1200.00, \"EUR\"))\n\n response = api_client.get(\n reverse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verifies correct movements are returned when calling endpoint with amount_to parameter | def test_movements_amount_to(api_client):
MovementFactory(amount=Money(-10.00, "EUR"))
MovementFactory(amount=Money(50.00, "EUR"))
response = api_client.get(reverse("api:movements-list"), {"amount_to": -7})
assert response.status_code == 200
assert len(response.data) == 1
assert response.data... | [
"def test_movements_amount_from_amount_to(api_client):\n\n MovementFactory(amount=Money(-300.00, \"EUR\"))\n MovementFactory(amount=Money(-10.00, \"EUR\"))\n MovementFactory(amount=Money(50.00, \"EUR\"))\n MovementFactory(amount=Money(1200.00, \"EUR\"))\n\n response = api_client.get(\n reverse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verifies correct movements are returned when calling endpoint with amount_from and amount_to parameter | def test_movements_amount_from_amount_to(api_client):
MovementFactory(amount=Money(-300.00, "EUR"))
MovementFactory(amount=Money(-10.00, "EUR"))
MovementFactory(amount=Money(50.00, "EUR"))
MovementFactory(amount=Money(1200.00, "EUR"))
response = api_client.get(
reverse("api:movements-list"... | [
"def test_movements_amount_from(api_client):\n\n MovementFactory(amount=Money(-10.00, \"EUR\"))\n MovementFactory(amount=Money(50.00, \"EUR\"))\n\n response = api_client.get(reverse(\"api:movements-list\"), {\"amount_from\": -7})\n\n assert response.status_code == 200\n assert len(response.data) == 1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verifies correct movements are return when calling endpoint with search parameter | def test_movements_search(api_client):
MovementFactory(
description="Best Food Ever!", category="Lunch", sub_category="Lunch"
)
MovementFactory(description="Booze Monday", category="Food", sub_category="Beer")
MovementFactory(
description="Kindle book", category="E-Commerce", sub_catego... | [
"def test_act_is_searching(self):\n # setup\n self.strategy._is_searching = True\n\n # operation\n self.search_behaviour.act()\n\n # after\n self.assert_quantity_in_outbox(1)\n has_attributes, error_str = self.message_has_attributes(\n actual_message=self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if Raspberry PI. | def is_raspberry_pi(raise_on_errors=False):
try:
with io.open('/proc/cpuinfo', 'r') as cpuinfo:
found = False
for line in cpuinfo:
if line.startswith('Hardware'):
found = True
label, value = line.strip().split(':', 1)
... | [
"def os_is_pi():\n return \"raspberrypi\" in platform.uname()",
"def is_raspberry_pi(raise_on_errors=False):\n try:\n with io.open(\"/proc/cpuinfo\", \"r\") as cpuinfo:\n found = False\n for line in cpuinfo:\n if line.startswith(\"Hardware\"):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
compute shape that results when slicing a totshape array with slicetuple | def sliceshape(slicetuple, totshape):
res = []
for i,s in enumerate(slicetuple):
if isinstance(s,int):
#n = 1
pass
else:
i0,i1,istep = s.indices(totshape[i])
n = (i1-i0)//istep
res.append(n)
return res | [
"def slice_shape(slice_, shape):\n from coverage_model.basic_types import Span\n # If shape is an integer, tuplize it\n if isinstance(shape, int):\n shape = (shape,)\n\n fixed_slice = fix_slice(slice_, shape)\n\n dim_lengths = []\n\n for s,shape in zip(fixed_slice, shape):\n if isins... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
tm = tilemap('res_????/PP/PP_day.0000052704.%03d.001.data',(30,51,102),itile,'f4','r') tm = tilemap('res_????/PP/PP_day.0000052704.%03d.001.data',(30,51,102),ncs=510) tm = tilemap('res_%04d/PP/PP_day.0000052704.%03d.001.data',tshape=(30,51,102),ncs=510,dtype='>f4',mode='r') | def __init__(self, filepatt, tshape, itile=None, dtype='>f4', mode='r', offset=0, order=None, ncs=None, blankval=nan):
self.filepatt = filepatt
self.dtype = dtype
self.mode = mode
self.offset = offset
self.order = order
self.tshape = tuple(tshape)
self.tnx = tshap... | [
"def build_tiles(img,tilefile,tilesize,options=[]):\n\tlevels=ceil(log(max(img.get_xsize(),img.get_ysize())/tilesize)/log(2.0))\n\t\n\ttf=file(tilefile,\"w\")\n\t\n\ttile_dict={}\n\tpos=0\n\timg2=img.copy()\n\txs,ys=img2.get_xsize(),img2.get_ysize()\n\tfor l in range(int(levels)):\n\t\trmin=img2.get_attr(\"mean\")-... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
tm = tiledfile('res_????/PP/PP_day.0000052704.%03d.001.data',(30,51,102),itile,'f4','r') tm = tiledfile('res_????/PP/PP_day.0000052704.%03d.001.data',(30,51,102),ncs=510) tm = tiledfile('res_%04d/PP/PP_day.0000052704.%03d.001.data',tshape=(30,51,102),ncs=510,dtype='>f4',mode='r') | def __init__(self, filepatt, tshape, itile=None, dtype='>f4', ncs=None, blankval=nan):
self.filepatt = filepatt
self.dtype = dtype
self.tshape = tuple(tshape)
self.tnx = tshape[-1]
self.tny = tshape[-2]
self.tsize = prod(self.tshape)
self.glob = False
if '... | [
"def __init__(self, filepatt, tshape=None, itile=None, dtype='>f4', ncs=None, blankval=nan, its=None, cache=False,rot=None):\n self.filepatt = filepatt\n self.dtype = dtype\n if tshape is not None:\n self.tshape = tuple(tshape)\n else:\n metapatt = re.sub(r'\\.data$... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
tm = tiledfiles('res_%04d/PP/PP_day.%010d.%03d.001.data',(30,51,102),itile,'f4','r') tm = tiledfiles('res_????/PP/PP_day.%010d.%03d.001.data',(30,51,102),ncs=510,dtype='f4') | def __init__(self, filepatt, tshape=None, itile=None, dtype='>f4', ncs=None, blankval=nan, its=None, cache=False,rot=None):
self.filepatt = filepatt
self.dtype = dtype
if tshape is not None:
self.tshape = tuple(tshape)
else:
metapatt = re.sub(r'\.data$', '.meta', ... | [
"def __init__(self, filepatt, tshape, itile=None, dtype='>f4', ncs=None, blankval=nan):\n self.filepatt = filepatt\n self.dtype = dtype\n self.tshape = tuple(tshape)\n self.tnx = tshape[-1]\n self.tny = tshape[-2]\n self.tsize = prod(self.tshape)\n self.glob = False\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Outputs all the results of the jobs into a log file, including their errors and the total number of jobs that failed and passed | def print_result(job_managers: 'list[job_manager.JobManager]'):
info("Number of jobs run {}.".format(len(job_managers)))
failed_jobs = 0 # type: int
for job_item in job_managers:
if job_item.status.job_state != utils.JobState.COMPLETE:
failed_jobs += 1
warning(
... | [
"def finish(self):\n for msg, info in self.errors.iteritems():\n hosts = [ self.job_to_str_func(job) for job in info['jobs'] ]\n\n max_jobs_num = self.max_jobs_num\n if max_jobs_num < 0 or max_jobs_num > len(hosts):\n hosts_msg = ': %s' % ' '.join(hosts)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create/ Connect to the database and fetch the required data | def initialize_database():
db = Database(database_name)
i, m, u, p = db.fetch_needed_data()
return i, m, u, p | [
"def connect_db_and_load_data(cls):\n db.connect()\n db.create_tables([Product], safe=True)\n load_data(transform_data('./inventory.csv'))",
"def test_retrieve_database(self):\n pass",
"def setup_db(self):\n\n self.db_conn = sqlite3.connect(config.db_file)\n self.db_cur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turn the result returned from a thread into a dictionary | def from_thread_result_to_dictionary(returned_result):
keys = []
values = []
for returned_result_item in returned_result:
keys.append(returned_result_item[0])
values.append(returned_result_item[1])
dictionary = dict(zip(keys, values))
return dictionary | [
"def get_dict(self):\n thread = current_thread()\n return self.dicts[id(thread)][1]",
"def get_dict(self):\n\n return self._task_results",
"def convert_thread_to_dict(py8chan_thread):\n assert(type(py8chan_thread) is py8chan.Thread)# Expects py8chan.Thread object.\n\n files = []\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a tuple of machines numbers | def create_machines_tuple(value):
tuple_values = []
for j in range(1, value + 1):
tuple_values.append(j)
return tuple(tuple_values) | [
"def numreduct(vers):\n numvers = []\n for c in vers:\n try:\n numvers.append(int(c))\n except ValueError:\n break\n return tuple(numvers)",
"def GenDistinctId(self):\t\n \"\"\"4 bits to unique a machine \\\n\t5 bits for processes\"\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Center a Tkinter window | def center(window):
window.update_idletasks()
# Find the screen resolution
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
# Find new (x, y) coordinates
size = tuple(int(_) for _ in window.geometry().split('+')[0].split('x'))
x = screen_width/2 - 7 * s... | [
"def center(self):\n self.eval('tk::PlaceWindow %s center' % app.winfo_pathname(app.winfo_id()))",
"def center(window):\n window.update_idletasks()\n w = window.winfo_screenwidth()\n h = window.winfo_screenheight()\n size = tuple(int(_)\n for _ in window.geom... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Bring calculations records of a certain date and save to a file | def bring_records_to_file_using_threads():
username = username_entry.get()
password = password_entry.get()
day = int(day_entry.get())
month = int(month_entry.get())
year = int(year_entry.get())
today = datetime.date(year, month, day)
if username in users:
if password == users[usernam... | [
"def make_res_csv(self):\n results = self.format_results()\n self.fin_results.append(results)\n with open(\"Result_File_\" + self._file, 'w', newline='') as my_file:\n wr = csv.writer(my_file, quoting=csv.QUOTE_ALL)\n wr.writerow([min(self.dates), max(self.dates) - min(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a list of (action, filename) that have changed in comparison with `ref`. | def _git_diff_files(ref="master"):
result = []
command = ["git", "diff", "--name-status", "%s" % (ref)]
exit_code, output = _execute(command)
if exit_code != 0:
print("Failed to diff files.")
sys.exit(1)
for line in output.decode("utf-8").splitlines():
parts = line.split("\t... | [
"def get_items_changed(self, base_ref='HEAD'):\n command = ['diff-index', '--name-only',\n '--cached', base_ref]\n res = self.run(command)\n items = res.split('\\n') if res else []\n return items",
"def fileCmp (working, ref, compare_content=0, verbose=0):\n\tif verbo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run checker on all the sources using `options` and sending results to `reporter`. | def check_sources(options, reporter=None):
if reporter is None:
reporter = Reporter(Reporter.CONSOLE)
reporter.call_count = 0
if options.diff_branch:
# We ignore the passed sources, and get the files from the VCS.
sources = []
for change in _git_diff_files(ref=options.diff_b... | [
"def main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--tools\", action=\"extend\", nargs=\"+\", type=str, \n help='specify which tools to run ({})'.format(\", \".join(TOOLS)))\n args = parser.parse_args()\n\n if args.tools:\n for t in args.tools:\n if t not ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Answers the path of the PageBot test fonts. | def getTestFontsPath():
resourcesPath = getResourcesPath()
return '%s/%s' % (resourcesPath, 'testfonts') | [
"def getRootFontPath():\n return getRootPath() + '/Fonts'",
"def getDemoFontPath():\n\ttestdata = os.path.join(os.path.dirname(__file__), \"testdata\")\n\treturn os.path.join(testdata, \"DemoFont.ufo\")",
"def getDemoFontGlyphSetPath():\n\treturn os.path.join(getDemoFontPath(), \"glyphs\")",
"def get_fonts... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Answers the path that is source of the given font name. If the path is already a valid font path, then aswer it unchanged. Answer None if the font cannot be found. >>> from pagebot.fonttoolbox.objects.font import findFont >>> font = findFont('RobotoRegular') >>> path = getFontPathOfFont(font.path) Set as font path >>> ... | def getFontPathOfFont(font, default=None):
if hasattr(font, 'path'): # In case it is a Font instance, get its path.
font = font.path
if font is not None and not os.path.exists(font):
font = getFontPaths().get(font)
if font is None:
font = default or getDefaultFontPath()
return fo... | [
"def fontFilePath(self):\n font = getNSFontFromNameOrPath(self._font, self._fontSize, self._fontNumber)\n if font is not None:\n url = CoreText.CTFontDescriptorCopyAttribute(font.fontDescriptor(), CoreText.kCTFontURLAttribute)\n if url is not None:\n return url.pat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recursive helper function for getFontPaths. If the fileName already exists in the fontPaths, then ignore. | def _recursivelyCollectFontPaths(path, collectedFontPaths):
if os.path.exists(path):
if os.path.isdir(path):
for fileName in os.listdir(path):
dirPath = path + '/' + fileName
_recursivelyCollectFontPaths(dirPath, collectedFontPaths)
else:
fontN... | [
"def _recursivelyCollectFontPaths(path, fontPaths):\n for fileName in os.listdir(path):\n filePath = path + '/' + fileName\n if os.path.isdir(filePath):\n _recursivelyCollectFontPaths(filePath, fontPaths)\n else:\n extension = fileName.split('.')[-1].lower()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints all quadrants. Returns None | def print_board(self):
for i in range(0, self.quadrants_count, 2):
for row in range(3):
line = self.play_area[i].get_line(row) + " | " + self.play_area[i+1].get_line(row)
print(line)
if i < self.quadrants_count - 2:
print("----------------"... | [
"def print_all(cls):\n\t\tprint(\"Quads ===============================\")\n\t\tfor x in cls.quadruples:\n\t\t\tx.print()",
"def print_all(self):\n count = 0\n print(\"Quads ===============================\")\n #Traer lista de cuadruplos\n l = [x.to_list(self.next_free_quad) for x in self._quads]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Rotates selected quadrant in specific direction either left or right. Calls Quadrant method. | def rotate_quadrant(self, quadrant, direction):
direction = Direction(direction)
self.play_area[quadrant].rotate(direction) | [
"def quadrant(self) -> Quadrant:\n\n if self.x > 0:\n if self.y > 0:\n return Quadrant.I\n if self.y < 0:\n return Quadrant.IV\n if self.x < 0:\n if self.y > 0:\n return Quadrant.II\n if self.y < 0:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates specific player positions on the whole play area. Values are based on which quadrant position is held. First quadrant might contain values from 1 to 9, next quadrant might contain values from 10 to 18 etc. | def player_choices(self, player):
player_choices = []
for i in range(self.quadrants_count):
quadrant_board = self.play_area[i].get_board()
for j in range(self.quadrant_positions_count):
if quadrant_board[j] == player:
position = j + 1 + i * 9
... | [
"def get_starting_positions_for_players(self, qty):\n positions = []\n for i in range(qty):\n x = random.choice(range(self.w))\n y = random.choice(range(self.h))\n while self.out_of_bounds(x, y) or (x,y) in positions:\n x = random.choice(range(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates all available moves, from all quadrants, which player can make. First quadrant might contain values from 1 to 9, next quadrant might contain values from 10 to 18 etc. Returns | def available_moves(self):
available_moves = []
for i in range(self.quadrants_count):
quadrant_positions = self.play_area[i].available_positions()
for p in quadrant_positions:
position = p + i * 9
for j in range(self.quadrants_count):
... | [
"def quadrant(board,n):\r\n quadrants = []\r\n for j in [0,1,6,7]:\r\n block = []\r\n for k in range(3):\r\n block.append(board[6*k+3*j:6*k+3*j+3])\r\n quad = []\r\n for thing in block:\r\n for t in thing:\r\n quad.append(t)\r\n quadrants... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that we can create an invalid bill, and validation will fail | def test_basic_invalid_bill():
b = toy_bill()
b.identifier = None
with pytest.raises(ValueError):
b.validate() | [
"def test_basic_invalid_bill():\n b = toy_bill()\n b.name = None\n with pytest.raises(ValueError):\n b.validate()",
"def test_create_bill(self):\n pass",
"def test_set_invalid_type_year_for_billing_data(self):\n try:\n self.client.connect()\n year = 'foo'\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make sure related bills work | def test_add_related_bill():
b = toy_bill()
b.add_related_bill(
identifier="HB 2020", legislative_session="2011A", relation_type="companion"
)
assert len(b.related_bills) == 1
assert b.related_bills[0] == {
"identifier": "HB 2020",
"legislative_session": "2011A",
"rel... | [
"def test_list_bills(self):\n pass",
"def test_add_related_bill():\n b = toy_bill()\n b.add_related_bill(name=\"HB 2020\", session=\"2011A\", chamber=\"upper\", relation=\"companion\")\n assert len(b.related_bills) == 1\n assert b.related_bills[0] == {'name': 'HB 2020', 'session': '2011A', 'cha... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that logging in as a new user creates a new docker service. | def test_creates_service(hub_service):
client = docker.from_env()
services_before_login = client.services.list()
# This request should create a new docker service to run the server for a-new-user
response = requests.post("http://127.0.0.1:8000/hub/login?next=", data={"username": "a-new-user", "passwor... | [
"def test_create_user(self):\n pass",
"def test_create_system_user(self):\n pass",
"def test_admin_containers():\n app = create_ctfd()\n with app.app_context():\n client = login_as_user(app, name=\"admin\", password=\"password\")\n r = client.get('/admin/containers')\n a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run the neural network as a subprocess. | def _run_neural_network(self):
program = ['mpiexec','-np',self._np,'python','./scripts/runClosedLoopNn.py',self._eesFreq,self._eesAmp,self._nnStructFile,self._species,self._totSimulationTime,self._perturbationParams]
self._neuralNetwork = subprocess.Popen(program, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stde... | [
"def run_nvml(args):\n proc = subprocess.Popen(args.command.split(\" \"), \n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT)\n pid = proc.pid\n proc = psutil.Process(pid)\n\n nvsmi = nvidia_smi.getInstance()\n sleep(8) # wait for training job... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run webots as a subprocess | def _run_webots(self):
if self._experiment == "bed":
program = ["/Applications/Webots7/webots","--stdout","../../webots/worlds/743_formento_bed.wbt"]
elif self._experiment == "treadmill":
program = ["/Applications/Webots7/webots","--stdout","../../webots/worlds/743_formento_tbws.wbt"]
elif self._experiment ... | [
"def setupWebots():\n os.putenv('WEBOTS_TEST_SUITE', 'TRUE')\n os.putenv('WEBOTS_EMPTY_PROJECT_PATH',\n os.environ['WEBOTS_HOME'] + os.sep + 'tests' + os.sep +\n defaultProjectPath)\n\n global webotsFullPath\n global webotsVersion\n global webotsSysInfo\n\n if sys.platfor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the data coming from the webots controller. | def _wbt_read_data(self):
reaData = True
wbtIncomingData = False
wbtData = ""
while reaData:
wbtIncomingMsg = self._webots.stdout.readline().rstrip("\n").split()
if "COMM_OUT" in wbtIncomingMsg: wbtIncomingData = True
elif "END" in wbtIncomingMsg: reaData = False
elif wbtIncomingData: wbtData += " ... | [
"def read_data(self):\n pass",
"def read_data(self):\n\t\t\n\t\tself.wii_init()\n\t\tsleep(0.01)\n\t\t# Para leer del Nunchuck primero se debe enviar un comando 0x00\n\t\t# y después leer 6 bytes de información\n\t\t#\n\t\t# La información recibida debe ser decodificada realizando\n\t\t# XOR con 0x17 y des... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Send webots' data to the neural network. | def _send_data_to_nn(self,wbtData):
self._neuralNetwork.stdin.write("COMM IN\n") # this shitty COMM IN is not really needed..to modify in closedloop.py
self._neuralNetwork.stdin.write(wbtData) | [
"def trainNet():",
"def _send_data(self, data):\n if not self._socket:\n # The user hasn't connected yet. Do that form them.\n self.connect()\n\n # Call the datapoint's method to convert it into a string that is\n # understood by Graphite\n datastring = data.get_s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the data coming form the neural network. | def _nn_read_data(self):
reaData = True
nnIncomingData = False
nnData = ""
while reaData and self._neuralNetwork.poll()==None:
nnIncomingMsg = self._neuralNetwork.stdout.readline().rstrip("\n").split()
if "COMM_OUT" in nnIncomingMsg: nnIncomingData = True
elif "END" in nnIncomingMsg: reaData = False
... | [
"def ReadTxtNeuralNet(file, inputDimension, inputCoordinates):\n\t\tprint \"Reading neural net from file: \" + file",
"def ReadBinNeuralNet(file, inputDimension, inputCoordinates):\n\t\tprint \"Reading neural net from file: \" + file",
"def read_data(self):\n pass",
"def load_neuraldata(filename):\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List all GoalProgress, or create a new GoalProgress. | def get(self, request, format = None):
goalProgress = GoalProgress.objects.all()
serializer = GoalProgressSerializer(goalProgress, many=True)
return Response(serializer.data) | [
"def progress_for(self, user):\n try:\n # Look for an existing progress record...\n p = Progress.objects.get(user=user, badge=self)\n except Progress.DoesNotExist:\n # If none found, create a new one but don't save it yet.\n p = Progress(user=user, badge=sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs a command 'cmd' within an ssh connection. Upon success returns a list of lines from the output of the command. cmd mandatory string representing the command to be run against the remote ssh session verbose optional will default to global setting, can be set per cmd() as well here timeout optional integer used to t... | def cmd(self, cmd, verbose=None, timeout=120, listformat=False):
if verbose is None:
verbose = self.verbose
cmd = str(cmd)
t = None #used for timer
start = time.time()
output = []
if verbose:
self.debug( "[" + self.userna... | [
"def call_ssh(cmd, host, user=None, timeout=None, cwd=None):\n if user:\n host = \"%s@%s\" % (user, host)\n full_cmd = ['ssh', host, '-oBatchMode=yes', '--']\n if cwd:\n full_cmd.append(\"cd %s;\" % cwd)\n full_cmd.extend(quote(i) for i in cmd)\n return check_output(full_cmd, timeout=ti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function mimics the bash command fs3cmd available in the fairusers_aws module on the FAIR cluster. Works on H2. Not tested on H1 this is a guess based on the definition in H2. | def fs3cmd(args):
os.environ["FAIR_CLUSTER_NAME"] = os.environ["FAIR_ENV_CLUSTER"].lower()
subprocess.check_call(["/public/apps/fairusers_aws/bin/fs3cmd"] + args) | [
"def format_volume_to_ext3(ssh_client, device=\"/dev/sda\"):\n cmds = [\n \"echo -e 'n\\np\\n1\\n\\n\\nw' | fdisk %s\" % device,\n \"mkfs.ext3 %s1\" % device,\n ]\n for c in cmds:\n ssh_client.execute(c)",
"def create_command_hadoop_2(mapper, reducer, command, command_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This allows an IR ARO to get their own details such as the electoral district they belong to and the polling districts under their control. | def get_my_details(self, request):
try:
user = request.user
staff = user.aro.staff
polling_districts = []
for pd in user.aro.polling_districts.all():
polling_districts.append(pd.polling_district)
polling_division = polling_districts[0... | [
"def getInfo():\n\tcity_list_url = 'https://airnow.gov/index.cfm?action=airnow.local_state&stateid=5'\n\taq_info_url = 'https://airnow.gov/index.cfm?action=airnow.local_city&mapcenter=0&cityid='\n\tcity_list = []\n\tcity_name_list = []\n\tgetCityList(city_list, city_name_list, city_list_url)\n\tinfo = []\n\tgetAllA... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a configuration dictionary return flags for the XST build if user flags are not specified take the default flags from site_scons/xst_default_flags.json | def get_xst_flags(config):
#print "Apply slave tags"
flags = {}
user_flags = {}
if "xst" in config.keys():
if "flags" in config["xst"].keys():
user_flags = config["xst"]["flags"]
fn = os.path.join(os.path.dirname(__file__), XST_DEFAULT_FLAG_FILE)
default_flags = json.load(op... | [
"def flags(self):\n\n config_header = self.toolchain.get_config_header()\n flags = {key + \"_flags\": copy.deepcopy(value) for key, value\n in self.toolchain.flags.items()}\n if config_header:\n config_header = relpath(config_header,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an xst directiroy in the build folder | def create_xst_dir(config):
#Create a output directory if it does not exist
build_dir = utils.create_build_directory(config)
#Now I have an output directory to put stuff in
#Create an XST directory to put stuff related to XST
xst_dir = os.path.join(build_dir, XST_DIR)
if not os.path.exists(xst_d... | [
"def create_xst_project_file(config):\n #print \"Creating xst project file\"\n xst_dir = create_xst_dir(config)\n project_fn = os.path.join(xst_dir, PROJECT_FILENAME)\n \n fp = open(project_fn, \"w\")\n v = \"\"\n #XXX: There should be allowances for adding different libraries in the future\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an xst temporary directory in the build folder | def create_temp_dir(config):
xst_dir = os.path.join(config["build_dir"], XST_DIR)
temp_dir = os.path.join(xst_dir, XST_TEMP_DIR)
temp_abs_dir = os.path.join(utils.get_project_base(), xst_dir, XST_TEMP_DIR)
if not os.path.exists(temp_abs_dir):
os.makedirs(temp_abs_dir)
return temp_dir | [
"def create_xst_dir(config):\n #Create a output directory if it does not exist\n build_dir = utils.create_build_directory(config)\n #Now I have an output directory to put stuff in\n #Create an XST directory to put stuff related to XST\n xst_dir = os.path.join(build_dir, XST_DIR)\n if not os.path.e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a configuration file create the .prj which holds the verilog filenames to be built | def create_xst_project_file(config):
#print "Creating xst project file"
xst_dir = create_xst_dir(config)
project_fn = os.path.join(xst_dir, PROJECT_FILENAME)
fp = open(project_fn, "w")
v = ""
#XXX: There should be allowances for adding different libraries in the future
for vf in config[... | [
"def create_project_file(config):\n core_dir = get_coregen_dir(config, absolute = True)\n cp_fn = os.path.join(core_dir, COREGEN_PROJECT_NAME)\n fp = open(cp_fn, \"w\")\n\n #Open up the template dictionary\n fn = COREGEN_TEMPLATE\n fn = os.path.join(os.path.dirname(__file__), fn)\n\n template =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a library search order file location for the XST script This is to declutter the base directory | def create_lso_file(config):
xst_dir = os.path.join(config["build_dir"], XST_DIR)
lso_fn = os.path.join(xst_dir, XST_PROJECT_LSO)
xst_abs_dir = create_xst_dir(config)
fn = os.path.join(xst_abs_dir, XST_PROJECT_LSO)
#print "lSO filename: %s" % fn
fp = open(fn, "w")
#fp.write("DEFAULT_SEARCH_... | [
"def _setLibraryRoot(self):\n\t\tself._libHome = os.path.abspath(rootDir)",
"def library_dirs(self):",
"def create_xst_dir(config):\n #Create a output directory if it does not exist\n build_dir = utils.create_build_directory(config)\n #Now I have an output directory to put stuff in\n #Create an XST ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Format an integer as a IPv6 string | def format_ipv6(value, mask):
value_ipv6 = ":".join(re.findall('..', "{:032x}".format(value)))
if mask is None:
return value_ipv6
value_mask = ":".join(re.findall('..', "{:032x}".format(mask)))
return "{}/{}".format(value_ipv6, value_mask) | [
"def ip_v6(self) -> str:\n ipv6 = IPv6Address(\n self.random.randint(\n 0, 2 ** 128 - 1,\n ),\n )\n return str(ipv6)",
"def bracketIPv6(ip):\n return \"[%s]\" % ip",
"def ipv6_to_ipv4(ipv6):\n return '.'.join([str(b) for b in ipv6[12:]])",
"def i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Format an integer as a IPv4 string | def format_ipv4(value, mask=None):
value_ipv4 = ".".join([str(int(x, 16)) for x in re.findall('..', "{:08x}".format(value))])
if mask is None:
return value_ipv4
value_mask = ".".join([str(int(x, 16)) for x in re.findall('..', "{:08x}".format(mask))])
return "{}/{}".format(value_ipv4, value_mask) | [
"def convert_ipv4_to_str(n_int):\n return \".\".join([str(n_int >> n & 0xFF) for n in [24, 16, 8, 0]])",
"def IPv4():\n return \"%d.%d.%d.%d\" % (\n random.randint(0, 255),\n random.randint(0, 255),\n random.randint(0, 255),\n random.randint(0, 255)\n )",
"def int_2_ip_str(i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of SQL file paths based on parameters. | def get_sql_files(root=".", filterl=None, exclude=None):
paths = Path(root).rglob("*.sql")
if root:
if filterl:
return [
str(path)
for path in paths
if any(
re.match(path.parts[-2], name, re.IGNORECASE) for name in... | [
"def get_sqls_from_dir(self, dir_path):\n sql_list = []\n files = os.listdir(dir_path)\n for create_file in files:\n if not create_file.startswith(\".\"):\n file_path = \"%s/%s\" % (dir_path, create_file)\n sql = self.get_sql_from_file(file_path)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a runset of runner file path and SQL file names in the same directory. | def get_run_set(bdir, runs):
path = Path(bdir)
dirs = [unit for unit in path.iterdir() if unit.is_dir()]
run_set = [
(
"".join(list(map(str, (Path(dir).rglob(runs))))),
list(map(lambda sqlfile: sqlfile.name, (Path(dir).rglob("*.sql")))),
)
for dir in d... | [
"def find_runs():\n runs = []\n for root, dirs, files in os.walk(settings.DATA_DIR):\n for d in dirs:\n run_data = os.path.join(root, d, 'run_data.json')\n if os.path.isfile(run_data):\n try:\n runs.append(Run(os.path.dirname(run_data)))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse given runset to get collections of valid SQL `exa_run` cmds, SQL file names in directory, path to runner and wrong `exa_run` cmds in runner. | def parse_run_set(rset, ptrn_exarun, ptrn_valid, ptrn_sql):
valid_sqls = []
wrong_runs = []
sqlsl = None
runf = None
for runf, sqlsl in rset:
exa_runs = re.findall(ptrn_exarun, Path(runf).read_text(), re.I | re.M)
for exa_run in exa_runs:
if re.match(ptrn_valid, e... | [
"def get_run_set(bdir, runs):\r\n path = Path(bdir)\r\n dirs = [unit for unit in path.iterdir() if unit.is_dir()]\r\n run_set = [\r\n (\r\n \"\".join(list(map(str, (Path(dir).rglob(runs))))),\r\n list(map(lambda sqlfile: sqlfile.name, (Path(dir).rglob(\"*.sql\")))),\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads a SQL file under given path and checks if each command contains required command. | def assert_sql_contains_only(path, cmds, exclude=False):
_, stmts, _ = parse_sql(path, DDL)
for cmd in cmds:
for stmt in stmts:
check = check_stmt(stmt, [cmd], exclude)
if exclude:
assert check, f"{path} should not contain {cmd} statement(s)!"
... | [
"def sqlfile(fname):\n conn = getConnection()\n with open(fname, 'r') as f:\n sql = f.read()\n\n commands = sql.split(';')\n \n print('executing sql', fname)\n with conn.cursor() as cur:\n for command in commands:\n command = command.strip()\n if command != '' a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a new access key on behalf of the user and stores the new access key in secrets manager. Then, send a notification email to users to notify them to rotate the key for their applications. It returns a JSON with status 200 if successful and 500 if error occurs. | def create_key(iam_username):
try:
response = iam.create_access_key(UserName=iam_username)
access_key = response["AccessKey"]["AccessKeyId"]
secret_key = response["AccessKey"]["SecretAccessKey"]
json_data = json.dumps({"AccessKey": access_key, "SecretKey": secret_key})
secre... | [
"def generate_access_key(self):\n\t\tfrom app import app\n\t\ts = JSONWebSignatureSerializer(app.config['SECRET_KEY'])\n\t\taccess_key = s.dumps({'username': self.username}) \n\t\tself.access_key = access_key",
"def _generate_new_access_token(self, action_result, data):\n\n req_url = '{}{}'.format(DEFENDER... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds the secret that stores the user's previous access key and mark it as inactive. Then, send a notification email to users to remind them to rotate the key for their applications. It returns a JSON with status 200 if successful and 500 if error occurs. | def deactive_key(iam_username):
try:
previous_secret_value = secretmanager.get_secret_value(
SecretId=iam_username, VersionStage="AWSPREVIOUS"
)
previous_secret_data = json.loads(previous_secret_value["SecretString"])
previous_access_key = previous_secret_data["AccessKey... | [
"def deactivate_key() -> tuple:\n json_data: dict = request.get_json()\n api_key: Optional[str] = json_data.get('api-key')\n secret_key: Optional[str] = json_data.get('SECRET_KEY')\n verify_secret_key(secret_key)\n\n return api_keys_view.deactivate_key(key=api_key)",
"def response_forbidden():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes the deactivated access key in the given iam user. Returns a JSON with status 200 if successful, 500 for error and 400 for if secrets don't match | def delete_key(iam_username):
try:
previous_secret_value = secretmanager.get_secret_value(
SecretId=iam_username, VersionStage="AWSPREVIOUS"
)
previous_secret_string = json.loads(previous_secret_value["SecretString"])
previous_access_key_id = previous_secret_string["Acces... | [
"def deactive_key(iam_username):\n\n try:\n previous_secret_value = secretmanager.get_secret_value(\n SecretId=iam_username, VersionStage=\"AWSPREVIOUS\"\n )\n previous_secret_data = json.loads(previous_secret_value[\"SecretString\"])\n previous_access_key = previous_secret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set shipping method code to session | def use_shipping_method(self, code):
self.reset_shipping_data()
self._set('shipping', 'method_code', code) | [
"def shipping_method(self, shipping_method):\n\n self._shipping_method = shipping_method",
"def setShippingMethods(self):",
"def shipping_carrier_code(self, shipping_carrier_code):\n\n self._shipping_carrier_code = shipping_carrier_code",
"def shipping_service_code(self, shipping_service_code):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use an user address (from an address book) as the shipping address. | def ship_to_user_address(self, address):
self._set('shipping', 'user_address_id', address.id) | [
"def ship_to_user(self, user):\n self.bill_to = '%s %s' % (user.first_name, user.last_name)\n self.ship_to = self.ship_to.strip()\n\n self.ship_to_first_name = user.first_name\n self.ship_to_last_name = user.last_name\n self.ship_to_email = user.email\n\n if hasattr(user, '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test whether a shipping address has been stored in the session. This can be from a new address or reusing an existing address. | def is_shipping_address_set(self):
new_fields = self.new_shipping_address_fields()
has_new_address = new_fields is not None
user_address_id = self.shipping_user_address_id()
has_old_address = user_address_id is not None and user_address_id > 0
pickup_address_id = self.shipping_pi... | [
"def has_receipt_address(self):\n return self.receipt_address_uploaded_at is not None",
"def has_shipping_event_occurred(self, event_type, quantity=None):\n if not quantity:\n quantity = self.quantity\n return self.shipping_event_quantity(event_type) == quantity",
"def check_pend... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compila el shader cargado | def compile(self):
if not self.isCompiled():
if self.file is not None:
try:
if self.tipo == VERTEX:
self.shader = glCreateShader(GL_VERTEX_SHADER)
else:
self.shader = glCreateShader(GL_FRAGMENT_SH... | [
"def compile_fragment_shader(self, render_ctx, value):\n print(\"COMPILE FRAGMENT SHADER\", self.__class__)\n shader = render_ctx.shader\n old_value = shader.fs\n shader.fs = value\n if not shader.success:\n shader.fs = old_value\n raise Exception('failed to ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retorna el fragment shader | def getFragmentShader(self):
return self.fshader | [
"def compile_fragment_shader(self, render_ctx, value):\n print(\"COMPILE FRAGMENT SHADER\", self.__class__)\n shader = render_ctx.shader\n old_value = shader.fs\n shader.fs = value\n if not shader.success:\n shader.fs = old_value\n raise Exception('failed to ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retorna el vertex shader | def getVertexShader(self):
return self.vshader | [
"def compile_vertex_shader(source):\n vertex_shader = gl.glCreateShader(gl.GL_VERTEX_SHADER)\n gl.glShaderSource(vertex_shader, source)\n gl.glCompileShader(vertex_shader)\n # check compilation error\n result = gl.glGetShaderiv(vertex_shader, gl.GL_COMPILE_STATUS)\n if not(result):\n raise ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retorna el programa compilado | def getCompiled(self):
if self.isCompiled():
return self.program
else:
raise Exception("el programa no ha sido compilado aun") | [
"def get_program_info():\n return f\"{get_program_name()} v{where.__version__}\"",
"def getExecutable():\n\n return sys.executable",
"def executable():\n return sys.executable",
"def build(self, progname):\n self.run_programm(self.COMPILED[self.progtype][0], \"%s %s %s\" %\\\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Funcion que carga un shader y retorna un objeto del tipo ShaderProgram | def loadShader(shaderpath, shadername, vertexFormatList=None, fragmentFormatlist=None):
fragment = Shader(shaderpath + shadername + ".fsh", FRAGMENT, True, fragmentFormatlist)
vertex = Shader(shaderpath + shadername + ".vsh", VERTEX, True, vertexFormatList)
return ShaderProgram(vertex, fragment, True) | [
"def shader(self):\n #TODO -- think -- if sheader is None create shader without prepare!\n #Note -- because shader accepts list of shader in prepare!!!!!!!\n # And thease shader can be None!\n return self._shader",
"def _compile_and_link_gl_program():\n program = gl.glCreateProg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply the module's layers (the fully connected network, then the unflatten/reshaping) to feature maps to obtain decoded images. | def layers(self, features: Dict[str, torch.Tensor]) -> torch.Tensor:
features: torch.Tensor = features[self.in_feature] # type: ignore[no-redef]
decoded_images = self.network(features)["out"]
decoded_images = self.reshape(decoded_images)
return decoded_images | [
"def layers(self, features: Dict[str, torch.Tensor]) -> torch.Tensor:\n x: torch.Tensor\n for i, f in enumerate(self.in_features):\n if i == 0:\n x = self.scale_heads[i](features[f])\n else:\n x = x + self.scale_heads[i](features[f])\n x = sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to create A_B_X testing directories and return the corresponding answer key An A file is chosen from either the scenario one or two with a 50/50 probability. The B file is then from the scenario not chosen for A. An X file is then created with a 50/50 probability of being either a duplicate of A or B | def create_A_B_X_cases(A_B_cases_zip_list, output_path):
logging.info("Enter: create_A_B_X_cases ")
global scenario_one
global scenario_two
global answer_key
# create listening directories and record answer to each in answer_log
for case_num, case in enumerate(A_B_cases_zip_list):
#MRR I... | [
"def generate_key(alice_results, bob_results, test_prob=None):\n basis_match = alice_results[0] == bob_results[0]\n alice_key = alice_results[1][basis_match].astype(int)\n bob_key = bob_results[1][basis_match].astype(int)\n\n if test_prob is not None:\n test_idxs = binomial(1, test_prob, size... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the notes that match the IDs in the given list | def get_notes_by_id(self, ids: List[str]) -> pd.Series:
return self.notes[self.notes.apply(lambda n: n.id in ids)] | [
"def get_notes_from_uuids(dictionary, uuid_list):\n titles = []\n texts = []\n notes = []\n for key in dictionary:\n if dictionary[key][\"content_type\"] == \"Note\" and dictionary[key][\"uuid\"] in uuid_list:\n try:\n titles.append(dictionary[key][\"content\"][\"title\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |