query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Tests that the function's output's 'treat` column is an int column | def test_stochatreat_output_treat_col_dtype(treatments_dict):
treatments_df = treatments_dict["treatments"]
assert treatments_df["treat"].dtype == np.int64, "Treatment column is missing" | [
"def returns_int(self):\n return \"int\" in self.return_type",
"def test_output_ints():\n output = filter_distances(point=x, data=df, threshold=threshold)\n\n assert(all(isinstance(x, int) for x in output))",
"def check_int(series):\n if series.nunique() == 2:\n # Possibly boolean\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that the function's output's 'block_id` column is an int column' | def test_stochatreat_output_block_id_col_dtype(treatments_dict):
treatments_df = treatments_dict["treatments"]
assert treatments_df["block_id"].dtype == np.int64, "Block_id column is missing" | [
"def test_output_ints():\n output = filter_distances(point=x, data=df, threshold=threshold)\n\n assert(all(isinstance(x, int) for x in output))",
"def test_integer(self):\n conn = self.database.connection()\n cursor = conn.cursor()\n dialect = self.database.dialect()\n dbapi = se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that the function's output's 'idx_col` column is the same type as the input' | def test_stochatreat_output_idx_col(treatments_dict):
treatments_df = treatments_dict["treatments"]
data = treatments_dict["data"]
idx_col = treatments_dict["idx_col"]
assert treatments_df[idx_col].dtype == data[idx_col].dtype, "Index column is missing" | [
"def test_assert_output_series_dtypes(self):\n\n try:\n num_variables = len(iec_calc.pd_obj_out.columns)\n #get the string of the type that is expected and the type that has resulted\n result = pd.Series(False, index=list(range(num_variables)), dtype='bool')\n expe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that overall treatment assignment proportions across all strata are as intended when strata are such that there are only misfits | def test_stochatreat_only_misfits(probs):
N = 1_000
df = pd.DataFrame(
data={
"id": np.arange(N),
"block": np.arange(N),
}
)
treats = stochatreat(
data=df,
block_cols=["block"],
treats=len(probs),
idx_col="id",
probs=probs,
... | [
"def identified_attributes_percentage(results_data, results_columns) :\n \n #identify the attributes that have been correctly identified\n results = results_data[results_columns].mode().transpose()[0]\n for c in results_columns :\n if 'rmse' in c :\n results[c] = True if results[c] == ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tests that the function returns the right number of block ids | def test_stochatreat_block_ids(df, block_cols):
treats = stochatreat(
data=df,
block_cols=block_cols,
treats=2,
idx_col="id",
random_state=42,
)
n_unique_blocks = len(df[block_cols].drop_duplicates())
n_unique_block_ids = len(treats["block_id"].drop_duplicates()... | [
"def num_blocks(self): # -> int:\n ...",
"def test_get_last_n_blocks(self):\n\n number_of_blocks = 5\n wait_for_block(self.network, 5)\n for validator_id in range(self.network.validators_count()):\n host, public_port, private_port = self.network.api_address(validator_id)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
decorated method should be called if `enabled` is True | def test_require_enabled_call_method(self):
method = MagicMock(return_value=True)
decorated = require_enabled(method)
self = MagicMock()
self.enabled = True
self.assertTrue(decorated(self))
self.assertTrue(method.called) | [
"def execute_if_enabled(f):\n @functools.wraps(f)\n def wrapper(self, *args, **kwargs):\n if not self._enabled:\n return\n return f(self, *args, **kwargs)\n return wrapper",
"def test_require_enabled_do_not_call_method(self):\n method = MagicMock(return_value=True)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
decorated method should not be called if `enabled` is False | def test_require_enabled_do_not_call_method(self):
method = MagicMock(return_value=True)
decorated = require_enabled(method)
self = MagicMock()
self.enabled = False
self.assertIsNone(decorated(self))
self.assertFalse(method.called) | [
"def execute_if_enabled(f):\n @functools.wraps(f)\n def wrapper(self, *args, **kwargs):\n if not self._enabled:\n return\n return f(self, *args, **kwargs)\n return wrapper",
"def disable(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n return func(*args, **kwa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build package for each os and upload to conda | def build_and_upload(python_version, package, vers):
vspl = python_version.split('.')
python_string = vspl[0] + vspl[1]
current_os = get_current_os()
cmd = ('conda build --old-build-string conda.recipe '
'--output-folder artifacts '
'--no-anaconda-upload --python {python_version}')... | [
"def build_packages(update_list, nodeps):\n if nodeps:\n options = '-fcd'\n else:\n options = '-fc'\n for pkg, dir in update_list.items():\n subprocess.run(['makepkg', options], cwd=dir)\n # put the package in the repo directory\n for tar in dir.iterdir():\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replace version in `meta.yaml` file so that it doesn't need to be updated for each release | def replace_version(version):
filename = 'conda.recipe/meta.yaml'
pattern = r'version: .*'
replacement = 'version: {version}'.format(version=version)
lines = []
with open(filename) as meta_file:
for line in meta_file.readlines():
lines.append(re.sub(pattern, replacement, line))
... | [
"def update_metadata(metadata, version):\n with open(metadata.option_source('general', 'version'), 'r+b') as fp:\n rawMetadata = fp.read()\n rawMetadata = re.sub(\n r'^(\\s*version\\s*=\\s*).*', r'\\g<1>%s' % version,\n rawMetadata, flags=re.I | re.M,\n )\n\n fp.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
initializes stored procedure information | def construct_sp(self, info):
if "query" in info.keys():
if info["query"].upper().startswith("CALL"):
self.q_str = info["query"]
self.sql_type_ind = (info["q_type_ind"] if "q_type_ind" in info.keys() else
sql_type.STORED_PROCEDURE_... | [
"def _create_query_data(self) -> dict:\n return {\n \"dbname\": self._dbname,\n \"proc_name\": self._name\n }",
"def init(self):\n self.init_db_header()\n self.load_segments()",
"def load(cls):\n \n # Loop through procedures and build patient procedure... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
append element to current q_str using user spec'd split | def append_query_element(self, val, append=", "):
self.q_str = append.join([self.q_str, val]) | [
"def __string_splitter(self, arr, string, split_length):\n if len(string) < split_length:\n arr.append(string)\n return arr\n else:\n arr.append(string[:split_length])\n return self.__string_splitter(arr, string[split_length:], split_length)",
"def _append... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
cleans final element if ends with search (default='), \n') | def clean_query_element(self, search="), \n", replace=");"):
if len(search) > 1 and self.q_str.endswith(search):
ln1 = len(search)
self.q_str = self.q_str[:-ln1] + replace | [
"def clear_useless_end(input_string):\n input_string = input_string.strip()\n while input_string.endswith(\",\"):\n input_string = input_string[:-1]\n return input_string",
"def delete_last_comma(text):\n return text[:-1] + text[-1].replace(',', '')",
"def remove_last_char_from_search_string(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates SQL table from query string | def calc_table_name(q_str, qtype):
table = None
q_split = q_str.split() # Quick split => all white space throws away empties
if qtype is sql_type.SELECT:
fnd = False
for itm in q_split:
if itm.upper() == "FROM":
fnd = True
elif fnd and itm != "":
... | [
"def build_table_list(sql_str):\n query_no_comments = remove_comments(sql_str)\n logger.info(f\"sql_str: {sql_str}\")\n logger.info(f\"query_no_comments: {query_no_comments}\")\n tables = get_tables(sql_str)\n return tables",
"def get_tables(sql_str, from_clause):\n # start with text between FRO... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This crossover is specific to floatingpoint representation. Simulate behavior of onepoint crossover for binary representations. For large values of eta there is a higher probability that offspring will be created near the parents. For small values of eta, offspring will be more distant from parents Equation 9.9, 9.10, ... | def crossover_simulated_binary(
self,
parent1,
parent2,
eta: float
):
# Calculate Gamma (Eq. 9.11)
rand = self.rng.random(parent1.shape)
gamma = np.empty(parent1.shape)
gamma[rand <= 0.5] = (2 * rand[rand <= 0.5]) ** (1.0 / (eta + 1)) ... | [
"def test_single_point_crossover(self):\n # Method should fail if parents do not have same number of variables\n parent2 = Solution(self._problem, [1] * (self._variable_count + 1))\n self.assertRaises(\n ValueError, lambda: gm.uniform_crossover(self._parent1, parent2))\n\n pr ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A Function that splits the conversations in sentences. | def split_on_sentences(conversations):
sentence_list = []
for conversation in conversations:
for sentences in conversation:
token_sen = tokenize.sent_tokenize(sentences)
for sentence in token_sen:
if sentence != 'Patient:' and sentence != 'Doctor:':
... | [
"def splitInSentence(self,text):\n return self._support.splitInPhrase(text)",
"def split_conversation(conversation):\n if len(conversation) <= 10:\n return\n else:\n conversations = []\n for start in range(0, len(conversation) - 10, 5):\n conversations.append(conversat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A function that preprocesses the data (so that it is displayed per sentence), and saves is as a .csv file for later use. | def preprocess_to_csv(data_path, save_to):
# Split on dialogue
conversations = split_on_dialogue(data_path)
# Split on sentence
sentences = split_on_sentences(conversations)
# Make dataframe and drop dubplicates
df_sent = pd.DataFrame(np.array(sentences), columns=['sentences'])
df_sent.dr... | [
"def output(data): #This will store the data into a csv file in desired format\n if(len(data[0].text)>=3):\n f.write(dt_string+\",\"+data[0].text.replace(',','')+\",\"+data[1].text.replace(',','')+\",\"+data[2].text.replace(',','')+\",\"+data[3].text.replace(',','')+\",\"\n +data[4].text.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function takes in the prediction of a sentence of the pretrained model and returns the symptoms mentioned in that sentence. | def get_predicted_symptoms(prediction):
symptoms = []
# Check if there is a predicted entity
if len(prediction[0]['entity']) > 0:
number_of_entities = len(prediction[0]['entity'])
# Loop over predicted entities and get symptoms (here called: disease)
for i in range(num... | [
"def pred_sentence(self):\r\n output_sentence = ' '.join(self.predicted_words)\r\n return output_sentence",
"def sentence_prediction(self, sentence, echo=False):\n sentence = norm_input(sentence)\n sentence = self.typing_errors(sentence)\n sent_seq = self.tokenizer_x.texts_to_se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Because finding primes (especially the first 100 primes) has been done many times before, we can simply lookup the answer and hardcode it into a template. While this doesn't really count as 'computation,' it still can be useful by serving as an acceptance test for the other techniques. | def precomputed(request):
return {'name': 'Precomputed Primes'} | [
"def problem_7():\n primes_found = 0\n current_num = 2\n\n while True:\n # Is it prime?\n is_prime = True\n for i in range(2, int(current_num ** 0.5) + 1):\n if i != current_num and current_num % i == 0:\n is_prime = False\n break\n\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Combining the serverside and clientside examples, we can perform the computation in both places. In this particular example, we only calculate a subset of the results on the serveside and then redo the entire computation on the clientside. While not an exceedlingly practical example, performing computations in both pla... | def server_and_clientside(request):
return {'name': 'Primes computed on the client and server-side',
'primes': ", ".join([str(prime) for prime in sieve(100)])} | [
"def master(client, data, column_name):\n\n # Info messages can help you when an algorithm crashes. These info\n # messages are stored in a log file which is send to the server when\n # either a task finished or crashes.\n info('Collecting participating organizations')\n\n # Collect all organization ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Not all web applictions use a relational database as their data layer, but many nosql databases are also capable of performing computations. Using redis' support for lua scripts we can [implement our sieve in | def redis_script(request):
r = redis_connection()
sieve = r.register_script(sieve_lua)
primes = sieve(args=[LAST_PRIME])
return {'name': 'Primes computed with a Redis script',
'primes': ", ".join([str(prime) for prime in primes])} | [
"def mem_query():\n\n start = time.time()\n query = \"select * from fatality where Fatality_SEX='M'or fatality_location like '%open'\"\n query1 = \"select count(*) from fatality where Fatality_SEX='M'or fatality_location like '%open'\"\n cache = memc.get(\"query\" + str(1))\n if not cache:\n \... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle velocitybased movement requests. | def cmdVelCallback(self, req):
x = req.linear.x # m/s
th = req.angular.z # rad/s
if x == 0:
# Turn in place
right = th * self.wheel_track * self.gear_reduction / 2.0
left = -right
elif th == 0:
# Pure forward/backward mot... | [
"def _cb_cmd_vel(self,msg):\r\n print \"Walker velocity command received: \",msg\r\n vx=msg.linear.x\r\n vy=msg.linear.y\r\n vt=msg.angular.z\r\n self.start()\r\n self.set_desired_velocity(vx,vy,vt)",
"def velocity(self, vel):\n self.messenger.call('kVelocity',vel)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
load the world from a file | def loadWorld(self, filename):
worldFile = open(filename, 'r');
for line in worldFile:
info = line.split(' ');
if(info[0]=="WIDTH"):
self.mWidth = int(info[1]);
elif info[0] == "HEIGHT":
self.mHeight = int(info[1]);
elif in... | [
"def from_file(cls, filename, world):\n with open(filename, 'r') as myFile:\n text = myFile.readlines()\n\n rows = len(text)\n columns = len(text[0])\n newWorld = world(rows, columns)\n for rowNumber, row in enumerate(text):\n for columnNumber, cellText in en... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save the world in to a file | def saveWorld(self, filename):
worldFile = open( filename, 'w' );
worldFile.write( "WIDTH {0}\nHEIGHT {1}\n".format( self.mWidth, self.mHeight ) );
for space in self.mSpaces:
if isinstance(space, Circle):
worldFile.write( "SPACE circle {0} {1} {2}\n".format( space.X,... | [
"def _save_to_file(self, world, is_smart):\n filepath = self._get_filepath(world._generating_city_name, is_smart, world._generating_scale)\n assert not os.path.exists(filepath), \"File '%s' already exists!\" % filepath\n log.info(\"Saving the new results to {} ...\".format(filepath))\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes an iterable to a CSV file. | def CSVWriter (iterable, outLoc, header="", ):
if not iterable:
print ("nothing to write")
return 0
out = open(outLoc, 'w')
if header:
out.write(header+'\n')
#Only works if iterable is a nested list
for member in iterable:
for item in member:
out.write(... | [
"def save_iterable_as_csv(iterable, file_name='urnai_iterable_' + time.strftime('%Y%m%d_%H%M%S'),\n directory=expanduser('~'), convert_to_int=False, convert_to_string=False,\n delimiter=','):\n if '.csv' not in file_name:\n file_name += '.csv'\n\n csv = N... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
parses .tail file into a nested list usable by other modules | def tailParser(inLoc):
f = open(inLoc, 'r')
tails = f.readlines()
f.close()
tailList = []
for i in range(len(tails)):
if i==0: continue #skips the header
line = tails[i].rstrip().split(',')
tailList.append(line)
return tailList | [
"def BuildTailList(all_file_contents):\n tail_list = []\n list_all_file_contents = (all_file_contents)\n tail_start = False\n for line in list_all_file_contents:\n word = line[0:3]\n if word == \"TER\":\n tail_start = True\n if tail_start == True:\n tail_list.a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads a file in gettext .po format | def read_po(self, inputfile):
is_index = False
lines = inputfile.readlines()
index = ''
value = ''
for line in lines:
if line.startswith('#'):
continue
elif line.startswith('msgid'):
is_index = True
self.translations[index] = value
index = ''
value... | [
"def parse_django_po(po_filename):\n # Holds the header at the top of the django po file\n header = ''\n # A sentinel to know when to stop considering lines part of the header\n header_done = False\n # The return dict of Message to code ref 'file:line_num'\n message_to_ref = {}\n # The current ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads in a translation file in json format. | def read_json(self, inputfile):
transtransfile = json.load(inputfile)
self.language = transfile['lang']
self.translations = transfile['strings'] | [
"def get_translation_dict_from_file(path, lang, app):\n\tjson_content = {}\n\tif os.path.exists(path):\n\t\twith open(path, 'r') as f:\n\t\t\tjson_content = json.loads(f.read())\n\n\treturn json_content",
"def json_read(self):\n\n with open(self.file_name, 'r') as f_obj:\n return(json.load(f_obj... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes a new translation file in quoted csv format. | def write_csv(self, outputfile):
d = csv.writer(outputfile, quoting=csv.QUOTE_ALL)
for row in self.translations.iteritems():
d.writerow(row) | [
"def write_csv_file(path, app_messages, lang_dict):\n\tapp_messages.sort(key=lambda x: x[1])\n\n\twith open(path, \"w\", newline=\"\") as msgfile:\n\t\tw = writer(msgfile, lineterminator=\"\\n\")\n\n\t\tfor app_message in app_messages:\n\t\t\tcontext = None\n\t\t\tif len(app_message) == 2:\n\t\t\t\tpath, message = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes a translation file in json format. | def write_json(self, outputfile):
outputfile.write(json.dumps(self.translations,
sort_keys=True, indent=4)) | [
"def write(self, _filepath=None):\n _json_txt = json.dumps(self.json_dict, indent=2)\n self._write_json_text(_json_txt, _filepath)",
"def _write_json(self):\n with open(self._file_path, 'w') as f:\n json.dump(self._content, f, indent=4, separators=None,\n encod... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes a translation file in java properties format. | def write_properties(self, inputfile):
raise NotImplementedError(
"Writing to this file format is not yet implemented") | [
"def write_properties(self, prop_filename):\n # Collect list of all keys in self.plats that have True values,\n # but change \"windows\" to \"win64\" because build-sanity is annoying.\n sanity_plats = [\n (x if x != \"windows\" else \"win64\")\n for x in self.plats.keys() ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets up Reactbased interface if required. | def run(self):
super().run()
if self.react_interface is not None:
self.setup_react_interface(
os.path.join(
getattr(self, self.__react_path_attr__),
'lingvodoc')) | [
"def setup_react_interface(self, lingvodoc_dir):\n\n self.announce('Installing React-based interface')\n\n interface_dir = os.path.expanduser(self.react_interface)\n\n index_from_path = os.path.join(interface_dir, 'index.html')\n\n index_to_path = os.path.join(lingvodoc_dir,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets up Reactbased interface by copying its distribution files to appropriate locations. | def setup_react_interface(self, lingvodoc_dir):
self.announce('Installing React-based interface')
interface_dir = os.path.expanduser(self.react_interface)
index_from_path = os.path.join(interface_dir, 'index.html')
index_to_path = os.path.join(lingvodoc_dir,
'views', 'v2'... | [
"def run(self):\n\n super().run()\n\n if self.react_interface is not None:\n\n self.setup_react_interface(\n\n os.path.join(\n getattr(self, self.__react_path_attr__),\n 'lingvodoc'))",
"def static_react(ctx, **_):\n # type: (click.C... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tries to determine version info from the Git repository and pip installation state, saves it to 'lingvodoc/version.py' if required. | def run(self):
version_str = (
get_git_version(here))
version_uniparser_dict = (
get_uniparser_version())
if (version_str is not None or
version_uniparser_dict is not None):
with open(
os.path.join(here, 'lingvodoc', 'version.py... | [
"def find_package_version(self):\n res = {\n 'pip_version': None,\n 'pip_url': None,\n 'pip_requirement': None,\n 'pkg_resources_version': None,\n 'pkg_resources_url': None,\n 'git_tag': None,\n 'git_commit': None,\n 'git... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
API Call for county stats | def get_covid_stats_by_county(state, county):
url = "https://corona.lmao.ninja/v2/jhucsse/counties/" + county
response = requests.get(url)
data = response.json()
counties = []
for res in data:
if res["province"] == state:
county1 = res["county"]
updatedAt = res["updat... | [
"def get_county() -> Dict:\n\n # Load data model template into a local dictionary called 'out'.\n out = get_data_model()\n\n # populate dataset headers\n out[\"name\"] = \"Alameda County\"\n out[\"source_url\"] = landing_page\n out[\"meta_from_source\"] = get_notes()\n\n # fetch cases metadata,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test invoking the import parameter command in all variants. | def test_cmd_param_import(run_cli_command):
from shutil import copyfile
from aiida_fleur.cmdline.data.parameters import cmd_param_import
options = [SI_INPXML_FILE, '--fleurinp']
run_cli_command(cmd_param_import, options=options)
options = [SI_INPXML_FILE, '--fleurinp', '--dry-run']
run_cli_com... | [
"def test_cmd(self):\n imp_file = imp.import_cmd(app)\n self.assertTrue(bool(imp_file) is True, 'CMD function failed ')",
"def test_preset_import(): \n\tdef test(): \n\t\t\"\"\" \n\t\tTest the import of the preset yield file \n\t\t\"\"\" \n\t\ttry: \n\t\t\tfrom vice.yields.presets import vice_dummy_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an exception indicating a PyXBrelated problem. If no args are present, a default argument is taken from the C{message} keyword. | def __init__ (self, *args, **kw):
if 0 == len(args) and 'message' in kw:
args = (kw.pop('message'),)
self._args = args
self._kw = kw
super(PyXBException, self).__init__(*args) | [
"def create_exception(self, msg: str):",
"def create_exception(self, msg):\n return Exception(msg)",
"def exception(self, msg, *args, **kwargs):\n if args:\n try:\n msg = msg % args\n except TypeError:\n log.exception_orig(_('Wrong format of a lo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The QName of the L{node} as a L{pyxb.namespace.ExpandedName} | def __get_node_name (self):
import pyxb.namespace
return pyxb.namespace.ExpandedName(self.node.namespaceURI, self.node.localName) | [
"def get_fully_qualified_name(self, node):\r\n return self._send({'name': 'getFullyQualifiedName', 'args': [node]})",
"def full_qname(self):\n return self.namespace + \".\" + self.app_name",
"def qname(self, prefix, name):\n\t\treturn element_tree.QName(self.xml_namespaces[prefix], name)",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Step the simulator through step_size using zeroorder hold of estmd_input as the stimulus. | def step(self, step_size, estmd_input=None):
if estmd_input and estmd_input is not None:
estmd_mapped_input = self.map_estmd_input(estmd_input=estmd_input)
if self.verbose_debug:
print "Mapped input"
print estmd_mapped_input
self.simulator.loa... | [
"def step(self, d=1):\n raise NotImplementedError()",
"def simStepSize(self, stepsize):\n self.simulation.stepSize = stepsize",
"def step(self, batch_size: int):\n raise NotImplementedError(\"`step` must be implemented by concrete evaluator.\")",
"def step(self, state):",
"def step(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Map the estmd input indexed by (x,y) to estmd input indexed by (compartment.idx) | def map_estmd_input(self, estmd_input):
return np.array([(self.estmd_mapping[(x, y)], stimulus) for y, x, stimulus in estmd_input]) | [
"def _map_data(self, point):\n index_mapper = self.component.index_mapper\n value_mapper = self.component.value_mapper\n if self.component.orientation == 'h':\n ndx = index_mapper.map_data(point[0])\n val = value_mapper.map_data(point[1])\n else:\n ndx = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the voltages from CUDA device Indexed like [time,compartment] | def get_voltages(self):
if self.v is None or self.dirty is True:
v = self.simulator.get_voltages()
n_compartments = self.neuron_collection.total_compartments()
self.v = np.array(v).reshape([len(v) / n_compartments, n_compartments])
self.dirty = False
t = int(... | [
"def voltage(self):\n return [\n self.channel[i].voltage for i in range(self._channel_count)\n ]",
"def get_all_voltages(self):\n self.check_validity()\n\n return self.ipcon.send_request(self, BrickletIndustrialDualAnalogInV2.FUNCTION_GET_ALL_VOLTAGES, (), '', 16, '2i')",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the recovery variables from CUDA device Each array is indexed [time,compartment] | def get_recovery_variables(self):
if self.m is None or self.dirty is True:
m, n, h = self.simulator.get_recovery_variables()
n_compartments = self.neuron_collection.total_compartments()
self.m = np.array(m).reshape([len(m) / n_compartments, n_compartments])
self.n... | [
"def get_at_device_Set(self, act='F'): \n varNames = ['idx_at_%s' %act, 'CT'] \n try:\n idx, CT = [getattr(self, var) for var in varNames]\n except AttributeError:\n idx, CT = [self.load(var) for var in varNames]\n if act == 'HB':\n idx[-1] = False # av... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot the spikes for each of the electrodes | def plot_spikes(self, show=False, save_path=None, expand = False):
spikes = np.array(self.spike_history)
spike_time, e_idx = np.where(spikes)
spike_time = spike_time.astype('float32')
spike_time *= self.global_dt
spike_time_pair = zip(e_idx,spike_time)
spike_time_pair.sor... | [
"def plot_spikes(self, ax, spiketimes, gid, y_min=0, y_max=1, lw=1):\n for s in spiketimes:\n ax.plot((s, s), (y_min+0.1, y_max-.1), c=self.color_dict[gid], lw=lw)",
"def draw_spike_times(spike_times):\n for line in spike_times:\n plt.axvline(x=line, color='y')",
"def plot_energies(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns relative index for the middle frame in sequence. | def get_seq_middle(seq_length):
half_offset = int((seq_length - 1) / 2)
return seq_length - 1 - half_offset | [
"def get_middle():\n num_list = session_attributes[NUMBER_LIST_KEY]\n return num_list[round(len(num_list) / 2) - 1] # Subtract 1 since arrays start at 0",
"def get_middle_position(self):\n a=self.adjustment\n return self.pixel2unit( a.value + a.page_size / 2, absolute=True )",
"def fetch_mi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true if obj is a numpy array. | def is_a_numpy_array(obj):
return type(obj).__module__ == np.__name__ | [
"def _is_array(obj):\r\n return isinstance(obj, np.ndarray)",
"def is_numpy(obj):\n return 'numpy' in str(type(obj))",
"def is_arraylike(obj):\n if isinstance(obj, list):\n return True\n elif isinstance(obj, np.ndarray):\n return True\n elif isinstance(obj, pd.Series):\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns dict of variables to restore from ImageNetcheckpoint. | def get_imagenet_vars_to_restore(imagenet_ckpt):
vars_to_restore_imagenet = {}
ckpt_var_names = tf.contrib.framework.list_variables(imagenet_ckpt)
ckpt_var_names = [name for (name, unused_shape) in ckpt_var_names]
model_vars = tf.global_variables()
for v in model_vars:
if 'global_step' in v... | [
"def _restore_variables(self, checkpoint):\n checkpoint_variables_map = list_variables(checkpoint)\n valid_variable = lambda name: name.startswith('model/encoder') or \\\n name.startswith('model/decoder')\n checkpoint_variable_names = [name for (name, _) in checkpoint_varia... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns multiple intrinsic matrices for different scales. | def get_multi_scale_intrinsics(intrinsics, num_scales):
intrinsics_multi_scale = []
# Scale the intrinsics accordingly for each scale
for s in range(num_scales):
fx = intrinsics[0, 0] / (2 ** s)
fy = intrinsics[1, 1] / (2 ** s)
cx = intrinsics[0, 2] / (2 ** s)
cy = intrinsics... | [
"def getScalingMatrix(sx, sy, sz):\n return MatrixExtended([\n [sx, 0, 0, 0],\n [0, sy, 0, 0],\n [0, 0, sz, 0],\n [0, 0, 0, 1]])",
"def get_scale_matrix():\n scale = 170 / 1.5\n return OpenMaya.MMatrix(\n [\n 1.0 * scale, 0.0, 0.0, 0.0,\n 0.0, -1.0 * scale... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pack depth predictions as a single .npy file | def pack_pred_depths(pred_dir, test_file):
test_images = read_text_lines(test_file)
save_name = 'pred_depth.npy'
output_file = os.path.join(pred_dir, save_name)
img_height = 128
img_width = 416
all_pred = np.zeros((len(test_images), img_height, img_width))
for i, img_path in enumerate(te... | [
"def dump_npy(filename: str, obj, **kwargs):\n return np.save(filename, obj)",
"def depth_write(filename, depth):\n height,width = depth.shape[:2]\n f = open(filename,'wb')\n np.array(TAG_FLOAT).astype(np.float32).tofile(f)\n np.array(width).astype(np.int32).tofile(f)\n np.array(height).astype(n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function implements an iterator for searching a gtk.TextBuffer for a certain string. It supports forward and backwards search. It also supports finding from the start or from where the cursor is located. | def search_iterator (text_buffer, search_text, find_forward = True, start_in_cursor = True):
if start_in_cursor:
bounds = text_buffer.get_selection_bounds ()
if len (bounds) == 0:
text_iter = text_buffer.get_iter_at_mark(text_buffer.get_insert())
else:
text_iter = fi... | [
"def searchNext(self,searchStr):\n\n\t\t#编码\n\t\tsearchStr = unicode(searchStr)\n\n\t\tresult = None;\n\t\tif len(self.lines) == 0:\n\t\t\treturn None;\n\n\t\twhile self.currentPosition.row < len(self.lines):\n\t\t\ti = self.lines[self.currentPosition.row].find(searchStr,self.currentPosition.column)\n\t\t\tif i==-1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mutative removal of squares that correspond to only one blank (since we only want to save overlaps) | def clean_overlapping(overlapping):
remove = []
for square in overlapping:
if len(overlapping[square]) == 1:
remove.append(square)
for square in remove:
overlapping.pop(square)
return overlapping | [
"def _prune(self):\n mask = ~equivalent(self.data, self.fill_value)\n self.coords = self.coords[:, mask]\n self.data = self.data[mask]",
"def uncover_blanks(self, row, col):\n checked = {}\n to_be_checked = []\n to_be_checked.append((row, col))\n while len(to_be_ch... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a dictionary mapping blank number (index) to the number of conflicts the blank's word assignment cause | def check_conflicts(overlapping, vocab_used):
conflicts = {}
for square in overlapping:
overlapped_blanks = overlapping.get(square)
# if word at blank is used multiple times add a conflict for the corresponding blank
for blank in overlapped_blanks:
if blank.index not in confl... | [
"def computeWordDict(self):\n if(len(self.goodWord) == 0):\n for num in xrange(self.r):\n self.goodWord[num] = self.numToWord(num)",
"def bigrams(words):\n d = DefaultDict(DefaultDict(0))\n for (w1, w2) in zip([None] + words, words + [None]):\n d[w1][w2] += 1\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a tuple (sum of all conflicts, list of blanks with conflicts) | def sum_conflicts(conflicts, blanks_list):
sum_con = 0
conflict_blanks = []
for b in conflicts:
if conflicts[b]:
conflict_blanks.append(blanks_list[b])
sum_con += conflicts[b]
return sum_con, conflict_blanks | [
"def conflicts(self):\n return minsets(self.prove_all_ass(['false']))",
"def check_conflicts(overlapping, vocab_used):\n conflicts = {}\n for square in overlapping:\n overlapped_blanks = overlapping.get(square)\n # if word at blank is used multiple times add a conflict for the correspon... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if given value is in the given source | def check_list(source, value):
try:
return value in json.loads(source)
except:
return False | [
"def is_in(input_: str, value: list) -> bool:\n return input_ in value",
"def contains(value, arg):\r\n return arg in value # pragma: no cover\r",
"def in_bwlist(self, doc_id, source) -> bool:\n # Convert doc_id to string if it was int type\n if type(doc_id) == int:\n doc_id ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print all the table names in this database. | def print_all_tables(self):
conn = self.connect()
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
print(cursor.fetchall()) | [
"def print_database(self):\n table_names = self.catalog\n for table_name in table_names:\n table = self.parse_table(table_name)\n if not table:\n continue\n print(f'TABLE NAME: {table_name}\\r\\n')\n print(tabulate(table, headers=\"keys\"))\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Printable representation of Restaurant model. | def __repr__(self):
return f'<Restaurant id: {self.id}>' | [
"def __repr__(self):\n\n return \"<Restaurant {name}>\".format(name=self.name)",
"def __repr__(self):\n return f'<RestaurantProduct restaurant: {self.restaurant_id} product: {self.product_id}>'",
"def __repr__(self):\n return f'<RestaurantCourier restaurant: {self.restaurant_id} courier: {s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a printable representation of the Courier model. | def __repr__(self):
return f'<Courier id: {self.id}>' | [
"def __str__(self):\n\n str_representation = \\\n + 80 * \"_\" + os.linesep \\\n + 80 * \"-\" + os.linesep\n str_representation += \\\n (\"Transcript(object):\\t\" +\n self.transcript_id +\n os.linesep)\n str_representation += \\\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Printable representation of RestaurantCourier model. | def __repr__(self):
return f'<RestaurantCourier restaurant: {self.restaurant_id} courier: {self.courier_id}>' | [
"def __repr__(self):\n\n return \"<Restaurant {name}>\".format(name=self.name)",
"def __repr__(self):\n return f'<Restaurant id: {self.id}>'",
"def __repr__(self):\n return f'<RestaurantProduct restaurant: {self.restaurant_id} product: {self.product_id}>'",
"def __repr__(self):\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Printable representation of RestaurantProduct model. | def __repr__(self):
return f'<RestaurantProduct restaurant: {self.restaurant_id} product: {self.product_id}>' | [
"def __repr__(self):\n\n return \"<Product: {}>\".format(self.name)",
"def __repr__(self):\n\n return \"<Restaurant {name}>\".format(name=self.name)",
"def __repr__(self):\n return f'<Restaurant id: {self.id}>'",
"def __repr__(self):\n return f'<RestaurantCourier restaurant: {self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Psuedo code Input > Prediction file for Hand fingers, Foot fingers, Wrists and Hand IP joints, including the joint IDS and Labels for the Joint patches Specify type of prediction file associated Mapping file with the relevent column names to be given to the Prediction files Patient ID list in the test set without JPG e... | def get_final_submission_file(check, joint_type, prediction_type, mapping_file, PATIENT_ID_LIST):
if joint_type in ['wrist', 'hand_ip']:
check['Patient_ID'] = check['Joint_image_ID'].str.split("-", expand=True)[0]
check['limb_name'] = check['Joint_image_ID'].str.split("-", expand=True)[1]
c... | [
"def get_prediction_files(test_path, joint_model_path_mapping, \n mapping_file, column_mapping, erosion_cols, narrowing_cols,\n image_batch_array):\n final_prediction_file = pd.DataFrame()\n for joint_type in joint_model_path_mapping.keys():\n #Dependenc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Input > Joints_path list, test_images_path, joint_image_mapping_dict, Joint_models_mapping_dict, column_mapping_file, all_columns_in_prediction_file, erosion_cols, narrowing_cols Output > Final prediction file | def get_prediction_files(test_path, joint_model_path_mapping,
mapping_file, column_mapping, erosion_cols, narrowing_cols,
image_batch_array):
final_prediction_file = pd.DataFrame()
for joint_type in joint_model_path_mapping.keys():
#Dependency
... | [
"def predict_and_save(self, test_data_paths, filename, min_acceptable=0.5):\n \n # get number of examples\n num_examples = len(test_data_paths)\n\n # create data buffers for images and masks\n images = np.zeros((num_examples, self.image_height, self.image_width, 1))\n depth... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Post event to be handled soon. event is added to the queue of events. Returns a future which resolves when the handlers of event (and all events generated during those handlers) have completed. | def post_event(self, event):
self.events.append(event)
LOG.debug('added event %s, pending=%s', event, len(self.events))
self.new_events.set()
if not self.future:
self.future = self.loop.create_task(self._run())
return self.future | [
"def post(self, event):\n self._event_queue.put(event)\n self._notify()\n return None",
"def dispatch(self, event):\n self.queue.put(event)",
"def process_events(self, return_at = None):\n while return_at or not self.queue.empty():\n event = self.queue.get()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call handler with event and log any exception. If handler returns an awaitable, then it is wrapped in a coroutine that will log any exception from awaiting it. | def _run_handler(self, handler, event):
result = None
try:
result = handler(event)
except Exception as e:
self._handle_exception(exception=e, csbot_event=event)
future = maybe_future(result, log=LOG)
if future:
future = asyncio.ensure_future(se... | [
"def async_handler():\n async def target(*args, **kwargs):\n target.fired = True\n target.args = args\n target.kwargs = kwargs\n target.fired = False\n return target",
"def async_handler():\n\n async def target(*args, **kwargs):\n target.fired = True\n target.args = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Await future and log any exception. | async def _finish_async_handler(self, future, event):
try:
await future
except Exception:
self._handle_exception(future=future, csbot_event=event) | [
"def exception(self):\n return self.future.exception()",
"def testErrorInBackgroundThread(self):\n\n @utils.make_async()\n def async_fn():\n raise ValueError()\n\n future = async_fn() # pylint: disable=assignment-from-no-return\n self.assertIsNotNone(future.exception())",
"async def run... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run the event runner loop. Process events and await futures until all events and handlers have been processed. | async def _run(self):
# Use self as context manager so an escaping exception doesn't break
# the event runner instance permanently (i.e. we clean up the future)
with self:
# Run until no more events or lingering futures
while len(self.events) + len(self.futures) > 0:
... | [
"def _run_event_loop(self) -> None:\n # Use a session for the event read loop\n # with a commit every time the event time\n # has changed. This reduces the disk io.\n queue_ = self._queue\n startup_tasks: list[RecorderTask] = []\n while not queue_.empty() and (task := queue... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new event by extending an existing event. The main purpose of this classmethod is to duplicate an event as a new | def extend(cls, event, event_type=None, data=None):
# Duplicate event information
e = cls(event.bot,
event.event_type,
event)
e.datetime = event.datetime
# Apply optional updates
if event_type is not None:
e.event_type = event_type
... | [
"def new_event(self) -> Event:\n ...",
"async def createEvent(self, event: Event) -> None:",
"def clone(self):\n return _libsbml.Event_clone(self)",
"def create_event(self, event_name: str, **kwargs: Any) -> CustomEvent:\n return CustomEvent(event_name, self.handler_properties, **kwargs)"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse self["data"] into a list of arguments using | def arguments(self):
return parse_arguments(self['data']) | [
"def dataargs(self):\n return self.argsbytype(Data)",
"def _get_data(data, *args):\n args = list(args)\n for i, arg in enumerate(args):\n if isinstance(arg, str):\n try:\n array = data[arg]\n except KeyError:\n pass\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Submitted value, or field value converted to string. Return value is always either None or a string. | def value(self):
v = None
if not self.field.is_readonly() and self.params is not None:
# submitted value. do not deserialize here since that requires
# valid data, which we might not have
try:
v = self._serialized_value()
except for... | [
"def get_prep_value(self, value):\n if (value is UNKNOWN) or (value is ''):\n # If Django tries to save an empty string, send the db None (NULL).\n return None\n else:\n # Otherwise, just pass the value.\n return value",
"def value_if_defined(self) -> Any:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds deck for a player, up to an initial amount of 28, then the deck is shuffled. Player HP is also set. | def buildDeck(self, resources):
for key,value in resources.deckData.items():
self.deck.append(resources.cards[value[self.playerClass]])
random.shuffle(self.deck)
self.HP = self.getHP() # Set HP | [
"def build_deck(self):\n for suit in self.suits:\n for value in range(2, 15):\n self.deck.append(card.Card(suit, value))",
"def make_new_deck(self):\n deck_nominals = self.nominals * 4 * self.no_of_decks\n deck_suits = self.suits * 13 * self.no_of_decks\n\n ra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Player draws up to 6 cards. If one player has their deck size (HP) reach zero, the party returns the bonfire to rest. Returns None. | def draw(self):
while len(self.hand) < 6: # While player doesn't have 6 cards in hand
if self.HP == 0:
print("You died.")
break
else:
self.hand.append(self.deck.pop(0)) # Draw from their deck
self.HP = self.getHP() # Update ... | [
"def showdown(self):\r\n\r\n poker_hands = []\r\n message = \"\"\r\n for player in self.players:\r\n poker_hands.append(player.hand.best_poker_hand(self.community_cards.cards))\r\n\r\n # Reveal all cards when the round is over\r\n player.reveal_cards()\r\n\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes the player choice for blocking enemy attack and returns stamina cards used in tribute, discards those cards, and calculates damage to HP. | def blockOption(self, equipChoice, optionChoice, enemy):
selectedCard = self.handLookup[equipChoice] # Chosen equipment
cost = selectedCard.choices[optionChoice-1]["cost"] # Get choice cost of chosen equipment
_, _, tributed = self.tribute(cost,self.getStaminas()) # Get stamina ... | [
"async def attack(self, ctx):\r\n def simulate_battle(player1, player2):\r\n \"\"\"Simulate a battle between two players based solely off ATK and Crit.\r\n Each side has a small chance to land a \"crit\" (based off crit) and win.\r\n Otherwise it will base the victor off the ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method is called by the fitmethod of the Study class (and the step method of the OnlineStudy class) and processes multidimensional data and missing data and passes it to the pdfmethod of the child class. | def processedPdf(self, grid, dataSegment):
# if self.multipyLikelihoods == True, multi-dimensional data is processed one dimension at a time;
# likelihoods are then multiplied
if len(dataSegment.shape) == 2 and self.multiplyLikelihoods:
return np.prod(np.array([self.processedPdf(grid... | [
"def process(self):\n\n log.info(\"Feature Engineering of pred_analys_record_personal_access data of school: \" + self.school_kind.value)\n log.debug(\"QuadrimestersFeatureEngineering.process()\")\n\n global pr_plan_subject_call, pr_scholarship_per_year\n\n analys_record_personal_access ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recursively breaks a field name down into parts and explains each piece. If you're having trouble with this method after adding new fields, you'll need to modify explanations{} to have longer prefixes, or modify this algorithm so that it doesn't shortcut down a dead end. | def explain(field_name, explained_parts=None):
if explained_parts is None: # It's import you don't initialize this in the signature, it side-effects the result since [] is mutable
explained_parts = []
if not field_name:
return ' '.join(explained_parts)
if field_name in explanations.keys():... | [
"def getFieldDescr(fieldName, descr):\n i = getIter(descr)\n if not i:\n return\n\n try:\n sw = ''\n item = i.next()\n while item:\n if fieldName == item[0]:\n yield item\n break\n if isinstance(item[1], list):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the string representation of geoWithin Predicate | def toString(self):
return "geoWithin" | [
"def geoWithin(self, value):\n\n withinP = P(self.toString(), value)\n\n return withinP",
"def _geography_query(self, kwargs):\n out = \"\"\n zipcode = _make_list(kwargs.pop(\"zipcode\", []))\n state = _make_list(kwargs.pop(\"state\", []))\n\n if len(zipcode) == 0:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calls the Gremlin Python's P serializer to query based on geoWithin predicate. | def geoWithin(self, value):
withinP = P(self.toString(), value)
return withinP | [
"def toString(self):\n return \"geoWithin\"",
"def _geography_query(self, kwargs):\n out = \"\"\n zipcode = _make_list(kwargs.pop(\"zipcode\", []))\n state = _make_list(kwargs.pop(\"state\", []))\n\n if len(zipcode) == 0:\n if len(state) == 0:\n m = \"B... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the number of turns | def get_turn_count(self):
return self.turns.count() | [
"def getTurnCount(self):\n return self._turnCount",
"def get_turns_remaining(self):\r\n return self.max_turn - self.current_turn",
"def number_moves(game, player):\n return float(len(game.get_legal_moves(player)))",
"def get_number_of_moves(self):\n return self._number_of_moves",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the current turn object | def get_current_turn(self):
return self.turns.latest('number') | [
"def get_current_player_turn(self):\n return self.player_turn",
"def current_player(self):\n return self.__turn",
"def get_current_adversary_turn(self):\n return self.adversary_turn",
"def take_turn(self):\n return self.turn_taker.take_turn()",
"def turnoActual(self):\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the profile of player with number number | def get_player(self, number):
num = int(number)
assert (num in [1, 2])
return self.player_1 if num == 1 else self.player_2 | [
"def _get_profile(self, season, player):\n try:\n try:\n player = int(player)\n except ValueError:\n player = player.lower()\n player_list = season.get_season_data()[\"proPlayers\"]\n for p in player_list:\n if p[\"id\"]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Spend a list of resources times a quantity | def spend_resources(self, costs, quantity, commit=False):
for cost in costs:
resource_state, _ = ResourceState.objects.get_or_create(state=self, resource=cost.resource)
resource_state.quantity -= cost.amount * quantity
resource_state.clean()
if commit:
... | [
"def _buy(self, units=1):\n self.quantity -= units",
"def add_resources(self, resources):\n self.actions += resources.actions\n self.buys += resources.buys\n self.coins += resources.coins\n self._game.bc_gain_resources(self, resources)",
"def create(self, good, quantity):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Syncs the two game states territory states | def sync_territories(self):
for territory_state in self.territory.all():
territory_state.sync() | [
"def sync_state(self):\n full_status = self.get_status()\n\n if full_status:\n status = full_status.get(\"Status\", {}).get(\"State\",\"missing\").lower()\n self.state = EMRCluster.state_lookup.get(status)\n self.current_state_definition = full_status",
"def update_t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks to see if territory is in the list of valid moves | def validate_invasion(self, player, territory):
current_territory = [ts.territory for ts in self.territory.filter(player=player)]
valid_coordinates = []
for t in current_territory:
valid_coordinates += t.get_valid_moves()
valid_moves = [territory.arena.get_by_coordinates(coor... | [
"def has_available_move(self, opponent):\n possible_moves = set()\n remove_moves = set()\n for piece in self._pieces: # get all possible moves for all pieces\n piece_moves = piece.get_possible_moves()\n possible_moves = possible_moves.union(piece_moves)\n f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run resolve on all non aggressor conflicts | def resolve_conflicts(self, commit=True):
pass # pragma: no cover | [
"def cannot_resolve ( self, *deps, **kw ):\n return self._do_resolve_weak_greedy ( deps, kw, greedy=True ) is None",
"def end_resolve(self, resolved, unresolved):",
"def resolve(self, _: None = None) -> None:\n\n # TODO: check cyclic module imports\n for module in self.module_map.values():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies a turn to the current game state. If validate is false, the changes will actually apply. | def apply_turn(self, turn, commit=False):
for move in turn.moves.all():
if move.action.name == "Refine":
try:
resource = Resource.objects.get(name=move.object)
except ObjectDoesNotExist:
raise ValidationError('invalid resource n... | [
"def apply(self, gameState):\n pass",
"def handle_apply(self):\n self._validate_transition(self.actions.APPLY,\n {self.states.UNCOMMITTED,\n self.states.ABANDONED})\n self.state = self.states.APPLIED",
"def apply_move(self, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visualize generator outputs during training. | def visualize_training_generator(train_step_num, start_time, data_np):
print('Training step: %i' % train_step_num)
time_since_start = (time.time() - start_time) / 60.0
print('Time since start: %f m' % time_since_start)
print('Steps per min: %f' % (train_step_num / time_since_start))
plt.axis('off')
... | [
"def visualize_training(self, settings):\n pass",
"def visualise(self, batch, output, mode):",
"def show_generated_samples(self, label, save: bool):\n\n input_noise = torch.randn(100, self.latent_vector_size, 1, 1, device=self.device)\n\n with torch.no_grad():\n # visualize the g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replaces ['edges']['node'][key].... LIST DICT With a list of dictionaries. | def unedgify(edgy_node):
if isinstance(edgy_node, dict):
if 'edges' in edgy_node:
edgy_node = edgy_node['edges']
index = 0
while index < len(edgy_node):
if isinstance(edgy_node[index], dict) and\
... | [
"def dict_replace_nodekeys(d, xid, idmap = {}):\n\n # loop over dictionary items\n for k, v in list(d.items()):\n # print \"dict_replace_nodekeys: k = %s, v = %s, idmap = %s\" % (k, v.keys(), idmap)\n # new id from old id\n if type(xid) is tuple:\n k_ = \"%s%s%s%s\" % (k, xid[0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Flatten json reply, starting at root, down to stopkey, skipping edges and node key. Each key is named with the levels traversed prepended (each named level seperated by the seperator parameter.. | def _flatten_json(node, stop_prefix, seperator='/', prefix='/', depth=0):
node_list = []
field_dict = {}
# print(f"{' ' * depth}>>> {prefix}")
node_type = type(node)
if node_type == list:
for entry in node:
sub_list, sub_fields = _flat... | [
"def flatten_row(row):\n # [u'hop_survey.node_id', u'hop_survey.created', u'hop_survey',\n # u'case.node_id', u'case',\n # u'experiment.node_id', u'experiment',\n # u'project.node_id', u'project',\n # u'program.node_id', u'program']\n label_created_col_name = [k for k in row.keys() if 'created' in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Overrides parent json_reply should be a list, even if only one item is expected to be returned. This eases dict versus list confusion at the cost of doing only_entry = list[0]. NewGQL.single_entry_to_dict can be used to work around this... | def send_query(self, rt, json_reply, errors=None):
#assert isinstance(json_reply, list)
json_data = {}
status_code = super().send_query(rt, json_data, errors)
#assert False, "NewGQL:lumpy: " + pprint.pformat(json_data)
if not errors is None and len(errors) > 0 and len(j... | [
"def _ListValueMessageToJsonObject(self, message):\n return [self._ValueMessageToJsonObject(value)\n for value in message.values]",
"def convert(self):\n if isinstance(self.json, list):\n return self.iter_list(self.json)\n\n if isinstance(self.json, dict):\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders previously loaded template using provided variables and checks the output for any remaining unpopulated variables. If template is fully populated, then the string is returned; otherwise None is returned If None is passed for 'variables', the variables (if any) passed to the constructor are used | def render_template(self, variables=None):
if self._template is None:
return None
if variables is None:
variables = self._variables
if variables is None:
return None
rendered = self._template.render(variables)
lines = rendered.splitlines()
... | [
"def render_string(self, template: str, **vars) -> str:",
"def template(self, data, variables, fail_on_undefined=False):\n try:\n templar = Templar(loader=self.data_loader, variables=variables)\n return templar.template(data, fail_on_undefined=fail_on_undefined)\n except Ansibl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets all songs in the database | def get_all_songs(self):
to_send = self.db.get_all_songs()
to_send = '$'.join(to_send)
self.send_message(to_send) | [
"def get_all_songs():\r\n return [Song.song_json(song) for song in Song.query.all()]",
"def get_songs(db: Session = Depends(get_db)):\n songs = crud.get_songs(db)\n return [song.title for song in songs]",
"def get_all_songs() -> Generator[dict, None, None]:\n\n logging.debug(\"Fetching from serv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets a ll songs in a certain playlist | def get_all_songs_in_pl(self, playlist):
to_send = self.db.get_songs(playlist)
to_send = DOLLAR.join(to_send)
self.send_message(to_send) | [
"def get_songs_from_playlist(player, playlist_name):\n lists = player.get_sonos_playlists()\n for playlist in lists:\n if playlist.title == playlist_name:\n return player.music_library.browse(playlist)",
"def get_playlist(self):\r\n\r\n playlist_url = input('insert playlist url: ')\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
makes sure the database holds only all the songs that are saved on the server | def update_db(self):
songs = self.db.get_all_songs()
for song in songs:
if choose_song(song) == ERROR:
self.db.delete_song(song)
files = []
for song in glob.glob("songs\*.wav"):
to_append = song.split('\\')[ONE][:-4]
files.append(to_app... | [
"def add_lyrics_and_song_data_to_database(artist, song):\n if exists('song_database.txt'):\n f = open('song_database.txt', 'r+')\n song_list = pickle.load(f)\n current_entry = Song_data(artist, song)\n if current_entry.id in [previous_entry.id for previous_entry in song_list]:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sends the data from a song file chosen by the pick song method manages skips and pauses | def stream_song(self, path, e):
if path == ERROR:
self.send_streaming_message(INVALID_REQ)
return
# sends metadata
sample_rate, channels, my_format = get_metadata(path)
to_send = sample_rate + DOLLAR + channels + DOLLAR + my_format
skip_amount = get_byte_n... | [
"def __done(self):\n log.debug(\"done playing\")\n # if doExit is set don't play again \n if not self.do_exit:\n # first song is always empty -> no log entry \n if self.filetoplay != \"\":\n self.__playlog(self.__gettime() + \" \" + self.nextreason + \" \" +... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
receives a message from the client on the streaming socket | def receive_streaming_msg(self):
size, client_streaming_address = self.server_socket_streaming.recvfrom(
HEADER_SIZE)
data, client_streaming_address = self.server_socket_streaming.recvfrom(
int(size))
data = data.decode()
data = data.split(DOLLAR)
self.cli... | [
"def receive_message(current_client, address, port):\n new_msg = True\n header_ctrl = True\n stream = b''\n msg_len = 0\n while new_msg:\n msg = current_client.recv(20)\n if header_ctrl:\n msg_len = int(msg[:HEADER_SIZE].decode('utf-8'))\n print('Client {}:{} sent ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sends a message to the client on the streaming socket | def send_streaming_message(self, data):
header, data = format_msg(data)
self.server_socket_streaming.sendto(header,
self.client_streaming_address)
self.server_socket_streaming.sendto(data,
self.client_streami... | [
"def send_message(current_client, stream):\n current_client.sendall(stream)",
"def send(self, msg):\n self.__sock.send(msg)",
"def write_line(self, message):\n #print('WRITE: {}'.format(message))\n self.socket.sendall(bytes(message + \"\\n\", 'utf-8'))",
"def send_to_client(self, msg):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
handles the streaming socket | def handle_stream_client(self, event):
try:
while True:
client_req = self.receive_streaming_msg()
self.choose_action(client_req[ZERO], client_req[ONE:], event)
except socket.error as e:
print('stream', e) | [
"def handle_stream(self, stream, address):\n\t\t#SimpleTcpServer.client_id += 1\n\t\t#stream.set_close_callback(on_disconnect)\n\t\t#print('[connection %d] In!' % SimpleTcpServer.client_id)\n\t\tconnection = SimpleTcpClient(stream)\n\t\tyield connection.on_connect()",
"def server_streaming(self) -> global___Snipp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks if a song is valid | def song_check(song):
msg = choose_song(song)
return msg != ERROR | [
"def validate(song):\n if not isinstance(song, Song):\n return False\n if song.get_genre() not in [\"Rock\", \"Pop\", \"Jazz\", \"Altele\"]:\n return False\n try:\n if int(song.get_playtime()) < 0:\n return False\n except ValueError:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
chooses the file of the requested song and checks if its valid | def choose_song(my_name):
my_name = my_name.split(ET)[ZERO]
path = ''
for filename in os.listdir(str(Path.cwd()) + '/songs'):
name = filename.split('\\')[-1]
name = name.split('.')[ZERO]
name = name.split(ET)[ZERO]
if filename.endswith(".wav") and my_name == name:
... | [
"def add_song(self):\r\n path = input(\"Give file path:\\t\") # Request file path\r\n path = path.replace('\\\\', '/')\r\n if self.path_song_re.match(path) and not self.path_storage_re.match(\r\n path): # Check that the path leads to a song that is not already found in Storage\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the two strings as self attributes | def __init__(self, string1, string2):
self.s1 = string1
self.s2 = string2
return | [
"def assign(self, *args):\n return _libsbml.string_assign(self, *args)",
"def set(self, other):\n self._type = other.get_type()\n self._value = other.get_untypedvalue()\n self._text = other.get_text()\n self._name = other.get_name()\n self._description = other.get_descrip... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function builds upon the initialized NW matrix and scores the remaining cells based on a scoring function defined below. Match +1 Mismatch 1 Insertion/Deletion 1 | def needleman_wunsch_fill(self):
matrix = self.init_needleman_wunsch_matrix() # Building on the previous definition
def score_cell(i,j):
"""
This is our first example of a nested definition. This scoreing definition will return the score of
a position (i, j) ... | [
"def smith_waterman_fill(self):\r\n\r\n matrix = self.empty_matrix() # Building on the previous definition\r\n\r\n def score_cell(i,j):\r\n \"\"\"\r\n This scoreing definition will return the score of\r\n a position (i, j) based on the left, upper, and upper left value... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fills in a matrix using the SmithWaterman Algorithm. This algorithm builds upon an empty matrix from self.empty_matrix() Match +3 Mismatch 3 Insertion/Deletion 2 | def smith_waterman_fill(self):
matrix = self.empty_matrix() # Building on the previous definition
def score_cell(i,j):
"""
This scoreing definition will return the score of
a position (i, j) based on the left, upper, and upper left values.
Your s... | [
"def fill_matrix(self):\n\n print(\"Creating Needleman-Wunsch matrix..\")\n\n for i in range(self.matrix.shape[0]):\n for j in range(self.matrix.shape[1]):\n\n if i < len(self.seq_2) and j < len(self.seq_1):\n self.matrix[0, i + 2] = self.seq_2[i]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks a string using list comprehension for any unallowed characters (DNA can only contain C, T, A, and G) and returns True if it only contains those 4 characters, and False otherwise | def is_dna(string):
DNA = ['A','T','G','C']
return False if False in [ str in DNA for str in string] else True | [
"def validate_dna(s):\n\n t = s.lower()\n c = t.count('a') + t.count('t') + t.count('g') + t.count('c')\n if len(t) > c:\n \treturn False\n else:\n\treturn True",
"def checkInvalidChars(string):\n isValid = True\n invalidChars = [\"!\", \"@\", \"#\", \"$\", \"%\", \"^\", \"&\", \"*\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The Sequence Read Archive (SRA) is the worlds largest database of raw sequencing data. This definition takes in the run_id of one dataset and downloads the xml metadata from the URL below. | def get_sra_xml(sra_run_id):
url = "http://www.ncbi.nlm.nih.gov/Traces/sra/?run={}&experimental=1&retmode=xml".format(sra_run_id)
return ur.urlopen(url).read().decode() | [
"def download_SRA(SRA):\n\n print(\"Downloading SRA archive\")\n output = subprocess.run(['prefetch', '-f', 'yes', SRA], stderr=subprocess.STDOUT)\n\n print(\"Extracting FASTQ data\")\n output = subprocess.run(['fastq-dump', '--gzip', NCBI_DIR+SRA+'.sra'], stderr=subprocess.STDOUT)",
"def download_SRA... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |