text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count_intersections(self, line_segments_b):
""" Count the intersections of two strokes with each other. Parameters line_segments_b : list A list of line sege... |
line_segments_a = self.lineSegments
# Calculate intersections
intersection_points = []
for line1, line2 in itertools.product(line_segments_a,
line_segments_b):
intersection_points += get_segments_intersections(line1, line2)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_area(self):
"""Calculate area of bounding box.""" |
return (self.p2.x-self.p1.x)*(self.p2.y-self.p1.y) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_center(self):
""" Get the center point of this bounding box. """ |
return Point((self.p1.x+self.p2.x)/2.0, (self.p1.y+self.p2.y)/2.0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _list_ids(path_to_data):
"""List raw data IDs grouped by symbol ID from a pickle file ``path_to_data``.""" |
loaded = pickle.load(open(path_to_data, "rb"))
raw_datasets = loaded['handwriting_datasets']
raw_ids = {}
for raw_dataset in raw_datasets:
raw_data_id = raw_dataset['handwriting'].raw_data_id
if raw_dataset['formula_id'] not in raw_ids:
raw_ids[raw_dataset['formula_id']] = [... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_system(model_folder):
"""Return the preprocessing description, the feature description and the model description.""" |
# Get model description
model_description_file = os.path.join(model_folder, "info.yml")
if not os.path.isfile(model_description_file):
logging.error("You are probably not in the folder of a model, because "
"%s is not a file. (-m argument)",
model_descri... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def display_data(raw_data_string, raw_data_id, model_folder, show_raw):
"""Print ``raw_data_id`` with the content ``raw_data_string`` after applying the preproce... |
print("## Raw Data (ID: %i)" % raw_data_id)
print("```")
print(raw_data_string)
print("```")
preprocessing_desc, feature_desc, _ = _get_system(model_folder)
# Print model
print("## Model")
print("%s\n" % model_folder)
# Get the preprocessing queue
tmp = preprocessing_desc['qu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(list_ids, model, contact_server, raw_data_id, show_raw, mysql_cfg='mysql_online'):
"""Main function of view.py.""" |
if list_ids:
preprocessing_desc, _, _ = _get_system(model)
raw_datapath = os.path.join(utils.get_project_root(),
preprocessing_desc['data-source'])
_list_ids(raw_datapath)
else:
if contact_server:
data = _fetch_data_from_server(raw... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_parameters(folder):
"""Get the parameters of the preprocessing done within `folder`. Parameters folder : string Returns ------- tuple : (path of raw data... |
# Read the model description file
with open(os.path.join(folder, "info.yml"), 'r') as ymlfile:
preprocessing_description = yaml.load(ymlfile)
# Get the path of the raw data
raw_datapath = os.path.join(utils.get_project_root(),
preprocessing_description['data-so... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_preprocessed_dataset(path_to_data, outputpath, preprocessing_queue):
"""Create a preprocessed dataset file by applying `preprocessing_queue` to `path_... |
# Log everything
logging.info("Data soure %s", path_to_data)
logging.info("Output will be stored in %s", outputpath)
tmp = "Preprocessing Queue:\n"
for preprocessing_class in preprocessing_queue:
tmp += str(preprocessing_class) + "\n"
logging.info(tmp)
# Load from pickled file
i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(folder):
"""Main part of preprocess_dataset that glues things togeter.""" |
raw_datapath, outputpath, p_queue = get_parameters(folder)
create_preprocessed_dataset(raw_datapath, outputpath, p_queue)
utils.create_run_logfile(folder) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _create_index_formula_lookup(formula_id2index, feature_folder, index2latex):
""" Create a lookup file where the index is mapped to the formula id and the LaT... |
index2formula_id = sorted(formula_id2index.items(), key=lambda n: n[1])
index2formula_file = os.path.join(feature_folder, "index2formula_id.csv")
with open(index2formula_file, "w") as f:
f.write("index,formula_id,latex\n")
for formula_id, index in index2formula_id:
f.write("%i,%... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(feature_folder, create_learning_curve=False):
"""main function of create_ffiles.py""" |
# Read the feature description file
with open(os.path.join(feature_folder, "info.yml"), 'r') as ymlfile:
feature_description = yaml.load(ymlfile)
# Get preprocessed .pickle file from model description file
path_to_data = os.path.join(utils.get_project_root(),
f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def training_set_multiplication(training_set, mult_queue):
""" Multiply the training set by all methods listed in mult_queue. Parameters training_set : set of al... |
logging.info("Multiply data...")
for algorithm in mult_queue:
new_trning_set = []
for recording in training_set:
samples = algorithm(recording['handwriting'])
for sample in samples:
new_trning_set.append({'id': recording['id'],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _calculate_feature_stats(feature_list, prepared, serialization_file):
# pylint: disable=R0914 """Calculate min, max and mean for each feature. Store it in ob... |
# Create feature only list
feats = [x for x, _ in prepared] # Label is not necessary
# Calculate all means / mins / maxs
means = numpy.mean(feats, 0)
mins = numpy.min(feats, 0)
maxs = numpy.max(feats, 0)
# Calculate, min, max and mean vector for each feature with
# normalization
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def make_hdf5(dataset_name, feature_count, data, output_filename, create_learning_curve):
""" Create the hdf5 file. Parameters filename : name of the file that h... |
# create raw data file for hdf5_create
if dataset_name == "traindata" and create_learning_curve:
max_trainingexamples = 501
output_filename_save = output_filename
steps = 10
for trainingexamples in range(100, max_trainingexamples, steps):
# adjust output_filename
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_dataset():
"""Create a dataset for machine learning of segmentations. Returns ------- tuple : (X, y) where X is a list of tuples. Each tuple is a feature... |
seg_data = "segmentation-X.npy"
seg_labels = "segmentation-y.npy"
# seg_ids = "segmentation-ids.npy"
if os.path.isfile(seg_data) and os.path.isfile(seg_labels):
X = numpy.load(seg_data)
y = numpy.load(seg_labels)
with open('datasets.pickle', 'rb') as f:
datasets = p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_segmented_raw_data(top_n=10000):
"""Fetch data from the server. Parameters top_n : int Number of data sets which get fetched from the server. """ |
cfg = utils.get_database_configuration()
mysql = cfg['mysql_online']
connection = pymysql.connect(host=mysql['host'],
user=mysql['user'],
passwd=mysql['passwd'],
db=mysql['db'],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_stroke_features(recording, strokeid1, strokeid2):
"""Get the features used to decide if two strokes belong to the same symbol or not. Parameters recordin... |
stroke1 = recording[strokeid1]
stroke2 = recording[strokeid2]
assert isinstance(stroke1, list), "stroke1 is a %s" % type(stroke1)
X_i = []
for s in [stroke1, stroke2]:
hw = HandwrittenData(json.dumps([s]))
feat1 = features.ConstantPointCoordinates(strokes=1,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_segmentation(recording, single_clf, single_stroke_clf, stroke_segmented_classifier):
""" Get a list of segmentations of recording with the probability of... |
mst_wood = get_mst_wood(recording, single_clf)
return [(normalize_segmentation([mst['strokes'] for mst in mst_wood]),
1.0)]
# HandwrittenData(json.dumps(recording)).show()
# return [([[i for i in range(len(recording))]], 1.0)]
# #mst_wood = break_mst(mst, recording) # TODO
# for... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def break_mst(mst, i):
""" Break mst into multiple MSTs by removing one node i. Parameters mst : symmetrical square matrix i : index of the mst where to break Re... |
for j in range(len(mst['mst'])):
mst['mst'][i][j] = 0
mst['mst'][j][i] = 0
_, components = scipy.sparse.csgraph.connected_components(mst['mst'])
comp_indices = {}
for el in set(components):
comp_indices[el] = {'strokes': [], 'strokes_i': []}
for i, comp_nr in enumerate(compo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_out_of_order(segmentation):
""" Check if a given segmentation is out of order. Examples -------- False False True """ |
last_stroke = -1
for symbol in segmentation:
for stroke in symbol:
if last_stroke > stroke:
return True
last_stroke = stroke
return False |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_bb_intersections(recording):
""" Get all intersections of the bounding boxes of strokes. Parameters recording : list of lists of integers Returns -------... |
intersections = numpy.zeros((len(recording), len(recording)),
dtype=bool)
for i in range(len(recording)-1):
a = geometry.get_bounding_box(recording[i]).grow(0.2)
for j in range(i+1, len(recording)):
b = geometry.get_bounding_box(recording[j]).grow(0.2... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def p_strokes(symbol, count):
""" Get the probability of a written `symbol` having `count` strokes. Parameters symbol : str LaTeX command count : int, >= 1 Retur... |
global stroke_prob
assert count >= 1
epsilon = 0.00000001
if stroke_prob is None:
misc_path = pkg_resources.resource_filename('hwrt', 'misc/')
stroke_prob_file = os.path.join(misc_path,
'prob_stroke_count_by_symbol.yml')
with open(stroke_p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _add_hypotheses_assuming_new_stroke(self, new_stroke, stroke_nr, new_beam):
""" Get new guesses by assuming new_stroke is a new symbol. Parameters new_stroke... |
guesses = single_clf.predict({'data': [new_stroke],
'id': None})[:self.m]
for hyp in self.hypotheses:
new_geometry = deepcopy(hyp['geometry'])
most_right = new_geometry
if len(hyp['symbols']) == 0:
while 'right' i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_stroke(self, new_stroke):
""" Update the beam so that it considers `new_stroke`. When a `new_stroke` comes, it can either belong to a symbol for which at... |
global single_clf
if len(self.hypotheses) == 0: # Don't put this in the constructor!
self.hypotheses = [{'segmentation': [],
'symbols': [],
'geometry': {},
'probability': Decimal(1)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _prune(self):
"""Shorten hypotheses to the best k ones.""" |
self.hypotheses = sorted(self.hypotheses,
key=lambda e: e['probability'],
reverse=True)[:self.k] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_matrices():
""" Get the matrices from a pickled files. Returns ------- list List of all matrices. """ |
with open('hwrt/misc/is_one_symbol_classifier.pickle', 'rb') as f:
a = pickle.load(f)
arrays = []
for el1 in a.input_storage:
for el2 in el1.__dict__['storage']:
if isinstance(el2, cuda.CudaNdarray):
arrays.append({'storage': numpy.asarray(el2),
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_model_tar(matrices, tarname="model-cuda-converted.tar"):
""" Create a tar file which contains the model. Parameters matrices : list tarname : str Targ... |
# Write layers
filenames = []
for layer in range(len(matrices)):
if matrices[layer]['name'] == 'W':
weights = matrices[layer]['storage']
weights_file = h5py.File('W%i.hdf5' % (layer / 2), 'w')
weights_file.create_dataset(weights_file.id.name, data=weights)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_python_version():
"""Check if the currently running Python version is new enough.""" |
# Required due to multiple with statements on one line
req_version = (2, 7)
cur_version = sys.version_info
if cur_version >= req_version:
print("Python version... %sOK%s (found %s, requires %s)" %
(Bcolors.OKGREEN, Bcolors.ENDC, str(platform.python_version()),
str(r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Execute all checks.""" |
check_python_version()
check_python_modules()
check_executables()
home = os.path.expanduser("~")
print("\033[1mCheck files\033[0m")
rcfile = os.path.join(home, ".hwrtrc")
if os.path.isfile(rcfile):
print("~/.hwrtrc... %sFOUND%s" %
(Bcolors.OKGREEN, Bcolors.ENDC))
e... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge(d1, d2):
"""Merge two raw datasets into one. Parameters d1 : dict d2 : dict Returns ------- dict """ |
if d1['formula_id2latex'] is None:
formula_id2latex = {}
else:
formula_id2latex = d1['formula_id2latex'].copy()
formula_id2latex.update(d2['formula_id2latex'])
handwriting_datasets = d1['handwriting_datasets']
for dataset in d2['handwriting_datasets']:
handwriting_datasets.a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_file_consistent(local_path_file, md5_hash):
"""Check if file is there and if the md5_hash is correct.""" |
return os.path.isfile(local_path_file) and \
hashlib.md5(open(local_path_file, 'rb').read()).hexdigest() == md5_hash |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Main part of the download script.""" |
# Read config file. This has to get updated via git
project_root = utils.get_project_root()
infofile = os.path.join(project_root, "raw-datasets/info.yml")
logging.info("Read '%s'...", infofile)
with open(infofile, 'r') as ymlfile:
datasets = yaml.load(ymlfile)
for dataset in datasets:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_model():
""" Load a n-gram language model for mathematics in ARPA format which gets shipped with hwrt. Returns ------- A NgramLanguageModel object """ |
logging.info("Load language model...")
ngram_arpa_t = pkg_resources.resource_filename('hwrt',
'misc/ngram.arpa.tar.bz2')
with tarfile.open(ngram_arpa_t, 'r:bz2') as tar:
tarfolder = tempfile.mkdtemp()
tar.extractall(path=tarfolder)
ngra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_from_arpa_str(self, arpa_str):
""" Initialize N-gram model by reading an ARPA language model string. Parameters arpa_str : str A string in ARPA language... |
data_found = False
end_found = False
in_ngram_block = 0
for i, line in enumerate(arpa_str.split("\n")):
if not end_found:
if not data_found:
if "\\data\\" in line:
data_found = True
else:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_probability(self, sentence):
""" Calculate the probability of a sentence, given this language model. Parameters sentence : list A list of strings / token... |
if len(sentence) == 1:
return Decimal(10)**self.get_unigram_log_prob(sentence)
elif len(sentence) == 2:
return Decimal(10)**self.get_bigram_log_prob(sentence)
else:
log_prob = Decimal(0.0)
for w1, w2, w3 in zip(sentence, sentence[1:], sentence[2:]... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate_dir(sample_dir):
"""Evaluate all recordings in `sample_dir`. Parameters sample_dir : string The path to a directory with *.inkml files. Returns ----... |
results = []
if sample_dir[-1] == "/":
sample_dir = sample_dir[:-1]
for filename in glob.glob("%s/*.inkml" % sample_dir):
results.append(evaluate_inkml(filename))
return results |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate_inkml(inkml_file_path):
"""Evaluate an InkML file. Parameters inkml_file_path : string path to an InkML file Returns ------- dictionary The dictiona... |
logging.info("Start evaluating '%s'...", inkml_file_path)
ret = {'filename': inkml_file_path}
recording = inkml.read(inkml_file_path)
results = evaluate(json.dumps(recording.get_sorted_pointlist()),
result_format='LaTeX')
ret['results'] = results
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_output_csv(evaluation_results, filename='results.csv'):
"""Generate the evaluation results in the format Parameters evaluation_results : list of dic... |
with open(filename, 'w') as f:
for result in evaluation_results:
for i, entry in enumerate(result['results']):
if entry['semantics'] == ',':
result['results']['semantics'] = 'COMMA'
f.write("%s, " % result['filename'])
f.write(", ".joi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_project_configuration():
"""Get project configuration as dictionary.""" |
home = os.path.expanduser("~")
rcfile = os.path.join(home, ".hwrtrc")
if not os.path.isfile(rcfile):
create_project_configuration(rcfile)
with open(rcfile, 'r') as ymlfile:
cfg = yaml.load(ymlfile)
return cfg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_project_configuration(filename):
"""Create a project configuration file which contains a configuration that might make sense.""" |
home = os.path.expanduser("~")
project_root_folder = os.path.join(home, "hwr-experiments")
config = {'root': project_root_folder,
'nntoolkit': None,
'dropbox_app_key': None,
'dropbox_app_secret': None,
'dbconfig': os.path.join(home, "hwrt-config/db.co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_project_root():
"""Get the project root folder as a string.""" |
cfg = get_project_configuration()
# At this point it can be sure that the configuration file exists
# Now make sure the project structure exists
for dirname in ["raw-datasets",
"preprocessed",
"feature-files",
"models",
"re... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_template_folder():
"""Get path to the folder where th HTML templates are.""" |
cfg = get_project_configuration()
if 'templates' not in cfg:
home = os.path.expanduser("~")
rcfile = os.path.join(home, ".hwrtrc")
cfg['templates'] = pkg_resources.resource_filename('hwrt',
'templates/')
with open(rcfile... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_database_config_file():
"""Get the absolute path to the database configuration file.""" |
cfg = get_project_configuration()
if 'dbconfig' in cfg:
if os.path.isfile(cfg['dbconfig']):
return cfg['dbconfig']
else:
logging.info("File '%s' was not found. Adjust 'dbconfig' in your "
"~/.hwrtrc file.",
cfg['dbconfig'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_database_configuration():
"""Get database configuration as dictionary.""" |
db_config = get_database_config_file()
if db_config is None:
return None
with open(db_config, 'r') as ymlfile:
cfg = yaml.load(ymlfile)
return cfg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def input_int_default(question="", default=0):
"""A function that works for both, Python 2.x and Python 3.x. It asks the user for input and returns it as a strin... |
answer = input_string(question)
if answer == "" or answer == "yes":
return default
else:
return int(answer) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_run_logfile(folder):
"""Create a 'run.log' within folder. This file contains the time of the latest successful run. """ |
with open(os.path.join(folder, "run.log"), "w") as f:
datestring = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
f.write("timestamp: '%s'" % datestring) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def choose_raw_dataset(currently=""):
"""Let the user choose a raw dataset. Return the absolute path.""" |
folder = os.path.join(get_project_root(), "raw-datasets")
files = [os.path.join(folder, name) for name in os.listdir(folder)
if name.endswith(".pickle")]
default = -1
for i, filename in enumerate(files):
if os.path.basename(currently) == os.path.basename(filename):
defa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_readable_time(t):
""" Format the time to a readable format. Parameters t : int Time in ms Returns ------- string """ |
ms = t % 1000
t -= ms
t /= 1000
s = t % 60
t -= s
t /= 60
minutes = t % 60
t -= minutes
t /= 60
if t != 0:
return "%ih, %i minutes %is %ims" % (t, minutes, s, ms)
elif minutes != 0:
return "%i minutes %is %ims" % (minutes, s, ms)
elif s != 0:
r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def default_model():
"""Get a path for a default value for the model. Start searching in the current directory.""" |
project_root = get_project_root()
models_dir = os.path.join(project_root, "models")
curr_dir = os.getcwd()
if os.path.commonprefix([models_dir, curr_dir]) == models_dir and \
curr_dir != models_dir:
latest_model = curr_dir
else:
latest_model = get_latest_folder(models_dir)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_adjusted_model_for_percentages(model_src, model_use):
"""Replace logreg layer by sigmoid to get probabilities.""" |
# Copy model file
shutil.copyfile(model_src, model_use)
# Adjust model file
with open(model_src) as f:
content = f.read()
content = content.replace("logreg", "sigmoid")
with open(model_use, "w") as f:
f.write(content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_hdf5(output_filename, feature_count, data):
""" Create a HDF5 feature files. Parameters output_filename : string name of the HDF5 file that will be cr... |
import h5py
logging.info("Start creating of %s hdf file", output_filename)
x = []
y = []
for features, label in data:
assert len(features) == feature_count, \
"Expected %i features, got %i features" % \
(feature_count, len(features))
x.append(features)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_model(model_file):
"""Load a model by its file. This includes the model itself, but also the preprocessing queue, the feature list and the output semant... |
# Extract tar
with tarfile.open(model_file) as tar:
tarfolder = tempfile.mkdtemp()
tar.extractall(path=tarfolder)
from . import features
from . import preprocessing
# Get the preprocessing
with open(os.path.join(tarfolder, "preprocessing.yml"), 'r') as ymlfile:
preproc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate_model_single_recording_preloaded(preprocessing_queue, feature_list, model, output_semantics, recording, recording_id=None):
""" Evaluate a model for... |
handwriting = handwritten_data.HandwrittenData(recording,
raw_data_id=recording_id)
handwriting.preprocessing(preprocessing_queue)
x = handwriting.feature_extraction(feature_list)
import nntoolkit.evaluate
model_output = nntoolkit.evaluate.get_mode... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate_model_single_recording_preloaded_multisymbol(preprocessing_queue, feature_list, model, output_semantics, recording):
""" Evaluate a model for a sing... |
import json
import nntoolkit.evaluate
recording = json.loads(recording)
logging.info(("## start (%i strokes)" % len(recording)) + "#" * 80)
hypotheses = [] # [[{'score': 0.123, symbols: [123, 123]}] # split0
# []] # Split i...
for split in get_possible_splits(len(recordi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate_model_single_recording_multisymbol(model_file, recording):
""" Evaluate a model for a single recording where possibly multiple symbols are. Paramete... |
(preprocessing_queue, feature_list, model,
output_semantics) = load_model(model_file)
logging.info("multiple symbol mode")
logging.info(recording)
results = evaluate_model_single_recording_preloaded(preprocessing_queue,
feature_list,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate_model(recording, model_folder, verbose=False):
"""Evaluate model for a single recording.""" |
from . import preprocess_dataset
from . import features
for target_folder in get_recognizer_folders(model_folder):
# The source is later than the target. That means we need to
# refresh the target
if "preprocessed" in target_folder:
logging.info("Start applying preproce... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_index2latex(model_description):
""" Get a dictionary that maps indices to LaTeX commands. Parameters model_description : string A model description file ... |
index2latex = {}
translation_csv = os.path.join(get_project_root(),
model_description["data-source"],
"index2formula_id.csv")
with open(translation_csv) as csvfile:
csvreader = csv.DictReader(csvfile, delimiter=',', quotechar='"'... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_online_symbol_data(database_id):
"""Get from the server.""" |
import pymysql
import pymysql.cursors
cfg = get_database_configuration()
mysql = cfg['mysql_online']
connection = pymysql.connect(host=mysql['host'],
user=mysql['user'],
passwd=mysql['passwd'],
db=mys... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def classify_single_recording(raw_data_json, model_folder, verbose=False):
""" Get the classification as a list of tuples. The first value is the LaTeX code, the... |
evaluation_file = evaluate_model(raw_data_json, model_folder, verbose)
with open(os.path.join(model_folder, "info.yml")) as ymlfile:
model_description = yaml.load(ymlfile)
index2latex = get_index2latex(model_description)
# Map line to probabilites for LaTeX commands
with open(evaluation_f... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_objectlist(description, config_key, module):
""" Take a description and return a list of classes. Parameters description : list of dictionaries Each dict... |
object_list = []
for feature in description:
for feat, params in feature.items():
feat = get_class(feat, config_key, module)
if params is None:
object_list.append(feat())
else:
parameters = {}
for dicts in params:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_class(name, config_key, module):
"""Get the class by its name as a string.""" |
clsmembers = inspect.getmembers(module, inspect.isclass)
for string_name, act_class in clsmembers:
if string_name == name:
return act_class
# Check if the user has specified a plugin and if the class is in there
cfg = get_project_configuration()
if config_key in cfg:
mo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_mysql_cfg():
""" Get the appropriate MySQL configuration """ |
environment = get_project_configuration()['environment']
cfg = get_database_configuration()
if environment == 'production':
mysql = cfg['mysql_online']
else:
mysql = cfg['mysql_dev']
return mysql |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def softmax(w, t=1.0):
"""Calculate the softmax of a list of numbers w. Parameters w : list of numbers Returns ------- a list of the same length as w of non-nega... |
w = [Decimal(el) for el in w]
e = numpy.exp(numpy.array(w) / Decimal(t))
dist = e / numpy.sum(e)
return dist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_beam_cache_directory():
""" Get a directory where pickled Beam Data can be stored. Create that directory, if it doesn't exist. Returns ------- str Path t... |
home = os.path.expanduser("~")
cache_dir = os.path.join(home, '.hwrt-beam-cache')
if not os.path.exists(cache_dir):
os.makedirs(cache_dir)
return cache_dir |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_beam(secret_uuid):
""" Get a beam from the session with `secret_uuid`. Parameters secret_uuid : str Returns ------- The beam object if it exists, otherwi... |
beam_dir = get_beam_cache_directory()
beam_filename = os.path.join(beam_dir, secret_uuid)
if os.path.isfile(beam_filename):
with open(beam_filename, 'rb') as handle:
beam = pickle.load(handle)
return beam
else:
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def is_valid_uuid(uuid_to_test, version=4):
""" Check if uuid_to_test is a valid UUID. Parameters uuid_to_test : str version : {1, 2, 3, 4} Returns ------- `True... |
try:
uuid_obj = UUID(uuid_to_test, version=version)
except ValueError:
return False
return str(uuid_obj) == uuid_to_test |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepare_table(table):
"""Make the table 'symmetric' where the lower left part of the matrix is the reverse probability """ |
n = len(table)
for i, row in enumerate(table):
assert len(row) == n
for j, el in enumerate(row):
if i == j:
table[i][i] = 0.0
elif i > j:
table[i][j] = 1-table[j][i]
return table |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def neclusters(l, K):
"""Partition list ``l`` in ``K`` partitions, without empty parts. [[[0, 1], [2]], [[1], [0, 2]], [[0], [1, 2]]] [[[0, 1, 2]]] """ |
for c in clusters(l, K):
if all(x for x in c):
yield c |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def all_segmentations(l):
"""Get all segmentations of a list ``l``. This gets bigger fast. See https://oeis.org/A000110 For len(l) = 14 it is 190,899,322 [[[0, 1... |
for K in range(1, len(l)+1):
gen = neclusters(l, K)
for el in gen:
yield el |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def q(segmentation, s1, s2):
"""Test if ``s1`` and ``s2`` are in the same symbol, given the ``segmentation``. """ |
index1 = find_index(segmentation, s1)
index2 = find_index(segmentation, s2)
return index1 == index2 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def score_segmentation(segmentation, table):
"""Get the score of a segmentation.""" |
stroke_nr = sum(1 for symbol in segmentation for stroke in symbol)
score = 1
for i in range(stroke_nr):
for j in range(i+1, stroke_nr):
qval = q(segmentation, i, j)
if qval:
score *= table[i][j]
else:
score *= table[j][i]
retur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def push(self, element, value):
"""Push an ``element`` into the datastrucutre together with its value and only save it if it currently is one of the top n elemen... |
insert_pos = 0
for index, el in enumerate(self.tops):
if not self.find_min and el[1] >= value:
insert_pos = index+1
elif self.find_min and el[1] <= value:
insert_pos = index+1
self.tops.insert(insert_pos, [element, value])
self.top... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _array2cstr(arr):
""" Serializes a numpy array to a compressed base64 string """ |
out = StringIO()
np.save(out, arr)
return b64encode(out.getvalue()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _str2array(d):
""" Reconstructs a numpy array from a plain-text string """ |
if type(d) == list:
return np.asarray([_str2array(s) for s in d])
ins = StringIO(d)
return np.loadtxt(ins) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_output_semantics(model_folder, outputs):
""" Create a 'output_semantics.csv' file which contains information what the output of the single output neur... |
with open('output_semantics.csv', 'wb') as csvfile:
model_description_file = os.path.join(model_folder, "info.yml")
with open(model_description_file, 'r') as ymlfile:
model_description = yaml.load(ymlfile)
logging.info("Start fetching translation dict...")
translation_d... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def elementtree_to_dict(element):
"""Convert an xml ElementTree to a dictionary.""" |
d = dict()
if hasattr(element, 'text') and element.text is not None:
d['text'] = element.text
d.update(element.items()) # element's attributes
for c in list(element): # element's children
if c.tag not in d:
d[c.tag] = elementtree_to_dict(c)
# an element with the ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def strip_end(text, suffix):
"""Strip `suffix` from the end of `text` if `text` has that suffix.""" |
if not text.endswith(suffix):
return text
return text[:len(text)-len(suffix)] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def formula_to_dbid(formula_str, backslash_fix=False):
""" Convert a LaTeX formula to the database index. Parameters formula_str : string The formula as LaTeX co... |
global __formula_to_dbid_cache
if __formula_to_dbid_cache is None:
mysql = utils.get_mysql_cfg()
connection = pymysql.connect(host=mysql['host'],
user=mysql['user'],
passwd=mysql['passwd'],
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insert_recording(hw):
"""Insert recording `hw` into database.""" |
mysql = utils.get_mysql_cfg()
connection = pymysql.connect(host=mysql['host'],
user=mysql['user'],
passwd=mysql['passwd'],
db=mysql['db'],
charset='utf8mb4',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insert_symbol_mapping(raw_data_id, symbol_id, user_id, strokes):
""" Insert data into `wm_strokes_to_symbol`. Parameters raw_data_id : int user_id : int stro... |
mysql = utils.get_mysql_cfg()
connection = pymysql.connect(host=mysql['host'],
user=mysql['user'],
passwd=mysql['passwd'],
db=mysql['db'],
charset='utf8mb4',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter_label(label, replace_by_similar=True):
"""Some labels currently don't work together because of LaTeX naming clashes. Those will be replaced by simple ... |
bad_names = ['celsius', 'degree', 'ohm', 'venus', 'mars', 'astrosun',
'fullmoon', 'leftmoon', 'female', 'male', 'checked',
'diameter', 'sun', 'Bowtie', 'sqrt',
'cong', 'copyright', 'dag', 'parr', 'notin', 'dotsc',
'mathds', 'mathfrak']
if any(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def analyze_feature(raw_datasets, feature, basename="aspect_ratios"):
""" Apply ``feature`` to all recordings in ``raw_datasets``. Store the results in two files... |
# Prepare files
csv_file = dam.prepare_file(basename + '.csv')
raw_file = dam.prepare_file(basename + '.raw')
csv_file = open(csv_file, 'a')
raw_file = open(raw_file, 'a')
csv_file.write("label,mean,std\n") # Write header
raw_file.write("latex,raw_data_id,value\n") # Write header
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(handwriting_datasets_file, analyze_features):
"""Start the creation of the wanted metric.""" |
# Load from pickled file
logging.info("Start loading data '%s' ...", handwriting_datasets_file)
loaded = pickle.load(open(handwriting_datasets_file))
raw_datasets = loaded['handwriting_datasets']
logging.info("%i datasets loaded.", len(raw_datasets))
logging.info("Start analyzing...")
if a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_matching_braces(latex):
""" If `latex` is surrounded by matching braces, remove them. They are not necessary. Parameters latex : string Returns ------... |
if latex.startswith('{') and latex.endswith('}'):
opened = 1
matches = True
for char in latex[1:-1]:
if char == '{':
opened += 1
elif char == '}':
opened -= 1
if opened == 0:
matches = False
if match... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_folder(folder):
"""Read all files of `folder` and return a list of HandwrittenData objects. Parameters folder : string Path to a folder Returns ------- ... |
recordings = []
for filename in glob.glob(os.path.join(folder, '*.ink')):
recording = parse_scg_ink_file(filename)
recordings.append(recording)
return recordings |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_colors(segmentation):
"""Get a list of colors which is as long as the segmentation. Parameters segmentation : list of lists Returns ------- list A list ... |
symbol_count = len(segmentation)
num_colors = symbol_count
# See http://stackoverflow.com/a/20298116/562769
color_array = [
"#000000", "#FFFF00", "#1CE6FF", "#FF34FF", "#FF4A46", "#008941",
"#006FA6", "#A30059", "#FFDBE5", "#7A4900", "#0000A6", "#63FFAC",
"#B79762", "#004D43", ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fix_times(self):
""" Some recordings have wrong times. Fix them so that nothing after loading a handwritten recording breaks. """ |
pointlist = self.get_pointlist()
times = [point['time'] for stroke in pointlist for point in stroke]
times_min = max(min(times), 0) # Make sure this is not None
for i, stroke in enumerate(pointlist):
for j, point in enumerate(stroke):
if point['time'] is Non... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_pointlist(self):
""" Get a list of lists of tuples from JSON raw data string. Those lists represent strokes with control points. Returns ------- list : A... |
try:
pointlist = json.loads(self.raw_data_json)
except Exception as inst:
logging.debug("pointStrokeList: strokelistP")
logging.debug(self.raw_data_json)
logging.debug("didn't work")
raise inst
if len(pointlist) == 0:
logg... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_sorted_pointlist(self):
""" Make sure that the points and strokes are in order. Returns ------- list A list of all strokes in the recording. Each stroke ... |
pointlist = self.get_pointlist()
for i in range(len(pointlist)):
pointlist[i] = sorted(pointlist[i], key=lambda p: p['time'])
pointlist = sorted(pointlist, key=lambda stroke: stroke[0]['time'])
return pointlist |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_pointlist(self, pointlist):
"""Overwrite pointlist. Parameters pointlist : a list of strokes; each stroke is a list of points The inner lists represent s... |
assert type(pointlist) is list, \
"pointlist is not of type list, but %r" % type(pointlist)
assert len(pointlist) >= 1, \
"The pointlist of formula_id %i is %s" % (self.formula_id,
self.get_pointlist())
self.raw_data_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_bounding_box(self):
""" Get the bounding box of a pointlist. """ |
pointlist = self.get_pointlist()
# Initialize bounding box parameters to save values
minx, maxx = pointlist[0][0]["x"], pointlist[0][0]["x"]
miny, maxy = pointlist[0][0]["y"], pointlist[0][0]["y"]
mint, maxt = pointlist[0][0]["time"], pointlist[0][0]["time"]
# Adjust p... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_bitmap(self, time=None, size=32, store_path=None):
""" Get a bitmap of the object at a given instance of time. If time is `None`,`then the bitmap is gene... |
# bitmap_width = int(self.get_width()*size) + 2
# bitmap_height = int(self.get_height()*size) + 2
img = Image.new('L', (size, size), 'black')
draw = ImageDraw.Draw(img, 'L')
bb = self.get_bounding_box()
for stroke in self.get_sorted_pointlist():
for p1, p2 in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def preprocessing(self, algorithms):
"""Apply preprocessing algorithms. Parameters algorithms : a list objects Preprocessing allgorithms which get applied in ord... |
assert type(algorithms) is list
for algorithm in algorithms:
algorithm(self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def feature_extraction(self, algorithms):
"""Get a list of features. Every algorithm has to return the features as a list.""" |
assert type(algorithms) is list
features = []
for algorithm in algorithms:
new_features = algorithm(self)
assert len(new_features) == algorithm.get_dimension(), \
"Expected %i features from algorithm %s, got %i features" % \
(algorithm.get... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def show(self):
"""Show the data graphically in a new pop-up window.""" |
# prevent the following error:
# '_tkinter.TclError: no display name and no $DISPLAY environment
# variable'
# import matplotlib
# matplotlib.use('GTK3Agg', warn=False)
import matplotlib.pyplot as plt
pointlist = self.get_pointlist()
if 'pen_down' i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count_single_dots(self):
"""Count all strokes of this recording that have only a single dot. """ |
pointlist = self.get_pointlist()
single_dots = 0
for stroke in pointlist:
if len(stroke) == 1:
single_dots += 1
return single_dots |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_single_symbol_list(self):
""" Convert this HandwrittenData object into a list of HandwrittenData objects. Each element of the list is a single symbol. Ret... |
symbol_stream = getattr(self,
'symbol_stream',
[None for symbol in self.segmentation])
single_symbols = []
pointlist = self.get_sorted_pointlist()
for stroke_indices, label in zip(self.segmentation, symbol_stream):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_git_postversion(addon_dir):
""" return the addon version number, with a developmental version increment if there were git commits in the addon_dir after ... |
addon_dir = os.path.realpath(addon_dir)
last_version = read_manifest(addon_dir).get('version', '0.0.0')
last_version_parsed = parse_version(last_version)
if not is_git_controlled(addon_dir):
return last_version
if get_git_uncommitted(addon_dir):
uncommitted = True
count = 1
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_odoo_version_info(addons_dir, odoo_version_override=None):
""" Detect Odoo version from an addons directory """ |
odoo_version_info = None
addons = os.listdir(addons_dir)
for addon in addons:
addon_dir = os.path.join(addons_dir, addon)
if is_installable_addon(addon_dir):
manifest = read_manifest(addon_dir)
_, _, addon_odoo_version_info = _get_version(
addon_dir, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.