query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Calculate the eV/atom at given energies with mu_en | def eVatom_en(matID, keV, mJ, rms_mm, density=None):
if density == None:
density = defaultDensity(matID)
attL = 1.0 / mu_en(matID, keV, density)
EdensityJcm3 = mJ/1000 / (2 * np.pi * attL*u['cm'] * (rms_mm*0.1)**2)
atomVolcm3 = atomWeight(matID) / c['NA'] / density
return EdensityJcm3 * atom... | [
"def V2E(V):\n# for v in m/s returns energy in meV\n return 5.227e-6*V*V",
"def v_from_KE(E, m = 39.95):\n return np.sqrt(E/(6.24E18 * 0.5 * 1.66E-27*m))/1E5",
"def convert_kcalmol_eV(en_kcalmol):\n return en_kcalmol*kcalmol_eV",
"def convert_kJmol_eV(en_kJmol):\n return en_kJmol*kJmol_eV",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the material drill speed (mm/s) based on vaporization heat | def drillSpeed(matID, W, FWHM_mm):
vaporH = { # kJ/mol
# spec heat from room temperature to melting + latent heat of fusion + spec heat from melting to boiling + latent heat of vaporization
# refer https://webbook.nist.gov/chemistry/ for heat capacity, this tool also has some data in specificHeatPa... | [
"def get_speed_m_per_s(cls, kinetic_energy_MeV: float) -> float:\n return LIGHT_SPEED * math.sqrt(\n 1\n - (cls.STATIC_MASS_KG / cls.get_relativistic_mass(kinetic_energy_MeV)) ** 2\n )",
"def drillTime(matID, thickness_mm, W, FWHM_mm):\n return thickness_mm / drillSpeed(matI... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the material drill time based on vaporization heat | def drillTime(matID, thickness_mm, W, FWHM_mm):
return thickness_mm / drillSpeed(matID, W, FWHM_mm) | [
"def get_specific_heat() -> float:\n return 1006.0",
"def drillSpeed(matID, W, FWHM_mm):\n vaporH = { # kJ/mol\n # spec heat from room temperature to melting + latent heat of fusion + spec heat from melting to boiling + latent heat of vaporization\n # refer https://webbook.nist.gov/chemistry/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cut spectrum to a given energy range; return [0,0] if out of range | def spectrum_cut(spectrum, eVrange=(0.0, 0.0)):
if eVrange[1] == 0.0:
return spectrum
else:
if spectrum[-1,0] <= eVrange[0] or spectrum[0,0] >= eVrange[1]:
return np.array([[0, 0]], dtype=np.float)
else:
idx1 = np.argmax(spectrum[:,0] >= eVrange[0])
id... | [
"def cut_spectrum(input_spectrum, desired_frequency_range):\n channels_ip = []\n for ip in input_spectrum.GetChannels():\n channel_ip = []\n channel_op = []\n for n, i in enumerate(ip):\n if n > desired_frequency_range[0] / input_spectrum.GetResolution() and n < desired_frequen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the Bragg angle (deg) of the specified material, reflection and photon energy | def BraggAngle(ID,hkl,E=None):
E = eV(E)
d = dSpace(ID,hkl)
theta = asind(lam(E)/2/d)
return theta | [
"def comp_angle_magnet(self):\n Rbo = self.get_Rbo()\n W0 = self.comp_W0m()\n Harc = self.comp_H_arc()\n if self.is_outwards():\n return float(2 * arctan(W0 / (2 * (Rbo + self.H1 - Harc))))\n else:\n return float(2 * arctan(W0 / (2 * (Rbo - self.H1 - Harc))))\n\n # if self.W0_is_rad:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the structure factor | def StructureFactor(ID,f,hkl,z=None):
ID=goodID(ID)
i=complex(0,1)
h=hkl[0]
k=hkl[1]
l=hkl[2]
L=latticeType[ID]
if L=='fcc':
F=f*(1+np.exp(-i*np.pi*(k+l))+np.exp(-i*np.pi*(h+l))+np.exp(-i*np.pi*(h+k)))
elif L=='bcc':
F=f*(1+np.exp(-i*np.pi*(h+k+l)))
elif L=='cubic':
... | [
"def structure_factor(crystal, G):\n # define function for atomic factor\n def atomic_struc(element):\n \"\"\"calculate atomic structure factor for element el and reciprocal vector G in direct coordinates and rec_lattice in A^-1\"\"\"\n # calculate scalar reciprocal wave number\n q = np.l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the Darwin width for a specified crystal reflection (degrees) | def DarwinWidth(ID, hkl, E, T=293):
ID = goodID(ID)
E = eV(E)
theta = BraggAngle(ID,hkl,E)
l = lam(E)
f = FF(ID,2*theta,E)
F = StructureFactor(ID,f,hkl)
V = UnitCellVolume(ID)
dw=(2*c['eRad']*l**2*np.abs(F))/(np.pi*V*sind(2*theta))/u['rad']
return dw | [
"def arclength(c):\n r=c[1][0]\n start=c[1][1]\n end=c[1][2]\n if start == 0 and end == 360:\n return r * pi2\n else:\n start = start % 360.0\n end = end % 360.0\n\n if start > end:\n end = end+360.0\n d = pi2*r\n l = d*(end-start)/360.0\n return l",
"def get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the momentum transfer in Ang^1 from xraylib [sin(2theta)/lam] E is the photon energy (eV or KeV) twotheta is the scattering angle in degrees | def MomentumTransfer(E,twotheta):
E = keV(E)
th = np.deg2rad(twotheta)
p = xl.MomentTransf(E, th)
return p | [
"def momentum(E,m):\n\treturn math.sqrt(E*E - m*m)",
"def Eta(theta):\n return -np.log(np.tan(theta/2))",
"def angular_momentum(self, AM):\n # Printing the amplitude to command line\n amplitude = max(AM)-min(AM)\n print('Amplitude of angular momentum during %i year(s): %g[AU²/yr²]' \... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the writable of this SkillPropertyModel. | def writable(self) -> bool:
return self._writable | [
"def Writable(self):\n return self._get_attr('Writable')",
"def isWriteable(self):\n pass",
"def write_enabled(self):\n return self._write_enabled",
"def _get_read_only(self):\n return self._read_only",
"def readonly(self):\n return self._readonly",
"def immutability_pol... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the writable of this SkillPropertyModel. | def writable(self, writable: bool):
if writable is None:
raise ValueError("Invalid value for `writable`, must not be `None`") # noqa: E501
self._writable = writable | [
"def set_writable(self, permission):\n if isinstance(permission, string_types):\n self.set_config(\"$writable\", permission)\n else:\n raise ValueError(\"Passed permission is not string\")",
"def writable(self) -> bool:\n return self._writable",
"def Writable(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test whether a MARWILAlgorithm can be built with all frameworks. Learns from a historicdata file. | def test_marwil_compilation_and_learning_from_offline_file(self):
rllib_dir = Path(__file__).parent.parent.parent.parent
print("rllib dir={}".format(rllib_dir))
data_file = os.path.join(rllib_dir, "tests/data/cartpole/large.json")
print("data_file={} exists={}".format(data_file, os.path.... | [
"def in_maya():\n return \"maya.bin\" in sys.argv[0]",
"def check_optim_support(optim_name: str, framework: str) -> bool: \n return optim_name in OPTIM_LIST and framework in OPTIM_LIST[optim_name]",
"def is_build_job(self):\n\n for fspec in self.outdata:\n if '.lib.' in fspec.lfn and ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test whether MARWIL runs with cont. actions. Learns from a historicdata file. | def test_marwil_cont_actions_from_offline_file(self):
rllib_dir = Path(__file__).parent.parent.parent.parent
print("rllib dir={}".format(rllib_dir))
data_file = os.path.join(rllib_dir, "tests/data/pendulum/large.json")
print("data_file={} exists={}".format(data_file, os.path.isfile(data_... | [
"def is_hmm(filename):\n #print(\"Inside the hmm function {}\".format(filename))\n flag = True \n return flag",
"def check_report_is_at_recognition_of_prior_learning(text) -> bool:\n recog_check_regex = re.compile(r\"^recognition\\sof\\sprior\\slearning\", re.IGNORECASE).match(text)\n check_flag_re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if setHook has been called, else False. | def hooked(self):
return hasattr(self, 'hook') | [
"def hooked(self):\n return hasattr(self, \"hook\")",
"def has_hookscript ( self ):\n return self.hook_script_ref is not None",
"def check_called(self, func):\n self.called[func] = False\n def _check(*args, **kwargs):\n self.called[func] = True\n return func(*args... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Triggers traffic to be sent asynchronously. This is not a blocking function. | def send_traffic_async(self, traffic, function):
raise NotImplementedError(
"The TrafficController does not implement",
"the \"send_traffic_async\" function.") | [
"def requestFuture(self):\n self.socket.sendRequest()",
"async def blocking_call():\n time.sleep(5)",
"def execute_async(self):\n\t\tAsynchronousAction(self).start()",
"def send(self, packet):\n self._loop.create_task(self.send_coro(packet))",
"def send_async(self, transaction, headers=None... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calcule le prix total en fonction du nombre de CD et de DVD | def prix(n_cd=0, n_dvd=0):
if n_cd < SEUIL_CD:
prix_cd = n_cd * PRIX_CD
else:
prix_cd = n_cd * PRIX_CD_SOLDE
if n_dvd < SEUIL_DVD:
prix_dvd = n_dvd * PRIX_DVD
else:
prix_dvd = n_dvd * PRIX_DVD_SOLDE
return prix_cd + prix_dvd # prix total | [
"def getTotalPrice():",
"def subtotal(self):\n return self.cantidad * self.precio",
"def calcular_precio_total(self):\n\t\tsuma=0\n\t\tfor linea in detalle_pedido:\n\t\t\tsuma+= linea.subtotal\n\t\tself.total=suma",
"def valor_total(self):\n\n return self.cantidad * self.valor",
"def prix_tvac... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing the sum function with a list of integers | def test_sum_list_int(self):
list_of_int = [1, 2, 3]
result = sum(list_of_int)
self.assertEqual(result, 6) | [
"def test_list_int(self):\n data = [1, 2, 3]\n result = sum(data)\n self.assertEqual(result, 6)",
"def get_sum(numbers: List[int]) -> int:\n pass",
"def sum(numbers):",
"def calculate_sum(integers: List[int]) -> int:\n try:\n return sum(integers)\n except TypeError:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing the sum function with a list of fractions | def test_sum_list_fraction(self):
list_of_fractions = [Fraction(1, 4), Fraction(1, 4), Fraction(1, 2)]
result = sum(list_of_fractions)
self.assertEqual(result, 1) | [
"def test_sum_list_floats(self):\n\n list_of_floats = [1.2, 2.34, 2.001]\n result = sum(list_of_floats)\n\n self.assertEqual(result, 5.541)",
"def test_sum():\n from simplecalc.calculator import sum_\n\n assert sum_([0, 1]) == 1\n assert sum_([0, 1, -0.1]) == 0.9",
"def test_fracti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Testing the sum function with a list of float values | def test_sum_list_floats(self):
list_of_floats = [1.2, 2.34, 2.001]
result = sum(list_of_floats)
self.assertEqual(result, 5.541) | [
"def sum_list(input_list: List[float]) -> float:\n return sum(input_list)",
"def test_total_floats(self):\n float_list = [5.1, 10.321, 50.0, 3.98, 4.4]\n self.assertAlmostEqual(cr.total(float_list), 73.801, places=2)",
"def fsum(iterable):\n return 0.0",
"def test_sum():\n from simp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a sorted list of selfplay data directories. | def list_selfplay_dirs(base_dir):
model_dirs = [os.path.join(base_dir, x)
for x in tf.io.gfile.listdir(base_dir)]
return sorted(model_dirs, reverse=True) | [
"def dirs(self) -> list:\n dirs = [tic + \"/\" for tic in sorted(self._dirs, key=str.casefold)]\n return dirs",
"def find_data(self):\n data_list = []\n for root, dirs, files in os.walk(pathfinder.data_path()):\n for name in files:\n data_list.append(os.path.j... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Waits for all of the awaitable objects (e.g. coroutines) in aws to finish. All the awaitable objects are waited for, even if one of them raises an exception. When one or more awaitable raises an exception, the exception from the awaitable with the lowest index in the aws list will be reraised. | def wait(aws):
aws_list = aws if isinstance(aws, list) else [aws]
results = asyncio.get_event_loop().run_until_complete(asyncio.gather(
*aws_list, return_exceptions=True))
# If any of the cmds failed, re-raise the error.
for result in results:
if isinstance(result, Exception):
... | [
"def wait(aws):\n\n aws_list = aws if isinstance(aws, list) else [aws]\n results = asyncio.get_event_loop().run_until_complete(asyncio.gather(\n *aws_list, return_exceptions=True))\n # If any of the cmds failed, re-raise the error.\n for result in results:\n if isinstance(result, Exception):\n rais... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check to see that only warn and info output appears in the stream. The first line may start with WARN] or WARNING] depending on whether 'WARN' has been registered as a global log level. See options_bootstrapper.py. | def assertWarnInfoOutput(self, lines):
self.assertEqual(2, len(lines))
self.assertRegexpMatches(lines[0], '^WARN\w*] warn')
self.assertEqual('INFO] info', lines[1]) | [
"def no_log_warn(logical_line):\n\n msg = (\"G330: LOG.warn is deprecated, please use LOG.warning!\")\n if \"LOG.warn(\" in logical_line:\n yield (0, msg)",
"def log_check_warnings(self):\n pass",
"def _filter_info_warning(lines):\n lines = list(filter(lambda x: 'RuntimeWarning' not in x,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses instruction's arguments using instructionargument module | def parse_args(self, instruction: ET.Element):
self.__args = []
cur_order = []
for child in instruction:
arg = Argument(child)
if arg.order in cur_order:
raise UnexpectedXMLStructure(
'Wrong order of argument element "{}"'.format(arg.d... | [
"def parse_arguments(args):",
"def _parse_instruction(line: str) -> list:\n\n split = line.split(' ')\n instruction, argument = split\n\n return [instruction, int(argument)]",
"def decode_instruction(instruction):\n if not instruction.endswith(INST_TERM):\n raise InvalidInstruction('I... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets either a run or a compile task from the API | def getTask():
content = requests.get(MANAGER_URL+"task", params={"apiKey": API_KEY}).text
if content == "null":
return None
else:
return json.loads(content) | [
"async def get_task(self, task_id: str) -> Task:",
"def getTask():\n content = requests.get(MANAGER_URL+\"task\", params={\"apiKey\": API_KEY}).text\n\n print(\"Task call %s\\n\" % content)\n if content == \"null\":\n return None\n else:\n return json.loads(content)",
"def get_task(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Posts the result of a compilation task | def compileResult(userID, didCompile, language):
r = requests.post(MANAGER_URL+"compile", data={"apiKey": API_KEY, "userID": userID, "didCompile": int(didCompile), "language": language}) | [
"def compileResult(userID, didCompile, language, errors=None):\n r = requests.post(MANAGER_URL+\"compile\", data={\"apiKey\": API_KEY, \"userID\": userID, \"didCompile\": int(didCompile), \"language\": language, \"errors\": errors})\n print(\"Posting compile result %s\\n\" % r.text)",
"def compile_submissio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Append base url to partial url | def get_full_url(self, part_url):
return BASE_URL + part_url | [
"def set_short_url_base(url):",
"def _prepare_url(self , url):\n return urljoin(self.baseurl , url)",
"def get_short_url_base():",
"def generate_full_url(base_url, lineage, segment):\n params = \"/\".join([lineage, segment])\n return urljoin(base_url, params)",
"def default_url_append(self,path... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets stats about additions and deletions Commit url to be used can be set via commit_url or generated using both full_name and commit_sha If all parameters are set, commit_url will be used, the others ignored | def get_commit_change_stats(self, commit_url='', full_name='', commit_sha=''):
if commit_url == '' and (commit_sha == '' and full_name == ''):
raise BaseException('commit url could not be generated. Commit url, commit sha and full name not set')
return None
url = commit_url
... | [
"def get_commit_stats(self):\n return self.commit_stats",
"def latestCommitInfo(u, r):\n global headers\n url='https://api.github.com/repos/{}/{}/commits?per_page=1'.format(u, r)\n rawrepourl=\"https://github.com/{}/{}\".format(u,r)\n canonurl='https://api.github.com/repos/{}/{}'.format(u, r)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract repo commits from details in the repo object | def extract_commits(self, repo_obj):
url = REPO_COMMIT_LIST.format(full_name=repo_obj['full_name'])
url = self.get_full_url(url)
json_data = loads(self.get_from_net(url))
commits = []
for i in json_data:
committer = i['committer']
#stats = self.get_commit_... | [
"def commits_between(repo_path, start, end):\n \n git = subprocess.Popen([\"git\", \"log\", \"%s..%s\" % (start, end)], stdout=subprocess.PIPE, cwd=repo_path)\n log = git.stdout.read().decode(\"utf-8\")\n \n cur = None\n commits = []\n \n for line in log.splitlines():\n cm = re.match(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets all the public repos | def get_public_repos(self, max_repos=DEFAULT_MAX_PUBLIC_REPOS):
since = 0
repo_count = 0
repos = []
while repo_count < max_repos:
temp = self.process_repo(self.get_full_url(ALL_REPO_LIST.format(since=since)), True)
repos.extend(temp)
repo_count = len(r... | [
"def list_public_repos():\n return Collaborator.objects.filter(user__username=settings.PUBLIC_ROLE)",
"def repositories():\n return user.repos()",
"def list_all(self):\n rlist = list()\n url = self._api + \"orgs/\" + self._organisation + \"/repos\"\n\n for page in range(1, MAX_NUM... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Specifies that a property on a PlanningSolution class is a Collection of problem facts. A problem fact must not change during solving (except through a ProblemFactChange event). The constraints in a ConstraintProvider rely on problem facts for ConstraintFactory.from(Class). | def problem_fact_collection_property(fact_type):
def problem_fact_collection_property_function_mapper(getter_function):
ensure_init()
from org.optaplanner.optapy import PythonWrapperGenerator
from org.optaplanner.core.api.domain.solution import \
ProblemFactCollectionProperty as ... | [
"def planning_entity_collection_property(entity_type):\n def planning_entity_collection_property_function_mapper(getter_function):\n ensure_init()\n from org.optaplanner.optapy import PythonWrapperGenerator\n from org.optaplanner.core.api.domain.solution import \\\n PlanningEntity... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Specifies that a property on a PlanningSolution class is a Collection of planning entities. Every element in the planning entity collection should have the PlanningEntity annotation. Every element in the planning entity collection will be added to the ScoreDirector. | def planning_entity_collection_property(entity_type):
def planning_entity_collection_property_function_mapper(getter_function):
ensure_init()
from org.optaplanner.optapy import PythonWrapperGenerator
from org.optaplanner.core.api.domain.solution import \
PlanningEntityCollectionP... | [
"def problem_fact_collection_property(fact_type):\n def problem_fact_collection_property_function_mapper(getter_function):\n ensure_init()\n from org.optaplanner.optapy import PythonWrapperGenerator\n from org.optaplanner.core.api.domain.solution import \\\n ProblemFactCollectionP... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Specifies that a class is a problem fact. A problem fact must not change during solving (except through a ProblemFactChange event). The constraints in a ConstraintProvider rely on problem facts for ConstraintFactory.from(Class). | def problem_fact(fact_class):
ensure_init()
out = JImplements('org.optaplanner.optapy.OpaquePythonReference')(fact_class)
out.__javaClass = _generate_problem_fact_class(fact_class)
_add_deep_copy_to_class(out)
return out | [
"def register_problem(problem_cls):\n problem_name = _default_name(problem_cls)\n if problem_name in REGISTERED_PROBLEMS:\n raise LookupError(\"Problem {} already registered.\".format(problem_name))\n REGISTERED_PROBLEMS[problem_name] = problem_cls\n problem_cls.name = problem_name\n return problem_cls",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Specifies that the class is a planning solution (represents a problem and a possible solution of that problem). A possible solution does not need to be optimal or even feasible. A solution's planning variables might not be initialized (especially when delivered as a problem). A solution is mutable. For scalability reas... | def planning_solution(planning_solution_class):
ensure_init()
out = JImplements('org.optaplanner.optapy.OpaquePythonReference')(planning_solution_class)
out.__javaClass = _generate_planning_solution_class(planning_solution_class)
_add_deep_copy_to_class(out)
return out | [
"def __init__(self, initial=[(3,3,1),(0,0,0)], goal=[(0,0,0),(3,3,1)]):\n self.goal = goal\n Problem.__init__(self, initial, goal)",
"def __init__(self, initial, goal=(3, 3, 0, 0, 0)):\n\n self.goal = goal\n Problem.__init__(self, initial, goal)",
"def __init__(self, initial, goal=(1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Marks a function as a ConstraintProvider. The function takes a single parameter, the ConstraintFactory, and must return a list of Constraints. To create a Constraint, start with ConstraintFactory.from(get_class(PythonClass)). | def constraint_provider(constraint_provider_function):
ensure_init()
constraint_provider_function.__javaClass = _generate_constraint_provider_class(constraint_provider_function)
return constraint_provider_function | [
"def createConstraint(*argv):",
"def constraint(var_names, test, error_code, error_message_gen):\n new_constraint = _Constraint(var_names, test, error_code, error_message_gen)\n Model.add_constraint_to_current_context(new_constraint)\n return new_constraint",
"def provider() -> Callable[[P], P]:\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a set of nodes to a role. The ROLE argument specify the role which the nodes will be added. | def role_add(role, nodes, node, node_vars, host_vars, extra):
role_manager = get_role_manager()
node += nodes
nodes, node_vars, host_vars, extra_args = _split_vars(
node, node_vars, host_vars, extra)
if not nodes:
raise ArgumentError('No nodes informed')
added_nodes = role_manager.a... | [
"def _add_roles(self, node, roles):\n if node is None:\n raise Exception(\"Node is None!\")\n\n if not roles:\n logging.info(\"Role list is None. Run list will no change.\")\n return\n\n run_list = node.run_list\n for role in roles:\n if role n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Perform an group action at a set of nodes. The ROLE argument specify the role which the action will be performed. | def role_action(role, action, nodes, node, node_vars, host_vars, extra):
role_manager = get_role_manager()
node += nodes
nodes, node_vars, host_vars, extra_args = _split_vars(
node, node_vars, host_vars, extra)
if not nodes:
nodes = role_manager.get_all_role_nodes_hosts(role)
else:
... | [
"def _create_grouprole_actions(cls, request, grouprole):\n for info in grouprole:\n action = request.add_action(type='add_role')\n action.add_target(project=info.project, package=info.package)\n action.add_group(name=info.group, role=info.role)",
"def _visit_roles_node(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print roles in role path. The ROLE argument filter specific roles. | def role_list(role, detailed, indent, quiet):
if quiet and detailed:
raise ValueError(f"Options `detailed` and `quiet` are mutually exclusive")
role_manager = get_role_manager()
roles = role_manager.roles if not role else {
rname: r
for rname, r in role_manager.roles.items() if rnam... | [
"async def list_roles(self, args):\n if not args:\n await self.client.send(\"The following roles exist: \" + ', '.join(['#**%s**' % name for name in self.roles]))\n else:\n args = args.lstrip('#')\n if args not in self.roles:\n await self.client.send_err... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Explicitly set identity and claims for jwt. | def add_claims_to_access_token(identity):
if identity == 'admin':
roles = 'admin'
else:
roles = 'peasant'
now = datetime.utcnow()
return {
'exp': now + current_app.config['JWT_EXPIRES'],
'iat': now,
'nbf': now,
'sub': identity,
'roles': roles
... | [
"def add_claims_to_jwt(identity):\n user = UserModel.find_by_id(identity)\n if user.is_admin:\n return {\"is_admin\": True}\n return {\"is_admin\": False}",
"def remember(self, response, request, identity):\n extra_claims = identity.as_dict()\n userid = extra_claims.p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Search list for device name and retrieve address | def get_address(self,device_list):
for device in device_list:
if device.name == self.NAME:
self.ADDR = device.address
return True
return False | [
"def search(self,name=None):\n\t\taddresses = discover_devices()\n\t\t#if len(addresses) == 0:\n\t\t#\treturn None\n\t\tnames = []\n\t\tfor adr in addresses:\n\t\t\tnames.append(lookup_name(adr))\n\t\t\tif name != None and name == names[-1]:\n\t\t\t\treturn adr\n\n\t\treturn zip(addresses,names)",
"def _find_devi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Connect button press callback, retrieves device name from text box and sets flag | def get_device(self):
self.connect_button = 1
self.device_name = self.deviceEntry.text() | [
"def device_connect(self):\n pass",
"def run_btn_event(self):\n self.add_device_widget = AddDeviceWidget() # add device\n self.add_device_widget.setWindowModality(Qt.ApplicationModal)\n self.device_and_data_signal.connect(self.add_device_widget.add_radio_to_widget, Qt.QueuedConnection... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the options and value positional arguments are working for RadioItems. | def test_dbpa002_radio_items(dash_duo):
app = Dash()
options = {
"OptionA": "Option 1",
"OptionB": "Option 2",
"OptionC": "Option 3",
}
value = "OptionB"
with_keywords = RadioItems(
options=options,
value=value,
id="with-keywords",
)
without... | [
"def test_option_types(self, options, proto_options):\n st.radio('the label', options)\n\n c = self.get_delta_from_queue().new_element.radio\n self.assertEqual(c.label, 'the label')\n self.assertEqual(c.value, 0)\n self.assertEqual(c.options, proto_options)",
"def test_cast_opti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test draw two (nondeterministic(. | def test_draw_two(self):
f = txn_oracle.draw_two
for _ in range(1000):
max_n = random.randint(4, 20)
i, j = f(max_n)
assert i != j | [
"def testdraw():",
"def test_simulate_draw():\n # TODO: Use a proper testing framework\n TESTS = [\n ([], []),\n (['A'], []),\n (['A', 'B', 'C', 'D'], [('A', 'C'), ('D', 'B'), ('A', 'B'), ('C', 'D'), ('A', 'D'), ('B', 'C')]),\n (['A', 'B', 'C', 'D', 'E'], [('A', 'E'), ('B', 'C'),... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks for differences between ActivityType instance and upstream version | def _diff(self) -> ModelDiff:
try:
description = self.connection.describe_activity_type(self.domain.name, self.name, self.version)
except SWFResponseError as err:
if err.error_code == "UnknownResourceFault":
raise DoesNotExistError("Remote ActivityType does not ex... | [
"def _is_version_up_to_date(self):",
"def test__ActivityMetadataBase__eq():\n activity_metadata = ActivityMetadataBase()\n \n vampytest.assert_eq(activity_metadata, activity_metadata)\n vampytest.assert_ne(activity_metadata, object())",
"def is_changed_subtype(self):\n type_ = self.current_fi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if the ActivityType exists amazonside | def exists(self) -> bool:
self.connection.describe_activity_type(self.domain.name, self.name, self.version)
return True | [
"def exists_intent_action(self, intent_keyword):\n pass",
"def is_assessor_type(obj_type):\n _okeys = list(obj_type.keys())\n return 'xsiType' in _okeys or 'procstatus' in _okeys",
"def is_start(self, activity) -> bool:\n return activity == self.activity_concept_name(TRACE_START)",
"def is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests updating aesthetic fields on Tenant | def test_tenant_update(sample_identity):
access_token, tenant, tenant_user, tc = sample_identity
tenant.name = "ilovebeansllc"
headers = {"Authorization": "Bearer " + access_token}
updated_tenant_request = id_schemas.TenantSchema().dump(tenant)
updated_tenant = tc.put(
f"api/v1/identity/tena... | [
"def test_tenant_user_aesthetic_update(sample_identity):\n access_token, tenant, tenant_user, tc = sample_identity\n headers = {\"Authorization\": \"Bearer \" + access_token}\n new_email = f\"{uuid.uuid4()}@c1.com\"\n new_first_name = str(uuid.uuid4())\n new_last_name = str(uuid.uuid4())\n updated... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests aesthetic updates for tenant_user | def test_tenant_user_aesthetic_update(sample_identity):
access_token, tenant, tenant_user, tc = sample_identity
headers = {"Authorization": "Bearer " + access_token}
new_email = f"{uuid.uuid4()}@c1.com"
new_first_name = str(uuid.uuid4())
new_last_name = str(uuid.uuid4())
updated_tenant_user = {"... | [
"def test_update_user(self):\n pass",
"def test_tenant_update(sample_identity):\n access_token, tenant, tenant_user, tc = sample_identity\n tenant.name = \"ilovebeansllc\"\n headers = {\"Authorization\": \"Bearer \" + access_token}\n updated_tenant_request = id_schemas.TenantSchema().dump(tenan... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests authorization around limiting reassignment of TenantUsers by nonadministrators | def test_tenant_user_change_tenant(sample_identity):
access_token, tenant, tenant_user, tc = sample_identity
# Create a new Tenant
new_tenant = identity.Tenant()
new_tenant.name = "Aperture Science"
db.session.add(new_tenant)
db.session.commit()
# Create a Tenant Specific admin role
new_... | [
"def test_get_tenant_admin(self):\n from django.contrib.auth import get_user_model\n\n # Create a normal user and get the authorization token. Then force the\n # user to be a tenant admin.\n token = create_and_login()\n\n user = get_user_model().objects.get(username=TEST_USER_1[0]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get score ranging from [0, 100] from gender, grate, test_name and test_result. | def get_score_from_test(gender, grade, test_name, test_result):
score_map = TestSports[test_name.upper()] \
.value \
[Constants.SCORE_MAP] \
[Gender[gender.upper()]] \
[Grade[grade.upper()]]
print(score_map)
score = Student.get_score(score_map, te... | [
"def score(name):\r\n return (sorted(test).index(name)+1)*value(name)",
"def status_results(score):\n if score < 0 or score > 100:\n return \"Invalid score\"\n elif score >= 90:\n return \"Excellent\"\n elif score >= 50:\n return \"Passable\"\n else:\n return \"Bad\"",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the overlay polygon based on the selection and the location of the source and destination plots. | def calculate_points(self, component):
# find selection range on source plot
x_start, x_end = self._get_selection_screencoords()
if x_start > x_end:
x_start, x_end = x_end, x_start
y_end = self.source.y
y_start = self.source.y2
left_top = np.array([x_start, ... | [
"def calculate_points(self, component):\n # find selection range on source plot\n x_start, x_end = self._get_selection_screencoords()\n if x_start > x_end:\n x_start, x_end = x_end, x_start\n\n y_end = self.source.y\n y_start = self.source.y2\n\n left_top = np.ar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a tuple of (x1, x2) screen space coordinates of the start and end selection points. If there is no current selection, then returns None. | def _get_selection_screencoords(self):
selection = self.source.index.metadata["selections"]
if (selection is not None) and (len(selection) == 2):
mapper = self.source.index_mapper
return mapper.map_screen(np.array(selection))
else:
return None | [
"def get_selection(self):\n if not len(self.GetSelectionBlockTopLeft()):\n selected_columns = self.GetSelectedCols()\n selected_rows = self.GetSelectedRows()\n if selected_columns:\n start_col = selected_columns[0]\n end_col = selected_columns[-1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the overlay polygon based on the selection and the location of the source and destination plots. | def calculate_points(self, component):
# find selection range on source plot
x_start, x_end = self._get_selection_screencoords()
if x_start > x_end:
x_start, x_end = x_end, x_start
y_end = self.source.y
y_start = self.source.y2
left_top = np.array([x_start, ... | [
"def calculate_points(self, component):\n # find selection range on source plot\n x_start, x_end = self._get_selection_screencoords()\n if x_start > x_end:\n x_start, x_end = x_end, x_start\n\n y_end = self.source.y\n y_start = self.source.y2\n\n left_top = np.ar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Display error messages and exit if no lore environment can be found. | def validate():
if not os.path.exists(os.path.join(ROOT, APP, '__init__.py')):
message = ansi.error() + ' Python module not found.'
if os.environ.get('LORE_APP') is None:
message += ' $LORE_APP is not set. Should it be different than "%s"?' % APP
else:
message += ' $L... | [
"def verify_environment():\n\n if \"MROPATH\" not in os.environ:\n raise EnvironmentError(\n \"MROPATH is not in the environment. You probably need to source \"\n \"sourceme.bash in cellranger before running this tool.\")\n\n try:\n import martian\n except ImportError:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reboot python in the Lore virtualenv | def reboot(*args):
args = list(sys.argv) + list(args)
if args[0] == 'python' or not args[0]:
args[0] = BIN_PYTHON
elif os.path.basename(sys.argv[0]) in ['lore', 'lore.exe']:
args[0] = BIN_LORE
try:
os.execv(args[0], args)
except Exception as e:
if args[0] == BIN_LORE ... | [
"async def restart(self, ctx):\n await self.bot.send(ctx, ':warning: Rebooting Lilac...')\n os.execl(sys.executable, sys.executable, * sys.argv)",
"def reboot():\n sudo('/mnt/apps/bin/restart-all-apache.sh')",
"def restart():\r\n fprint('Restarting supervisord')\r\n sudo('cp ~ec2-user/viewfin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sanity check version information for corrupt virtualenv symlinks | def check_version():
if sys.version_info[0:3] == PYTHON_VERSION_INFO[0:3]:
return
sys.exit(
ansi.error() + ' your virtual env points to the wrong python version. '
'This is likely because you used a python installer that clobbered '
'the system inst... | [
"def virtualenvwrapper_check():\n compare_result = False\n try:\n output = subprocess.check_output(shlex.split(\"virtualenv --version\"), stderr=subprocess.STDOUT)\n lines = output.split(\"\\n\")\n version_string = re.compile(\"(\\d)+.(\\d)+.(\\d)\")\n line0_result = version_string... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attempts to read a python version string from a runtime.txt file | def read_version(path):
version = None
if os.path.exists(path):
version = open(path, 'r', encoding='utf-8').read().strip()
if version:
return re.sub(r'^python-', '', version)
return version | [
"def _read_version():\n source_dir = os.path.abspath(os.path.dirname(__file__))\n version_file = os.path.join(source_dir, '__version__.txt')\n version = open(version_file, 'r').readlines().pop()\n if isinstance(version, bytes):\n version = version.decode('utf-8')\n version = str(version).strip... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Idempotently caches the list of packages installed in the virtualenv. Can be run safely before the virtualenv is created, and will be rerun afterwards. | def set_installed_packages():
global INSTALLED_PACKAGES, REQUIRED_VERSION
if INSTALLED_PACKAGES:
return
if os.path.exists(BIN_PYTHON):
pip = subprocess.Popen(
(BIN_PYTHON, '-m', 'pip', 'freeze'),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
... | [
"def get_package_list(self, venv):\n # activate virtual environment\n activate_this = os.path.expanduser(\n os.path.join(self.venvs_dir, venv, 'bin/activate_this.py'))\n execfile(activate_this, dict(__file__=activate_this))\n\n # get installed packages\n package_list =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given two matching sets of coordinates on detector and sky, compute the WCS. Fits a WCS object to matched set of input detector and sky coordinates. Optionally, a SIP can be fit to account for geometric distortion. Returns an `~astropy.wcs.WCS` object with the best fit parameters for mapping between input pixel and sky... | def fit_wcs_from_points(xy, world_coords, proj_point='center',
projection='TAN', sip_degree=None): # pragma: no cover
from astropy.coordinates import SkyCoord # here to avoid circular import
import astropy.units as u
from astropy.wcs import Sip
from scipy.optimize import least_... | [
"def WCS(imname, outname, astronet=False, timeout=None):\n\n print_cmd_line(\"STAP_WCS.py\", imname, outname,\n astronet=astronet, timeout=timeout)\n\n if astronet:\n cmd = \"solve-mosaic_single.py {0} {1}\".format(imname,outname)\n else:\n cmd = \"{0}/bin/SM-WCS-perchip.py ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The function creates an new dictionary entry 'AUX' that includes starting values of each parameter and the number of covariates. | def auxiliary(dict_):
dict_['AUX'] = {}
if dict_['DIST']['coeff'] == [0.0] * len(dict_['DIST']['coeff']):
is_deterministic = True
else:
is_deterministic = False
for key_ in ['UNTREATED', 'TREATED', 'COST', 'DIST']:
if key_ in ['UNTREATED', 'TREATED', 'COST']:
dict_[k... | [
"def initialize_subs():\n per_qual = dict(zip(range(0,130),[0]*130))\n subs = {\"CT-before\":per_qual.copy(),\\\n \"TC-before\":per_qual.copy(),\\\n \"GA-before\":per_qual.copy(),\\\n \"AG-before\":per_qual.copy(),\\\n \"CT-after\":per_qual.copy(),\\\n \"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Train hotel cluster embeddings model on data saved in ../processed. | def main(input_filepath, output_model_filepath):
logger = logging.getLogger(__name__)
logger.info('training hotel cluster embeddings models')
input_file = os.path.join(input_filepath, 'sentences.pkl')
output_model_file = os.path.join(output_model_filepath, 'hotelcluster2vec.bin')
train(input_file,... | [
"def main(inputdir,\n embeddings_file,\n targetdir,\n lowercase=False,\n ignore_punctuation=False,\n num_words=None,\n stopwords=[],\n labeldict={},\n bos=None,\n eos=None):\n\n if not os.path.exists(targetdir):\n os.makedirs(targetdi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an unresolved Entry for this builder. Calls `_CONTEXT.on_entry` to register/check dependencies etc. | def __call__(self, config):
entry = Entry(self.name, make_key(config), config, None, None, None)
if not hasattr(_CONTEXT, "on_entry"):
return entry
on_entry = _CONTEXT.on_entry
if on_entry:
on_entry(entry)
return entry | [
"def create_entry(self, entry, paths):\n return self.entry_cls(entry, paths)",
"def _CreateEntry(self, node, props):\n entry_list = props.get('type', 'empty').split()\n ftype = entry_list[0]\n if ftype == 'empty':\n ftype = ''\n key = None\n if len(entry_list) > 1:\n key = entry_li... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert from mjd utc to et using tempo2 out put tt2tdb | def mjd2et(mjd,tt2tdb):
mjdJ2000 = mp.mpf("51544.5")
secDay = mp.mpf("86400.0")
mjdTT = tc.mjd2tdt(mp.mpf(mjd))
# Convert mjdutc to mjdtdt using HP time convert lib
# print "python ",mjdTT
et = (mp.mpf(mjdTT)-mjdJ2000)*mp.mpf(86400.0)+mp.mpf(tt2tdb)
return et | [
"def mjd2et(self, time):\n time=time+2400000.5\n return (sp.str2et('JD '+repr(time)))",
"def mjd2et(self, time):\n\n time=time+2400000.5\n return (sp.str2et('JD '+repr(time)))",
"def tt(self):\n return self.MJD + self.tt_ut1 + 2400000.5",
"def mjdToUT(mjd=None, use_metool=Tr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Suggest a default file name for a results (dac) file. If the file is in a '/femdata' folder, will suggest the respective '/results' folder. Otherwise the file is simply renamed from '.fem' to '.dac'. | def suggest_dac_filename(self, relative=False):
fempath = os.path.abspath(self.doc.getProblemPath())
folders = os.path.dirname(fempath).split(os.path.sep)
if folders[-1] == "femdata":
folders[-1] = "results"
folder = os.path.sep.join(folders)
dacpath = folder ... | [
"def autodetect_result_path():\n global _result_path\n\n # Get all sub folders\n sub_folders = [(x[0], x[2]) for x in os.walk('.')]\n\n possible_paths = []\n\n # Loop over them\n for sub_folder, files in sub_folders:\n # Check if this folder contains jnf and agc/ags files. If so, return the... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load the first time step after the time step provided by time | def load_first_ts_after(self, time):
# get time step list
df_ts = self.doc.c.sim.df.time_steps()
if type(time) in [float, int]:
if len(df_ts[df_ts.simulation_time > time]) == 0:
raise RuntimeError("{} contains no timestep after {} d".format(self.doc.c.or... | [
"def set_first_machine_time_step(self, first_machine_time_step):",
"def onTimeStepStart(self, timeStep):\n pass",
"def time_step():\n return TimeStep()",
"def next_step(self):\n if self.time_point + 1 >= len(self.data):\n print(\"Error: at last time point\")\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a calendar time (datetime) to simulation time (in hours). Requires that the Reference Time is set in the model. | def calendar_to_simtime(self, calendar_time):
time_ref = self.doc.getReferenceTime()
if time_ref is None:
raise (RuntimeError("Reference time not set in model"))
return (calendar_time - time_ref).total_seconds() / (24 * 60 * 60) | [
"def simtime_to_calendar(self, sim_time):\n time_ref = self.doc.getReferenceTime()\n if time_ref is None:\n raise (RuntimeError(\"Reference time not set in model\"))\n\n return time_ref + timedelta(sim_time)",
"def minutes_to_hours(self):\n\n unmasked_minutes = 1 - ma.getmas... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a simulation time (in unit days since reference time) into a calendar date (datetime.datetime). Requires that the Reference Time is set in the model. | def simtime_to_calendar(self, sim_time):
time_ref = self.doc.getReferenceTime()
if time_ref is None:
raise (RuntimeError("Reference time not set in model"))
return time_ref + timedelta(sim_time) | [
"def calendar_to_simtime(self, calendar_time):\n time_ref = self.doc.getReferenceTime()\n\n if time_ref is None:\n raise (RuntimeError(\"Reference time not set in model\"))\n\n return (calendar_time - time_ref).total_seconds() / (24 * 60 * 60)",
"def reference_date(self) -> datetim... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Augments the image by rotating the image by max_angle in the axial plane in both directions Also flips the image from left to right and rotates by max_angle in both directions | def augment_image(image,max_angle):
angles = [-max_angle,max_angle]
axes = [(0,1),(0,2),(1,2)]
images_aug = [image,image[::-1]]
for angle in angles:
for axis in axes:
images_aug.append(aug.rotate(image, angle, axes=axis, reshape=False, order=0))
images_aug.append(aug.rota... | [
"def rotate(img, angle, resample=False, expand=False, center=None):\n \n return img.rotate(angle, resample, expand, center)",
"def rotate_augmentation():\n rand_rotate = np.random.randint(180)\n return lambda image: rotate_with_extension(image, rand_rotate)",
"def optimiz... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a survival class label list from a list of survival days categories are 0 for under 10 month survival, 1 for 1015 months and 2 for 15+ months | def categorize(y):
y_out = []
for yi in y:
if int(yi)<(365*10.0)/12.0:
y_out.append(0)
elif int(yi)<(365*15.0)/12.0:
y_out.append(1)
else:
y_out.append(2)
return np.array(y_out) | [
"def add_classes(self, class_list):\n for university_class in class_list:\n if self.name in university_class.days:\n self.classes.append(university_class)\n self.calculate_length()\n self.classes.sort()",
"def create_cat_features(v, n):\n return [convert_to_cat(x,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns all provas >>> self._getAllProvas() | def _getAllProvas(self):
return self.execSql("select_all_provas") | [
"def _getConteudoProvas(self, id_conteudo):\n return self.execSql(\"select_conteudo_provas\",\n id_conteudo=int(id_conteudo))",
"def get_all_drawables(self): \n drawables = []\n if len(self.component_list) > 0:\n for c in self.component_list:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns all provas from conteudo >>> self._getConteudoProvas() | def _getConteudoProvas(self, id_conteudo):
return self.execSql("select_conteudo_provas",
id_conteudo=int(id_conteudo)) | [
"def _getAllProvas(self):\n return self.execSql(\"select_all_provas\")",
"def _getConteudoCadastros(self, id_conteudo):\n return self.execSql(\"select_conteudo_cadastros\",\n id_conteudo=int(id_conteudo))",
"def pruebas(self):\n self.gestor_pca.pruebas()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns all cadastros from conteudo >>> self._getConteudoCadastros() | def _getConteudoCadastros(self, id_conteudo):
return self.execSql("select_conteudo_cadastros",
id_conteudo=int(id_conteudo)) | [
"def _getConteudoCadastrosSelecionados(self, id_conteudo):\n return self.execSql(\"select_conteudo_cadastros_selecionados\",\n id_conteudo=int(id_conteudo))",
"def lista_cajeros(self):\n self.conexion.iniciar()\n cur = self.conexion.conn.cursor()\n\n query =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns all cadastros selecionados from conteudo >>> self._getConteudoCadastrosSelecionados() | def _getConteudoCadastrosSelecionados(self, id_conteudo):
return self.execSql("select_conteudo_cadastros_selecionados",
id_conteudo=int(id_conteudo)) | [
"def _getConteudoCadastros(self, id_conteudo):\n return self.execSql(\"select_conteudo_cadastros\",\n id_conteudo=int(id_conteudo))",
"def lista_cajeros(self):\n self.conexion.iniciar()\n cur = self.conexion.conn.cursor()\n\n query = \"SELECT * FROM Cajeros\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns all cursos superiores from cadastro >>> self._getCadastroCursosSuperiores() | def _getCadastroCursosSuperiores(self, id_cadastro):
return self.execSql("select_cadastro_cursos_superiores",
id_cadastro=int(id_cadastro)) | [
"def super_categories(self):\n R = self.base().base_ring()\n category = GradedHopfAlgebrasWithBasis(R)\n return [Realizations(self.base()), category.Quotients()]",
"def getCursosGraduacao(self):\n params = {\"NIVEL_CURSO_ITEM\": 3}\n return self.getCursos(params)",
"def genera... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns all idiomas from cadastro >>> self._getCadastroIdiomas() | def _getCadastroIdiomas(self, id_cadastro):
return self.execSql("select_cadastro_idiomas",
id_cadastro=int(id_cadastro)) | [
"def _getCadastroEmpregos(self, id_cadastro):\n return self.execSql(\"select_cadastro_empregos\",\n id_cadastro=int(id_cadastro))",
"def _getCadastroCursos(self, id_cadastro):\n return self.execSql(\"select_cadastro_cursos\",\n id_cadastro=int(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns all cursos from cadastro >>> self._getCadastroCursos() | def _getCadastroCursos(self, id_cadastro):
return self.execSql("select_cadastro_cursos",
id_cadastro=int(id_cadastro)) | [
"def _getCadastroCursosSuperiores(self, id_cadastro):\n return self.execSql(\"select_cadastro_cursos_superiores\",\n id_cadastro=int(id_cadastro))",
"def list_cursos():\n schema = CursoSchema()\n data = Curso.query.all()\n cursos = [schema.dump(c) for c in data]\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns all estagios from cadastro >>> self._getCadastroEstagios() | def _getCadastroEstagios(self, id_cadastro):
return self.execSql("select_cadastro_estagios",
id_cadastro=int(id_cadastro)) | [
"def __getEstados__(self):\n lista=[]\n for x in self.getEstados():\n lista.append(x.getNombre())\n return lista",
"def _reiniciar_estados(self) -> None:\n self.estados: List[Estado] = []\n self.estado: Estado = Estado()\n self.entregou = self.estado.entregou\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns all empregos from cadastro >>> self._getCadastroEmpregos() | def _getCadastroEmpregos(self, id_cadastro):
return self.execSql("select_cadastro_empregos",
id_cadastro=int(id_cadastro)) | [
"def listar_empresas(self):\r\n return list(set([cliente.empresa for cliente in self.clientes]))",
"def get_employees(self):\n from Employee import Employee\n cursor = self.dbconnect.get_cursor()\n cursor.execute('select * from employee')\n\n employees = list()\n for row ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts the CSS shortcut string into a valid innertag. | def process_shortcut(s):
if s.count('[') != s.count(']'):
raise MismatchedGrouping('Invalid grouping of brackets, %s' % s)
if s.count('"') % 2 != 0 or s.count("'") % 2 != 0:
raise MismatchedGrouping('Quotation groupings are mismatched, %s' % s)
ret_dict = {}
# find the classes and id
... | [
"def from_hashtag(self, text):\n # TODO: This is a bad heuristic and you can do better.\n return text.lstrip('#').replace('e', 'e ').upper().strip()",
"def from_shortcuts(self, shortcut_string):\n\n # try to extract source information from shortcut (source info is given in brackets at the end... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a new password reset code returns user | def get_reset_code(self, email):
try:
user = self.get(email__iexact=email)
user.reset_code = self.make_random_password(length=20)
user.reset_code_expire = timezone.now() + timedelta(days=2)
user.save()
return user
except get_user_model().Does... | [
"def request_password_reset():",
"def reset_password(username, code, new_password):\n pass",
"def new_password(self):\n # create new password\n return password_generator.create_password()\n # have password reset",
"def post(self):\n args = passwd_reset_parser.parse_args()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a ramp to the specified ramp parameter. | def add_ramp(self, parameter, start_time, ramp_duration, delta, clear_existing=False):
if clear_existing:
self.parameters[parameter] = [[],[],[]]
self.parameters[parameter][0].append(start_time)
self.parameters[parameter][1].append(ramp_duration)
self.parameters[parameter][2]... | [
"def set_setpoint_ramp(self, ramp=True, output=1, rate=0.1):\r\n if ramp:\r\n ramp = 1 \r\n else:\r\n ramp = 0\r\n try:\r\n gpib_lock.acquire()\r\n self.lakeshore.write('RAMP %i,%i,%f;'%(output,ramp,rate))\r\n except Exception,e:\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Evaluate file cadence to see if it is daily or greater than daily. | def is_daily_file_cadence(file_cadence):
is_daily = True
if hasattr(file_cadence, 'days'):
if file_cadence.days > 1:
is_daily = False
else:
if not (hasattr(file_cadence, 'microseconds')
or hasattr(file_cadence, 'seconds')
or hasattr(file_cadence, ... | [
"def check_filedates(config, data, filename):\n\n min_file_date = re.match(config[\"min_file_date_regex\"], filename)\n max_file_date = re.match(config[\"max_file_date_regex\"], filename)\n\n # Try and convert to date time\n if min_file_date and max_file_date:\n min_file_date = pd.to_datetime(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load CSV data from a list of files into a single DataFrame. | def load_csv_data(fnames, read_csv_kwargs=None):
# Ensure the filename input is array-like
fnames = np.asarray(fnames)
if fnames.shape == ():
fnames = np.asarray([fnames])
# Initialize the optional kwargs
if read_csv_kwargs is None:
read_csv_kwargs = {}
# Create a list of data ... | [
"def importing(files_list):\n\n dataframes = []\n\n for file in files_list:\n imported_df = pd.read_csv(f'full_data/{file}.csv')(file)\n imported_df.columns = imported_df.columns.str.strip().str.lower()\n dataframes.append(imported_df)\n\n return dataframes",
"def parse_df(files: lis... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sum the total of weighted cells in each polygon, compute the unit value (where possible), and write to raster vect = input vector map val = vector map attribute with desired value weights = input rast map with cell weights out = output raster map wcol = weight column in vect (default=name of output raster) deleted prio... | def calcUnitWeight(vect, val, weights, out, wcol=None):
if not wcol:
wcol = out
grass.run_command('v.rast.sum', zones=vect, _input=weights, column=wcol)
grass.run_command('v.db.update', column=wcol, value=val+'/'+wcol,
where='wcol>0')
grass.run_command('v.to.rast', _input=... | [
"def _store_weights_and_measures(self):\n\n ntriw = np.zeros(self.tri.npoints)\n area = np.zeros(self.tri.npoints)\n\n for idx, triangle in enumerate(self.tri.simplices):\n coords = self.tri.points[ triangle ]\n vector1 = coords[1] - coords[0]\n vector2 = coor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets all paths from input to symbol | def get_paths_from(self, symbol):
to_return = []
visitation_queue = [self.head]
while len(visitation_queue) != 0:
visiting = visitation_queue.pop(0)
for elem in visiting.children:
visitation_queue.append(elem)
if symbol in visiting.inputs:
... | [
"def _get_paths(symbol: Union[str, int]) -> str:\n if isinstance(symbol, str):\n return {\n 'circle':\n '\"M\"+b1+\",0A\"+b1+\",\"+b1+\" 0 1,1 0,-\"+b1+\"A\"+b1+\",\"+b1+\" 0 0,1 \"+b1+\",0Z\"',\n 'square':\n '\"M\"+b1+\",\"+b1+\"H-\"+b1+\"V-\"+b1+\"H\"+b1+\"Z\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test surf on regularly spaced coordinates like MayaVi. | def test_surf():
def f(x, y):
sin, cos = numpy.sin, numpy.cos
return sin(x + y) + sin(2 * x - y) + cos(3 * x + 4 * y)
x, y = numpy.mgrid[-7.:7.05:0.1, -5.:5.05:0.05]
s = surf(x, y, f)
mlab.show()
#cs = contour_surf(x, y, f, contour_z=0)
return | [
"def test_contour_surf():\n def f(x, y):\n sin, cos = numpy.sin, numpy.cos\n return sin(x+y) + sin(2*x - y) + cos(3*x+4*y)\n\n x, y = numpy.mgrid[-7.:7.05:0.1, -5.:5.05:0.05]\n s = contour_surf(x, y, f)\n return s",
"def surfcut_points(**kwargs):\n npoints = kwargs.get( 'npoints', 240... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes the data taken from the completeData.csv and the formattedXValues.csv. Note that these must be the names of the arrays in your folder. | def initializeData():
# Read in the CSV
allX = pd.read_csv('completeData.csv', keep_default_na=False)
xValues = pd.read_csv('formattedXValues.csv')
filename = "completeData.csv and formattedXValues.csv"
# Separate the CSV columns into array variables and numpy vars to store new categorical variabl... | [
"def __init__(self, filename):\n temp_data = []\n all_data = []\n columns = None\n\n with open(\"pennymac/data/\" + filename) as f:\n for line in f:\n temp_data = line.split()\n if len(temp_data) > 1:\n if not columns:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For the given datasize from the .csv file generates a set of random indices to use for the training set. Uses a user defined percentage of the data for training and testing. | def generaterandomindices(dataSize, percentTest):
TrainIndices = np.array([])
while TrainIndices.__len__() < int(percentTest * dataSize):
# Randomly select an index value and store it. If it has already been chosen, pick again.
index = int(random.random() * dataSize)
if not TrainIndices... | [
"def loadDataset(filename, split, trainingSet=[], testSet=[]):\n with open('iris.csv', 'r') as datafile:\n lines = csv.reader(datafile)\n dataset = list(lines)\n for i in range(len(dataset)-1):\n for j in range(4):\n dataset[i][j] = float(dataset[i][j])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate an example dask HighLevelGraph. | def dask_highlevelgraph() -> HighLevelGraph:
@dask.delayed(pure=True) # type: ignore
def create_dataframe(num_rows: int, num_cols: int) -> pd.DataFrame:
print('Creating DataFrame...')
return pd.DataFrame(data=[range(num_cols)] * num_rows)
@dask.delayed(pure=True) # type: ignore
def cr... | [
"def create_graph(identifier=None):",
"def generate_graph(store, graph):\n return Graph(store=store, identifier=_format_graph_uri(graph))",
"def test_documentation_popxl_basic_subgraph(self):\n filename = \"basic_graph.py\"\n self.run_python(filename, file_dir=working_dir, working_dir=working_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Since the bcbio object does not retain all the information necessary for some of the templates, this finds and adds the additional information and then fills the template file and writes as the output file. | def __fill_template__(self,template_file,output_fname):
dictionary = {}
for k,v in self.__dict__.iteritems():
if k == 'sample_key':
try:
int(v)
new_sample_key = "Sample_" + str(v)
dictionary.update({k:new_sample_key}... | [
"def _write_files(self):\n\n for src, dest in _walk_files(self.output_dir, False):\n if not os.path.exists(os.path.dirname(dest)):\n util.mkdir(os.path.dirname(dest))\n\n if src.endswith(\".mako\"):\n with open(src, encoding='utf-8') as t_file:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Multiple templates are used for the bcbio process. This wraps filling all templates. | def __fill_all_templates__(self,configs):
template_dir = configs['system'].get('Common_directories','template')
sample_template = os.path.join(template_dir,configs['pipeline'].get('Template_files','sample'))
system_template = os.path.join(template_dir,configs['pipeline'].get('Template_files','sy... | [
"def render_all(pages):\n for page in pages:\n render_template(page['template'], page['output'], page['values'])",
"def initialize_template():\n global template\n blocks = ['title', 'content']\n template = open(template_file, 'r').read()\n for block in blocks:\n template = template.re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Normalizes the inputs JSONRPC endpoints that take a 2tuple of `(ContentKey, bytes)` | def content_key_and_content_munger(
module: Any, content_key: ContentKey, content: bytes,
) -> Tuple[HexStr, HexStr]:
return (
encode_hex(content_key),
encode_hex(content),
) | [
"def decode_PUT_input(self, action, *string_inputs):\n return string_inputs",
"def _split_endpoint_arguments(self):\r\n self.req.not_verified = []\r\n # Python 2 compatibility\r\n # self.req.endpoint_parsed = self.req.endpoint.copy()\r\n self.req.endpoint_parsed = copy(self.req.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load weights from snapshot file | def load_weights(net, optimizer, scheduler, snapshot_file, restore_optimizer_bool=False):
logging.info("Loading weights from model %s", snapshot_file)
net, optimizer, scheduler, epoch, mean_iu = restore_snapshot(net, optimizer, scheduler, snapshot_file,
restore_optimizer_bool)
return epoch, mean... | [
"def loadweights(self, filename):",
"def load_weights(self, filename):",
"def load_weights(self, filepath):\n self.model.load_weights(filepath)",
"def _load_weights(self):\n self.npz_weights = np.load(self._weight_file)\n self._load_byte_embedding()\n self._load_cnn_weights()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if claims user belongs to Tenant or has override permissions to edit other Tenants | def check_tenant_authorization(tenant_id, override_permission=None):
claims = get_jwt_claims()
if "id" in list(claims.keys()):
tenant_user = identity.TenantUser.query.filter_by(id=claims["id"]).first()
if (
tenant_user.tenant_id == tenant_id
or override_permission in tena... | [
"def has_object_permission(self, request, view, obj):\n if request.user.is_superuser:\n return True\n if request.user.profile.role == UserRole.CLIENT and obj.owner != request.user:\n return False\n if request.user.profile.role == UserRole.EXECUTOR and obj.executor != reque... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a tenant schema, create a tenant | def create_tenant(tenant):
exists = identity.Tenant.query.filter_by(name=tenant.name).first()
if exists:
abort(409, "Tenant Already Exists")
db.session.add(tenant)
db.session.commit()
return tenant.id | [
"def create_tenant(self, tenant=None):\r\n\r\n uri = \"\"\"https://{}/api/mo/uni.json\"\"\".format(self.apic)\r\n\r\n if tenant not in self.tenant_array:\r\n\r\n tenants = \"\"\"{\"fvTenant\" : { \"attributes\" : { \"name\" : \"%s\"}}}\"\"\" % tenant\r\n request = self.session.po... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given tenant_id and tenant object, update a Tenant | def update_tenant(tenant_id, new_tenant):
check_tenant_authorization(tenant_id)
new_tenant.id = tenant_id
updated_tenant = db.session.merge(new_tenant)
db.session.commit()
return updated_tenant | [
"def test_tenant_update(sample_identity):\n access_token, tenant, tenant_user, tc = sample_identity\n tenant.name = \"ilovebeansllc\"\n headers = {\"Authorization\": \"Bearer \" + access_token}\n updated_tenant_request = id_schemas.TenantSchema().dump(tenant)\n updated_tenant = tc.put(\n f\"ap... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a tenant id, fetch the tenant for that id | def get_tenant_by_id(tenant_id):
tenant = identity.Tenant.query.filter_by(id=tenant_id).first()
if tenant:
return tenant
abort(404, f"Unable to find tenant with id: {tenant_id}") | [
"def get_tenant_config(tenant_id):\n for tenant in tenants:\n if tenant['tenant_id'] == tenant_id:\n return tenant\n raise errors.BaseTapisError(\"invalid tenant id.\")",
"def get_tenant(key, tenant_name):\n for tenant in key.tenants.list():\n if tenant.name == tenant_name:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provides list of all Tenants | def get_all_tenants():
tenants = identity.Tenant.query.all()
return tenants | [
"def get_tenant_list():\n tenants = Query_Objs(\"fvTenant\", \"tn\")\n tn_list = [\"\"]\n for tn in tenants:\n tn_list.append(tn.name)\n return tn_list",
"def get_tenants(self):\n return self.get_operation(self.PREFIX_LIST[\"TENANTS\"])",
"def get_tenants():\n tenant_list = []\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mark this track as missed (no association at the current time step). | def mark_missed(self):
if self.state == TrackState.Tentative:
self.state = TrackState.Deleted
elif self.time_since_update > self._max_age:
self.state = TrackState.Deleted | [
"def addTrack(self, track):\n if track not in self.__tracks:\n self.__tracks[track] = None",
"def mark_as_not_done(self):\n grade_event = {'value': 0, 'max_value': self.points}\n self.runtime.publish(self, 'grade', grade_event)",
"def set_board_value_miss(self, point):\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if this track is confirmed. | def is_confirmed(self):
return self.state == TrackState.Confirmed | [
"def is_confirmed(self) -> bool:\n return self._is_confirmed",
"def IsConfirmedUser(self):\r\n return www_util.IsConfirmedCookie(self.confirm_time)",
"def account_verified(self):\n return self.instance.connect_account and self.instance.connect_account.status == 'verified'",
"def is_email_conf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
WYpisuje informacje o samochodzie | def wypisz_info(self):
print(f"Samochód: {self.producent} {self.model}") | [
"def mostra_informacao(self):\n\n pass",
"def info(self):\n messagebox.showinfo(\"Informacje\", \"Część pracy inżynierskiej pt. 'System automatyzacji uprawy drzewka bonsai'\" +\n \". Aplikacja służy do zarządzania oraz sterowania systemem a także do zbierania danych.\" +\n \"Wykonał Da... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load all images in the specified file and returns an array with all of them. | def loadImages(loadPath):
img_array = []
for filename in glob.glob(loadPath):
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width, height)
img_array.append(img)
return img_array | [
"def get_images(self, file_path: str) -> Iterable[Image]:\n return []",
"def load_images(file_dir):\n x = np.load(file_dir + \"/x.npy\")\n y = np.load(file_dir + \"/y.npy\")\n return x, y",
"def loadImages(file, tiles):\n array = []\n image = wx.Image(file, wx.BITMAP_TYPE_PNG)\n \n w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take some English text and return a Pirateish version thereof. | def translate(english):
# Normalise a list of words (remove whitespace and make lowercase)
words = [w.lower() for w in english.split()]
# Substitute some English words with Pirate equivalents.
result = [_PIRATE_WORDS.get(word, word) for word in words]
# Capitalize words that begin a sentence and pot... | [
"def unpack_english_contractions(text):\n\n text = re.sub(\n r\"(\\b)([Aa]re|[Cc]ould|[Dd]id|[Dd]oes|[Dd]o|[Hh]ad|[Hh]as|[Hh]ave|[Ii]s|[Mm]ight|[Mm]ust|[Ss]hould|[Ww]ere|[Ww]ould)n't\",\n r'\\1\\2 not',\n text,\n )\n text = re.sub(\n r\"(\\b)([Hh]e|[Ii]|[Ss]he|[Tt]hey|[Ww]e|[Ww]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |