code
stringlengths 13
6.09M
| order_type
stringclasses 2
values | original_example
dict | step_ids
listlengths 1
5
|
|---|---|---|---|
<|reserved_special_token_0|>
def convert_idx(text, tokens):
current = 0
spans = []
for token in tokens:
current = text.find(token, current)
if current < 0:
print('Token {} cannot be found'.format(token))
raise Exception()
spans.append((current, current + len(token)))
current += len(token)
return spans
def process_file(filename, data_type, word_counter, char_counter, shuffle=False
):
print('Generating {} examples...'.format(data_type))
examples = []
eval_examples = {}
total = 0
with open(filename, 'r') as fh:
for l in fh:
ques, ans, label = l.strip().split('\t')
ques_tokens = word_tokenize(ques)
ques_chars = [list(token) for token in ques_tokens]
ans_tokens = word_tokenize(ans)
ans_chars = [list(token) for token in ans_tokens]
label = int(label)
total += 1
for token in ques_tokens:
word_counter[token.lower()] += 1
for char in token:
char_counter[char] += 1
for token in ans_tokens:
word_counter[token.lower()] += 1
for char in token:
char_counter[char] += 1
example = {'ans_tokens': ans_tokens, 'ans_chars': ans_chars,
'ques_tokens': ques_tokens, 'ques_chars': ques_chars, 'y':
label, 'id': total}
examples.append(example)
if random:
random.shuffle(examples)
print('{} questions in total'.format(len(examples)))
return examples
<|reserved_special_token_0|>
def build_features_SemEval(config, examples, data_type, out_file,
word2idx_dict, char2idx_dict, is_test=False):
ans_limit = config.test_para_limit if is_test else config.para_limit
ques_limit = config.test_ques_limit if is_test else config.ques_limit
char_limit = config.char_limit
def filter_func(example, is_test=False):
return len(example['ans_tokens']) > ans_limit or len(example[
'ques_tokens']) > ques_limit
print('Processing {} examples...'.format(data_type))
writer = tf.python_io.TFRecordWriter(out_file)
total = 0
total_ = 0
meta = {}
for example in tqdm(examples):
total_ += 1
total += 1
context_idxs = np.zeros([ans_limit], dtype=np.int32)
context_char_idxs = np.zeros([ans_limit, char_limit], dtype=np.int32)
ques_idxs = np.zeros([ques_limit], dtype=np.int32)
ques_char_idxs = np.zeros([ques_limit, char_limit], dtype=np.int32)
y = 0
def _get_word(word):
for each in (word, word.lower(), word.capitalize(), word.upper()):
if each in word2idx_dict:
return word2idx_dict[each]
return 1
def _get_char(char):
if char in char2idx_dict:
return char2idx_dict[char]
return 1
for i, token in enumerate(example['ans_tokens'][:ans_limit]):
context_idxs[i] = _get_word(token)
for i, token in enumerate(example['ques_tokens'][:ques_limit]):
ques_idxs[i] = _get_word(token)
for i, token in enumerate(example['ans_chars'][:ans_limit]):
for j, char in enumerate(token):
if j == char_limit:
break
context_char_idxs[i, j] = _get_char(char)
for i, token in enumerate(example['ques_chars'][:ques_limit]):
for j, char in enumerate(token):
if j == char_limit:
break
ques_char_idxs[i, j] = _get_char(char)
label = example['y']
y = float(label)
record = tf.train.Example(features=tf.train.Features(feature={
'ans_idxs': tf.train.Feature(bytes_list=tf.train.BytesList(
value=[context_idxs.tostring()])), 'ques_idxs': tf.train.
Feature(bytes_list=tf.train.BytesList(value=[ques_idxs.tostring
()])), 'ans_char_idxs': tf.train.Feature(bytes_list=tf.train.
BytesList(value=[context_char_idxs.tostring()])),
'ques_char_idxs': tf.train.Feature(bytes_list=tf.train.
BytesList(value=[ques_char_idxs.tostring()])), 'y': tf.train.
Feature(bytes_list=tf.train.BytesList(value=[np.array([y]).
tostring()])), 'id': tf.train.Feature(int64_list=tf.train.
Int64List(value=[example['id']]))}))
writer.write(record.SerializeToString())
print('Build {} / {} instances of features in total'.format(total, total_))
meta['total'] = total
writer.close()
return meta
def save(filename, obj, message=None):
if message is not None:
print('Saving {}...'.format(message))
with open(filename, 'w') as fh:
json.dump(obj, fh)
def preproSemEval(config):
word_counter, char_counter = Counter(), Counter()
train_examples = process_file(config.SemEval_train_file, 'train',
word_counter, char_counter, shuffle=True)
dev_examples = process_file(config.SemEval_dev_file, 'dev',
word_counter, char_counter)
test_examples = process_file(config.SemEval_test_file, 'test',
word_counter, char_counter)
word_emb_file = (config.fasttext_file if config.fasttext else config.
glove_word_file)
char_emb_file = config.glove_char_file if config.pretrained_char else None
char_emb_size = config.glove_char_size if config.pretrained_char else None
char_emb_dim = (config.glove_dim if config.pretrained_char else config.
char_dim)
word2idx_dict = None
if os.path.isfile(config.word2idx_file):
with open(config.word2idx_file, 'r') as fh:
word2idx_dict = json.load(fh)
word_emb_mat, word2idx_dict = get_embedding(word_counter, 'word',
emb_file=word_emb_file, size=config.glove_word_size, vec_size=
config.glove_dim, token2idx_dict=word2idx_dict)
char2idx_dict = None
if os.path.isfile(config.char2idx_file):
with open(config.char2idx_file, 'r') as fh:
char2idx_dict = json.load(fh)
char_emb_mat, char2idx_dict = get_embedding(char_counter, 'char',
emb_file=char_emb_file, size=char_emb_size, vec_size=char_emb_dim,
token2idx_dict=char2idx_dict)
build_features_SemEval(config, train_examples, 'train', config.
train_record_file, word2idx_dict, char2idx_dict)
dev_meta = build_features_SemEval(config, dev_examples, 'dev', config.
dev_record_file, word2idx_dict, char2idx_dict)
test_meta = build_features_SemEval(config, test_examples, 'test',
config.test_record_file, word2idx_dict, char2idx_dict, is_test=True)
save(config.word_emb_file, word_emb_mat, message='word embedding')
save(config.char_emb_file, char_emb_mat, message='char embedding')
save(config.dev_meta, dev_meta, message='dev meta')
save(config.word2idx_file, word2idx_dict, message='word2idx')
save(config.char2idx_file, char2idx_dict, message='char2idx')
save(config.test_meta, test_meta, message='test meta')
save('data/test.json', dev_examples, message='test example')
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def convert_idx(text, tokens):
current = 0
spans = []
for token in tokens:
current = text.find(token, current)
if current < 0:
print('Token {} cannot be found'.format(token))
raise Exception()
spans.append((current, current + len(token)))
current += len(token)
return spans
def process_file(filename, data_type, word_counter, char_counter, shuffle=False
):
print('Generating {} examples...'.format(data_type))
examples = []
eval_examples = {}
total = 0
with open(filename, 'r') as fh:
for l in fh:
ques, ans, label = l.strip().split('\t')
ques_tokens = word_tokenize(ques)
ques_chars = [list(token) for token in ques_tokens]
ans_tokens = word_tokenize(ans)
ans_chars = [list(token) for token in ans_tokens]
label = int(label)
total += 1
for token in ques_tokens:
word_counter[token.lower()] += 1
for char in token:
char_counter[char] += 1
for token in ans_tokens:
word_counter[token.lower()] += 1
for char in token:
char_counter[char] += 1
example = {'ans_tokens': ans_tokens, 'ans_chars': ans_chars,
'ques_tokens': ques_tokens, 'ques_chars': ques_chars, 'y':
label, 'id': total}
examples.append(example)
if random:
random.shuffle(examples)
print('{} questions in total'.format(len(examples)))
return examples
def get_embedding(counter, data_type, limit=-1, emb_file=None, size=None,
vec_size=None, token2idx_dict=None):
print('Generating {} embedding...'.format(data_type))
embedding_dict = {}
filtered_elements = [k for k, v in counter.items() if v > limit]
if emb_file is not None:
assert size is not None
assert vec_size is not None
with open(emb_file, 'r', encoding='utf-8') as fh:
for line in tqdm(fh, total=size):
array = line.split()
word = ''.join(array[0:-vec_size])
vector = list(map(float, array[-vec_size:]))
if word in counter and counter[word] > limit:
embedding_dict[word] = vector
print('{} / {} tokens have corresponding {} embedding vector'.
format(len(embedding_dict), len(filtered_elements), data_type))
else:
assert vec_size is not None
for token in filtered_elements:
embedding_dict[token] = [np.random.normal(scale=0.01) for _ in
range(vec_size)]
print('{} tokens have corresponding embedding vector'.format(len(
filtered_elements)))
NULL = '--NULL--'
OOV = '--OOV--'
token2idx_dict = {token: idx for idx, token in enumerate(embedding_dict
.keys(), 2)} if token2idx_dict is None else token2idx_dict
token2idx_dict[NULL] = 0
token2idx_dict[OOV] = 1
embedding_dict[NULL] = [(0.0) for _ in range(vec_size)]
embedding_dict[OOV] = [(0.0) for _ in range(vec_size)]
idx2emb_dict = {idx: embedding_dict[token] for token, idx in
token2idx_dict.items()}
emb_mat = [idx2emb_dict[idx] for idx in range(len(idx2emb_dict))]
return emb_mat, token2idx_dict
def build_features_SemEval(config, examples, data_type, out_file,
word2idx_dict, char2idx_dict, is_test=False):
ans_limit = config.test_para_limit if is_test else config.para_limit
ques_limit = config.test_ques_limit if is_test else config.ques_limit
char_limit = config.char_limit
def filter_func(example, is_test=False):
return len(example['ans_tokens']) > ans_limit or len(example[
'ques_tokens']) > ques_limit
print('Processing {} examples...'.format(data_type))
writer = tf.python_io.TFRecordWriter(out_file)
total = 0
total_ = 0
meta = {}
for example in tqdm(examples):
total_ += 1
total += 1
context_idxs = np.zeros([ans_limit], dtype=np.int32)
context_char_idxs = np.zeros([ans_limit, char_limit], dtype=np.int32)
ques_idxs = np.zeros([ques_limit], dtype=np.int32)
ques_char_idxs = np.zeros([ques_limit, char_limit], dtype=np.int32)
y = 0
def _get_word(word):
for each in (word, word.lower(), word.capitalize(), word.upper()):
if each in word2idx_dict:
return word2idx_dict[each]
return 1
def _get_char(char):
if char in char2idx_dict:
return char2idx_dict[char]
return 1
for i, token in enumerate(example['ans_tokens'][:ans_limit]):
context_idxs[i] = _get_word(token)
for i, token in enumerate(example['ques_tokens'][:ques_limit]):
ques_idxs[i] = _get_word(token)
for i, token in enumerate(example['ans_chars'][:ans_limit]):
for j, char in enumerate(token):
if j == char_limit:
break
context_char_idxs[i, j] = _get_char(char)
for i, token in enumerate(example['ques_chars'][:ques_limit]):
for j, char in enumerate(token):
if j == char_limit:
break
ques_char_idxs[i, j] = _get_char(char)
label = example['y']
y = float(label)
record = tf.train.Example(features=tf.train.Features(feature={
'ans_idxs': tf.train.Feature(bytes_list=tf.train.BytesList(
value=[context_idxs.tostring()])), 'ques_idxs': tf.train.
Feature(bytes_list=tf.train.BytesList(value=[ques_idxs.tostring
()])), 'ans_char_idxs': tf.train.Feature(bytes_list=tf.train.
BytesList(value=[context_char_idxs.tostring()])),
'ques_char_idxs': tf.train.Feature(bytes_list=tf.train.
BytesList(value=[ques_char_idxs.tostring()])), 'y': tf.train.
Feature(bytes_list=tf.train.BytesList(value=[np.array([y]).
tostring()])), 'id': tf.train.Feature(int64_list=tf.train.
Int64List(value=[example['id']]))}))
writer.write(record.SerializeToString())
print('Build {} / {} instances of features in total'.format(total, total_))
meta['total'] = total
writer.close()
return meta
def save(filename, obj, message=None):
if message is not None:
print('Saving {}...'.format(message))
with open(filename, 'w') as fh:
json.dump(obj, fh)
def preproSemEval(config):
word_counter, char_counter = Counter(), Counter()
train_examples = process_file(config.SemEval_train_file, 'train',
word_counter, char_counter, shuffle=True)
dev_examples = process_file(config.SemEval_dev_file, 'dev',
word_counter, char_counter)
test_examples = process_file(config.SemEval_test_file, 'test',
word_counter, char_counter)
word_emb_file = (config.fasttext_file if config.fasttext else config.
glove_word_file)
char_emb_file = config.glove_char_file if config.pretrained_char else None
char_emb_size = config.glove_char_size if config.pretrained_char else None
char_emb_dim = (config.glove_dim if config.pretrained_char else config.
char_dim)
word2idx_dict = None
if os.path.isfile(config.word2idx_file):
with open(config.word2idx_file, 'r') as fh:
word2idx_dict = json.load(fh)
word_emb_mat, word2idx_dict = get_embedding(word_counter, 'word',
emb_file=word_emb_file, size=config.glove_word_size, vec_size=
config.glove_dim, token2idx_dict=word2idx_dict)
char2idx_dict = None
if os.path.isfile(config.char2idx_file):
with open(config.char2idx_file, 'r') as fh:
char2idx_dict = json.load(fh)
char_emb_mat, char2idx_dict = get_embedding(char_counter, 'char',
emb_file=char_emb_file, size=char_emb_size, vec_size=char_emb_dim,
token2idx_dict=char2idx_dict)
build_features_SemEval(config, train_examples, 'train', config.
train_record_file, word2idx_dict, char2idx_dict)
dev_meta = build_features_SemEval(config, dev_examples, 'dev', config.
dev_record_file, word2idx_dict, char2idx_dict)
test_meta = build_features_SemEval(config, test_examples, 'test',
config.test_record_file, word2idx_dict, char2idx_dict, is_test=True)
save(config.word_emb_file, word_emb_mat, message='word embedding')
save(config.char_emb_file, char_emb_mat, message='char embedding')
save(config.dev_meta, dev_meta, message='dev meta')
save(config.word2idx_file, word2idx_dict, message='word2idx')
save(config.char2idx_file, char2idx_dict, message='char2idx')
save(config.test_meta, test_meta, message='test meta')
save('data/test.json', dev_examples, message='test example')
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def word_tokenize(sent):
doc = nlp(sent)
return [token.text for token in doc]
def convert_idx(text, tokens):
current = 0
spans = []
for token in tokens:
current = text.find(token, current)
if current < 0:
print('Token {} cannot be found'.format(token))
raise Exception()
spans.append((current, current + len(token)))
current += len(token)
return spans
def process_file(filename, data_type, word_counter, char_counter, shuffle=False
):
print('Generating {} examples...'.format(data_type))
examples = []
eval_examples = {}
total = 0
with open(filename, 'r') as fh:
for l in fh:
ques, ans, label = l.strip().split('\t')
ques_tokens = word_tokenize(ques)
ques_chars = [list(token) for token in ques_tokens]
ans_tokens = word_tokenize(ans)
ans_chars = [list(token) for token in ans_tokens]
label = int(label)
total += 1
for token in ques_tokens:
word_counter[token.lower()] += 1
for char in token:
char_counter[char] += 1
for token in ans_tokens:
word_counter[token.lower()] += 1
for char in token:
char_counter[char] += 1
example = {'ans_tokens': ans_tokens, 'ans_chars': ans_chars,
'ques_tokens': ques_tokens, 'ques_chars': ques_chars, 'y':
label, 'id': total}
examples.append(example)
if random:
random.shuffle(examples)
print('{} questions in total'.format(len(examples)))
return examples
def get_embedding(counter, data_type, limit=-1, emb_file=None, size=None,
vec_size=None, token2idx_dict=None):
print('Generating {} embedding...'.format(data_type))
embedding_dict = {}
filtered_elements = [k for k, v in counter.items() if v > limit]
if emb_file is not None:
assert size is not None
assert vec_size is not None
with open(emb_file, 'r', encoding='utf-8') as fh:
for line in tqdm(fh, total=size):
array = line.split()
word = ''.join(array[0:-vec_size])
vector = list(map(float, array[-vec_size:]))
if word in counter and counter[word] > limit:
embedding_dict[word] = vector
print('{} / {} tokens have corresponding {} embedding vector'.
format(len(embedding_dict), len(filtered_elements), data_type))
else:
assert vec_size is not None
for token in filtered_elements:
embedding_dict[token] = [np.random.normal(scale=0.01) for _ in
range(vec_size)]
print('{} tokens have corresponding embedding vector'.format(len(
filtered_elements)))
NULL = '--NULL--'
OOV = '--OOV--'
token2idx_dict = {token: idx for idx, token in enumerate(embedding_dict
.keys(), 2)} if token2idx_dict is None else token2idx_dict
token2idx_dict[NULL] = 0
token2idx_dict[OOV] = 1
embedding_dict[NULL] = [(0.0) for _ in range(vec_size)]
embedding_dict[OOV] = [(0.0) for _ in range(vec_size)]
idx2emb_dict = {idx: embedding_dict[token] for token, idx in
token2idx_dict.items()}
emb_mat = [idx2emb_dict[idx] for idx in range(len(idx2emb_dict))]
return emb_mat, token2idx_dict
def build_features_SemEval(config, examples, data_type, out_file,
word2idx_dict, char2idx_dict, is_test=False):
ans_limit = config.test_para_limit if is_test else config.para_limit
ques_limit = config.test_ques_limit if is_test else config.ques_limit
char_limit = config.char_limit
def filter_func(example, is_test=False):
return len(example['ans_tokens']) > ans_limit or len(example[
'ques_tokens']) > ques_limit
print('Processing {} examples...'.format(data_type))
writer = tf.python_io.TFRecordWriter(out_file)
total = 0
total_ = 0
meta = {}
for example in tqdm(examples):
total_ += 1
total += 1
context_idxs = np.zeros([ans_limit], dtype=np.int32)
context_char_idxs = np.zeros([ans_limit, char_limit], dtype=np.int32)
ques_idxs = np.zeros([ques_limit], dtype=np.int32)
ques_char_idxs = np.zeros([ques_limit, char_limit], dtype=np.int32)
y = 0
def _get_word(word):
for each in (word, word.lower(), word.capitalize(), word.upper()):
if each in word2idx_dict:
return word2idx_dict[each]
return 1
def _get_char(char):
if char in char2idx_dict:
return char2idx_dict[char]
return 1
for i, token in enumerate(example['ans_tokens'][:ans_limit]):
context_idxs[i] = _get_word(token)
for i, token in enumerate(example['ques_tokens'][:ques_limit]):
ques_idxs[i] = _get_word(token)
for i, token in enumerate(example['ans_chars'][:ans_limit]):
for j, char in enumerate(token):
if j == char_limit:
break
context_char_idxs[i, j] = _get_char(char)
for i, token in enumerate(example['ques_chars'][:ques_limit]):
for j, char in enumerate(token):
if j == char_limit:
break
ques_char_idxs[i, j] = _get_char(char)
label = example['y']
y = float(label)
record = tf.train.Example(features=tf.train.Features(feature={
'ans_idxs': tf.train.Feature(bytes_list=tf.train.BytesList(
value=[context_idxs.tostring()])), 'ques_idxs': tf.train.
Feature(bytes_list=tf.train.BytesList(value=[ques_idxs.tostring
()])), 'ans_char_idxs': tf.train.Feature(bytes_list=tf.train.
BytesList(value=[context_char_idxs.tostring()])),
'ques_char_idxs': tf.train.Feature(bytes_list=tf.train.
BytesList(value=[ques_char_idxs.tostring()])), 'y': tf.train.
Feature(bytes_list=tf.train.BytesList(value=[np.array([y]).
tostring()])), 'id': tf.train.Feature(int64_list=tf.train.
Int64List(value=[example['id']]))}))
writer.write(record.SerializeToString())
print('Build {} / {} instances of features in total'.format(total, total_))
meta['total'] = total
writer.close()
return meta
def save(filename, obj, message=None):
if message is not None:
print('Saving {}...'.format(message))
with open(filename, 'w') as fh:
json.dump(obj, fh)
def preproSemEval(config):
word_counter, char_counter = Counter(), Counter()
train_examples = process_file(config.SemEval_train_file, 'train',
word_counter, char_counter, shuffle=True)
dev_examples = process_file(config.SemEval_dev_file, 'dev',
word_counter, char_counter)
test_examples = process_file(config.SemEval_test_file, 'test',
word_counter, char_counter)
word_emb_file = (config.fasttext_file if config.fasttext else config.
glove_word_file)
char_emb_file = config.glove_char_file if config.pretrained_char else None
char_emb_size = config.glove_char_size if config.pretrained_char else None
char_emb_dim = (config.glove_dim if config.pretrained_char else config.
char_dim)
word2idx_dict = None
if os.path.isfile(config.word2idx_file):
with open(config.word2idx_file, 'r') as fh:
word2idx_dict = json.load(fh)
word_emb_mat, word2idx_dict = get_embedding(word_counter, 'word',
emb_file=word_emb_file, size=config.glove_word_size, vec_size=
config.glove_dim, token2idx_dict=word2idx_dict)
char2idx_dict = None
if os.path.isfile(config.char2idx_file):
with open(config.char2idx_file, 'r') as fh:
char2idx_dict = json.load(fh)
char_emb_mat, char2idx_dict = get_embedding(char_counter, 'char',
emb_file=char_emb_file, size=char_emb_size, vec_size=char_emb_dim,
token2idx_dict=char2idx_dict)
build_features_SemEval(config, train_examples, 'train', config.
train_record_file, word2idx_dict, char2idx_dict)
dev_meta = build_features_SemEval(config, dev_examples, 'dev', config.
dev_record_file, word2idx_dict, char2idx_dict)
test_meta = build_features_SemEval(config, test_examples, 'test',
config.test_record_file, word2idx_dict, char2idx_dict, is_test=True)
save(config.word_emb_file, word_emb_mat, message='word embedding')
save(config.char_emb_file, char_emb_mat, message='char embedding')
save(config.dev_meta, dev_meta, message='dev meta')
save(config.word2idx_file, word2idx_dict, message='word2idx')
save(config.char2idx_file, char2idx_dict, message='char2idx')
save(config.test_meta, test_meta, message='test meta')
save('data/test.json', dev_examples, message='test example')
<|reserved_special_token_1|>
<|reserved_special_token_0|>
nlp = spacy.blank('en')
def word_tokenize(sent):
doc = nlp(sent)
return [token.text for token in doc]
def convert_idx(text, tokens):
current = 0
spans = []
for token in tokens:
current = text.find(token, current)
if current < 0:
print('Token {} cannot be found'.format(token))
raise Exception()
spans.append((current, current + len(token)))
current += len(token)
return spans
def process_file(filename, data_type, word_counter, char_counter, shuffle=False
):
print('Generating {} examples...'.format(data_type))
examples = []
eval_examples = {}
total = 0
with open(filename, 'r') as fh:
for l in fh:
ques, ans, label = l.strip().split('\t')
ques_tokens = word_tokenize(ques)
ques_chars = [list(token) for token in ques_tokens]
ans_tokens = word_tokenize(ans)
ans_chars = [list(token) for token in ans_tokens]
label = int(label)
total += 1
for token in ques_tokens:
word_counter[token.lower()] += 1
for char in token:
char_counter[char] += 1
for token in ans_tokens:
word_counter[token.lower()] += 1
for char in token:
char_counter[char] += 1
example = {'ans_tokens': ans_tokens, 'ans_chars': ans_chars,
'ques_tokens': ques_tokens, 'ques_chars': ques_chars, 'y':
label, 'id': total}
examples.append(example)
if random:
random.shuffle(examples)
print('{} questions in total'.format(len(examples)))
return examples
def get_embedding(counter, data_type, limit=-1, emb_file=None, size=None,
vec_size=None, token2idx_dict=None):
print('Generating {} embedding...'.format(data_type))
embedding_dict = {}
filtered_elements = [k for k, v in counter.items() if v > limit]
if emb_file is not None:
assert size is not None
assert vec_size is not None
with open(emb_file, 'r', encoding='utf-8') as fh:
for line in tqdm(fh, total=size):
array = line.split()
word = ''.join(array[0:-vec_size])
vector = list(map(float, array[-vec_size:]))
if word in counter and counter[word] > limit:
embedding_dict[word] = vector
print('{} / {} tokens have corresponding {} embedding vector'.
format(len(embedding_dict), len(filtered_elements), data_type))
else:
assert vec_size is not None
for token in filtered_elements:
embedding_dict[token] = [np.random.normal(scale=0.01) for _ in
range(vec_size)]
print('{} tokens have corresponding embedding vector'.format(len(
filtered_elements)))
NULL = '--NULL--'
OOV = '--OOV--'
token2idx_dict = {token: idx for idx, token in enumerate(embedding_dict
.keys(), 2)} if token2idx_dict is None else token2idx_dict
token2idx_dict[NULL] = 0
token2idx_dict[OOV] = 1
embedding_dict[NULL] = [(0.0) for _ in range(vec_size)]
embedding_dict[OOV] = [(0.0) for _ in range(vec_size)]
idx2emb_dict = {idx: embedding_dict[token] for token, idx in
token2idx_dict.items()}
emb_mat = [idx2emb_dict[idx] for idx in range(len(idx2emb_dict))]
return emb_mat, token2idx_dict
def build_features_SemEval(config, examples, data_type, out_file,
word2idx_dict, char2idx_dict, is_test=False):
ans_limit = config.test_para_limit if is_test else config.para_limit
ques_limit = config.test_ques_limit if is_test else config.ques_limit
char_limit = config.char_limit
def filter_func(example, is_test=False):
return len(example['ans_tokens']) > ans_limit or len(example[
'ques_tokens']) > ques_limit
print('Processing {} examples...'.format(data_type))
writer = tf.python_io.TFRecordWriter(out_file)
total = 0
total_ = 0
meta = {}
for example in tqdm(examples):
total_ += 1
total += 1
context_idxs = np.zeros([ans_limit], dtype=np.int32)
context_char_idxs = np.zeros([ans_limit, char_limit], dtype=np.int32)
ques_idxs = np.zeros([ques_limit], dtype=np.int32)
ques_char_idxs = np.zeros([ques_limit, char_limit], dtype=np.int32)
y = 0
def _get_word(word):
for each in (word, word.lower(), word.capitalize(), word.upper()):
if each in word2idx_dict:
return word2idx_dict[each]
return 1
def _get_char(char):
if char in char2idx_dict:
return char2idx_dict[char]
return 1
for i, token in enumerate(example['ans_tokens'][:ans_limit]):
context_idxs[i] = _get_word(token)
for i, token in enumerate(example['ques_tokens'][:ques_limit]):
ques_idxs[i] = _get_word(token)
for i, token in enumerate(example['ans_chars'][:ans_limit]):
for j, char in enumerate(token):
if j == char_limit:
break
context_char_idxs[i, j] = _get_char(char)
for i, token in enumerate(example['ques_chars'][:ques_limit]):
for j, char in enumerate(token):
if j == char_limit:
break
ques_char_idxs[i, j] = _get_char(char)
label = example['y']
y = float(label)
record = tf.train.Example(features=tf.train.Features(feature={
'ans_idxs': tf.train.Feature(bytes_list=tf.train.BytesList(
value=[context_idxs.tostring()])), 'ques_idxs': tf.train.
Feature(bytes_list=tf.train.BytesList(value=[ques_idxs.tostring
()])), 'ans_char_idxs': tf.train.Feature(bytes_list=tf.train.
BytesList(value=[context_char_idxs.tostring()])),
'ques_char_idxs': tf.train.Feature(bytes_list=tf.train.
BytesList(value=[ques_char_idxs.tostring()])), 'y': tf.train.
Feature(bytes_list=tf.train.BytesList(value=[np.array([y]).
tostring()])), 'id': tf.train.Feature(int64_list=tf.train.
Int64List(value=[example['id']]))}))
writer.write(record.SerializeToString())
print('Build {} / {} instances of features in total'.format(total, total_))
meta['total'] = total
writer.close()
return meta
def save(filename, obj, message=None):
if message is not None:
print('Saving {}...'.format(message))
with open(filename, 'w') as fh:
json.dump(obj, fh)
def preproSemEval(config):
word_counter, char_counter = Counter(), Counter()
train_examples = process_file(config.SemEval_train_file, 'train',
word_counter, char_counter, shuffle=True)
dev_examples = process_file(config.SemEval_dev_file, 'dev',
word_counter, char_counter)
test_examples = process_file(config.SemEval_test_file, 'test',
word_counter, char_counter)
word_emb_file = (config.fasttext_file if config.fasttext else config.
glove_word_file)
char_emb_file = config.glove_char_file if config.pretrained_char else None
char_emb_size = config.glove_char_size if config.pretrained_char else None
char_emb_dim = (config.glove_dim if config.pretrained_char else config.
char_dim)
word2idx_dict = None
if os.path.isfile(config.word2idx_file):
with open(config.word2idx_file, 'r') as fh:
word2idx_dict = json.load(fh)
word_emb_mat, word2idx_dict = get_embedding(word_counter, 'word',
emb_file=word_emb_file, size=config.glove_word_size, vec_size=
config.glove_dim, token2idx_dict=word2idx_dict)
char2idx_dict = None
if os.path.isfile(config.char2idx_file):
with open(config.char2idx_file, 'r') as fh:
char2idx_dict = json.load(fh)
char_emb_mat, char2idx_dict = get_embedding(char_counter, 'char',
emb_file=char_emb_file, size=char_emb_size, vec_size=char_emb_dim,
token2idx_dict=char2idx_dict)
build_features_SemEval(config, train_examples, 'train', config.
train_record_file, word2idx_dict, char2idx_dict)
dev_meta = build_features_SemEval(config, dev_examples, 'dev', config.
dev_record_file, word2idx_dict, char2idx_dict)
test_meta = build_features_SemEval(config, test_examples, 'test',
config.test_record_file, word2idx_dict, char2idx_dict, is_test=True)
save(config.word_emb_file, word_emb_mat, message='word embedding')
save(config.char_emb_file, char_emb_mat, message='char embedding')
save(config.dev_meta, dev_meta, message='dev meta')
save(config.word2idx_file, word2idx_dict, message='word2idx')
save(config.char2idx_file, char2idx_dict, message='char2idx')
save(config.test_meta, test_meta, message='test meta')
save('data/test.json', dev_examples, message='test example')
<|reserved_special_token_1|>
import tensorflow as tf
import random
from tqdm import tqdm
import spacy
import ujson as json
from collections import Counter
import numpy as np
import os.path
nlp = spacy.blank("en")
def word_tokenize(sent):
doc = nlp(sent)
return [token.text for token in doc]
def convert_idx(text, tokens):
current = 0
spans = []
for token in tokens:
current = text.find(token, current)
if current < 0:
print("Token {} cannot be found".format(token))
raise Exception()
spans.append((current, current + len(token)))
current += len(token)
return spans
def process_file(filename, data_type, word_counter, char_counter, shuffle=False):
print("Generating {} examples...".format(data_type))
examples = []
eval_examples = {}
total = 0
with open(filename, "r") as fh:
for l in fh:
ques, ans, label = l.strip().split("\t")
ques_tokens = word_tokenize(ques)
ques_chars = [list(token) for token in ques_tokens]
ans_tokens = word_tokenize(ans)
ans_chars = [list(token) for token in ans_tokens]
label = int(label)
total += 1
for token in ques_tokens:
word_counter[token.lower()] += 1
for char in token:
char_counter[char] += 1
for token in ans_tokens:
word_counter[token.lower()] += 1
for char in token:
char_counter[char] += 1
example = {"ans_tokens": ans_tokens,
"ans_chars": ans_chars, "ques_tokens": ques_tokens,
"ques_chars": ques_chars, "y":label, "id": total}
examples.append(example)
if random:
random.shuffle(examples)
print("{} questions in total".format(len(examples)))
return examples
def get_embedding(counter, data_type, limit=-1, emb_file=None, size=None, vec_size=None, token2idx_dict=None):
print("Generating {} embedding...".format(data_type))
embedding_dict = {}
filtered_elements = [k for k, v in counter.items() if v > limit]
if emb_file is not None:
assert size is not None
assert vec_size is not None
with open(emb_file, "r", encoding="utf-8") as fh:
for line in tqdm(fh, total=size):
array = line.split()
word = "".join(array[0:-vec_size])
vector = list(map(float, array[-vec_size:]))
if word in counter and counter[word] > limit:
embedding_dict[word] = vector
print("{} / {} tokens have corresponding {} embedding vector".format(
len(embedding_dict), len(filtered_elements), data_type))
else:
assert vec_size is not None
for token in filtered_elements:
embedding_dict[token] = [np.random.normal(
scale=0.01) for _ in range(vec_size)]
print("{} tokens have corresponding embedding vector".format(
len(filtered_elements)))
NULL = "--NULL--"
OOV = "--OOV--"
token2idx_dict = {token: idx for idx, token in enumerate(
embedding_dict.keys(), 2)} if token2idx_dict is None else token2idx_dict
token2idx_dict[NULL] = 0
token2idx_dict[OOV] = 1
embedding_dict[NULL] = [0. for _ in range(vec_size)]
embedding_dict[OOV] = [0. for _ in range(vec_size)]
idx2emb_dict = {idx: embedding_dict[token]
for token, idx in token2idx_dict.items()}
emb_mat = [idx2emb_dict[idx] for idx in range(len(idx2emb_dict))]
return emb_mat, token2idx_dict
def build_features_SemEval(config, examples, data_type, out_file, word2idx_dict, char2idx_dict, is_test=False):
ans_limit = config.test_para_limit if is_test else config.para_limit
ques_limit = config.test_ques_limit if is_test else config.ques_limit
char_limit = config.char_limit
def filter_func(example, is_test=False):
return len(example["ans_tokens"]) > ans_limit or len(example["ques_tokens"]) > ques_limit
print("Processing {} examples...".format(data_type))
writer = tf.python_io.TFRecordWriter(out_file)
total = 0
total_ = 0
meta = {}
for example in tqdm(examples):
total_ += 1
#if filter_func(example, is_test):
# continue
total += 1
context_idxs = np.zeros([ans_limit], dtype=np.int32)
context_char_idxs = np.zeros([ans_limit, char_limit], dtype=np.int32)
ques_idxs = np.zeros([ques_limit], dtype=np.int32)
ques_char_idxs = np.zeros([ques_limit, char_limit], dtype=np.int32)
y = 0
def _get_word(word):
for each in (word, word.lower(), word.capitalize(), word.upper()):
if each in word2idx_dict:
return word2idx_dict[each]
return 1
def _get_char(char):
if char in char2idx_dict:
return char2idx_dict[char]
return 1
for i, token in enumerate(example["ans_tokens"][:ans_limit]):
context_idxs[i] = _get_word(token)
for i, token in enumerate(example["ques_tokens"][:ques_limit]):
ques_idxs[i] = _get_word(token)
for i, token in enumerate(example["ans_chars"][:ans_limit]):
for j, char in enumerate(token):
if j == char_limit:
break
context_char_idxs[i, j] = _get_char(char)
for i, token in enumerate(example["ques_chars"][:ques_limit]):
for j, char in enumerate(token):
if j == char_limit:
break
ques_char_idxs[i, j] = _get_char(char)
label = example["y"]
y = float(label)
record = tf.train.Example(features=tf.train.Features(feature={
"ans_idxs": tf.train.Feature(bytes_list=tf.train.BytesList(value=[context_idxs.tostring()])),
"ques_idxs": tf.train.Feature(bytes_list=tf.train.BytesList(value=[ques_idxs.tostring()])),
"ans_char_idxs": tf.train.Feature(bytes_list=tf.train.BytesList(value=[context_char_idxs.tostring()])),
"ques_char_idxs": tf.train.Feature(bytes_list=tf.train.BytesList(value=[ques_char_idxs.tostring()])),
"y": tf.train.Feature(bytes_list=tf.train.BytesList(value=[np.array([y]).tostring()])),
"id": tf.train.Feature(int64_list=tf.train.Int64List(value=[example["id"]]))
}))
writer.write(record.SerializeToString())
print("Build {} / {} instances of features in total".format(total, total_))
meta["total"] = total
writer.close()
return meta
def save(filename, obj, message=None):
if message is not None:
print("Saving {}...".format(message))
with open(filename, "w") as fh:
json.dump(obj, fh)
def preproSemEval(config):
word_counter, char_counter = Counter(), Counter()
train_examples = process_file(
config.SemEval_train_file, "train", word_counter, char_counter, shuffle=True)
dev_examples = process_file(
config.SemEval_dev_file, "dev", word_counter, char_counter)
test_examples = process_file(
config.SemEval_test_file, "test", word_counter, char_counter)
word_emb_file = config.fasttext_file if config.fasttext else config.glove_word_file
char_emb_file = config.glove_char_file if config.pretrained_char else None
char_emb_size = config.glove_char_size if config.pretrained_char else None
char_emb_dim = config.glove_dim if config.pretrained_char else config.char_dim
word2idx_dict = None
if os.path.isfile(config.word2idx_file):
with open(config.word2idx_file, "r") as fh:
word2idx_dict = json.load(fh)
word_emb_mat, word2idx_dict = get_embedding(word_counter, "word", emb_file=word_emb_file,
size=config.glove_word_size, vec_size=config.glove_dim, token2idx_dict=word2idx_dict)
char2idx_dict = None
if os.path.isfile(config.char2idx_file):
with open(config.char2idx_file, "r") as fh:
char2idx_dict = json.load(fh)
char_emb_mat, char2idx_dict = get_embedding(
char_counter, "char", emb_file=char_emb_file, size=char_emb_size, vec_size=char_emb_dim, token2idx_dict=char2idx_dict)
build_features_SemEval(config, train_examples, "train",
config.train_record_file, word2idx_dict, char2idx_dict)
dev_meta = build_features_SemEval(config, dev_examples, "dev",
config.dev_record_file, word2idx_dict, char2idx_dict)
test_meta = build_features_SemEval(config, test_examples, "test",
config.test_record_file, word2idx_dict, char2idx_dict, is_test=True)
save(config.word_emb_file, word_emb_mat, message="word embedding")
save(config.char_emb_file, char_emb_mat, message="char embedding")
save(config.dev_meta, dev_meta, message="dev meta")
save(config.word2idx_file, word2idx_dict, message="word2idx")
save(config.char2idx_file, char2idx_dict, message="char2idx")
save(config.test_meta, test_meta, message="test meta")
save("data/test.json", dev_examples, message="test example")
|
flexible
|
{
"blob_id": "5cd9d4fe9889c4d53b50d86fa78ae84d0c242536",
"index": 3693,
"step-1": "<mask token>\n\n\ndef convert_idx(text, tokens):\n current = 0\n spans = []\n for token in tokens:\n current = text.find(token, current)\n if current < 0:\n print('Token {} cannot be found'.format(token))\n raise Exception()\n spans.append((current, current + len(token)))\n current += len(token)\n return spans\n\n\ndef process_file(filename, data_type, word_counter, char_counter, shuffle=False\n ):\n print('Generating {} examples...'.format(data_type))\n examples = []\n eval_examples = {}\n total = 0\n with open(filename, 'r') as fh:\n for l in fh:\n ques, ans, label = l.strip().split('\\t')\n ques_tokens = word_tokenize(ques)\n ques_chars = [list(token) for token in ques_tokens]\n ans_tokens = word_tokenize(ans)\n ans_chars = [list(token) for token in ans_tokens]\n label = int(label)\n total += 1\n for token in ques_tokens:\n word_counter[token.lower()] += 1\n for char in token:\n char_counter[char] += 1\n for token in ans_tokens:\n word_counter[token.lower()] += 1\n for char in token:\n char_counter[char] += 1\n example = {'ans_tokens': ans_tokens, 'ans_chars': ans_chars,\n 'ques_tokens': ques_tokens, 'ques_chars': ques_chars, 'y':\n label, 'id': total}\n examples.append(example)\n if random:\n random.shuffle(examples)\n print('{} questions in total'.format(len(examples)))\n return examples\n\n\n<mask token>\n\n\ndef build_features_SemEval(config, examples, data_type, out_file,\n word2idx_dict, char2idx_dict, is_test=False):\n ans_limit = config.test_para_limit if is_test else config.para_limit\n ques_limit = config.test_ques_limit if is_test else config.ques_limit\n char_limit = config.char_limit\n\n def filter_func(example, is_test=False):\n return len(example['ans_tokens']) > ans_limit or len(example[\n 'ques_tokens']) > ques_limit\n print('Processing {} examples...'.format(data_type))\n writer = tf.python_io.TFRecordWriter(out_file)\n total = 0\n total_ = 0\n meta = {}\n for example in tqdm(examples):\n total_ += 1\n total += 1\n context_idxs = np.zeros([ans_limit], dtype=np.int32)\n context_char_idxs = np.zeros([ans_limit, char_limit], dtype=np.int32)\n ques_idxs = np.zeros([ques_limit], dtype=np.int32)\n ques_char_idxs = np.zeros([ques_limit, char_limit], dtype=np.int32)\n y = 0\n\n def _get_word(word):\n for each in (word, word.lower(), word.capitalize(), word.upper()):\n if each in word2idx_dict:\n return word2idx_dict[each]\n return 1\n\n def _get_char(char):\n if char in char2idx_dict:\n return char2idx_dict[char]\n return 1\n for i, token in enumerate(example['ans_tokens'][:ans_limit]):\n context_idxs[i] = _get_word(token)\n for i, token in enumerate(example['ques_tokens'][:ques_limit]):\n ques_idxs[i] = _get_word(token)\n for i, token in enumerate(example['ans_chars'][:ans_limit]):\n for j, char in enumerate(token):\n if j == char_limit:\n break\n context_char_idxs[i, j] = _get_char(char)\n for i, token in enumerate(example['ques_chars'][:ques_limit]):\n for j, char in enumerate(token):\n if j == char_limit:\n break\n ques_char_idxs[i, j] = _get_char(char)\n label = example['y']\n y = float(label)\n record = tf.train.Example(features=tf.train.Features(feature={\n 'ans_idxs': tf.train.Feature(bytes_list=tf.train.BytesList(\n value=[context_idxs.tostring()])), 'ques_idxs': tf.train.\n Feature(bytes_list=tf.train.BytesList(value=[ques_idxs.tostring\n ()])), 'ans_char_idxs': tf.train.Feature(bytes_list=tf.train.\n BytesList(value=[context_char_idxs.tostring()])),\n 'ques_char_idxs': tf.train.Feature(bytes_list=tf.train.\n BytesList(value=[ques_char_idxs.tostring()])), 'y': tf.train.\n Feature(bytes_list=tf.train.BytesList(value=[np.array([y]).\n tostring()])), 'id': tf.train.Feature(int64_list=tf.train.\n Int64List(value=[example['id']]))}))\n writer.write(record.SerializeToString())\n print('Build {} / {} instances of features in total'.format(total, total_))\n meta['total'] = total\n writer.close()\n return meta\n\n\ndef save(filename, obj, message=None):\n if message is not None:\n print('Saving {}...'.format(message))\n with open(filename, 'w') as fh:\n json.dump(obj, fh)\n\n\ndef preproSemEval(config):\n word_counter, char_counter = Counter(), Counter()\n train_examples = process_file(config.SemEval_train_file, 'train',\n word_counter, char_counter, shuffle=True)\n dev_examples = process_file(config.SemEval_dev_file, 'dev',\n word_counter, char_counter)\n test_examples = process_file(config.SemEval_test_file, 'test',\n word_counter, char_counter)\n word_emb_file = (config.fasttext_file if config.fasttext else config.\n glove_word_file)\n char_emb_file = config.glove_char_file if config.pretrained_char else None\n char_emb_size = config.glove_char_size if config.pretrained_char else None\n char_emb_dim = (config.glove_dim if config.pretrained_char else config.\n char_dim)\n word2idx_dict = None\n if os.path.isfile(config.word2idx_file):\n with open(config.word2idx_file, 'r') as fh:\n word2idx_dict = json.load(fh)\n word_emb_mat, word2idx_dict = get_embedding(word_counter, 'word',\n emb_file=word_emb_file, size=config.glove_word_size, vec_size=\n config.glove_dim, token2idx_dict=word2idx_dict)\n char2idx_dict = None\n if os.path.isfile(config.char2idx_file):\n with open(config.char2idx_file, 'r') as fh:\n char2idx_dict = json.load(fh)\n char_emb_mat, char2idx_dict = get_embedding(char_counter, 'char',\n emb_file=char_emb_file, size=char_emb_size, vec_size=char_emb_dim,\n token2idx_dict=char2idx_dict)\n build_features_SemEval(config, train_examples, 'train', config.\n train_record_file, word2idx_dict, char2idx_dict)\n dev_meta = build_features_SemEval(config, dev_examples, 'dev', config.\n dev_record_file, word2idx_dict, char2idx_dict)\n test_meta = build_features_SemEval(config, test_examples, 'test',\n config.test_record_file, word2idx_dict, char2idx_dict, is_test=True)\n save(config.word_emb_file, word_emb_mat, message='word embedding')\n save(config.char_emb_file, char_emb_mat, message='char embedding')\n save(config.dev_meta, dev_meta, message='dev meta')\n save(config.word2idx_file, word2idx_dict, message='word2idx')\n save(config.char2idx_file, char2idx_dict, message='char2idx')\n save(config.test_meta, test_meta, message='test meta')\n save('data/test.json', dev_examples, message='test example')\n",
"step-2": "<mask token>\n\n\ndef convert_idx(text, tokens):\n current = 0\n spans = []\n for token in tokens:\n current = text.find(token, current)\n if current < 0:\n print('Token {} cannot be found'.format(token))\n raise Exception()\n spans.append((current, current + len(token)))\n current += len(token)\n return spans\n\n\ndef process_file(filename, data_type, word_counter, char_counter, shuffle=False\n ):\n print('Generating {} examples...'.format(data_type))\n examples = []\n eval_examples = {}\n total = 0\n with open(filename, 'r') as fh:\n for l in fh:\n ques, ans, label = l.strip().split('\\t')\n ques_tokens = word_tokenize(ques)\n ques_chars = [list(token) for token in ques_tokens]\n ans_tokens = word_tokenize(ans)\n ans_chars = [list(token) for token in ans_tokens]\n label = int(label)\n total += 1\n for token in ques_tokens:\n word_counter[token.lower()] += 1\n for char in token:\n char_counter[char] += 1\n for token in ans_tokens:\n word_counter[token.lower()] += 1\n for char in token:\n char_counter[char] += 1\n example = {'ans_tokens': ans_tokens, 'ans_chars': ans_chars,\n 'ques_tokens': ques_tokens, 'ques_chars': ques_chars, 'y':\n label, 'id': total}\n examples.append(example)\n if random:\n random.shuffle(examples)\n print('{} questions in total'.format(len(examples)))\n return examples\n\n\ndef get_embedding(counter, data_type, limit=-1, emb_file=None, size=None,\n vec_size=None, token2idx_dict=None):\n print('Generating {} embedding...'.format(data_type))\n embedding_dict = {}\n filtered_elements = [k for k, v in counter.items() if v > limit]\n if emb_file is not None:\n assert size is not None\n assert vec_size is not None\n with open(emb_file, 'r', encoding='utf-8') as fh:\n for line in tqdm(fh, total=size):\n array = line.split()\n word = ''.join(array[0:-vec_size])\n vector = list(map(float, array[-vec_size:]))\n if word in counter and counter[word] > limit:\n embedding_dict[word] = vector\n print('{} / {} tokens have corresponding {} embedding vector'.\n format(len(embedding_dict), len(filtered_elements), data_type))\n else:\n assert vec_size is not None\n for token in filtered_elements:\n embedding_dict[token] = [np.random.normal(scale=0.01) for _ in\n range(vec_size)]\n print('{} tokens have corresponding embedding vector'.format(len(\n filtered_elements)))\n NULL = '--NULL--'\n OOV = '--OOV--'\n token2idx_dict = {token: idx for idx, token in enumerate(embedding_dict\n .keys(), 2)} if token2idx_dict is None else token2idx_dict\n token2idx_dict[NULL] = 0\n token2idx_dict[OOV] = 1\n embedding_dict[NULL] = [(0.0) for _ in range(vec_size)]\n embedding_dict[OOV] = [(0.0) for _ in range(vec_size)]\n idx2emb_dict = {idx: embedding_dict[token] for token, idx in\n token2idx_dict.items()}\n emb_mat = [idx2emb_dict[idx] for idx in range(len(idx2emb_dict))]\n return emb_mat, token2idx_dict\n\n\ndef build_features_SemEval(config, examples, data_type, out_file,\n word2idx_dict, char2idx_dict, is_test=False):\n ans_limit = config.test_para_limit if is_test else config.para_limit\n ques_limit = config.test_ques_limit if is_test else config.ques_limit\n char_limit = config.char_limit\n\n def filter_func(example, is_test=False):\n return len(example['ans_tokens']) > ans_limit or len(example[\n 'ques_tokens']) > ques_limit\n print('Processing {} examples...'.format(data_type))\n writer = tf.python_io.TFRecordWriter(out_file)\n total = 0\n total_ = 0\n meta = {}\n for example in tqdm(examples):\n total_ += 1\n total += 1\n context_idxs = np.zeros([ans_limit], dtype=np.int32)\n context_char_idxs = np.zeros([ans_limit, char_limit], dtype=np.int32)\n ques_idxs = np.zeros([ques_limit], dtype=np.int32)\n ques_char_idxs = np.zeros([ques_limit, char_limit], dtype=np.int32)\n y = 0\n\n def _get_word(word):\n for each in (word, word.lower(), word.capitalize(), word.upper()):\n if each in word2idx_dict:\n return word2idx_dict[each]\n return 1\n\n def _get_char(char):\n if char in char2idx_dict:\n return char2idx_dict[char]\n return 1\n for i, token in enumerate(example['ans_tokens'][:ans_limit]):\n context_idxs[i] = _get_word(token)\n for i, token in enumerate(example['ques_tokens'][:ques_limit]):\n ques_idxs[i] = _get_word(token)\n for i, token in enumerate(example['ans_chars'][:ans_limit]):\n for j, char in enumerate(token):\n if j == char_limit:\n break\n context_char_idxs[i, j] = _get_char(char)\n for i, token in enumerate(example['ques_chars'][:ques_limit]):\n for j, char in enumerate(token):\n if j == char_limit:\n break\n ques_char_idxs[i, j] = _get_char(char)\n label = example['y']\n y = float(label)\n record = tf.train.Example(features=tf.train.Features(feature={\n 'ans_idxs': tf.train.Feature(bytes_list=tf.train.BytesList(\n value=[context_idxs.tostring()])), 'ques_idxs': tf.train.\n Feature(bytes_list=tf.train.BytesList(value=[ques_idxs.tostring\n ()])), 'ans_char_idxs': tf.train.Feature(bytes_list=tf.train.\n BytesList(value=[context_char_idxs.tostring()])),\n 'ques_char_idxs': tf.train.Feature(bytes_list=tf.train.\n BytesList(value=[ques_char_idxs.tostring()])), 'y': tf.train.\n Feature(bytes_list=tf.train.BytesList(value=[np.array([y]).\n tostring()])), 'id': tf.train.Feature(int64_list=tf.train.\n Int64List(value=[example['id']]))}))\n writer.write(record.SerializeToString())\n print('Build {} / {} instances of features in total'.format(total, total_))\n meta['total'] = total\n writer.close()\n return meta\n\n\ndef save(filename, obj, message=None):\n if message is not None:\n print('Saving {}...'.format(message))\n with open(filename, 'w') as fh:\n json.dump(obj, fh)\n\n\ndef preproSemEval(config):\n word_counter, char_counter = Counter(), Counter()\n train_examples = process_file(config.SemEval_train_file, 'train',\n word_counter, char_counter, shuffle=True)\n dev_examples = process_file(config.SemEval_dev_file, 'dev',\n word_counter, char_counter)\n test_examples = process_file(config.SemEval_test_file, 'test',\n word_counter, char_counter)\n word_emb_file = (config.fasttext_file if config.fasttext else config.\n glove_word_file)\n char_emb_file = config.glove_char_file if config.pretrained_char else None\n char_emb_size = config.glove_char_size if config.pretrained_char else None\n char_emb_dim = (config.glove_dim if config.pretrained_char else config.\n char_dim)\n word2idx_dict = None\n if os.path.isfile(config.word2idx_file):\n with open(config.word2idx_file, 'r') as fh:\n word2idx_dict = json.load(fh)\n word_emb_mat, word2idx_dict = get_embedding(word_counter, 'word',\n emb_file=word_emb_file, size=config.glove_word_size, vec_size=\n config.glove_dim, token2idx_dict=word2idx_dict)\n char2idx_dict = None\n if os.path.isfile(config.char2idx_file):\n with open(config.char2idx_file, 'r') as fh:\n char2idx_dict = json.load(fh)\n char_emb_mat, char2idx_dict = get_embedding(char_counter, 'char',\n emb_file=char_emb_file, size=char_emb_size, vec_size=char_emb_dim,\n token2idx_dict=char2idx_dict)\n build_features_SemEval(config, train_examples, 'train', config.\n train_record_file, word2idx_dict, char2idx_dict)\n dev_meta = build_features_SemEval(config, dev_examples, 'dev', config.\n dev_record_file, word2idx_dict, char2idx_dict)\n test_meta = build_features_SemEval(config, test_examples, 'test',\n config.test_record_file, word2idx_dict, char2idx_dict, is_test=True)\n save(config.word_emb_file, word_emb_mat, message='word embedding')\n save(config.char_emb_file, char_emb_mat, message='char embedding')\n save(config.dev_meta, dev_meta, message='dev meta')\n save(config.word2idx_file, word2idx_dict, message='word2idx')\n save(config.char2idx_file, char2idx_dict, message='char2idx')\n save(config.test_meta, test_meta, message='test meta')\n save('data/test.json', dev_examples, message='test example')\n",
"step-3": "<mask token>\n\n\ndef word_tokenize(sent):\n doc = nlp(sent)\n return [token.text for token in doc]\n\n\ndef convert_idx(text, tokens):\n current = 0\n spans = []\n for token in tokens:\n current = text.find(token, current)\n if current < 0:\n print('Token {} cannot be found'.format(token))\n raise Exception()\n spans.append((current, current + len(token)))\n current += len(token)\n return spans\n\n\ndef process_file(filename, data_type, word_counter, char_counter, shuffle=False\n ):\n print('Generating {} examples...'.format(data_type))\n examples = []\n eval_examples = {}\n total = 0\n with open(filename, 'r') as fh:\n for l in fh:\n ques, ans, label = l.strip().split('\\t')\n ques_tokens = word_tokenize(ques)\n ques_chars = [list(token) for token in ques_tokens]\n ans_tokens = word_tokenize(ans)\n ans_chars = [list(token) for token in ans_tokens]\n label = int(label)\n total += 1\n for token in ques_tokens:\n word_counter[token.lower()] += 1\n for char in token:\n char_counter[char] += 1\n for token in ans_tokens:\n word_counter[token.lower()] += 1\n for char in token:\n char_counter[char] += 1\n example = {'ans_tokens': ans_tokens, 'ans_chars': ans_chars,\n 'ques_tokens': ques_tokens, 'ques_chars': ques_chars, 'y':\n label, 'id': total}\n examples.append(example)\n if random:\n random.shuffle(examples)\n print('{} questions in total'.format(len(examples)))\n return examples\n\n\ndef get_embedding(counter, data_type, limit=-1, emb_file=None, size=None,\n vec_size=None, token2idx_dict=None):\n print('Generating {} embedding...'.format(data_type))\n embedding_dict = {}\n filtered_elements = [k for k, v in counter.items() if v > limit]\n if emb_file is not None:\n assert size is not None\n assert vec_size is not None\n with open(emb_file, 'r', encoding='utf-8') as fh:\n for line in tqdm(fh, total=size):\n array = line.split()\n word = ''.join(array[0:-vec_size])\n vector = list(map(float, array[-vec_size:]))\n if word in counter and counter[word] > limit:\n embedding_dict[word] = vector\n print('{} / {} tokens have corresponding {} embedding vector'.\n format(len(embedding_dict), len(filtered_elements), data_type))\n else:\n assert vec_size is not None\n for token in filtered_elements:\n embedding_dict[token] = [np.random.normal(scale=0.01) for _ in\n range(vec_size)]\n print('{} tokens have corresponding embedding vector'.format(len(\n filtered_elements)))\n NULL = '--NULL--'\n OOV = '--OOV--'\n token2idx_dict = {token: idx for idx, token in enumerate(embedding_dict\n .keys(), 2)} if token2idx_dict is None else token2idx_dict\n token2idx_dict[NULL] = 0\n token2idx_dict[OOV] = 1\n embedding_dict[NULL] = [(0.0) for _ in range(vec_size)]\n embedding_dict[OOV] = [(0.0) for _ in range(vec_size)]\n idx2emb_dict = {idx: embedding_dict[token] for token, idx in\n token2idx_dict.items()}\n emb_mat = [idx2emb_dict[idx] for idx in range(len(idx2emb_dict))]\n return emb_mat, token2idx_dict\n\n\ndef build_features_SemEval(config, examples, data_type, out_file,\n word2idx_dict, char2idx_dict, is_test=False):\n ans_limit = config.test_para_limit if is_test else config.para_limit\n ques_limit = config.test_ques_limit if is_test else config.ques_limit\n char_limit = config.char_limit\n\n def filter_func(example, is_test=False):\n return len(example['ans_tokens']) > ans_limit or len(example[\n 'ques_tokens']) > ques_limit\n print('Processing {} examples...'.format(data_type))\n writer = tf.python_io.TFRecordWriter(out_file)\n total = 0\n total_ = 0\n meta = {}\n for example in tqdm(examples):\n total_ += 1\n total += 1\n context_idxs = np.zeros([ans_limit], dtype=np.int32)\n context_char_idxs = np.zeros([ans_limit, char_limit], dtype=np.int32)\n ques_idxs = np.zeros([ques_limit], dtype=np.int32)\n ques_char_idxs = np.zeros([ques_limit, char_limit], dtype=np.int32)\n y = 0\n\n def _get_word(word):\n for each in (word, word.lower(), word.capitalize(), word.upper()):\n if each in word2idx_dict:\n return word2idx_dict[each]\n return 1\n\n def _get_char(char):\n if char in char2idx_dict:\n return char2idx_dict[char]\n return 1\n for i, token in enumerate(example['ans_tokens'][:ans_limit]):\n context_idxs[i] = _get_word(token)\n for i, token in enumerate(example['ques_tokens'][:ques_limit]):\n ques_idxs[i] = _get_word(token)\n for i, token in enumerate(example['ans_chars'][:ans_limit]):\n for j, char in enumerate(token):\n if j == char_limit:\n break\n context_char_idxs[i, j] = _get_char(char)\n for i, token in enumerate(example['ques_chars'][:ques_limit]):\n for j, char in enumerate(token):\n if j == char_limit:\n break\n ques_char_idxs[i, j] = _get_char(char)\n label = example['y']\n y = float(label)\n record = tf.train.Example(features=tf.train.Features(feature={\n 'ans_idxs': tf.train.Feature(bytes_list=tf.train.BytesList(\n value=[context_idxs.tostring()])), 'ques_idxs': tf.train.\n Feature(bytes_list=tf.train.BytesList(value=[ques_idxs.tostring\n ()])), 'ans_char_idxs': tf.train.Feature(bytes_list=tf.train.\n BytesList(value=[context_char_idxs.tostring()])),\n 'ques_char_idxs': tf.train.Feature(bytes_list=tf.train.\n BytesList(value=[ques_char_idxs.tostring()])), 'y': tf.train.\n Feature(bytes_list=tf.train.BytesList(value=[np.array([y]).\n tostring()])), 'id': tf.train.Feature(int64_list=tf.train.\n Int64List(value=[example['id']]))}))\n writer.write(record.SerializeToString())\n print('Build {} / {} instances of features in total'.format(total, total_))\n meta['total'] = total\n writer.close()\n return meta\n\n\ndef save(filename, obj, message=None):\n if message is not None:\n print('Saving {}...'.format(message))\n with open(filename, 'w') as fh:\n json.dump(obj, fh)\n\n\ndef preproSemEval(config):\n word_counter, char_counter = Counter(), Counter()\n train_examples = process_file(config.SemEval_train_file, 'train',\n word_counter, char_counter, shuffle=True)\n dev_examples = process_file(config.SemEval_dev_file, 'dev',\n word_counter, char_counter)\n test_examples = process_file(config.SemEval_test_file, 'test',\n word_counter, char_counter)\n word_emb_file = (config.fasttext_file if config.fasttext else config.\n glove_word_file)\n char_emb_file = config.glove_char_file if config.pretrained_char else None\n char_emb_size = config.glove_char_size if config.pretrained_char else None\n char_emb_dim = (config.glove_dim if config.pretrained_char else config.\n char_dim)\n word2idx_dict = None\n if os.path.isfile(config.word2idx_file):\n with open(config.word2idx_file, 'r') as fh:\n word2idx_dict = json.load(fh)\n word_emb_mat, word2idx_dict = get_embedding(word_counter, 'word',\n emb_file=word_emb_file, size=config.glove_word_size, vec_size=\n config.glove_dim, token2idx_dict=word2idx_dict)\n char2idx_dict = None\n if os.path.isfile(config.char2idx_file):\n with open(config.char2idx_file, 'r') as fh:\n char2idx_dict = json.load(fh)\n char_emb_mat, char2idx_dict = get_embedding(char_counter, 'char',\n emb_file=char_emb_file, size=char_emb_size, vec_size=char_emb_dim,\n token2idx_dict=char2idx_dict)\n build_features_SemEval(config, train_examples, 'train', config.\n train_record_file, word2idx_dict, char2idx_dict)\n dev_meta = build_features_SemEval(config, dev_examples, 'dev', config.\n dev_record_file, word2idx_dict, char2idx_dict)\n test_meta = build_features_SemEval(config, test_examples, 'test',\n config.test_record_file, word2idx_dict, char2idx_dict, is_test=True)\n save(config.word_emb_file, word_emb_mat, message='word embedding')\n save(config.char_emb_file, char_emb_mat, message='char embedding')\n save(config.dev_meta, dev_meta, message='dev meta')\n save(config.word2idx_file, word2idx_dict, message='word2idx')\n save(config.char2idx_file, char2idx_dict, message='char2idx')\n save(config.test_meta, test_meta, message='test meta')\n save('data/test.json', dev_examples, message='test example')\n",
"step-4": "<mask token>\nnlp = spacy.blank('en')\n\n\ndef word_tokenize(sent):\n doc = nlp(sent)\n return [token.text for token in doc]\n\n\ndef convert_idx(text, tokens):\n current = 0\n spans = []\n for token in tokens:\n current = text.find(token, current)\n if current < 0:\n print('Token {} cannot be found'.format(token))\n raise Exception()\n spans.append((current, current + len(token)))\n current += len(token)\n return spans\n\n\ndef process_file(filename, data_type, word_counter, char_counter, shuffle=False\n ):\n print('Generating {} examples...'.format(data_type))\n examples = []\n eval_examples = {}\n total = 0\n with open(filename, 'r') as fh:\n for l in fh:\n ques, ans, label = l.strip().split('\\t')\n ques_tokens = word_tokenize(ques)\n ques_chars = [list(token) for token in ques_tokens]\n ans_tokens = word_tokenize(ans)\n ans_chars = [list(token) for token in ans_tokens]\n label = int(label)\n total += 1\n for token in ques_tokens:\n word_counter[token.lower()] += 1\n for char in token:\n char_counter[char] += 1\n for token in ans_tokens:\n word_counter[token.lower()] += 1\n for char in token:\n char_counter[char] += 1\n example = {'ans_tokens': ans_tokens, 'ans_chars': ans_chars,\n 'ques_tokens': ques_tokens, 'ques_chars': ques_chars, 'y':\n label, 'id': total}\n examples.append(example)\n if random:\n random.shuffle(examples)\n print('{} questions in total'.format(len(examples)))\n return examples\n\n\ndef get_embedding(counter, data_type, limit=-1, emb_file=None, size=None,\n vec_size=None, token2idx_dict=None):\n print('Generating {} embedding...'.format(data_type))\n embedding_dict = {}\n filtered_elements = [k for k, v in counter.items() if v > limit]\n if emb_file is not None:\n assert size is not None\n assert vec_size is not None\n with open(emb_file, 'r', encoding='utf-8') as fh:\n for line in tqdm(fh, total=size):\n array = line.split()\n word = ''.join(array[0:-vec_size])\n vector = list(map(float, array[-vec_size:]))\n if word in counter and counter[word] > limit:\n embedding_dict[word] = vector\n print('{} / {} tokens have corresponding {} embedding vector'.\n format(len(embedding_dict), len(filtered_elements), data_type))\n else:\n assert vec_size is not None\n for token in filtered_elements:\n embedding_dict[token] = [np.random.normal(scale=0.01) for _ in\n range(vec_size)]\n print('{} tokens have corresponding embedding vector'.format(len(\n filtered_elements)))\n NULL = '--NULL--'\n OOV = '--OOV--'\n token2idx_dict = {token: idx for idx, token in enumerate(embedding_dict\n .keys(), 2)} if token2idx_dict is None else token2idx_dict\n token2idx_dict[NULL] = 0\n token2idx_dict[OOV] = 1\n embedding_dict[NULL] = [(0.0) for _ in range(vec_size)]\n embedding_dict[OOV] = [(0.0) for _ in range(vec_size)]\n idx2emb_dict = {idx: embedding_dict[token] for token, idx in\n token2idx_dict.items()}\n emb_mat = [idx2emb_dict[idx] for idx in range(len(idx2emb_dict))]\n return emb_mat, token2idx_dict\n\n\ndef build_features_SemEval(config, examples, data_type, out_file,\n word2idx_dict, char2idx_dict, is_test=False):\n ans_limit = config.test_para_limit if is_test else config.para_limit\n ques_limit = config.test_ques_limit if is_test else config.ques_limit\n char_limit = config.char_limit\n\n def filter_func(example, is_test=False):\n return len(example['ans_tokens']) > ans_limit or len(example[\n 'ques_tokens']) > ques_limit\n print('Processing {} examples...'.format(data_type))\n writer = tf.python_io.TFRecordWriter(out_file)\n total = 0\n total_ = 0\n meta = {}\n for example in tqdm(examples):\n total_ += 1\n total += 1\n context_idxs = np.zeros([ans_limit], dtype=np.int32)\n context_char_idxs = np.zeros([ans_limit, char_limit], dtype=np.int32)\n ques_idxs = np.zeros([ques_limit], dtype=np.int32)\n ques_char_idxs = np.zeros([ques_limit, char_limit], dtype=np.int32)\n y = 0\n\n def _get_word(word):\n for each in (word, word.lower(), word.capitalize(), word.upper()):\n if each in word2idx_dict:\n return word2idx_dict[each]\n return 1\n\n def _get_char(char):\n if char in char2idx_dict:\n return char2idx_dict[char]\n return 1\n for i, token in enumerate(example['ans_tokens'][:ans_limit]):\n context_idxs[i] = _get_word(token)\n for i, token in enumerate(example['ques_tokens'][:ques_limit]):\n ques_idxs[i] = _get_word(token)\n for i, token in enumerate(example['ans_chars'][:ans_limit]):\n for j, char in enumerate(token):\n if j == char_limit:\n break\n context_char_idxs[i, j] = _get_char(char)\n for i, token in enumerate(example['ques_chars'][:ques_limit]):\n for j, char in enumerate(token):\n if j == char_limit:\n break\n ques_char_idxs[i, j] = _get_char(char)\n label = example['y']\n y = float(label)\n record = tf.train.Example(features=tf.train.Features(feature={\n 'ans_idxs': tf.train.Feature(bytes_list=tf.train.BytesList(\n value=[context_idxs.tostring()])), 'ques_idxs': tf.train.\n Feature(bytes_list=tf.train.BytesList(value=[ques_idxs.tostring\n ()])), 'ans_char_idxs': tf.train.Feature(bytes_list=tf.train.\n BytesList(value=[context_char_idxs.tostring()])),\n 'ques_char_idxs': tf.train.Feature(bytes_list=tf.train.\n BytesList(value=[ques_char_idxs.tostring()])), 'y': tf.train.\n Feature(bytes_list=tf.train.BytesList(value=[np.array([y]).\n tostring()])), 'id': tf.train.Feature(int64_list=tf.train.\n Int64List(value=[example['id']]))}))\n writer.write(record.SerializeToString())\n print('Build {} / {} instances of features in total'.format(total, total_))\n meta['total'] = total\n writer.close()\n return meta\n\n\ndef save(filename, obj, message=None):\n if message is not None:\n print('Saving {}...'.format(message))\n with open(filename, 'w') as fh:\n json.dump(obj, fh)\n\n\ndef preproSemEval(config):\n word_counter, char_counter = Counter(), Counter()\n train_examples = process_file(config.SemEval_train_file, 'train',\n word_counter, char_counter, shuffle=True)\n dev_examples = process_file(config.SemEval_dev_file, 'dev',\n word_counter, char_counter)\n test_examples = process_file(config.SemEval_test_file, 'test',\n word_counter, char_counter)\n word_emb_file = (config.fasttext_file if config.fasttext else config.\n glove_word_file)\n char_emb_file = config.glove_char_file if config.pretrained_char else None\n char_emb_size = config.glove_char_size if config.pretrained_char else None\n char_emb_dim = (config.glove_dim if config.pretrained_char else config.\n char_dim)\n word2idx_dict = None\n if os.path.isfile(config.word2idx_file):\n with open(config.word2idx_file, 'r') as fh:\n word2idx_dict = json.load(fh)\n word_emb_mat, word2idx_dict = get_embedding(word_counter, 'word',\n emb_file=word_emb_file, size=config.glove_word_size, vec_size=\n config.glove_dim, token2idx_dict=word2idx_dict)\n char2idx_dict = None\n if os.path.isfile(config.char2idx_file):\n with open(config.char2idx_file, 'r') as fh:\n char2idx_dict = json.load(fh)\n char_emb_mat, char2idx_dict = get_embedding(char_counter, 'char',\n emb_file=char_emb_file, size=char_emb_size, vec_size=char_emb_dim,\n token2idx_dict=char2idx_dict)\n build_features_SemEval(config, train_examples, 'train', config.\n train_record_file, word2idx_dict, char2idx_dict)\n dev_meta = build_features_SemEval(config, dev_examples, 'dev', config.\n dev_record_file, word2idx_dict, char2idx_dict)\n test_meta = build_features_SemEval(config, test_examples, 'test',\n config.test_record_file, word2idx_dict, char2idx_dict, is_test=True)\n save(config.word_emb_file, word_emb_mat, message='word embedding')\n save(config.char_emb_file, char_emb_mat, message='char embedding')\n save(config.dev_meta, dev_meta, message='dev meta')\n save(config.word2idx_file, word2idx_dict, message='word2idx')\n save(config.char2idx_file, char2idx_dict, message='char2idx')\n save(config.test_meta, test_meta, message='test meta')\n save('data/test.json', dev_examples, message='test example')\n",
"step-5": "import tensorflow as tf\nimport random\nfrom tqdm import tqdm\nimport spacy\nimport ujson as json\nfrom collections import Counter\nimport numpy as np\nimport os.path\n\nnlp = spacy.blank(\"en\")\n\n\ndef word_tokenize(sent):\n doc = nlp(sent)\n return [token.text for token in doc]\n\n\ndef convert_idx(text, tokens):\n current = 0\n spans = []\n for token in tokens:\n current = text.find(token, current)\n if current < 0:\n print(\"Token {} cannot be found\".format(token))\n raise Exception()\n spans.append((current, current + len(token)))\n current += len(token)\n return spans\n\n\ndef process_file(filename, data_type, word_counter, char_counter, shuffle=False):\n print(\"Generating {} examples...\".format(data_type))\n examples = []\n eval_examples = {}\n total = 0\n with open(filename, \"r\") as fh:\n for l in fh:\n ques, ans, label = l.strip().split(\"\\t\")\n ques_tokens = word_tokenize(ques)\n ques_chars = [list(token) for token in ques_tokens]\n ans_tokens = word_tokenize(ans)\n ans_chars = [list(token) for token in ans_tokens]\n label = int(label)\n total += 1\n for token in ques_tokens:\n word_counter[token.lower()] += 1\n for char in token:\n char_counter[char] += 1\n for token in ans_tokens:\n word_counter[token.lower()] += 1\n for char in token:\n char_counter[char] += 1\n example = {\"ans_tokens\": ans_tokens,\n \"ans_chars\": ans_chars, \"ques_tokens\": ques_tokens,\n \"ques_chars\": ques_chars, \"y\":label, \"id\": total}\n \n examples.append(example)\n if random:\n random.shuffle(examples)\n print(\"{} questions in total\".format(len(examples)))\n return examples\n\n\ndef get_embedding(counter, data_type, limit=-1, emb_file=None, size=None, vec_size=None, token2idx_dict=None):\n print(\"Generating {} embedding...\".format(data_type))\n embedding_dict = {}\n filtered_elements = [k for k, v in counter.items() if v > limit]\n if emb_file is not None:\n assert size is not None\n assert vec_size is not None\n with open(emb_file, \"r\", encoding=\"utf-8\") as fh:\n for line in tqdm(fh, total=size):\n array = line.split()\n word = \"\".join(array[0:-vec_size])\n vector = list(map(float, array[-vec_size:]))\n if word in counter and counter[word] > limit:\n embedding_dict[word] = vector\n print(\"{} / {} tokens have corresponding {} embedding vector\".format(\n len(embedding_dict), len(filtered_elements), data_type))\n else:\n assert vec_size is not None\n for token in filtered_elements:\n embedding_dict[token] = [np.random.normal(\n scale=0.01) for _ in range(vec_size)]\n print(\"{} tokens have corresponding embedding vector\".format(\n len(filtered_elements)))\n\n NULL = \"--NULL--\"\n OOV = \"--OOV--\"\n token2idx_dict = {token: idx for idx, token in enumerate(\n embedding_dict.keys(), 2)} if token2idx_dict is None else token2idx_dict\n token2idx_dict[NULL] = 0\n token2idx_dict[OOV] = 1\n embedding_dict[NULL] = [0. for _ in range(vec_size)]\n embedding_dict[OOV] = [0. for _ in range(vec_size)]\n idx2emb_dict = {idx: embedding_dict[token]\n for token, idx in token2idx_dict.items()}\n emb_mat = [idx2emb_dict[idx] for idx in range(len(idx2emb_dict))]\n return emb_mat, token2idx_dict\n\n\ndef build_features_SemEval(config, examples, data_type, out_file, word2idx_dict, char2idx_dict, is_test=False):\n ans_limit = config.test_para_limit if is_test else config.para_limit\n ques_limit = config.test_ques_limit if is_test else config.ques_limit\n char_limit = config.char_limit\n\n def filter_func(example, is_test=False):\n return len(example[\"ans_tokens\"]) > ans_limit or len(example[\"ques_tokens\"]) > ques_limit\n\n print(\"Processing {} examples...\".format(data_type))\n writer = tf.python_io.TFRecordWriter(out_file)\n total = 0\n total_ = 0\n meta = {}\n for example in tqdm(examples):\n total_ += 1\n\n #if filter_func(example, is_test):\n # continue\n\n total += 1\n context_idxs = np.zeros([ans_limit], dtype=np.int32)\n context_char_idxs = np.zeros([ans_limit, char_limit], dtype=np.int32)\n ques_idxs = np.zeros([ques_limit], dtype=np.int32)\n ques_char_idxs = np.zeros([ques_limit, char_limit], dtype=np.int32)\n y = 0\n \n\n def _get_word(word):\n for each in (word, word.lower(), word.capitalize(), word.upper()):\n if each in word2idx_dict:\n return word2idx_dict[each]\n return 1\n\n def _get_char(char):\n if char in char2idx_dict:\n return char2idx_dict[char]\n return 1\n\n for i, token in enumerate(example[\"ans_tokens\"][:ans_limit]):\n context_idxs[i] = _get_word(token)\n\n for i, token in enumerate(example[\"ques_tokens\"][:ques_limit]):\n ques_idxs[i] = _get_word(token)\n\n for i, token in enumerate(example[\"ans_chars\"][:ans_limit]):\n for j, char in enumerate(token):\n if j == char_limit:\n break\n context_char_idxs[i, j] = _get_char(char)\n\n for i, token in enumerate(example[\"ques_chars\"][:ques_limit]):\n for j, char in enumerate(token):\n if j == char_limit:\n break\n ques_char_idxs[i, j] = _get_char(char)\n\n label = example[\"y\"]\n y = float(label)\n\n record = tf.train.Example(features=tf.train.Features(feature={\n \"ans_idxs\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[context_idxs.tostring()])),\n \"ques_idxs\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[ques_idxs.tostring()])),\n \"ans_char_idxs\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[context_char_idxs.tostring()])),\n \"ques_char_idxs\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[ques_char_idxs.tostring()])),\n \"y\": tf.train.Feature(bytes_list=tf.train.BytesList(value=[np.array([y]).tostring()])),\n \"id\": tf.train.Feature(int64_list=tf.train.Int64List(value=[example[\"id\"]]))\n }))\n writer.write(record.SerializeToString())\n print(\"Build {} / {} instances of features in total\".format(total, total_))\n meta[\"total\"] = total\n writer.close()\n return meta\n\n\ndef save(filename, obj, message=None):\n if message is not None:\n print(\"Saving {}...\".format(message))\n with open(filename, \"w\") as fh:\n json.dump(obj, fh)\n\n\ndef preproSemEval(config):\n word_counter, char_counter = Counter(), Counter()\n train_examples = process_file(\n config.SemEval_train_file, \"train\", word_counter, char_counter, shuffle=True)\n dev_examples = process_file(\n config.SemEval_dev_file, \"dev\", word_counter, char_counter)\n test_examples = process_file(\n config.SemEval_test_file, \"test\", word_counter, char_counter)\n\n word_emb_file = config.fasttext_file if config.fasttext else config.glove_word_file\n char_emb_file = config.glove_char_file if config.pretrained_char else None\n char_emb_size = config.glove_char_size if config.pretrained_char else None\n char_emb_dim = config.glove_dim if config.pretrained_char else config.char_dim\n\n word2idx_dict = None\n if os.path.isfile(config.word2idx_file):\n with open(config.word2idx_file, \"r\") as fh:\n word2idx_dict = json.load(fh)\n word_emb_mat, word2idx_dict = get_embedding(word_counter, \"word\", emb_file=word_emb_file,\n size=config.glove_word_size, vec_size=config.glove_dim, token2idx_dict=word2idx_dict)\n\n char2idx_dict = None\n if os.path.isfile(config.char2idx_file):\n with open(config.char2idx_file, \"r\") as fh:\n char2idx_dict = json.load(fh)\n char_emb_mat, char2idx_dict = get_embedding(\n char_counter, \"char\", emb_file=char_emb_file, size=char_emb_size, vec_size=char_emb_dim, token2idx_dict=char2idx_dict)\n\n build_features_SemEval(config, train_examples, \"train\",\n config.train_record_file, word2idx_dict, char2idx_dict)\n dev_meta = build_features_SemEval(config, dev_examples, \"dev\",\n config.dev_record_file, word2idx_dict, char2idx_dict)\n test_meta = build_features_SemEval(config, test_examples, \"test\",\n config.test_record_file, word2idx_dict, char2idx_dict, is_test=True)\n\n save(config.word_emb_file, word_emb_mat, message=\"word embedding\")\n save(config.char_emb_file, char_emb_mat, message=\"char embedding\")\n save(config.dev_meta, dev_meta, message=\"dev meta\")\n save(config.word2idx_file, word2idx_dict, message=\"word2idx\")\n save(config.char2idx_file, char2idx_dict, message=\"char2idx\")\n save(config.test_meta, test_meta, message=\"test meta\")\n save(\"data/test.json\", dev_examples, message=\"test example\") \n",
"step-ids": [
5,
6,
7,
8,
10
]
}
|
[
5,
6,
7,
8,
10
] |
#!/usr/bin/env python3
import numpy as np
from DMP.PIDMP import RLDMPs
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
np.random.seed(50)
dmp_y0 = np.array([-1.52017496, 0.04908739, 1.41433029])
dmp_goal = np.array([-1.50848603, 0.0591503 , 1.44347592])
load_file_name = "w_0_2_right_3_100_1000.0_0.01_4"
#load_file_name = raw_input('file name: ')
load_file_name_list = load_file_name.split('_')
### learning ep
ep = int(load_file_name_list[1])
### pouring number of ball to the other tube
numofball = int(load_file_name_list[2])
### which arm do the pouring motion
pour_arm = load_file_name_list[3]
n_dmps = int(load_file_name_list[4])
n_bfs = int(load_file_name_list[5])
decay = float(load_file_name_list[6])
dt = float(load_file_name_list[7])
### initial DMP
rl = RLDMPs(n_dmps = n_dmps , n_bfs = n_bfs , decay = decay, y0 = dmp_y0 , goal = dmp_goal,ay=np.ones(n_dmps)*10.0,dt = dt)
rl.load_weight(load_file_name)
traj_init = rl.predict().y
track = rl.rollout()
print(rl.w)
x = np.linspace(0,1,len(traj_init[0][:,0]))
plt.scatter(x,track.y[0][:,0],c='b',label="random")
plt.scatter(x,track.y[1][:,0],c='b')
plt.scatter(x,track.y[2][:,0],c='b')
plt.scatter(x,track.y[3][:,0],c='b')
plt.scatter(x,track.y[4][:,0],c='b')
plt.scatter(x,traj_init[0][:,0],c='r',label="initial")
plt.xlabel("time(s)")
plt.ylabel("raw (rad)")
plt.legend(loc = 4)
plt.show()
plt.scatter(x,track.y[0][:,1],c='b',label="random")
plt.scatter(x,track.y[1][:,1],c='b')
plt.scatter(x,track.y[2][:,1],c='b')
plt.scatter(x,track.y[3][:,1],c='b')
plt.scatter(x,track.y[4][:,1],c='b')
plt.scatter(x,traj_init[0][:,1],c='r',label="initial")
plt.xlabel("time(s)")
plt.ylabel("yaw (rad)")
plt.legend(loc = 4)
plt.show()
plt.scatter(x,track.y[0][:,2],c='b',label="random")
plt.scatter(x,track.y[1][:,2],c='b')
plt.scatter(x,track.y[2][:,2],c='b')
plt.scatter(x,track.y[3][:,2],c='b')
plt.scatter(x,track.y[4][:,2],c='b')
plt.scatter(x,traj_init[0][:,2],c='r',label="initial")
plt.xlabel("time(s)")
plt.ylabel("pitch (rad)")
plt.legend(loc = 4)
plt.show()
|
normal
|
{
"blob_id": "5e6bbb10ec82e566c749dd4d794eabd2e8f7a648",
"index": 4488,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nnp.random.seed(50)\n<mask token>\nrl.load_weight(load_file_name)\n<mask token>\nprint(rl.w)\n<mask token>\nplt.scatter(x, track.y[0][:, 0], c='b', label='random')\nplt.scatter(x, track.y[1][:, 0], c='b')\nplt.scatter(x, track.y[2][:, 0], c='b')\nplt.scatter(x, track.y[3][:, 0], c='b')\nplt.scatter(x, track.y[4][:, 0], c='b')\nplt.scatter(x, traj_init[0][:, 0], c='r', label='initial')\nplt.xlabel('time(s)')\nplt.ylabel('raw (rad)')\nplt.legend(loc=4)\nplt.show()\nplt.scatter(x, track.y[0][:, 1], c='b', label='random')\nplt.scatter(x, track.y[1][:, 1], c='b')\nplt.scatter(x, track.y[2][:, 1], c='b')\nplt.scatter(x, track.y[3][:, 1], c='b')\nplt.scatter(x, track.y[4][:, 1], c='b')\nplt.scatter(x, traj_init[0][:, 1], c='r', label='initial')\nplt.xlabel('time(s)')\nplt.ylabel('yaw (rad)')\nplt.legend(loc=4)\nplt.show()\nplt.scatter(x, track.y[0][:, 2], c='b', label='random')\nplt.scatter(x, track.y[1][:, 2], c='b')\nplt.scatter(x, track.y[2][:, 2], c='b')\nplt.scatter(x, track.y[3][:, 2], c='b')\nplt.scatter(x, track.y[4][:, 2], c='b')\nplt.scatter(x, traj_init[0][:, 2], c='r', label='initial')\nplt.xlabel('time(s)')\nplt.ylabel('pitch (rad)')\nplt.legend(loc=4)\nplt.show()\n",
"step-3": "<mask token>\nnp.random.seed(50)\ndmp_y0 = np.array([-1.52017496, 0.04908739, 1.41433029])\ndmp_goal = np.array([-1.50848603, 0.0591503, 1.44347592])\nload_file_name = 'w_0_2_right_3_100_1000.0_0.01_4'\nload_file_name_list = load_file_name.split('_')\nep = int(load_file_name_list[1])\nnumofball = int(load_file_name_list[2])\npour_arm = load_file_name_list[3]\nn_dmps = int(load_file_name_list[4])\nn_bfs = int(load_file_name_list[5])\ndecay = float(load_file_name_list[6])\ndt = float(load_file_name_list[7])\nrl = RLDMPs(n_dmps=n_dmps, n_bfs=n_bfs, decay=decay, y0=dmp_y0, goal=\n dmp_goal, ay=np.ones(n_dmps) * 10.0, dt=dt)\nrl.load_weight(load_file_name)\ntraj_init = rl.predict().y\ntrack = rl.rollout()\nprint(rl.w)\nx = np.linspace(0, 1, len(traj_init[0][:, 0]))\nplt.scatter(x, track.y[0][:, 0], c='b', label='random')\nplt.scatter(x, track.y[1][:, 0], c='b')\nplt.scatter(x, track.y[2][:, 0], c='b')\nplt.scatter(x, track.y[3][:, 0], c='b')\nplt.scatter(x, track.y[4][:, 0], c='b')\nplt.scatter(x, traj_init[0][:, 0], c='r', label='initial')\nplt.xlabel('time(s)')\nplt.ylabel('raw (rad)')\nplt.legend(loc=4)\nplt.show()\nplt.scatter(x, track.y[0][:, 1], c='b', label='random')\nplt.scatter(x, track.y[1][:, 1], c='b')\nplt.scatter(x, track.y[2][:, 1], c='b')\nplt.scatter(x, track.y[3][:, 1], c='b')\nplt.scatter(x, track.y[4][:, 1], c='b')\nplt.scatter(x, traj_init[0][:, 1], c='r', label='initial')\nplt.xlabel('time(s)')\nplt.ylabel('yaw (rad)')\nplt.legend(loc=4)\nplt.show()\nplt.scatter(x, track.y[0][:, 2], c='b', label='random')\nplt.scatter(x, track.y[1][:, 2], c='b')\nplt.scatter(x, track.y[2][:, 2], c='b')\nplt.scatter(x, track.y[3][:, 2], c='b')\nplt.scatter(x, track.y[4][:, 2], c='b')\nplt.scatter(x, traj_init[0][:, 2], c='r', label='initial')\nplt.xlabel('time(s)')\nplt.ylabel('pitch (rad)')\nplt.legend(loc=4)\nplt.show()\n",
"step-4": "import numpy as np\nfrom DMP.PIDMP import RLDMPs\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nnp.random.seed(50)\ndmp_y0 = np.array([-1.52017496, 0.04908739, 1.41433029])\ndmp_goal = np.array([-1.50848603, 0.0591503, 1.44347592])\nload_file_name = 'w_0_2_right_3_100_1000.0_0.01_4'\nload_file_name_list = load_file_name.split('_')\nep = int(load_file_name_list[1])\nnumofball = int(load_file_name_list[2])\npour_arm = load_file_name_list[3]\nn_dmps = int(load_file_name_list[4])\nn_bfs = int(load_file_name_list[5])\ndecay = float(load_file_name_list[6])\ndt = float(load_file_name_list[7])\nrl = RLDMPs(n_dmps=n_dmps, n_bfs=n_bfs, decay=decay, y0=dmp_y0, goal=\n dmp_goal, ay=np.ones(n_dmps) * 10.0, dt=dt)\nrl.load_weight(load_file_name)\ntraj_init = rl.predict().y\ntrack = rl.rollout()\nprint(rl.w)\nx = np.linspace(0, 1, len(traj_init[0][:, 0]))\nplt.scatter(x, track.y[0][:, 0], c='b', label='random')\nplt.scatter(x, track.y[1][:, 0], c='b')\nplt.scatter(x, track.y[2][:, 0], c='b')\nplt.scatter(x, track.y[3][:, 0], c='b')\nplt.scatter(x, track.y[4][:, 0], c='b')\nplt.scatter(x, traj_init[0][:, 0], c='r', label='initial')\nplt.xlabel('time(s)')\nplt.ylabel('raw (rad)')\nplt.legend(loc=4)\nplt.show()\nplt.scatter(x, track.y[0][:, 1], c='b', label='random')\nplt.scatter(x, track.y[1][:, 1], c='b')\nplt.scatter(x, track.y[2][:, 1], c='b')\nplt.scatter(x, track.y[3][:, 1], c='b')\nplt.scatter(x, track.y[4][:, 1], c='b')\nplt.scatter(x, traj_init[0][:, 1], c='r', label='initial')\nplt.xlabel('time(s)')\nplt.ylabel('yaw (rad)')\nplt.legend(loc=4)\nplt.show()\nplt.scatter(x, track.y[0][:, 2], c='b', label='random')\nplt.scatter(x, track.y[1][:, 2], c='b')\nplt.scatter(x, track.y[2][:, 2], c='b')\nplt.scatter(x, track.y[3][:, 2], c='b')\nplt.scatter(x, track.y[4][:, 2], c='b')\nplt.scatter(x, traj_init[0][:, 2], c='r', label='initial')\nplt.xlabel('time(s)')\nplt.ylabel('pitch (rad)')\nplt.legend(loc=4)\nplt.show()\n",
"step-5": "#!/usr/bin/env python3\nimport numpy as np\nfrom DMP.PIDMP import RLDMPs\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\nnp.random.seed(50)\ndmp_y0 = np.array([-1.52017496, 0.04908739, 1.41433029])\ndmp_goal = np.array([-1.50848603, 0.0591503 , 1.44347592])\n \n\nload_file_name = \"w_0_2_right_3_100_1000.0_0.01_4\"\n#load_file_name = raw_input('file name: ')\nload_file_name_list = load_file_name.split('_')\n### learning ep\nep = int(load_file_name_list[1])\n### pouring number of ball to the other tube\nnumofball = int(load_file_name_list[2])\n### which arm do the pouring motion\npour_arm = load_file_name_list[3]\nn_dmps = int(load_file_name_list[4])\nn_bfs = int(load_file_name_list[5])\ndecay = float(load_file_name_list[6])\ndt = float(load_file_name_list[7])\n\n### initial DMP\nrl = RLDMPs(n_dmps = n_dmps , n_bfs = n_bfs , decay = decay, y0 = dmp_y0 , goal = dmp_goal,ay=np.ones(n_dmps)*10.0,dt = dt)\n\nrl.load_weight(load_file_name)\n\ntraj_init = rl.predict().y\ntrack = rl.rollout()\n\nprint(rl.w)\n\nx = np.linspace(0,1,len(traj_init[0][:,0]))\n\nplt.scatter(x,track.y[0][:,0],c='b',label=\"random\")\nplt.scatter(x,track.y[1][:,0],c='b')\nplt.scatter(x,track.y[2][:,0],c='b')\nplt.scatter(x,track.y[3][:,0],c='b')\nplt.scatter(x,track.y[4][:,0],c='b')\nplt.scatter(x,traj_init[0][:,0],c='r',label=\"initial\")\nplt.xlabel(\"time(s)\")\nplt.ylabel(\"raw (rad)\")\nplt.legend(loc = 4)\nplt.show()\n\n\nplt.scatter(x,track.y[0][:,1],c='b',label=\"random\")\nplt.scatter(x,track.y[1][:,1],c='b')\nplt.scatter(x,track.y[2][:,1],c='b')\nplt.scatter(x,track.y[3][:,1],c='b')\nplt.scatter(x,track.y[4][:,1],c='b')\nplt.scatter(x,traj_init[0][:,1],c='r',label=\"initial\")\nplt.xlabel(\"time(s)\")\nplt.ylabel(\"yaw (rad)\")\nplt.legend(loc = 4)\nplt.show()\n\n\nplt.scatter(x,track.y[0][:,2],c='b',label=\"random\")\nplt.scatter(x,track.y[1][:,2],c='b')\nplt.scatter(x,track.y[2][:,2],c='b')\nplt.scatter(x,track.y[3][:,2],c='b')\nplt.scatter(x,track.y[4][:,2],c='b')\nplt.scatter(x,traj_init[0][:,2],c='r',label=\"initial\")\n\nplt.xlabel(\"time(s)\")\nplt.ylabel(\"pitch (rad)\")\nplt.legend(loc = 4)\nplt.show()\n\n\n\n\n\n\n\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
"""
======================
@author:小谢学测试
@time:2021/9/8:8:34
@email:xie7791@qq.com
======================
"""
import pytest
# @pytest.fixture()
# def login():
# print("登录方法")
# def pytest_conftest(config):
# marker_list = ["search","login"]
# for markers in marker_list:
# config.addinivalue_line("markers",markers)
|
normal
|
{
"blob_id": "b52429f936013ac60659950492b67078fabf3a13",
"index": 4042,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nimport pytest\n",
"step-3": "\"\"\"\n======================\n@author:小谢学测试\n@time:2021/9/8:8:34\n@email:xie7791@qq.com\n======================\n\"\"\"\nimport pytest\n# @pytest.fixture()\n# def login():\n# print(\"登录方法\")\n\n# def pytest_conftest(config):\n# marker_list = [\"search\",\"login\"]\n# for markers in marker_list:\n# config.addinivalue_line(\"markers\",markers)",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
import vobject
import glob
import sys
vobj=vobject.readOne(open("Nelson.vcf"))
print vobj.contents
def main(args):
suma = 0
titulos = ['nombre del archivo', 'Total', 'subtotoal', 'rfc', 'fecha', 'ivaTrasladado', 'isrTrasladado', 'ivaRetenido', 'isrRetenido']
import csv
out = csv.writer(open("out.csv","w"), delimiter=',',quoting=csv.QUOTE_ALL)
out.writerow(titulos)
for argument in args:
t = datos(argument)
row = []
if not t["rfcEmisor"] in catedraticos:
suma += t["total"]
row.append(argument)
row.append(t['total'])
row.append(t['subTotal'])
row.append(t['rfcEmisor'])
row.append(t['fecha'])
row.append(t['ivat'])
row.append(t['isrt'])
row.append(t['ivar'])
row.append(t['isrr'])
out.writerow(row)
if __name__ == '__main__':
if len(sys.argv[1:]) > 0:
main(sys.argv[1:])
else:
files = glob.glob("*.xml")
if files:
main(files)
else:
raw_input("no hay archivos xml")
|
normal
|
{
"blob_id": "a1115766c5f17abc1ba90a3314cb5b9c4aab73d6",
"index": 8169,
"step-1": "import vobject\nimport glob\nimport sys\n\nvobj=vobject.readOne(open(\"Nelson.vcf\"))\nprint vobj.contents\n\n\ndef main(args):\n suma = 0\n titulos = ['nombre del archivo', 'Total', 'subtotoal', 'rfc', 'fecha', 'ivaTrasladado', 'isrTrasladado', 'ivaRetenido', 'isrRetenido']\n import csv\n out = csv.writer(open(\"out.csv\",\"w\"), delimiter=',',quoting=csv.QUOTE_ALL)\n out.writerow(titulos)\n for argument in args:\n t = datos(argument)\n row = []\n if not t[\"rfcEmisor\"] in catedraticos:\n suma += t[\"total\"]\n row.append(argument)\n row.append(t['total'])\n row.append(t['subTotal'])\n row.append(t['rfcEmisor'])\n row.append(t['fecha'])\n row.append(t['ivat'])\n row.append(t['isrt'])\n row.append(t['ivar'])\n row.append(t['isrr'])\n out.writerow(row)\n\nif __name__ == '__main__':\n if len(sys.argv[1:]) > 0:\n main(sys.argv[1:])\n else:\n files = glob.glob(\"*.xml\")\n if files:\n main(files)\n else:\n raw_input(\"no hay archivos xml\")\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
"""
==============================
Visualize Cylinder with Wrench
==============================
We apply a constant body-fixed wrench to a cylinder and integrate
acceleration to twist and exponential coordinates of transformation
to finally compute the new pose of the cylinder.
"""
import numpy as np
from pytransform3d.transformations import (
transform_from_exponential_coordinates)
import pytransform3d.visualizer as pv
def spatial_inertia_of_cylinder(mass, length, radius):
I_xx = I_yy = 0.25 * mass * radius ** 2 + 1.0 / 12.0 * mass * length ** 2
I_zz = 0.5 * mass * radius ** 2
inertia = np.eye(6)
inertia[:3, :3] *= np.array([I_xx, I_yy, I_zz])
inertia[3:, 3:] *= mass
return inertia
def animation_callback(
step, cylinder, cylinder_frame, prev_cylinder2world,
Stheta_dot, inertia_inv):
if step == 0: # Reset cylinder state
prev_cylinder2world[:, :] = np.eye(4)
Stheta_dot[:] = 0.0
# Apply constant wrench
wrench_in_cylinder = np.array([0.1, 0.001, 0.001, 0.01, 1.0, 1.0])
dt = 0.0005
Stheta_ddot = np.dot(inertia_inv, wrench_in_cylinder)
Stheta_dot += dt * Stheta_ddot
cylinder2world = transform_from_exponential_coordinates(
dt * Stheta_dot).dot(prev_cylinder2world)
# Update visualization
cylinder_frame.set_data(cylinder2world)
cylinder.set_data(cylinder2world)
prev_cylinder2world[:, :] = cylinder2world
return cylinder_frame, cylinder
fig = pv.figure()
# Definition of cylinder
mass = 1.0
length = 0.5
radius = 0.1
inertia_inv = np.linalg.inv(
spatial_inertia_of_cylinder(mass=mass, length=length, radius=radius))
# State of cylinder
cylinder2world = np.eye(4)
twist = np.zeros(6)
cylinder = fig.plot_cylinder(length=length, radius=radius, c=[1, 0.5, 0])
cylinder_frame = fig.plot_transform(A2B=cylinder2world, s=0.5)
fig.plot_transform(A2B=np.eye(4), s=0.5)
fig.view_init()
if "__file__" in globals():
fig.animate(
animation_callback, n_frames=10000,
fargs=(cylinder, cylinder_frame, cylinder2world, twist, inertia_inv),
loop=True)
fig.show()
else:
fig.save_image("__open3d_rendered_image.jpg")
|
normal
|
{
"blob_id": "2019a2a5588e57164ff4226ef3bcbbc506f2b315",
"index": 7432,
"step-1": "<mask token>\n\n\ndef animation_callback(step, cylinder, cylinder_frame, prev_cylinder2world,\n Stheta_dot, inertia_inv):\n if step == 0:\n prev_cylinder2world[:, :] = np.eye(4)\n Stheta_dot[:] = 0.0\n wrench_in_cylinder = np.array([0.1, 0.001, 0.001, 0.01, 1.0, 1.0])\n dt = 0.0005\n Stheta_ddot = np.dot(inertia_inv, wrench_in_cylinder)\n Stheta_dot += dt * Stheta_ddot\n cylinder2world = transform_from_exponential_coordinates(dt * Stheta_dot\n ).dot(prev_cylinder2world)\n cylinder_frame.set_data(cylinder2world)\n cylinder.set_data(cylinder2world)\n prev_cylinder2world[:, :] = cylinder2world\n return cylinder_frame, cylinder\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef spatial_inertia_of_cylinder(mass, length, radius):\n I_xx = I_yy = 0.25 * mass * radius ** 2 + 1.0 / 12.0 * mass * length ** 2\n I_zz = 0.5 * mass * radius ** 2\n inertia = np.eye(6)\n inertia[:3, :3] *= np.array([I_xx, I_yy, I_zz])\n inertia[3:, 3:] *= mass\n return inertia\n\n\ndef animation_callback(step, cylinder, cylinder_frame, prev_cylinder2world,\n Stheta_dot, inertia_inv):\n if step == 0:\n prev_cylinder2world[:, :] = np.eye(4)\n Stheta_dot[:] = 0.0\n wrench_in_cylinder = np.array([0.1, 0.001, 0.001, 0.01, 1.0, 1.0])\n dt = 0.0005\n Stheta_ddot = np.dot(inertia_inv, wrench_in_cylinder)\n Stheta_dot += dt * Stheta_ddot\n cylinder2world = transform_from_exponential_coordinates(dt * Stheta_dot\n ).dot(prev_cylinder2world)\n cylinder_frame.set_data(cylinder2world)\n cylinder.set_data(cylinder2world)\n prev_cylinder2world[:, :] = cylinder2world\n return cylinder_frame, cylinder\n\n\n<mask token>\nfig.plot_transform(A2B=np.eye(4), s=0.5)\nfig.view_init()\nif '__file__' in globals():\n fig.animate(animation_callback, n_frames=10000, fargs=(cylinder,\n cylinder_frame, cylinder2world, twist, inertia_inv), loop=True)\n fig.show()\nelse:\n fig.save_image('__open3d_rendered_image.jpg')\n",
"step-3": "<mask token>\n\n\ndef spatial_inertia_of_cylinder(mass, length, radius):\n I_xx = I_yy = 0.25 * mass * radius ** 2 + 1.0 / 12.0 * mass * length ** 2\n I_zz = 0.5 * mass * radius ** 2\n inertia = np.eye(6)\n inertia[:3, :3] *= np.array([I_xx, I_yy, I_zz])\n inertia[3:, 3:] *= mass\n return inertia\n\n\ndef animation_callback(step, cylinder, cylinder_frame, prev_cylinder2world,\n Stheta_dot, inertia_inv):\n if step == 0:\n prev_cylinder2world[:, :] = np.eye(4)\n Stheta_dot[:] = 0.0\n wrench_in_cylinder = np.array([0.1, 0.001, 0.001, 0.01, 1.0, 1.0])\n dt = 0.0005\n Stheta_ddot = np.dot(inertia_inv, wrench_in_cylinder)\n Stheta_dot += dt * Stheta_ddot\n cylinder2world = transform_from_exponential_coordinates(dt * Stheta_dot\n ).dot(prev_cylinder2world)\n cylinder_frame.set_data(cylinder2world)\n cylinder.set_data(cylinder2world)\n prev_cylinder2world[:, :] = cylinder2world\n return cylinder_frame, cylinder\n\n\nfig = pv.figure()\nmass = 1.0\nlength = 0.5\nradius = 0.1\ninertia_inv = np.linalg.inv(spatial_inertia_of_cylinder(mass=mass, length=\n length, radius=radius))\ncylinder2world = np.eye(4)\ntwist = np.zeros(6)\ncylinder = fig.plot_cylinder(length=length, radius=radius, c=[1, 0.5, 0])\ncylinder_frame = fig.plot_transform(A2B=cylinder2world, s=0.5)\nfig.plot_transform(A2B=np.eye(4), s=0.5)\nfig.view_init()\nif '__file__' in globals():\n fig.animate(animation_callback, n_frames=10000, fargs=(cylinder,\n cylinder_frame, cylinder2world, twist, inertia_inv), loop=True)\n fig.show()\nelse:\n fig.save_image('__open3d_rendered_image.jpg')\n",
"step-4": "<mask token>\nimport numpy as np\nfrom pytransform3d.transformations import transform_from_exponential_coordinates\nimport pytransform3d.visualizer as pv\n\n\ndef spatial_inertia_of_cylinder(mass, length, radius):\n I_xx = I_yy = 0.25 * mass * radius ** 2 + 1.0 / 12.0 * mass * length ** 2\n I_zz = 0.5 * mass * radius ** 2\n inertia = np.eye(6)\n inertia[:3, :3] *= np.array([I_xx, I_yy, I_zz])\n inertia[3:, 3:] *= mass\n return inertia\n\n\ndef animation_callback(step, cylinder, cylinder_frame, prev_cylinder2world,\n Stheta_dot, inertia_inv):\n if step == 0:\n prev_cylinder2world[:, :] = np.eye(4)\n Stheta_dot[:] = 0.0\n wrench_in_cylinder = np.array([0.1, 0.001, 0.001, 0.01, 1.0, 1.0])\n dt = 0.0005\n Stheta_ddot = np.dot(inertia_inv, wrench_in_cylinder)\n Stheta_dot += dt * Stheta_ddot\n cylinder2world = transform_from_exponential_coordinates(dt * Stheta_dot\n ).dot(prev_cylinder2world)\n cylinder_frame.set_data(cylinder2world)\n cylinder.set_data(cylinder2world)\n prev_cylinder2world[:, :] = cylinder2world\n return cylinder_frame, cylinder\n\n\nfig = pv.figure()\nmass = 1.0\nlength = 0.5\nradius = 0.1\ninertia_inv = np.linalg.inv(spatial_inertia_of_cylinder(mass=mass, length=\n length, radius=radius))\ncylinder2world = np.eye(4)\ntwist = np.zeros(6)\ncylinder = fig.plot_cylinder(length=length, radius=radius, c=[1, 0.5, 0])\ncylinder_frame = fig.plot_transform(A2B=cylinder2world, s=0.5)\nfig.plot_transform(A2B=np.eye(4), s=0.5)\nfig.view_init()\nif '__file__' in globals():\n fig.animate(animation_callback, n_frames=10000, fargs=(cylinder,\n cylinder_frame, cylinder2world, twist, inertia_inv), loop=True)\n fig.show()\nelse:\n fig.save_image('__open3d_rendered_image.jpg')\n",
"step-5": "\"\"\"\n==============================\nVisualize Cylinder with Wrench\n==============================\n\nWe apply a constant body-fixed wrench to a cylinder and integrate\nacceleration to twist and exponential coordinates of transformation\nto finally compute the new pose of the cylinder.\n\"\"\"\nimport numpy as np\nfrom pytransform3d.transformations import (\n transform_from_exponential_coordinates)\nimport pytransform3d.visualizer as pv\n\n\ndef spatial_inertia_of_cylinder(mass, length, radius):\n I_xx = I_yy = 0.25 * mass * radius ** 2 + 1.0 / 12.0 * mass * length ** 2\n I_zz = 0.5 * mass * radius ** 2\n inertia = np.eye(6)\n inertia[:3, :3] *= np.array([I_xx, I_yy, I_zz])\n inertia[3:, 3:] *= mass\n return inertia\n\n\ndef animation_callback(\n step, cylinder, cylinder_frame, prev_cylinder2world,\n Stheta_dot, inertia_inv):\n if step == 0: # Reset cylinder state\n prev_cylinder2world[:, :] = np.eye(4)\n Stheta_dot[:] = 0.0\n\n # Apply constant wrench\n wrench_in_cylinder = np.array([0.1, 0.001, 0.001, 0.01, 1.0, 1.0])\n dt = 0.0005\n\n Stheta_ddot = np.dot(inertia_inv, wrench_in_cylinder)\n Stheta_dot += dt * Stheta_ddot\n cylinder2world = transform_from_exponential_coordinates(\n dt * Stheta_dot).dot(prev_cylinder2world)\n\n # Update visualization\n cylinder_frame.set_data(cylinder2world)\n cylinder.set_data(cylinder2world)\n\n prev_cylinder2world[:, :] = cylinder2world\n\n return cylinder_frame, cylinder\n\n\nfig = pv.figure()\n\n# Definition of cylinder\nmass = 1.0\nlength = 0.5\nradius = 0.1\ninertia_inv = np.linalg.inv(\n spatial_inertia_of_cylinder(mass=mass, length=length, radius=radius))\n\n# State of cylinder\ncylinder2world = np.eye(4)\ntwist = np.zeros(6)\n\ncylinder = fig.plot_cylinder(length=length, radius=radius, c=[1, 0.5, 0])\ncylinder_frame = fig.plot_transform(A2B=cylinder2world, s=0.5)\n\nfig.plot_transform(A2B=np.eye(4), s=0.5)\n\nfig.view_init()\n\nif \"__file__\" in globals():\n fig.animate(\n animation_callback, n_frames=10000,\n fargs=(cylinder, cylinder_frame, cylinder2world, twist, inertia_inv),\n loop=True)\n fig.show()\nelse:\n fig.save_image(\"__open3d_rendered_image.jpg\")\n",
"step-ids": [
1,
3,
4,
5,
6
]
}
|
[
1,
3,
4,
5,
6
] |
from functools import wraps
from flask import request, abort
# Apply Aspect Oriented Programming to server routes using roles
# e.g. we want to specify the role, perhaps supplied
# by the request or a jwt token, using a decorator
# to abstract away the authorization
# possible decorator implementation
def roles_required(roles):
def decorator(func):
# can't skip this @wraps function
# or error 'View function mapping is overwriting an existing endpoint function
# stackoverflow.com/questions/19964079
@wraps(func)
def wrapper(*args, **kwargs):
print(roles, 'required')
print(args, kwargs, 'provided')
if (kwargs['role']):
print(kwargs['role'])
if (kwargs['role'] not in roles):
print('unauthorised')
return abort(401)
else:
print('authorised')
return func(*args, **kwargs)
#return abort(401)
#func()
return wrapper
return decorator
# can in theory use jwt token parsing to check role here
|
normal
|
{
"blob_id": "1adaca88cf41d4e4d3a55996022278102887be07",
"index": 3707,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef roles_required(roles):\n\n def decorator(func):\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n print(roles, 'required')\n print(args, kwargs, 'provided')\n if kwargs['role']:\n print(kwargs['role'])\n if kwargs['role'] not in roles:\n print('unauthorised')\n return abort(401)\n else:\n print('authorised')\n return func(*args, **kwargs)\n return wrapper\n return decorator\n",
"step-3": "from functools import wraps\nfrom flask import request, abort\n\n\ndef roles_required(roles):\n\n def decorator(func):\n\n @wraps(func)\n def wrapper(*args, **kwargs):\n print(roles, 'required')\n print(args, kwargs, 'provided')\n if kwargs['role']:\n print(kwargs['role'])\n if kwargs['role'] not in roles:\n print('unauthorised')\n return abort(401)\n else:\n print('authorised')\n return func(*args, **kwargs)\n return wrapper\n return decorator\n",
"step-4": "from functools import wraps\nfrom flask import request, abort\n# Apply Aspect Oriented Programming to server routes using roles\n\n# e.g. we want to specify the role, perhaps supplied\n# by the request or a jwt token, using a decorator\n# to abstract away the authorization\n\n\n# possible decorator implementation\ndef roles_required(roles):\n def decorator(func):\n # can't skip this @wraps function \n # or error 'View function mapping is overwriting an existing endpoint function\n # stackoverflow.com/questions/19964079\n @wraps(func)\n def wrapper(*args, **kwargs):\n print(roles, 'required')\n print(args, kwargs, 'provided')\n if (kwargs['role']):\n print(kwargs['role'])\n if (kwargs['role'] not in roles):\n print('unauthorised')\n return abort(401)\n else:\n print('authorised')\n return func(*args, **kwargs)\n #return abort(401)\n #func()\n return wrapper\n return decorator\n \n\n# can in theory use jwt token parsing to check role here\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
def RangeExtender(filename, directory):
fileNC = nc.Dataset(directory + filename, 'r')
nu = fileNC['nu'][:]
filename, ext = os.path.splitext(filename)
fileOut = nc.Dataset(directory + filename + '_50000cm-1.nc', 'w')
nu_orig_length = len(nu)
step = abs(nu[1] - nu[0])
print(nu, step, len(nu))
nu = [nu[i] for i in range(len(nu))]
count = 0
while nu[-1] < 50000 * 100:
count += 1
if count % 25000.0 == 0:
print('{0}, {1:6.5e}'.format(len(nu), 50000 * 100 - nu[-1]),
end='\r', flush=True)
nu.append(nu[-1] + step)
print('\n', len(nu))
nu_length = len(nu)
pt_num = len(fileNC['t_calc'])
nu_dim = fileOut.createDimension('nu', nu_length)
pt_pair_dim = fileOut.createDimension('pt_pair', pt_num)
scalar_dim = fileOut.createDimension('scalar', 1)
nu_var = fileOut.createVariable('nu', 'f8', ('nu',))
kabs = fileOut.createVariable('kabs', 'f4', ('pt_pair', 'nu'))
t_calc = fileOut.createVariable('t_calc', 'f8', ('pt_pair',))
p_calc = fileOut.createVariable('p_calc', 'f8', ('pt_pair',))
nu = np.array(nu)
nu_var[:] = nu[:]
nu_var.step = step
t_calc[:] = fileNC['t_calc'][:]
p_calc[:] = fileNC['p_calc'][:]
k_zero = np.zeros(nu_length)
for i in range(pt_num):
print(i, pt_num, end='\r', flush=True)
k_zero_used = np.copy(k_zero)
kabs[i, :] = k_zero_used[:]
kabs[i, :nu_orig_length] = fileNC['kabs'][i, :]
print('')
fileNC.close()
fileOut.close()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def RangeExtender(filename, directory):
fileNC = nc.Dataset(directory + filename, 'r')
nu = fileNC['nu'][:]
filename, ext = os.path.splitext(filename)
fileOut = nc.Dataset(directory + filename + '_50000cm-1.nc', 'w')
nu_orig_length = len(nu)
step = abs(nu[1] - nu[0])
print(nu, step, len(nu))
nu = [nu[i] for i in range(len(nu))]
count = 0
while nu[-1] < 50000 * 100:
count += 1
if count % 25000.0 == 0:
print('{0}, {1:6.5e}'.format(len(nu), 50000 * 100 - nu[-1]),
end='\r', flush=True)
nu.append(nu[-1] + step)
print('\n', len(nu))
nu_length = len(nu)
pt_num = len(fileNC['t_calc'])
nu_dim = fileOut.createDimension('nu', nu_length)
pt_pair_dim = fileOut.createDimension('pt_pair', pt_num)
scalar_dim = fileOut.createDimension('scalar', 1)
nu_var = fileOut.createVariable('nu', 'f8', ('nu',))
kabs = fileOut.createVariable('kabs', 'f4', ('pt_pair', 'nu'))
t_calc = fileOut.createVariable('t_calc', 'f8', ('pt_pair',))
p_calc = fileOut.createVariable('p_calc', 'f8', ('pt_pair',))
nu = np.array(nu)
nu_var[:] = nu[:]
nu_var.step = step
t_calc[:] = fileNC['t_calc'][:]
p_calc[:] = fileNC['p_calc'][:]
k_zero = np.zeros(nu_length)
for i in range(pt_num):
print(i, pt_num, end='\r', flush=True)
k_zero_used = np.copy(k_zero)
kabs[i, :] = k_zero_used[:]
kabs[i, :nu_orig_length] = fileNC['kabs'][i, :]
print('')
fileNC.close()
fileOut.close()
<|reserved_special_token_0|>
RangeExtender(filename, directory)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def RangeExtender(filename, directory):
fileNC = nc.Dataset(directory + filename, 'r')
nu = fileNC['nu'][:]
filename, ext = os.path.splitext(filename)
fileOut = nc.Dataset(directory + filename + '_50000cm-1.nc', 'w')
nu_orig_length = len(nu)
step = abs(nu[1] - nu[0])
print(nu, step, len(nu))
nu = [nu[i] for i in range(len(nu))]
count = 0
while nu[-1] < 50000 * 100:
count += 1
if count % 25000.0 == 0:
print('{0}, {1:6.5e}'.format(len(nu), 50000 * 100 - nu[-1]),
end='\r', flush=True)
nu.append(nu[-1] + step)
print('\n', len(nu))
nu_length = len(nu)
pt_num = len(fileNC['t_calc'])
nu_dim = fileOut.createDimension('nu', nu_length)
pt_pair_dim = fileOut.createDimension('pt_pair', pt_num)
scalar_dim = fileOut.createDimension('scalar', 1)
nu_var = fileOut.createVariable('nu', 'f8', ('nu',))
kabs = fileOut.createVariable('kabs', 'f4', ('pt_pair', 'nu'))
t_calc = fileOut.createVariable('t_calc', 'f8', ('pt_pair',))
p_calc = fileOut.createVariable('p_calc', 'f8', ('pt_pair',))
nu = np.array(nu)
nu_var[:] = nu[:]
nu_var.step = step
t_calc[:] = fileNC['t_calc'][:]
p_calc[:] = fileNC['p_calc'][:]
k_zero = np.zeros(nu_length)
for i in range(pt_num):
print(i, pt_num, end='\r', flush=True)
k_zero_used = np.copy(k_zero)
kabs[i, :] = k_zero_used[:]
kabs[i, :nu_orig_length] = fileNC['kabs'][i, :]
print('')
fileNC.close()
fileOut.close()
filename = 'abs_coeff_TiO_Toto_TerrestrialAbund_pt800.nc'
directory = '/home/dc-ridg1/AbsCoeffs/'
RangeExtender(filename, directory)
<|reserved_special_token_1|>
import netCDF4 as nc
import numpy as np
import os
def RangeExtender(filename, directory):
fileNC = nc.Dataset(directory + filename, 'r')
nu = fileNC['nu'][:]
filename, ext = os.path.splitext(filename)
fileOut = nc.Dataset(directory + filename + '_50000cm-1.nc', 'w')
nu_orig_length = len(nu)
step = abs(nu[1] - nu[0])
print(nu, step, len(nu))
nu = [nu[i] for i in range(len(nu))]
count = 0
while nu[-1] < 50000 * 100:
count += 1
if count % 25000.0 == 0:
print('{0}, {1:6.5e}'.format(len(nu), 50000 * 100 - nu[-1]),
end='\r', flush=True)
nu.append(nu[-1] + step)
print('\n', len(nu))
nu_length = len(nu)
pt_num = len(fileNC['t_calc'])
nu_dim = fileOut.createDimension('nu', nu_length)
pt_pair_dim = fileOut.createDimension('pt_pair', pt_num)
scalar_dim = fileOut.createDimension('scalar', 1)
nu_var = fileOut.createVariable('nu', 'f8', ('nu',))
kabs = fileOut.createVariable('kabs', 'f4', ('pt_pair', 'nu'))
t_calc = fileOut.createVariable('t_calc', 'f8', ('pt_pair',))
p_calc = fileOut.createVariable('p_calc', 'f8', ('pt_pair',))
nu = np.array(nu)
nu_var[:] = nu[:]
nu_var.step = step
t_calc[:] = fileNC['t_calc'][:]
p_calc[:] = fileNC['p_calc'][:]
k_zero = np.zeros(nu_length)
for i in range(pt_num):
print(i, pt_num, end='\r', flush=True)
k_zero_used = np.copy(k_zero)
kabs[i, :] = k_zero_used[:]
kabs[i, :nu_orig_length] = fileNC['kabs'][i, :]
print('')
fileNC.close()
fileOut.close()
filename = 'abs_coeff_TiO_Toto_TerrestrialAbund_pt800.nc'
directory = '/home/dc-ridg1/AbsCoeffs/'
RangeExtender(filename, directory)
<|reserved_special_token_1|>
import netCDF4 as nc
import numpy as np
import os
def RangeExtender(filename,directory):
fileNC=nc.Dataset(directory+filename,'r')
nu=fileNC['nu'][:]
filename,ext=os.path.splitext(filename)
fileOut=nc.Dataset(directory+filename+"_50000cm-1.nc",'w')
nu_orig_length=len(nu)
step=abs(nu[1]-nu[0])
print(nu,step,len(nu))
nu=[nu[i] for i in range(len(nu))]
count=0
while nu[-1] < 50000*100:
count+=1
if count % 2.5e4 ==0:
print("{0}, {1:6.5e}".format(len(nu),50000*100-nu[-1]),end='\r',flush=True)
nu.append(nu[-1]+step)
print('\n',len(nu))
nu_length=len(nu)
pt_num=len(fileNC['t_calc'])
nu_dim=fileOut.createDimension('nu',nu_length)
pt_pair_dim=fileOut.createDimension('pt_pair',pt_num)
scalar_dim=fileOut.createDimension('scalar',1)
nu_var=fileOut.createVariable('nu','f8',('nu',))
kabs=fileOut.createVariable('kabs','f4',('pt_pair','nu',))
t_calc= fileOut.createVariable('t_calc','f8',('pt_pair',))
p_calc= fileOut.createVariable('p_calc','f8',('pt_pair',))
nu=np.array(nu)
nu_var[:]=nu[:]
nu_var.step=step
t_calc[:]=fileNC['t_calc'][:]
p_calc[:]=fileNC['p_calc'][:]
k_zero=np.zeros(nu_length)
for i in range(pt_num):
print(i,pt_num,end='\r',flush=True)
k_zero_used=np.copy(k_zero)
kabs[i,:]=k_zero_used[:]
kabs[i,:nu_orig_length]=fileNC['kabs'][i,:]
print('')
fileNC.close()
fileOut.close()
filename='abs_coeff_TiO_Toto_TerrestrialAbund_pt800.nc'
directory='/home/dc-ridg1/AbsCoeffs/'
RangeExtender(filename,directory)
|
flexible
|
{
"blob_id": "f3527185117fd7205f55f47f2f08448a7d7b0100",
"index": 8143,
"step-1": "<mask token>\n\n\ndef RangeExtender(filename, directory):\n fileNC = nc.Dataset(directory + filename, 'r')\n nu = fileNC['nu'][:]\n filename, ext = os.path.splitext(filename)\n fileOut = nc.Dataset(directory + filename + '_50000cm-1.nc', 'w')\n nu_orig_length = len(nu)\n step = abs(nu[1] - nu[0])\n print(nu, step, len(nu))\n nu = [nu[i] for i in range(len(nu))]\n count = 0\n while nu[-1] < 50000 * 100:\n count += 1\n if count % 25000.0 == 0:\n print('{0}, {1:6.5e}'.format(len(nu), 50000 * 100 - nu[-1]),\n end='\\r', flush=True)\n nu.append(nu[-1] + step)\n print('\\n', len(nu))\n nu_length = len(nu)\n pt_num = len(fileNC['t_calc'])\n nu_dim = fileOut.createDimension('nu', nu_length)\n pt_pair_dim = fileOut.createDimension('pt_pair', pt_num)\n scalar_dim = fileOut.createDimension('scalar', 1)\n nu_var = fileOut.createVariable('nu', 'f8', ('nu',))\n kabs = fileOut.createVariable('kabs', 'f4', ('pt_pair', 'nu'))\n t_calc = fileOut.createVariable('t_calc', 'f8', ('pt_pair',))\n p_calc = fileOut.createVariable('p_calc', 'f8', ('pt_pair',))\n nu = np.array(nu)\n nu_var[:] = nu[:]\n nu_var.step = step\n t_calc[:] = fileNC['t_calc'][:]\n p_calc[:] = fileNC['p_calc'][:]\n k_zero = np.zeros(nu_length)\n for i in range(pt_num):\n print(i, pt_num, end='\\r', flush=True)\n k_zero_used = np.copy(k_zero)\n kabs[i, :] = k_zero_used[:]\n kabs[i, :nu_orig_length] = fileNC['kabs'][i, :]\n print('')\n fileNC.close()\n fileOut.close()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef RangeExtender(filename, directory):\n fileNC = nc.Dataset(directory + filename, 'r')\n nu = fileNC['nu'][:]\n filename, ext = os.path.splitext(filename)\n fileOut = nc.Dataset(directory + filename + '_50000cm-1.nc', 'w')\n nu_orig_length = len(nu)\n step = abs(nu[1] - nu[0])\n print(nu, step, len(nu))\n nu = [nu[i] for i in range(len(nu))]\n count = 0\n while nu[-1] < 50000 * 100:\n count += 1\n if count % 25000.0 == 0:\n print('{0}, {1:6.5e}'.format(len(nu), 50000 * 100 - nu[-1]),\n end='\\r', flush=True)\n nu.append(nu[-1] + step)\n print('\\n', len(nu))\n nu_length = len(nu)\n pt_num = len(fileNC['t_calc'])\n nu_dim = fileOut.createDimension('nu', nu_length)\n pt_pair_dim = fileOut.createDimension('pt_pair', pt_num)\n scalar_dim = fileOut.createDimension('scalar', 1)\n nu_var = fileOut.createVariable('nu', 'f8', ('nu',))\n kabs = fileOut.createVariable('kabs', 'f4', ('pt_pair', 'nu'))\n t_calc = fileOut.createVariable('t_calc', 'f8', ('pt_pair',))\n p_calc = fileOut.createVariable('p_calc', 'f8', ('pt_pair',))\n nu = np.array(nu)\n nu_var[:] = nu[:]\n nu_var.step = step\n t_calc[:] = fileNC['t_calc'][:]\n p_calc[:] = fileNC['p_calc'][:]\n k_zero = np.zeros(nu_length)\n for i in range(pt_num):\n print(i, pt_num, end='\\r', flush=True)\n k_zero_used = np.copy(k_zero)\n kabs[i, :] = k_zero_used[:]\n kabs[i, :nu_orig_length] = fileNC['kabs'][i, :]\n print('')\n fileNC.close()\n fileOut.close()\n\n\n<mask token>\nRangeExtender(filename, directory)\n",
"step-3": "<mask token>\n\n\ndef RangeExtender(filename, directory):\n fileNC = nc.Dataset(directory + filename, 'r')\n nu = fileNC['nu'][:]\n filename, ext = os.path.splitext(filename)\n fileOut = nc.Dataset(directory + filename + '_50000cm-1.nc', 'w')\n nu_orig_length = len(nu)\n step = abs(nu[1] - nu[0])\n print(nu, step, len(nu))\n nu = [nu[i] for i in range(len(nu))]\n count = 0\n while nu[-1] < 50000 * 100:\n count += 1\n if count % 25000.0 == 0:\n print('{0}, {1:6.5e}'.format(len(nu), 50000 * 100 - nu[-1]),\n end='\\r', flush=True)\n nu.append(nu[-1] + step)\n print('\\n', len(nu))\n nu_length = len(nu)\n pt_num = len(fileNC['t_calc'])\n nu_dim = fileOut.createDimension('nu', nu_length)\n pt_pair_dim = fileOut.createDimension('pt_pair', pt_num)\n scalar_dim = fileOut.createDimension('scalar', 1)\n nu_var = fileOut.createVariable('nu', 'f8', ('nu',))\n kabs = fileOut.createVariable('kabs', 'f4', ('pt_pair', 'nu'))\n t_calc = fileOut.createVariable('t_calc', 'f8', ('pt_pair',))\n p_calc = fileOut.createVariable('p_calc', 'f8', ('pt_pair',))\n nu = np.array(nu)\n nu_var[:] = nu[:]\n nu_var.step = step\n t_calc[:] = fileNC['t_calc'][:]\n p_calc[:] = fileNC['p_calc'][:]\n k_zero = np.zeros(nu_length)\n for i in range(pt_num):\n print(i, pt_num, end='\\r', flush=True)\n k_zero_used = np.copy(k_zero)\n kabs[i, :] = k_zero_used[:]\n kabs[i, :nu_orig_length] = fileNC['kabs'][i, :]\n print('')\n fileNC.close()\n fileOut.close()\n\n\nfilename = 'abs_coeff_TiO_Toto_TerrestrialAbund_pt800.nc'\ndirectory = '/home/dc-ridg1/AbsCoeffs/'\nRangeExtender(filename, directory)\n",
"step-4": "import netCDF4 as nc\nimport numpy as np\nimport os\n\n\ndef RangeExtender(filename, directory):\n fileNC = nc.Dataset(directory + filename, 'r')\n nu = fileNC['nu'][:]\n filename, ext = os.path.splitext(filename)\n fileOut = nc.Dataset(directory + filename + '_50000cm-1.nc', 'w')\n nu_orig_length = len(nu)\n step = abs(nu[1] - nu[0])\n print(nu, step, len(nu))\n nu = [nu[i] for i in range(len(nu))]\n count = 0\n while nu[-1] < 50000 * 100:\n count += 1\n if count % 25000.0 == 0:\n print('{0}, {1:6.5e}'.format(len(nu), 50000 * 100 - nu[-1]),\n end='\\r', flush=True)\n nu.append(nu[-1] + step)\n print('\\n', len(nu))\n nu_length = len(nu)\n pt_num = len(fileNC['t_calc'])\n nu_dim = fileOut.createDimension('nu', nu_length)\n pt_pair_dim = fileOut.createDimension('pt_pair', pt_num)\n scalar_dim = fileOut.createDimension('scalar', 1)\n nu_var = fileOut.createVariable('nu', 'f8', ('nu',))\n kabs = fileOut.createVariable('kabs', 'f4', ('pt_pair', 'nu'))\n t_calc = fileOut.createVariable('t_calc', 'f8', ('pt_pair',))\n p_calc = fileOut.createVariable('p_calc', 'f8', ('pt_pair',))\n nu = np.array(nu)\n nu_var[:] = nu[:]\n nu_var.step = step\n t_calc[:] = fileNC['t_calc'][:]\n p_calc[:] = fileNC['p_calc'][:]\n k_zero = np.zeros(nu_length)\n for i in range(pt_num):\n print(i, pt_num, end='\\r', flush=True)\n k_zero_used = np.copy(k_zero)\n kabs[i, :] = k_zero_used[:]\n kabs[i, :nu_orig_length] = fileNC['kabs'][i, :]\n print('')\n fileNC.close()\n fileOut.close()\n\n\nfilename = 'abs_coeff_TiO_Toto_TerrestrialAbund_pt800.nc'\ndirectory = '/home/dc-ridg1/AbsCoeffs/'\nRangeExtender(filename, directory)\n",
"step-5": "\n\n\nimport netCDF4 as nc\nimport numpy as np\nimport os\n\n\ndef RangeExtender(filename,directory):\n \n fileNC=nc.Dataset(directory+filename,'r')\n nu=fileNC['nu'][:]\n filename,ext=os.path.splitext(filename)\n fileOut=nc.Dataset(directory+filename+\"_50000cm-1.nc\",'w')\n nu_orig_length=len(nu)\n step=abs(nu[1]-nu[0])\n print(nu,step,len(nu))\n nu=[nu[i] for i in range(len(nu))]\n count=0\n while nu[-1] < 50000*100:\n count+=1\n if count % 2.5e4 ==0:\n print(\"{0}, {1:6.5e}\".format(len(nu),50000*100-nu[-1]),end='\\r',flush=True)\n nu.append(nu[-1]+step)\n print('\\n',len(nu))\n nu_length=len(nu)\n pt_num=len(fileNC['t_calc'])\n nu_dim=fileOut.createDimension('nu',nu_length)\n pt_pair_dim=fileOut.createDimension('pt_pair',pt_num)\n scalar_dim=fileOut.createDimension('scalar',1)\n\n nu_var=fileOut.createVariable('nu','f8',('nu',))\n kabs=fileOut.createVariable('kabs','f4',('pt_pair','nu',))\n t_calc= fileOut.createVariable('t_calc','f8',('pt_pair',))\n p_calc= fileOut.createVariable('p_calc','f8',('pt_pair',))\n nu=np.array(nu)\n nu_var[:]=nu[:]\n nu_var.step=step\n\n t_calc[:]=fileNC['t_calc'][:]\n p_calc[:]=fileNC['p_calc'][:]\n k_zero=np.zeros(nu_length)\n\n for i in range(pt_num):\n print(i,pt_num,end='\\r',flush=True)\n k_zero_used=np.copy(k_zero)\n kabs[i,:]=k_zero_used[:]\n kabs[i,:nu_orig_length]=fileNC['kabs'][i,:]\n print('')\n fileNC.close()\n fileOut.close()\nfilename='abs_coeff_TiO_Toto_TerrestrialAbund_pt800.nc'\ndirectory='/home/dc-ridg1/AbsCoeffs/'\nRangeExtender(filename,directory)\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
print(' sum of n numbers with help of for loop. ')
<|reserved_special_token_0|>
for num in range(0, n + 1, 1):
sum = sum + num
print('Output: SUM of first ', n, 'numbers is: ', sum)
print(' sum of n numbers with help of while loop. ')
<|reserved_special_token_0|>
if num <= 0:
print('Enter a whole positive number!')
else:
while num > 0:
sum = sum + num
num = num - 1
print('Sum of first', hold, 'natural number is: ', sum)
print('Take an integer and find whether the number is prime or not')
<|reserved_special_token_0|>
if number > 1:
for i in range(2, number):
if number % i == 0:
print(number, 'is not a prime number')
break
else:
print(number, 'is a prime number')
else:
print(number, 'is not a prime number')
<|reserved_special_token_1|>
print(' sum of n numbers with help of for loop. ')
n = 10
sum = 0
for num in range(0, n + 1, 1):
sum = sum + num
print('Output: SUM of first ', n, 'numbers is: ', sum)
print(' sum of n numbers with help of while loop. ')
num = int(input('Enter the value of n: '))
hold = num
sum = 0
if num <= 0:
print('Enter a whole positive number!')
else:
while num > 0:
sum = sum + num
num = num - 1
print('Sum of first', hold, 'natural number is: ', sum)
print('Take an integer and find whether the number is prime or not')
number = int(input('Enter any number: '))
if number > 1:
for i in range(2, number):
if number % i == 0:
print(number, 'is not a prime number')
break
else:
print(number, 'is a prime number')
else:
print(number, 'is not a prime number')
<|reserved_special_token_1|>
#!/usr/bin/env python
# coding: utf-8
# In[2]:
print(" sum of n numbers with help of for loop. ")
n = 10
sum = 0
for num in range(0, n+1, 1):
sum = sum+num
print("Output: SUM of first ", n, "numbers is: ", sum )
# In[3]:
print(" sum of n numbers with help of while loop. ")
num = int(input("Enter the value of n: "))
hold = num
sum = 0
if num <= 0:
print("Enter a whole positive number!")
else:
while num > 0:
sum = sum + num
num = num - 1;
# displaying output
print("Sum of first", hold, "natural number is: ",sum)
# In[4]:
print("Take an integer and find whether the number is prime or not")
#input from user
number = int(input("Enter any number: "))
# prime number is always greater than 1
if number > 1:
for i in range(2, number):
if (number % i) == 0:
print(number, "is not a prime number")
break
else: print(number, "is a prime number")
# if the entered number is less than or equal to 1
# then it is not prime number
else: print(number, "is not a prime number")
# In[ ]:
|
flexible
|
{
"blob_id": "d3c36ad36c50cd97f2101bc8df99d1961b0ad7ea",
"index": 4078,
"step-1": "<mask token>\n",
"step-2": "print(' sum of n numbers with help of for loop. ')\n<mask token>\nfor num in range(0, n + 1, 1):\n sum = sum + num\nprint('Output: SUM of first ', n, 'numbers is: ', sum)\nprint(' sum of n numbers with help of while loop. ')\n<mask token>\nif num <= 0:\n print('Enter a whole positive number!')\nelse:\n while num > 0:\n sum = sum + num\n num = num - 1\nprint('Sum of first', hold, 'natural number is: ', sum)\nprint('Take an integer and find whether the number is prime or not')\n<mask token>\nif number > 1:\n for i in range(2, number):\n if number % i == 0:\n print(number, 'is not a prime number')\n break\n else:\n print(number, 'is a prime number')\nelse:\n print(number, 'is not a prime number')\n",
"step-3": "print(' sum of n numbers with help of for loop. ')\nn = 10\nsum = 0\nfor num in range(0, n + 1, 1):\n sum = sum + num\nprint('Output: SUM of first ', n, 'numbers is: ', sum)\nprint(' sum of n numbers with help of while loop. ')\nnum = int(input('Enter the value of n: '))\nhold = num\nsum = 0\nif num <= 0:\n print('Enter a whole positive number!')\nelse:\n while num > 0:\n sum = sum + num\n num = num - 1\nprint('Sum of first', hold, 'natural number is: ', sum)\nprint('Take an integer and find whether the number is prime or not')\nnumber = int(input('Enter any number: '))\nif number > 1:\n for i in range(2, number):\n if number % i == 0:\n print(number, 'is not a prime number')\n break\n else:\n print(number, 'is a prime number')\nelse:\n print(number, 'is not a prime number')\n",
"step-4": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nprint(\" sum of n numbers with help of for loop. \")\nn = 10\nsum = 0\nfor num in range(0, n+1, 1):\n sum = sum+num\nprint(\"Output: SUM of first \", n, \"numbers is: \", sum )\n\n\n# In[3]:\n\n\nprint(\" sum of n numbers with help of while loop. \")\nnum = int(input(\"Enter the value of n: \"))\nhold = num \nsum = 0 \n\n\nif num <= 0: \n print(\"Enter a whole positive number!\") \nelse: \n while num > 0: \n sum = sum + num \n num = num - 1;\n # displaying output \nprint(\"Sum of first\", hold, \"natural number is: \",sum)\n\n\n# In[4]:\n\n\nprint(\"Take an integer and find whether the number is prime or not\")\n#input from user\nnumber = int(input(\"Enter any number: \")) \n# prime number is always greater than 1\nif number > 1: \n for i in range(2, number):\n if (number % i) == 0: \n print(number, \"is not a prime number\")\n break \n else: print(number, \"is a prime number\")\n # if the entered number is less than or equal to 1 \n # then it is not prime number \nelse: print(number, \"is not a prime number\")\n\n\n# In[ ]:\n\n\n\n\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
import math
def Distance(t1, t2):
RADIUS = 6371000. # earth's mean radius in km
p1 = [0, 0]
p2 = [0, 0]
p1[0] = t1[0] * math.pi / 180.
p1[1] = t1[1] * math.pi / 180.
p2[0] = t2[0] * math.pi / 180.
p2[1] = t2[1] * math.pi / 180.
d_lat = (p2[0] - p1[0])
d_lon = (p2[1] - p1[1])
a = math.sin(d_lat / 2) * math.sin(d_lat / 2) + math.cos(
p1[0]) * math.cos(p2[0]) * math.sin(d_lon / 2) * math.sin(d_lon / 2)
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
d = RADIUS * c
return d
def tile_number(lon_deg, lat_deg, zoom):
n = 2.0 ** zoom
xtile = int((lon_deg + 180.0) / 360.0 * n)
ytile = int((lat_deg + 90.0) / 180.0 * n)
return (xtile, ytile)
|
normal
|
{
"blob_id": "f3f5b14917c89c5bc2866dd56e212bd3ec8af1cd",
"index": 4841,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef tile_number(lon_deg, lat_deg, zoom):\n n = 2.0 ** zoom\n xtile = int((lon_deg + 180.0) / 360.0 * n)\n ytile = int((lat_deg + 90.0) / 180.0 * n)\n return xtile, ytile\n",
"step-3": "<mask token>\n\n\ndef Distance(t1, t2):\n RADIUS = 6371000.0\n p1 = [0, 0]\n p2 = [0, 0]\n p1[0] = t1[0] * math.pi / 180.0\n p1[1] = t1[1] * math.pi / 180.0\n p2[0] = t2[0] * math.pi / 180.0\n p2[1] = t2[1] * math.pi / 180.0\n d_lat = p2[0] - p1[0]\n d_lon = p2[1] - p1[1]\n a = math.sin(d_lat / 2) * math.sin(d_lat / 2) + math.cos(p1[0]) * math.cos(\n p2[0]) * math.sin(d_lon / 2) * math.sin(d_lon / 2)\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))\n d = RADIUS * c\n return d\n\n\ndef tile_number(lon_deg, lat_deg, zoom):\n n = 2.0 ** zoom\n xtile = int((lon_deg + 180.0) / 360.0 * n)\n ytile = int((lat_deg + 90.0) / 180.0 * n)\n return xtile, ytile\n",
"step-4": "import math\n\n\ndef Distance(t1, t2):\n RADIUS = 6371000.0\n p1 = [0, 0]\n p2 = [0, 0]\n p1[0] = t1[0] * math.pi / 180.0\n p1[1] = t1[1] * math.pi / 180.0\n p2[0] = t2[0] * math.pi / 180.0\n p2[1] = t2[1] * math.pi / 180.0\n d_lat = p2[0] - p1[0]\n d_lon = p2[1] - p1[1]\n a = math.sin(d_lat / 2) * math.sin(d_lat / 2) + math.cos(p1[0]) * math.cos(\n p2[0]) * math.sin(d_lon / 2) * math.sin(d_lon / 2)\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))\n d = RADIUS * c\n return d\n\n\ndef tile_number(lon_deg, lat_deg, zoom):\n n = 2.0 ** zoom\n xtile = int((lon_deg + 180.0) / 360.0 * n)\n ytile = int((lat_deg + 90.0) / 180.0 * n)\n return xtile, ytile\n",
"step-5": "import math\n\ndef Distance(t1, t2):\n RADIUS = 6371000. # earth's mean radius in km\n p1 = [0, 0]\n p2 = [0, 0]\n p1[0] = t1[0] * math.pi / 180.\n p1[1] = t1[1] * math.pi / 180.\n p2[0] = t2[0] * math.pi / 180.\n p2[1] = t2[1] * math.pi / 180.\n\n d_lat = (p2[0] - p1[0])\n d_lon = (p2[1] - p1[1])\n\n a = math.sin(d_lat / 2) * math.sin(d_lat / 2) + math.cos(\n p1[0]) * math.cos(p2[0]) * math.sin(d_lon / 2) * math.sin(d_lon / 2)\n c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))\n d = RADIUS * c\n return d\n\ndef tile_number(lon_deg, lat_deg, zoom):\n n = 2.0 ** zoom\n xtile = int((lon_deg + 180.0) / 360.0 * n)\n ytile = int((lat_deg + 90.0) / 180.0 * n)\n return (xtile, ytile)",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
def hello():
messagebox.showinfo('Say Hello', 'Hello World')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def hello():
messagebox.showinfo('Say Hello', 'Hello World')
<|reserved_special_token_0|>
B1.pack()
mainloop()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
root = Tk()
def hello():
messagebox.showinfo('Say Hello', 'Hello World')
B1 = Button(root, text='Say Hello', command=hello, font='arial 20')
B1.pack()
mainloop()
<|reserved_special_token_1|>
from tkinter import *
from tkinter import messagebox
root = Tk()
def hello():
messagebox.showinfo('Say Hello', 'Hello World')
B1 = Button(root, text='Say Hello', command=hello, font='arial 20')
B1.pack()
mainloop()
<|reserved_special_token_1|>
from tkinter import *
from tkinter import messagebox
root = Tk()
def hello():
messagebox.showinfo("Say Hello", "Hello World")
B1 = Button(root, text = "Say Hello", command = hello, font='arial 20')
B1.pack()
mainloop()
|
flexible
|
{
"blob_id": "61e38ae6ae2a1ed061f9893742f45b3e44f19a68",
"index": 6110,
"step-1": "<mask token>\n\n\ndef hello():\n messagebox.showinfo('Say Hello', 'Hello World')\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef hello():\n messagebox.showinfo('Say Hello', 'Hello World')\n\n\n<mask token>\nB1.pack()\nmainloop()\n",
"step-3": "<mask token>\nroot = Tk()\n\n\ndef hello():\n messagebox.showinfo('Say Hello', 'Hello World')\n\n\nB1 = Button(root, text='Say Hello', command=hello, font='arial 20')\nB1.pack()\nmainloop()\n",
"step-4": "from tkinter import *\nfrom tkinter import messagebox\nroot = Tk()\n\n\ndef hello():\n messagebox.showinfo('Say Hello', 'Hello World')\n\n\nB1 = Button(root, text='Say Hello', command=hello, font='arial 20')\nB1.pack()\nmainloop()\n",
"step-5": "from tkinter import *\r\nfrom tkinter import messagebox\r\n\r\nroot = Tk()\r\ndef hello():\r\n messagebox.showinfo(\"Say Hello\", \"Hello World\")\r\n\r\nB1 = Button(root, text = \"Say Hello\", command = hello, font='arial 20')\r\nB1.pack()\r\n\r\nmainloop()\r\n\r\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
from .gunicorn import *
from .server_app import *
|
flexible
|
{
"blob_id": "ed5dd954dedb00bf645f9ca14b5ca9cd122b2adc",
"index": 6183,
"step-1": "<mask token>\n",
"step-2": "from .gunicorn import *\nfrom .server_app import *\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
}
|
[
0,
1
] |
def test(x):
print x
|
normal
|
{
"blob_id": "78e008b4a51cdbbb81dead7bc5945ee98ccad862",
"index": 8266,
"step-1": "def test(x):\n print x\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
rule run_all:
shell:
'''
echo 'Hello World!'
'''
|
normal
|
{
"blob_id": "c967a63d03f9f836d97ae917dba2a7bfb7a54a0e",
"index": 9673,
"step-1": "rule run_all:\n shell:\n '''\n echo 'Hello World!'\n '''\n\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
def lucky(ticket):
def sum_(number):
number = str(number)
while len(number) != 6:
number = '0' + number
x = list(map(int, number))
return sum(x[:3]) == sum(x[3:])
return 'Счастливый' if sum_(ticket) == sum_(lastTicket) else 'Несчастливый'
<|reserved_special_token_0|>
<|reserved_special_token_1|>
def lucky(ticket):
def sum_(number):
number = str(number)
while len(number) != 6:
number = '0' + number
x = list(map(int, number))
return sum(x[:3]) == sum(x[3:])
return 'Счастливый' if sum_(ticket) == sum_(lastTicket) else 'Несчастливый'
<|reserved_special_token_0|>
print(lucky(100001))
<|reserved_special_token_0|>
print(lucky(100001))
<|reserved_special_token_1|>
def lucky(ticket):
def sum_(number):
number = str(number)
while len(number) != 6:
number = '0' + number
x = list(map(int, number))
return sum(x[:3]) == sum(x[3:])
return 'Счастливый' if sum_(ticket) == sum_(lastTicket) else 'Несчастливый'
lastTicket = 123456
print(lucky(100001))
lastTicket = 123321
print(lucky(100001))
<|reserved_special_token_1|>
# Алексей Головлев, группа БСБО-07-19
def lucky(ticket):
def sum_(number):
number = str(number)
while len(number) != 6:
number = '0' + number
x = list(map(int, number))
return sum(x[:3]) == sum(x[3:])
return 'Счастливый' if sum_(ticket) == sum_(lastTicket) else 'Несчастливый'
lastTicket = 123456
print(lucky(100001))
lastTicket = 123321
print(lucky(100001))
|
flexible
|
{
"blob_id": "85ac851e28dba3816f18fefb727001b8e396cc2b",
"index": 5278,
"step-1": "<mask token>\n",
"step-2": "def lucky(ticket):\n\n def sum_(number):\n number = str(number)\n while len(number) != 6:\n number = '0' + number\n x = list(map(int, number))\n return sum(x[:3]) == sum(x[3:])\n return 'Счастливый' if sum_(ticket) == sum_(lastTicket) else 'Несчастливый'\n\n\n<mask token>\n",
"step-3": "def lucky(ticket):\n\n def sum_(number):\n number = str(number)\n while len(number) != 6:\n number = '0' + number\n x = list(map(int, number))\n return sum(x[:3]) == sum(x[3:])\n return 'Счастливый' if sum_(ticket) == sum_(lastTicket) else 'Несчастливый'\n\n\n<mask token>\nprint(lucky(100001))\n<mask token>\nprint(lucky(100001))\n",
"step-4": "def lucky(ticket):\n\n def sum_(number):\n number = str(number)\n while len(number) != 6:\n number = '0' + number\n x = list(map(int, number))\n return sum(x[:3]) == sum(x[3:])\n return 'Счастливый' if sum_(ticket) == sum_(lastTicket) else 'Несчастливый'\n\n\nlastTicket = 123456\nprint(lucky(100001))\nlastTicket = 123321\nprint(lucky(100001))\n",
"step-5": "# Алексей Головлев, группа БСБО-07-19\n\ndef lucky(ticket):\n def sum_(number):\n number = str(number)\n while len(number) != 6:\n number = '0' + number\n x = list(map(int, number))\n return sum(x[:3]) == sum(x[3:])\n\n return 'Счастливый' if sum_(ticket) == sum_(lastTicket) else 'Несчастливый'\n\n\nlastTicket = 123456\nprint(lucky(100001))\n\nlastTicket = 123321\nprint(lucky(100001))\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
def console_check(csl, f):
if csl == 'playstation-4':
f.write('\tdbo:computingPlatform dbpedia:PlayStation_4.')
if csl == 'playstation-3':
f.write('\tdbo:computingPlatform dbpedia:PlayStation_3.')
if csl == 'playstation-2':
f.write('\tdbo:computingPlatform dbpedia:PlayStation_2.')
if csl == 'playstation':
f.write('\tdbo:computingPlatform dbpedia:PlayStation.')
if csl == 'xbox-one':
f.write('\tdbo:computingPlatform dbpedia:Xbox_One.')
if csl == 'xbox-360':
f.write('\tdbo:computingPlatform dbpedia:Xbox_360.')
if csl == 'switch':
f.write('\tdbo:computingPlatform dbpedia:Nintendo_Switch.')
if csl == 'pc':
f.write('\tdbo:computingPlatform dbpedia:Computer.')
f.write('\n\n')
def initial_warnings():
cprint('Esse programa funciona usando uma API chamada Chicken Coop API.',
'red', attrs=['bold'])
cprint('Essa API pega informações sobre jogos de determinados consoles.',
'red', attrs=['bold'])
cprint('Para que ela rode corretamente, siga as seguintes instruções:',
'cyan', attrs=['bold'])
cprint('Consoles:', 'yellow', attrs=['bold'])
cprint(' Playstation 4 -> playstation-4', 'green', attrs=['bold'])
cprint(' Xbox One -> xbox-one', 'green', attrs=['bold'])
cprint(' Computador -> pc', 'green', attrs=['bold'])
cprint(' Nintendo Switch -> switch', 'green', attrs=['bold'])
cprint('Exemplos de jogos: ', 'yellow', attrs=['bold'])
cprint(' Uncharted: The Lost Legacy', 'green', attrs=['bold'])
cprint(' God of War', 'green', attrs=['bold'])
cprint(' Ori and The Blind Forest', 'green', attrs=['bold'])
cprint(
'Aviso: Os jogos devem ser escritos com o nome exato e os consoles da maneira demonstrada, caso contrário, não funcionará!'
, 'magenta', attrs=['bold'])
print('\n')
def get_and_write(mc, csl):
print(f"Title: {mc['result']['title']}")
print(f"Release Date: {mc['result']['releaseDate']}")
print(f"Score: {mc['result']['score']}")
print(f"Developer: {mc['result']['developer']}\n")
mc_title = mc['result']['title']
mc_score = mc['result']['score']
mc_developer = mc['result']['developer']
rsp = write_file(mc_title, mc_score, mc_developer, mc, csl)
if rsp:
write_file(mc_title, mc_score, mc_developer, mc, csl)
def write_file(title, score, developer, mc, csl):
source = '<https://www.metacritic.com/game/'
aux_title = ''
source = source + csl + '/'
path = Path('gamedeflib_rdf.ttl')
if path.is_file() and os.stat('gamedeflib_rdf.ttl').st_size > 0:
file = open('gamedeflib_rdf.ttl', 'r')
count = 1
for element in file:
jogo = f'_:game{count}\n'
if element == jogo:
count = count + 1
file.close()
file = open('gamedeflib_rdf.ttl', 'a+')
file.write(f'\n_:game{count}\n')
file.write(f'\trdfs:label "{title}";\n')
file.write(f'\tdbp:score {score};\n')
genre_number(mc, file)
publisher_number(mc, file)
file.write(f'\tdbo:developer "{developer}";\n')
aux_title = title.lower()
aux_title = aux_title.replace(':', '')
aux_title = aux_title.replace(' ', '-')
source = source + aux_title + '>'
file.write(f'\tdc:source {source};\n')
console_check(csl, file)
file.close()
else:
file = open('gamedeflib_rdf.ttl', 'w+')
file.write('@prefix dc: \t<http://purl.org/dc/elements/1.1/> .\n')
file.write(
'@prefix rdf:\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n')
file.write('@prefix rdfs:\t<http://www.w3.org/2000/01/rdf-schema#> .\n'
)
file.write('@prefix foaf:\t<http://xmlns.com/foaf/0.1/> .\n')
file.write('@prefix dbo: <http://dbpedia.org/ontology/> .\n')
file.write('@prefix dbpedia: <http://dbpedia.org/page/> .\n')
file.write('@prefix dbp: <http://dbpedia.org/property/> .\n')
file.write(
"""dbpedia:PlayStation_4
foaf:name "PlayStation 4";
dbo:type dbpedia:Home_video_game_console;
rdfs:label "PlayStation 4".
"""
)
file.write(
"""dbpedia:PlayStation_3
dbo:type dbpedia:Home_video_game_console;
rdfs:label "PlayStation 3".
"""
)
file.write(
"""dbpedia:PlayStation_2
dbo:type dbpedia:Home_video_game_console;
rdfs:label "PlayStation 2".
"""
)
file.write(
"""dbpedia:PlayStation
dbp:type dbpedia:Video_game_console;
rdfs:label "PlayStation".
"""
)
file.write(
"""dbpedia:XBox_One
foaf:name "XBox One";
dbo:type dbpedia:Home_video_game_console;
rdfs:label "XBox One" .
"""
)
file.write(
"""dbpedia:XBox_360
dbo:type dbpedia:Home_video_game_console;
rdfs:label "XBox 360" .
"""
)
file.write(
"""dbpedia:Nintendo_Switch
foaf:name "New Nintendank New Wii U 2.0+";
dbo:type dbpedia:Video_game_hardware;
rdfs:label "Nintendo Switch" .
"""
)
file.write(
"""dbpedia:Computer
dbp:title "Computer";
rdf:type dbo:Device;
rdfs:label "Computer" .
"""
)
return 1
def genre_number(mc, f):
tam = len(mc['result']['genre'])
for x in range(0, tam):
print(f"Genre number {x + 1}: {mc['result']['genre'][x]}")
aux = mc['result']['genre'][x]
f.write(f'\tdbo:genre "{aux}";\n')
def publisher_number(mc, f):
tam = len(mc['result']['publisher'])
for x in range(0, tam):
print(f"Publisher number {x + 1}: {mc['result']['publisher'][x]}")
aux = mc['result']['publisher'][x]
f.write(f'\tdbo:publisher "{aux}";\n')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def console_check(csl, f):
if csl == 'playstation-4':
f.write('\tdbo:computingPlatform dbpedia:PlayStation_4.')
if csl == 'playstation-3':
f.write('\tdbo:computingPlatform dbpedia:PlayStation_3.')
if csl == 'playstation-2':
f.write('\tdbo:computingPlatform dbpedia:PlayStation_2.')
if csl == 'playstation':
f.write('\tdbo:computingPlatform dbpedia:PlayStation.')
if csl == 'xbox-one':
f.write('\tdbo:computingPlatform dbpedia:Xbox_One.')
if csl == 'xbox-360':
f.write('\tdbo:computingPlatform dbpedia:Xbox_360.')
if csl == 'switch':
f.write('\tdbo:computingPlatform dbpedia:Nintendo_Switch.')
if csl == 'pc':
f.write('\tdbo:computingPlatform dbpedia:Computer.')
f.write('\n\n')
def initial_warnings():
cprint('Esse programa funciona usando uma API chamada Chicken Coop API.',
'red', attrs=['bold'])
cprint('Essa API pega informações sobre jogos de determinados consoles.',
'red', attrs=['bold'])
cprint('Para que ela rode corretamente, siga as seguintes instruções:',
'cyan', attrs=['bold'])
cprint('Consoles:', 'yellow', attrs=['bold'])
cprint(' Playstation 4 -> playstation-4', 'green', attrs=['bold'])
cprint(' Xbox One -> xbox-one', 'green', attrs=['bold'])
cprint(' Computador -> pc', 'green', attrs=['bold'])
cprint(' Nintendo Switch -> switch', 'green', attrs=['bold'])
cprint('Exemplos de jogos: ', 'yellow', attrs=['bold'])
cprint(' Uncharted: The Lost Legacy', 'green', attrs=['bold'])
cprint(' God of War', 'green', attrs=['bold'])
cprint(' Ori and The Blind Forest', 'green', attrs=['bold'])
cprint(
'Aviso: Os jogos devem ser escritos com o nome exato e os consoles da maneira demonstrada, caso contrário, não funcionará!'
, 'magenta', attrs=['bold'])
print('\n')
def get_and_write(mc, csl):
print(f"Title: {mc['result']['title']}")
print(f"Release Date: {mc['result']['releaseDate']}")
print(f"Score: {mc['result']['score']}")
print(f"Developer: {mc['result']['developer']}\n")
mc_title = mc['result']['title']
mc_score = mc['result']['score']
mc_developer = mc['result']['developer']
rsp = write_file(mc_title, mc_score, mc_developer, mc, csl)
if rsp:
write_file(mc_title, mc_score, mc_developer, mc, csl)
def write_file(title, score, developer, mc, csl):
source = '<https://www.metacritic.com/game/'
aux_title = ''
source = source + csl + '/'
path = Path('gamedeflib_rdf.ttl')
if path.is_file() and os.stat('gamedeflib_rdf.ttl').st_size > 0:
file = open('gamedeflib_rdf.ttl', 'r')
count = 1
for element in file:
jogo = f'_:game{count}\n'
if element == jogo:
count = count + 1
file.close()
file = open('gamedeflib_rdf.ttl', 'a+')
file.write(f'\n_:game{count}\n')
file.write(f'\trdfs:label "{title}";\n')
file.write(f'\tdbp:score {score};\n')
genre_number(mc, file)
publisher_number(mc, file)
file.write(f'\tdbo:developer "{developer}";\n')
aux_title = title.lower()
aux_title = aux_title.replace(':', '')
aux_title = aux_title.replace(' ', '-')
source = source + aux_title + '>'
file.write(f'\tdc:source {source};\n')
console_check(csl, file)
file.close()
else:
file = open('gamedeflib_rdf.ttl', 'w+')
file.write('@prefix dc: \t<http://purl.org/dc/elements/1.1/> .\n')
file.write(
'@prefix rdf:\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n')
file.write('@prefix rdfs:\t<http://www.w3.org/2000/01/rdf-schema#> .\n'
)
file.write('@prefix foaf:\t<http://xmlns.com/foaf/0.1/> .\n')
file.write('@prefix dbo: <http://dbpedia.org/ontology/> .\n')
file.write('@prefix dbpedia: <http://dbpedia.org/page/> .\n')
file.write('@prefix dbp: <http://dbpedia.org/property/> .\n')
file.write(
"""dbpedia:PlayStation_4
foaf:name "PlayStation 4";
dbo:type dbpedia:Home_video_game_console;
rdfs:label "PlayStation 4".
"""
)
file.write(
"""dbpedia:PlayStation_3
dbo:type dbpedia:Home_video_game_console;
rdfs:label "PlayStation 3".
"""
)
file.write(
"""dbpedia:PlayStation_2
dbo:type dbpedia:Home_video_game_console;
rdfs:label "PlayStation 2".
"""
)
file.write(
"""dbpedia:PlayStation
dbp:type dbpedia:Video_game_console;
rdfs:label "PlayStation".
"""
)
file.write(
"""dbpedia:XBox_One
foaf:name "XBox One";
dbo:type dbpedia:Home_video_game_console;
rdfs:label "XBox One" .
"""
)
file.write(
"""dbpedia:XBox_360
dbo:type dbpedia:Home_video_game_console;
rdfs:label "XBox 360" .
"""
)
file.write(
"""dbpedia:Nintendo_Switch
foaf:name "New Nintendank New Wii U 2.0+";
dbo:type dbpedia:Video_game_hardware;
rdfs:label "Nintendo Switch" .
"""
)
file.write(
"""dbpedia:Computer
dbp:title "Computer";
rdf:type dbo:Device;
rdfs:label "Computer" .
"""
)
return 1
def genre_number(mc, f):
tam = len(mc['result']['genre'])
for x in range(0, tam):
print(f"Genre number {x + 1}: {mc['result']['genre'][x]}")
aux = mc['result']['genre'][x]
f.write(f'\tdbo:genre "{aux}";\n')
def publisher_number(mc, f):
tam = len(mc['result']['publisher'])
for x in range(0, tam):
print(f"Publisher number {x + 1}: {mc['result']['publisher'][x]}")
aux = mc['result']['publisher'][x]
f.write(f'\tdbo:publisher "{aux}";\n')
def main():
print('Digite o console do jogo desejado: ', end='')
console = str(input())
print('Digite o título do jogo desejado: ', end='')
title = str(input())
try:
url = 'https://chicken-coop.p.rapidapi.com/games/' + title
querystring = {'platform': console}
headers = {'x-rapidapi-host': 'chicken-coop.p.rapidapi.com',
'x-rapidapi-key':
'c3df04dcc0msh2d6e3cc8ccd93dep1c9851jsn230c81227b26'}
response = requests.request('GET', url, headers=headers, params=
querystring)
metacritic = json.loads(response.text)
if metacritic['result'] == 'No result':
print(
'\nAlguma informação digitada está incorreta. Tente novamente.'
)
else:
get_and_write(metacritic, console)
except Exception as err:
print(
'Algum erro desconhecido ocorreu durante a execucação.\nTente novamente.'
)
cprint(err, 'red')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def console_check(csl, f):
if csl == 'playstation-4':
f.write('\tdbo:computingPlatform dbpedia:PlayStation_4.')
if csl == 'playstation-3':
f.write('\tdbo:computingPlatform dbpedia:PlayStation_3.')
if csl == 'playstation-2':
f.write('\tdbo:computingPlatform dbpedia:PlayStation_2.')
if csl == 'playstation':
f.write('\tdbo:computingPlatform dbpedia:PlayStation.')
if csl == 'xbox-one':
f.write('\tdbo:computingPlatform dbpedia:Xbox_One.')
if csl == 'xbox-360':
f.write('\tdbo:computingPlatform dbpedia:Xbox_360.')
if csl == 'switch':
f.write('\tdbo:computingPlatform dbpedia:Nintendo_Switch.')
if csl == 'pc':
f.write('\tdbo:computingPlatform dbpedia:Computer.')
f.write('\n\n')
def initial_warnings():
cprint('Esse programa funciona usando uma API chamada Chicken Coop API.',
'red', attrs=['bold'])
cprint('Essa API pega informações sobre jogos de determinados consoles.',
'red', attrs=['bold'])
cprint('Para que ela rode corretamente, siga as seguintes instruções:',
'cyan', attrs=['bold'])
cprint('Consoles:', 'yellow', attrs=['bold'])
cprint(' Playstation 4 -> playstation-4', 'green', attrs=['bold'])
cprint(' Xbox One -> xbox-one', 'green', attrs=['bold'])
cprint(' Computador -> pc', 'green', attrs=['bold'])
cprint(' Nintendo Switch -> switch', 'green', attrs=['bold'])
cprint('Exemplos de jogos: ', 'yellow', attrs=['bold'])
cprint(' Uncharted: The Lost Legacy', 'green', attrs=['bold'])
cprint(' God of War', 'green', attrs=['bold'])
cprint(' Ori and The Blind Forest', 'green', attrs=['bold'])
cprint(
'Aviso: Os jogos devem ser escritos com o nome exato e os consoles da maneira demonstrada, caso contrário, não funcionará!'
, 'magenta', attrs=['bold'])
print('\n')
def get_and_write(mc, csl):
print(f"Title: {mc['result']['title']}")
print(f"Release Date: {mc['result']['releaseDate']}")
print(f"Score: {mc['result']['score']}")
print(f"Developer: {mc['result']['developer']}\n")
mc_title = mc['result']['title']
mc_score = mc['result']['score']
mc_developer = mc['result']['developer']
rsp = write_file(mc_title, mc_score, mc_developer, mc, csl)
if rsp:
write_file(mc_title, mc_score, mc_developer, mc, csl)
def write_file(title, score, developer, mc, csl):
source = '<https://www.metacritic.com/game/'
aux_title = ''
source = source + csl + '/'
path = Path('gamedeflib_rdf.ttl')
if path.is_file() and os.stat('gamedeflib_rdf.ttl').st_size > 0:
file = open('gamedeflib_rdf.ttl', 'r')
count = 1
for element in file:
jogo = f'_:game{count}\n'
if element == jogo:
count = count + 1
file.close()
file = open('gamedeflib_rdf.ttl', 'a+')
file.write(f'\n_:game{count}\n')
file.write(f'\trdfs:label "{title}";\n')
file.write(f'\tdbp:score {score};\n')
genre_number(mc, file)
publisher_number(mc, file)
file.write(f'\tdbo:developer "{developer}";\n')
aux_title = title.lower()
aux_title = aux_title.replace(':', '')
aux_title = aux_title.replace(' ', '-')
source = source + aux_title + '>'
file.write(f'\tdc:source {source};\n')
console_check(csl, file)
file.close()
else:
file = open('gamedeflib_rdf.ttl', 'w+')
file.write('@prefix dc: \t<http://purl.org/dc/elements/1.1/> .\n')
file.write(
'@prefix rdf:\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n')
file.write('@prefix rdfs:\t<http://www.w3.org/2000/01/rdf-schema#> .\n'
)
file.write('@prefix foaf:\t<http://xmlns.com/foaf/0.1/> .\n')
file.write('@prefix dbo: <http://dbpedia.org/ontology/> .\n')
file.write('@prefix dbpedia: <http://dbpedia.org/page/> .\n')
file.write('@prefix dbp: <http://dbpedia.org/property/> .\n')
file.write(
"""dbpedia:PlayStation_4
foaf:name "PlayStation 4";
dbo:type dbpedia:Home_video_game_console;
rdfs:label "PlayStation 4".
"""
)
file.write(
"""dbpedia:PlayStation_3
dbo:type dbpedia:Home_video_game_console;
rdfs:label "PlayStation 3".
"""
)
file.write(
"""dbpedia:PlayStation_2
dbo:type dbpedia:Home_video_game_console;
rdfs:label "PlayStation 2".
"""
)
file.write(
"""dbpedia:PlayStation
dbp:type dbpedia:Video_game_console;
rdfs:label "PlayStation".
"""
)
file.write(
"""dbpedia:XBox_One
foaf:name "XBox One";
dbo:type dbpedia:Home_video_game_console;
rdfs:label "XBox One" .
"""
)
file.write(
"""dbpedia:XBox_360
dbo:type dbpedia:Home_video_game_console;
rdfs:label "XBox 360" .
"""
)
file.write(
"""dbpedia:Nintendo_Switch
foaf:name "New Nintendank New Wii U 2.0+";
dbo:type dbpedia:Video_game_hardware;
rdfs:label "Nintendo Switch" .
"""
)
file.write(
"""dbpedia:Computer
dbp:title "Computer";
rdf:type dbo:Device;
rdfs:label "Computer" .
"""
)
return 1
def genre_number(mc, f):
tam = len(mc['result']['genre'])
for x in range(0, tam):
print(f"Genre number {x + 1}: {mc['result']['genre'][x]}")
aux = mc['result']['genre'][x]
f.write(f'\tdbo:genre "{aux}";\n')
def publisher_number(mc, f):
tam = len(mc['result']['publisher'])
for x in range(0, tam):
print(f"Publisher number {x + 1}: {mc['result']['publisher'][x]}")
aux = mc['result']['publisher'][x]
f.write(f'\tdbo:publisher "{aux}";\n')
def main():
print('Digite o console do jogo desejado: ', end='')
console = str(input())
print('Digite o título do jogo desejado: ', end='')
title = str(input())
try:
url = 'https://chicken-coop.p.rapidapi.com/games/' + title
querystring = {'platform': console}
headers = {'x-rapidapi-host': 'chicken-coop.p.rapidapi.com',
'x-rapidapi-key':
'c3df04dcc0msh2d6e3cc8ccd93dep1c9851jsn230c81227b26'}
response = requests.request('GET', url, headers=headers, params=
querystring)
metacritic = json.loads(response.text)
if metacritic['result'] == 'No result':
print(
'\nAlguma informação digitada está incorreta. Tente novamente.'
)
else:
get_and_write(metacritic, console)
except Exception as err:
print(
'Algum erro desconhecido ocorreu durante a execucação.\nTente novamente.'
)
cprint(err, 'red')
initial_warnings()
main()
while True:
print('Gostaria de adicionar outro jogo na base RDF: (1 - Sim/0 - Não): ',
end='')
try:
ans = int(input())
if ans == 1:
main()
elif ans == 0:
print('Encerrando o script')
break
else:
print('Valor digitado deve ser 0 ou 1.')
except ValueError as e:
print('Valor foi inserido incorretamente. Tente denovo.')
cprint(e, 'red')
<|reserved_special_token_1|>
import requests
import json
from termcolor import cprint
from pathlib import Path
import os
def console_check(csl, f):
if csl == 'playstation-4':
f.write('\tdbo:computingPlatform dbpedia:PlayStation_4.')
if csl == 'playstation-3':
f.write('\tdbo:computingPlatform dbpedia:PlayStation_3.')
if csl == 'playstation-2':
f.write('\tdbo:computingPlatform dbpedia:PlayStation_2.')
if csl == 'playstation':
f.write('\tdbo:computingPlatform dbpedia:PlayStation.')
if csl == 'xbox-one':
f.write('\tdbo:computingPlatform dbpedia:Xbox_One.')
if csl == 'xbox-360':
f.write('\tdbo:computingPlatform dbpedia:Xbox_360.')
if csl == 'switch':
f.write('\tdbo:computingPlatform dbpedia:Nintendo_Switch.')
if csl == 'pc':
f.write('\tdbo:computingPlatform dbpedia:Computer.')
f.write('\n\n')
def initial_warnings():
cprint('Esse programa funciona usando uma API chamada Chicken Coop API.',
'red', attrs=['bold'])
cprint('Essa API pega informações sobre jogos de determinados consoles.',
'red', attrs=['bold'])
cprint('Para que ela rode corretamente, siga as seguintes instruções:',
'cyan', attrs=['bold'])
cprint('Consoles:', 'yellow', attrs=['bold'])
cprint(' Playstation 4 -> playstation-4', 'green', attrs=['bold'])
cprint(' Xbox One -> xbox-one', 'green', attrs=['bold'])
cprint(' Computador -> pc', 'green', attrs=['bold'])
cprint(' Nintendo Switch -> switch', 'green', attrs=['bold'])
cprint('Exemplos de jogos: ', 'yellow', attrs=['bold'])
cprint(' Uncharted: The Lost Legacy', 'green', attrs=['bold'])
cprint(' God of War', 'green', attrs=['bold'])
cprint(' Ori and The Blind Forest', 'green', attrs=['bold'])
cprint(
'Aviso: Os jogos devem ser escritos com o nome exato e os consoles da maneira demonstrada, caso contrário, não funcionará!'
, 'magenta', attrs=['bold'])
print('\n')
def get_and_write(mc, csl):
print(f"Title: {mc['result']['title']}")
print(f"Release Date: {mc['result']['releaseDate']}")
print(f"Score: {mc['result']['score']}")
print(f"Developer: {mc['result']['developer']}\n")
mc_title = mc['result']['title']
mc_score = mc['result']['score']
mc_developer = mc['result']['developer']
rsp = write_file(mc_title, mc_score, mc_developer, mc, csl)
if rsp:
write_file(mc_title, mc_score, mc_developer, mc, csl)
def write_file(title, score, developer, mc, csl):
source = '<https://www.metacritic.com/game/'
aux_title = ''
source = source + csl + '/'
path = Path('gamedeflib_rdf.ttl')
if path.is_file() and os.stat('gamedeflib_rdf.ttl').st_size > 0:
file = open('gamedeflib_rdf.ttl', 'r')
count = 1
for element in file:
jogo = f'_:game{count}\n'
if element == jogo:
count = count + 1
file.close()
file = open('gamedeflib_rdf.ttl', 'a+')
file.write(f'\n_:game{count}\n')
file.write(f'\trdfs:label "{title}";\n')
file.write(f'\tdbp:score {score};\n')
genre_number(mc, file)
publisher_number(mc, file)
file.write(f'\tdbo:developer "{developer}";\n')
aux_title = title.lower()
aux_title = aux_title.replace(':', '')
aux_title = aux_title.replace(' ', '-')
source = source + aux_title + '>'
file.write(f'\tdc:source {source};\n')
console_check(csl, file)
file.close()
else:
file = open('gamedeflib_rdf.ttl', 'w+')
file.write('@prefix dc: \t<http://purl.org/dc/elements/1.1/> .\n')
file.write(
'@prefix rdf:\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n')
file.write('@prefix rdfs:\t<http://www.w3.org/2000/01/rdf-schema#> .\n'
)
file.write('@prefix foaf:\t<http://xmlns.com/foaf/0.1/> .\n')
file.write('@prefix dbo: <http://dbpedia.org/ontology/> .\n')
file.write('@prefix dbpedia: <http://dbpedia.org/page/> .\n')
file.write('@prefix dbp: <http://dbpedia.org/property/> .\n')
file.write(
"""dbpedia:PlayStation_4
foaf:name "PlayStation 4";
dbo:type dbpedia:Home_video_game_console;
rdfs:label "PlayStation 4".
"""
)
file.write(
"""dbpedia:PlayStation_3
dbo:type dbpedia:Home_video_game_console;
rdfs:label "PlayStation 3".
"""
)
file.write(
"""dbpedia:PlayStation_2
dbo:type dbpedia:Home_video_game_console;
rdfs:label "PlayStation 2".
"""
)
file.write(
"""dbpedia:PlayStation
dbp:type dbpedia:Video_game_console;
rdfs:label "PlayStation".
"""
)
file.write(
"""dbpedia:XBox_One
foaf:name "XBox One";
dbo:type dbpedia:Home_video_game_console;
rdfs:label "XBox One" .
"""
)
file.write(
"""dbpedia:XBox_360
dbo:type dbpedia:Home_video_game_console;
rdfs:label "XBox 360" .
"""
)
file.write(
"""dbpedia:Nintendo_Switch
foaf:name "New Nintendank New Wii U 2.0+";
dbo:type dbpedia:Video_game_hardware;
rdfs:label "Nintendo Switch" .
"""
)
file.write(
"""dbpedia:Computer
dbp:title "Computer";
rdf:type dbo:Device;
rdfs:label "Computer" .
"""
)
return 1
def genre_number(mc, f):
tam = len(mc['result']['genre'])
for x in range(0, tam):
print(f"Genre number {x + 1}: {mc['result']['genre'][x]}")
aux = mc['result']['genre'][x]
f.write(f'\tdbo:genre "{aux}";\n')
def publisher_number(mc, f):
tam = len(mc['result']['publisher'])
for x in range(0, tam):
print(f"Publisher number {x + 1}: {mc['result']['publisher'][x]}")
aux = mc['result']['publisher'][x]
f.write(f'\tdbo:publisher "{aux}";\n')
def main():
print('Digite o console do jogo desejado: ', end='')
console = str(input())
print('Digite o título do jogo desejado: ', end='')
title = str(input())
try:
url = 'https://chicken-coop.p.rapidapi.com/games/' + title
querystring = {'platform': console}
headers = {'x-rapidapi-host': 'chicken-coop.p.rapidapi.com',
'x-rapidapi-key':
'c3df04dcc0msh2d6e3cc8ccd93dep1c9851jsn230c81227b26'}
response = requests.request('GET', url, headers=headers, params=
querystring)
metacritic = json.loads(response.text)
if metacritic['result'] == 'No result':
print(
'\nAlguma informação digitada está incorreta. Tente novamente.'
)
else:
get_and_write(metacritic, console)
except Exception as err:
print(
'Algum erro desconhecido ocorreu durante a execucação.\nTente novamente.'
)
cprint(err, 'red')
initial_warnings()
main()
while True:
print('Gostaria de adicionar outro jogo na base RDF: (1 - Sim/0 - Não): ',
end='')
try:
ans = int(input())
if ans == 1:
main()
elif ans == 0:
print('Encerrando o script')
break
else:
print('Valor digitado deve ser 0 ou 1.')
except ValueError as e:
print('Valor foi inserido incorretamente. Tente denovo.')
cprint(e, 'red')
<|reserved_special_token_1|>
import requests
import json
from termcolor import cprint
from pathlib import Path
import os
def console_check(csl, f):
if csl == 'playstation-4':
f.write('\tdbo:computingPlatform dbpedia:PlayStation_4.')
if csl == 'playstation-3':
f.write('\tdbo:computingPlatform dbpedia:PlayStation_3.')
if csl == 'playstation-2':
f.write('\tdbo:computingPlatform dbpedia:PlayStation_2.')
if csl == 'playstation':
f.write('\tdbo:computingPlatform dbpedia:PlayStation.')
if csl == 'xbox-one':
f.write('\tdbo:computingPlatform dbpedia:Xbox_One.')
if csl == 'xbox-360':
f.write('\tdbo:computingPlatform dbpedia:Xbox_360.')
if csl == 'switch':
f.write('\tdbo:computingPlatform dbpedia:Nintendo_Switch.')
if csl == 'pc':
f.write('\tdbo:computingPlatform dbpedia:Computer.')
f.write('\n\n')
def initial_warnings():
cprint("Esse programa funciona usando uma API chamada Chicken Coop API.", "red", attrs=['bold'])
cprint("Essa API pega informações sobre jogos de determinados consoles.", "red", attrs=['bold'])
cprint("Para que ela rode corretamente, siga as seguintes instruções:", "cyan", attrs=['bold'])
cprint("Consoles:", 'yellow', attrs=['bold'])
cprint(" Playstation 4 -> playstation-4", "green", attrs=['bold'])
cprint(" Xbox One -> xbox-one", "green", attrs=['bold'])
cprint(" Computador -> pc", "green", attrs=['bold'])
cprint(" Nintendo Switch -> switch", "green", attrs=['bold'])
cprint("Exemplos de jogos: ", 'yellow', attrs=['bold'])
cprint(" Uncharted: The Lost Legacy", "green", attrs=['bold'])
cprint(" God of War", "green", attrs=['bold'])
cprint(" Ori and The Blind Forest", "green", attrs=['bold'])
cprint("Aviso: Os jogos devem ser escritos com o nome exato e os consoles da maneira demonstrada,"
" caso contrário, não funcionará!", 'magenta', attrs=['bold'])
print("\n")
def get_and_write(mc, csl):
print(f"Title: {mc['result']['title']}")
print(f"Release Date: {mc['result']['releaseDate']}")
# print(f"Description: {mc['result']['description']}")
print(f"Score: {mc['result']['score']}")
# print(f"Rating: {mc['result']['rating']}")
print(f"Developer: {mc['result']['developer']}\n")
mc_title = mc['result']['title']
# mc_description = mc['result']['description']
mc_score = mc['result']['score']
mc_developer = mc['result']['developer']
rsp = write_file(mc_title, mc_score, mc_developer, mc, csl)
if rsp:
write_file(mc_title, mc_score, mc_developer, mc, csl)
def write_file(title, score, developer, mc, csl):
source = "<https://www.metacritic.com/game/"
aux_title = ''
source = source + csl + '/'
path = Path('gamedeflib_rdf.ttl')
if path.is_file() and os.stat('gamedeflib_rdf.ttl').st_size > 0:
file = open('gamedeflib_rdf.ttl', 'r')
count = 1
for element in file:
jogo = f'_:game{count}\n'
if element == jogo:
count = count + 1
file.close()
file = open('gamedeflib_rdf.ttl', 'a+')
file.write(f'\n_:game{count}\n')
file.write(f'\trdfs:label "{title}";\n')
file.write(f'\tdbp:score {score};\n')
genre_number(mc, file)
publisher_number(mc, file)
file.write(f'\tdbo:developer "{developer}";\n')
aux_title = title.lower()
aux_title = aux_title.replace(":", "")
aux_title = aux_title.replace(" ", "-")
source = source + aux_title + ">"
file.write(f'\tdc:source {source};\n')
console_check(csl, file)
file.close()
else:
file = open('gamedeflib_rdf.ttl', 'w+')
file.write("@prefix dc: <http://purl.org/dc/elements/1.1/> .\n")
file.write("@prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\n")
file.write("@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .\n")
file.write("@prefix foaf: <http://xmlns.com/foaf/0.1/> .\n")
file.write("@prefix dbo: <http://dbpedia.org/ontology/> .\n")
file.write("@prefix dbpedia: <http://dbpedia.org/page/> .\n")
file.write("@prefix dbp: <http://dbpedia.org/property/> .\n")
file.write('dbpedia:PlayStation_4\n'
'\tfoaf:name "PlayStation 4";\n'
'\tdbo:type dbpedia:Home_video_game_console;\n'
'\trdfs:label "PlayStation 4".\n\n')
file.write('dbpedia:PlayStation_3\n'
'\tdbo:type dbpedia:Home_video_game_console;\n'
'\trdfs:label "PlayStation 3".\n\n')
file.write('dbpedia:PlayStation_2\n'
'\tdbo:type dbpedia:Home_video_game_console;\n'
'\trdfs:label "PlayStation 2".\n\n')
file.write('dbpedia:PlayStation\n'
'\tdbp:type dbpedia:Video_game_console;\n'
'\trdfs:label "PlayStation".\n\n')
file.write('dbpedia:XBox_One\n'
'\tfoaf:name "XBox One";\n'
'\tdbo:type dbpedia:Home_video_game_console;\n'
'\trdfs:label "XBox One" .\n\n')
file.write('dbpedia:XBox_360\n'
'\tdbo:type dbpedia:Home_video_game_console;\n'
'\trdfs:label "XBox 360" .\n\n')
file.write('dbpedia:Nintendo_Switch\n'
'\tfoaf:name "New Nintendank New Wii U 2.0+";\n'
'\tdbo:type dbpedia:Video_game_hardware;\n'
'\trdfs:label "Nintendo Switch" .\n\n')
file.write('dbpedia:Computer\n'
'\tdbp:title "Computer";\n'
'\trdf:type dbo:Device;\n'
'\trdfs:label "Computer" .\n\n')
return 1
def genre_number(mc, f):
tam = len(mc['result']['genre'])
for x in range(0, tam):
print(f"Genre number {x+1}: {mc['result']['genre'][x]}")
aux = mc['result']['genre'][x]
f.write(f'\tdbo:genre "{aux}";\n')
def publisher_number(mc, f):
tam = len(mc['result']['publisher'])
for x in range(0, tam):
print(f"Publisher number {x + 1}: {mc['result']['publisher'][x]}")
aux = mc['result']['publisher'][x]
f.write(f'\tdbo:publisher "{aux}";\n')
def main():
print('Digite o console do jogo desejado: ', end='')
console = str(input())
print('Digite o título do jogo desejado: ', end='')
title = str(input())
try:
url = "https://chicken-coop.p.rapidapi.com/games/"+title
querystring = {"platform": console}
headers = {
'x-rapidapi-host': "chicken-coop.p.rapidapi.com",
'x-rapidapi-key': "c3df04dcc0msh2d6e3cc8ccd93dep1c9851jsn230c81227b26"
}
response = requests.request("GET", url, headers=headers, params=querystring)
metacritic = json.loads(response.text)
if metacritic['result'] == 'No result':
print("\nAlguma informação digitada está incorreta. Tente novamente.")
else:
get_and_write(metacritic, console)
except Exception as err:
print("Algum erro desconhecido ocorreu durante a execucação.\nTente novamente.")
cprint(err, 'red')
initial_warnings()
main()
while True:
print('Gostaria de adicionar outro jogo na base RDF: (1 - Sim/0 - Não): ', end='')
try:
ans = int(input())
if ans == 1:
main()
elif ans == 0:
print('Encerrando o script')
break
else:
print('Valor digitado deve ser 0 ou 1.')
except ValueError as e:
print('Valor foi inserido incorretamente. Tente denovo.')
cprint(e, 'red')
|
flexible
|
{
"blob_id": "b290763362af96f5af03fa31f4936339cef66a1d",
"index": 2062,
"step-1": "<mask token>\n\n\ndef console_check(csl, f):\n if csl == 'playstation-4':\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation_4.')\n if csl == 'playstation-3':\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation_3.')\n if csl == 'playstation-2':\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation_2.')\n if csl == 'playstation':\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation.')\n if csl == 'xbox-one':\n f.write('\\tdbo:computingPlatform dbpedia:Xbox_One.')\n if csl == 'xbox-360':\n f.write('\\tdbo:computingPlatform dbpedia:Xbox_360.')\n if csl == 'switch':\n f.write('\\tdbo:computingPlatform dbpedia:Nintendo_Switch.')\n if csl == 'pc':\n f.write('\\tdbo:computingPlatform dbpedia:Computer.')\n f.write('\\n\\n')\n\n\ndef initial_warnings():\n cprint('Esse programa funciona usando uma API chamada Chicken Coop API.',\n 'red', attrs=['bold'])\n cprint('Essa API pega informações sobre jogos de determinados consoles.',\n 'red', attrs=['bold'])\n cprint('Para que ela rode corretamente, siga as seguintes instruções:',\n 'cyan', attrs=['bold'])\n cprint('Consoles:', 'yellow', attrs=['bold'])\n cprint(' Playstation 4 -> playstation-4', 'green', attrs=['bold'])\n cprint(' Xbox One -> xbox-one', 'green', attrs=['bold'])\n cprint(' Computador -> pc', 'green', attrs=['bold'])\n cprint(' Nintendo Switch -> switch', 'green', attrs=['bold'])\n cprint('Exemplos de jogos: ', 'yellow', attrs=['bold'])\n cprint(' Uncharted: The Lost Legacy', 'green', attrs=['bold'])\n cprint(' God of War', 'green', attrs=['bold'])\n cprint(' Ori and The Blind Forest', 'green', attrs=['bold'])\n cprint(\n 'Aviso: Os jogos devem ser escritos com o nome exato e os consoles da maneira demonstrada, caso contrário, não funcionará!'\n , 'magenta', attrs=['bold'])\n print('\\n')\n\n\ndef get_and_write(mc, csl):\n print(f\"Title: {mc['result']['title']}\")\n print(f\"Release Date: {mc['result']['releaseDate']}\")\n print(f\"Score: {mc['result']['score']}\")\n print(f\"Developer: {mc['result']['developer']}\\n\")\n mc_title = mc['result']['title']\n mc_score = mc['result']['score']\n mc_developer = mc['result']['developer']\n rsp = write_file(mc_title, mc_score, mc_developer, mc, csl)\n if rsp:\n write_file(mc_title, mc_score, mc_developer, mc, csl)\n\n\ndef write_file(title, score, developer, mc, csl):\n source = '<https://www.metacritic.com/game/'\n aux_title = ''\n source = source + csl + '/'\n path = Path('gamedeflib_rdf.ttl')\n if path.is_file() and os.stat('gamedeflib_rdf.ttl').st_size > 0:\n file = open('gamedeflib_rdf.ttl', 'r')\n count = 1\n for element in file:\n jogo = f'_:game{count}\\n'\n if element == jogo:\n count = count + 1\n file.close()\n file = open('gamedeflib_rdf.ttl', 'a+')\n file.write(f'\\n_:game{count}\\n')\n file.write(f'\\trdfs:label \"{title}\";\\n')\n file.write(f'\\tdbp:score {score};\\n')\n genre_number(mc, file)\n publisher_number(mc, file)\n file.write(f'\\tdbo:developer \"{developer}\";\\n')\n aux_title = title.lower()\n aux_title = aux_title.replace(':', '')\n aux_title = aux_title.replace(' ', '-')\n source = source + aux_title + '>'\n file.write(f'\\tdc:source {source};\\n')\n console_check(csl, file)\n file.close()\n else:\n file = open('gamedeflib_rdf.ttl', 'w+')\n file.write('@prefix dc: \\t<http://purl.org/dc/elements/1.1/> .\\n')\n file.write(\n '@prefix rdf:\\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\\n')\n file.write('@prefix rdfs:\\t<http://www.w3.org/2000/01/rdf-schema#> .\\n'\n )\n file.write('@prefix foaf:\\t<http://xmlns.com/foaf/0.1/> .\\n')\n file.write('@prefix dbo: <http://dbpedia.org/ontology/> .\\n')\n file.write('@prefix dbpedia: <http://dbpedia.org/page/> .\\n')\n file.write('@prefix dbp: <http://dbpedia.org/property/> .\\n')\n file.write(\n \"\"\"dbpedia:PlayStation_4\n\tfoaf:name \"PlayStation 4\";\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"PlayStation 4\".\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:PlayStation_3\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"PlayStation 3\".\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:PlayStation_2\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"PlayStation 2\".\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:PlayStation\n\tdbp:type dbpedia:Video_game_console;\n\trdfs:label \"PlayStation\".\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:XBox_One\n\tfoaf:name \"XBox One\";\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"XBox One\" .\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:XBox_360\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"XBox 360\" .\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:Nintendo_Switch\n\tfoaf:name \"New Nintendank New Wii U 2.0+\";\n\tdbo:type dbpedia:Video_game_hardware;\n\trdfs:label \"Nintendo Switch\" .\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:Computer\n\tdbp:title \"Computer\";\n\trdf:type dbo:Device;\n\trdfs:label \"Computer\" .\n\n\"\"\"\n )\n return 1\n\n\ndef genre_number(mc, f):\n tam = len(mc['result']['genre'])\n for x in range(0, tam):\n print(f\"Genre number {x + 1}: {mc['result']['genre'][x]}\")\n aux = mc['result']['genre'][x]\n f.write(f'\\tdbo:genre \"{aux}\";\\n')\n\n\ndef publisher_number(mc, f):\n tam = len(mc['result']['publisher'])\n for x in range(0, tam):\n print(f\"Publisher number {x + 1}: {mc['result']['publisher'][x]}\")\n aux = mc['result']['publisher'][x]\n f.write(f'\\tdbo:publisher \"{aux}\";\\n')\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef console_check(csl, f):\n if csl == 'playstation-4':\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation_4.')\n if csl == 'playstation-3':\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation_3.')\n if csl == 'playstation-2':\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation_2.')\n if csl == 'playstation':\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation.')\n if csl == 'xbox-one':\n f.write('\\tdbo:computingPlatform dbpedia:Xbox_One.')\n if csl == 'xbox-360':\n f.write('\\tdbo:computingPlatform dbpedia:Xbox_360.')\n if csl == 'switch':\n f.write('\\tdbo:computingPlatform dbpedia:Nintendo_Switch.')\n if csl == 'pc':\n f.write('\\tdbo:computingPlatform dbpedia:Computer.')\n f.write('\\n\\n')\n\n\ndef initial_warnings():\n cprint('Esse programa funciona usando uma API chamada Chicken Coop API.',\n 'red', attrs=['bold'])\n cprint('Essa API pega informações sobre jogos de determinados consoles.',\n 'red', attrs=['bold'])\n cprint('Para que ela rode corretamente, siga as seguintes instruções:',\n 'cyan', attrs=['bold'])\n cprint('Consoles:', 'yellow', attrs=['bold'])\n cprint(' Playstation 4 -> playstation-4', 'green', attrs=['bold'])\n cprint(' Xbox One -> xbox-one', 'green', attrs=['bold'])\n cprint(' Computador -> pc', 'green', attrs=['bold'])\n cprint(' Nintendo Switch -> switch', 'green', attrs=['bold'])\n cprint('Exemplos de jogos: ', 'yellow', attrs=['bold'])\n cprint(' Uncharted: The Lost Legacy', 'green', attrs=['bold'])\n cprint(' God of War', 'green', attrs=['bold'])\n cprint(' Ori and The Blind Forest', 'green', attrs=['bold'])\n cprint(\n 'Aviso: Os jogos devem ser escritos com o nome exato e os consoles da maneira demonstrada, caso contrário, não funcionará!'\n , 'magenta', attrs=['bold'])\n print('\\n')\n\n\ndef get_and_write(mc, csl):\n print(f\"Title: {mc['result']['title']}\")\n print(f\"Release Date: {mc['result']['releaseDate']}\")\n print(f\"Score: {mc['result']['score']}\")\n print(f\"Developer: {mc['result']['developer']}\\n\")\n mc_title = mc['result']['title']\n mc_score = mc['result']['score']\n mc_developer = mc['result']['developer']\n rsp = write_file(mc_title, mc_score, mc_developer, mc, csl)\n if rsp:\n write_file(mc_title, mc_score, mc_developer, mc, csl)\n\n\ndef write_file(title, score, developer, mc, csl):\n source = '<https://www.metacritic.com/game/'\n aux_title = ''\n source = source + csl + '/'\n path = Path('gamedeflib_rdf.ttl')\n if path.is_file() and os.stat('gamedeflib_rdf.ttl').st_size > 0:\n file = open('gamedeflib_rdf.ttl', 'r')\n count = 1\n for element in file:\n jogo = f'_:game{count}\\n'\n if element == jogo:\n count = count + 1\n file.close()\n file = open('gamedeflib_rdf.ttl', 'a+')\n file.write(f'\\n_:game{count}\\n')\n file.write(f'\\trdfs:label \"{title}\";\\n')\n file.write(f'\\tdbp:score {score};\\n')\n genre_number(mc, file)\n publisher_number(mc, file)\n file.write(f'\\tdbo:developer \"{developer}\";\\n')\n aux_title = title.lower()\n aux_title = aux_title.replace(':', '')\n aux_title = aux_title.replace(' ', '-')\n source = source + aux_title + '>'\n file.write(f'\\tdc:source {source};\\n')\n console_check(csl, file)\n file.close()\n else:\n file = open('gamedeflib_rdf.ttl', 'w+')\n file.write('@prefix dc: \\t<http://purl.org/dc/elements/1.1/> .\\n')\n file.write(\n '@prefix rdf:\\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\\n')\n file.write('@prefix rdfs:\\t<http://www.w3.org/2000/01/rdf-schema#> .\\n'\n )\n file.write('@prefix foaf:\\t<http://xmlns.com/foaf/0.1/> .\\n')\n file.write('@prefix dbo: <http://dbpedia.org/ontology/> .\\n')\n file.write('@prefix dbpedia: <http://dbpedia.org/page/> .\\n')\n file.write('@prefix dbp: <http://dbpedia.org/property/> .\\n')\n file.write(\n \"\"\"dbpedia:PlayStation_4\n\tfoaf:name \"PlayStation 4\";\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"PlayStation 4\".\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:PlayStation_3\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"PlayStation 3\".\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:PlayStation_2\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"PlayStation 2\".\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:PlayStation\n\tdbp:type dbpedia:Video_game_console;\n\trdfs:label \"PlayStation\".\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:XBox_One\n\tfoaf:name \"XBox One\";\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"XBox One\" .\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:XBox_360\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"XBox 360\" .\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:Nintendo_Switch\n\tfoaf:name \"New Nintendank New Wii U 2.0+\";\n\tdbo:type dbpedia:Video_game_hardware;\n\trdfs:label \"Nintendo Switch\" .\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:Computer\n\tdbp:title \"Computer\";\n\trdf:type dbo:Device;\n\trdfs:label \"Computer\" .\n\n\"\"\"\n )\n return 1\n\n\ndef genre_number(mc, f):\n tam = len(mc['result']['genre'])\n for x in range(0, tam):\n print(f\"Genre number {x + 1}: {mc['result']['genre'][x]}\")\n aux = mc['result']['genre'][x]\n f.write(f'\\tdbo:genre \"{aux}\";\\n')\n\n\ndef publisher_number(mc, f):\n tam = len(mc['result']['publisher'])\n for x in range(0, tam):\n print(f\"Publisher number {x + 1}: {mc['result']['publisher'][x]}\")\n aux = mc['result']['publisher'][x]\n f.write(f'\\tdbo:publisher \"{aux}\";\\n')\n\n\ndef main():\n print('Digite o console do jogo desejado: ', end='')\n console = str(input())\n print('Digite o título do jogo desejado: ', end='')\n title = str(input())\n try:\n url = 'https://chicken-coop.p.rapidapi.com/games/' + title\n querystring = {'platform': console}\n headers = {'x-rapidapi-host': 'chicken-coop.p.rapidapi.com',\n 'x-rapidapi-key':\n 'c3df04dcc0msh2d6e3cc8ccd93dep1c9851jsn230c81227b26'}\n response = requests.request('GET', url, headers=headers, params=\n querystring)\n metacritic = json.loads(response.text)\n if metacritic['result'] == 'No result':\n print(\n '\\nAlguma informação digitada está incorreta. Tente novamente.'\n )\n else:\n get_and_write(metacritic, console)\n except Exception as err:\n print(\n 'Algum erro desconhecido ocorreu durante a execucação.\\nTente novamente.'\n )\n cprint(err, 'red')\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef console_check(csl, f):\n if csl == 'playstation-4':\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation_4.')\n if csl == 'playstation-3':\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation_3.')\n if csl == 'playstation-2':\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation_2.')\n if csl == 'playstation':\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation.')\n if csl == 'xbox-one':\n f.write('\\tdbo:computingPlatform dbpedia:Xbox_One.')\n if csl == 'xbox-360':\n f.write('\\tdbo:computingPlatform dbpedia:Xbox_360.')\n if csl == 'switch':\n f.write('\\tdbo:computingPlatform dbpedia:Nintendo_Switch.')\n if csl == 'pc':\n f.write('\\tdbo:computingPlatform dbpedia:Computer.')\n f.write('\\n\\n')\n\n\ndef initial_warnings():\n cprint('Esse programa funciona usando uma API chamada Chicken Coop API.',\n 'red', attrs=['bold'])\n cprint('Essa API pega informações sobre jogos de determinados consoles.',\n 'red', attrs=['bold'])\n cprint('Para que ela rode corretamente, siga as seguintes instruções:',\n 'cyan', attrs=['bold'])\n cprint('Consoles:', 'yellow', attrs=['bold'])\n cprint(' Playstation 4 -> playstation-4', 'green', attrs=['bold'])\n cprint(' Xbox One -> xbox-one', 'green', attrs=['bold'])\n cprint(' Computador -> pc', 'green', attrs=['bold'])\n cprint(' Nintendo Switch -> switch', 'green', attrs=['bold'])\n cprint('Exemplos de jogos: ', 'yellow', attrs=['bold'])\n cprint(' Uncharted: The Lost Legacy', 'green', attrs=['bold'])\n cprint(' God of War', 'green', attrs=['bold'])\n cprint(' Ori and The Blind Forest', 'green', attrs=['bold'])\n cprint(\n 'Aviso: Os jogos devem ser escritos com o nome exato e os consoles da maneira demonstrada, caso contrário, não funcionará!'\n , 'magenta', attrs=['bold'])\n print('\\n')\n\n\ndef get_and_write(mc, csl):\n print(f\"Title: {mc['result']['title']}\")\n print(f\"Release Date: {mc['result']['releaseDate']}\")\n print(f\"Score: {mc['result']['score']}\")\n print(f\"Developer: {mc['result']['developer']}\\n\")\n mc_title = mc['result']['title']\n mc_score = mc['result']['score']\n mc_developer = mc['result']['developer']\n rsp = write_file(mc_title, mc_score, mc_developer, mc, csl)\n if rsp:\n write_file(mc_title, mc_score, mc_developer, mc, csl)\n\n\ndef write_file(title, score, developer, mc, csl):\n source = '<https://www.metacritic.com/game/'\n aux_title = ''\n source = source + csl + '/'\n path = Path('gamedeflib_rdf.ttl')\n if path.is_file() and os.stat('gamedeflib_rdf.ttl').st_size > 0:\n file = open('gamedeflib_rdf.ttl', 'r')\n count = 1\n for element in file:\n jogo = f'_:game{count}\\n'\n if element == jogo:\n count = count + 1\n file.close()\n file = open('gamedeflib_rdf.ttl', 'a+')\n file.write(f'\\n_:game{count}\\n')\n file.write(f'\\trdfs:label \"{title}\";\\n')\n file.write(f'\\tdbp:score {score};\\n')\n genre_number(mc, file)\n publisher_number(mc, file)\n file.write(f'\\tdbo:developer \"{developer}\";\\n')\n aux_title = title.lower()\n aux_title = aux_title.replace(':', '')\n aux_title = aux_title.replace(' ', '-')\n source = source + aux_title + '>'\n file.write(f'\\tdc:source {source};\\n')\n console_check(csl, file)\n file.close()\n else:\n file = open('gamedeflib_rdf.ttl', 'w+')\n file.write('@prefix dc: \\t<http://purl.org/dc/elements/1.1/> .\\n')\n file.write(\n '@prefix rdf:\\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\\n')\n file.write('@prefix rdfs:\\t<http://www.w3.org/2000/01/rdf-schema#> .\\n'\n )\n file.write('@prefix foaf:\\t<http://xmlns.com/foaf/0.1/> .\\n')\n file.write('@prefix dbo: <http://dbpedia.org/ontology/> .\\n')\n file.write('@prefix dbpedia: <http://dbpedia.org/page/> .\\n')\n file.write('@prefix dbp: <http://dbpedia.org/property/> .\\n')\n file.write(\n \"\"\"dbpedia:PlayStation_4\n\tfoaf:name \"PlayStation 4\";\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"PlayStation 4\".\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:PlayStation_3\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"PlayStation 3\".\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:PlayStation_2\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"PlayStation 2\".\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:PlayStation\n\tdbp:type dbpedia:Video_game_console;\n\trdfs:label \"PlayStation\".\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:XBox_One\n\tfoaf:name \"XBox One\";\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"XBox One\" .\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:XBox_360\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"XBox 360\" .\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:Nintendo_Switch\n\tfoaf:name \"New Nintendank New Wii U 2.0+\";\n\tdbo:type dbpedia:Video_game_hardware;\n\trdfs:label \"Nintendo Switch\" .\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:Computer\n\tdbp:title \"Computer\";\n\trdf:type dbo:Device;\n\trdfs:label \"Computer\" .\n\n\"\"\"\n )\n return 1\n\n\ndef genre_number(mc, f):\n tam = len(mc['result']['genre'])\n for x in range(0, tam):\n print(f\"Genre number {x + 1}: {mc['result']['genre'][x]}\")\n aux = mc['result']['genre'][x]\n f.write(f'\\tdbo:genre \"{aux}\";\\n')\n\n\ndef publisher_number(mc, f):\n tam = len(mc['result']['publisher'])\n for x in range(0, tam):\n print(f\"Publisher number {x + 1}: {mc['result']['publisher'][x]}\")\n aux = mc['result']['publisher'][x]\n f.write(f'\\tdbo:publisher \"{aux}\";\\n')\n\n\ndef main():\n print('Digite o console do jogo desejado: ', end='')\n console = str(input())\n print('Digite o título do jogo desejado: ', end='')\n title = str(input())\n try:\n url = 'https://chicken-coop.p.rapidapi.com/games/' + title\n querystring = {'platform': console}\n headers = {'x-rapidapi-host': 'chicken-coop.p.rapidapi.com',\n 'x-rapidapi-key':\n 'c3df04dcc0msh2d6e3cc8ccd93dep1c9851jsn230c81227b26'}\n response = requests.request('GET', url, headers=headers, params=\n querystring)\n metacritic = json.loads(response.text)\n if metacritic['result'] == 'No result':\n print(\n '\\nAlguma informação digitada está incorreta. Tente novamente.'\n )\n else:\n get_and_write(metacritic, console)\n except Exception as err:\n print(\n 'Algum erro desconhecido ocorreu durante a execucação.\\nTente novamente.'\n )\n cprint(err, 'red')\n\n\ninitial_warnings()\nmain()\nwhile True:\n print('Gostaria de adicionar outro jogo na base RDF: (1 - Sim/0 - Não): ',\n end='')\n try:\n ans = int(input())\n if ans == 1:\n main()\n elif ans == 0:\n print('Encerrando o script')\n break\n else:\n print('Valor digitado deve ser 0 ou 1.')\n except ValueError as e:\n print('Valor foi inserido incorretamente. Tente denovo.')\n cprint(e, 'red')\n",
"step-4": "import requests\nimport json\nfrom termcolor import cprint\nfrom pathlib import Path\nimport os\n\n\ndef console_check(csl, f):\n if csl == 'playstation-4':\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation_4.')\n if csl == 'playstation-3':\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation_3.')\n if csl == 'playstation-2':\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation_2.')\n if csl == 'playstation':\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation.')\n if csl == 'xbox-one':\n f.write('\\tdbo:computingPlatform dbpedia:Xbox_One.')\n if csl == 'xbox-360':\n f.write('\\tdbo:computingPlatform dbpedia:Xbox_360.')\n if csl == 'switch':\n f.write('\\tdbo:computingPlatform dbpedia:Nintendo_Switch.')\n if csl == 'pc':\n f.write('\\tdbo:computingPlatform dbpedia:Computer.')\n f.write('\\n\\n')\n\n\ndef initial_warnings():\n cprint('Esse programa funciona usando uma API chamada Chicken Coop API.',\n 'red', attrs=['bold'])\n cprint('Essa API pega informações sobre jogos de determinados consoles.',\n 'red', attrs=['bold'])\n cprint('Para que ela rode corretamente, siga as seguintes instruções:',\n 'cyan', attrs=['bold'])\n cprint('Consoles:', 'yellow', attrs=['bold'])\n cprint(' Playstation 4 -> playstation-4', 'green', attrs=['bold'])\n cprint(' Xbox One -> xbox-one', 'green', attrs=['bold'])\n cprint(' Computador -> pc', 'green', attrs=['bold'])\n cprint(' Nintendo Switch -> switch', 'green', attrs=['bold'])\n cprint('Exemplos de jogos: ', 'yellow', attrs=['bold'])\n cprint(' Uncharted: The Lost Legacy', 'green', attrs=['bold'])\n cprint(' God of War', 'green', attrs=['bold'])\n cprint(' Ori and The Blind Forest', 'green', attrs=['bold'])\n cprint(\n 'Aviso: Os jogos devem ser escritos com o nome exato e os consoles da maneira demonstrada, caso contrário, não funcionará!'\n , 'magenta', attrs=['bold'])\n print('\\n')\n\n\ndef get_and_write(mc, csl):\n print(f\"Title: {mc['result']['title']}\")\n print(f\"Release Date: {mc['result']['releaseDate']}\")\n print(f\"Score: {mc['result']['score']}\")\n print(f\"Developer: {mc['result']['developer']}\\n\")\n mc_title = mc['result']['title']\n mc_score = mc['result']['score']\n mc_developer = mc['result']['developer']\n rsp = write_file(mc_title, mc_score, mc_developer, mc, csl)\n if rsp:\n write_file(mc_title, mc_score, mc_developer, mc, csl)\n\n\ndef write_file(title, score, developer, mc, csl):\n source = '<https://www.metacritic.com/game/'\n aux_title = ''\n source = source + csl + '/'\n path = Path('gamedeflib_rdf.ttl')\n if path.is_file() and os.stat('gamedeflib_rdf.ttl').st_size > 0:\n file = open('gamedeflib_rdf.ttl', 'r')\n count = 1\n for element in file:\n jogo = f'_:game{count}\\n'\n if element == jogo:\n count = count + 1\n file.close()\n file = open('gamedeflib_rdf.ttl', 'a+')\n file.write(f'\\n_:game{count}\\n')\n file.write(f'\\trdfs:label \"{title}\";\\n')\n file.write(f'\\tdbp:score {score};\\n')\n genre_number(mc, file)\n publisher_number(mc, file)\n file.write(f'\\tdbo:developer \"{developer}\";\\n')\n aux_title = title.lower()\n aux_title = aux_title.replace(':', '')\n aux_title = aux_title.replace(' ', '-')\n source = source + aux_title + '>'\n file.write(f'\\tdc:source {source};\\n')\n console_check(csl, file)\n file.close()\n else:\n file = open('gamedeflib_rdf.ttl', 'w+')\n file.write('@prefix dc: \\t<http://purl.org/dc/elements/1.1/> .\\n')\n file.write(\n '@prefix rdf:\\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\\n')\n file.write('@prefix rdfs:\\t<http://www.w3.org/2000/01/rdf-schema#> .\\n'\n )\n file.write('@prefix foaf:\\t<http://xmlns.com/foaf/0.1/> .\\n')\n file.write('@prefix dbo: <http://dbpedia.org/ontology/> .\\n')\n file.write('@prefix dbpedia: <http://dbpedia.org/page/> .\\n')\n file.write('@prefix dbp: <http://dbpedia.org/property/> .\\n')\n file.write(\n \"\"\"dbpedia:PlayStation_4\n\tfoaf:name \"PlayStation 4\";\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"PlayStation 4\".\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:PlayStation_3\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"PlayStation 3\".\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:PlayStation_2\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"PlayStation 2\".\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:PlayStation\n\tdbp:type dbpedia:Video_game_console;\n\trdfs:label \"PlayStation\".\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:XBox_One\n\tfoaf:name \"XBox One\";\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"XBox One\" .\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:XBox_360\n\tdbo:type dbpedia:Home_video_game_console;\n\trdfs:label \"XBox 360\" .\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:Nintendo_Switch\n\tfoaf:name \"New Nintendank New Wii U 2.0+\";\n\tdbo:type dbpedia:Video_game_hardware;\n\trdfs:label \"Nintendo Switch\" .\n\n\"\"\"\n )\n file.write(\n \"\"\"dbpedia:Computer\n\tdbp:title \"Computer\";\n\trdf:type dbo:Device;\n\trdfs:label \"Computer\" .\n\n\"\"\"\n )\n return 1\n\n\ndef genre_number(mc, f):\n tam = len(mc['result']['genre'])\n for x in range(0, tam):\n print(f\"Genre number {x + 1}: {mc['result']['genre'][x]}\")\n aux = mc['result']['genre'][x]\n f.write(f'\\tdbo:genre \"{aux}\";\\n')\n\n\ndef publisher_number(mc, f):\n tam = len(mc['result']['publisher'])\n for x in range(0, tam):\n print(f\"Publisher number {x + 1}: {mc['result']['publisher'][x]}\")\n aux = mc['result']['publisher'][x]\n f.write(f'\\tdbo:publisher \"{aux}\";\\n')\n\n\ndef main():\n print('Digite o console do jogo desejado: ', end='')\n console = str(input())\n print('Digite o título do jogo desejado: ', end='')\n title = str(input())\n try:\n url = 'https://chicken-coop.p.rapidapi.com/games/' + title\n querystring = {'platform': console}\n headers = {'x-rapidapi-host': 'chicken-coop.p.rapidapi.com',\n 'x-rapidapi-key':\n 'c3df04dcc0msh2d6e3cc8ccd93dep1c9851jsn230c81227b26'}\n response = requests.request('GET', url, headers=headers, params=\n querystring)\n metacritic = json.loads(response.text)\n if metacritic['result'] == 'No result':\n print(\n '\\nAlguma informação digitada está incorreta. Tente novamente.'\n )\n else:\n get_and_write(metacritic, console)\n except Exception as err:\n print(\n 'Algum erro desconhecido ocorreu durante a execucação.\\nTente novamente.'\n )\n cprint(err, 'red')\n\n\ninitial_warnings()\nmain()\nwhile True:\n print('Gostaria de adicionar outro jogo na base RDF: (1 - Sim/0 - Não): ',\n end='')\n try:\n ans = int(input())\n if ans == 1:\n main()\n elif ans == 0:\n print('Encerrando o script')\n break\n else:\n print('Valor digitado deve ser 0 ou 1.')\n except ValueError as e:\n print('Valor foi inserido incorretamente. Tente denovo.')\n cprint(e, 'red')\n",
"step-5": "import requests\r\nimport json\r\nfrom termcolor import cprint\r\nfrom pathlib import Path\r\nimport os\r\n\r\n\r\ndef console_check(csl, f):\r\n if csl == 'playstation-4':\r\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation_4.')\r\n if csl == 'playstation-3':\r\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation_3.')\r\n if csl == 'playstation-2':\r\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation_2.')\r\n if csl == 'playstation':\r\n f.write('\\tdbo:computingPlatform dbpedia:PlayStation.')\r\n if csl == 'xbox-one':\r\n f.write('\\tdbo:computingPlatform dbpedia:Xbox_One.')\r\n if csl == 'xbox-360':\r\n f.write('\\tdbo:computingPlatform dbpedia:Xbox_360.')\r\n if csl == 'switch':\r\n f.write('\\tdbo:computingPlatform dbpedia:Nintendo_Switch.')\r\n if csl == 'pc':\r\n f.write('\\tdbo:computingPlatform dbpedia:Computer.')\r\n f.write('\\n\\n')\r\n\r\n\r\ndef initial_warnings():\r\n cprint(\"Esse programa funciona usando uma API chamada Chicken Coop API.\", \"red\", attrs=['bold'])\r\n cprint(\"Essa API pega informações sobre jogos de determinados consoles.\", \"red\", attrs=['bold'])\r\n cprint(\"Para que ela rode corretamente, siga as seguintes instruções:\", \"cyan\", attrs=['bold'])\r\n cprint(\"Consoles:\", 'yellow', attrs=['bold'])\r\n cprint(\" Playstation 4 -> playstation-4\", \"green\", attrs=['bold'])\r\n cprint(\" Xbox One -> xbox-one\", \"green\", attrs=['bold'])\r\n cprint(\" Computador -> pc\", \"green\", attrs=['bold'])\r\n cprint(\" Nintendo Switch -> switch\", \"green\", attrs=['bold'])\r\n cprint(\"Exemplos de jogos: \", 'yellow', attrs=['bold'])\r\n cprint(\" Uncharted: The Lost Legacy\", \"green\", attrs=['bold'])\r\n cprint(\" God of War\", \"green\", attrs=['bold'])\r\n cprint(\" Ori and The Blind Forest\", \"green\", attrs=['bold'])\r\n cprint(\"Aviso: Os jogos devem ser escritos com o nome exato e os consoles da maneira demonstrada,\"\r\n \" caso contrário, não funcionará!\", 'magenta', attrs=['bold'])\r\n print(\"\\n\")\r\n\r\n\r\ndef get_and_write(mc, csl):\r\n print(f\"Title: {mc['result']['title']}\")\r\n print(f\"Release Date: {mc['result']['releaseDate']}\")\r\n # print(f\"Description: {mc['result']['description']}\")\r\n print(f\"Score: {mc['result']['score']}\")\r\n # print(f\"Rating: {mc['result']['rating']}\")\r\n print(f\"Developer: {mc['result']['developer']}\\n\")\r\n mc_title = mc['result']['title']\r\n # mc_description = mc['result']['description']\r\n mc_score = mc['result']['score']\r\n mc_developer = mc['result']['developer']\r\n rsp = write_file(mc_title, mc_score, mc_developer, mc, csl)\r\n if rsp:\r\n write_file(mc_title, mc_score, mc_developer, mc, csl)\r\n\r\n\r\ndef write_file(title, score, developer, mc, csl):\r\n source = \"<https://www.metacritic.com/game/\"\r\n aux_title = ''\r\n source = source + csl + '/'\r\n path = Path('gamedeflib_rdf.ttl')\r\n if path.is_file() and os.stat('gamedeflib_rdf.ttl').st_size > 0:\r\n file = open('gamedeflib_rdf.ttl', 'r')\r\n count = 1\r\n for element in file:\r\n jogo = f'_:game{count}\\n'\r\n if element == jogo:\r\n count = count + 1\r\n file.close()\r\n file = open('gamedeflib_rdf.ttl', 'a+')\r\n file.write(f'\\n_:game{count}\\n')\r\n file.write(f'\\trdfs:label \"{title}\";\\n')\r\n file.write(f'\\tdbp:score {score};\\n')\r\n genre_number(mc, file)\r\n publisher_number(mc, file)\r\n file.write(f'\\tdbo:developer \"{developer}\";\\n')\r\n aux_title = title.lower()\r\n aux_title = aux_title.replace(\":\", \"\")\r\n aux_title = aux_title.replace(\" \", \"-\")\r\n source = source + aux_title + \">\"\r\n file.write(f'\\tdc:source {source};\\n')\r\n console_check(csl, file)\r\n file.close()\r\n else:\r\n file = open('gamedeflib_rdf.ttl', 'w+')\r\n file.write(\"@prefix dc: \t<http://purl.org/dc/elements/1.1/> .\\n\")\r\n file.write(\"@prefix rdf:\t<http://www.w3.org/1999/02/22-rdf-syntax-ns#> .\\n\")\r\n file.write(\"@prefix rdfs:\t<http://www.w3.org/2000/01/rdf-schema#> .\\n\")\r\n file.write(\"@prefix foaf:\t<http://xmlns.com/foaf/0.1/> .\\n\")\r\n file.write(\"@prefix dbo: <http://dbpedia.org/ontology/> .\\n\")\r\n file.write(\"@prefix dbpedia: <http://dbpedia.org/page/> .\\n\")\r\n file.write(\"@prefix dbp: <http://dbpedia.org/property/> .\\n\")\r\n file.write('dbpedia:PlayStation_4\\n'\r\n '\\tfoaf:name \"PlayStation 4\";\\n'\r\n '\\tdbo:type dbpedia:Home_video_game_console;\\n'\r\n '\\trdfs:label \"PlayStation 4\".\\n\\n')\r\n file.write('dbpedia:PlayStation_3\\n'\r\n '\\tdbo:type dbpedia:Home_video_game_console;\\n'\r\n '\\trdfs:label \"PlayStation 3\".\\n\\n')\r\n file.write('dbpedia:PlayStation_2\\n'\r\n '\\tdbo:type dbpedia:Home_video_game_console;\\n'\r\n '\\trdfs:label \"PlayStation 2\".\\n\\n')\r\n file.write('dbpedia:PlayStation\\n'\r\n '\\tdbp:type dbpedia:Video_game_console;\\n'\r\n '\\trdfs:label \"PlayStation\".\\n\\n')\r\n file.write('dbpedia:XBox_One\\n'\r\n '\\tfoaf:name \"XBox One\";\\n'\r\n '\\tdbo:type dbpedia:Home_video_game_console;\\n'\r\n '\\trdfs:label \"XBox One\" .\\n\\n')\r\n file.write('dbpedia:XBox_360\\n'\r\n '\\tdbo:type dbpedia:Home_video_game_console;\\n'\r\n '\\trdfs:label \"XBox 360\" .\\n\\n')\r\n file.write('dbpedia:Nintendo_Switch\\n'\r\n '\\tfoaf:name \"New Nintendank New Wii U 2.0+\";\\n'\r\n '\\tdbo:type dbpedia:Video_game_hardware;\\n'\r\n '\\trdfs:label \"Nintendo Switch\" .\\n\\n')\r\n file.write('dbpedia:Computer\\n'\r\n '\\tdbp:title \"Computer\";\\n'\r\n '\\trdf:type dbo:Device;\\n'\r\n '\\trdfs:label \"Computer\" .\\n\\n')\r\n return 1\r\n\r\n\r\ndef genre_number(mc, f):\r\n tam = len(mc['result']['genre'])\r\n for x in range(0, tam):\r\n print(f\"Genre number {x+1}: {mc['result']['genre'][x]}\")\r\n aux = mc['result']['genre'][x]\r\n f.write(f'\\tdbo:genre \"{aux}\";\\n')\r\n\r\n\r\ndef publisher_number(mc, f):\r\n tam = len(mc['result']['publisher'])\r\n for x in range(0, tam):\r\n print(f\"Publisher number {x + 1}: {mc['result']['publisher'][x]}\")\r\n aux = mc['result']['publisher'][x]\r\n f.write(f'\\tdbo:publisher \"{aux}\";\\n')\r\n\r\n\r\ndef main():\r\n print('Digite o console do jogo desejado: ', end='')\r\n console = str(input())\r\n print('Digite o título do jogo desejado: ', end='')\r\n title = str(input())\r\n try:\r\n url = \"https://chicken-coop.p.rapidapi.com/games/\"+title\r\n\r\n querystring = {\"platform\": console}\r\n\r\n headers = {\r\n 'x-rapidapi-host': \"chicken-coop.p.rapidapi.com\",\r\n 'x-rapidapi-key': \"c3df04dcc0msh2d6e3cc8ccd93dep1c9851jsn230c81227b26\"\r\n }\r\n\r\n response = requests.request(\"GET\", url, headers=headers, params=querystring)\r\n\r\n metacritic = json.loads(response.text)\r\n\r\n if metacritic['result'] == 'No result':\r\n print(\"\\nAlguma informação digitada está incorreta. Tente novamente.\")\r\n else:\r\n get_and_write(metacritic, console)\r\n\r\n except Exception as err:\r\n print(\"Algum erro desconhecido ocorreu durante a execucação.\\nTente novamente.\")\r\n cprint(err, 'red')\r\n\r\n\r\ninitial_warnings()\r\nmain()\r\nwhile True:\r\n print('Gostaria de adicionar outro jogo na base RDF: (1 - Sim/0 - Não): ', end='')\r\n try:\r\n ans = int(input())\r\n if ans == 1:\r\n main()\r\n elif ans == 0:\r\n print('Encerrando o script')\r\n break\r\n else:\r\n print('Valor digitado deve ser 0 ou 1.')\r\n except ValueError as e:\r\n print('Valor foi inserido incorretamente. Tente denovo.')\r\n cprint(e, 'red')\r\n",
"step-ids": [
6,
7,
8,
9,
10
]
}
|
[
6,
7,
8,
9,
10
] |
# encoding: utf-8
'''
Created on Nov 26, 2015
@author: tal
Based in part on:
Learn math - https://github.com/fchollet/keras/blob/master/examples/addition_rnn.py
See https://medium.com/@majortal/deep-spelling-9ffef96a24f6#.2c9pu8nlm
"""
Modified by Pavel Surmenok
'''
import argparse
import numpy as np
from keras.layers import Activation, TimeDistributed, Dense, RepeatVector, Dropout
from keras.layers import recurrent
from keras.models import Sequential
from keras.callbacks import ModelCheckpoint, TensorBoard, CSVLogger, LambdaCallback
from numpy.random import seed as random_seed
from numpy.random import randint as random_randint
import os
import pickle
from data import DataSet
random_seed(123) # Reproducibility
# Parameters for the model and dataset
DATASET_FILENAME = 'data/dataset/news.2011.en.shuffled'
NUMBER_OF_EPOCHS = 100000
RNN = recurrent.LSTM
INPUT_LAYERS = 2
OUTPUT_LAYERS = 2
AMOUNT_OF_DROPOUT = 0.3
BATCH_SIZE = 32
SAMPLES_PER_EPOCH = 65536
HIDDEN_SIZE = 700
INITIALIZATION = "he_normal" # : Gaussian initialization scaled by fan_in (He et al., 2014)
NUMBER_OF_CHARS = 100 # 75
CHARS = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ .")
INVERTED = True
MODEL_CHECKPOINT_DIRECTORYNAME = 'models'
MODEL_CHECKPOINT_FILENAME = 'weights.{epoch:02d}-{val_loss:.2f}.hdf5'
MODEL_DATASET_PARAMS_FILENAME = 'dataset_params.pickle'
MODEL_STARTING_CHECKPOINT_FILENAME = 'weights.hdf5'
CSV_LOG_FILENAME = 'log.csv'
def generate_model(output_len, chars=None):
"""Generate the model"""
print('Build model...')
chars = chars or CHARS
model = Sequential()
# "Encode" the input sequence using an RNN, producing an output of HIDDEN_SIZE
# note: in a situation where your input sequences have a variable length,
# use input_shape=(None, nb_feature).
for layer_number in range(INPUT_LAYERS):
model.add(recurrent.LSTM(HIDDEN_SIZE, input_shape=(None, len(chars)), init=INITIALIZATION,
return_sequences=layer_number + 1 < INPUT_LAYERS))
model.add(Dropout(AMOUNT_OF_DROPOUT))
# For the decoder's input, we repeat the encoded input for each time step
model.add(RepeatVector(output_len))
# The decoder RNN could be multiple layers stacked or a single layer
for _ in range(OUTPUT_LAYERS):
model.add(recurrent.LSTM(HIDDEN_SIZE, return_sequences=True, init=INITIALIZATION))
model.add(Dropout(AMOUNT_OF_DROPOUT))
# For each of step of the output sequence, decide which character should be chosen
model.add(TimeDistributed(Dense(len(chars), init=INITIALIZATION)))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
class Colors(object):
"""For nicer printouts"""
ok = '\033[92m'
fail = '\033[91m'
close = '\033[0m'
def show_samples(model, dataset, epoch, logs, X_dev_batch, y_dev_batch):
"""Selects 10 samples from the dev set at random so we can visualize errors"""
for _ in range(10):
ind = random_randint(0, len(X_dev_batch))
row_X, row_y = X_dev_batch[np.array([ind])], y_dev_batch[np.array([ind])]
preds = model.predict_classes(row_X, verbose=0)
q = dataset.character_table.decode(row_X[0])
correct = dataset.character_table.decode(row_y[0])
guess = dataset.character_table.decode(preds[0], calc_argmax=False)
if INVERTED:
print('Q', q[::-1]) # inverted back!
else:
print('Q', q)
print('A', correct)
print(Colors.ok + '☑' + Colors.close if correct == guess else Colors.fail + '☒' + Colors.close, guess)
print('---')
def iterate_training(model, dataset, initial_epoch):
"""Iterative Training"""
checkpoint = ModelCheckpoint(MODEL_CHECKPOINT_DIRECTORYNAME + '/' + MODEL_CHECKPOINT_FILENAME,
save_best_only=True)
tensorboard = TensorBoard()
csv_logger = CSVLogger(CSV_LOG_FILENAME)
X_dev_batch, y_dev_batch = next(dataset.dev_set_batch_generator(1000))
show_samples_callback = LambdaCallback(
on_epoch_end=lambda epoch, logs: show_samples(model, dataset, epoch, logs, X_dev_batch, y_dev_batch))
train_batch_generator = dataset.train_set_batch_generator(BATCH_SIZE)
validation_batch_generator = dataset.dev_set_batch_generator(BATCH_SIZE)
model.fit_generator(train_batch_generator,
samples_per_epoch=SAMPLES_PER_EPOCH,
nb_epoch=NUMBER_OF_EPOCHS,
validation_data=validation_batch_generator,
nb_val_samples=SAMPLES_PER_EPOCH,
callbacks=[checkpoint, tensorboard, csv_logger, show_samples_callback],
verbose=1,
initial_epoch=initial_epoch)
def save_dataset_params(dataset):
params = { 'chars': dataset.chars, 'y_max_length': dataset.y_max_length }
with open(MODEL_CHECKPOINT_DIRECTORYNAME + '/' + MODEL_DATASET_PARAMS_FILENAME, 'wb') as f:
pickle.dump(params, f)
def main_news(checkpoint_filename=None, dataset_params_filename=None, initial_epoch=1):
"""Main"""
dataset = DataSet(DATASET_FILENAME)
if not os.path.exists(MODEL_CHECKPOINT_DIRECTORYNAME):
os.makedirs(MODEL_CHECKPOINT_DIRECTORYNAME)
if dataset_params_filename is not None:
with open(dataset_params_filename, 'rb') as f:
dataset_params = pickle.load(f)
assert dataset_params['chars'] == dataset.chars
assert dataset_params['y_max_length'] == dataset.y_max_length
else:
save_dataset_params(dataset)
model = generate_model(dataset.y_max_length, dataset.chars)
if checkpoint_filename is not None:
model.load_weights(checkpoint_filename)
iterate_training(model, dataset, initial_epoch)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Trains a deep spelling model.')
parser.add_argument('--checkpoint', type=str,
help='Filename of a model checkpoint to start the training from.')
parser.add_argument('--datasetparams', type=str,
help='Filename of a file with dataset params to load for continuing model training.')
parser.add_argument('--initialepoch', type=int,
help='Initial epoch parameter for continuing model training.', default=0)
args = parser.parse_args()
main_news(args.checkpoint, args.datasetparams, args.initialepoch)
|
normal
|
{
"blob_id": "572a098053ebae4f42cd020d1003cc18eceb6af0",
"index": 4984,
"step-1": "<mask token>\n\n\ndef generate_model(output_len, chars=None):\n \"\"\"Generate the model\"\"\"\n print('Build model...')\n chars = chars or CHARS\n model = Sequential()\n for layer_number in range(INPUT_LAYERS):\n model.add(recurrent.LSTM(HIDDEN_SIZE, input_shape=(None, len(chars)\n ), init=INITIALIZATION, return_sequences=layer_number + 1 <\n INPUT_LAYERS))\n model.add(Dropout(AMOUNT_OF_DROPOUT))\n model.add(RepeatVector(output_len))\n for _ in range(OUTPUT_LAYERS):\n model.add(recurrent.LSTM(HIDDEN_SIZE, return_sequences=True, init=\n INITIALIZATION))\n model.add(Dropout(AMOUNT_OF_DROPOUT))\n model.add(TimeDistributed(Dense(len(chars), init=INITIALIZATION)))\n model.add(Activation('softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='adam',\n metrics=['accuracy'])\n return model\n\n\nclass Colors(object):\n \"\"\"For nicer printouts\"\"\"\n ok = '\\x1b[92m'\n fail = '\\x1b[91m'\n close = '\\x1b[0m'\n\n\ndef show_samples(model, dataset, epoch, logs, X_dev_batch, y_dev_batch):\n \"\"\"Selects 10 samples from the dev set at random so we can visualize errors\"\"\"\n for _ in range(10):\n ind = random_randint(0, len(X_dev_batch))\n row_X, row_y = X_dev_batch[np.array([ind])], y_dev_batch[np.array([\n ind])]\n preds = model.predict_classes(row_X, verbose=0)\n q = dataset.character_table.decode(row_X[0])\n correct = dataset.character_table.decode(row_y[0])\n guess = dataset.character_table.decode(preds[0], calc_argmax=False)\n if INVERTED:\n print('Q', q[::-1])\n else:\n print('Q', q)\n print('A', correct)\n print(Colors.ok + '☑' + Colors.close if correct == guess else \n Colors.fail + '☒' + Colors.close, guess)\n print('---')\n\n\ndef iterate_training(model, dataset, initial_epoch):\n \"\"\"Iterative Training\"\"\"\n checkpoint = ModelCheckpoint(MODEL_CHECKPOINT_DIRECTORYNAME + '/' +\n MODEL_CHECKPOINT_FILENAME, save_best_only=True)\n tensorboard = TensorBoard()\n csv_logger = CSVLogger(CSV_LOG_FILENAME)\n X_dev_batch, y_dev_batch = next(dataset.dev_set_batch_generator(1000))\n show_samples_callback = LambdaCallback(on_epoch_end=lambda epoch, logs:\n show_samples(model, dataset, epoch, logs, X_dev_batch, y_dev_batch))\n train_batch_generator = dataset.train_set_batch_generator(BATCH_SIZE)\n validation_batch_generator = dataset.dev_set_batch_generator(BATCH_SIZE)\n model.fit_generator(train_batch_generator, samples_per_epoch=\n SAMPLES_PER_EPOCH, nb_epoch=NUMBER_OF_EPOCHS, validation_data=\n validation_batch_generator, nb_val_samples=SAMPLES_PER_EPOCH,\n callbacks=[checkpoint, tensorboard, csv_logger,\n show_samples_callback], verbose=1, initial_epoch=initial_epoch)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef generate_model(output_len, chars=None):\n \"\"\"Generate the model\"\"\"\n print('Build model...')\n chars = chars or CHARS\n model = Sequential()\n for layer_number in range(INPUT_LAYERS):\n model.add(recurrent.LSTM(HIDDEN_SIZE, input_shape=(None, len(chars)\n ), init=INITIALIZATION, return_sequences=layer_number + 1 <\n INPUT_LAYERS))\n model.add(Dropout(AMOUNT_OF_DROPOUT))\n model.add(RepeatVector(output_len))\n for _ in range(OUTPUT_LAYERS):\n model.add(recurrent.LSTM(HIDDEN_SIZE, return_sequences=True, init=\n INITIALIZATION))\n model.add(Dropout(AMOUNT_OF_DROPOUT))\n model.add(TimeDistributed(Dense(len(chars), init=INITIALIZATION)))\n model.add(Activation('softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='adam',\n metrics=['accuracy'])\n return model\n\n\nclass Colors(object):\n \"\"\"For nicer printouts\"\"\"\n ok = '\\x1b[92m'\n fail = '\\x1b[91m'\n close = '\\x1b[0m'\n\n\ndef show_samples(model, dataset, epoch, logs, X_dev_batch, y_dev_batch):\n \"\"\"Selects 10 samples from the dev set at random so we can visualize errors\"\"\"\n for _ in range(10):\n ind = random_randint(0, len(X_dev_batch))\n row_X, row_y = X_dev_batch[np.array([ind])], y_dev_batch[np.array([\n ind])]\n preds = model.predict_classes(row_X, verbose=0)\n q = dataset.character_table.decode(row_X[0])\n correct = dataset.character_table.decode(row_y[0])\n guess = dataset.character_table.decode(preds[0], calc_argmax=False)\n if INVERTED:\n print('Q', q[::-1])\n else:\n print('Q', q)\n print('A', correct)\n print(Colors.ok + '☑' + Colors.close if correct == guess else \n Colors.fail + '☒' + Colors.close, guess)\n print('---')\n\n\ndef iterate_training(model, dataset, initial_epoch):\n \"\"\"Iterative Training\"\"\"\n checkpoint = ModelCheckpoint(MODEL_CHECKPOINT_DIRECTORYNAME + '/' +\n MODEL_CHECKPOINT_FILENAME, save_best_only=True)\n tensorboard = TensorBoard()\n csv_logger = CSVLogger(CSV_LOG_FILENAME)\n X_dev_batch, y_dev_batch = next(dataset.dev_set_batch_generator(1000))\n show_samples_callback = LambdaCallback(on_epoch_end=lambda epoch, logs:\n show_samples(model, dataset, epoch, logs, X_dev_batch, y_dev_batch))\n train_batch_generator = dataset.train_set_batch_generator(BATCH_SIZE)\n validation_batch_generator = dataset.dev_set_batch_generator(BATCH_SIZE)\n model.fit_generator(train_batch_generator, samples_per_epoch=\n SAMPLES_PER_EPOCH, nb_epoch=NUMBER_OF_EPOCHS, validation_data=\n validation_batch_generator, nb_val_samples=SAMPLES_PER_EPOCH,\n callbacks=[checkpoint, tensorboard, csv_logger,\n show_samples_callback], verbose=1, initial_epoch=initial_epoch)\n\n\ndef save_dataset_params(dataset):\n params = {'chars': dataset.chars, 'y_max_length': dataset.y_max_length}\n with open(MODEL_CHECKPOINT_DIRECTORYNAME + '/' +\n MODEL_DATASET_PARAMS_FILENAME, 'wb') as f:\n pickle.dump(params, f)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef generate_model(output_len, chars=None):\n \"\"\"Generate the model\"\"\"\n print('Build model...')\n chars = chars or CHARS\n model = Sequential()\n for layer_number in range(INPUT_LAYERS):\n model.add(recurrent.LSTM(HIDDEN_SIZE, input_shape=(None, len(chars)\n ), init=INITIALIZATION, return_sequences=layer_number + 1 <\n INPUT_LAYERS))\n model.add(Dropout(AMOUNT_OF_DROPOUT))\n model.add(RepeatVector(output_len))\n for _ in range(OUTPUT_LAYERS):\n model.add(recurrent.LSTM(HIDDEN_SIZE, return_sequences=True, init=\n INITIALIZATION))\n model.add(Dropout(AMOUNT_OF_DROPOUT))\n model.add(TimeDistributed(Dense(len(chars), init=INITIALIZATION)))\n model.add(Activation('softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='adam',\n metrics=['accuracy'])\n return model\n\n\nclass Colors(object):\n \"\"\"For nicer printouts\"\"\"\n ok = '\\x1b[92m'\n fail = '\\x1b[91m'\n close = '\\x1b[0m'\n\n\ndef show_samples(model, dataset, epoch, logs, X_dev_batch, y_dev_batch):\n \"\"\"Selects 10 samples from the dev set at random so we can visualize errors\"\"\"\n for _ in range(10):\n ind = random_randint(0, len(X_dev_batch))\n row_X, row_y = X_dev_batch[np.array([ind])], y_dev_batch[np.array([\n ind])]\n preds = model.predict_classes(row_X, verbose=0)\n q = dataset.character_table.decode(row_X[0])\n correct = dataset.character_table.decode(row_y[0])\n guess = dataset.character_table.decode(preds[0], calc_argmax=False)\n if INVERTED:\n print('Q', q[::-1])\n else:\n print('Q', q)\n print('A', correct)\n print(Colors.ok + '☑' + Colors.close if correct == guess else \n Colors.fail + '☒' + Colors.close, guess)\n print('---')\n\n\ndef iterate_training(model, dataset, initial_epoch):\n \"\"\"Iterative Training\"\"\"\n checkpoint = ModelCheckpoint(MODEL_CHECKPOINT_DIRECTORYNAME + '/' +\n MODEL_CHECKPOINT_FILENAME, save_best_only=True)\n tensorboard = TensorBoard()\n csv_logger = CSVLogger(CSV_LOG_FILENAME)\n X_dev_batch, y_dev_batch = next(dataset.dev_set_batch_generator(1000))\n show_samples_callback = LambdaCallback(on_epoch_end=lambda epoch, logs:\n show_samples(model, dataset, epoch, logs, X_dev_batch, y_dev_batch))\n train_batch_generator = dataset.train_set_batch_generator(BATCH_SIZE)\n validation_batch_generator = dataset.dev_set_batch_generator(BATCH_SIZE)\n model.fit_generator(train_batch_generator, samples_per_epoch=\n SAMPLES_PER_EPOCH, nb_epoch=NUMBER_OF_EPOCHS, validation_data=\n validation_batch_generator, nb_val_samples=SAMPLES_PER_EPOCH,\n callbacks=[checkpoint, tensorboard, csv_logger,\n show_samples_callback], verbose=1, initial_epoch=initial_epoch)\n\n\ndef save_dataset_params(dataset):\n params = {'chars': dataset.chars, 'y_max_length': dataset.y_max_length}\n with open(MODEL_CHECKPOINT_DIRECTORYNAME + '/' +\n MODEL_DATASET_PARAMS_FILENAME, 'wb') as f:\n pickle.dump(params, f)\n\n\ndef main_news(checkpoint_filename=None, dataset_params_filename=None,\n initial_epoch=1):\n \"\"\"Main\"\"\"\n dataset = DataSet(DATASET_FILENAME)\n if not os.path.exists(MODEL_CHECKPOINT_DIRECTORYNAME):\n os.makedirs(MODEL_CHECKPOINT_DIRECTORYNAME)\n if dataset_params_filename is not None:\n with open(dataset_params_filename, 'rb') as f:\n dataset_params = pickle.load(f)\n assert dataset_params['chars'] == dataset.chars\n assert dataset_params['y_max_length'] == dataset.y_max_length\n else:\n save_dataset_params(dataset)\n model = generate_model(dataset.y_max_length, dataset.chars)\n if checkpoint_filename is not None:\n model.load_weights(checkpoint_filename)\n iterate_training(model, dataset, initial_epoch)\n\n\n<mask token>\n",
"step-4": "<mask token>\nrandom_seed(123)\nDATASET_FILENAME = 'data/dataset/news.2011.en.shuffled'\nNUMBER_OF_EPOCHS = 100000\nRNN = recurrent.LSTM\nINPUT_LAYERS = 2\nOUTPUT_LAYERS = 2\nAMOUNT_OF_DROPOUT = 0.3\nBATCH_SIZE = 32\nSAMPLES_PER_EPOCH = 65536\nHIDDEN_SIZE = 700\nINITIALIZATION = 'he_normal'\nNUMBER_OF_CHARS = 100\nCHARS = list('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ .')\nINVERTED = True\nMODEL_CHECKPOINT_DIRECTORYNAME = 'models'\nMODEL_CHECKPOINT_FILENAME = 'weights.{epoch:02d}-{val_loss:.2f}.hdf5'\nMODEL_DATASET_PARAMS_FILENAME = 'dataset_params.pickle'\nMODEL_STARTING_CHECKPOINT_FILENAME = 'weights.hdf5'\nCSV_LOG_FILENAME = 'log.csv'\n\n\ndef generate_model(output_len, chars=None):\n \"\"\"Generate the model\"\"\"\n print('Build model...')\n chars = chars or CHARS\n model = Sequential()\n for layer_number in range(INPUT_LAYERS):\n model.add(recurrent.LSTM(HIDDEN_SIZE, input_shape=(None, len(chars)\n ), init=INITIALIZATION, return_sequences=layer_number + 1 <\n INPUT_LAYERS))\n model.add(Dropout(AMOUNT_OF_DROPOUT))\n model.add(RepeatVector(output_len))\n for _ in range(OUTPUT_LAYERS):\n model.add(recurrent.LSTM(HIDDEN_SIZE, return_sequences=True, init=\n INITIALIZATION))\n model.add(Dropout(AMOUNT_OF_DROPOUT))\n model.add(TimeDistributed(Dense(len(chars), init=INITIALIZATION)))\n model.add(Activation('softmax'))\n model.compile(loss='categorical_crossentropy', optimizer='adam',\n metrics=['accuracy'])\n return model\n\n\nclass Colors(object):\n \"\"\"For nicer printouts\"\"\"\n ok = '\\x1b[92m'\n fail = '\\x1b[91m'\n close = '\\x1b[0m'\n\n\ndef show_samples(model, dataset, epoch, logs, X_dev_batch, y_dev_batch):\n \"\"\"Selects 10 samples from the dev set at random so we can visualize errors\"\"\"\n for _ in range(10):\n ind = random_randint(0, len(X_dev_batch))\n row_X, row_y = X_dev_batch[np.array([ind])], y_dev_batch[np.array([\n ind])]\n preds = model.predict_classes(row_X, verbose=0)\n q = dataset.character_table.decode(row_X[0])\n correct = dataset.character_table.decode(row_y[0])\n guess = dataset.character_table.decode(preds[0], calc_argmax=False)\n if INVERTED:\n print('Q', q[::-1])\n else:\n print('Q', q)\n print('A', correct)\n print(Colors.ok + '☑' + Colors.close if correct == guess else \n Colors.fail + '☒' + Colors.close, guess)\n print('---')\n\n\ndef iterate_training(model, dataset, initial_epoch):\n \"\"\"Iterative Training\"\"\"\n checkpoint = ModelCheckpoint(MODEL_CHECKPOINT_DIRECTORYNAME + '/' +\n MODEL_CHECKPOINT_FILENAME, save_best_only=True)\n tensorboard = TensorBoard()\n csv_logger = CSVLogger(CSV_LOG_FILENAME)\n X_dev_batch, y_dev_batch = next(dataset.dev_set_batch_generator(1000))\n show_samples_callback = LambdaCallback(on_epoch_end=lambda epoch, logs:\n show_samples(model, dataset, epoch, logs, X_dev_batch, y_dev_batch))\n train_batch_generator = dataset.train_set_batch_generator(BATCH_SIZE)\n validation_batch_generator = dataset.dev_set_batch_generator(BATCH_SIZE)\n model.fit_generator(train_batch_generator, samples_per_epoch=\n SAMPLES_PER_EPOCH, nb_epoch=NUMBER_OF_EPOCHS, validation_data=\n validation_batch_generator, nb_val_samples=SAMPLES_PER_EPOCH,\n callbacks=[checkpoint, tensorboard, csv_logger,\n show_samples_callback], verbose=1, initial_epoch=initial_epoch)\n\n\ndef save_dataset_params(dataset):\n params = {'chars': dataset.chars, 'y_max_length': dataset.y_max_length}\n with open(MODEL_CHECKPOINT_DIRECTORYNAME + '/' +\n MODEL_DATASET_PARAMS_FILENAME, 'wb') as f:\n pickle.dump(params, f)\n\n\ndef main_news(checkpoint_filename=None, dataset_params_filename=None,\n initial_epoch=1):\n \"\"\"Main\"\"\"\n dataset = DataSet(DATASET_FILENAME)\n if not os.path.exists(MODEL_CHECKPOINT_DIRECTORYNAME):\n os.makedirs(MODEL_CHECKPOINT_DIRECTORYNAME)\n if dataset_params_filename is not None:\n with open(dataset_params_filename, 'rb') as f:\n dataset_params = pickle.load(f)\n assert dataset_params['chars'] == dataset.chars\n assert dataset_params['y_max_length'] == dataset.y_max_length\n else:\n save_dataset_params(dataset)\n model = generate_model(dataset.y_max_length, dataset.chars)\n if checkpoint_filename is not None:\n model.load_weights(checkpoint_filename)\n iterate_training(model, dataset, initial_epoch)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\n 'Trains a deep spelling model.')\n parser.add_argument('--checkpoint', type=str, help=\n 'Filename of a model checkpoint to start the training from.')\n parser.add_argument('--datasetparams', type=str, help=\n 'Filename of a file with dataset params to load for continuing model training.'\n )\n parser.add_argument('--initialepoch', type=int, help=\n 'Initial epoch parameter for continuing model training.', default=0)\n args = parser.parse_args()\n main_news(args.checkpoint, args.datasetparams, args.initialepoch)\n",
"step-5": "# encoding: utf-8\n'''\nCreated on Nov 26, 2015\n\n@author: tal\n\nBased in part on:\nLearn math - https://github.com/fchollet/keras/blob/master/examples/addition_rnn.py\n\nSee https://medium.com/@majortal/deep-spelling-9ffef96a24f6#.2c9pu8nlm\n\"\"\"\n\nModified by Pavel Surmenok\n\n'''\n\nimport argparse\nimport numpy as np\nfrom keras.layers import Activation, TimeDistributed, Dense, RepeatVector, Dropout\nfrom keras.layers import recurrent\nfrom keras.models import Sequential\nfrom keras.callbacks import ModelCheckpoint, TensorBoard, CSVLogger, LambdaCallback\nfrom numpy.random import seed as random_seed\nfrom numpy.random import randint as random_randint\nimport os\nimport pickle\n\nfrom data import DataSet\n\nrandom_seed(123) # Reproducibility\n\n# Parameters for the model and dataset\nDATASET_FILENAME = 'data/dataset/news.2011.en.shuffled'\nNUMBER_OF_EPOCHS = 100000\nRNN = recurrent.LSTM\nINPUT_LAYERS = 2\nOUTPUT_LAYERS = 2\nAMOUNT_OF_DROPOUT = 0.3\nBATCH_SIZE = 32\nSAMPLES_PER_EPOCH = 65536\nHIDDEN_SIZE = 700\nINITIALIZATION = \"he_normal\" # : Gaussian initialization scaled by fan_in (He et al., 2014)\nNUMBER_OF_CHARS = 100 # 75\nCHARS = list(\"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ .\")\nINVERTED = True\nMODEL_CHECKPOINT_DIRECTORYNAME = 'models'\nMODEL_CHECKPOINT_FILENAME = 'weights.{epoch:02d}-{val_loss:.2f}.hdf5'\nMODEL_DATASET_PARAMS_FILENAME = 'dataset_params.pickle'\nMODEL_STARTING_CHECKPOINT_FILENAME = 'weights.hdf5'\nCSV_LOG_FILENAME = 'log.csv'\n\n\ndef generate_model(output_len, chars=None):\n \"\"\"Generate the model\"\"\"\n print('Build model...')\n chars = chars or CHARS\n model = Sequential()\n # \"Encode\" the input sequence using an RNN, producing an output of HIDDEN_SIZE\n # note: in a situation where your input sequences have a variable length,\n # use input_shape=(None, nb_feature).\n for layer_number in range(INPUT_LAYERS):\n model.add(recurrent.LSTM(HIDDEN_SIZE, input_shape=(None, len(chars)), init=INITIALIZATION,\n return_sequences=layer_number + 1 < INPUT_LAYERS))\n model.add(Dropout(AMOUNT_OF_DROPOUT))\n # For the decoder's input, we repeat the encoded input for each time step\n model.add(RepeatVector(output_len))\n # The decoder RNN could be multiple layers stacked or a single layer\n for _ in range(OUTPUT_LAYERS):\n model.add(recurrent.LSTM(HIDDEN_SIZE, return_sequences=True, init=INITIALIZATION))\n model.add(Dropout(AMOUNT_OF_DROPOUT))\n\n # For each of step of the output sequence, decide which character should be chosen\n model.add(TimeDistributed(Dense(len(chars), init=INITIALIZATION)))\n model.add(Activation('softmax'))\n\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n return model\n\n\nclass Colors(object):\n \"\"\"For nicer printouts\"\"\"\n ok = '\\033[92m'\n fail = '\\033[91m'\n close = '\\033[0m'\n\n\ndef show_samples(model, dataset, epoch, logs, X_dev_batch, y_dev_batch):\n \"\"\"Selects 10 samples from the dev set at random so we can visualize errors\"\"\"\n\n for _ in range(10):\n ind = random_randint(0, len(X_dev_batch))\n row_X, row_y = X_dev_batch[np.array([ind])], y_dev_batch[np.array([ind])]\n preds = model.predict_classes(row_X, verbose=0)\n q = dataset.character_table.decode(row_X[0])\n correct = dataset.character_table.decode(row_y[0])\n guess = dataset.character_table.decode(preds[0], calc_argmax=False)\n\n if INVERTED:\n print('Q', q[::-1]) # inverted back!\n else:\n print('Q', q)\n\n print('A', correct)\n print(Colors.ok + '☑' + Colors.close if correct == guess else Colors.fail + '☒' + Colors.close, guess)\n print('---')\n\n\n\ndef iterate_training(model, dataset, initial_epoch):\n \"\"\"Iterative Training\"\"\"\n\n checkpoint = ModelCheckpoint(MODEL_CHECKPOINT_DIRECTORYNAME + '/' + MODEL_CHECKPOINT_FILENAME,\n save_best_only=True)\n tensorboard = TensorBoard()\n csv_logger = CSVLogger(CSV_LOG_FILENAME)\n\n X_dev_batch, y_dev_batch = next(dataset.dev_set_batch_generator(1000))\n show_samples_callback = LambdaCallback(\n on_epoch_end=lambda epoch, logs: show_samples(model, dataset, epoch, logs, X_dev_batch, y_dev_batch))\n\n train_batch_generator = dataset.train_set_batch_generator(BATCH_SIZE)\n validation_batch_generator = dataset.dev_set_batch_generator(BATCH_SIZE)\n\n model.fit_generator(train_batch_generator,\n samples_per_epoch=SAMPLES_PER_EPOCH,\n nb_epoch=NUMBER_OF_EPOCHS,\n validation_data=validation_batch_generator,\n nb_val_samples=SAMPLES_PER_EPOCH,\n callbacks=[checkpoint, tensorboard, csv_logger, show_samples_callback],\n verbose=1,\n initial_epoch=initial_epoch)\n\n\ndef save_dataset_params(dataset):\n params = { 'chars': dataset.chars, 'y_max_length': dataset.y_max_length }\n with open(MODEL_CHECKPOINT_DIRECTORYNAME + '/' + MODEL_DATASET_PARAMS_FILENAME, 'wb') as f:\n pickle.dump(params, f)\n\n\ndef main_news(checkpoint_filename=None, dataset_params_filename=None, initial_epoch=1):\n \"\"\"Main\"\"\"\n dataset = DataSet(DATASET_FILENAME)\n\n if not os.path.exists(MODEL_CHECKPOINT_DIRECTORYNAME):\n os.makedirs(MODEL_CHECKPOINT_DIRECTORYNAME)\n\n if dataset_params_filename is not None:\n with open(dataset_params_filename, 'rb') as f:\n dataset_params = pickle.load(f)\n\n assert dataset_params['chars'] == dataset.chars\n assert dataset_params['y_max_length'] == dataset.y_max_length\n\n else:\n save_dataset_params(dataset)\n\n model = generate_model(dataset.y_max_length, dataset.chars)\n\n if checkpoint_filename is not None:\n model.load_weights(checkpoint_filename)\n\n iterate_training(model, dataset, initial_epoch)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Trains a deep spelling model.')\n parser.add_argument('--checkpoint', type=str,\n help='Filename of a model checkpoint to start the training from.')\n parser.add_argument('--datasetparams', type=str,\n help='Filename of a file with dataset params to load for continuing model training.')\n parser.add_argument('--initialepoch', type=int,\n help='Initial epoch parameter for continuing model training.', default=0)\n\n args = parser.parse_args()\n\n main_news(args.checkpoint, args.datasetparams, args.initialepoch)\n",
"step-ids": [
6,
7,
8,
10,
12
]
}
|
[
6,
7,
8,
10,
12
] |
from ..scope_manager import ScopeManager
from ..span import Span
from ..tracer import Tracer
from .propagator import Propagator
class MockTracer(Tracer):
def __init__(self, scope_manager: ScopeManager | None = ...) -> None: ...
def register_propagator(self, format: str, propagator: Propagator) -> None: ...
def finished_spans(self) -> list[Span]: ...
def reset(self) -> None: ...
|
normal
|
{
"blob_id": "76d2c80c673f9a0444e72721909a51479ff35521",
"index": 1785,
"step-1": "<mask token>\n\n\nclass MockTracer(Tracer):\n\n def __init__(self, scope_manager: (ScopeManager | None)=...) ->None:\n ...\n\n def register_propagator(self, format: str, propagator: Propagator) ->None:\n ...\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass MockTracer(Tracer):\n\n def __init__(self, scope_manager: (ScopeManager | None)=...) ->None:\n ...\n\n def register_propagator(self, format: str, propagator: Propagator) ->None:\n ...\n <mask token>\n\n def reset(self) ->None:\n ...\n",
"step-3": "<mask token>\n\n\nclass MockTracer(Tracer):\n\n def __init__(self, scope_manager: (ScopeManager | None)=...) ->None:\n ...\n\n def register_propagator(self, format: str, propagator: Propagator) ->None:\n ...\n\n def finished_spans(self) ->list[Span]:\n ...\n\n def reset(self) ->None:\n ...\n",
"step-4": "from ..scope_manager import ScopeManager\nfrom ..span import Span\nfrom ..tracer import Tracer\nfrom .propagator import Propagator\n\n\nclass MockTracer(Tracer):\n\n def __init__(self, scope_manager: (ScopeManager | None)=...) ->None:\n ...\n\n def register_propagator(self, format: str, propagator: Propagator) ->None:\n ...\n\n def finished_spans(self) ->list[Span]:\n ...\n\n def reset(self) ->None:\n ...\n",
"step-5": "from ..scope_manager import ScopeManager\nfrom ..span import Span\nfrom ..tracer import Tracer\nfrom .propagator import Propagator\n\nclass MockTracer(Tracer):\n def __init__(self, scope_manager: ScopeManager | None = ...) -> None: ...\n def register_propagator(self, format: str, propagator: Propagator) -> None: ...\n def finished_spans(self) -> list[Span]: ...\n def reset(self) -> None: ...\n",
"step-ids": [
3,
4,
5,
6,
7
]
}
|
[
3,
4,
5,
6,
7
] |
from timemachines.skatertools.testing.allregressiontests import REGRESSION_TESTS
import time
import random
TIMEOUT = 60*5
# Regression tests run occasionally to check various parts of hyper-param spaces, etc.
if __name__=='__main__':
start_time = time.time()
elapsed = time.time()-start_time
while elapsed < TIMEOUT:
a_test = random.choice(REGRESSION_TESTS)
print('Running '+str(a_test.__name__))
a_test()
elapsed = time.time() - start_time
|
normal
|
{
"blob_id": "710bb0e0efc2c4a3ba9b1ae85e1c22e81f8ca68e",
"index": 7960,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif __name__ == '__main__':\n start_time = time.time()\n elapsed = time.time() - start_time\n while elapsed < TIMEOUT:\n a_test = random.choice(REGRESSION_TESTS)\n print('Running ' + str(a_test.__name__))\n a_test()\n elapsed = time.time() - start_time\n",
"step-3": "<mask token>\nTIMEOUT = 60 * 5\nif __name__ == '__main__':\n start_time = time.time()\n elapsed = time.time() - start_time\n while elapsed < TIMEOUT:\n a_test = random.choice(REGRESSION_TESTS)\n print('Running ' + str(a_test.__name__))\n a_test()\n elapsed = time.time() - start_time\n",
"step-4": "from timemachines.skatertools.testing.allregressiontests import REGRESSION_TESTS\nimport time\nimport random\nTIMEOUT = 60 * 5\nif __name__ == '__main__':\n start_time = time.time()\n elapsed = time.time() - start_time\n while elapsed < TIMEOUT:\n a_test = random.choice(REGRESSION_TESTS)\n print('Running ' + str(a_test.__name__))\n a_test()\n elapsed = time.time() - start_time\n",
"step-5": "from timemachines.skatertools.testing.allregressiontests import REGRESSION_TESTS\nimport time\nimport random\nTIMEOUT = 60*5\n\n# Regression tests run occasionally to check various parts of hyper-param spaces, etc.\n\nif __name__=='__main__':\n start_time = time.time()\n elapsed = time.time()-start_time\n while elapsed < TIMEOUT:\n a_test = random.choice(REGRESSION_TESTS)\n print('Running '+str(a_test.__name__))\n a_test()\n elapsed = time.time() - start_time\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
# coding=utf-8
"""SCALE UI: feature tests."""
import pytest
import xpaths
from function import (
wait_on_element,
is_element_present,
wait_on_element_disappear
)
from pytest_bdd import (
given,
scenario,
then,
when,
)
@pytest.mark.dependency(name='Set_Group')
@scenario('features/NAS-T1250.feature', 'Verify that you can create a new group')
def test_verify_that_you_can_create_a_new_group():
"""Verify that you can create a new group."""
@given('the browser is open, navigate to the SCALE URL, and login')
def the_browser_is_open_navigate_to_the_scale_url_and_login(driver, nas_ip, root_password):
"""the browser is open, navigate to the SCALE URL, and login."""
if nas_ip not in driver.current_url:
driver.get(f"http://{nas_ip}")
assert wait_on_element(driver, 10, xpaths.login.user_Input)
if not is_element_present(driver, xpaths.side_Menu.dashboard):
assert wait_on_element(driver, 10, xpaths.login.user_Input)
driver.find_element_by_xpath(xpaths.login.user_Input).clear()
driver.find_element_by_xpath(xpaths.login.user_Input).send_keys('root')
driver.find_element_by_xpath(xpaths.login.password_Input).clear()
driver.find_element_by_xpath(xpaths.login.password_Input).send_keys(root_password)
assert wait_on_element(driver, 5, xpaths.login.signin_Button)
driver.find_element_by_xpath(xpaths.login.signin_Button).click()
else:
assert wait_on_element(driver, 10, xpaths.side_Menu.dashboard, 'clickable')
driver.find_element_by_xpath(xpaths.side_Menu.dashboard).click()
@when('on the dashboard click on Credentials and Local Groups')
def on_the_dashboard_click_on_credentials_and_local_groups(driver):
"""on the dashboard click on Credentials and Local Groups."""
assert wait_on_element(driver, 10, xpaths.dashboard.title)
assert wait_on_element(driver, 10, xpaths.dashboard.system_Info_Card_Title)
assert wait_on_element(driver, 10, xpaths.side_Menu.credentials, 'clickable')
driver.find_element_by_xpath(xpaths.side_Menu.credentials).click()
assert wait_on_element(driver, 10, xpaths.side_Menu.local_Group, 'clickable')
driver.find_element_by_xpath(xpaths.side_Menu.local_Group).click()
@then('on the Groups page, click Add')
def on_the_groups_page_click_add(driver):
"""on the Groups page, click Add."""
assert wait_on_element(driver, 10, xpaths.groups.title)
assert wait_on_element(driver, 10, xpaths.button.add, 'clickable')
driver.find_element_by_xpath(xpaths.button.add).click()
@then('on the Add Group side box input the group name')
def on_the_add_group_side_box_input_the_group_name(driver):
"""on the Add Group side box input the group name."""
assert wait_on_element(driver, 7, xpaths.add_Group.title)
assert wait_on_element(driver, 7, xpaths.add_Group.name_Input, 'inputable')
driver.find_element_by_xpath(xpaths.add_Group.name_Input).clear()
driver.find_element_by_xpath(xpaths.add_Group.name_Input).send_keys('qetest')
@then('click save and verify the group was added')
def click_save_and_verify_the_group_was_added(driver):
"""click save and verify the group was added."""
assert wait_on_element(driver, 7, xpaths.button.save, 'clickable')
driver.find_element_by_xpath(xpaths.button.save).click()
assert wait_on_element_disappear(driver, 20, xpaths.progress.progressbar)
assert wait_on_element(driver, 10, xpaths.groups.title)
assert wait_on_element(driver, 10, xpaths.groups.qetest_Name)
|
normal
|
{
"blob_id": "f4aaf0449bff68814090552ea4f6ccac85dacf1b",
"index": 5617,
"step-1": "<mask token>\n\n\n@given('the browser is open, navigate to the SCALE URL, and login')\ndef the_browser_is_open_navigate_to_the_scale_url_and_login(driver, nas_ip,\n root_password):\n \"\"\"the browser is open, navigate to the SCALE URL, and login.\"\"\"\n if nas_ip not in driver.current_url:\n driver.get(f'http://{nas_ip}')\n assert wait_on_element(driver, 10, xpaths.login.user_Input)\n if not is_element_present(driver, xpaths.side_Menu.dashboard):\n assert wait_on_element(driver, 10, xpaths.login.user_Input)\n driver.find_element_by_xpath(xpaths.login.user_Input).clear()\n driver.find_element_by_xpath(xpaths.login.user_Input).send_keys('root')\n driver.find_element_by_xpath(xpaths.login.password_Input).clear()\n driver.find_element_by_xpath(xpaths.login.password_Input).send_keys(\n root_password)\n assert wait_on_element(driver, 5, xpaths.login.signin_Button)\n driver.find_element_by_xpath(xpaths.login.signin_Button).click()\n else:\n assert wait_on_element(driver, 10, xpaths.side_Menu.dashboard,\n 'clickable')\n driver.find_element_by_xpath(xpaths.side_Menu.dashboard).click()\n\n\n@when('on the dashboard click on Credentials and Local Groups')\ndef on_the_dashboard_click_on_credentials_and_local_groups(driver):\n \"\"\"on the dashboard click on Credentials and Local Groups.\"\"\"\n assert wait_on_element(driver, 10, xpaths.dashboard.title)\n assert wait_on_element(driver, 10, xpaths.dashboard.system_Info_Card_Title)\n assert wait_on_element(driver, 10, xpaths.side_Menu.credentials,\n 'clickable')\n driver.find_element_by_xpath(xpaths.side_Menu.credentials).click()\n assert wait_on_element(driver, 10, xpaths.side_Menu.local_Group,\n 'clickable')\n driver.find_element_by_xpath(xpaths.side_Menu.local_Group).click()\n\n\n<mask token>\n\n\n@then('on the Add Group side box input the group name')\ndef on_the_add_group_side_box_input_the_group_name(driver):\n \"\"\"on the Add Group side box input the group name.\"\"\"\n assert wait_on_element(driver, 7, xpaths.add_Group.title)\n assert wait_on_element(driver, 7, xpaths.add_Group.name_Input, 'inputable')\n driver.find_element_by_xpath(xpaths.add_Group.name_Input).clear()\n driver.find_element_by_xpath(xpaths.add_Group.name_Input).send_keys(\n 'qetest')\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\n@given('the browser is open, navigate to the SCALE URL, and login')\ndef the_browser_is_open_navigate_to_the_scale_url_and_login(driver, nas_ip,\n root_password):\n \"\"\"the browser is open, navigate to the SCALE URL, and login.\"\"\"\n if nas_ip not in driver.current_url:\n driver.get(f'http://{nas_ip}')\n assert wait_on_element(driver, 10, xpaths.login.user_Input)\n if not is_element_present(driver, xpaths.side_Menu.dashboard):\n assert wait_on_element(driver, 10, xpaths.login.user_Input)\n driver.find_element_by_xpath(xpaths.login.user_Input).clear()\n driver.find_element_by_xpath(xpaths.login.user_Input).send_keys('root')\n driver.find_element_by_xpath(xpaths.login.password_Input).clear()\n driver.find_element_by_xpath(xpaths.login.password_Input).send_keys(\n root_password)\n assert wait_on_element(driver, 5, xpaths.login.signin_Button)\n driver.find_element_by_xpath(xpaths.login.signin_Button).click()\n else:\n assert wait_on_element(driver, 10, xpaths.side_Menu.dashboard,\n 'clickable')\n driver.find_element_by_xpath(xpaths.side_Menu.dashboard).click()\n\n\n@when('on the dashboard click on Credentials and Local Groups')\ndef on_the_dashboard_click_on_credentials_and_local_groups(driver):\n \"\"\"on the dashboard click on Credentials and Local Groups.\"\"\"\n assert wait_on_element(driver, 10, xpaths.dashboard.title)\n assert wait_on_element(driver, 10, xpaths.dashboard.system_Info_Card_Title)\n assert wait_on_element(driver, 10, xpaths.side_Menu.credentials,\n 'clickable')\n driver.find_element_by_xpath(xpaths.side_Menu.credentials).click()\n assert wait_on_element(driver, 10, xpaths.side_Menu.local_Group,\n 'clickable')\n driver.find_element_by_xpath(xpaths.side_Menu.local_Group).click()\n\n\n@then('on the Groups page, click Add')\ndef on_the_groups_page_click_add(driver):\n \"\"\"on the Groups page, click Add.\"\"\"\n assert wait_on_element(driver, 10, xpaths.groups.title)\n assert wait_on_element(driver, 10, xpaths.button.add, 'clickable')\n driver.find_element_by_xpath(xpaths.button.add).click()\n\n\n@then('on the Add Group side box input the group name')\ndef on_the_add_group_side_box_input_the_group_name(driver):\n \"\"\"on the Add Group side box input the group name.\"\"\"\n assert wait_on_element(driver, 7, xpaths.add_Group.title)\n assert wait_on_element(driver, 7, xpaths.add_Group.name_Input, 'inputable')\n driver.find_element_by_xpath(xpaths.add_Group.name_Input).clear()\n driver.find_element_by_xpath(xpaths.add_Group.name_Input).send_keys(\n 'qetest')\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\n@given('the browser is open, navigate to the SCALE URL, and login')\ndef the_browser_is_open_navigate_to_the_scale_url_and_login(driver, nas_ip,\n root_password):\n \"\"\"the browser is open, navigate to the SCALE URL, and login.\"\"\"\n if nas_ip not in driver.current_url:\n driver.get(f'http://{nas_ip}')\n assert wait_on_element(driver, 10, xpaths.login.user_Input)\n if not is_element_present(driver, xpaths.side_Menu.dashboard):\n assert wait_on_element(driver, 10, xpaths.login.user_Input)\n driver.find_element_by_xpath(xpaths.login.user_Input).clear()\n driver.find_element_by_xpath(xpaths.login.user_Input).send_keys('root')\n driver.find_element_by_xpath(xpaths.login.password_Input).clear()\n driver.find_element_by_xpath(xpaths.login.password_Input).send_keys(\n root_password)\n assert wait_on_element(driver, 5, xpaths.login.signin_Button)\n driver.find_element_by_xpath(xpaths.login.signin_Button).click()\n else:\n assert wait_on_element(driver, 10, xpaths.side_Menu.dashboard,\n 'clickable')\n driver.find_element_by_xpath(xpaths.side_Menu.dashboard).click()\n\n\n@when('on the dashboard click on Credentials and Local Groups')\ndef on_the_dashboard_click_on_credentials_and_local_groups(driver):\n \"\"\"on the dashboard click on Credentials and Local Groups.\"\"\"\n assert wait_on_element(driver, 10, xpaths.dashboard.title)\n assert wait_on_element(driver, 10, xpaths.dashboard.system_Info_Card_Title)\n assert wait_on_element(driver, 10, xpaths.side_Menu.credentials,\n 'clickable')\n driver.find_element_by_xpath(xpaths.side_Menu.credentials).click()\n assert wait_on_element(driver, 10, xpaths.side_Menu.local_Group,\n 'clickable')\n driver.find_element_by_xpath(xpaths.side_Menu.local_Group).click()\n\n\n@then('on the Groups page, click Add')\ndef on_the_groups_page_click_add(driver):\n \"\"\"on the Groups page, click Add.\"\"\"\n assert wait_on_element(driver, 10, xpaths.groups.title)\n assert wait_on_element(driver, 10, xpaths.button.add, 'clickable')\n driver.find_element_by_xpath(xpaths.button.add).click()\n\n\n@then('on the Add Group side box input the group name')\ndef on_the_add_group_side_box_input_the_group_name(driver):\n \"\"\"on the Add Group side box input the group name.\"\"\"\n assert wait_on_element(driver, 7, xpaths.add_Group.title)\n assert wait_on_element(driver, 7, xpaths.add_Group.name_Input, 'inputable')\n driver.find_element_by_xpath(xpaths.add_Group.name_Input).clear()\n driver.find_element_by_xpath(xpaths.add_Group.name_Input).send_keys(\n 'qetest')\n\n\n@then('click save and verify the group was added')\ndef click_save_and_verify_the_group_was_added(driver):\n \"\"\"click save and verify the group was added.\"\"\"\n assert wait_on_element(driver, 7, xpaths.button.save, 'clickable')\n driver.find_element_by_xpath(xpaths.button.save).click()\n assert wait_on_element_disappear(driver, 20, xpaths.progress.progressbar)\n assert wait_on_element(driver, 10, xpaths.groups.title)\n assert wait_on_element(driver, 10, xpaths.groups.qetest_Name)\n",
"step-4": "<mask token>\nimport pytest\nimport xpaths\nfrom function import wait_on_element, is_element_present, wait_on_element_disappear\nfrom pytest_bdd import given, scenario, then, when\n\n\n@pytest.mark.dependency(name='Set_Group')\n@scenario('features/NAS-T1250.feature',\n 'Verify that you can create a new group')\ndef test_verify_that_you_can_create_a_new_group():\n \"\"\"Verify that you can create a new group.\"\"\"\n\n\n@given('the browser is open, navigate to the SCALE URL, and login')\ndef the_browser_is_open_navigate_to_the_scale_url_and_login(driver, nas_ip,\n root_password):\n \"\"\"the browser is open, navigate to the SCALE URL, and login.\"\"\"\n if nas_ip not in driver.current_url:\n driver.get(f'http://{nas_ip}')\n assert wait_on_element(driver, 10, xpaths.login.user_Input)\n if not is_element_present(driver, xpaths.side_Menu.dashboard):\n assert wait_on_element(driver, 10, xpaths.login.user_Input)\n driver.find_element_by_xpath(xpaths.login.user_Input).clear()\n driver.find_element_by_xpath(xpaths.login.user_Input).send_keys('root')\n driver.find_element_by_xpath(xpaths.login.password_Input).clear()\n driver.find_element_by_xpath(xpaths.login.password_Input).send_keys(\n root_password)\n assert wait_on_element(driver, 5, xpaths.login.signin_Button)\n driver.find_element_by_xpath(xpaths.login.signin_Button).click()\n else:\n assert wait_on_element(driver, 10, xpaths.side_Menu.dashboard,\n 'clickable')\n driver.find_element_by_xpath(xpaths.side_Menu.dashboard).click()\n\n\n@when('on the dashboard click on Credentials and Local Groups')\ndef on_the_dashboard_click_on_credentials_and_local_groups(driver):\n \"\"\"on the dashboard click on Credentials and Local Groups.\"\"\"\n assert wait_on_element(driver, 10, xpaths.dashboard.title)\n assert wait_on_element(driver, 10, xpaths.dashboard.system_Info_Card_Title)\n assert wait_on_element(driver, 10, xpaths.side_Menu.credentials,\n 'clickable')\n driver.find_element_by_xpath(xpaths.side_Menu.credentials).click()\n assert wait_on_element(driver, 10, xpaths.side_Menu.local_Group,\n 'clickable')\n driver.find_element_by_xpath(xpaths.side_Menu.local_Group).click()\n\n\n@then('on the Groups page, click Add')\ndef on_the_groups_page_click_add(driver):\n \"\"\"on the Groups page, click Add.\"\"\"\n assert wait_on_element(driver, 10, xpaths.groups.title)\n assert wait_on_element(driver, 10, xpaths.button.add, 'clickable')\n driver.find_element_by_xpath(xpaths.button.add).click()\n\n\n@then('on the Add Group side box input the group name')\ndef on_the_add_group_side_box_input_the_group_name(driver):\n \"\"\"on the Add Group side box input the group name.\"\"\"\n assert wait_on_element(driver, 7, xpaths.add_Group.title)\n assert wait_on_element(driver, 7, xpaths.add_Group.name_Input, 'inputable')\n driver.find_element_by_xpath(xpaths.add_Group.name_Input).clear()\n driver.find_element_by_xpath(xpaths.add_Group.name_Input).send_keys(\n 'qetest')\n\n\n@then('click save and verify the group was added')\ndef click_save_and_verify_the_group_was_added(driver):\n \"\"\"click save and verify the group was added.\"\"\"\n assert wait_on_element(driver, 7, xpaths.button.save, 'clickable')\n driver.find_element_by_xpath(xpaths.button.save).click()\n assert wait_on_element_disappear(driver, 20, xpaths.progress.progressbar)\n assert wait_on_element(driver, 10, xpaths.groups.title)\n assert wait_on_element(driver, 10, xpaths.groups.qetest_Name)\n",
"step-5": "# coding=utf-8\n\"\"\"SCALE UI: feature tests.\"\"\"\n\nimport pytest\nimport xpaths\nfrom function import (\n wait_on_element,\n is_element_present,\n wait_on_element_disappear\n)\nfrom pytest_bdd import (\n given,\n scenario,\n then,\n when,\n)\n\n\n@pytest.mark.dependency(name='Set_Group')\n@scenario('features/NAS-T1250.feature', 'Verify that you can create a new group')\ndef test_verify_that_you_can_create_a_new_group():\n \"\"\"Verify that you can create a new group.\"\"\"\n\n\n@given('the browser is open, navigate to the SCALE URL, and login')\ndef the_browser_is_open_navigate_to_the_scale_url_and_login(driver, nas_ip, root_password):\n \"\"\"the browser is open, navigate to the SCALE URL, and login.\"\"\"\n if nas_ip not in driver.current_url:\n driver.get(f\"http://{nas_ip}\")\n assert wait_on_element(driver, 10, xpaths.login.user_Input)\n if not is_element_present(driver, xpaths.side_Menu.dashboard):\n assert wait_on_element(driver, 10, xpaths.login.user_Input)\n driver.find_element_by_xpath(xpaths.login.user_Input).clear()\n driver.find_element_by_xpath(xpaths.login.user_Input).send_keys('root')\n driver.find_element_by_xpath(xpaths.login.password_Input).clear()\n driver.find_element_by_xpath(xpaths.login.password_Input).send_keys(root_password)\n assert wait_on_element(driver, 5, xpaths.login.signin_Button)\n driver.find_element_by_xpath(xpaths.login.signin_Button).click()\n else:\n assert wait_on_element(driver, 10, xpaths.side_Menu.dashboard, 'clickable')\n driver.find_element_by_xpath(xpaths.side_Menu.dashboard).click()\n\n\n@when('on the dashboard click on Credentials and Local Groups')\ndef on_the_dashboard_click_on_credentials_and_local_groups(driver):\n \"\"\"on the dashboard click on Credentials and Local Groups.\"\"\"\n assert wait_on_element(driver, 10, xpaths.dashboard.title)\n assert wait_on_element(driver, 10, xpaths.dashboard.system_Info_Card_Title)\n assert wait_on_element(driver, 10, xpaths.side_Menu.credentials, 'clickable')\n driver.find_element_by_xpath(xpaths.side_Menu.credentials).click()\n assert wait_on_element(driver, 10, xpaths.side_Menu.local_Group, 'clickable')\n driver.find_element_by_xpath(xpaths.side_Menu.local_Group).click()\n\n\n@then('on the Groups page, click Add')\ndef on_the_groups_page_click_add(driver):\n \"\"\"on the Groups page, click Add.\"\"\"\n assert wait_on_element(driver, 10, xpaths.groups.title)\n assert wait_on_element(driver, 10, xpaths.button.add, 'clickable')\n driver.find_element_by_xpath(xpaths.button.add).click()\n\n\n@then('on the Add Group side box input the group name')\ndef on_the_add_group_side_box_input_the_group_name(driver):\n \"\"\"on the Add Group side box input the group name.\"\"\"\n assert wait_on_element(driver, 7, xpaths.add_Group.title)\n assert wait_on_element(driver, 7, xpaths.add_Group.name_Input, 'inputable')\n driver.find_element_by_xpath(xpaths.add_Group.name_Input).clear()\n driver.find_element_by_xpath(xpaths.add_Group.name_Input).send_keys('qetest')\n\n\n@then('click save and verify the group was added')\ndef click_save_and_verify_the_group_was_added(driver):\n \"\"\"click save and verify the group was added.\"\"\"\n assert wait_on_element(driver, 7, xpaths.button.save, 'clickable')\n driver.find_element_by_xpath(xpaths.button.save).click()\n assert wait_on_element_disappear(driver, 20, xpaths.progress.progressbar)\n assert wait_on_element(driver, 10, xpaths.groups.title)\n assert wait_on_element(driver, 10, xpaths.groups.qetest_Name)\n",
"step-ids": [
3,
4,
5,
7,
8
]
}
|
[
3,
4,
5,
7,
8
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
def sum_numbers(numbers=None):
sum = 0
if numbers == None:
for number in range(1, 101):
sum += number
return sum
for number in numbers:
sum += number
return sum
|
flexible
|
{
"blob_id": "a85d06d72b053b0ef6cb6ec2ba465bfb8975b28e",
"index": 3879,
"step-1": "<mask token>\n",
"step-2": "def sum_numbers(numbers=None):\n sum = 0\n if numbers == None:\n for number in range(1, 101):\n sum += number\n return sum\n for number in numbers:\n sum += number\n return sum\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
}
|
[
0,
1
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
created by gjwei on 3/26/17
"""
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
a = ListNode(1)
a.next = ListNode(3)
a.next = None
print a.val
print a.next
def main():
print "hello"
a = []
for i in range(20):
a.append(i)
return a
|
normal
|
{
"blob_id": "4a0cbd59ffae4fb5ba6e3bd871231e37065d1aed",
"index": 3464,
"step-1": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\" \n created by gjwei on 3/26/17\n \n\"\"\"\nclass ListNode(object):\n def __init__(self, x):\n self.val = x\n self.next = None\n\n\na = ListNode(1)\na.next = ListNode(3)\n\na.next = None\nprint a.val\nprint a.next\n\n\ndef main():\n print \"hello\"\n a = []\n for i in range(20):\n a.append(i)\n\n return a\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
# -*- coding: utf-8 -*-
# @time : 2021/1/10 10:25
# @Author : Owen
# @File : mainpage.py
from selenium.webdriver.common.by import By
from homework.weixin.core.base import Base
from homework.weixin.core.contact import Contact
'''
企业微信首页
'''
class MainPage(Base):
#跳转到联系人页面
def goto_contact(self):
self.find(By.CSS_SELECTOR, '#menu_contacts').click()
return Contact(self.driver)
|
normal
|
{
"blob_id": "7775d260f0db06fad374d9f900b03d8dbcc00762",
"index": 6504,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass MainPage(Base):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass MainPage(Base):\n\n def goto_contact(self):\n self.find(By.CSS_SELECTOR, '#menu_contacts').click()\n return Contact(self.driver)\n",
"step-4": "from selenium.webdriver.common.by import By\nfrom homework.weixin.core.base import Base\nfrom homework.weixin.core.contact import Contact\n<mask token>\n\n\nclass MainPage(Base):\n\n def goto_contact(self):\n self.find(By.CSS_SELECTOR, '#menu_contacts').click()\n return Contact(self.driver)\n",
"step-5": "# -*- coding: utf-8 -*-\n# @time : 2021/1/10 10:25\n# @Author : Owen\n# @File : mainpage.py\nfrom selenium.webdriver.common.by import By\n\nfrom homework.weixin.core.base import Base\nfrom homework.weixin.core.contact import Contact\n'''\n企业微信首页\n'''\n\nclass MainPage(Base):\n #跳转到联系人页面\n def goto_contact(self):\n self.find(By.CSS_SELECTOR, '#menu_contacts').click()\n return Contact(self.driver)",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
print(60 * 60)
seconds_per_hour = 60 * 60
print(24 * seconds_per_hour)
seconds_per_day = 24 * seconds_per_hour
print(seconds_per_day / seconds_per_hour)
print(seconds_per_day // seconds_per_hour)
|
normal
|
{
"blob_id": "358879d83ed3058530031d50fb69e3ce11fbd524",
"index": 1057,
"step-1": "<mask token>\n",
"step-2": "print(60 * 60)\n<mask token>\nprint(24 * seconds_per_hour)\n<mask token>\nprint(seconds_per_day / seconds_per_hour)\nprint(seconds_per_day // seconds_per_hour)\n",
"step-3": "print(60 * 60)\nseconds_per_hour = 60 * 60\nprint(24 * seconds_per_hour)\nseconds_per_day = 24 * seconds_per_hour\nprint(seconds_per_day / seconds_per_hour)\nprint(seconds_per_day // seconds_per_hour)\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
MyScheduler = Scheduler()
<|reserved_special_token_1|>
from .scheduler import Scheduler
MyScheduler = Scheduler()
|
flexible
|
{
"blob_id": "d472a15d6fa826e50a550996369b00b6c599a1c7",
"index": 5401,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nMyScheduler = Scheduler()\n",
"step-3": "from .scheduler import Scheduler\nMyScheduler = Scheduler()\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
# PySNMP SMI module. Autogenerated from smidump -f python DS0BUNDLE-MIB
# by libsmi2pysnmp-0.1.3 at Thu May 22 11:57:37 2014,
# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)
# Imports
( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint")
( InterfaceIndex, ifIndex, ) = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex", "ifIndex")
( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup")
( Bits, Integer32, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, transmission, ) = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "Integer32", "ModuleIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "transmission")
( DisplayString, RowStatus, TestAndIncr, ) = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "RowStatus", "TestAndIncr")
# Objects
ds0Bundle = ModuleIdentity((1, 3, 6, 1, 2, 1, 10, 82)).setRevisions(("1998-07-16 16:30","1998-05-24 20:10",))
if mibBuilder.loadTexts: ds0Bundle.setOrganization("IETF Trunk MIB Working Group")
if mibBuilder.loadTexts: ds0Bundle.setContactInfo(" David Fowler\n\nPostal: Newbridge Networks Corporation\n 600 March Road\n Kanata, Ontario, Canada K2K 2E6\n\n Tel: +1 613 591 3600\n Fax: +1 613 599 3619\n\nE-mail: davef@newbridge.com")
if mibBuilder.loadTexts: ds0Bundle.setDescription("The MIB module to describe\nDS0 Bundle interfaces objects.")
dsx0BondingTable = MibTable((1, 3, 6, 1, 2, 1, 10, 82, 1))
if mibBuilder.loadTexts: dsx0BondingTable.setDescription("The DS0 Bonding table.")
dsx0BondingEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 82, 1, 1)).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: dsx0BondingEntry.setDescription("An entry in the DS0 Bonding table. There is a\nrow in this table for each DS0Bundle interface.")
dsx0BondMode = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 1, 1, 1), Integer().subtype(subtypeSpec=SingleValueConstraint(1,5,6,3,4,2,)).subtype(namedValues=NamedValues(("none", 1), ("other", 2), ("mode0", 3), ("mode1", 4), ("mode2", 5), ("mode3", 6), ))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: dsx0BondMode.setDescription("This object indicates which BONDing mode is used,\nif any, for a ds0Bundle. Mode0 provides parameter\nand number exchange with no synchronization. Mode\n1 provides parameter and number exchange. Mode 1\nalso provides synchronization during\ninitialization but does not include inband\nmonitoring. Mode 2 provides all of the above plus\ninband monitoring. Mode 2 also steals 1/64th of\nthe bandwidth of each channel (thus not supporting\nn x 56/64 kbit/s data channels for most values of\nn). Mode 3 provides all of the above, but also\nprovides n x 56/64 kbit/s data channels. Most\ncommon implementations of Mode 3 add an extra\nchannel to support the inband monitoring overhead.\nModeNone should be used when the interface is not\nperforming bandwidth-on-demand.")
dsx0BondStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 1, 1, 2), Integer().subtype(subtypeSpec=SingleValueConstraint(1,3,2,)).subtype(namedValues=NamedValues(("idle", 1), ("callSetup", 2), ("dataTransfer", 3), ))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsx0BondStatus.setDescription("This object indicates the current status of the\nbonding call using this ds0Bundle. idle(1) should\nbe used when the bonding mode is set to none(1).")
dsx0BondRowStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 1, 1, 3), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: dsx0BondRowStatus.setDescription("This object is used to create new rows in this\ntable, modify existing rows, and to delete\nexisting rows.")
dsx0BundleNextIndex = MibScalar((1, 3, 6, 1, 2, 1, 10, 82, 2), TestAndIncr()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: dsx0BundleNextIndex.setDescription("This object is used to assist the manager in\nselecting a value for dsx0BundleIndex. Because\nthis object is of syntax TestAndIncr (see the\nSNMPv2-TC document, RFC 1903) it can also be used\nto avoid race conditions with multiple managers\ntrying to create rows in the table.\n\nIf the result of the SET for dsx0BundleNextIndex\nis not success, this means the value has been\nchanged from index (i.e. another manager used the\nvalue), so a new value is required.\n\nThe algorithm is:\ndone = false\nwhile done == false\n index = GET (dsx0BundleNextIndex.0)\n SET (dsx0BundleNextIndex.0=index)\n if (set failed)\n done = false\n else\n SET(dsx0BundleRowStatus.index=createAndGo)\n if (set failed)\n done = false\n else\n done = true\n other error handling")
dsx0BundleTable = MibTable((1, 3, 6, 1, 2, 1, 10, 82, 3))
if mibBuilder.loadTexts: dsx0BundleTable.setDescription("There is an row in this table for each ds0Bundle\nin the system. This table can be used to\n(indirectly) create rows in the ifTable with\nifType = 'ds0Bundle(82)'.")
dsx0BundleEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 82, 3, 1)).setIndexNames((0, "DS0BUNDLE-MIB", "dsx0BundleIndex"))
if mibBuilder.loadTexts: dsx0BundleEntry.setDescription("There is a row in entry in this table for each\nds0Bundle interface.")
dsx0BundleIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("noaccess")
if mibBuilder.loadTexts: dsx0BundleIndex.setDescription("A unique identifier for a ds0Bundle. This is not\nthe same value as ifIndex. This table is not\nindexed by ifIndex because the manager has to\nchoose the index in a createable row and the agent\nmust be allowed to select ifIndex values.")
dsx0BundleIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 3, 1, 2), InterfaceIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dsx0BundleIfIndex.setDescription("The ifIndex value the agent selected for the\n(new) ds0Bundle interface.")
dsx0BundleCircuitIdentifier = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 3, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: dsx0BundleCircuitIdentifier.setDescription("This variable contains the transmission vendor's\ncircuit identifier, for the purpose of\nfacilitating troubleshooting.")
dsx0BundleRowStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 3, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: dsx0BundleRowStatus.setDescription("This object is used to create and delete rows in\nthis table.")
ds0BundleConformance = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 82, 4))
ds0BundleGroups = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 82, 4, 1))
ds0BundleCompliances = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 82, 4, 2))
# Augmentions
# Groups
ds0BondingGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 82, 4, 1, 1)).setObjects(*(("DS0BUNDLE-MIB", "dsx0BondMode"), ("DS0BUNDLE-MIB", "dsx0BondStatus"), ("DS0BUNDLE-MIB", "dsx0BondRowStatus"), ) )
if mibBuilder.loadTexts: ds0BondingGroup.setDescription("A collection of objects providing\nconfiguration information applicable\nto all DS0 interfaces.")
ds0BundleConfigGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 82, 4, 1, 2)).setObjects(*(("DS0BUNDLE-MIB", "dsx0BundleIfIndex"), ("DS0BUNDLE-MIB", "dsx0BundleRowStatus"), ("DS0BUNDLE-MIB", "dsx0BundleCircuitIdentifier"), ("DS0BUNDLE-MIB", "dsx0BundleNextIndex"), ) )
if mibBuilder.loadTexts: ds0BundleConfigGroup.setDescription("A collection of objects providing the ability to\ncreate a new ds0Bundle in the ifTable as well as\nconfiguration information about the ds0Bundle.")
# Compliances
ds0BundleCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 10, 82, 4, 2, 1)).setObjects(*(("DS0BUNDLE-MIB", "ds0BundleConfigGroup"), ("DS0BUNDLE-MIB", "ds0BondingGroup"), ) )
if mibBuilder.loadTexts: ds0BundleCompliance.setDescription("The compliance statement for DS0Bundle\ninterfaces.")
# Exports
# Module identity
mibBuilder.exportSymbols("DS0BUNDLE-MIB", PYSNMP_MODULE_ID=ds0Bundle)
# Objects
mibBuilder.exportSymbols("DS0BUNDLE-MIB", ds0Bundle=ds0Bundle, dsx0BondingTable=dsx0BondingTable, dsx0BondingEntry=dsx0BondingEntry, dsx0BondMode=dsx0BondMode, dsx0BondStatus=dsx0BondStatus, dsx0BondRowStatus=dsx0BondRowStatus, dsx0BundleNextIndex=dsx0BundleNextIndex, dsx0BundleTable=dsx0BundleTable, dsx0BundleEntry=dsx0BundleEntry, dsx0BundleIndex=dsx0BundleIndex, dsx0BundleIfIndex=dsx0BundleIfIndex, dsx0BundleCircuitIdentifier=dsx0BundleCircuitIdentifier, dsx0BundleRowStatus=dsx0BundleRowStatus, ds0BundleConformance=ds0BundleConformance, ds0BundleGroups=ds0BundleGroups, ds0BundleCompliances=ds0BundleCompliances)
# Groups
mibBuilder.exportSymbols("DS0BUNDLE-MIB", ds0BondingGroup=ds0BondingGroup, ds0BundleConfigGroup=ds0BundleConfigGroup)
# Compliances
mibBuilder.exportSymbols("DS0BUNDLE-MIB", ds0BundleCompliance=ds0BundleCompliance)
|
normal
|
{
"blob_id": "fab15d34d29301e53a26577725cdd66dca7507bc",
"index": 2330,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif mibBuilder.loadTexts:\n ds0Bundle.setOrganization('IETF Trunk MIB Working Group')\nif mibBuilder.loadTexts:\n ds0Bundle.setContactInfo(\n \"\"\" David Fowler\n\nPostal: Newbridge Networks Corporation\n 600 March Road\n Kanata, Ontario, Canada K2K 2E6\n\n Tel: +1 613 591 3600\n Fax: +1 613 599 3619\n\nE-mail: davef@newbridge.com\"\"\"\n )\nif mibBuilder.loadTexts:\n ds0Bundle.setDescription(\n 'The MIB module to describe\\nDS0 Bundle interfaces objects.')\n<mask token>\nif mibBuilder.loadTexts:\n dsx0BondingTable.setDescription('The DS0 Bonding table.')\n<mask token>\nif mibBuilder.loadTexts:\n dsx0BondingEntry.setDescription(\n \"\"\"An entry in the DS0 Bonding table. There is a\nrow in this table for each DS0Bundle interface.\"\"\"\n )\n<mask token>\nif mibBuilder.loadTexts:\n dsx0BondMode.setDescription(\n \"\"\"This object indicates which BONDing mode is used,\nif any, for a ds0Bundle. Mode0 provides parameter\nand number exchange with no synchronization. Mode\n1 provides parameter and number exchange. Mode 1\nalso provides synchronization during\ninitialization but does not include inband\nmonitoring. Mode 2 provides all of the above plus\ninband monitoring. Mode 2 also steals 1/64th of\nthe bandwidth of each channel (thus not supporting\nn x 56/64 kbit/s data channels for most values of\nn). Mode 3 provides all of the above, but also\nprovides n x 56/64 kbit/s data channels. Most\ncommon implementations of Mode 3 add an extra\nchannel to support the inband monitoring overhead.\nModeNone should be used when the interface is not\nperforming bandwidth-on-demand.\"\"\"\n )\n<mask token>\nif mibBuilder.loadTexts:\n dsx0BondStatus.setDescription(\n \"\"\"This object indicates the current status of the\nbonding call using this ds0Bundle. idle(1) should\nbe used when the bonding mode is set to none(1).\"\"\"\n )\n<mask token>\nif mibBuilder.loadTexts:\n dsx0BondRowStatus.setDescription(\n \"\"\"This object is used to create new rows in this\ntable, modify existing rows, and to delete\nexisting rows.\"\"\"\n )\n<mask token>\nif mibBuilder.loadTexts:\n dsx0BundleNextIndex.setDescription(\n \"\"\"This object is used to assist the manager in\nselecting a value for dsx0BundleIndex. Because\nthis object is of syntax TestAndIncr (see the\nSNMPv2-TC document, RFC 1903) it can also be used\nto avoid race conditions with multiple managers\ntrying to create rows in the table.\n\nIf the result of the SET for dsx0BundleNextIndex\nis not success, this means the value has been\nchanged from index (i.e. another manager used the\nvalue), so a new value is required.\n\nThe algorithm is:\ndone = false\nwhile done == false\n index = GET (dsx0BundleNextIndex.0)\n SET (dsx0BundleNextIndex.0=index)\n if (set failed)\n done = false\n else\n SET(dsx0BundleRowStatus.index=createAndGo)\n if (set failed)\n done = false\n else\n done = true\n other error handling\"\"\"\n )\n<mask token>\nif mibBuilder.loadTexts:\n dsx0BundleTable.setDescription(\n \"\"\"There is an row in this table for each ds0Bundle\nin the system. This table can be used to\n(indirectly) create rows in the ifTable with\nifType = 'ds0Bundle(82)'.\"\"\"\n )\n<mask token>\nif mibBuilder.loadTexts:\n dsx0BundleEntry.setDescription(\n \"\"\"There is a row in entry in this table for each\nds0Bundle interface.\"\"\"\n )\n<mask token>\nif mibBuilder.loadTexts:\n dsx0BundleIndex.setDescription(\n \"\"\"A unique identifier for a ds0Bundle. This is not\nthe same value as ifIndex. This table is not\nindexed by ifIndex because the manager has to\nchoose the index in a createable row and the agent\nmust be allowed to select ifIndex values.\"\"\"\n )\n<mask token>\nif mibBuilder.loadTexts:\n dsx0BundleIfIndex.setDescription(\n \"\"\"The ifIndex value the agent selected for the\n(new) ds0Bundle interface.\"\"\"\n )\n<mask token>\nif mibBuilder.loadTexts:\n dsx0BundleCircuitIdentifier.setDescription(\n \"\"\"This variable contains the transmission vendor's\ncircuit identifier, for the purpose of\nfacilitating troubleshooting.\"\"\"\n )\n<mask token>\nif mibBuilder.loadTexts:\n dsx0BundleRowStatus.setDescription(\n \"\"\"This object is used to create and delete rows in\nthis table.\"\"\")\n<mask token>\nif mibBuilder.loadTexts:\n ds0BondingGroup.setDescription(\n \"\"\"A collection of objects providing\nconfiguration information applicable\nto all DS0 interfaces.\"\"\"\n )\n<mask token>\nif mibBuilder.loadTexts:\n ds0BundleConfigGroup.setDescription(\n \"\"\"A collection of objects providing the ability to\ncreate a new ds0Bundle in the ifTable as well as\nconfiguration information about the ds0Bundle.\"\"\"\n )\n<mask token>\nif mibBuilder.loadTexts:\n ds0BundleCompliance.setDescription(\n 'The compliance statement for DS0Bundle\\ninterfaces.')\nmibBuilder.exportSymbols('DS0BUNDLE-MIB', PYSNMP_MODULE_ID=ds0Bundle)\nmibBuilder.exportSymbols('DS0BUNDLE-MIB', ds0Bundle=ds0Bundle,\n dsx0BondingTable=dsx0BondingTable, dsx0BondingEntry=dsx0BondingEntry,\n dsx0BondMode=dsx0BondMode, dsx0BondStatus=dsx0BondStatus,\n dsx0BondRowStatus=dsx0BondRowStatus, dsx0BundleNextIndex=\n dsx0BundleNextIndex, dsx0BundleTable=dsx0BundleTable, dsx0BundleEntry=\n dsx0BundleEntry, dsx0BundleIndex=dsx0BundleIndex, dsx0BundleIfIndex=\n dsx0BundleIfIndex, dsx0BundleCircuitIdentifier=\n dsx0BundleCircuitIdentifier, dsx0BundleRowStatus=dsx0BundleRowStatus,\n ds0BundleConformance=ds0BundleConformance, ds0BundleGroups=\n ds0BundleGroups, ds0BundleCompliances=ds0BundleCompliances)\nmibBuilder.exportSymbols('DS0BUNDLE-MIB', ds0BondingGroup=ds0BondingGroup,\n ds0BundleConfigGroup=ds0BundleConfigGroup)\nmibBuilder.exportSymbols('DS0BUNDLE-MIB', ds0BundleCompliance=\n ds0BundleCompliance)\n",
"step-3": "Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols('ASN1',\n 'Integer', 'ObjectIdentifier', 'OctetString')\nNamedValues, = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')\n(ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint,\n ValueRangeConstraint, ValueSizeConstraint) = (mibBuilder.importSymbols(\n 'ASN1-REFINEMENT', 'ConstraintsIntersection', 'ConstraintsUnion',\n 'SingleValueConstraint', 'ValueRangeConstraint', 'ValueSizeConstraint'))\nInterfaceIndex, ifIndex = mibBuilder.importSymbols('IF-MIB',\n 'InterfaceIndex', 'ifIndex')\nModuleCompliance, ObjectGroup = mibBuilder.importSymbols('SNMPv2-CONF',\n 'ModuleCompliance', 'ObjectGroup')\n(Bits, Integer32, ModuleIdentity, MibIdentifier, MibScalar, MibTable,\n MibTableRow, MibTableColumn, TimeTicks, transmission) = (mibBuilder.\n importSymbols('SNMPv2-SMI', 'Bits', 'Integer32', 'ModuleIdentity',\n 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow',\n 'MibTableColumn', 'TimeTicks', 'transmission'))\nDisplayString, RowStatus, TestAndIncr = mibBuilder.importSymbols('SNMPv2-TC',\n 'DisplayString', 'RowStatus', 'TestAndIncr')\nds0Bundle = ModuleIdentity((1, 3, 6, 1, 2, 1, 10, 82)).setRevisions((\n '1998-07-16 16:30', '1998-05-24 20:10'))\nif mibBuilder.loadTexts:\n ds0Bundle.setOrganization('IETF Trunk MIB Working Group')\nif mibBuilder.loadTexts:\n ds0Bundle.setContactInfo(\n \"\"\" David Fowler\n\nPostal: Newbridge Networks Corporation\n 600 March Road\n Kanata, Ontario, Canada K2K 2E6\n\n Tel: +1 613 591 3600\n Fax: +1 613 599 3619\n\nE-mail: davef@newbridge.com\"\"\"\n )\nif mibBuilder.loadTexts:\n ds0Bundle.setDescription(\n 'The MIB module to describe\\nDS0 Bundle interfaces objects.')\ndsx0BondingTable = MibTable((1, 3, 6, 1, 2, 1, 10, 82, 1))\nif mibBuilder.loadTexts:\n dsx0BondingTable.setDescription('The DS0 Bonding table.')\ndsx0BondingEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 82, 1, 1)).setIndexNames(\n (0, 'IF-MIB', 'ifIndex'))\nif mibBuilder.loadTexts:\n dsx0BondingEntry.setDescription(\n \"\"\"An entry in the DS0 Bonding table. There is a\nrow in this table for each DS0Bundle interface.\"\"\"\n )\ndsx0BondMode = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 1, 1, 1), Integer(\n ).subtype(subtypeSpec=SingleValueConstraint(1, 5, 6, 3, 4, 2)).subtype(\n namedValues=NamedValues(('none', 1), ('other', 2), ('mode0', 3), (\n 'mode1', 4), ('mode2', 5), ('mode3', 6)))).setMaxAccess('readcreate')\nif mibBuilder.loadTexts:\n dsx0BondMode.setDescription(\n \"\"\"This object indicates which BONDing mode is used,\nif any, for a ds0Bundle. Mode0 provides parameter\nand number exchange with no synchronization. Mode\n1 provides parameter and number exchange. Mode 1\nalso provides synchronization during\ninitialization but does not include inband\nmonitoring. Mode 2 provides all of the above plus\ninband monitoring. Mode 2 also steals 1/64th of\nthe bandwidth of each channel (thus not supporting\nn x 56/64 kbit/s data channels for most values of\nn). Mode 3 provides all of the above, but also\nprovides n x 56/64 kbit/s data channels. Most\ncommon implementations of Mode 3 add an extra\nchannel to support the inband monitoring overhead.\nModeNone should be used when the interface is not\nperforming bandwidth-on-demand.\"\"\"\n )\ndsx0BondStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 1, 1, 2),\n Integer().subtype(subtypeSpec=SingleValueConstraint(1, 3, 2)).subtype(\n namedValues=NamedValues(('idle', 1), ('callSetup', 2), ('dataTransfer',\n 3)))).setMaxAccess('readonly')\nif mibBuilder.loadTexts:\n dsx0BondStatus.setDescription(\n \"\"\"This object indicates the current status of the\nbonding call using this ds0Bundle. idle(1) should\nbe used when the bonding mode is set to none(1).\"\"\"\n )\ndsx0BondRowStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 1, 1, 3),\n RowStatus()).setMaxAccess('readcreate')\nif mibBuilder.loadTexts:\n dsx0BondRowStatus.setDescription(\n \"\"\"This object is used to create new rows in this\ntable, modify existing rows, and to delete\nexisting rows.\"\"\"\n )\ndsx0BundleNextIndex = MibScalar((1, 3, 6, 1, 2, 1, 10, 82, 2), TestAndIncr()\n ).setMaxAccess('readwrite')\nif mibBuilder.loadTexts:\n dsx0BundleNextIndex.setDescription(\n \"\"\"This object is used to assist the manager in\nselecting a value for dsx0BundleIndex. Because\nthis object is of syntax TestAndIncr (see the\nSNMPv2-TC document, RFC 1903) it can also be used\nto avoid race conditions with multiple managers\ntrying to create rows in the table.\n\nIf the result of the SET for dsx0BundleNextIndex\nis not success, this means the value has been\nchanged from index (i.e. another manager used the\nvalue), so a new value is required.\n\nThe algorithm is:\ndone = false\nwhile done == false\n index = GET (dsx0BundleNextIndex.0)\n SET (dsx0BundleNextIndex.0=index)\n if (set failed)\n done = false\n else\n SET(dsx0BundleRowStatus.index=createAndGo)\n if (set failed)\n done = false\n else\n done = true\n other error handling\"\"\"\n )\ndsx0BundleTable = MibTable((1, 3, 6, 1, 2, 1, 10, 82, 3))\nif mibBuilder.loadTexts:\n dsx0BundleTable.setDescription(\n \"\"\"There is an row in this table for each ds0Bundle\nin the system. This table can be used to\n(indirectly) create rows in the ifTable with\nifType = 'ds0Bundle(82)'.\"\"\"\n )\ndsx0BundleEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 82, 3, 1)).setIndexNames((\n 0, 'DS0BUNDLE-MIB', 'dsx0BundleIndex'))\nif mibBuilder.loadTexts:\n dsx0BundleEntry.setDescription(\n \"\"\"There is a row in entry in this table for each\nds0Bundle interface.\"\"\"\n )\ndsx0BundleIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 3, 1, 1),\n Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))\n ).setMaxAccess('noaccess')\nif mibBuilder.loadTexts:\n dsx0BundleIndex.setDescription(\n \"\"\"A unique identifier for a ds0Bundle. This is not\nthe same value as ifIndex. This table is not\nindexed by ifIndex because the manager has to\nchoose the index in a createable row and the agent\nmust be allowed to select ifIndex values.\"\"\"\n )\ndsx0BundleIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 3, 1, 2),\n InterfaceIndex()).setMaxAccess('readonly')\nif mibBuilder.loadTexts:\n dsx0BundleIfIndex.setDescription(\n \"\"\"The ifIndex value the agent selected for the\n(new) ds0Bundle interface.\"\"\"\n )\ndsx0BundleCircuitIdentifier = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 3, \n 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))\n ).setMaxAccess('readcreate')\nif mibBuilder.loadTexts:\n dsx0BundleCircuitIdentifier.setDescription(\n \"\"\"This variable contains the transmission vendor's\ncircuit identifier, for the purpose of\nfacilitating troubleshooting.\"\"\"\n )\ndsx0BundleRowStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 3, 1, 4),\n RowStatus()).setMaxAccess('readcreate')\nif mibBuilder.loadTexts:\n dsx0BundleRowStatus.setDescription(\n \"\"\"This object is used to create and delete rows in\nthis table.\"\"\")\nds0BundleConformance = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 82, 4))\nds0BundleGroups = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 82, 4, 1))\nds0BundleCompliances = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 82, 4, 2))\nds0BondingGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 82, 4, 1, 1)).setObjects(*\n (('DS0BUNDLE-MIB', 'dsx0BondMode'), ('DS0BUNDLE-MIB', 'dsx0BondStatus'),\n ('DS0BUNDLE-MIB', 'dsx0BondRowStatus')))\nif mibBuilder.loadTexts:\n ds0BondingGroup.setDescription(\n \"\"\"A collection of objects providing\nconfiguration information applicable\nto all DS0 interfaces.\"\"\"\n )\nds0BundleConfigGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 82, 4, 1, 2)\n ).setObjects(*(('DS0BUNDLE-MIB', 'dsx0BundleIfIndex'), ('DS0BUNDLE-MIB',\n 'dsx0BundleRowStatus'), ('DS0BUNDLE-MIB', 'dsx0BundleCircuitIdentifier'\n ), ('DS0BUNDLE-MIB', 'dsx0BundleNextIndex')))\nif mibBuilder.loadTexts:\n ds0BundleConfigGroup.setDescription(\n \"\"\"A collection of objects providing the ability to\ncreate a new ds0Bundle in the ifTable as well as\nconfiguration information about the ds0Bundle.\"\"\"\n )\nds0BundleCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 10, 82, 4, 2, 1)\n ).setObjects(*(('DS0BUNDLE-MIB', 'ds0BundleConfigGroup'), (\n 'DS0BUNDLE-MIB', 'ds0BondingGroup')))\nif mibBuilder.loadTexts:\n ds0BundleCompliance.setDescription(\n 'The compliance statement for DS0Bundle\\ninterfaces.')\nmibBuilder.exportSymbols('DS0BUNDLE-MIB', PYSNMP_MODULE_ID=ds0Bundle)\nmibBuilder.exportSymbols('DS0BUNDLE-MIB', ds0Bundle=ds0Bundle,\n dsx0BondingTable=dsx0BondingTable, dsx0BondingEntry=dsx0BondingEntry,\n dsx0BondMode=dsx0BondMode, dsx0BondStatus=dsx0BondStatus,\n dsx0BondRowStatus=dsx0BondRowStatus, dsx0BundleNextIndex=\n dsx0BundleNextIndex, dsx0BundleTable=dsx0BundleTable, dsx0BundleEntry=\n dsx0BundleEntry, dsx0BundleIndex=dsx0BundleIndex, dsx0BundleIfIndex=\n dsx0BundleIfIndex, dsx0BundleCircuitIdentifier=\n dsx0BundleCircuitIdentifier, dsx0BundleRowStatus=dsx0BundleRowStatus,\n ds0BundleConformance=ds0BundleConformance, ds0BundleGroups=\n ds0BundleGroups, ds0BundleCompliances=ds0BundleCompliances)\nmibBuilder.exportSymbols('DS0BUNDLE-MIB', ds0BondingGroup=ds0BondingGroup,\n ds0BundleConfigGroup=ds0BundleConfigGroup)\nmibBuilder.exportSymbols('DS0BUNDLE-MIB', ds0BundleCompliance=\n ds0BundleCompliance)\n",
"step-4": "# PySNMP SMI module. Autogenerated from smidump -f python DS0BUNDLE-MIB\n# by libsmi2pysnmp-0.1.3 at Thu May 22 11:57:37 2014,\n# Python version sys.version_info(major=2, minor=7, micro=2, releaselevel='final', serial=0)\n\n# Imports\n\n( Integer, ObjectIdentifier, OctetString, ) = mibBuilder.importSymbols(\"ASN1\", \"Integer\", \"ObjectIdentifier\", \"OctetString\")\n( NamedValues, ) = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\")\n( ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ) = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"ConstraintsIntersection\", \"ConstraintsUnion\", \"SingleValueConstraint\", \"ValueRangeConstraint\", \"ValueSizeConstraint\")\n( InterfaceIndex, ifIndex, ) = mibBuilder.importSymbols(\"IF-MIB\", \"InterfaceIndex\", \"ifIndex\")\n( ModuleCompliance, ObjectGroup, ) = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"ModuleCompliance\", \"ObjectGroup\")\n( Bits, Integer32, ModuleIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, transmission, ) = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Bits\", \"Integer32\", \"ModuleIdentity\", \"MibIdentifier\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"TimeTicks\", \"transmission\")\n( DisplayString, RowStatus, TestAndIncr, ) = mibBuilder.importSymbols(\"SNMPv2-TC\", \"DisplayString\", \"RowStatus\", \"TestAndIncr\")\n\n# Objects\n\nds0Bundle = ModuleIdentity((1, 3, 6, 1, 2, 1, 10, 82)).setRevisions((\"1998-07-16 16:30\",\"1998-05-24 20:10\",))\nif mibBuilder.loadTexts: ds0Bundle.setOrganization(\"IETF Trunk MIB Working Group\")\nif mibBuilder.loadTexts: ds0Bundle.setContactInfo(\" David Fowler\\n\\nPostal: Newbridge Networks Corporation\\n 600 March Road\\n Kanata, Ontario, Canada K2K 2E6\\n\\n Tel: +1 613 591 3600\\n Fax: +1 613 599 3619\\n\\nE-mail: davef@newbridge.com\")\nif mibBuilder.loadTexts: ds0Bundle.setDescription(\"The MIB module to describe\\nDS0 Bundle interfaces objects.\")\ndsx0BondingTable = MibTable((1, 3, 6, 1, 2, 1, 10, 82, 1))\nif mibBuilder.loadTexts: dsx0BondingTable.setDescription(\"The DS0 Bonding table.\")\ndsx0BondingEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 82, 1, 1)).setIndexNames((0, \"IF-MIB\", \"ifIndex\"))\nif mibBuilder.loadTexts: dsx0BondingEntry.setDescription(\"An entry in the DS0 Bonding table. There is a\\nrow in this table for each DS0Bundle interface.\")\ndsx0BondMode = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 1, 1, 1), Integer().subtype(subtypeSpec=SingleValueConstraint(1,5,6,3,4,2,)).subtype(namedValues=NamedValues((\"none\", 1), (\"other\", 2), (\"mode0\", 3), (\"mode1\", 4), (\"mode2\", 5), (\"mode3\", 6), ))).setMaxAccess(\"readcreate\")\nif mibBuilder.loadTexts: dsx0BondMode.setDescription(\"This object indicates which BONDing mode is used,\\nif any, for a ds0Bundle. Mode0 provides parameter\\nand number exchange with no synchronization. Mode\\n1 provides parameter and number exchange. Mode 1\\nalso provides synchronization during\\ninitialization but does not include inband\\nmonitoring. Mode 2 provides all of the above plus\\ninband monitoring. Mode 2 also steals 1/64th of\\nthe bandwidth of each channel (thus not supporting\\nn x 56/64 kbit/s data channels for most values of\\nn). Mode 3 provides all of the above, but also\\nprovides n x 56/64 kbit/s data channels. Most\\ncommon implementations of Mode 3 add an extra\\nchannel to support the inband monitoring overhead.\\nModeNone should be used when the interface is not\\nperforming bandwidth-on-demand.\")\ndsx0BondStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 1, 1, 2), Integer().subtype(subtypeSpec=SingleValueConstraint(1,3,2,)).subtype(namedValues=NamedValues((\"idle\", 1), (\"callSetup\", 2), (\"dataTransfer\", 3), ))).setMaxAccess(\"readonly\")\nif mibBuilder.loadTexts: dsx0BondStatus.setDescription(\"This object indicates the current status of the\\nbonding call using this ds0Bundle. idle(1) should\\nbe used when the bonding mode is set to none(1).\")\ndsx0BondRowStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 1, 1, 3), RowStatus()).setMaxAccess(\"readcreate\")\nif mibBuilder.loadTexts: dsx0BondRowStatus.setDescription(\"This object is used to create new rows in this\\ntable, modify existing rows, and to delete\\nexisting rows.\")\ndsx0BundleNextIndex = MibScalar((1, 3, 6, 1, 2, 1, 10, 82, 2), TestAndIncr()).setMaxAccess(\"readwrite\")\nif mibBuilder.loadTexts: dsx0BundleNextIndex.setDescription(\"This object is used to assist the manager in\\nselecting a value for dsx0BundleIndex. Because\\nthis object is of syntax TestAndIncr (see the\\nSNMPv2-TC document, RFC 1903) it can also be used\\nto avoid race conditions with multiple managers\\ntrying to create rows in the table.\\n\\nIf the result of the SET for dsx0BundleNextIndex\\nis not success, this means the value has been\\nchanged from index (i.e. another manager used the\\nvalue), so a new value is required.\\n\\nThe algorithm is:\\ndone = false\\nwhile done == false\\n index = GET (dsx0BundleNextIndex.0)\\n SET (dsx0BundleNextIndex.0=index)\\n if (set failed)\\n done = false\\n else\\n SET(dsx0BundleRowStatus.index=createAndGo)\\n if (set failed)\\n done = false\\n else\\n done = true\\n other error handling\")\ndsx0BundleTable = MibTable((1, 3, 6, 1, 2, 1, 10, 82, 3))\nif mibBuilder.loadTexts: dsx0BundleTable.setDescription(\"There is an row in this table for each ds0Bundle\\nin the system. This table can be used to\\n(indirectly) create rows in the ifTable with\\nifType = 'ds0Bundle(82)'.\")\ndsx0BundleEntry = MibTableRow((1, 3, 6, 1, 2, 1, 10, 82, 3, 1)).setIndexNames((0, \"DS0BUNDLE-MIB\", \"dsx0BundleIndex\"))\nif mibBuilder.loadTexts: dsx0BundleEntry.setDescription(\"There is a row in entry in this table for each\\nds0Bundle interface.\")\ndsx0BundleIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess(\"noaccess\")\nif mibBuilder.loadTexts: dsx0BundleIndex.setDescription(\"A unique identifier for a ds0Bundle. This is not\\nthe same value as ifIndex. This table is not\\nindexed by ifIndex because the manager has to\\nchoose the index in a createable row and the agent\\nmust be allowed to select ifIndex values.\")\ndsx0BundleIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 3, 1, 2), InterfaceIndex()).setMaxAccess(\"readonly\")\nif mibBuilder.loadTexts: dsx0BundleIfIndex.setDescription(\"The ifIndex value the agent selected for the\\n(new) ds0Bundle interface.\")\ndsx0BundleCircuitIdentifier = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 3, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess(\"readcreate\")\nif mibBuilder.loadTexts: dsx0BundleCircuitIdentifier.setDescription(\"This variable contains the transmission vendor's\\ncircuit identifier, for the purpose of\\nfacilitating troubleshooting.\")\ndsx0BundleRowStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 10, 82, 3, 1, 4), RowStatus()).setMaxAccess(\"readcreate\")\nif mibBuilder.loadTexts: dsx0BundleRowStatus.setDescription(\"This object is used to create and delete rows in\\nthis table.\")\nds0BundleConformance = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 82, 4))\nds0BundleGroups = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 82, 4, 1))\nds0BundleCompliances = MibIdentifier((1, 3, 6, 1, 2, 1, 10, 82, 4, 2))\n\n# Augmentions\n\n# Groups\n\nds0BondingGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 82, 4, 1, 1)).setObjects(*((\"DS0BUNDLE-MIB\", \"dsx0BondMode\"), (\"DS0BUNDLE-MIB\", \"dsx0BondStatus\"), (\"DS0BUNDLE-MIB\", \"dsx0BondRowStatus\"), ) )\nif mibBuilder.loadTexts: ds0BondingGroup.setDescription(\"A collection of objects providing\\nconfiguration information applicable\\nto all DS0 interfaces.\")\nds0BundleConfigGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 10, 82, 4, 1, 2)).setObjects(*((\"DS0BUNDLE-MIB\", \"dsx0BundleIfIndex\"), (\"DS0BUNDLE-MIB\", \"dsx0BundleRowStatus\"), (\"DS0BUNDLE-MIB\", \"dsx0BundleCircuitIdentifier\"), (\"DS0BUNDLE-MIB\", \"dsx0BundleNextIndex\"), ) )\nif mibBuilder.loadTexts: ds0BundleConfigGroup.setDescription(\"A collection of objects providing the ability to\\ncreate a new ds0Bundle in the ifTable as well as\\nconfiguration information about the ds0Bundle.\")\n\n# Compliances\n\nds0BundleCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 10, 82, 4, 2, 1)).setObjects(*((\"DS0BUNDLE-MIB\", \"ds0BundleConfigGroup\"), (\"DS0BUNDLE-MIB\", \"ds0BondingGroup\"), ) )\nif mibBuilder.loadTexts: ds0BundleCompliance.setDescription(\"The compliance statement for DS0Bundle\\ninterfaces.\")\n\n# Exports\n\n# Module identity\nmibBuilder.exportSymbols(\"DS0BUNDLE-MIB\", PYSNMP_MODULE_ID=ds0Bundle)\n\n# Objects\nmibBuilder.exportSymbols(\"DS0BUNDLE-MIB\", ds0Bundle=ds0Bundle, dsx0BondingTable=dsx0BondingTable, dsx0BondingEntry=dsx0BondingEntry, dsx0BondMode=dsx0BondMode, dsx0BondStatus=dsx0BondStatus, dsx0BondRowStatus=dsx0BondRowStatus, dsx0BundleNextIndex=dsx0BundleNextIndex, dsx0BundleTable=dsx0BundleTable, dsx0BundleEntry=dsx0BundleEntry, dsx0BundleIndex=dsx0BundleIndex, dsx0BundleIfIndex=dsx0BundleIfIndex, dsx0BundleCircuitIdentifier=dsx0BundleCircuitIdentifier, dsx0BundleRowStatus=dsx0BundleRowStatus, ds0BundleConformance=ds0BundleConformance, ds0BundleGroups=ds0BundleGroups, ds0BundleCompliances=ds0BundleCompliances)\n\n# Groups\nmibBuilder.exportSymbols(\"DS0BUNDLE-MIB\", ds0BondingGroup=ds0BondingGroup, ds0BundleConfigGroup=ds0BundleConfigGroup)\n\n# Compliances\nmibBuilder.exportSymbols(\"DS0BUNDLE-MIB\", ds0BundleCompliance=ds0BundleCompliance)\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
df=pd.read_csv('data.csv')
df=df.fillna(np.NaN)
#kita isi df dengan kolom target = 0, target_name = 0 , agar memudahkan untuk training
df['Target']=0
df['Target_name']='Non-Target'
# print(df)
#tandai target dengan angka 1,target_name='Target' pada dataframe usia <= 25, overall >= 80, dan potential >= 80
df['Target'][(df['Age']<=25)&(df['Overall']>=80)&(df['Potential']>=80)]=1
df['Target_name'][(df['Age']<=25)&(df['Overall']>=80)&(df['Potential']>=80)]='Target'
x=df.loc[:,['Age','Overall','Potential']]
y=df['Target']
kf=KFold(n_splits = 5)
for train_index,test_index in kf.split(x):
xtr=x.iloc[train_index]
ytr=y[train_index]
'''
KNN
nilai k terbaik atau n terbaik dapat dicari dengan cara sqrt(n_data) lalu pilih yg odd/ganjil
cari len dari data (banyak data) lalu kalikan pangkat setengah
'''
k = round(len(x) ** .5)
if((k%2) == 0):
k=k+1
else:
k=k
knn=KNeighborsClassifier(n_neighbors=k)
'''
Logistic Regression
'''
logreg=LogisticRegression(multi_class='auto',solver='liblinear')
'''
Random Forest
'''
ranfor=RandomForestClassifier(n_estimators=50)
'''
Decision Tree
'''
dec=DecisionTreeClassifier()
print("Skor KNN: ",round(cross_val_score(knn,xtr,ytr,cv=5).mean()*100),' %')
print("Skor Logistic Regression: ",round(cross_val_score(logreg,xtr,ytr,cv=5).mean()*100),' %')
print("Skor Random Forest: ",round(cross_val_score(ranfor,xtr,ytr,cv=5).mean()*100),' %')
print("Skor Decision Tree: ",round(cross_val_score(dec,xtr,ytr,cv=5).mean()*100),' %')
'''
Skor KNN: 96.0 %
Skor Logistic Regression: 97.0 %
Skor Random Forest: 96.0 %
Skor Decision Tree: 93.0 %
'''
|
normal
|
{
"blob_id": "84db1803a352e0ed8c01b7166f522d46ec89b6f5",
"index": 2487,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor train_index, test_index in kf.split(x):\n xtr = x.iloc[train_index]\n ytr = y[train_index]\n<mask token>\nif k % 2 == 0:\n k = k + 1\nelse:\n k = k\n<mask token>\nprint('Skor KNN: ', round(cross_val_score(knn, xtr, ytr, cv=5).mean() * 100\n ), ' %')\nprint('Skor Logistic Regression: ', round(cross_val_score(logreg, xtr, ytr,\n cv=5).mean() * 100), ' %')\nprint('Skor Random Forest: ', round(cross_val_score(ranfor, xtr, ytr, cv=5)\n .mean() * 100), ' %')\nprint('Skor Decision Tree: ', round(cross_val_score(dec, xtr, ytr, cv=5).\n mean() * 100), ' %')\n<mask token>\n",
"step-3": "<mask token>\ndf = pd.read_csv('data.csv')\ndf = df.fillna(np.NaN)\ndf['Target'] = 0\ndf['Target_name'] = 'Non-Target'\ndf['Target'][(df['Age'] <= 25) & (df['Overall'] >= 80) & (df['Potential'] >=\n 80)] = 1\ndf['Target_name'][(df['Age'] <= 25) & (df['Overall'] >= 80) & (df[\n 'Potential'] >= 80)] = 'Target'\nx = df.loc[:, ['Age', 'Overall', 'Potential']]\ny = df['Target']\nkf = KFold(n_splits=5)\nfor train_index, test_index in kf.split(x):\n xtr = x.iloc[train_index]\n ytr = y[train_index]\n<mask token>\nk = round(len(x) ** 0.5)\nif k % 2 == 0:\n k = k + 1\nelse:\n k = k\nknn = KNeighborsClassifier(n_neighbors=k)\n<mask token>\nlogreg = LogisticRegression(multi_class='auto', solver='liblinear')\n<mask token>\nranfor = RandomForestClassifier(n_estimators=50)\n<mask token>\ndec = DecisionTreeClassifier()\nprint('Skor KNN: ', round(cross_val_score(knn, xtr, ytr, cv=5).mean() * 100\n ), ' %')\nprint('Skor Logistic Regression: ', round(cross_val_score(logreg, xtr, ytr,\n cv=5).mean() * 100), ' %')\nprint('Skor Random Forest: ', round(cross_val_score(ranfor, xtr, ytr, cv=5)\n .mean() * 100), ' %')\nprint('Skor Decision Tree: ', round(cross_val_score(dec, xtr, ytr, cv=5).\n mean() * 100), ' %')\n<mask token>\n",
"step-4": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.model_selection import cross_val_score\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import KFold\ndf = pd.read_csv('data.csv')\ndf = df.fillna(np.NaN)\ndf['Target'] = 0\ndf['Target_name'] = 'Non-Target'\ndf['Target'][(df['Age'] <= 25) & (df['Overall'] >= 80) & (df['Potential'] >=\n 80)] = 1\ndf['Target_name'][(df['Age'] <= 25) & (df['Overall'] >= 80) & (df[\n 'Potential'] >= 80)] = 'Target'\nx = df.loc[:, ['Age', 'Overall', 'Potential']]\ny = df['Target']\nkf = KFold(n_splits=5)\nfor train_index, test_index in kf.split(x):\n xtr = x.iloc[train_index]\n ytr = y[train_index]\n<mask token>\nk = round(len(x) ** 0.5)\nif k % 2 == 0:\n k = k + 1\nelse:\n k = k\nknn = KNeighborsClassifier(n_neighbors=k)\n<mask token>\nlogreg = LogisticRegression(multi_class='auto', solver='liblinear')\n<mask token>\nranfor = RandomForestClassifier(n_estimators=50)\n<mask token>\ndec = DecisionTreeClassifier()\nprint('Skor KNN: ', round(cross_val_score(knn, xtr, ytr, cv=5).mean() * 100\n ), ' %')\nprint('Skor Logistic Regression: ', round(cross_val_score(logreg, xtr, ytr,\n cv=5).mean() * 100), ' %')\nprint('Skor Random Forest: ', round(cross_val_score(ranfor, xtr, ytr, cv=5)\n .mean() * 100), ' %')\nprint('Skor Decision Tree: ', round(cross_val_score(dec, xtr, ytr, cv=5).\n mean() * 100), ' %')\n<mask token>\n",
"step-5": "import numpy as np \r\nimport pandas as pd \r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.ensemble import RandomForestClassifier\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.linear_model import LogisticRegression\r\nfrom sklearn.tree import DecisionTreeClassifier\r\nfrom sklearn.model_selection import cross_val_score\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.model_selection import KFold\r\n\r\ndf=pd.read_csv('data.csv')\r\ndf=df.fillna(np.NaN)\r\n#kita isi df dengan kolom target = 0, target_name = 0 , agar memudahkan untuk training\r\ndf['Target']=0\r\ndf['Target_name']='Non-Target'\r\n# print(df)\r\n#tandai target dengan angka 1,target_name='Target' pada dataframe usia <= 25, overall >= 80, dan potential >= 80 \r\ndf['Target'][(df['Age']<=25)&(df['Overall']>=80)&(df['Potential']>=80)]=1\r\ndf['Target_name'][(df['Age']<=25)&(df['Overall']>=80)&(df['Potential']>=80)]='Target'\r\n\r\nx=df.loc[:,['Age','Overall','Potential']]\r\ny=df['Target']\r\nkf=KFold(n_splits = 5)\r\nfor train_index,test_index in kf.split(x):\r\n xtr=x.iloc[train_index]\r\n ytr=y[train_index]\r\n\r\n'''\r\nKNN\r\nnilai k terbaik atau n terbaik dapat dicari dengan cara sqrt(n_data) lalu pilih yg odd/ganjil\r\ncari len dari data (banyak data) lalu kalikan pangkat setengah\r\n'''\r\nk = round(len(x) ** .5)\r\nif((k%2) == 0):\r\n k=k+1\r\nelse:\r\n k=k\r\nknn=KNeighborsClassifier(n_neighbors=k)\r\n\r\n'''\r\nLogistic Regression\r\n'''\r\nlogreg=LogisticRegression(multi_class='auto',solver='liblinear')\r\n\r\n'''\r\nRandom Forest\r\n'''\r\nranfor=RandomForestClassifier(n_estimators=50)\r\n\r\n'''\r\nDecision Tree\r\n'''\r\ndec=DecisionTreeClassifier()\r\nprint(\"Skor KNN: \",round(cross_val_score(knn,xtr,ytr,cv=5).mean()*100),' %')\r\nprint(\"Skor Logistic Regression: \",round(cross_val_score(logreg,xtr,ytr,cv=5).mean()*100),' %')\r\nprint(\"Skor Random Forest: \",round(cross_val_score(ranfor,xtr,ytr,cv=5).mean()*100),' %')\r\nprint(\"Skor Decision Tree: \",round(cross_val_score(dec,xtr,ytr,cv=5).mean()*100),' %')\r\n\r\n'''\r\nSkor KNN: 96.0 %\r\nSkor Logistic Regression: 97.0 %\r\nSkor Random Forest: 96.0 %\r\nSkor Decision Tree: 93.0 %\r\n'''",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
class TestURLs:
def test_url_1(self):
assert is_url('http://heise.de')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def test_valid_url_https_path(self):
assert is_url('https://heise.de/thi_s&is=difficult')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class TestURLs:
def test_url_1(self):
assert is_url('http://heise.de')
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def test_valid_url_https_path(self):
assert is_url('https://heise.de/thi_s&is=difficult')
def test_invalid_url(self):
assert not is_url('htp://heise.de')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class TestURLs:
def test_url_1(self):
assert is_url('http://heise.de')
def test_valid_url_http(self):
assert is_url('http://heise.de')
def test_valid_url_https(self):
assert is_url('http://heise.de')
def test_valid_url_ftp(self):
assert is_url('http://heise.de')
def test_valid_url_https_path(self):
assert is_url('https://heise.de/thi_s&is=difficult')
def test_invalid_url(self):
assert not is_url('htp://heise.de')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class TestURLs:
def test_url_1(self):
assert is_url('http://heise.de')
def test_valid_url_http(self):
assert is_url('http://heise.de')
def test_valid_url_https(self):
assert is_url('http://heise.de')
def test_valid_url_ftp(self):
assert is_url('http://heise.de')
def test_valid_url_https_path(self):
assert is_url('https://heise.de/thi_s&is=difficult')
def test_invalid_url(self):
assert not is_url('htp://heise.de')
def test_token_introspection():
client_id = environment.get('FLAAT_CLIENT_ID')
client_secret = environment.get('FLAAT_CLIENT_SECRET')
if client_id is None or client_secret is None:
pytest.skip('FLAAT_CLIENT_ID and FLAAT_CLIENT_SECRET are not set')
issuer_config = IssuerConfig.get_from_string(FLAAT_ISS)
assert issuer_config is not None
issuer_config.client_id = client_id
issuer_config.client_secret = client_secret
introspection_info = issuer_config._get_introspected_token_info(FLAAT_AT)
assert introspection_info is not None
<|reserved_special_token_1|>
import pytest
from flaat.issuers import IssuerConfig, is_url
from flaat.test_env import FLAAT_AT, FLAAT_ISS, environment
class TestURLs:
def test_url_1(self):
assert is_url("http://heise.de")
def test_valid_url_http(self):
assert is_url("http://heise.de")
def test_valid_url_https(self):
assert is_url("http://heise.de")
def test_valid_url_ftp(self):
assert is_url("http://heise.de")
def test_valid_url_https_path(self):
assert is_url("https://heise.de/thi_s&is=difficult")
def test_invalid_url(self):
assert not is_url("htp://heise.de")
def test_token_introspection():
client_id = environment.get("FLAAT_CLIENT_ID")
client_secret = environment.get("FLAAT_CLIENT_SECRET")
if client_id is None or client_secret is None: # pragma: no cover
pytest.skip("FLAAT_CLIENT_ID and FLAAT_CLIENT_SECRET are not set")
issuer_config = IssuerConfig.get_from_string(FLAAT_ISS)
assert issuer_config is not None
issuer_config.client_id = client_id
issuer_config.client_secret = client_secret
introspection_info = issuer_config._get_introspected_token_info(FLAAT_AT)
assert introspection_info is not None
|
flexible
|
{
"blob_id": "021f224d031477bd305644261ad4d79d9eca98b3",
"index": 5474,
"step-1": "<mask token>\n\n\nclass TestURLs:\n\n def test_url_1(self):\n assert is_url('http://heise.de')\n <mask token>\n <mask token>\n <mask token>\n\n def test_valid_url_https_path(self):\n assert is_url('https://heise.de/thi_s&is=difficult')\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass TestURLs:\n\n def test_url_1(self):\n assert is_url('http://heise.de')\n <mask token>\n <mask token>\n <mask token>\n\n def test_valid_url_https_path(self):\n assert is_url('https://heise.de/thi_s&is=difficult')\n\n def test_invalid_url(self):\n assert not is_url('htp://heise.de')\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass TestURLs:\n\n def test_url_1(self):\n assert is_url('http://heise.de')\n\n def test_valid_url_http(self):\n assert is_url('http://heise.de')\n\n def test_valid_url_https(self):\n assert is_url('http://heise.de')\n\n def test_valid_url_ftp(self):\n assert is_url('http://heise.de')\n\n def test_valid_url_https_path(self):\n assert is_url('https://heise.de/thi_s&is=difficult')\n\n def test_invalid_url(self):\n assert not is_url('htp://heise.de')\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\nclass TestURLs:\n\n def test_url_1(self):\n assert is_url('http://heise.de')\n\n def test_valid_url_http(self):\n assert is_url('http://heise.de')\n\n def test_valid_url_https(self):\n assert is_url('http://heise.de')\n\n def test_valid_url_ftp(self):\n assert is_url('http://heise.de')\n\n def test_valid_url_https_path(self):\n assert is_url('https://heise.de/thi_s&is=difficult')\n\n def test_invalid_url(self):\n assert not is_url('htp://heise.de')\n\n\ndef test_token_introspection():\n client_id = environment.get('FLAAT_CLIENT_ID')\n client_secret = environment.get('FLAAT_CLIENT_SECRET')\n if client_id is None or client_secret is None:\n pytest.skip('FLAAT_CLIENT_ID and FLAAT_CLIENT_SECRET are not set')\n issuer_config = IssuerConfig.get_from_string(FLAAT_ISS)\n assert issuer_config is not None\n issuer_config.client_id = client_id\n issuer_config.client_secret = client_secret\n introspection_info = issuer_config._get_introspected_token_info(FLAAT_AT)\n assert introspection_info is not None\n",
"step-5": "import pytest\n\nfrom flaat.issuers import IssuerConfig, is_url\nfrom flaat.test_env import FLAAT_AT, FLAAT_ISS, environment\n\n\nclass TestURLs:\n def test_url_1(self):\n assert is_url(\"http://heise.de\")\n\n def test_valid_url_http(self):\n assert is_url(\"http://heise.de\")\n\n def test_valid_url_https(self):\n assert is_url(\"http://heise.de\")\n\n def test_valid_url_ftp(self):\n assert is_url(\"http://heise.de\")\n\n def test_valid_url_https_path(self):\n assert is_url(\"https://heise.de/thi_s&is=difficult\")\n\n def test_invalid_url(self):\n assert not is_url(\"htp://heise.de\")\n\n\ndef test_token_introspection():\n client_id = environment.get(\"FLAAT_CLIENT_ID\")\n client_secret = environment.get(\"FLAAT_CLIENT_SECRET\")\n if client_id is None or client_secret is None: # pragma: no cover\n pytest.skip(\"FLAAT_CLIENT_ID and FLAAT_CLIENT_SECRET are not set\")\n\n issuer_config = IssuerConfig.get_from_string(FLAAT_ISS)\n assert issuer_config is not None\n issuer_config.client_id = client_id\n issuer_config.client_secret = client_secret\n introspection_info = issuer_config._get_introspected_token_info(FLAAT_AT)\n assert introspection_info is not None\n",
"step-ids": [
3,
4,
7,
8,
10
]
}
|
[
3,
4,
7,
8,
10
] |
# encoding: utf-8
# -*- coding: utf-8 -*-
"""
The flask application package.
"""
#parse arguments
from flask import Flask
from flask_cors import CORS
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--testing', action='store_true') #to use the testing database
parser.add_argument('-i', '--init', action='store_true') #to use the testing database
parser.add_argument('-r', '--reinit', action='store_true') #to use the testing database
args = parser.parse_known_args()
#remove arguments to not interfere with unittest
import sys
try:
sys.argv.remove('-t')
except:
pass
try:
sys.argv.remove('--testing')
except:
pass
try:
sys.argv.remove('-i')
except:
pass
try:
sys.argv.remove('--init')
except:
pass
try:
sys.argv.remove('-r')
except:
pass
try:
sys.argv.remove('--reinit')
except:
pass
app = Flask(__name__)
app.config['TOKEN_SECRET'] = 'Secret_Token' #Change this
app.config['SECRET_KEY'] = 'Secret_Key' #Change this
app.config['CORS_HEADERS'] = ['Content-Type', 'Authorization']
app.config['CORS_AUTOMATIC_OPTIONS'] = True
CORS(app)
app.config['TESTING'] = args[0].testing
app.config['INIT'] = args[0].init
app.config['REINIT'] = args[0].reinit
from SmartRecruiting_BackEnd.data import DatabaseManager
dbManager = DatabaseManager()
import SmartRecruiting_BackEnd.api.routes
import SmartRecruiting_BackEnd.data
import SmartRecruiting_BackEnd.deeplearning.preprocess
|
normal
|
{
"blob_id": "e403a84ec2a3104cb908933f6949458cccc791c3",
"index": 4737,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nparser.add_argument('-t', '--testing', action='store_true')\nparser.add_argument('-i', '--init', action='store_true')\nparser.add_argument('-r', '--reinit', action='store_true')\n<mask token>\ntry:\n sys.argv.remove('-t')\nexcept:\n pass\ntry:\n sys.argv.remove('--testing')\nexcept:\n pass\ntry:\n sys.argv.remove('-i')\nexcept:\n pass\ntry:\n sys.argv.remove('--init')\nexcept:\n pass\ntry:\n sys.argv.remove('-r')\nexcept:\n pass\ntry:\n sys.argv.remove('--reinit')\nexcept:\n pass\n<mask token>\nCORS(app)\n<mask token>\n",
"step-3": "<mask token>\nparser = argparse.ArgumentParser()\nparser.add_argument('-t', '--testing', action='store_true')\nparser.add_argument('-i', '--init', action='store_true')\nparser.add_argument('-r', '--reinit', action='store_true')\nargs = parser.parse_known_args()\n<mask token>\ntry:\n sys.argv.remove('-t')\nexcept:\n pass\ntry:\n sys.argv.remove('--testing')\nexcept:\n pass\ntry:\n sys.argv.remove('-i')\nexcept:\n pass\ntry:\n sys.argv.remove('--init')\nexcept:\n pass\ntry:\n sys.argv.remove('-r')\nexcept:\n pass\ntry:\n sys.argv.remove('--reinit')\nexcept:\n pass\napp = Flask(__name__)\napp.config['TOKEN_SECRET'] = 'Secret_Token'\napp.config['SECRET_KEY'] = 'Secret_Key'\napp.config['CORS_HEADERS'] = ['Content-Type', 'Authorization']\napp.config['CORS_AUTOMATIC_OPTIONS'] = True\nCORS(app)\napp.config['TESTING'] = args[0].testing\napp.config['INIT'] = args[0].init\napp.config['REINIT'] = args[0].reinit\n<mask token>\ndbManager = DatabaseManager()\n<mask token>\n",
"step-4": "<mask token>\nfrom flask import Flask\nfrom flask_cors import CORS\nimport argparse\nparser = argparse.ArgumentParser()\nparser.add_argument('-t', '--testing', action='store_true')\nparser.add_argument('-i', '--init', action='store_true')\nparser.add_argument('-r', '--reinit', action='store_true')\nargs = parser.parse_known_args()\nimport sys\ntry:\n sys.argv.remove('-t')\nexcept:\n pass\ntry:\n sys.argv.remove('--testing')\nexcept:\n pass\ntry:\n sys.argv.remove('-i')\nexcept:\n pass\ntry:\n sys.argv.remove('--init')\nexcept:\n pass\ntry:\n sys.argv.remove('-r')\nexcept:\n pass\ntry:\n sys.argv.remove('--reinit')\nexcept:\n pass\napp = Flask(__name__)\napp.config['TOKEN_SECRET'] = 'Secret_Token'\napp.config['SECRET_KEY'] = 'Secret_Key'\napp.config['CORS_HEADERS'] = ['Content-Type', 'Authorization']\napp.config['CORS_AUTOMATIC_OPTIONS'] = True\nCORS(app)\napp.config['TESTING'] = args[0].testing\napp.config['INIT'] = args[0].init\napp.config['REINIT'] = args[0].reinit\nfrom SmartRecruiting_BackEnd.data import DatabaseManager\ndbManager = DatabaseManager()\nimport SmartRecruiting_BackEnd.api.routes\nimport SmartRecruiting_BackEnd.data\nimport SmartRecruiting_BackEnd.deeplearning.preprocess\n",
"step-5": "# encoding: utf-8\n# -*- coding: utf-8 -*-\n\"\"\"\nThe flask application package.\n\"\"\"\n\n#parse arguments\n\nfrom flask import Flask\nfrom flask_cors import CORS\n\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('-t', '--testing', action='store_true') #to use the testing database\nparser.add_argument('-i', '--init', action='store_true') #to use the testing database\nparser.add_argument('-r', '--reinit', action='store_true') #to use the testing database\nargs = parser.parse_known_args()\n\n#remove arguments to not interfere with unittest\nimport sys\ntry:\n sys.argv.remove('-t')\nexcept:\n pass\ntry:\n sys.argv.remove('--testing')\nexcept:\n pass\ntry:\n sys.argv.remove('-i')\nexcept:\n pass\ntry:\n sys.argv.remove('--init')\nexcept:\n pass\ntry:\n sys.argv.remove('-r')\nexcept:\n pass\ntry:\n sys.argv.remove('--reinit')\nexcept:\n pass\n\n\napp = Flask(__name__)\napp.config['TOKEN_SECRET'] = 'Secret_Token' #Change this\napp.config['SECRET_KEY'] = 'Secret_Key' #Change this\napp.config['CORS_HEADERS'] = ['Content-Type', 'Authorization']\napp.config['CORS_AUTOMATIC_OPTIONS'] = True\nCORS(app)\n\napp.config['TESTING'] = args[0].testing\napp.config['INIT'] = args[0].init\napp.config['REINIT'] = args[0].reinit\n\nfrom SmartRecruiting_BackEnd.data import DatabaseManager\ndbManager = DatabaseManager()\n\nimport SmartRecruiting_BackEnd.api.routes\nimport SmartRecruiting_BackEnd.data\nimport SmartRecruiting_BackEnd.deeplearning.preprocess\n\n\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
#Importacion de Dependencias Flask
from flask import Blueprint,Flask, render_template, request,redirect,url_for,flash
#modelado de basedato.
from App import db
# Importacion de modulo de ModeloCliente
from App.Modulos.Proveedor.model import Proveedor
#Inportacion de modulo de formularioCliente
from App.Modulos.Proveedor import form
_Proveedor=Blueprint('Proveedor',__name__,url_prefix='/Proveedor')
@_Proveedor.route('/Proveedor', methods=['GET', 'POST']) # registro de proveedor
def proveedor():
frm = form.Fr_Proveedor(request.form)
if request.method == 'POST':
pr = Proveedor.query.filter_by(CI=frm.CI.data).first()
if frm.validate() and pr is None:
new_user = Proveedor(razonSolcial=frm.RasonSocial.data,
CI=frm.CI.data,
Direccion=frm.Direccion.data,
Correo=frm.Correo.data,
convencional=frm.Convencional.data,
Celular=frm.Celular.data
)
db.session.add(new_user)
db.session.commit()
flash("Se registrado con exito sus datos")
return redirect(url_for('Proveedor.proveedor'))
else:
flash("Error: No se registrado con exito sus Datos")
return render_template('Proveedor/frproveedor.html', frm=frm)
@_Proveedor.route('/listaP') # listado de Proveedores.
def listaP():
titulo = "Lista Proveedor"
return render_template("Proveedor/listaP.html", titulo=titulo, listas=Proveedor.query.all())
@_Proveedor.route('/UpdateP', methods=[ 'POST'])
def UpdateP():
print(request.form)
updateP = Proveedor.query.filter_by(CI=request.form['CI']).first()
print("ci:",updateP.CI)
updateP.razonSolcial = request.form['RasonSocial']
updateP.Direccion = request.form['Direccion']
updateP.Correo = request.form['Correo']
updateP.convencional= request.form['Convencional']
updateP.Celular = request.form['Celular']
db.session.commit()
return redirect(url_for('Proveedor.listaP'))
@_Proveedor.route('/deleteP/<string:id>',methods=['GET','POST'])
def deleteP(id=None):
dlTP = Proveedor.query.filter_by(CI=id).first()
db.session.delete(dlTP)
db.session.commit()
return redirect(url_for('Proveedor.listaP'))
@_Proveedor.route("/modalP")
def modalP():
frm = form.Fr_Proveedor(request.form)
return render_template("modal/modaproveedor.html", frm=frm, title="Proveedor")
|
normal
|
{
"blob_id": "99ecb927e22bc303dd9dffd2793887e7398dbb83",
"index": 3649,
"step-1": "<mask token>\n\n\n@_Proveedor.route('/Proveedor', methods=['GET', 'POST'])\ndef proveedor():\n frm = form.Fr_Proveedor(request.form)\n if request.method == 'POST':\n pr = Proveedor.query.filter_by(CI=frm.CI.data).first()\n if frm.validate() and pr is None:\n new_user = Proveedor(razonSolcial=frm.RasonSocial.data, CI=frm.\n CI.data, Direccion=frm.Direccion.data, Correo=frm.Correo.\n data, convencional=frm.Convencional.data, Celular=frm.\n Celular.data)\n db.session.add(new_user)\n db.session.commit()\n flash('Se registrado con exito sus datos')\n return redirect(url_for('Proveedor.proveedor'))\n else:\n flash('Error: No se registrado con exito sus Datos')\n return render_template('Proveedor/frproveedor.html', frm=frm)\n\n\n<mask token>\n\n\n@_Proveedor.route('/UpdateP', methods=['POST'])\ndef UpdateP():\n print(request.form)\n updateP = Proveedor.query.filter_by(CI=request.form['CI']).first()\n print('ci:', updateP.CI)\n updateP.razonSolcial = request.form['RasonSocial']\n updateP.Direccion = request.form['Direccion']\n updateP.Correo = request.form['Correo']\n updateP.convencional = request.form['Convencional']\n updateP.Celular = request.form['Celular']\n db.session.commit()\n return redirect(url_for('Proveedor.listaP'))\n\n\n<mask token>\n\n\n@_Proveedor.route('/modalP')\ndef modalP():\n frm = form.Fr_Proveedor(request.form)\n return render_template('modal/modaproveedor.html', frm=frm, title=\n 'Proveedor')\n",
"step-2": "<mask token>\n\n\n@_Proveedor.route('/Proveedor', methods=['GET', 'POST'])\ndef proveedor():\n frm = form.Fr_Proveedor(request.form)\n if request.method == 'POST':\n pr = Proveedor.query.filter_by(CI=frm.CI.data).first()\n if frm.validate() and pr is None:\n new_user = Proveedor(razonSolcial=frm.RasonSocial.data, CI=frm.\n CI.data, Direccion=frm.Direccion.data, Correo=frm.Correo.\n data, convencional=frm.Convencional.data, Celular=frm.\n Celular.data)\n db.session.add(new_user)\n db.session.commit()\n flash('Se registrado con exito sus datos')\n return redirect(url_for('Proveedor.proveedor'))\n else:\n flash('Error: No se registrado con exito sus Datos')\n return render_template('Proveedor/frproveedor.html', frm=frm)\n\n\n@_Proveedor.route('/listaP')\ndef listaP():\n titulo = 'Lista Proveedor'\n return render_template('Proveedor/listaP.html', titulo=titulo, listas=\n Proveedor.query.all())\n\n\n@_Proveedor.route('/UpdateP', methods=['POST'])\ndef UpdateP():\n print(request.form)\n updateP = Proveedor.query.filter_by(CI=request.form['CI']).first()\n print('ci:', updateP.CI)\n updateP.razonSolcial = request.form['RasonSocial']\n updateP.Direccion = request.form['Direccion']\n updateP.Correo = request.form['Correo']\n updateP.convencional = request.form['Convencional']\n updateP.Celular = request.form['Celular']\n db.session.commit()\n return redirect(url_for('Proveedor.listaP'))\n\n\n@_Proveedor.route('/deleteP/<string:id>', methods=['GET', 'POST'])\ndef deleteP(id=None):\n dlTP = Proveedor.query.filter_by(CI=id).first()\n db.session.delete(dlTP)\n db.session.commit()\n return redirect(url_for('Proveedor.listaP'))\n\n\n@_Proveedor.route('/modalP')\ndef modalP():\n frm = form.Fr_Proveedor(request.form)\n return render_template('modal/modaproveedor.html', frm=frm, title=\n 'Proveedor')\n",
"step-3": "<mask token>\n_Proveedor = Blueprint('Proveedor', __name__, url_prefix='/Proveedor')\n\n\n@_Proveedor.route('/Proveedor', methods=['GET', 'POST'])\ndef proveedor():\n frm = form.Fr_Proveedor(request.form)\n if request.method == 'POST':\n pr = Proveedor.query.filter_by(CI=frm.CI.data).first()\n if frm.validate() and pr is None:\n new_user = Proveedor(razonSolcial=frm.RasonSocial.data, CI=frm.\n CI.data, Direccion=frm.Direccion.data, Correo=frm.Correo.\n data, convencional=frm.Convencional.data, Celular=frm.\n Celular.data)\n db.session.add(new_user)\n db.session.commit()\n flash('Se registrado con exito sus datos')\n return redirect(url_for('Proveedor.proveedor'))\n else:\n flash('Error: No se registrado con exito sus Datos')\n return render_template('Proveedor/frproveedor.html', frm=frm)\n\n\n@_Proveedor.route('/listaP')\ndef listaP():\n titulo = 'Lista Proveedor'\n return render_template('Proveedor/listaP.html', titulo=titulo, listas=\n Proveedor.query.all())\n\n\n@_Proveedor.route('/UpdateP', methods=['POST'])\ndef UpdateP():\n print(request.form)\n updateP = Proveedor.query.filter_by(CI=request.form['CI']).first()\n print('ci:', updateP.CI)\n updateP.razonSolcial = request.form['RasonSocial']\n updateP.Direccion = request.form['Direccion']\n updateP.Correo = request.form['Correo']\n updateP.convencional = request.form['Convencional']\n updateP.Celular = request.form['Celular']\n db.session.commit()\n return redirect(url_for('Proveedor.listaP'))\n\n\n@_Proveedor.route('/deleteP/<string:id>', methods=['GET', 'POST'])\ndef deleteP(id=None):\n dlTP = Proveedor.query.filter_by(CI=id).first()\n db.session.delete(dlTP)\n db.session.commit()\n return redirect(url_for('Proveedor.listaP'))\n\n\n@_Proveedor.route('/modalP')\ndef modalP():\n frm = form.Fr_Proveedor(request.form)\n return render_template('modal/modaproveedor.html', frm=frm, title=\n 'Proveedor')\n",
"step-4": "from flask import Blueprint, Flask, render_template, request, redirect, url_for, flash\nfrom App import db\nfrom App.Modulos.Proveedor.model import Proveedor\nfrom App.Modulos.Proveedor import form\n_Proveedor = Blueprint('Proveedor', __name__, url_prefix='/Proveedor')\n\n\n@_Proveedor.route('/Proveedor', methods=['GET', 'POST'])\ndef proveedor():\n frm = form.Fr_Proveedor(request.form)\n if request.method == 'POST':\n pr = Proveedor.query.filter_by(CI=frm.CI.data).first()\n if frm.validate() and pr is None:\n new_user = Proveedor(razonSolcial=frm.RasonSocial.data, CI=frm.\n CI.data, Direccion=frm.Direccion.data, Correo=frm.Correo.\n data, convencional=frm.Convencional.data, Celular=frm.\n Celular.data)\n db.session.add(new_user)\n db.session.commit()\n flash('Se registrado con exito sus datos')\n return redirect(url_for('Proveedor.proveedor'))\n else:\n flash('Error: No se registrado con exito sus Datos')\n return render_template('Proveedor/frproveedor.html', frm=frm)\n\n\n@_Proveedor.route('/listaP')\ndef listaP():\n titulo = 'Lista Proveedor'\n return render_template('Proveedor/listaP.html', titulo=titulo, listas=\n Proveedor.query.all())\n\n\n@_Proveedor.route('/UpdateP', methods=['POST'])\ndef UpdateP():\n print(request.form)\n updateP = Proveedor.query.filter_by(CI=request.form['CI']).first()\n print('ci:', updateP.CI)\n updateP.razonSolcial = request.form['RasonSocial']\n updateP.Direccion = request.form['Direccion']\n updateP.Correo = request.form['Correo']\n updateP.convencional = request.form['Convencional']\n updateP.Celular = request.form['Celular']\n db.session.commit()\n return redirect(url_for('Proveedor.listaP'))\n\n\n@_Proveedor.route('/deleteP/<string:id>', methods=['GET', 'POST'])\ndef deleteP(id=None):\n dlTP = Proveedor.query.filter_by(CI=id).first()\n db.session.delete(dlTP)\n db.session.commit()\n return redirect(url_for('Proveedor.listaP'))\n\n\n@_Proveedor.route('/modalP')\ndef modalP():\n frm = form.Fr_Proveedor(request.form)\n return render_template('modal/modaproveedor.html', frm=frm, title=\n 'Proveedor')\n",
"step-5": "#Importacion de Dependencias Flask\nfrom flask import Blueprint,Flask, render_template, request,redirect,url_for,flash\n#modelado de basedato.\nfrom App import db\n# Importacion de modulo de ModeloCliente\nfrom App.Modulos.Proveedor.model import Proveedor\n#Inportacion de modulo de formularioCliente\nfrom App.Modulos.Proveedor import form\n\n_Proveedor=Blueprint('Proveedor',__name__,url_prefix='/Proveedor')\n\n@_Proveedor.route('/Proveedor', methods=['GET', 'POST']) # registro de proveedor\ndef proveedor():\n frm = form.Fr_Proveedor(request.form)\n if request.method == 'POST':\n pr = Proveedor.query.filter_by(CI=frm.CI.data).first()\n if frm.validate() and pr is None:\n new_user = Proveedor(razonSolcial=frm.RasonSocial.data,\n CI=frm.CI.data,\n Direccion=frm.Direccion.data,\n Correo=frm.Correo.data,\n convencional=frm.Convencional.data,\n Celular=frm.Celular.data\n )\n db.session.add(new_user)\n db.session.commit()\n flash(\"Se registrado con exito sus datos\")\n return redirect(url_for('Proveedor.proveedor'))\n else:\n flash(\"Error: No se registrado con exito sus Datos\")\n return render_template('Proveedor/frproveedor.html', frm=frm)\n\n@_Proveedor.route('/listaP') # listado de Proveedores.\ndef listaP():\n titulo = \"Lista Proveedor\"\n return render_template(\"Proveedor/listaP.html\", titulo=titulo, listas=Proveedor.query.all())\n\n@_Proveedor.route('/UpdateP', methods=[ 'POST'])\ndef UpdateP():\n print(request.form)\n\n updateP = Proveedor.query.filter_by(CI=request.form['CI']).first()\n print(\"ci:\",updateP.CI)\n updateP.razonSolcial = request.form['RasonSocial']\n updateP.Direccion = request.form['Direccion']\n updateP.Correo = request.form['Correo']\n updateP.convencional= request.form['Convencional']\n updateP.Celular = request.form['Celular']\n db.session.commit()\n return redirect(url_for('Proveedor.listaP'))\n\n\n@_Proveedor.route('/deleteP/<string:id>',methods=['GET','POST'])\ndef deleteP(id=None):\n dlTP = Proveedor.query.filter_by(CI=id).first()\n db.session.delete(dlTP) \n db.session.commit()\n return redirect(url_for('Proveedor.listaP'))\n\n@_Proveedor.route(\"/modalP\")\ndef modalP():\n frm = form.Fr_Proveedor(request.form)\n return render_template(\"modal/modaproveedor.html\", frm=frm, title=\"Proveedor\")\n\n",
"step-ids": [
3,
5,
6,
7,
8
]
}
|
[
3,
5,
6,
7,
8
] |
<|reserved_special_token_0|>
class PersonInfo(scrapy.Item):
person_id = scrapy.Field()
buy_car = scrapy.Field()
address = scrapy.Field()
class OtherItem(scrapy.Item):
"""
可以定义另外一个item
"""
user_info = scrapy.Field()
main_url = scrapy.Field()
nick_name = scrapy.Field()
heigth = scrapy.Field()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class JiayuanItem(scrapy.Item):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class PersonInfo(scrapy.Item):
person_id = scrapy.Field()
buy_car = scrapy.Field()
address = scrapy.Field()
class OtherItem(scrapy.Item):
"""
可以定义另外一个item
"""
user_info = scrapy.Field()
main_url = scrapy.Field()
nick_name = scrapy.Field()
heigth = scrapy.Field()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class JiayuanItem(scrapy.Item):
person_id = scrapy.Field()
user_info = scrapy.Field()
main_url = scrapy.Field()
nick_name = scrapy.Field()
heigth = scrapy.Field()
class PersonInfo(scrapy.Item):
person_id = scrapy.Field()
buy_car = scrapy.Field()
address = scrapy.Field()
class OtherItem(scrapy.Item):
"""
可以定义另外一个item
"""
user_info = scrapy.Field()
main_url = scrapy.Field()
nick_name = scrapy.Field()
heigth = scrapy.Field()
<|reserved_special_token_1|>
import scrapy
class JiayuanItem(scrapy.Item):
person_id = scrapy.Field()
user_info = scrapy.Field()
main_url = scrapy.Field()
nick_name = scrapy.Field()
heigth = scrapy.Field()
class PersonInfo(scrapy.Item):
person_id = scrapy.Field()
buy_car = scrapy.Field()
address = scrapy.Field()
class OtherItem(scrapy.Item):
"""
可以定义另外一个item
"""
user_info = scrapy.Field()
main_url = scrapy.Field()
nick_name = scrapy.Field()
heigth = scrapy.Field()
<|reserved_special_token_1|>
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class JiayuanItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
person_id = scrapy.Field()#人员唯一ID
user_info = scrapy.Field()#搜索页面中的年龄与所属城市
main_url = scrapy.Field()#搜索页面中人员入口url
nick_name = scrapy.Field()#搜索页面中人员昵称
heigth = scrapy.Field()#搜索页面中身高
class PersonInfo((scrapy.Item)):
#person_info人员信息表
person_id = scrapy.Field()
buy_car = scrapy.Field()
address = scrapy.Field()
class OtherItem(scrapy.Item):
# define the fields for your item here like:
# name = scrapy.Field()
'''
可以定义另外一个item
'''
user_info = scrapy.Field()#搜索页面中的年龄与所属城市
main_url = scrapy.Field()#搜索页面中人员入口url
nick_name = scrapy.Field()#搜索页面中人员昵称
heigth = scrapy.Field()#搜索页面中身高
|
flexible
|
{
"blob_id": "9dbadb2421b04961e8e813831d06abc1ff301566",
"index": 3283,
"step-1": "<mask token>\n\n\nclass PersonInfo(scrapy.Item):\n person_id = scrapy.Field()\n buy_car = scrapy.Field()\n address = scrapy.Field()\n\n\nclass OtherItem(scrapy.Item):\n \"\"\"\n 可以定义另外一个item\n \"\"\"\n user_info = scrapy.Field()\n main_url = scrapy.Field()\n nick_name = scrapy.Field()\n heigth = scrapy.Field()\n",
"step-2": "<mask token>\n\n\nclass JiayuanItem(scrapy.Item):\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass PersonInfo(scrapy.Item):\n person_id = scrapy.Field()\n buy_car = scrapy.Field()\n address = scrapy.Field()\n\n\nclass OtherItem(scrapy.Item):\n \"\"\"\n 可以定义另外一个item\n \"\"\"\n user_info = scrapy.Field()\n main_url = scrapy.Field()\n nick_name = scrapy.Field()\n heigth = scrapy.Field()\n",
"step-3": "<mask token>\n\n\nclass JiayuanItem(scrapy.Item):\n person_id = scrapy.Field()\n user_info = scrapy.Field()\n main_url = scrapy.Field()\n nick_name = scrapy.Field()\n heigth = scrapy.Field()\n\n\nclass PersonInfo(scrapy.Item):\n person_id = scrapy.Field()\n buy_car = scrapy.Field()\n address = scrapy.Field()\n\n\nclass OtherItem(scrapy.Item):\n \"\"\"\n 可以定义另外一个item\n \"\"\"\n user_info = scrapy.Field()\n main_url = scrapy.Field()\n nick_name = scrapy.Field()\n heigth = scrapy.Field()\n",
"step-4": "import scrapy\n\n\nclass JiayuanItem(scrapy.Item):\n person_id = scrapy.Field()\n user_info = scrapy.Field()\n main_url = scrapy.Field()\n nick_name = scrapy.Field()\n heigth = scrapy.Field()\n\n\nclass PersonInfo(scrapy.Item):\n person_id = scrapy.Field()\n buy_car = scrapy.Field()\n address = scrapy.Field()\n\n\nclass OtherItem(scrapy.Item):\n \"\"\"\n 可以定义另外一个item\n \"\"\"\n user_info = scrapy.Field()\n main_url = scrapy.Field()\n nick_name = scrapy.Field()\n heigth = scrapy.Field()\n",
"step-5": "# -*- coding: utf-8 -*-\r\n\r\n# Define here the models for your scraped items\r\n#\r\n# See documentation in:\r\n# https://doc.scrapy.org/en/latest/topics/items.html\r\n\r\nimport scrapy\r\n\r\n\r\nclass JiayuanItem(scrapy.Item):\r\n # define the fields for your item here like:\r\n # name = scrapy.Field()\r\n person_id = scrapy.Field()#人员唯一ID\r\n user_info = scrapy.Field()#搜索页面中的年龄与所属城市\r\n main_url = scrapy.Field()#搜索页面中人员入口url\r\n nick_name = scrapy.Field()#搜索页面中人员昵称\r\n heigth = scrapy.Field()#搜索页面中身高\r\n \r\nclass PersonInfo((scrapy.Item)):\r\n #person_info人员信息表\r\n person_id = scrapy.Field()\r\n buy_car = scrapy.Field()\r\n address = scrapy.Field()\r\n \r\nclass OtherItem(scrapy.Item):\r\n # define the fields for your item here like:\r\n # name = scrapy.Field()\r\n '''\r\n 可以定义另外一个item\r\n '''\r\n user_info = scrapy.Field()#搜索页面中的年龄与所属城市\r\n main_url = scrapy.Field()#搜索页面中人员入口url\r\n nick_name = scrapy.Field()#搜索页面中人员昵称\r\n heigth = scrapy.Field()#搜索页面中身高",
"step-ids": [
5,
6,
7,
8,
9
]
}
|
[
5,
6,
7,
8,
9
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
print('RUNNING ON CPU')
<|reserved_special_token_0|>
assert config.changePrice == True
print(config.config)
<|reserved_special_token_0|>
for t in range(993, 4592):
broker, totalOrders = broker_funcs.thresholdBrokerage(traderIDs, t,
broker, totalOrders)
broker, transactions = broker_funcs.instantMatch(traderIDs, broker,
transactions)
portfolio.priceChange(time=t)
print('New threshold 500', t)
<|reserved_special_token_0|>
with open('./results/traderIDs_500_newthreshold' + '.pkl', 'wb') as f:
pickle.dump(traderIDs, f, pickle.HIGHEST_PROTOCOL)
print('CPU RUN TIME | nportfs: ', config.nportfs)
print(t0str)
print(t1str)
<|reserved_special_token_0|>
transactions.to_csv('./results/transactions_500_newthreshold.csv')
totalOrders.to_csv('./results/totalOrders_500_newthreshold.csv')
np.save('./results/stockPool_500_newthreshold.npy', TstockPool)
np.save('./results/hurstPool_500_newthreshold.npy', ThurstPool)
<|reserved_special_token_0|>
conf.write(str(config.config))
conf.close()
<|reserved_special_token_1|>
print('RUNNING ON CPU')
<|reserved_special_token_0|>
assert config.changePrice == True
print(config.config)
t0 = time.localtime()
t0str = time.strftime('%H:%M:%S', t0)
traderIDs = portfolio.portfGen()
transactions = pd.DataFrame()
totalOrders = pd.DataFrame()
broker = pd.DataFrame()
for t in range(993, 4592):
broker, totalOrders = broker_funcs.thresholdBrokerage(traderIDs, t,
broker, totalOrders)
broker, transactions = broker_funcs.instantMatch(traderIDs, broker,
transactions)
portfolio.priceChange(time=t)
print('New threshold 500', t)
t1 = time.localtime()
t1str = time.strftime('%H:%M:%S', t1)
with open('./results/traderIDs_500_newthreshold' + '.pkl', 'wb') as f:
pickle.dump(traderIDs, f, pickle.HIGHEST_PROTOCOL)
print('CPU RUN TIME | nportfs: ', config.nportfs)
print(t0str)
print(t1str)
TstockPool, ThurstPool = portfolio.stockChars()
transactions.to_csv('./results/transactions_500_newthreshold.csv')
totalOrders.to_csv('./results/totalOrders_500_newthreshold.csv')
np.save('./results/stockPool_500_newthreshold.npy', TstockPool)
np.save('./results/hurstPool_500_newthreshold.npy', ThurstPool)
conf = open('./results/config_500_newthresholded' + '.txt', 'w')
conf.write(str(config.config))
conf.close()
<|reserved_special_token_1|>
print('RUNNING ON CPU')
from library import config, utils, broker_funcs, portfolio
import numpy as np
import pandas as pd
from fbm.fbmlib import fbm
import time
import pickle
assert config.changePrice == True
print(config.config)
t0 = time.localtime()
t0str = time.strftime('%H:%M:%S', t0)
traderIDs = portfolio.portfGen()
transactions = pd.DataFrame()
totalOrders = pd.DataFrame()
broker = pd.DataFrame()
for t in range(993, 4592):
broker, totalOrders = broker_funcs.thresholdBrokerage(traderIDs, t,
broker, totalOrders)
broker, transactions = broker_funcs.instantMatch(traderIDs, broker,
transactions)
portfolio.priceChange(time=t)
print('New threshold 500', t)
t1 = time.localtime()
t1str = time.strftime('%H:%M:%S', t1)
with open('./results/traderIDs_500_newthreshold' + '.pkl', 'wb') as f:
pickle.dump(traderIDs, f, pickle.HIGHEST_PROTOCOL)
print('CPU RUN TIME | nportfs: ', config.nportfs)
print(t0str)
print(t1str)
TstockPool, ThurstPool = portfolio.stockChars()
transactions.to_csv('./results/transactions_500_newthreshold.csv')
totalOrders.to_csv('./results/totalOrders_500_newthreshold.csv')
np.save('./results/stockPool_500_newthreshold.npy', TstockPool)
np.save('./results/hurstPool_500_newthreshold.npy', ThurstPool)
conf = open('./results/config_500_newthresholded' + '.txt', 'w')
conf.write(str(config.config))
conf.close()
<|reserved_special_token_1|>
print("RUNNING ON CPU")
from library import config, utils, broker_funcs, portfolio
import numpy as np
import pandas as pd
# import matplotlib.pyplot as plt
from fbm.fbmlib import fbm
import time
import pickle
assert config.changePrice == True
print(config.config)
t0 = time.localtime()
t0str = time.strftime("%H:%M:%S",t0)
traderIDs = portfolio.portfGen()
transactions = pd.DataFrame()
totalOrders = pd.DataFrame()
broker = pd.DataFrame()
for t in range(993,4592):
broker, totalOrders = broker_funcs.thresholdBrokerage(traderIDs, t, broker, totalOrders)
broker, transactions = broker_funcs.instantMatch(traderIDs, broker, transactions)
portfolio.priceChange(time=t)
print("New threshold 500", t)
# with open('./results/traderIDs_cpu_nothreshold' + '.pkl', 'wb') as f:
# pickle.dump(traderIDs, f, pickle.HIGHEST_PROTOCOL)
# Ttransactions = pd.DataFrame()
# TtotalOrders = pd.DataFrame()
# Tbroker = pd.DataFrame()
# for key,portf in traderIDs.items():
# portf.reset(ptile=70)
# for t in range (993,4592):
# Tbroker, TtotalOrders = broker_funcs.thresholdBrokerage(traderIDs, t, Tbroker, TtotalOrders)
# Tbroker, Ttransactions = broker_funcs.instantMatch(traderIDs, Tbroker, Ttransactions)
# portfolio.priceChange(time=t)
# print(t)
t1 = time.localtime()
t1str = time.strftime("%H:%M:%S",t1)
with open('./results/traderIDs_500_newthreshold' + '.pkl', 'wb') as f:
pickle.dump(traderIDs, f, pickle.HIGHEST_PROTOCOL)
print("CPU RUN TIME | nportfs: ", config.nportfs)
print(t0str)
print(t1str)
TstockPool, ThurstPool = portfolio.stockChars()
transactions.to_csv('./results/transactions_500_newthreshold.csv')
totalOrders.to_csv('./results/totalOrders_500_newthreshold.csv')
np.save('./results/stockPool_500_newthreshold.npy',TstockPool)
np.save('./results/hurstPool_500_newthreshold.npy',ThurstPool)
conf = open('./results/config_500_newthresholded' + '.txt',"w")
conf.write(str(config.config))
conf.close()
|
flexible
|
{
"blob_id": "21aee78e8cbb1ca150bca880e79dc0d84326e2d4",
"index": 4162,
"step-1": "<mask token>\n",
"step-2": "print('RUNNING ON CPU')\n<mask token>\nassert config.changePrice == True\nprint(config.config)\n<mask token>\nfor t in range(993, 4592):\n broker, totalOrders = broker_funcs.thresholdBrokerage(traderIDs, t,\n broker, totalOrders)\n broker, transactions = broker_funcs.instantMatch(traderIDs, broker,\n transactions)\n portfolio.priceChange(time=t)\n print('New threshold 500', t)\n<mask token>\nwith open('./results/traderIDs_500_newthreshold' + '.pkl', 'wb') as f:\n pickle.dump(traderIDs, f, pickle.HIGHEST_PROTOCOL)\nprint('CPU RUN TIME | nportfs: ', config.nportfs)\nprint(t0str)\nprint(t1str)\n<mask token>\ntransactions.to_csv('./results/transactions_500_newthreshold.csv')\ntotalOrders.to_csv('./results/totalOrders_500_newthreshold.csv')\nnp.save('./results/stockPool_500_newthreshold.npy', TstockPool)\nnp.save('./results/hurstPool_500_newthreshold.npy', ThurstPool)\n<mask token>\nconf.write(str(config.config))\nconf.close()\n",
"step-3": "print('RUNNING ON CPU')\n<mask token>\nassert config.changePrice == True\nprint(config.config)\nt0 = time.localtime()\nt0str = time.strftime('%H:%M:%S', t0)\ntraderIDs = portfolio.portfGen()\ntransactions = pd.DataFrame()\ntotalOrders = pd.DataFrame()\nbroker = pd.DataFrame()\nfor t in range(993, 4592):\n broker, totalOrders = broker_funcs.thresholdBrokerage(traderIDs, t,\n broker, totalOrders)\n broker, transactions = broker_funcs.instantMatch(traderIDs, broker,\n transactions)\n portfolio.priceChange(time=t)\n print('New threshold 500', t)\nt1 = time.localtime()\nt1str = time.strftime('%H:%M:%S', t1)\nwith open('./results/traderIDs_500_newthreshold' + '.pkl', 'wb') as f:\n pickle.dump(traderIDs, f, pickle.HIGHEST_PROTOCOL)\nprint('CPU RUN TIME | nportfs: ', config.nportfs)\nprint(t0str)\nprint(t1str)\nTstockPool, ThurstPool = portfolio.stockChars()\ntransactions.to_csv('./results/transactions_500_newthreshold.csv')\ntotalOrders.to_csv('./results/totalOrders_500_newthreshold.csv')\nnp.save('./results/stockPool_500_newthreshold.npy', TstockPool)\nnp.save('./results/hurstPool_500_newthreshold.npy', ThurstPool)\nconf = open('./results/config_500_newthresholded' + '.txt', 'w')\nconf.write(str(config.config))\nconf.close()\n",
"step-4": "print('RUNNING ON CPU')\nfrom library import config, utils, broker_funcs, portfolio\nimport numpy as np\nimport pandas as pd\nfrom fbm.fbmlib import fbm\nimport time\nimport pickle\nassert config.changePrice == True\nprint(config.config)\nt0 = time.localtime()\nt0str = time.strftime('%H:%M:%S', t0)\ntraderIDs = portfolio.portfGen()\ntransactions = pd.DataFrame()\ntotalOrders = pd.DataFrame()\nbroker = pd.DataFrame()\nfor t in range(993, 4592):\n broker, totalOrders = broker_funcs.thresholdBrokerage(traderIDs, t,\n broker, totalOrders)\n broker, transactions = broker_funcs.instantMatch(traderIDs, broker,\n transactions)\n portfolio.priceChange(time=t)\n print('New threshold 500', t)\nt1 = time.localtime()\nt1str = time.strftime('%H:%M:%S', t1)\nwith open('./results/traderIDs_500_newthreshold' + '.pkl', 'wb') as f:\n pickle.dump(traderIDs, f, pickle.HIGHEST_PROTOCOL)\nprint('CPU RUN TIME | nportfs: ', config.nportfs)\nprint(t0str)\nprint(t1str)\nTstockPool, ThurstPool = portfolio.stockChars()\ntransactions.to_csv('./results/transactions_500_newthreshold.csv')\ntotalOrders.to_csv('./results/totalOrders_500_newthreshold.csv')\nnp.save('./results/stockPool_500_newthreshold.npy', TstockPool)\nnp.save('./results/hurstPool_500_newthreshold.npy', ThurstPool)\nconf = open('./results/config_500_newthresholded' + '.txt', 'w')\nconf.write(str(config.config))\nconf.close()\n",
"step-5": "print(\"RUNNING ON CPU\")\nfrom library import config, utils, broker_funcs, portfolio\nimport numpy as np\nimport pandas as pd\n# import matplotlib.pyplot as plt\nfrom fbm.fbmlib import fbm\nimport time\nimport pickle\n\nassert config.changePrice == True\n\nprint(config.config)\n\nt0 = time.localtime()\nt0str = time.strftime(\"%H:%M:%S\",t0)\n\n\ntraderIDs = portfolio.portfGen()\n\ntransactions = pd.DataFrame()\ntotalOrders = pd.DataFrame()\nbroker = pd.DataFrame()\n\nfor t in range(993,4592):\n broker, totalOrders = broker_funcs.thresholdBrokerage(traderIDs, t, broker, totalOrders)\n broker, transactions = broker_funcs.instantMatch(traderIDs, broker, transactions)\n portfolio.priceChange(time=t)\n print(\"New threshold 500\", t)\n\n# with open('./results/traderIDs_cpu_nothreshold' + '.pkl', 'wb') as f:\n# pickle.dump(traderIDs, f, pickle.HIGHEST_PROTOCOL)\n\n# Ttransactions = pd.DataFrame()\n# TtotalOrders = pd.DataFrame()\n# Tbroker = pd.DataFrame()\n\n# for key,portf in traderIDs.items():\n# portf.reset(ptile=70)\n\n# for t in range (993,4592):\n# Tbroker, TtotalOrders = broker_funcs.thresholdBrokerage(traderIDs, t, Tbroker, TtotalOrders)\n# Tbroker, Ttransactions = broker_funcs.instantMatch(traderIDs, Tbroker, Ttransactions)\n# portfolio.priceChange(time=t)\n# print(t)\n\n\nt1 = time.localtime()\nt1str = time.strftime(\"%H:%M:%S\",t1)\n\n\n\nwith open('./results/traderIDs_500_newthreshold' + '.pkl', 'wb') as f:\n pickle.dump(traderIDs, f, pickle.HIGHEST_PROTOCOL)\n\nprint(\"CPU RUN TIME | nportfs: \", config.nportfs)\nprint(t0str)\nprint(t1str)\n\nTstockPool, ThurstPool = portfolio.stockChars()\n\ntransactions.to_csv('./results/transactions_500_newthreshold.csv')\ntotalOrders.to_csv('./results/totalOrders_500_newthreshold.csv')\nnp.save('./results/stockPool_500_newthreshold.npy',TstockPool)\nnp.save('./results/hurstPool_500_newthreshold.npy',ThurstPool)\nconf = open('./results/config_500_newthresholded' + '.txt',\"w\")\nconf.write(str(config.config))\nconf.close()",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import urllib.request
from bs4 import BeautifulSoup
def getTitlesFromAll(amount, rating='all'):
output = ''
for i in range(1, amount+1):
try:
if rating == 'all':
html = urllib.request.urlopen('https://habr.com/all/page'+ str(i) +'/').read()
else:
html = urllib.request.urlopen('https://habr.com/all/'+ rating +'/page'+ str(i) +'/').read()
except urllib.error.HTTPError:
print('Error 404 Not Found')
break
soup = BeautifulSoup(html, 'html.parser')
title = soup.find_all('a', class_ = 'post__title_link')
for i in title:
i = i.get_text()
output += ('- "'+i+'",\n')
return output
def getTitlesFromTop(amount, age='daily'):
output = ''
for i in range(1, amount+1):
try:
html = urllib.request.urlopen('https://habr.com/top/'+ age +'/page'+ str(i) +'/').read()
except urllib.error.HTTPError:
print('Error 404 Not Found')
break
soup = BeautifulSoup(html, 'html.parser')
title = soup.find_all('a', class_ = 'post__title_link')
for i in title:
i = i.get_text()
output += ('- "'+i+'",\n')
return output
|
normal
|
{
"blob_id": "d6cfea95c76021bdbfbb4471878c653564c9accd",
"index": 1816,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef getTitlesFromAll(amount, rating='all'):\n output = ''\n for i in range(1, amount + 1):\n try:\n if rating == 'all':\n html = urllib.request.urlopen('https://habr.com/all/page' +\n str(i) + '/').read()\n else:\n html = urllib.request.urlopen('https://habr.com/all/' +\n rating + '/page' + str(i) + '/').read()\n except urllib.error.HTTPError:\n print('Error 404 Not Found')\n break\n soup = BeautifulSoup(html, 'html.parser')\n title = soup.find_all('a', class_='post__title_link')\n for i in title:\n i = i.get_text()\n output += '- \"' + i + '\",\\n'\n return output\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef getTitlesFromAll(amount, rating='all'):\n output = ''\n for i in range(1, amount + 1):\n try:\n if rating == 'all':\n html = urllib.request.urlopen('https://habr.com/all/page' +\n str(i) + '/').read()\n else:\n html = urllib.request.urlopen('https://habr.com/all/' +\n rating + '/page' + str(i) + '/').read()\n except urllib.error.HTTPError:\n print('Error 404 Not Found')\n break\n soup = BeautifulSoup(html, 'html.parser')\n title = soup.find_all('a', class_='post__title_link')\n for i in title:\n i = i.get_text()\n output += '- \"' + i + '\",\\n'\n return output\n\n\ndef getTitlesFromTop(amount, age='daily'):\n output = ''\n for i in range(1, amount + 1):\n try:\n html = urllib.request.urlopen('https://habr.com/top/' + age +\n '/page' + str(i) + '/').read()\n except urllib.error.HTTPError:\n print('Error 404 Not Found')\n break\n soup = BeautifulSoup(html, 'html.parser')\n title = soup.find_all('a', class_='post__title_link')\n for i in title:\n i = i.get_text()\n output += '- \"' + i + '\",\\n'\n return output\n",
"step-4": "import urllib.request\nfrom bs4 import BeautifulSoup\n\n\ndef getTitlesFromAll(amount, rating='all'):\n output = ''\n for i in range(1, amount + 1):\n try:\n if rating == 'all':\n html = urllib.request.urlopen('https://habr.com/all/page' +\n str(i) + '/').read()\n else:\n html = urllib.request.urlopen('https://habr.com/all/' +\n rating + '/page' + str(i) + '/').read()\n except urllib.error.HTTPError:\n print('Error 404 Not Found')\n break\n soup = BeautifulSoup(html, 'html.parser')\n title = soup.find_all('a', class_='post__title_link')\n for i in title:\n i = i.get_text()\n output += '- \"' + i + '\",\\n'\n return output\n\n\ndef getTitlesFromTop(amount, age='daily'):\n output = ''\n for i in range(1, amount + 1):\n try:\n html = urllib.request.urlopen('https://habr.com/top/' + age +\n '/page' + str(i) + '/').read()\n except urllib.error.HTTPError:\n print('Error 404 Not Found')\n break\n soup = BeautifulSoup(html, 'html.parser')\n title = soup.find_all('a', class_='post__title_link')\n for i in title:\n i = i.get_text()\n output += '- \"' + i + '\",\\n'\n return output\n",
"step-5": "import urllib.request\nfrom bs4 import BeautifulSoup\n\ndef getTitlesFromAll(amount, rating='all'):\n output = ''\n for i in range(1, amount+1):\n try:\n if rating == 'all':\n html = urllib.request.urlopen('https://habr.com/all/page'+ str(i) +'/').read()\n else:\n html = urllib.request.urlopen('https://habr.com/all/'+ rating +'/page'+ str(i) +'/').read()\n except urllib.error.HTTPError:\n print('Error 404 Not Found')\n break\n soup = BeautifulSoup(html, 'html.parser')\n title = soup.find_all('a', class_ = 'post__title_link')\n for i in title:\n i = i.get_text()\n output += ('- \"'+i+'\",\\n')\n return output\n\ndef getTitlesFromTop(amount, age='daily'):\n output = ''\n for i in range(1, amount+1):\n try:\n html = urllib.request.urlopen('https://habr.com/top/'+ age +'/page'+ str(i) +'/').read()\n except urllib.error.HTTPError:\n print('Error 404 Not Found')\n break\n soup = BeautifulSoup(html, 'html.parser')\n title = soup.find_all('a', class_ = 'post__title_link')\n for i in title:\n i = i.get_text()\n output += ('- \"'+i+'\",\\n')\n return output\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
def AnalyzeFrames(vidpath):
print('\nGetting video info & writing out image files for each frame...\n')
vidObj = cv2.VideoCapture(vidpath)
fps = vidObj.get(cv2.CAP_PROP_FPS)
print('Frames per second: {0}\n'.format(fps))
count = 0
jpeglist = []
success = 1
while success:
success, frame = vidObj.read()
cv2.imwrite('frame{0}.jpg'.format(count), frame)
jpeglist.append('frame{0}.jpg'.format(count))
count += 1
vidObj.release()
print('Total number of frames: {0}\n'.format(count))
print('Video duration in seconds: {0}\n'.format(round(count / fps)))
print('Analyzing visual edges and writing output file...\n')
for jpeg in jpeglist[0:193]:
img = cv2.imread(imgpath + jpeg, 0)
edges = cv2.Canny(img, 100, 200)
n_pix = np.sum(edges > -1)
n_white_pix = np.sum(edges == 255)
prop_edge_pix = float(n_white_pix / n_pix)
edge_outfile.write('{0},{1}\n'.format(jpeg, prop_edge_pix))
print('Done! Check your output file: edge_outfile.csv')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
edge_outfile.write('frame,prop_edge_pix\n')
def AnalyzeFrames(vidpath):
print('\nGetting video info & writing out image files for each frame...\n')
vidObj = cv2.VideoCapture(vidpath)
fps = vidObj.get(cv2.CAP_PROP_FPS)
print('Frames per second: {0}\n'.format(fps))
count = 0
jpeglist = []
success = 1
while success:
success, frame = vidObj.read()
cv2.imwrite('frame{0}.jpg'.format(count), frame)
jpeglist.append('frame{0}.jpg'.format(count))
count += 1
vidObj.release()
print('Total number of frames: {0}\n'.format(count))
print('Video duration in seconds: {0}\n'.format(round(count / fps)))
print('Analyzing visual edges and writing output file...\n')
for jpeg in jpeglist[0:193]:
img = cv2.imread(imgpath + jpeg, 0)
edges = cv2.Canny(img, 100, 200)
n_pix = np.sum(edges > -1)
n_white_pix = np.sum(edges == 255)
prop_edge_pix = float(n_white_pix / n_pix)
edge_outfile.write('{0},{1}\n'.format(jpeg, prop_edge_pix))
print('Done! Check your output file: edge_outfile.csv')
if __name__ == '__main__':
AnalyzeFrames(vidpath)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
vidpath = '/Users/zreagh/Desktop/edge_vector_analysis/test.mov'
imgpath = '/Users/zreagh/Desktop/edge_vector_analysis/'
edge_outfile = open('edge_outfile.csv', 'w')
edge_outfile.write('frame,prop_edge_pix\n')
def AnalyzeFrames(vidpath):
print('\nGetting video info & writing out image files for each frame...\n')
vidObj = cv2.VideoCapture(vidpath)
fps = vidObj.get(cv2.CAP_PROP_FPS)
print('Frames per second: {0}\n'.format(fps))
count = 0
jpeglist = []
success = 1
while success:
success, frame = vidObj.read()
cv2.imwrite('frame{0}.jpg'.format(count), frame)
jpeglist.append('frame{0}.jpg'.format(count))
count += 1
vidObj.release()
print('Total number of frames: {0}\n'.format(count))
print('Video duration in seconds: {0}\n'.format(round(count / fps)))
print('Analyzing visual edges and writing output file...\n')
for jpeg in jpeglist[0:193]:
img = cv2.imread(imgpath + jpeg, 0)
edges = cv2.Canny(img, 100, 200)
n_pix = np.sum(edges > -1)
n_white_pix = np.sum(edges == 255)
prop_edge_pix = float(n_white_pix / n_pix)
edge_outfile.write('{0},{1}\n'.format(jpeg, prop_edge_pix))
print('Done! Check your output file: edge_outfile.csv')
if __name__ == '__main__':
AnalyzeFrames(vidpath)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
import cv2
import numpy as np
vidpath = '/Users/zreagh/Desktop/edge_vector_analysis/test.mov'
imgpath = '/Users/zreagh/Desktop/edge_vector_analysis/'
edge_outfile = open('edge_outfile.csv', 'w')
edge_outfile.write('frame,prop_edge_pix\n')
def AnalyzeFrames(vidpath):
print('\nGetting video info & writing out image files for each frame...\n')
vidObj = cv2.VideoCapture(vidpath)
fps = vidObj.get(cv2.CAP_PROP_FPS)
print('Frames per second: {0}\n'.format(fps))
count = 0
jpeglist = []
success = 1
while success:
success, frame = vidObj.read()
cv2.imwrite('frame{0}.jpg'.format(count), frame)
jpeglist.append('frame{0}.jpg'.format(count))
count += 1
vidObj.release()
print('Total number of frames: {0}\n'.format(count))
print('Video duration in seconds: {0}\n'.format(round(count / fps)))
print('Analyzing visual edges and writing output file...\n')
for jpeg in jpeglist[0:193]:
img = cv2.imread(imgpath + jpeg, 0)
edges = cv2.Canny(img, 100, 200)
n_pix = np.sum(edges > -1)
n_white_pix = np.sum(edges == 255)
prop_edge_pix = float(n_white_pix / n_pix)
edge_outfile.write('{0},{1}\n'.format(jpeg, prop_edge_pix))
print('Done! Check your output file: edge_outfile.csv')
if __name__ == '__main__':
AnalyzeFrames(vidpath)
<|reserved_special_token_1|>
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This script reads in video information frame-by-frame, and then calculates
visual edge information for each frame, storing the information in a vector.
This can be averaged within TRs in an fMRI analysis to 'regress out'
high-frequency visual information in the video.
@author: zreagh
"""
import cv2
import numpy as np
# Can uncomment this pyplot import for frame plotting - see below
#from matplotlib import pyplot as plt
# Define the paths to your video file and eventual JPEG image files
vidpath = '/Users/zreagh/Desktop/edge_vector_analysis/test.mov'
imgpath = '/Users/zreagh/Desktop/edge_vector_analysis/'
edge_outfile = open('edge_outfile.csv','w')
edge_outfile.write('frame,prop_edge_pix\n')
# Function to extract video info including frames
def AnalyzeFrames(vidpath):
print("\nGetting video info & writing out image files for each frame...\n")
# Path to video file
vidObj = cv2.VideoCapture(vidpath)
# Get FPS
fps = vidObj.get(cv2.CAP_PROP_FPS)
print("Frames per second: {0}\n".format(fps))
# Used as counter variable
count = 0
# Create an empty list to be filled with image names for calculations below
jpeglist = []
# Checks whether frames were extracted
success = 1
# Make sure vidObj call is read
while success:
# Function extract frames
success, frame = vidObj.read()
# Saves the frames indexed with frame number as jpeg frames
cv2.imwrite("frame{0}.jpg".format(count), frame)
# Iteratively fill our list to be called in frame analyses below
jpeglist.append("frame{0}.jpg".format(count))
# Tick up our counter with each frame
count += 1
# Drop the video from the buffer
vidObj.release()
# Print some useful info to the console
print('Total number of frames: {0}\n'.format(count))
print('Video duration in seconds: {0}\n'.format(round(count/fps)))
# Loop through the images and do edge calculations
# NOTE: I am constraining to range 0:193 here because my 193rd image is
# empty for some reason. You can probably delete this for your purposes
# so that it reads "for jpeg in jpeglist:" instead!
print("Analyzing visual edges and writing output file...\n")
for jpeg in jpeglist[0:193]:
img = cv2.imread(imgpath + jpeg,0)
edges = cv2.Canny(img,100,200)
# Get the total number of pixels for each image
n_pix = np.sum(edges > -1)
# Get the proportion of white (edge) pixels for each image
n_white_pix = np.sum(edges == 255)
# Calculate the proportion of edge pixels (white/total) for each image
prop_edge_pix = float(n_white_pix/n_pix)
edge_outfile.write('{0},{1}\n'.format(jpeg,prop_edge_pix))
# Prints out relevant calculations above for each image - uncomment to
# debug or peek under the hood
# print('\nFrame image:', jpeg)
# print('Total number of pixels:', n_pix)
# print('Number of white pixels:', n_white_pix)
# print('Proportion of edge pixels:', prop_edge_pix)
# Plot each raw frame and edge frame side-by-side - uncomment to
# peek under the hood (will slow things down a bunch FYI)
# plt.subplot(121),plt.imshow(img,cmap = 'gray')
# plt.title('Original Image'), plt.xticks([]), plt.yticks([])
# plt.subplot(122),plt.imshow(edges,cmap = 'gray')
# plt.title('Edge Image'), plt.xticks([]), plt.yticks([])
# plt.show()
print("Done! Check your output file: edge_outfile.csv")
# Do the damn thing
if __name__ == '__main__':
# Calling the function
AnalyzeFrames(vidpath)
|
flexible
|
{
"blob_id": "d70d3d8eef711441ac89c2d98c72a5f95e0ab20d",
"index": 5261,
"step-1": "<mask token>\n\n\ndef AnalyzeFrames(vidpath):\n print('\\nGetting video info & writing out image files for each frame...\\n')\n vidObj = cv2.VideoCapture(vidpath)\n fps = vidObj.get(cv2.CAP_PROP_FPS)\n print('Frames per second: {0}\\n'.format(fps))\n count = 0\n jpeglist = []\n success = 1\n while success:\n success, frame = vidObj.read()\n cv2.imwrite('frame{0}.jpg'.format(count), frame)\n jpeglist.append('frame{0}.jpg'.format(count))\n count += 1\n vidObj.release()\n print('Total number of frames: {0}\\n'.format(count))\n print('Video duration in seconds: {0}\\n'.format(round(count / fps)))\n print('Analyzing visual edges and writing output file...\\n')\n for jpeg in jpeglist[0:193]:\n img = cv2.imread(imgpath + jpeg, 0)\n edges = cv2.Canny(img, 100, 200)\n n_pix = np.sum(edges > -1)\n n_white_pix = np.sum(edges == 255)\n prop_edge_pix = float(n_white_pix / n_pix)\n edge_outfile.write('{0},{1}\\n'.format(jpeg, prop_edge_pix))\n print('Done! Check your output file: edge_outfile.csv')\n\n\n<mask token>\n",
"step-2": "<mask token>\nedge_outfile.write('frame,prop_edge_pix\\n')\n\n\ndef AnalyzeFrames(vidpath):\n print('\\nGetting video info & writing out image files for each frame...\\n')\n vidObj = cv2.VideoCapture(vidpath)\n fps = vidObj.get(cv2.CAP_PROP_FPS)\n print('Frames per second: {0}\\n'.format(fps))\n count = 0\n jpeglist = []\n success = 1\n while success:\n success, frame = vidObj.read()\n cv2.imwrite('frame{0}.jpg'.format(count), frame)\n jpeglist.append('frame{0}.jpg'.format(count))\n count += 1\n vidObj.release()\n print('Total number of frames: {0}\\n'.format(count))\n print('Video duration in seconds: {0}\\n'.format(round(count / fps)))\n print('Analyzing visual edges and writing output file...\\n')\n for jpeg in jpeglist[0:193]:\n img = cv2.imread(imgpath + jpeg, 0)\n edges = cv2.Canny(img, 100, 200)\n n_pix = np.sum(edges > -1)\n n_white_pix = np.sum(edges == 255)\n prop_edge_pix = float(n_white_pix / n_pix)\n edge_outfile.write('{0},{1}\\n'.format(jpeg, prop_edge_pix))\n print('Done! Check your output file: edge_outfile.csv')\n\n\nif __name__ == '__main__':\n AnalyzeFrames(vidpath)\n",
"step-3": "<mask token>\nvidpath = '/Users/zreagh/Desktop/edge_vector_analysis/test.mov'\nimgpath = '/Users/zreagh/Desktop/edge_vector_analysis/'\nedge_outfile = open('edge_outfile.csv', 'w')\nedge_outfile.write('frame,prop_edge_pix\\n')\n\n\ndef AnalyzeFrames(vidpath):\n print('\\nGetting video info & writing out image files for each frame...\\n')\n vidObj = cv2.VideoCapture(vidpath)\n fps = vidObj.get(cv2.CAP_PROP_FPS)\n print('Frames per second: {0}\\n'.format(fps))\n count = 0\n jpeglist = []\n success = 1\n while success:\n success, frame = vidObj.read()\n cv2.imwrite('frame{0}.jpg'.format(count), frame)\n jpeglist.append('frame{0}.jpg'.format(count))\n count += 1\n vidObj.release()\n print('Total number of frames: {0}\\n'.format(count))\n print('Video duration in seconds: {0}\\n'.format(round(count / fps)))\n print('Analyzing visual edges and writing output file...\\n')\n for jpeg in jpeglist[0:193]:\n img = cv2.imread(imgpath + jpeg, 0)\n edges = cv2.Canny(img, 100, 200)\n n_pix = np.sum(edges > -1)\n n_white_pix = np.sum(edges == 255)\n prop_edge_pix = float(n_white_pix / n_pix)\n edge_outfile.write('{0},{1}\\n'.format(jpeg, prop_edge_pix))\n print('Done! Check your output file: edge_outfile.csv')\n\n\nif __name__ == '__main__':\n AnalyzeFrames(vidpath)\n",
"step-4": "<mask token>\nimport cv2\nimport numpy as np\nvidpath = '/Users/zreagh/Desktop/edge_vector_analysis/test.mov'\nimgpath = '/Users/zreagh/Desktop/edge_vector_analysis/'\nedge_outfile = open('edge_outfile.csv', 'w')\nedge_outfile.write('frame,prop_edge_pix\\n')\n\n\ndef AnalyzeFrames(vidpath):\n print('\\nGetting video info & writing out image files for each frame...\\n')\n vidObj = cv2.VideoCapture(vidpath)\n fps = vidObj.get(cv2.CAP_PROP_FPS)\n print('Frames per second: {0}\\n'.format(fps))\n count = 0\n jpeglist = []\n success = 1\n while success:\n success, frame = vidObj.read()\n cv2.imwrite('frame{0}.jpg'.format(count), frame)\n jpeglist.append('frame{0}.jpg'.format(count))\n count += 1\n vidObj.release()\n print('Total number of frames: {0}\\n'.format(count))\n print('Video duration in seconds: {0}\\n'.format(round(count / fps)))\n print('Analyzing visual edges and writing output file...\\n')\n for jpeg in jpeglist[0:193]:\n img = cv2.imread(imgpath + jpeg, 0)\n edges = cv2.Canny(img, 100, 200)\n n_pix = np.sum(edges > -1)\n n_white_pix = np.sum(edges == 255)\n prop_edge_pix = float(n_white_pix / n_pix)\n edge_outfile.write('{0},{1}\\n'.format(jpeg, prop_edge_pix))\n print('Done! Check your output file: edge_outfile.csv')\n\n\nif __name__ == '__main__':\n AnalyzeFrames(vidpath)\n",
"step-5": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nThis script reads in video information frame-by-frame, and then calculates\nvisual edge information for each frame, storing the information in a vector.\nThis can be averaged within TRs in an fMRI analysis to 'regress out'\nhigh-frequency visual information in the video.\n\n@author: zreagh\n\"\"\"\n\nimport cv2\nimport numpy as np\n\n# Can uncomment this pyplot import for frame plotting - see below\n#from matplotlib import pyplot as plt\n\n# Define the paths to your video file and eventual JPEG image files\nvidpath = '/Users/zreagh/Desktop/edge_vector_analysis/test.mov'\nimgpath = '/Users/zreagh/Desktop/edge_vector_analysis/'\n\nedge_outfile = open('edge_outfile.csv','w')\nedge_outfile.write('frame,prop_edge_pix\\n')\n \n# Function to extract video info including frames\ndef AnalyzeFrames(vidpath): \n \n print(\"\\nGetting video info & writing out image files for each frame...\\n\")\n \n # Path to video file \n vidObj = cv2.VideoCapture(vidpath) \n \n # Get FPS\n fps = vidObj.get(cv2.CAP_PROP_FPS)\n print(\"Frames per second: {0}\\n\".format(fps))\n \n # Used as counter variable \n count = 0\n \n # Create an empty list to be filled with image names for calculations below\n jpeglist = []\n \n # Checks whether frames were extracted \n success = 1\n \n # Make sure vidObj call is read\n while success: \n \n # Function extract frames \n success, frame = vidObj.read()\n \n # Saves the frames indexed with frame number as jpeg frames\n cv2.imwrite(\"frame{0}.jpg\".format(count), frame)\n \n # Iteratively fill our list to be called in frame analyses below\n jpeglist.append(\"frame{0}.jpg\".format(count))\n \n # Tick up our counter with each frame\n count += 1\n \n # Drop the video from the buffer\n vidObj.release()\n\n # Print some useful info to the console\n print('Total number of frames: {0}\\n'.format(count))\n print('Video duration in seconds: {0}\\n'.format(round(count/fps)))\n \n # Loop through the images and do edge calculations\n # NOTE: I am constraining to range 0:193 here because my 193rd image is\n # empty for some reason. You can probably delete this for your purposes\n # so that it reads \"for jpeg in jpeglist:\" instead!\n print(\"Analyzing visual edges and writing output file...\\n\")\n \n for jpeg in jpeglist[0:193]:\n \n img = cv2.imread(imgpath + jpeg,0)\n edges = cv2.Canny(img,100,200)\n \n # Get the total number of pixels for each image\n n_pix = np.sum(edges > -1)\n \n # Get the proportion of white (edge) pixels for each image\n n_white_pix = np.sum(edges == 255)\n \n # Calculate the proportion of edge pixels (white/total) for each image\n prop_edge_pix = float(n_white_pix/n_pix)\n \n edge_outfile.write('{0},{1}\\n'.format(jpeg,prop_edge_pix))\n\n # Prints out relevant calculations above for each image - uncomment to\n # debug or peek under the hood\n# print('\\nFrame image:', jpeg)\n# print('Total number of pixels:', n_pix)\n# print('Number of white pixels:', n_white_pix)\n# print('Proportion of edge pixels:', prop_edge_pix)\n \n # Plot each raw frame and edge frame side-by-side - uncomment to\n # peek under the hood (will slow things down a bunch FYI)\n# plt.subplot(121),plt.imshow(img,cmap = 'gray')\n# plt.title('Original Image'), plt.xticks([]), plt.yticks([])\n# plt.subplot(122),plt.imshow(edges,cmap = 'gray')\n# plt.title('Edge Image'), plt.xticks([]), plt.yticks([])\n# plt.show()\n\n print(\"Done! Check your output file: edge_outfile.csv\")\n \n# Do the damn thing\nif __name__ == '__main__': \n \n # Calling the function \n AnalyzeFrames(vidpath) ",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
sys.path.insert(0, os.path.dirname(__file__))
<|reserved_special_token_0|>
for volume, frequency in notes:
samples = square_wave(int(44100 / frequency // 2))
samples = gain(samples, volume)
samples = repeat(samples, quarter_second)
samples = fade(samples, quarter_second)
all_samples.extend(samples)
<|reserved_special_token_0|>
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(44100)
w.writeframes(struct.pack('<' + 'h' * len(all_samples), *all_samples))
<|reserved_special_token_1|>
<|reserved_special_token_0|>
sys.path.insert(0, os.path.dirname(__file__))
C5 = 523
B4b = 466
G4 = 392
E5 = 659
F5 = 698
VOLUME = 12000
notes = [[VOLUME, C5], [VOLUME, C5], [VOLUME, B4b], [VOLUME, C5], [0, C5],
[VOLUME, G4], [0, C5], [VOLUME, G4], [VOLUME, C5], [VOLUME, F5], [
VOLUME, E5], [VOLUME, C5]]
<|reserved_special_token_0|>
all_samples = []
quarter_second = 44100 // 4
for volume, frequency in notes:
samples = square_wave(int(44100 / frequency // 2))
samples = gain(samples, volume)
samples = repeat(samples, quarter_second)
samples = fade(samples, quarter_second)
all_samples.extend(samples)
all_samples = [int(sample) for sample in all_samples]
w = wave.open('music.wav', 'wb')
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(44100)
w.writeframes(struct.pack('<' + 'h' * len(all_samples), *all_samples))
<|reserved_special_token_1|>
import os
import struct
import sys
import wave
sys.path.insert(0, os.path.dirname(__file__))
C5 = 523
B4b = 466
G4 = 392
E5 = 659
F5 = 698
VOLUME = 12000
notes = [[VOLUME, C5], [VOLUME, C5], [VOLUME, B4b], [VOLUME, C5], [0, C5],
[VOLUME, G4], [0, C5], [VOLUME, G4], [VOLUME, C5], [VOLUME, F5], [
VOLUME, E5], [VOLUME, C5]]
from fade import fade
from gain import gain
from repeat import repeat
from square import square_wave
all_samples = []
quarter_second = 44100 // 4
for volume, frequency in notes:
samples = square_wave(int(44100 / frequency // 2))
samples = gain(samples, volume)
samples = repeat(samples, quarter_second)
samples = fade(samples, quarter_second)
all_samples.extend(samples)
all_samples = [int(sample) for sample in all_samples]
w = wave.open('music.wav', 'wb')
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(44100)
w.writeframes(struct.pack('<' + 'h' * len(all_samples), *all_samples))
<|reserved_special_token_1|>
import os
import struct
import sys
import wave
sys.path.insert(0, os.path.dirname(__file__))
C5 = 523
B4b = 466
G4 = 392
E5 = 659
F5 = 698
VOLUME = 12000
notes = [
[VOLUME, C5],
[VOLUME, C5],
[VOLUME, B4b],
[VOLUME, C5],
[0, C5],
[VOLUME, G4],
[0, C5],
[VOLUME, G4],
[VOLUME, C5],
[VOLUME, F5],
[VOLUME, E5],
[VOLUME, C5],
]
from fade import fade
from gain import gain
from repeat import repeat
from square import square_wave
all_samples = []
quarter_second = 44100 // 4
for volume, frequency in notes:
samples = square_wave(int(44100 / frequency // 2))
samples = gain(samples, volume)
samples = repeat(samples, quarter_second)
samples = fade(samples, quarter_second)
all_samples.extend(samples)
all_samples = [int(sample) for sample in all_samples]
w = wave.open('music.wav', 'wb')
w.setnchannels(1)
w.setsampwidth(2)
w.setframerate(44100)
w.writeframes(struct.pack('<' + 'h' * len(all_samples), *all_samples))
|
flexible
|
{
"blob_id": "4fb563985bd99599e88676e167ee84a95b018aba",
"index": 5414,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsys.path.insert(0, os.path.dirname(__file__))\n<mask token>\nfor volume, frequency in notes:\n samples = square_wave(int(44100 / frequency // 2))\n samples = gain(samples, volume)\n samples = repeat(samples, quarter_second)\n samples = fade(samples, quarter_second)\n all_samples.extend(samples)\n<mask token>\nw.setnchannels(1)\nw.setsampwidth(2)\nw.setframerate(44100)\nw.writeframes(struct.pack('<' + 'h' * len(all_samples), *all_samples))\n",
"step-3": "<mask token>\nsys.path.insert(0, os.path.dirname(__file__))\nC5 = 523\nB4b = 466\nG4 = 392\nE5 = 659\nF5 = 698\nVOLUME = 12000\nnotes = [[VOLUME, C5], [VOLUME, C5], [VOLUME, B4b], [VOLUME, C5], [0, C5],\n [VOLUME, G4], [0, C5], [VOLUME, G4], [VOLUME, C5], [VOLUME, F5], [\n VOLUME, E5], [VOLUME, C5]]\n<mask token>\nall_samples = []\nquarter_second = 44100 // 4\nfor volume, frequency in notes:\n samples = square_wave(int(44100 / frequency // 2))\n samples = gain(samples, volume)\n samples = repeat(samples, quarter_second)\n samples = fade(samples, quarter_second)\n all_samples.extend(samples)\nall_samples = [int(sample) for sample in all_samples]\nw = wave.open('music.wav', 'wb')\nw.setnchannels(1)\nw.setsampwidth(2)\nw.setframerate(44100)\nw.writeframes(struct.pack('<' + 'h' * len(all_samples), *all_samples))\n",
"step-4": "import os\nimport struct\nimport sys\nimport wave\nsys.path.insert(0, os.path.dirname(__file__))\nC5 = 523\nB4b = 466\nG4 = 392\nE5 = 659\nF5 = 698\nVOLUME = 12000\nnotes = [[VOLUME, C5], [VOLUME, C5], [VOLUME, B4b], [VOLUME, C5], [0, C5],\n [VOLUME, G4], [0, C5], [VOLUME, G4], [VOLUME, C5], [VOLUME, F5], [\n VOLUME, E5], [VOLUME, C5]]\nfrom fade import fade\nfrom gain import gain\nfrom repeat import repeat\nfrom square import square_wave\nall_samples = []\nquarter_second = 44100 // 4\nfor volume, frequency in notes:\n samples = square_wave(int(44100 / frequency // 2))\n samples = gain(samples, volume)\n samples = repeat(samples, quarter_second)\n samples = fade(samples, quarter_second)\n all_samples.extend(samples)\nall_samples = [int(sample) for sample in all_samples]\nw = wave.open('music.wav', 'wb')\nw.setnchannels(1)\nw.setsampwidth(2)\nw.setframerate(44100)\nw.writeframes(struct.pack('<' + 'h' * len(all_samples), *all_samples))\n",
"step-5": "import os\nimport struct\nimport sys\nimport wave\n\nsys.path.insert(0, os.path.dirname(__file__))\n\nC5 = 523\nB4b = 466\nG4 = 392\nE5 = 659\nF5 = 698\nVOLUME = 12000\n\nnotes = [\n [VOLUME, C5],\n [VOLUME, C5],\n [VOLUME, B4b],\n [VOLUME, C5],\n [0, C5],\n [VOLUME, G4],\n [0, C5],\n [VOLUME, G4],\n [VOLUME, C5],\n [VOLUME, F5],\n [VOLUME, E5],\n [VOLUME, C5],\n]\n\nfrom fade import fade\nfrom gain import gain\nfrom repeat import repeat\nfrom square import square_wave\n\nall_samples = []\nquarter_second = 44100 // 4\nfor volume, frequency in notes:\n samples = square_wave(int(44100 / frequency // 2))\n samples = gain(samples, volume)\n samples = repeat(samples, quarter_second)\n samples = fade(samples, quarter_second)\n all_samples.extend(samples)\n\nall_samples = [int(sample) for sample in all_samples]\n\nw = wave.open('music.wav', 'wb')\nw.setnchannels(1)\nw.setsampwidth(2)\nw.setframerate(44100)\nw.writeframes(struct.pack('<' + 'h' * len(all_samples), *all_samples))\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
class Postfix:
def __init__(self, regex):
self.__regex = regex.expression
self.__modr = Postfix.modRegex(self.__regex)
self.__pila = Stack()
self.__postfix = self.convertInfixToPostfix()
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def getPostfix(self):
return self.__postfix
@staticmethod
def isConcat(character, nextCharacter):
if Symbol.isOperand(character) and Symbol.isOperand(nextCharacter):
return True
elif Symbol.isRightParenthesis(character) and Symbol.isLeftParenthesis(
nextCharacter):
return True
elif Symbol.isStar(character) and Symbol.isOperand(nextCharacter):
return True
elif Symbol.isStar(character) and Symbol.isLeftParenthesis(
nextCharacter):
return True
elif Symbol.isOperand(character) and Symbol.isLeftParenthesis(
nextCharacter):
return True
elif Symbol.isRightParenthesis(character) and nextCharacter == '#':
return True
elif Symbol.isRightParenthesis(character) and Symbol.isOperand(
nextCharacter):
return True
else:
return False
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Postfix:
def __init__(self, regex):
self.__regex = regex.expression
self.__modr = Postfix.modRegex(self.__regex)
self.__pila = Stack()
self.__postfix = self.convertInfixToPostfix()
def getRegex(self):
return self.__regex
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def getPostfix(self):
return self.__postfix
@staticmethod
def isConcat(character, nextCharacter):
if Symbol.isOperand(character) and Symbol.isOperand(nextCharacter):
return True
elif Symbol.isRightParenthesis(character) and Symbol.isLeftParenthesis(
nextCharacter):
return True
elif Symbol.isStar(character) and Symbol.isOperand(nextCharacter):
return True
elif Symbol.isStar(character) and Symbol.isLeftParenthesis(
nextCharacter):
return True
elif Symbol.isOperand(character) and Symbol.isLeftParenthesis(
nextCharacter):
return True
elif Symbol.isRightParenthesis(character) and nextCharacter == '#':
return True
elif Symbol.isRightParenthesis(character) and Symbol.isOperand(
nextCharacter):
return True
else:
return False
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Postfix:
def __init__(self, regex):
self.__regex = regex.expression
self.__modr = Postfix.modRegex(self.__regex)
self.__pila = Stack()
self.__postfix = self.convertInfixToPostfix()
def getRegex(self):
return self.__regex
def getExtendedRegex(self):
return self.__extended
def getModifiedRegex(self):
return self.__modr
def getPostfix(self):
return self.__postfix
@staticmethod
def isConcat(character, nextCharacter):
if Symbol.isOperand(character) and Symbol.isOperand(nextCharacter):
return True
elif Symbol.isRightParenthesis(character) and Symbol.isLeftParenthesis(
nextCharacter):
return True
elif Symbol.isStar(character) and Symbol.isOperand(nextCharacter):
return True
elif Symbol.isStar(character) and Symbol.isLeftParenthesis(
nextCharacter):
return True
elif Symbol.isOperand(character) and Symbol.isLeftParenthesis(
nextCharacter):
return True
elif Symbol.isRightParenthesis(character) and nextCharacter == '#':
return True
elif Symbol.isRightParenthesis(character) and Symbol.isOperand(
nextCharacter):
return True
else:
return False
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Postfix:
def __init__(self, regex):
self.__regex = regex.expression
self.__modr = Postfix.modRegex(self.__regex)
self.__pila = Stack()
self.__postfix = self.convertInfixToPostfix()
def getRegex(self):
return self.__regex
def getExtendedRegex(self):
return self.__extended
def getModifiedRegex(self):
return self.__modr
def getPostfix(self):
return self.__postfix
@staticmethod
def isConcat(character, nextCharacter):
if Symbol.isOperand(character) and Symbol.isOperand(nextCharacter):
return True
elif Symbol.isRightParenthesis(character) and Symbol.isLeftParenthesis(
nextCharacter):
return True
elif Symbol.isStar(character) and Symbol.isOperand(nextCharacter):
return True
elif Symbol.isStar(character) and Symbol.isLeftParenthesis(
nextCharacter):
return True
elif Symbol.isOperand(character) and Symbol.isLeftParenthesis(
nextCharacter):
return True
elif Symbol.isRightParenthesis(character) and nextCharacter == '#':
return True
elif Symbol.isRightParenthesis(character) and Symbol.isOperand(
nextCharacter):
return True
else:
return False
@staticmethod
def modRegex(reg):
list = [char for char in reg + '$']
nlist = []
for i in range(len(list) - 1):
if Postfix.isConcat(list[i], list[i + 1]) and list[i + 1] != '$':
nlist.append(list[i])
nlist.append('.')
elif list[i] != list[-1] and list[i + 1] != '$':
nlist.append(list[i])
else:
nlist.append(list[i])
return ''.join(nlist)
def convertInfixToPostfix(self):
self.__pila.push('(')
tempr = self.__modr + ')'
auxpost = ''
for i in range(len(tempr)):
if Symbol.isOperand(tempr[i]):
auxpost += tempr[i]
elif Symbol.isLeftParenthesis(tempr[i]):
self.__pila.push(tempr[i])
elif Symbol.isOperator(tempr[i]):
while not self.__pila.isEmpty() and Symbol.isOperator(self.
__pila.peek()) and Symbol.checkPrecedence(self.__pila.
peek()) >= Symbol.checkPrecedence(tempr[i]):
auxpost += self.__pila.pop()
self.__pila.push(tempr[i])
elif Symbol.isRightParenthesis(tempr[i]):
while not self.__pila.isEmpty(
) and not Symbol.isLeftParenthesis(self.__pila.peek()):
auxpost += self.__pila.pop()
self.__pila.pop()
return auxpost
<|reserved_special_token_1|>
from Stack import Stack
from Regex import Regex
from Symbol import Symbol
class Postfix:
def __init__(self, regex):
self.__regex = regex.expression
self.__modr = Postfix.modRegex(self.__regex)
self.__pila = Stack()
self.__postfix = self.convertInfixToPostfix()
def getRegex(self):
return self.__regex
def getExtendedRegex(self):
return self.__extended
def getModifiedRegex(self):
return self.__modr
def getPostfix(self):
return self.__postfix
@staticmethod
def isConcat(character, nextCharacter):
if Symbol.isOperand(character) and Symbol.isOperand(nextCharacter):
return True
elif Symbol.isRightParenthesis(character) and Symbol.isLeftParenthesis(nextCharacter):
return True
elif Symbol.isStar(character) and Symbol.isOperand(nextCharacter):
return True
elif Symbol.isStar(character) and Symbol.isLeftParenthesis(nextCharacter):
return True
elif Symbol.isOperand(character) and Symbol.isLeftParenthesis(nextCharacter):
return True
elif Symbol.isRightParenthesis(character) and nextCharacter == "#":
return True
elif Symbol.isRightParenthesis(character) and Symbol.isOperand(nextCharacter):
return True
else:
return False
@staticmethod
def modRegex(reg):
list = [char for char in reg+'$']
nlist = []
for i in range(len(list)-1):
if Postfix.isConcat(list[i], list[i+1]) and list[i+1] != '$':
nlist.append(list[i])
nlist.append('.')
elif(list[i] != list[-1] and list[i+1] != '$'):
nlist.append(list[i])
else:
nlist.append(list[i])
return "".join(nlist)
def convertInfixToPostfix(self):
self.__pila.push('(')
tempr = self.__modr+')'
auxpost = ""
for i in range(len(tempr)):
if Symbol.isOperand(tempr[i]):
auxpost += tempr[i]
elif Symbol.isLeftParenthesis(tempr[i]):
self.__pila.push(tempr[i])
elif Symbol.isOperator(tempr[i]):
while not self.__pila.isEmpty() and Symbol.isOperator(self.__pila.peek()) and (Symbol.checkPrecedence(self.__pila.peek()) >= Symbol.checkPrecedence(tempr[i])):
auxpost += self.__pila.pop()
self.__pila.push(tempr[i])
elif Symbol.isRightParenthesis(tempr[i]):
while not self.__pila.isEmpty() and not Symbol.isLeftParenthesis(self.__pila.peek()):
auxpost += self.__pila.pop()
self.__pila.pop()
return auxpost
|
flexible
|
{
"blob_id": "acc39044fa1ae444dd4a737ea37a0baa60a2c7bd",
"index": 4040,
"step-1": "<mask token>\n\n\nclass Postfix:\n\n def __init__(self, regex):\n self.__regex = regex.expression\n self.__modr = Postfix.modRegex(self.__regex)\n self.__pila = Stack()\n self.__postfix = self.convertInfixToPostfix()\n <mask token>\n <mask token>\n <mask token>\n\n def getPostfix(self):\n return self.__postfix\n\n @staticmethod\n def isConcat(character, nextCharacter):\n if Symbol.isOperand(character) and Symbol.isOperand(nextCharacter):\n return True\n elif Symbol.isRightParenthesis(character) and Symbol.isLeftParenthesis(\n nextCharacter):\n return True\n elif Symbol.isStar(character) and Symbol.isOperand(nextCharacter):\n return True\n elif Symbol.isStar(character) and Symbol.isLeftParenthesis(\n nextCharacter):\n return True\n elif Symbol.isOperand(character) and Symbol.isLeftParenthesis(\n nextCharacter):\n return True\n elif Symbol.isRightParenthesis(character) and nextCharacter == '#':\n return True\n elif Symbol.isRightParenthesis(character) and Symbol.isOperand(\n nextCharacter):\n return True\n else:\n return False\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Postfix:\n\n def __init__(self, regex):\n self.__regex = regex.expression\n self.__modr = Postfix.modRegex(self.__regex)\n self.__pila = Stack()\n self.__postfix = self.convertInfixToPostfix()\n\n def getRegex(self):\n return self.__regex\n <mask token>\n <mask token>\n\n def getPostfix(self):\n return self.__postfix\n\n @staticmethod\n def isConcat(character, nextCharacter):\n if Symbol.isOperand(character) and Symbol.isOperand(nextCharacter):\n return True\n elif Symbol.isRightParenthesis(character) and Symbol.isLeftParenthesis(\n nextCharacter):\n return True\n elif Symbol.isStar(character) and Symbol.isOperand(nextCharacter):\n return True\n elif Symbol.isStar(character) and Symbol.isLeftParenthesis(\n nextCharacter):\n return True\n elif Symbol.isOperand(character) and Symbol.isLeftParenthesis(\n nextCharacter):\n return True\n elif Symbol.isRightParenthesis(character) and nextCharacter == '#':\n return True\n elif Symbol.isRightParenthesis(character) and Symbol.isOperand(\n nextCharacter):\n return True\n else:\n return False\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Postfix:\n\n def __init__(self, regex):\n self.__regex = regex.expression\n self.__modr = Postfix.modRegex(self.__regex)\n self.__pila = Stack()\n self.__postfix = self.convertInfixToPostfix()\n\n def getRegex(self):\n return self.__regex\n\n def getExtendedRegex(self):\n return self.__extended\n\n def getModifiedRegex(self):\n return self.__modr\n\n def getPostfix(self):\n return self.__postfix\n\n @staticmethod\n def isConcat(character, nextCharacter):\n if Symbol.isOperand(character) and Symbol.isOperand(nextCharacter):\n return True\n elif Symbol.isRightParenthesis(character) and Symbol.isLeftParenthesis(\n nextCharacter):\n return True\n elif Symbol.isStar(character) and Symbol.isOperand(nextCharacter):\n return True\n elif Symbol.isStar(character) and Symbol.isLeftParenthesis(\n nextCharacter):\n return True\n elif Symbol.isOperand(character) and Symbol.isLeftParenthesis(\n nextCharacter):\n return True\n elif Symbol.isRightParenthesis(character) and nextCharacter == '#':\n return True\n elif Symbol.isRightParenthesis(character) and Symbol.isOperand(\n nextCharacter):\n return True\n else:\n return False\n <mask token>\n <mask token>\n",
"step-4": "<mask token>\n\n\nclass Postfix:\n\n def __init__(self, regex):\n self.__regex = regex.expression\n self.__modr = Postfix.modRegex(self.__regex)\n self.__pila = Stack()\n self.__postfix = self.convertInfixToPostfix()\n\n def getRegex(self):\n return self.__regex\n\n def getExtendedRegex(self):\n return self.__extended\n\n def getModifiedRegex(self):\n return self.__modr\n\n def getPostfix(self):\n return self.__postfix\n\n @staticmethod\n def isConcat(character, nextCharacter):\n if Symbol.isOperand(character) and Symbol.isOperand(nextCharacter):\n return True\n elif Symbol.isRightParenthesis(character) and Symbol.isLeftParenthesis(\n nextCharacter):\n return True\n elif Symbol.isStar(character) and Symbol.isOperand(nextCharacter):\n return True\n elif Symbol.isStar(character) and Symbol.isLeftParenthesis(\n nextCharacter):\n return True\n elif Symbol.isOperand(character) and Symbol.isLeftParenthesis(\n nextCharacter):\n return True\n elif Symbol.isRightParenthesis(character) and nextCharacter == '#':\n return True\n elif Symbol.isRightParenthesis(character) and Symbol.isOperand(\n nextCharacter):\n return True\n else:\n return False\n\n @staticmethod\n def modRegex(reg):\n list = [char for char in reg + '$']\n nlist = []\n for i in range(len(list) - 1):\n if Postfix.isConcat(list[i], list[i + 1]) and list[i + 1] != '$':\n nlist.append(list[i])\n nlist.append('.')\n elif list[i] != list[-1] and list[i + 1] != '$':\n nlist.append(list[i])\n else:\n nlist.append(list[i])\n return ''.join(nlist)\n\n def convertInfixToPostfix(self):\n self.__pila.push('(')\n tempr = self.__modr + ')'\n auxpost = ''\n for i in range(len(tempr)):\n if Symbol.isOperand(tempr[i]):\n auxpost += tempr[i]\n elif Symbol.isLeftParenthesis(tempr[i]):\n self.__pila.push(tempr[i])\n elif Symbol.isOperator(tempr[i]):\n while not self.__pila.isEmpty() and Symbol.isOperator(self.\n __pila.peek()) and Symbol.checkPrecedence(self.__pila.\n peek()) >= Symbol.checkPrecedence(tempr[i]):\n auxpost += self.__pila.pop()\n self.__pila.push(tempr[i])\n elif Symbol.isRightParenthesis(tempr[i]):\n while not self.__pila.isEmpty(\n ) and not Symbol.isLeftParenthesis(self.__pila.peek()):\n auxpost += self.__pila.pop()\n self.__pila.pop()\n return auxpost\n",
"step-5": "from Stack import Stack\nfrom Regex import Regex\nfrom Symbol import Symbol\n\nclass Postfix:\n def __init__(self, regex):\n self.__regex = regex.expression\n self.__modr = Postfix.modRegex(self.__regex)\n self.__pila = Stack()\n self.__postfix = self.convertInfixToPostfix()\n \n def getRegex(self):\n return self.__regex\n \n def getExtendedRegex(self):\n return self.__extended\n\n def getModifiedRegex(self):\n return self.__modr\n\n def getPostfix(self):\n return self.__postfix\n\n @staticmethod\n def isConcat(character, nextCharacter):\n if Symbol.isOperand(character) and Symbol.isOperand(nextCharacter):\n return True\n elif Symbol.isRightParenthesis(character) and Symbol.isLeftParenthesis(nextCharacter):\n return True\n elif Symbol.isStar(character) and Symbol.isOperand(nextCharacter):\n return True\n elif Symbol.isStar(character) and Symbol.isLeftParenthesis(nextCharacter):\n return True\n elif Symbol.isOperand(character) and Symbol.isLeftParenthesis(nextCharacter):\n return True\n elif Symbol.isRightParenthesis(character) and nextCharacter == \"#\":\n return True\n elif Symbol.isRightParenthesis(character) and Symbol.isOperand(nextCharacter):\n return True\n else:\n return False\n\n @staticmethod\n def modRegex(reg):\n list = [char for char in reg+'$']\n nlist = []\n for i in range(len(list)-1):\n if Postfix.isConcat(list[i], list[i+1]) and list[i+1] != '$':\n nlist.append(list[i])\n nlist.append('.')\n elif(list[i] != list[-1] and list[i+1] != '$'):\n nlist.append(list[i])\n else:\n nlist.append(list[i])\n return \"\".join(nlist)\n\n def convertInfixToPostfix(self):\n self.__pila.push('(')\n tempr = self.__modr+')'\n auxpost = \"\"\n for i in range(len(tempr)):\n if Symbol.isOperand(tempr[i]):\n auxpost += tempr[i]\n elif Symbol.isLeftParenthesis(tempr[i]):\n self.__pila.push(tempr[i])\n elif Symbol.isOperator(tempr[i]):\n while not self.__pila.isEmpty() and Symbol.isOperator(self.__pila.peek()) and (Symbol.checkPrecedence(self.__pila.peek()) >= Symbol.checkPrecedence(tempr[i])):\n auxpost += self.__pila.pop()\n self.__pila.push(tempr[i])\n elif Symbol.isRightParenthesis(tempr[i]):\n while not self.__pila.isEmpty() and not Symbol.isLeftParenthesis(self.__pila.peek()):\n auxpost += self.__pila.pop()\n self.__pila.pop()\n return auxpost",
"step-ids": [
4,
5,
7,
9,
11
]
}
|
[
4,
5,
7,
9,
11
] |
""" A set of constants to describe the package.
Don't put any code in here, because it must be safe to execute in setup.py. """
__title__ = 'space_tracer' # => name in setup.py
__version__ = '4.10.2'
__author__ = "Don Kirkby"
__author_email__ = "donkirkby@gmail.com"
__description__ = "Trade time for space when debugging your code."
__url__ = "https://donkirkby.github.io/live-py-plugin/"
|
normal
|
{
"blob_id": "6cb29ebd9c0f2660d0eb868bec87ffd97cf4d198",
"index": 6262,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n__title__ = 'space_tracer'\n__version__ = '4.10.2'\n__author__ = 'Don Kirkby'\n__author_email__ = 'donkirkby@gmail.com'\n__description__ = 'Trade time for space when debugging your code.'\n__url__ = 'https://donkirkby.github.io/live-py-plugin/'\n",
"step-3": "\"\"\" A set of constants to describe the package.\n\nDon't put any code in here, because it must be safe to execute in setup.py. \"\"\"\n\n__title__ = 'space_tracer' # => name in setup.py\n__version__ = '4.10.2'\n__author__ = \"Don Kirkby\"\n__author_email__ = \"donkirkby@gmail.com\"\n__description__ = \"Trade time for space when debugging your code.\"\n__url__ = \"https://donkirkby.github.io/live-py-plugin/\"\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
class Coms:
def __init__(self, name, addr, coord):
self.name = name
self.addr = addr
self.coord = coord
def getString(self):
return "회사명\n"+self.name+"\n\n주소\n"+self.addr
def getTeleString(self):
return "회사명 : " + self.name + ", 주소 : " + self.addr
class Jobs:
def __init__(self, name, type, experience, education, keyword, salary, url, start, end):
self.name = name
self.type = type
self.experience = experience
self.education = education
self.keyword = keyword
self.salary = salary
self.url=url
self.start = start
self.end = end
def getString(self):
return "공고명 : " + self.name + "\n채용형태 : " + self.type + "\n경력 : " + self.experience + "\n학력 : " + self.education + "\n업무 : " + self.keyword + "\n연봉 : " + self.salary
def getTeleString(self):
return "공고명 : " + self.name
|
normal
|
{
"blob_id": "bcc24d5f97e46433acb8bcfb08fe582f51eb28ce",
"index": 2932,
"step-1": "<mask token>\n\n\nclass Jobs:\n\n def __init__(self, name, type, experience, education, keyword, salary,\n url, start, end):\n self.name = name\n self.type = type\n self.experience = experience\n self.education = education\n self.keyword = keyword\n self.salary = salary\n self.url = url\n self.start = start\n self.end = end\n\n def getString(self):\n return ('공고명 : ' + self.name + '\\n채용형태 : ' + self.type + '\\n경력 : ' +\n self.experience + '\\n학력 : ' + self.education + '\\n업무 : ' + self\n .keyword + '\\n연봉 : ' + self.salary)\n\n def getTeleString(self):\n return '공고명 : ' + self.name\n",
"step-2": "class Coms:\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Jobs:\n\n def __init__(self, name, type, experience, education, keyword, salary,\n url, start, end):\n self.name = name\n self.type = type\n self.experience = experience\n self.education = education\n self.keyword = keyword\n self.salary = salary\n self.url = url\n self.start = start\n self.end = end\n\n def getString(self):\n return ('공고명 : ' + self.name + '\\n채용형태 : ' + self.type + '\\n경력 : ' +\n self.experience + '\\n학력 : ' + self.education + '\\n업무 : ' + self\n .keyword + '\\n연봉 : ' + self.salary)\n\n def getTeleString(self):\n return '공고명 : ' + self.name\n",
"step-3": "class Coms:\n\n def __init__(self, name, addr, coord):\n self.name = name\n self.addr = addr\n self.coord = coord\n <mask token>\n <mask token>\n\n\nclass Jobs:\n\n def __init__(self, name, type, experience, education, keyword, salary,\n url, start, end):\n self.name = name\n self.type = type\n self.experience = experience\n self.education = education\n self.keyword = keyword\n self.salary = salary\n self.url = url\n self.start = start\n self.end = end\n\n def getString(self):\n return ('공고명 : ' + self.name + '\\n채용형태 : ' + self.type + '\\n경력 : ' +\n self.experience + '\\n학력 : ' + self.education + '\\n업무 : ' + self\n .keyword + '\\n연봉 : ' + self.salary)\n\n def getTeleString(self):\n return '공고명 : ' + self.name\n",
"step-4": "class Coms:\n\n def __init__(self, name, addr, coord):\n self.name = name\n self.addr = addr\n self.coord = coord\n <mask token>\n\n def getTeleString(self):\n return '회사명 : ' + self.name + ', 주소 : ' + self.addr\n\n\nclass Jobs:\n\n def __init__(self, name, type, experience, education, keyword, salary,\n url, start, end):\n self.name = name\n self.type = type\n self.experience = experience\n self.education = education\n self.keyword = keyword\n self.salary = salary\n self.url = url\n self.start = start\n self.end = end\n\n def getString(self):\n return ('공고명 : ' + self.name + '\\n채용형태 : ' + self.type + '\\n경력 : ' +\n self.experience + '\\n학력 : ' + self.education + '\\n업무 : ' + self\n .keyword + '\\n연봉 : ' + self.salary)\n\n def getTeleString(self):\n return '공고명 : ' + self.name\n",
"step-5": "class Coms:\n def __init__(self, name, addr, coord):\n self.name = name\n self.addr = addr\n self.coord = coord\n\n def getString(self):\n return \"회사명\\n\"+self.name+\"\\n\\n주소\\n\"+self.addr\n\n def getTeleString(self):\n return \"회사명 : \" + self.name + \", 주소 : \" + self.addr\n\nclass Jobs:\n def __init__(self, name, type, experience, education, keyword, salary, url, start, end):\n self.name = name\n self.type = type\n self.experience = experience\n self.education = education\n self.keyword = keyword\n self.salary = salary\n self.url=url\n self.start = start\n self.end = end\n\n def getString(self):\n return \"공고명 : \" + self.name + \"\\n채용형태 : \" + self.type + \"\\n경력 : \" + self.experience + \"\\n학력 : \" + self.education + \"\\n업무 : \" + self.keyword + \"\\n연봉 : \" + self.salary\n\n def getTeleString(self):\n return \"공고명 : \" + self.name",
"step-ids": [
4,
5,
6,
7,
9
]
}
|
[
4,
5,
6,
7,
9
] |
import pandas as pd
from fbprophet import Prophet
import os
from utils.json_utils import read_json, write_json
from sklearn.model_selection import train_test_split
import numpy as np
from sklearn.metrics import mean_absolute_error
root_dir = "/home/charan/Documents/workspaces/python_workspaces/Data/ADL_Project/"
final_df_path = os.path.join(root_dir, "final_data/311_Cases_master_with_desc_with_prediction.csv")
test_train_df = os.path.join(root_dir, "final_data/Data_with_no_desc.csv")
dept_category = read_json(os.path.join(root_dir, "dept/dept_category.json"))
def mean_absolute_percentage_error(y_true, y_pred):
y_true, y_pred = np.array(y_true), np.array(y_pred)
return np.mean(np.abs((y_true - y_pred) / y_true)) * 100
value_dict = {}
# Python
final_df = pd.read_csv(final_df_path)
test_train_df = pd.read_csv(test_train_df)
test_train_df = test_train_df[test_train_df['CREATION YEAR'] > 2015]
train_split = 80
final_df['DAYS TO CLOSE'].fillna(0, inplace=True)
print(final_df['CREATION DATE'].isna().sum())
print(final_df['DAYS TO CLOSE'].isna().sum())
test_train_df['DAYS TO CLOSE'] = test_train_df['DAYS TO CLOSE'].apply(lambda x: str(x).replace(",", ""))
list_of_dataframes = []
for each_dept in sorted(list(dept_category.values())):
print(f' processing - {each_dept}')
each_test_train = test_train_df[test_train_df.DEPARTMENT == each_dept].reset_index()
each_dept_df = final_df[final_df.DEPARTMENT == each_dept].reset_index()
test_time_train = each_test_train[['CREATION DATE', 'DAYS TO CLOSE']]
each_df = each_dept_df[['CREATION DATE', 'DAYS TO CLOSE']]
each_df.rename(columns={'CREATION DATE': 'ds', 'DAYS TO CLOSE': 'y'}, inplace=True)
test_time_train.rename(columns={'CREATION DATE': 'ds', 'DAYS TO CLOSE': 'y'}, inplace=True)
# test_time_train.y.apply(lambda x: str(x).replace(",", ""))
test_time_train.y = test_time_train.y.astype('float64')
test_time_train.y.fillna(0, inplace=True)
train, test = train_test_split(test_time_train, test_size=0.2)
m = Prophet()
m.fit(train)
forecast = m.predict(test)
mae_value = mean_absolute_error(test['y'].values, forecast['yhat'].values)
mape_error = mean_absolute_percentage_error(test['y'].values, forecast['yhat'].values)
print(f'mean absolute error : {mae_value},MAPE {mape_error} , department {each_dept}')
metric_dict = {'MAE': mae_value, 'MAPE': mape_error}
value_dict[each_dept] = metric_dict
fig1 = m.plot(forecast)
fig1.savefig(each_dept + ".png")
whole_result = m.predict(each_df)
each_df['TIME_PRED'] = whole_result['yhat']
each_df['CASE ID'] = each_dept_df['CASE ID']
list_of_dataframes.append(each_df)
write_json(value_dict, "time_series_metrics.json")
final_pred = pd.concat(list_of_dataframes)
final_pred.to_csv("final_val.csv", header=True, index=False)
|
normal
|
{
"blob_id": "25dd7ea4a154e5693c65f8c42107224efee42516",
"index": 4533,
"step-1": "<mask token>\n\n\ndef mean_absolute_percentage_error(y_true, y_pred):\n y_true, y_pred = np.array(y_true), np.array(y_pred)\n return np.mean(np.abs((y_true - y_pred) / y_true)) * 100\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef mean_absolute_percentage_error(y_true, y_pred):\n y_true, y_pred = np.array(y_true), np.array(y_pred)\n return np.mean(np.abs((y_true - y_pred) / y_true)) * 100\n\n\n<mask token>\nfinal_df['DAYS TO CLOSE'].fillna(0, inplace=True)\nprint(final_df['CREATION DATE'].isna().sum())\nprint(final_df['DAYS TO CLOSE'].isna().sum())\n<mask token>\nfor each_dept in sorted(list(dept_category.values())):\n print(f' processing - {each_dept}')\n each_test_train = test_train_df[test_train_df.DEPARTMENT == each_dept\n ].reset_index()\n each_dept_df = final_df[final_df.DEPARTMENT == each_dept].reset_index()\n test_time_train = each_test_train[['CREATION DATE', 'DAYS TO CLOSE']]\n each_df = each_dept_df[['CREATION DATE', 'DAYS TO CLOSE']]\n each_df.rename(columns={'CREATION DATE': 'ds', 'DAYS TO CLOSE': 'y'},\n inplace=True)\n test_time_train.rename(columns={'CREATION DATE': 'ds', 'DAYS TO CLOSE':\n 'y'}, inplace=True)\n test_time_train.y = test_time_train.y.astype('float64')\n test_time_train.y.fillna(0, inplace=True)\n train, test = train_test_split(test_time_train, test_size=0.2)\n m = Prophet()\n m.fit(train)\n forecast = m.predict(test)\n mae_value = mean_absolute_error(test['y'].values, forecast['yhat'].values)\n mape_error = mean_absolute_percentage_error(test['y'].values, forecast[\n 'yhat'].values)\n print(\n f'mean absolute error : {mae_value},MAPE {mape_error} , department {each_dept}'\n )\n metric_dict = {'MAE': mae_value, 'MAPE': mape_error}\n value_dict[each_dept] = metric_dict\n fig1 = m.plot(forecast)\n fig1.savefig(each_dept + '.png')\n whole_result = m.predict(each_df)\n each_df['TIME_PRED'] = whole_result['yhat']\n each_df['CASE ID'] = each_dept_df['CASE ID']\n list_of_dataframes.append(each_df)\nwrite_json(value_dict, 'time_series_metrics.json')\n<mask token>\nfinal_pred.to_csv('final_val.csv', header=True, index=False)\n",
"step-3": "<mask token>\nroot_dir = (\n '/home/charan/Documents/workspaces/python_workspaces/Data/ADL_Project/')\nfinal_df_path = os.path.join(root_dir,\n 'final_data/311_Cases_master_with_desc_with_prediction.csv')\ntest_train_df = os.path.join(root_dir, 'final_data/Data_with_no_desc.csv')\ndept_category = read_json(os.path.join(root_dir, 'dept/dept_category.json'))\n\n\ndef mean_absolute_percentage_error(y_true, y_pred):\n y_true, y_pred = np.array(y_true), np.array(y_pred)\n return np.mean(np.abs((y_true - y_pred) / y_true)) * 100\n\n\nvalue_dict = {}\nfinal_df = pd.read_csv(final_df_path)\ntest_train_df = pd.read_csv(test_train_df)\ntest_train_df = test_train_df[test_train_df['CREATION YEAR'] > 2015]\ntrain_split = 80\nfinal_df['DAYS TO CLOSE'].fillna(0, inplace=True)\nprint(final_df['CREATION DATE'].isna().sum())\nprint(final_df['DAYS TO CLOSE'].isna().sum())\ntest_train_df['DAYS TO CLOSE'] = test_train_df['DAYS TO CLOSE'].apply(lambda\n x: str(x).replace(',', ''))\nlist_of_dataframes = []\nfor each_dept in sorted(list(dept_category.values())):\n print(f' processing - {each_dept}')\n each_test_train = test_train_df[test_train_df.DEPARTMENT == each_dept\n ].reset_index()\n each_dept_df = final_df[final_df.DEPARTMENT == each_dept].reset_index()\n test_time_train = each_test_train[['CREATION DATE', 'DAYS TO CLOSE']]\n each_df = each_dept_df[['CREATION DATE', 'DAYS TO CLOSE']]\n each_df.rename(columns={'CREATION DATE': 'ds', 'DAYS TO CLOSE': 'y'},\n inplace=True)\n test_time_train.rename(columns={'CREATION DATE': 'ds', 'DAYS TO CLOSE':\n 'y'}, inplace=True)\n test_time_train.y = test_time_train.y.astype('float64')\n test_time_train.y.fillna(0, inplace=True)\n train, test = train_test_split(test_time_train, test_size=0.2)\n m = Prophet()\n m.fit(train)\n forecast = m.predict(test)\n mae_value = mean_absolute_error(test['y'].values, forecast['yhat'].values)\n mape_error = mean_absolute_percentage_error(test['y'].values, forecast[\n 'yhat'].values)\n print(\n f'mean absolute error : {mae_value},MAPE {mape_error} , department {each_dept}'\n )\n metric_dict = {'MAE': mae_value, 'MAPE': mape_error}\n value_dict[each_dept] = metric_dict\n fig1 = m.plot(forecast)\n fig1.savefig(each_dept + '.png')\n whole_result = m.predict(each_df)\n each_df['TIME_PRED'] = whole_result['yhat']\n each_df['CASE ID'] = each_dept_df['CASE ID']\n list_of_dataframes.append(each_df)\nwrite_json(value_dict, 'time_series_metrics.json')\nfinal_pred = pd.concat(list_of_dataframes)\nfinal_pred.to_csv('final_val.csv', header=True, index=False)\n",
"step-4": "import pandas as pd\nfrom fbprophet import Prophet\nimport os\nfrom utils.json_utils import read_json, write_json\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nfrom sklearn.metrics import mean_absolute_error\nroot_dir = (\n '/home/charan/Documents/workspaces/python_workspaces/Data/ADL_Project/')\nfinal_df_path = os.path.join(root_dir,\n 'final_data/311_Cases_master_with_desc_with_prediction.csv')\ntest_train_df = os.path.join(root_dir, 'final_data/Data_with_no_desc.csv')\ndept_category = read_json(os.path.join(root_dir, 'dept/dept_category.json'))\n\n\ndef mean_absolute_percentage_error(y_true, y_pred):\n y_true, y_pred = np.array(y_true), np.array(y_pred)\n return np.mean(np.abs((y_true - y_pred) / y_true)) * 100\n\n\nvalue_dict = {}\nfinal_df = pd.read_csv(final_df_path)\ntest_train_df = pd.read_csv(test_train_df)\ntest_train_df = test_train_df[test_train_df['CREATION YEAR'] > 2015]\ntrain_split = 80\nfinal_df['DAYS TO CLOSE'].fillna(0, inplace=True)\nprint(final_df['CREATION DATE'].isna().sum())\nprint(final_df['DAYS TO CLOSE'].isna().sum())\ntest_train_df['DAYS TO CLOSE'] = test_train_df['DAYS TO CLOSE'].apply(lambda\n x: str(x).replace(',', ''))\nlist_of_dataframes = []\nfor each_dept in sorted(list(dept_category.values())):\n print(f' processing - {each_dept}')\n each_test_train = test_train_df[test_train_df.DEPARTMENT == each_dept\n ].reset_index()\n each_dept_df = final_df[final_df.DEPARTMENT == each_dept].reset_index()\n test_time_train = each_test_train[['CREATION DATE', 'DAYS TO CLOSE']]\n each_df = each_dept_df[['CREATION DATE', 'DAYS TO CLOSE']]\n each_df.rename(columns={'CREATION DATE': 'ds', 'DAYS TO CLOSE': 'y'},\n inplace=True)\n test_time_train.rename(columns={'CREATION DATE': 'ds', 'DAYS TO CLOSE':\n 'y'}, inplace=True)\n test_time_train.y = test_time_train.y.astype('float64')\n test_time_train.y.fillna(0, inplace=True)\n train, test = train_test_split(test_time_train, test_size=0.2)\n m = Prophet()\n m.fit(train)\n forecast = m.predict(test)\n mae_value = mean_absolute_error(test['y'].values, forecast['yhat'].values)\n mape_error = mean_absolute_percentage_error(test['y'].values, forecast[\n 'yhat'].values)\n print(\n f'mean absolute error : {mae_value},MAPE {mape_error} , department {each_dept}'\n )\n metric_dict = {'MAE': mae_value, 'MAPE': mape_error}\n value_dict[each_dept] = metric_dict\n fig1 = m.plot(forecast)\n fig1.savefig(each_dept + '.png')\n whole_result = m.predict(each_df)\n each_df['TIME_PRED'] = whole_result['yhat']\n each_df['CASE ID'] = each_dept_df['CASE ID']\n list_of_dataframes.append(each_df)\nwrite_json(value_dict, 'time_series_metrics.json')\nfinal_pred = pd.concat(list_of_dataframes)\nfinal_pred.to_csv('final_val.csv', header=True, index=False)\n",
"step-5": "import pandas as pd\nfrom fbprophet import Prophet\nimport os\nfrom utils.json_utils import read_json, write_json\nfrom sklearn.model_selection import train_test_split\nimport numpy as np\nfrom sklearn.metrics import mean_absolute_error\n\nroot_dir = \"/home/charan/Documents/workspaces/python_workspaces/Data/ADL_Project/\"\nfinal_df_path = os.path.join(root_dir, \"final_data/311_Cases_master_with_desc_with_prediction.csv\")\ntest_train_df = os.path.join(root_dir, \"final_data/Data_with_no_desc.csv\")\ndept_category = read_json(os.path.join(root_dir, \"dept/dept_category.json\"))\n\n\ndef mean_absolute_percentage_error(y_true, y_pred):\n y_true, y_pred = np.array(y_true), np.array(y_pred)\n return np.mean(np.abs((y_true - y_pred) / y_true)) * 100\n\n\nvalue_dict = {}\n# Python\nfinal_df = pd.read_csv(final_df_path)\ntest_train_df = pd.read_csv(test_train_df)\ntest_train_df = test_train_df[test_train_df['CREATION YEAR'] > 2015]\ntrain_split = 80\n\nfinal_df['DAYS TO CLOSE'].fillna(0, inplace=True)\nprint(final_df['CREATION DATE'].isna().sum())\nprint(final_df['DAYS TO CLOSE'].isna().sum())\n\ntest_train_df['DAYS TO CLOSE'] = test_train_df['DAYS TO CLOSE'].apply(lambda x: str(x).replace(\",\", \"\"))\n\nlist_of_dataframes = []\n\nfor each_dept in sorted(list(dept_category.values())):\n print(f' processing - {each_dept}')\n each_test_train = test_train_df[test_train_df.DEPARTMENT == each_dept].reset_index()\n each_dept_df = final_df[final_df.DEPARTMENT == each_dept].reset_index()\n\n test_time_train = each_test_train[['CREATION DATE', 'DAYS TO CLOSE']]\n each_df = each_dept_df[['CREATION DATE', 'DAYS TO CLOSE']]\n\n each_df.rename(columns={'CREATION DATE': 'ds', 'DAYS TO CLOSE': 'y'}, inplace=True)\n test_time_train.rename(columns={'CREATION DATE': 'ds', 'DAYS TO CLOSE': 'y'}, inplace=True)\n # test_time_train.y.apply(lambda x: str(x).replace(\",\", \"\"))\n test_time_train.y = test_time_train.y.astype('float64')\n test_time_train.y.fillna(0, inplace=True)\n train, test = train_test_split(test_time_train, test_size=0.2)\n m = Prophet()\n m.fit(train)\n forecast = m.predict(test)\n mae_value = mean_absolute_error(test['y'].values, forecast['yhat'].values)\n mape_error = mean_absolute_percentage_error(test['y'].values, forecast['yhat'].values)\n print(f'mean absolute error : {mae_value},MAPE {mape_error} , department {each_dept}')\n metric_dict = {'MAE': mae_value, 'MAPE': mape_error}\n value_dict[each_dept] = metric_dict\n fig1 = m.plot(forecast)\n fig1.savefig(each_dept + \".png\")\n whole_result = m.predict(each_df)\n each_df['TIME_PRED'] = whole_result['yhat']\n each_df['CASE ID'] = each_dept_df['CASE ID']\n list_of_dataframes.append(each_df)\n\nwrite_json(value_dict, \"time_series_metrics.json\")\nfinal_pred = pd.concat(list_of_dataframes)\nfinal_pred.to_csv(\"final_val.csv\", header=True, index=False)\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
from microbit import *
import speech
while True:
speech.say("I am a DALEK - EXTERMINATE", speed=120, pitch=100, throat=100, mouth=200) #kokeile muuttaa parametrejä
|
normal
|
{
"blob_id": "dad78d7948fb1038f9cf66732f39c18a18f2a3c8",
"index": 5233,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile True:\n speech.say('I am a DALEK - EXTERMINATE', speed=120, pitch=100, throat=\n 100, mouth=200)\n",
"step-3": "from microbit import *\nimport speech\nwhile True:\n speech.say('I am a DALEK - EXTERMINATE', speed=120, pitch=100, throat=\n 100, mouth=200)\n",
"step-4": "from microbit import *\n\nimport speech\n\n\nwhile True:\n speech.say(\"I am a DALEK - EXTERMINATE\", speed=120, pitch=100, throat=100, mouth=200) #kokeile muuttaa parametrejä\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 20 17:13:46 2017
@author: pmonnot
"""
import blpapi
import datetime
# Create a Session
session = blpapi.Session()
# Start a Session
if not session.start():
print "Failed to start session."
if not session.openService("//blp/refdata"):
print "Failed to open //blp/refdata"
refDataService = session.getService("//blp/refdata")
request = refDataService.createRequest("HistoricalDataRequest")
request.append("securities", "AAPL US Equity")
#FIELDS - if simply one field use: #request.append("fields", "PX_LAST")
#If you wish to loop the fields
field_list = ["PX_OPEN","PX_HIGH","PX_LAST","PX_VOLUME"]
for field in field_list:
request.append("fields", field)
request.set("startDate", "20170101")
request.set("endDate", "20170201")
request.set("adjustmentFollowDPDF", "False")
request.set("adjustmentAbnormal", "True")
request.set("adjustmentNormal", "True")
request.set("adjustmentSplit", "True")
request.set("periodicitySelection", "DAILY")
request.set("nonTradingDayFillOption", "NON_TRADING_WEEKDAYS") #also takes ALL_CALENDAR_DAYS and ACTIVE_DAYS_ONLY
request.set("nonTradingDayFillMethod", "PREVIOUS_VALUE")
print "Sending Request:", request
session.sendRequest(request)
endReached = False
while endReached == False:
ev = session.nextEvent()
if ev.eventType() == blpapi.Event.RESPONSE or ev.eventType() == blpapi.Event.PARTIAL_RESPONSE:
for msg in ev:
numPoints = msg.getElement("securityData").getElement("fieldData").numValues()
for i in range(0,numPoints):
Point = msg.getElement('securityData').getElement('fieldData').getValueAsElement(i)
print Point.getElement('date').getValue(),'\t',Point.getElement('PX_LAST').getValue(),'\t'
if ev.eventType() == blpapi.Event.RESPONSE:
endReached = True
|
normal
|
{
"blob_id": "a8a2d672369f61c6412229380cc6097d152ba126",
"index": 9883,
"step-1": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Feb 20 17:13:46 2017\r\n\r\n@author: pmonnot\r\n\"\"\"\r\n\r\nimport blpapi\r\nimport datetime\r\n\r\n# Create a Session\r\nsession = blpapi.Session()\r\n# Start a Session\r\nif not session.start():\r\n print \"Failed to start session.\"\r\nif not session.openService(\"//blp/refdata\"):\r\n print \"Failed to open //blp/refdata\"\r\n\r\nrefDataService = session.getService(\"//blp/refdata\")\r\nrequest = refDataService.createRequest(\"HistoricalDataRequest\")\r\n\r\nrequest.append(\"securities\", \"AAPL US Equity\")\r\n\r\n#FIELDS - if simply one field use: #request.append(\"fields\", \"PX_LAST\")\r\n#If you wish to loop the fields\r\nfield_list = [\"PX_OPEN\",\"PX_HIGH\",\"PX_LAST\",\"PX_VOLUME\"]\r\nfor field in field_list:\r\n request.append(\"fields\", field)\r\n\r\nrequest.set(\"startDate\", \"20170101\")\r\nrequest.set(\"endDate\", \"20170201\")\r\nrequest.set(\"adjustmentFollowDPDF\", \"False\")\r\nrequest.set(\"adjustmentAbnormal\", \"True\")\r\nrequest.set(\"adjustmentNormal\", \"True\")\r\nrequest.set(\"adjustmentSplit\", \"True\")\r\nrequest.set(\"periodicitySelection\", \"DAILY\")\r\nrequest.set(\"nonTradingDayFillOption\", \"NON_TRADING_WEEKDAYS\") #also takes ALL_CALENDAR_DAYS and ACTIVE_DAYS_ONLY\r\nrequest.set(\"nonTradingDayFillMethod\", \"PREVIOUS_VALUE\")\r\n\r\n\r\n\r\nprint \"Sending Request:\", request\r\nsession.sendRequest(request)\r\n\r\n\r\nendReached = False\r\nwhile endReached == False:\r\n ev = session.nextEvent()\r\n if ev.eventType() == blpapi.Event.RESPONSE or ev.eventType() == blpapi.Event.PARTIAL_RESPONSE:\r\n \r\n for msg in ev:\r\n numPoints = msg.getElement(\"securityData\").getElement(\"fieldData\").numValues()\r\n for i in range(0,numPoints):\r\n Point = msg.getElement('securityData').getElement('fieldData').getValueAsElement(i)\r\n print Point.getElement('date').getValue(),'\\t',Point.getElement('PX_LAST').getValue(),'\\t'\r\n \r\n \r\n if ev.eventType() == blpapi.Event.RESPONSE:\r\n endReached = True",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0
]
}
|
[
0
] |
print ("Hello Workls!")
|
normal
|
{
"blob_id": "c52d1c187edb17e85a8e2b47aa6731bc9a41ab1b",
"index": 561,
"step-1": "<mask token>\n",
"step-2": "print('Hello Workls!')\n",
"step-3": "print (\"Hello Workls!\")\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def test_pixel_pixelMatchesColor():
"""屏幕像素获取、屏幕像素匹配"""
print(pixelMatchesColor(44, 107, (148, 212, 234), tolerance=20))
print(pixelMatchesColor(44, 107, (100, 212, 234), tolerance=20))
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def test_pixel_pixelMatchesColor():
"""屏幕像素获取、屏幕像素匹配"""
print(pixelMatchesColor(44, 107, (148, 212, 234), tolerance=20))
print(pixelMatchesColor(44, 107, (100, 212, 234), tolerance=20))
test_pixel_pixelMatchesColor()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
from pyautogui import pixel, pixelMatchesColor, screenshot
<|reserved_special_token_0|>
def test_pixel_pixelMatchesColor():
"""屏幕像素获取、屏幕像素匹配"""
print(pixelMatchesColor(44, 107, (148, 212, 234), tolerance=20))
print(pixelMatchesColor(44, 107, (100, 212, 234), tolerance=20))
test_pixel_pixelMatchesColor()
<|reserved_special_token_1|>
"""
pyautogui 屏幕像素获取、屏幕像素匹配
@author : zhouhuajian
@version : v1.0
"""
from pyautogui import pixel, pixelMatchesColor, screenshot
"""
主要内容:
1. pixel() - 获取屏幕像素;
2. pixelMatchesColor() - 屏幕像素匹配颜色。
"""
def test_pixel_pixelMatchesColor():
"""屏幕像素获取、屏幕像素匹配"""
# img = screenshot()
# print(img)
# print(img.getpixel((44, 107)))
# (149, 212, 234)
# print(pixel(44, 107))
# 根据上面返回值修改color
# print(pixelMatchesColor(44, 107, (149, 212, 234)))
# print(pixelMatchesColor(44, 107, (148, 212, 234)))
# color简单调整
print(pixelMatchesColor(44, 107, (148, 212, 234), tolerance=20))
print(pixelMatchesColor(44, 107, (100, 212, 234), tolerance=20))
# 看看小项目 重试、等待
test_pixel_pixelMatchesColor()
|
flexible
|
{
"blob_id": "c15faf9df8fa2e1ad89ea2c922ab0551eaa69d3f",
"index": 1936,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef test_pixel_pixelMatchesColor():\n \"\"\"屏幕像素获取、屏幕像素匹配\"\"\"\n print(pixelMatchesColor(44, 107, (148, 212, 234), tolerance=20))\n print(pixelMatchesColor(44, 107, (100, 212, 234), tolerance=20))\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef test_pixel_pixelMatchesColor():\n \"\"\"屏幕像素获取、屏幕像素匹配\"\"\"\n print(pixelMatchesColor(44, 107, (148, 212, 234), tolerance=20))\n print(pixelMatchesColor(44, 107, (100, 212, 234), tolerance=20))\n\n\ntest_pixel_pixelMatchesColor()\n",
"step-4": "<mask token>\nfrom pyautogui import pixel, pixelMatchesColor, screenshot\n<mask token>\n\n\ndef test_pixel_pixelMatchesColor():\n \"\"\"屏幕像素获取、屏幕像素匹配\"\"\"\n print(pixelMatchesColor(44, 107, (148, 212, 234), tolerance=20))\n print(pixelMatchesColor(44, 107, (100, 212, 234), tolerance=20))\n\n\ntest_pixel_pixelMatchesColor()\n",
"step-5": "\"\"\"\npyautogui 屏幕像素获取、屏幕像素匹配\n\n@author : zhouhuajian\n@version : v1.0\n\"\"\"\n\nfrom pyautogui import pixel, pixelMatchesColor, screenshot\n\n\"\"\"\n主要内容:\n1. pixel() - 获取屏幕像素;\n2. pixelMatchesColor() - 屏幕像素匹配颜色。\n\"\"\"\n\n\ndef test_pixel_pixelMatchesColor():\n \"\"\"屏幕像素获取、屏幕像素匹配\"\"\"\n # img = screenshot()\n # print(img)\n # print(img.getpixel((44, 107)))\n # (149, 212, 234)\n\n # print(pixel(44, 107))\n\n # 根据上面返回值修改color\n # print(pixelMatchesColor(44, 107, (149, 212, 234)))\n # print(pixelMatchesColor(44, 107, (148, 212, 234)))\n\n # color简单调整\n print(pixelMatchesColor(44, 107, (148, 212, 234), tolerance=20))\n print(pixelMatchesColor(44, 107, (100, 212, 234), tolerance=20))\n\n # 看看小项目 重试、等待\n\n\ntest_pixel_pixelMatchesColor()\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
#dict1 = {"я":"i","люблю":"love","Питон":"Рython"}
#user_input = input("---->")
#print(dict1[user_input])
#list1 =[i for i in range(0,101) if i%7 ==0 if i%5 !=0]
#print(list1)
#stroka = "я обычная строка быть которая должна быть длиннее чем десять символ"
#stroka1=stroka.split()
#dict1={}
#for i in stroka1:
# dict1[i] = stroka.count(i)
#print(dict1)
# #ФУНКЦИИ
##1.
##def foo():
## print("Мой любимый фильм ето ",input())
##foo()
##2.
##import random
##def rand():
## rn = random.randint(0,10)
## return rn
##x=rand()
##print(x)
##list1=[]
##for i in range(0,10):
## list1.append(rand())
##print(list1)
##3.
##def arifm(*x):
## return(sum(x)/len(x))
##print(arifm(1,2,4,5,6))
##4.
##def dict2(x,y):
## return {x:y}
##dict1 = {}
##dict1.update(dict2("GB","London"))
##print(dict1)
##dict5 = {}
##dict5.update(dict2("Hungary","Budapest"))
##print(dict5)
|
normal
|
{
"blob_id": "c0512a90b6a4e50c41d630f6853d1244f78debfb",
"index": 4350,
"step-1": "#dict1 = {\"я\":\"i\",\"люблю\":\"love\",\"Питон\":\"Рython\"}\n#user_input = input(\"---->\")\n#print(dict1[user_input])\n\n\n#list1 =[i for i in range(0,101) if i%7 ==0 if i%5 !=0]\n#print(list1)\n\n\n\n#stroka = \"я обычная строка быть которая должна быть длиннее чем десять символ\"\n\n#stroka1=stroka.split()\n#dict1={}\n#for i in stroka1:\n# dict1[i] = stroka.count(i)\n#print(dict1)\n\n\n\n# #ФУНКЦИИ\n\n##1.\n##def foo():\n## print(\"Мой любимый фильм ето \",input())\n##foo()\n\n##2.\n##import random \n\n##def rand():\n## rn = random.randint(0,10)\n## return rn\n##x=rand()\n##print(x)\n\n##list1=[]\n\n##for i in range(0,10):\n## list1.append(rand())\n##print(list1)\n\n##3.\n##def arifm(*x):\n## return(sum(x)/len(x))\n##print(arifm(1,2,4,5,6))\n\n##4.\n##def dict2(x,y):\n## return {x:y}\n\n##dict1 = {}\n##dict1.update(dict2(\"GB\",\"London\"))\n##print(dict1)\n\n##dict5 = {}\n##dict5.update(dict2(\"Hungary\",\"Budapest\"))\n##print(dict5)\n\n\n",
"step-2": null,
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
1
]
}
|
[
1
] |
<|reserved_special_token_0|>
def get_links_from_markdown(path, name):
try:
with open(path, 'r') as file:
md = file.read()
html = markdown.markdown(md)
soup = BeautifulSoup(html, 'html.parser')
return soup.find_all('a')
except PermissionError:
print('Could not open "%s"' % path)
except UnicodeDecodeError:
print('Could not proccess "%s"' % path)
return []
def get_guide_packages(src_dir='content'):
if len(sys.argv) > 1:
src_dir = sys.argv[1]
subjects = defaultdict(list)
for entry in os.scandir(src_dir):
name = entry.name[:-3]
for link in get_links_from_markdown(entry.path, name):
if len(link.text.split(':')) == 2:
subjects[name].append(link.text)
return subjects
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def get_links_from_markdown(path, name):
try:
with open(path, 'r') as file:
md = file.read()
html = markdown.markdown(md)
soup = BeautifulSoup(html, 'html.parser')
return soup.find_all('a')
except PermissionError:
print('Could not open "%s"' % path)
except UnicodeDecodeError:
print('Could not proccess "%s"' % path)
return []
def get_guide_packages(src_dir='content'):
if len(sys.argv) > 1:
src_dir = sys.argv[1]
subjects = defaultdict(list)
for entry in os.scandir(src_dir):
name = entry.name[:-3]
for link in get_links_from_markdown(entry.path, name):
if len(link.text.split(':')) == 2:
subjects[name].append(link.text)
return subjects
def write_packages(packages, path='packages-guide'):
with open(path, 'w') as out:
out.write('\n# packages from http://guide.meteor.com\n')
for subject, links in packages.items():
out.write('\n# %s\n' % subject)
for link in links:
out.write('%s\n' % link)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def get_links_from_markdown(path, name):
try:
with open(path, 'r') as file:
md = file.read()
html = markdown.markdown(md)
soup = BeautifulSoup(html, 'html.parser')
return soup.find_all('a')
except PermissionError:
print('Could not open "%s"' % path)
except UnicodeDecodeError:
print('Could not proccess "%s"' % path)
return []
def get_guide_packages(src_dir='content'):
if len(sys.argv) > 1:
src_dir = sys.argv[1]
subjects = defaultdict(list)
for entry in os.scandir(src_dir):
name = entry.name[:-3]
for link in get_links_from_markdown(entry.path, name):
if len(link.text.split(':')) == 2:
subjects[name].append(link.text)
return subjects
def write_packages(packages, path='packages-guide'):
with open(path, 'w') as out:
out.write('\n# packages from http://guide.meteor.com\n')
for subject, links in packages.items():
out.write('\n# %s\n' % subject)
for link in links:
out.write('%s\n' % link)
if __name__ == '__main__':
GUIDE = get_guide_packages()
write_packages(GUIDE)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
from collections import defaultdict
import os
import sys
import markdown
from bs4 import BeautifulSoup
def get_links_from_markdown(path, name):
try:
with open(path, 'r') as file:
md = file.read()
html = markdown.markdown(md)
soup = BeautifulSoup(html, 'html.parser')
return soup.find_all('a')
except PermissionError:
print('Could not open "%s"' % path)
except UnicodeDecodeError:
print('Could not proccess "%s"' % path)
return []
def get_guide_packages(src_dir='content'):
if len(sys.argv) > 1:
src_dir = sys.argv[1]
subjects = defaultdict(list)
for entry in os.scandir(src_dir):
name = entry.name[:-3]
for link in get_links_from_markdown(entry.path, name):
if len(link.text.split(':')) == 2:
subjects[name].append(link.text)
return subjects
def write_packages(packages, path='packages-guide'):
with open(path, 'w') as out:
out.write('\n# packages from http://guide.meteor.com\n')
for subject, links in packages.items():
out.write('\n# %s\n' % subject)
for link in links:
out.write('%s\n' % link)
if __name__ == '__main__':
GUIDE = get_guide_packages()
write_packages(GUIDE)
<|reserved_special_token_1|>
''' extract package names from the Meteor guide and write them to packages-guide
Uses the content folder of https://github.com/meteor/guide '''
from collections import defaultdict
import os
import sys
import markdown
from bs4 import BeautifulSoup
def get_links_from_markdown(path, name):
try:
with open(path, 'r') as file:
md = file.read()
html = markdown.markdown(md)
soup = BeautifulSoup(html, 'html.parser')
return soup.find_all('a')
except PermissionError:
print('Could not open "%s"' % path)
except UnicodeDecodeError:
print('Could not proccess "%s"' % path)
return []
def get_guide_packages(src_dir='content'):
if len(sys.argv) > 1:
src_dir = sys.argv[1]
subjects = defaultdict(list)
for entry in os.scandir(src_dir):
name = entry.name[:-3]
for link in get_links_from_markdown(entry.path, name):
if len(link.text.split(':')) == 2: # packages only
subjects[name].append(link.text)
return subjects
def write_packages(packages, path='packages-guide'):
with open(path, 'w') as out:
out.write('\n# packages from http://guide.meteor.com\n')
for subject, links in packages.items():
out.write('\n# %s\n' % subject)
for link in links:
out.write('%s\n' % link)
if __name__ == '__main__':
GUIDE = get_guide_packages()
write_packages(GUIDE)
|
flexible
|
{
"blob_id": "274185896ab5c11256d69699df69fc2c0dde4f2d",
"index": 987,
"step-1": "<mask token>\n\n\ndef get_links_from_markdown(path, name):\n try:\n with open(path, 'r') as file:\n md = file.read()\n html = markdown.markdown(md)\n soup = BeautifulSoup(html, 'html.parser')\n return soup.find_all('a')\n except PermissionError:\n print('Could not open \"%s\"' % path)\n except UnicodeDecodeError:\n print('Could not proccess \"%s\"' % path)\n return []\n\n\ndef get_guide_packages(src_dir='content'):\n if len(sys.argv) > 1:\n src_dir = sys.argv[1]\n subjects = defaultdict(list)\n for entry in os.scandir(src_dir):\n name = entry.name[:-3]\n for link in get_links_from_markdown(entry.path, name):\n if len(link.text.split(':')) == 2:\n subjects[name].append(link.text)\n return subjects\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef get_links_from_markdown(path, name):\n try:\n with open(path, 'r') as file:\n md = file.read()\n html = markdown.markdown(md)\n soup = BeautifulSoup(html, 'html.parser')\n return soup.find_all('a')\n except PermissionError:\n print('Could not open \"%s\"' % path)\n except UnicodeDecodeError:\n print('Could not proccess \"%s\"' % path)\n return []\n\n\ndef get_guide_packages(src_dir='content'):\n if len(sys.argv) > 1:\n src_dir = sys.argv[1]\n subjects = defaultdict(list)\n for entry in os.scandir(src_dir):\n name = entry.name[:-3]\n for link in get_links_from_markdown(entry.path, name):\n if len(link.text.split(':')) == 2:\n subjects[name].append(link.text)\n return subjects\n\n\ndef write_packages(packages, path='packages-guide'):\n with open(path, 'w') as out:\n out.write('\\n# packages from http://guide.meteor.com\\n')\n for subject, links in packages.items():\n out.write('\\n# %s\\n' % subject)\n for link in links:\n out.write('%s\\n' % link)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef get_links_from_markdown(path, name):\n try:\n with open(path, 'r') as file:\n md = file.read()\n html = markdown.markdown(md)\n soup = BeautifulSoup(html, 'html.parser')\n return soup.find_all('a')\n except PermissionError:\n print('Could not open \"%s\"' % path)\n except UnicodeDecodeError:\n print('Could not proccess \"%s\"' % path)\n return []\n\n\ndef get_guide_packages(src_dir='content'):\n if len(sys.argv) > 1:\n src_dir = sys.argv[1]\n subjects = defaultdict(list)\n for entry in os.scandir(src_dir):\n name = entry.name[:-3]\n for link in get_links_from_markdown(entry.path, name):\n if len(link.text.split(':')) == 2:\n subjects[name].append(link.text)\n return subjects\n\n\ndef write_packages(packages, path='packages-guide'):\n with open(path, 'w') as out:\n out.write('\\n# packages from http://guide.meteor.com\\n')\n for subject, links in packages.items():\n out.write('\\n# %s\\n' % subject)\n for link in links:\n out.write('%s\\n' % link)\n\n\nif __name__ == '__main__':\n GUIDE = get_guide_packages()\n write_packages(GUIDE)\n",
"step-4": "<mask token>\nfrom collections import defaultdict\nimport os\nimport sys\nimport markdown\nfrom bs4 import BeautifulSoup\n\n\ndef get_links_from_markdown(path, name):\n try:\n with open(path, 'r') as file:\n md = file.read()\n html = markdown.markdown(md)\n soup = BeautifulSoup(html, 'html.parser')\n return soup.find_all('a')\n except PermissionError:\n print('Could not open \"%s\"' % path)\n except UnicodeDecodeError:\n print('Could not proccess \"%s\"' % path)\n return []\n\n\ndef get_guide_packages(src_dir='content'):\n if len(sys.argv) > 1:\n src_dir = sys.argv[1]\n subjects = defaultdict(list)\n for entry in os.scandir(src_dir):\n name = entry.name[:-3]\n for link in get_links_from_markdown(entry.path, name):\n if len(link.text.split(':')) == 2:\n subjects[name].append(link.text)\n return subjects\n\n\ndef write_packages(packages, path='packages-guide'):\n with open(path, 'w') as out:\n out.write('\\n# packages from http://guide.meteor.com\\n')\n for subject, links in packages.items():\n out.write('\\n# %s\\n' % subject)\n for link in links:\n out.write('%s\\n' % link)\n\n\nif __name__ == '__main__':\n GUIDE = get_guide_packages()\n write_packages(GUIDE)\n",
"step-5": "''' extract package names from the Meteor guide and write them to packages-guide\n Uses the content folder of https://github.com/meteor/guide '''\n\nfrom collections import defaultdict\nimport os\nimport sys\n\nimport markdown\nfrom bs4 import BeautifulSoup\n\n\ndef get_links_from_markdown(path, name):\n try:\n with open(path, 'r') as file:\n md = file.read()\n html = markdown.markdown(md)\n soup = BeautifulSoup(html, 'html.parser')\n return soup.find_all('a')\n except PermissionError:\n print('Could not open \"%s\"' % path)\n except UnicodeDecodeError:\n print('Could not proccess \"%s\"' % path)\n return []\n\n\ndef get_guide_packages(src_dir='content'):\n if len(sys.argv) > 1:\n src_dir = sys.argv[1]\n subjects = defaultdict(list)\n for entry in os.scandir(src_dir):\n name = entry.name[:-3]\n for link in get_links_from_markdown(entry.path, name):\n if len(link.text.split(':')) == 2: # packages only\n subjects[name].append(link.text)\n return subjects\n\n\ndef write_packages(packages, path='packages-guide'):\n with open(path, 'w') as out:\n out.write('\\n# packages from http://guide.meteor.com\\n')\n for subject, links in packages.items():\n out.write('\\n# %s\\n' % subject)\n for link in links:\n out.write('%s\\n' % link)\n\n\nif __name__ == '__main__':\n GUIDE = get_guide_packages()\n write_packages(GUIDE)\n",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
ceis_arquivo.reset_index()
ceis_arquivo.info()
<|reserved_special_token_0|>
ceis_sp.to_csv('ceis_sp.csv')
<|reserved_special_token_1|>
<|reserved_special_token_0|>
ceis_arquivo = pd.read_csv('20180225_CEIS.csv', sep=';', encoding='latin_1',
converters={'CPF ou CNPJ do Sancionado': lambda x: str(x)})
ceis_arquivo.reset_index()
ceis_arquivo.info()
ceis_sp = ceis_arquivo[ceis_arquivo['UF Órgão Sancionador'] == 'SP']
ceis_sp.to_csv('ceis_sp.csv')
<|reserved_special_token_1|>
import pandas as pd
ceis_arquivo = pd.read_csv('20180225_CEIS.csv', sep=';', encoding='latin_1',
converters={'CPF ou CNPJ do Sancionado': lambda x: str(x)})
ceis_arquivo.reset_index()
ceis_arquivo.info()
ceis_sp = ceis_arquivo[ceis_arquivo['UF Órgão Sancionador'] == 'SP']
ceis_sp.to_csv('ceis_sp.csv')
<|reserved_special_token_1|>
# -*- coding: utf-8
# @paidatocandeira
# Acessa arquivo do CADASTRO NACIONAL DE EMPRESAS INIDÔNEAS E SUSPENSAS (CEIS) que está no portal da Transparência
#
import pandas as pd
# Parte 2 - pode rodar no Jupyter para ver resultados
# Método lendo direto o arquivo disponível para download (http://www.portaltransparencia.gov.br/downloads/snapshot.asp?c=CEIS#get)
ceis_arquivo = pd.read_csv("20180225_CEIS.csv",sep=';',encoding = 'latin_1', converters={'CPF ou CNPJ do Sancionado': lambda x: str(x)})
# É um arquivo CSV comum, pode abrir em outros programas também
ceis_arquivo.reset_index()
# Exemplo de busca - de SP
ceis_arquivo.info() # mostra nomes de todas colunas
ceis_sp = ceis_arquivo[(ceis_arquivo['UF Órgão Sancionador'] == 'SP')]
ceis_sp.to_csv('ceis_sp.csv') # Salva como CSV só o grupo de SP
|
flexible
|
{
"blob_id": "d2325b07d11e64df0b26d0de9992a6f496e92a30",
"index": 2879,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nceis_arquivo.reset_index()\nceis_arquivo.info()\n<mask token>\nceis_sp.to_csv('ceis_sp.csv')\n",
"step-3": "<mask token>\nceis_arquivo = pd.read_csv('20180225_CEIS.csv', sep=';', encoding='latin_1',\n converters={'CPF ou CNPJ do Sancionado': lambda x: str(x)})\nceis_arquivo.reset_index()\nceis_arquivo.info()\nceis_sp = ceis_arquivo[ceis_arquivo['UF Órgão Sancionador'] == 'SP']\nceis_sp.to_csv('ceis_sp.csv')\n",
"step-4": "import pandas as pd\nceis_arquivo = pd.read_csv('20180225_CEIS.csv', sep=';', encoding='latin_1',\n converters={'CPF ou CNPJ do Sancionado': lambda x: str(x)})\nceis_arquivo.reset_index()\nceis_arquivo.info()\nceis_sp = ceis_arquivo[ceis_arquivo['UF Órgão Sancionador'] == 'SP']\nceis_sp.to_csv('ceis_sp.csv')\n",
"step-5": "# -*- coding: utf-8\n# @paidatocandeira\n# Acessa arquivo do CADASTRO NACIONAL DE EMPRESAS INIDÔNEAS E SUSPENSAS (CEIS) que está no portal da Transparência\n#\n\nimport pandas as pd\n\n# Parte 2 - pode rodar no Jupyter para ver resultados\n# Método lendo direto o arquivo disponível para download (http://www.portaltransparencia.gov.br/downloads/snapshot.asp?c=CEIS#get)\nceis_arquivo = pd.read_csv(\"20180225_CEIS.csv\",sep=';',encoding = 'latin_1', converters={'CPF ou CNPJ do Sancionado': lambda x: str(x)})\n# É um arquivo CSV comum, pode abrir em outros programas também\nceis_arquivo.reset_index()\n# Exemplo de busca - de SP\nceis_arquivo.info() # mostra nomes de todas colunas\nceis_sp = ceis_arquivo[(ceis_arquivo['UF Órgão Sancionador'] == 'SP')]\nceis_sp.to_csv('ceis_sp.csv') # Salva como CSV só o grupo de SP\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
ii = [('CoolWHM.py', 1), ('SoutRD.py', 1), ('BrewDTO.py', 2), (
'FitzRNS2.py', 1), ('LyelCPG3.py', 1), ('TaylIF.py', 2)]
|
flexible
|
{
"blob_id": "fbba928d51ccd08dbac25fcf2098be3a0d494d34",
"index": 6659,
"step-1": "<mask token>\n",
"step-2": "ii = [('CoolWHM.py', 1), ('SoutRD.py', 1), ('BrewDTO.py', 2), (\n 'FitzRNS2.py', 1), ('LyelCPG3.py', 1), ('TaylIF.py', 2)]\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
}
|
[
0,
1
] |
#
# @lc app=leetcode.cn id=784 lang=python3
#
# [784] 字母大小写全排列
#
# @lc code=start
# 回溯法 --> 通过 64 ms 13.5 MB
class Solution:
def __init__(self):
self.result = []
def letterCasePermutation(self, S: str) -> List[str]:
arr = list(S)
self.backtracing(arr, 0)
return self.result
def backtracing(self, arr, start):
if start == len(arr):
self.result.append(''.join(arr))
return
# 把自身递归
self.backtracing(arr, start+1)
# 若是字母,则切换大小写后递归
if arr[start].isalpha():
arr[start] = arr[start].lower() if arr[start].isupper() else arr[start].upper()
self.backtracing(arr, start+1)
# @lc code=end
|
normal
|
{
"blob_id": "632c690261b31c7ac0e1d90c814e3b9a7a0dcb29",
"index": 7663,
"step-1": "class Solution:\n <mask token>\n <mask token>\n <mask token>\n",
"step-2": "class Solution:\n <mask token>\n <mask token>\n\n def backtracing(self, arr, start):\n if start == len(arr):\n self.result.append(''.join(arr))\n return\n self.backtracing(arr, start + 1)\n if arr[start].isalpha():\n arr[start] = arr[start].lower() if arr[start].isupper() else arr[\n start].upper()\n self.backtracing(arr, start + 1)\n",
"step-3": "class Solution:\n\n def __init__(self):\n self.result = []\n <mask token>\n\n def backtracing(self, arr, start):\n if start == len(arr):\n self.result.append(''.join(arr))\n return\n self.backtracing(arr, start + 1)\n if arr[start].isalpha():\n arr[start] = arr[start].lower() if arr[start].isupper() else arr[\n start].upper()\n self.backtracing(arr, start + 1)\n",
"step-4": "class Solution:\n\n def __init__(self):\n self.result = []\n\n def letterCasePermutation(self, S: str) ->List[str]:\n arr = list(S)\n self.backtracing(arr, 0)\n return self.result\n\n def backtracing(self, arr, start):\n if start == len(arr):\n self.result.append(''.join(arr))\n return\n self.backtracing(arr, start + 1)\n if arr[start].isalpha():\n arr[start] = arr[start].lower() if arr[start].isupper() else arr[\n start].upper()\n self.backtracing(arr, start + 1)\n",
"step-5": "#\n# @lc app=leetcode.cn id=784 lang=python3\n#\n# [784] 字母大小写全排列\n#\n\n# @lc code=start\n# 回溯法 --> 通过 64 ms 13.5 MB\nclass Solution:\n def __init__(self):\n self.result = []\n\n def letterCasePermutation(self, S: str) -> List[str]:\n arr = list(S)\n self.backtracing(arr, 0)\n return self.result\n\n def backtracing(self, arr, start):\n if start == len(arr):\n self.result.append(''.join(arr))\n return\n # 把自身递归\n self.backtracing(arr, start+1)\n # 若是字母,则切换大小写后递归\n if arr[start].isalpha():\n arr[start] = arr[start].lower() if arr[start].isupper() else arr[start].upper()\n self.backtracing(arr, start+1)\n \n# @lc code=end\n\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
class System:
<|reserved_special_token_0|>
def bind_manager(self, manager):
self.manager = manager
<|reserved_special_token_0|>
def process(self, entity, deltaTime):
pass
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def update_entity_registration(self, entity):
contains = entity.id in self.entity_ids
matches = self.matches(entity)
if contains and not matches:
self.entity_ids.remove(entity.id)
elif not contains and matches:
self.entity_ids.add(entity.id)
def matches(self, entity):
for required in self.required:
if not entity.has_component(required):
return False
return True
class Manager:
def __init__(self):
self.entities = {}
self.current_id = 0
self.systems = []
def create_entity(self):
entity = Entity(self.current_id)
self.current_id += 1
self.entities[entity.id] = entity
return entity
def get_entity_by_id(self, id):
return self.entities[id]
def add_component_to_entity(self, entity, component):
entity.add_component(component)
self.update_entity_registration(entity)
def add_system(self, system):
system.bind_manager(self)
self.systems.append(system)
def update(self, deltaTime):
for system in self.systems:
system.update(deltaTime)
def update_entity_registration(self, entity):
for system in self.systems:
system.update_entity_registration(entity)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class System:
<|reserved_special_token_0|>
def bind_manager(self, manager):
self.manager = manager
def update(self, deltaTime):
self.begin()
for entity_id in self.entity_ids:
entity = self.manager.get_entity_by_id(entity_id)
self.process(entity, deltaTime)
self.end()
def process(self, entity, deltaTime):
pass
<|reserved_special_token_0|>
<|reserved_special_token_0|>
def update_entity_registration(self, entity):
contains = entity.id in self.entity_ids
matches = self.matches(entity)
if contains and not matches:
self.entity_ids.remove(entity.id)
elif not contains and matches:
self.entity_ids.add(entity.id)
def matches(self, entity):
for required in self.required:
if not entity.has_component(required):
return False
return True
class Manager:
def __init__(self):
self.entities = {}
self.current_id = 0
self.systems = []
def create_entity(self):
entity = Entity(self.current_id)
self.current_id += 1
self.entities[entity.id] = entity
return entity
def get_entity_by_id(self, id):
return self.entities[id]
def add_component_to_entity(self, entity, component):
entity.add_component(component)
self.update_entity_registration(entity)
def add_system(self, system):
system.bind_manager(self)
self.systems.append(system)
def update(self, deltaTime):
for system in self.systems:
system.update(deltaTime)
def update_entity_registration(self, entity):
for system in self.systems:
system.update_entity_registration(entity)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class System:
def __init__(self, *required):
self.required = required
self.entity_ids = set()
def bind_manager(self, manager):
self.manager = manager
def update(self, deltaTime):
self.begin()
for entity_id in self.entity_ids:
entity = self.manager.get_entity_by_id(entity_id)
self.process(entity, deltaTime)
self.end()
def process(self, entity, deltaTime):
pass
def begin(self):
pass
def end(self):
pass
def update_entity_registration(self, entity):
contains = entity.id in self.entity_ids
matches = self.matches(entity)
if contains and not matches:
self.entity_ids.remove(entity.id)
elif not contains and matches:
self.entity_ids.add(entity.id)
def matches(self, entity):
for required in self.required:
if not entity.has_component(required):
return False
return True
class Manager:
def __init__(self):
self.entities = {}
self.current_id = 0
self.systems = []
def create_entity(self):
entity = Entity(self.current_id)
self.current_id += 1
self.entities[entity.id] = entity
return entity
def get_entity_by_id(self, id):
return self.entities[id]
def add_component_to_entity(self, entity, component):
entity.add_component(component)
self.update_entity_registration(entity)
def add_system(self, system):
system.bind_manager(self)
self.systems.append(system)
def update(self, deltaTime):
for system in self.systems:
system.update(deltaTime)
def update_entity_registration(self, entity):
for system in self.systems:
system.update_entity_registration(entity)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Entity:
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class System:
def __init__(self, *required):
self.required = required
self.entity_ids = set()
def bind_manager(self, manager):
self.manager = manager
def update(self, deltaTime):
self.begin()
for entity_id in self.entity_ids:
entity = self.manager.get_entity_by_id(entity_id)
self.process(entity, deltaTime)
self.end()
def process(self, entity, deltaTime):
pass
def begin(self):
pass
def end(self):
pass
def update_entity_registration(self, entity):
contains = entity.id in self.entity_ids
matches = self.matches(entity)
if contains and not matches:
self.entity_ids.remove(entity.id)
elif not contains and matches:
self.entity_ids.add(entity.id)
def matches(self, entity):
for required in self.required:
if not entity.has_component(required):
return False
return True
class Manager:
def __init__(self):
self.entities = {}
self.current_id = 0
self.systems = []
def create_entity(self):
entity = Entity(self.current_id)
self.current_id += 1
self.entities[entity.id] = entity
return entity
def get_entity_by_id(self, id):
return self.entities[id]
def add_component_to_entity(self, entity, component):
entity.add_component(component)
self.update_entity_registration(entity)
def add_system(self, system):
system.bind_manager(self)
self.systems.append(system)
def update(self, deltaTime):
for system in self.systems:
system.update(deltaTime)
def update_entity_registration(self, entity):
for system in self.systems:
system.update_entity_registration(entity)
<|reserved_special_token_1|>
class Component:
pass
class Entity:
def __init__(self, id):
self.id = id
self.components = {}
def add_component(self, component):
if type(component) in self.components:
raise Exception("This entity already has a component of that type")
# Since there is only one of each type of component, they are stored by type
self.components[type(component)] = component
def has_component(self, component_type):
return component_type in self.components
def get_component(self, component_type):
return self.components[component_type]
class System:
def __init__(self, *required):
self.required = required
self.entity_ids = set()
def bind_manager(self, manager):
self.manager = manager
def update(self, deltaTime):
self.begin()
for entity_id in self.entity_ids:
entity = self.manager.get_entity_by_id(entity_id)
self.process(entity, deltaTime)
self.end()
# Overridden in the derived class to specify functionality of system
def process(self, entity, deltaTime):
pass
# Can be overridden if you want to do something before the first entity is processed
def begin(self):
pass
# Can be overridden if you want to do something after the last entity is processed
def end(self):
pass
def update_entity_registration(self, entity):
contains = entity.id in self.entity_ids
matches = self.matches(entity)
# Already exists, but no longer matches
if contains and not matches:
self.entity_ids.remove(entity.id)
# Doesn't exist, but does match
elif not contains and matches:
self.entity_ids.add(entity.id)
def matches(self, entity):
for required in self.required:
if not entity.has_component(required):
return False
return True
class Manager:
def __init__(self):
self.entities = {}
self.current_id = 0
self.systems = []
def create_entity(self):
entity = Entity(self.current_id)
self.current_id += 1
self.entities[entity.id] = entity
return entity
def get_entity_by_id(self, id):
return self.entities[id]
# Use this to add components, not the entity method!! Wish there was a way to enforce that in python
def add_component_to_entity(self, entity, component):
entity.add_component(component)
self.update_entity_registration(entity)
def add_system(self, system):
system.bind_manager(self)
self.systems.append(system)
def update(self, deltaTime):
for system in self.systems:
system.update(deltaTime)
def update_entity_registration(self, entity):
for system in self.systems:
system.update_entity_registration(entity)
|
flexible
|
{
"blob_id": "14f7f31fa64799cdc08b1363b945da50841d16b5",
"index": 3020,
"step-1": "<mask token>\n\n\nclass System:\n <mask token>\n\n def bind_manager(self, manager):\n self.manager = manager\n <mask token>\n\n def process(self, entity, deltaTime):\n pass\n <mask token>\n <mask token>\n\n def update_entity_registration(self, entity):\n contains = entity.id in self.entity_ids\n matches = self.matches(entity)\n if contains and not matches:\n self.entity_ids.remove(entity.id)\n elif not contains and matches:\n self.entity_ids.add(entity.id)\n\n def matches(self, entity):\n for required in self.required:\n if not entity.has_component(required):\n return False\n return True\n\n\nclass Manager:\n\n def __init__(self):\n self.entities = {}\n self.current_id = 0\n self.systems = []\n\n def create_entity(self):\n entity = Entity(self.current_id)\n self.current_id += 1\n self.entities[entity.id] = entity\n return entity\n\n def get_entity_by_id(self, id):\n return self.entities[id]\n\n def add_component_to_entity(self, entity, component):\n entity.add_component(component)\n self.update_entity_registration(entity)\n\n def add_system(self, system):\n system.bind_manager(self)\n self.systems.append(system)\n\n def update(self, deltaTime):\n for system in self.systems:\n system.update(deltaTime)\n\n def update_entity_registration(self, entity):\n for system in self.systems:\n system.update_entity_registration(entity)\n",
"step-2": "<mask token>\n\n\nclass System:\n <mask token>\n\n def bind_manager(self, manager):\n self.manager = manager\n\n def update(self, deltaTime):\n self.begin()\n for entity_id in self.entity_ids:\n entity = self.manager.get_entity_by_id(entity_id)\n self.process(entity, deltaTime)\n self.end()\n\n def process(self, entity, deltaTime):\n pass\n <mask token>\n <mask token>\n\n def update_entity_registration(self, entity):\n contains = entity.id in self.entity_ids\n matches = self.matches(entity)\n if contains and not matches:\n self.entity_ids.remove(entity.id)\n elif not contains and matches:\n self.entity_ids.add(entity.id)\n\n def matches(self, entity):\n for required in self.required:\n if not entity.has_component(required):\n return False\n return True\n\n\nclass Manager:\n\n def __init__(self):\n self.entities = {}\n self.current_id = 0\n self.systems = []\n\n def create_entity(self):\n entity = Entity(self.current_id)\n self.current_id += 1\n self.entities[entity.id] = entity\n return entity\n\n def get_entity_by_id(self, id):\n return self.entities[id]\n\n def add_component_to_entity(self, entity, component):\n entity.add_component(component)\n self.update_entity_registration(entity)\n\n def add_system(self, system):\n system.bind_manager(self)\n self.systems.append(system)\n\n def update(self, deltaTime):\n for system in self.systems:\n system.update(deltaTime)\n\n def update_entity_registration(self, entity):\n for system in self.systems:\n system.update_entity_registration(entity)\n",
"step-3": "<mask token>\n\n\nclass System:\n\n def __init__(self, *required):\n self.required = required\n self.entity_ids = set()\n\n def bind_manager(self, manager):\n self.manager = manager\n\n def update(self, deltaTime):\n self.begin()\n for entity_id in self.entity_ids:\n entity = self.manager.get_entity_by_id(entity_id)\n self.process(entity, deltaTime)\n self.end()\n\n def process(self, entity, deltaTime):\n pass\n\n def begin(self):\n pass\n\n def end(self):\n pass\n\n def update_entity_registration(self, entity):\n contains = entity.id in self.entity_ids\n matches = self.matches(entity)\n if contains and not matches:\n self.entity_ids.remove(entity.id)\n elif not contains and matches:\n self.entity_ids.add(entity.id)\n\n def matches(self, entity):\n for required in self.required:\n if not entity.has_component(required):\n return False\n return True\n\n\nclass Manager:\n\n def __init__(self):\n self.entities = {}\n self.current_id = 0\n self.systems = []\n\n def create_entity(self):\n entity = Entity(self.current_id)\n self.current_id += 1\n self.entities[entity.id] = entity\n return entity\n\n def get_entity_by_id(self, id):\n return self.entities[id]\n\n def add_component_to_entity(self, entity, component):\n entity.add_component(component)\n self.update_entity_registration(entity)\n\n def add_system(self, system):\n system.bind_manager(self)\n self.systems.append(system)\n\n def update(self, deltaTime):\n for system in self.systems:\n system.update(deltaTime)\n\n def update_entity_registration(self, entity):\n for system in self.systems:\n system.update_entity_registration(entity)\n",
"step-4": "<mask token>\n\n\nclass Entity:\n <mask token>\n <mask token>\n <mask token>\n <mask token>\n\n\nclass System:\n\n def __init__(self, *required):\n self.required = required\n self.entity_ids = set()\n\n def bind_manager(self, manager):\n self.manager = manager\n\n def update(self, deltaTime):\n self.begin()\n for entity_id in self.entity_ids:\n entity = self.manager.get_entity_by_id(entity_id)\n self.process(entity, deltaTime)\n self.end()\n\n def process(self, entity, deltaTime):\n pass\n\n def begin(self):\n pass\n\n def end(self):\n pass\n\n def update_entity_registration(self, entity):\n contains = entity.id in self.entity_ids\n matches = self.matches(entity)\n if contains and not matches:\n self.entity_ids.remove(entity.id)\n elif not contains and matches:\n self.entity_ids.add(entity.id)\n\n def matches(self, entity):\n for required in self.required:\n if not entity.has_component(required):\n return False\n return True\n\n\nclass Manager:\n\n def __init__(self):\n self.entities = {}\n self.current_id = 0\n self.systems = []\n\n def create_entity(self):\n entity = Entity(self.current_id)\n self.current_id += 1\n self.entities[entity.id] = entity\n return entity\n\n def get_entity_by_id(self, id):\n return self.entities[id]\n\n def add_component_to_entity(self, entity, component):\n entity.add_component(component)\n self.update_entity_registration(entity)\n\n def add_system(self, system):\n system.bind_manager(self)\n self.systems.append(system)\n\n def update(self, deltaTime):\n for system in self.systems:\n system.update(deltaTime)\n\n def update_entity_registration(self, entity):\n for system in self.systems:\n system.update_entity_registration(entity)\n",
"step-5": "\nclass Component:\n pass\n\nclass Entity:\n\n def __init__(self, id):\n self.id = id\n self.components = {}\n\n def add_component(self, component):\n if type(component) in self.components:\n raise Exception(\"This entity already has a component of that type\")\n\n # Since there is only one of each type of component, they are stored by type\n self.components[type(component)] = component\n\n def has_component(self, component_type):\n return component_type in self.components\n\n def get_component(self, component_type):\n return self.components[component_type]\n\nclass System:\n\n def __init__(self, *required):\n self.required = required\n self.entity_ids = set()\n\n def bind_manager(self, manager):\n self.manager = manager\n \n def update(self, deltaTime):\n self.begin()\n\n for entity_id in self.entity_ids:\n entity = self.manager.get_entity_by_id(entity_id)\n self.process(entity, deltaTime)\n \n self.end()\n\n # Overridden in the derived class to specify functionality of system\n def process(self, entity, deltaTime):\n pass\n\n # Can be overridden if you want to do something before the first entity is processed\n def begin(self):\n pass\n\n # Can be overridden if you want to do something after the last entity is processed\n def end(self):\n pass\n\n def update_entity_registration(self, entity):\n contains = entity.id in self.entity_ids\n matches = self.matches(entity)\n\n # Already exists, but no longer matches\n if contains and not matches:\n self.entity_ids.remove(entity.id)\n # Doesn't exist, but does match\n elif not contains and matches:\n self.entity_ids.add(entity.id)\n \n def matches(self, entity):\n for required in self.required:\n if not entity.has_component(required):\n return False\n\n return True\n\nclass Manager:\n\n def __init__(self):\n self.entities = {}\n self.current_id = 0\n\n self.systems = []\n \n def create_entity(self):\n entity = Entity(self.current_id)\n self.current_id += 1\n\n self.entities[entity.id] = entity\n return entity\n\n def get_entity_by_id(self, id):\n return self.entities[id]\n\n # Use this to add components, not the entity method!! Wish there was a way to enforce that in python\n def add_component_to_entity(self, entity, component):\n entity.add_component(component)\n self.update_entity_registration(entity)\n \n def add_system(self, system):\n system.bind_manager(self)\n self.systems.append(system)\n\n def update(self, deltaTime):\n for system in self.systems:\n system.update(deltaTime)\n\n def update_entity_registration(self, entity):\n for system in self.systems:\n system.update_entity_registration(entity)\n",
"step-ids": [
13,
14,
17,
18,
24
]
}
|
[
13,
14,
17,
18,
24
] |
<|reserved_special_token_0|>
def bar():
print('Explicit context to bar')
gevent.sleep(0)
print('Implicit contenxt switch back to bar')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def foo():
print('Running in foo')
gevent.sleep(0)
print('Explicit context switch to foo ageni')
def bar():
print('Explicit context to bar')
gevent.sleep(0)
print('Implicit contenxt switch back to bar')
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def foo():
print('Running in foo')
gevent.sleep(0)
print('Explicit context switch to foo ageni')
def bar():
print('Explicit context to bar')
gevent.sleep(0)
print('Implicit contenxt switch back to bar')
gevent.joinall([gevent.spawn(foo), gevent.spawn(bar)])
<|reserved_special_token_1|>
import gevent
def foo():
print('Running in foo')
gevent.sleep(0)
print('Explicit context switch to foo ageni')
def bar():
print('Explicit context to bar')
gevent.sleep(0)
print('Implicit contenxt switch back to bar')
gevent.joinall([gevent.spawn(foo), gevent.spawn(bar)])
<|reserved_special_token_1|>
#!/usr/bin/env python
# -*-coding:utf-8-*-
# Author:SemaseMing <blog.v-api.cn>
# Email: admin@v-api.cn
# Time: 2016-10-19 11:56
import gevent
def foo():
print('Running in foo')
gevent.sleep(0)
print('Explicit context switch to foo ageni')
def bar():
print('Explicit context to bar')
gevent.sleep(0)
print('Implicit contenxt switch back to bar')
gevent.joinall([gevent.spawn(foo), gevent.spawn(bar)])
|
flexible
|
{
"blob_id": "7f131e17f4fbd7d6b333a51dae557ddb07c30046",
"index": 9077,
"step-1": "<mask token>\n\n\ndef bar():\n print('Explicit context to bar')\n gevent.sleep(0)\n print('Implicit contenxt switch back to bar')\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef foo():\n print('Running in foo')\n gevent.sleep(0)\n print('Explicit context switch to foo ageni')\n\n\ndef bar():\n print('Explicit context to bar')\n gevent.sleep(0)\n print('Implicit contenxt switch back to bar')\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef foo():\n print('Running in foo')\n gevent.sleep(0)\n print('Explicit context switch to foo ageni')\n\n\ndef bar():\n print('Explicit context to bar')\n gevent.sleep(0)\n print('Implicit contenxt switch back to bar')\n\n\ngevent.joinall([gevent.spawn(foo), gevent.spawn(bar)])\n",
"step-4": "import gevent\n\n\ndef foo():\n print('Running in foo')\n gevent.sleep(0)\n print('Explicit context switch to foo ageni')\n\n\ndef bar():\n print('Explicit context to bar')\n gevent.sleep(0)\n print('Implicit contenxt switch back to bar')\n\n\ngevent.joinall([gevent.spawn(foo), gevent.spawn(bar)])\n",
"step-5": "#!/usr/bin/env python\n# -*-coding:utf-8-*-\n# Author:SemaseMing <blog.v-api.cn>\n# Email: admin@v-api.cn\n# Time: 2016-10-19 11:56\n\nimport gevent\n\n\ndef foo():\n print('Running in foo')\n gevent.sleep(0)\n print('Explicit context switch to foo ageni')\n\n\ndef bar():\n print('Explicit context to bar')\n gevent.sleep(0)\n print('Implicit contenxt switch back to bar')\n\ngevent.joinall([gevent.spawn(foo), gevent.spawn(bar)])",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
cijferICOR = float(input('Wat is je cijfer voor ICOR?: '))
x = 30
beloningICOR = cijferICOR * x
beloning = 'beloning €'
print(beloning, beloningICOR)
cijferPROG = float(input('Wat is je cijfer voor PROG: '))
beloningPROG = cijferPROG * x
print(beloning, beloningPROG)
cijferCSN = float(input('Wat is je cijfer voor CSN?: '))
beloningCSN = cijferCSN * x
print(beloning, beloningCSN)
gemiddelde = beloningICOR + beloningPROG + beloningCSN
print('de gemiddelde beloning is:€ ', gemiddelde / 3)
totalevergoeding = beloningICOR + beloningPROG + beloningCSN
print('uw totale vergoeding is:€ ', totalevergoeding)
gemiddeld_cijfer = (cijferICOR + cijferPROG + cijferCSN) / 3
print('mijn cijfers gemiddeld is een', gemiddeld_cijfer,
'en dat levert een beloning op van: €', totalevergoeding)
|
normal
|
{
"blob_id": "74bca94cbcba0851e13d855c02fbc13fb0b09e6a",
"index": 4263,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(beloning, beloningICOR)\n<mask token>\nprint(beloning, beloningPROG)\n<mask token>\nprint(beloning, beloningCSN)\n<mask token>\nprint('de gemiddelde beloning is:€ ', gemiddelde / 3)\n<mask token>\nprint('uw totale vergoeding is:€ ', totalevergoeding)\n<mask token>\nprint('mijn cijfers gemiddeld is een', gemiddeld_cijfer,\n 'en dat levert een beloning op van: €', totalevergoeding)\n",
"step-3": "cijferICOR = float(input('Wat is je cijfer voor ICOR?: '))\nx = 30\nbeloningICOR = cijferICOR * x\nbeloning = 'beloning €'\nprint(beloning, beloningICOR)\ncijferPROG = float(input('Wat is je cijfer voor PROG: '))\nbeloningPROG = cijferPROG * x\nprint(beloning, beloningPROG)\ncijferCSN = float(input('Wat is je cijfer voor CSN?: '))\nbeloningCSN = cijferCSN * x\nprint(beloning, beloningCSN)\ngemiddelde = beloningICOR + beloningPROG + beloningCSN\nprint('de gemiddelde beloning is:€ ', gemiddelde / 3)\ntotalevergoeding = beloningICOR + beloningPROG + beloningCSN\nprint('uw totale vergoeding is:€ ', totalevergoeding)\ngemiddeld_cijfer = (cijferICOR + cijferPROG + cijferCSN) / 3\nprint('mijn cijfers gemiddeld is een', gemiddeld_cijfer,\n 'en dat levert een beloning op van: €', totalevergoeding)\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 29 19:10:06 2018
@author: labuser
"""
# 2018-09-29
import os
import numpy as np
from scipy.stats import cauchy
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
import pandas as pd
def limit_scan(fname, ax):
data = pd.read_csv(fname, sep='\t', comment="#", index_col=False)
data['sig'] = data['s'] - data['sb']
data.sort_values(by='f', inplace=True)
data.plot(x='f', y='sig', ax=ax)
return
def limit():
"""Using the HP 214B, see what the DIL is."""
fig, ax = plt.subplots()
fname = "1_lim_dye.txt"
folder = os.path.join("..", "2018-09-29")
fname = os.path.join(folder, fname)
limit_scan(fname, ax)
fname = "2_lim_dye.txt"
folder = os.path.join("..", "2018-09-29")
fname = os.path.join(folder, fname)
limit_scan(fname, ax)
return
def cauchy_model(x, a, loc, scale, y0):
return a*cauchy.pdf(x, loc, scale) + y0
def cauchy_fit(x, y, d):
if d is -1:
a0 = -(max(y) - min(y))*(max(x) - min(x))/10
loc0 = x[np.argmin(y)]
scale0 = (max(x) - min(x))/10
y00 = max(y)
elif d is 1:
a0 = (max(y) - min(y))*(max(x) - min(x))/10
loc0 = x[np.argmax(y)]
scale0 = (max(x) - min(x))/10
y00 = min(y)
else:
a0 = 1
loc0 = np.mean(x)
scale0 = (max(x) - min(x))/10
y00 = 1
p0 = [a0, loc0, scale0, y00]
print(p0)
popt, pcov = curve_fit(cauchy_model, x, y, p0)
print("Center Frequency is : ", popt[1]*1e-6, " MHz")
print("FWHM is : ", 2*popt[2]*1e-6, " MHz")
print("Q is : ", popt[1]/(2*popt[2]))
return popt
def mw_fscan(fname, d, ax, plotting=True):
data = pd.read_csv(fname, sep="\t", comment="#", index_col=False,
header=None, names=['f', 'b', 's', 'r'])
data.sort_values(by='f', inplace=True)
data['sig'] = data['s'] - data['b']
data['ref'] = data['r'] - data['b']
data['nrm'] = data['sig'] / data['ref'] # norm by signal / reference
data['nrm'] = data['nrm']
popt = cauchy_fit(data['f'].values, data['nrm'].values, d)
# print(popt)
if plotting is True:
data.plot(x='f', y='nrm', ax=ax)
ax.plot(data['f'].values, cauchy_model(data['f'].values, *popt))
ax.plot(data['f'].values,
data['nrm'].values - cauchy_model(data['f'].values, *popt))
return data
def cavity_resonances():
"""Using the dye laser at -180 GHz, the MW f is scanned over the
cavity resonances, finding center, FWHM, and Q values."""
fig, axes = plt.subplots()
folder = os.path.join("..", "2018-09-29")
fname = "3_fscan.txt"
fname = os.path.join(folder, fname)
mw_fscan(fname, -1, axes)
axes.axhline(0.9, c='k')
fig.tight_layout()
return
def mwion_scan():
"""Take ratios of MW on / MW off to get ionization rate at different values
of the Variable Attenuator"""
fig, ax = plt.subplots()
# Data from 2018-09-27, using the SFIP
fname = "4_mwion_blnk.txt" # -180 GHz
folder = os.path.join("..", "2018-09-29")
fname = os.path.join(folder, fname)
data = pd.read_csv(fname, sep="\t", comment="#")
data['r'] = data['s1']/data['s2']
data['f'] = np.power(10, data['d']/20) # field equivalent
data.sort_values(by='f', inplace=True)
data.plot(x='f', y='r', marker='v', ax=ax, label="-180 GHz")
return
if __name__ == "__main__":
# limit()
# cavity_resonances()
mwion_scan()
|
normal
|
{
"blob_id": "aee8fa7bc1426945d61421fc72732e43ddadafa1",
"index": 3191,
"step-1": "<mask token>\n\n\ndef cauchy_model(x, a, loc, scale, y0):\n return a * cauchy.pdf(x, loc, scale) + y0\n\n\ndef cauchy_fit(x, y, d):\n if d is -1:\n a0 = -(max(y) - min(y)) * (max(x) - min(x)) / 10\n loc0 = x[np.argmin(y)]\n scale0 = (max(x) - min(x)) / 10\n y00 = max(y)\n elif d is 1:\n a0 = (max(y) - min(y)) * (max(x) - min(x)) / 10\n loc0 = x[np.argmax(y)]\n scale0 = (max(x) - min(x)) / 10\n y00 = min(y)\n else:\n a0 = 1\n loc0 = np.mean(x)\n scale0 = (max(x) - min(x)) / 10\n y00 = 1\n p0 = [a0, loc0, scale0, y00]\n print(p0)\n popt, pcov = curve_fit(cauchy_model, x, y, p0)\n print('Center Frequency is : ', popt[1] * 1e-06, ' MHz')\n print('FWHM is : ', 2 * popt[2] * 1e-06, ' MHz')\n print('Q is : ', popt[1] / (2 * popt[2]))\n return popt\n\n\ndef mw_fscan(fname, d, ax, plotting=True):\n data = pd.read_csv(fname, sep='\\t', comment='#', index_col=False,\n header=None, names=['f', 'b', 's', 'r'])\n data.sort_values(by='f', inplace=True)\n data['sig'] = data['s'] - data['b']\n data['ref'] = data['r'] - data['b']\n data['nrm'] = data['sig'] / data['ref']\n data['nrm'] = data['nrm']\n popt = cauchy_fit(data['f'].values, data['nrm'].values, d)\n if plotting is True:\n data.plot(x='f', y='nrm', ax=ax)\n ax.plot(data['f'].values, cauchy_model(data['f'].values, *popt))\n ax.plot(data['f'].values, data['nrm'].values - cauchy_model(data[\n 'f'].values, *popt))\n return data\n\n\ndef cavity_resonances():\n \"\"\"Using the dye laser at -180 GHz, the MW f is scanned over the\n cavity resonances, finding center, FWHM, and Q values.\"\"\"\n fig, axes = plt.subplots()\n folder = os.path.join('..', '2018-09-29')\n fname = '3_fscan.txt'\n fname = os.path.join(folder, fname)\n mw_fscan(fname, -1, axes)\n axes.axhline(0.9, c='k')\n fig.tight_layout()\n return\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef limit_scan(fname, ax):\n data = pd.read_csv(fname, sep='\\t', comment='#', index_col=False)\n data['sig'] = data['s'] - data['sb']\n data.sort_values(by='f', inplace=True)\n data.plot(x='f', y='sig', ax=ax)\n return\n\n\ndef limit():\n \"\"\"Using the HP 214B, see what the DIL is.\"\"\"\n fig, ax = plt.subplots()\n fname = '1_lim_dye.txt'\n folder = os.path.join('..', '2018-09-29')\n fname = os.path.join(folder, fname)\n limit_scan(fname, ax)\n fname = '2_lim_dye.txt'\n folder = os.path.join('..', '2018-09-29')\n fname = os.path.join(folder, fname)\n limit_scan(fname, ax)\n return\n\n\ndef cauchy_model(x, a, loc, scale, y0):\n return a * cauchy.pdf(x, loc, scale) + y0\n\n\ndef cauchy_fit(x, y, d):\n if d is -1:\n a0 = -(max(y) - min(y)) * (max(x) - min(x)) / 10\n loc0 = x[np.argmin(y)]\n scale0 = (max(x) - min(x)) / 10\n y00 = max(y)\n elif d is 1:\n a0 = (max(y) - min(y)) * (max(x) - min(x)) / 10\n loc0 = x[np.argmax(y)]\n scale0 = (max(x) - min(x)) / 10\n y00 = min(y)\n else:\n a0 = 1\n loc0 = np.mean(x)\n scale0 = (max(x) - min(x)) / 10\n y00 = 1\n p0 = [a0, loc0, scale0, y00]\n print(p0)\n popt, pcov = curve_fit(cauchy_model, x, y, p0)\n print('Center Frequency is : ', popt[1] * 1e-06, ' MHz')\n print('FWHM is : ', 2 * popt[2] * 1e-06, ' MHz')\n print('Q is : ', popt[1] / (2 * popt[2]))\n return popt\n\n\ndef mw_fscan(fname, d, ax, plotting=True):\n data = pd.read_csv(fname, sep='\\t', comment='#', index_col=False,\n header=None, names=['f', 'b', 's', 'r'])\n data.sort_values(by='f', inplace=True)\n data['sig'] = data['s'] - data['b']\n data['ref'] = data['r'] - data['b']\n data['nrm'] = data['sig'] / data['ref']\n data['nrm'] = data['nrm']\n popt = cauchy_fit(data['f'].values, data['nrm'].values, d)\n if plotting is True:\n data.plot(x='f', y='nrm', ax=ax)\n ax.plot(data['f'].values, cauchy_model(data['f'].values, *popt))\n ax.plot(data['f'].values, data['nrm'].values - cauchy_model(data[\n 'f'].values, *popt))\n return data\n\n\ndef cavity_resonances():\n \"\"\"Using the dye laser at -180 GHz, the MW f is scanned over the\n cavity resonances, finding center, FWHM, and Q values.\"\"\"\n fig, axes = plt.subplots()\n folder = os.path.join('..', '2018-09-29')\n fname = '3_fscan.txt'\n fname = os.path.join(folder, fname)\n mw_fscan(fname, -1, axes)\n axes.axhline(0.9, c='k')\n fig.tight_layout()\n return\n\n\ndef mwion_scan():\n \"\"\"Take ratios of MW on / MW off to get ionization rate at different values\n of the Variable Attenuator\"\"\"\n fig, ax = plt.subplots()\n fname = '4_mwion_blnk.txt'\n folder = os.path.join('..', '2018-09-29')\n fname = os.path.join(folder, fname)\n data = pd.read_csv(fname, sep='\\t', comment='#')\n data['r'] = data['s1'] / data['s2']\n data['f'] = np.power(10, data['d'] / 20)\n data.sort_values(by='f', inplace=True)\n data.plot(x='f', y='r', marker='v', ax=ax, label='-180 GHz')\n return\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef limit_scan(fname, ax):\n data = pd.read_csv(fname, sep='\\t', comment='#', index_col=False)\n data['sig'] = data['s'] - data['sb']\n data.sort_values(by='f', inplace=True)\n data.plot(x='f', y='sig', ax=ax)\n return\n\n\ndef limit():\n \"\"\"Using the HP 214B, see what the DIL is.\"\"\"\n fig, ax = plt.subplots()\n fname = '1_lim_dye.txt'\n folder = os.path.join('..', '2018-09-29')\n fname = os.path.join(folder, fname)\n limit_scan(fname, ax)\n fname = '2_lim_dye.txt'\n folder = os.path.join('..', '2018-09-29')\n fname = os.path.join(folder, fname)\n limit_scan(fname, ax)\n return\n\n\ndef cauchy_model(x, a, loc, scale, y0):\n return a * cauchy.pdf(x, loc, scale) + y0\n\n\ndef cauchy_fit(x, y, d):\n if d is -1:\n a0 = -(max(y) - min(y)) * (max(x) - min(x)) / 10\n loc0 = x[np.argmin(y)]\n scale0 = (max(x) - min(x)) / 10\n y00 = max(y)\n elif d is 1:\n a0 = (max(y) - min(y)) * (max(x) - min(x)) / 10\n loc0 = x[np.argmax(y)]\n scale0 = (max(x) - min(x)) / 10\n y00 = min(y)\n else:\n a0 = 1\n loc0 = np.mean(x)\n scale0 = (max(x) - min(x)) / 10\n y00 = 1\n p0 = [a0, loc0, scale0, y00]\n print(p0)\n popt, pcov = curve_fit(cauchy_model, x, y, p0)\n print('Center Frequency is : ', popt[1] * 1e-06, ' MHz')\n print('FWHM is : ', 2 * popt[2] * 1e-06, ' MHz')\n print('Q is : ', popt[1] / (2 * popt[2]))\n return popt\n\n\ndef mw_fscan(fname, d, ax, plotting=True):\n data = pd.read_csv(fname, sep='\\t', comment='#', index_col=False,\n header=None, names=['f', 'b', 's', 'r'])\n data.sort_values(by='f', inplace=True)\n data['sig'] = data['s'] - data['b']\n data['ref'] = data['r'] - data['b']\n data['nrm'] = data['sig'] / data['ref']\n data['nrm'] = data['nrm']\n popt = cauchy_fit(data['f'].values, data['nrm'].values, d)\n if plotting is True:\n data.plot(x='f', y='nrm', ax=ax)\n ax.plot(data['f'].values, cauchy_model(data['f'].values, *popt))\n ax.plot(data['f'].values, data['nrm'].values - cauchy_model(data[\n 'f'].values, *popt))\n return data\n\n\ndef cavity_resonances():\n \"\"\"Using the dye laser at -180 GHz, the MW f is scanned over the\n cavity resonances, finding center, FWHM, and Q values.\"\"\"\n fig, axes = plt.subplots()\n folder = os.path.join('..', '2018-09-29')\n fname = '3_fscan.txt'\n fname = os.path.join(folder, fname)\n mw_fscan(fname, -1, axes)\n axes.axhline(0.9, c='k')\n fig.tight_layout()\n return\n\n\ndef mwion_scan():\n \"\"\"Take ratios of MW on / MW off to get ionization rate at different values\n of the Variable Attenuator\"\"\"\n fig, ax = plt.subplots()\n fname = '4_mwion_blnk.txt'\n folder = os.path.join('..', '2018-09-29')\n fname = os.path.join(folder, fname)\n data = pd.read_csv(fname, sep='\\t', comment='#')\n data['r'] = data['s1'] / data['s2']\n data['f'] = np.power(10, data['d'] / 20)\n data.sort_values(by='f', inplace=True)\n data.plot(x='f', y='r', marker='v', ax=ax, label='-180 GHz')\n return\n\n\nif __name__ == '__main__':\n mwion_scan()\n",
"step-4": "<mask token>\nimport os\nimport numpy as np\nfrom scipy.stats import cauchy\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\ndef limit_scan(fname, ax):\n data = pd.read_csv(fname, sep='\\t', comment='#', index_col=False)\n data['sig'] = data['s'] - data['sb']\n data.sort_values(by='f', inplace=True)\n data.plot(x='f', y='sig', ax=ax)\n return\n\n\ndef limit():\n \"\"\"Using the HP 214B, see what the DIL is.\"\"\"\n fig, ax = plt.subplots()\n fname = '1_lim_dye.txt'\n folder = os.path.join('..', '2018-09-29')\n fname = os.path.join(folder, fname)\n limit_scan(fname, ax)\n fname = '2_lim_dye.txt'\n folder = os.path.join('..', '2018-09-29')\n fname = os.path.join(folder, fname)\n limit_scan(fname, ax)\n return\n\n\ndef cauchy_model(x, a, loc, scale, y0):\n return a * cauchy.pdf(x, loc, scale) + y0\n\n\ndef cauchy_fit(x, y, d):\n if d is -1:\n a0 = -(max(y) - min(y)) * (max(x) - min(x)) / 10\n loc0 = x[np.argmin(y)]\n scale0 = (max(x) - min(x)) / 10\n y00 = max(y)\n elif d is 1:\n a0 = (max(y) - min(y)) * (max(x) - min(x)) / 10\n loc0 = x[np.argmax(y)]\n scale0 = (max(x) - min(x)) / 10\n y00 = min(y)\n else:\n a0 = 1\n loc0 = np.mean(x)\n scale0 = (max(x) - min(x)) / 10\n y00 = 1\n p0 = [a0, loc0, scale0, y00]\n print(p0)\n popt, pcov = curve_fit(cauchy_model, x, y, p0)\n print('Center Frequency is : ', popt[1] * 1e-06, ' MHz')\n print('FWHM is : ', 2 * popt[2] * 1e-06, ' MHz')\n print('Q is : ', popt[1] / (2 * popt[2]))\n return popt\n\n\ndef mw_fscan(fname, d, ax, plotting=True):\n data = pd.read_csv(fname, sep='\\t', comment='#', index_col=False,\n header=None, names=['f', 'b', 's', 'r'])\n data.sort_values(by='f', inplace=True)\n data['sig'] = data['s'] - data['b']\n data['ref'] = data['r'] - data['b']\n data['nrm'] = data['sig'] / data['ref']\n data['nrm'] = data['nrm']\n popt = cauchy_fit(data['f'].values, data['nrm'].values, d)\n if plotting is True:\n data.plot(x='f', y='nrm', ax=ax)\n ax.plot(data['f'].values, cauchy_model(data['f'].values, *popt))\n ax.plot(data['f'].values, data['nrm'].values - cauchy_model(data[\n 'f'].values, *popt))\n return data\n\n\ndef cavity_resonances():\n \"\"\"Using the dye laser at -180 GHz, the MW f is scanned over the\n cavity resonances, finding center, FWHM, and Q values.\"\"\"\n fig, axes = plt.subplots()\n folder = os.path.join('..', '2018-09-29')\n fname = '3_fscan.txt'\n fname = os.path.join(folder, fname)\n mw_fscan(fname, -1, axes)\n axes.axhline(0.9, c='k')\n fig.tight_layout()\n return\n\n\ndef mwion_scan():\n \"\"\"Take ratios of MW on / MW off to get ionization rate at different values\n of the Variable Attenuator\"\"\"\n fig, ax = plt.subplots()\n fname = '4_mwion_blnk.txt'\n folder = os.path.join('..', '2018-09-29')\n fname = os.path.join(folder, fname)\n data = pd.read_csv(fname, sep='\\t', comment='#')\n data['r'] = data['s1'] / data['s2']\n data['f'] = np.power(10, data['d'] / 20)\n data.sort_values(by='f', inplace=True)\n data.plot(x='f', y='r', marker='v', ax=ax, label='-180 GHz')\n return\n\n\nif __name__ == '__main__':\n mwion_scan()\n",
"step-5": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Sep 29 19:10:06 2018\n\n@author: labuser\n\"\"\"\n\n\n# 2018-09-29\n\nimport os\nimport numpy as np\nfrom scipy.stats import cauchy\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n\ndef limit_scan(fname, ax):\n data = pd.read_csv(fname, sep='\\t', comment=\"#\", index_col=False)\n data['sig'] = data['s'] - data['sb']\n data.sort_values(by='f', inplace=True)\n data.plot(x='f', y='sig', ax=ax)\n return\n\n\ndef limit():\n \"\"\"Using the HP 214B, see what the DIL is.\"\"\"\n fig, ax = plt.subplots()\n fname = \"1_lim_dye.txt\"\n folder = os.path.join(\"..\", \"2018-09-29\")\n fname = os.path.join(folder, fname)\n limit_scan(fname, ax)\n fname = \"2_lim_dye.txt\"\n folder = os.path.join(\"..\", \"2018-09-29\")\n fname = os.path.join(folder, fname)\n limit_scan(fname, ax)\n return\n\n\ndef cauchy_model(x, a, loc, scale, y0):\n return a*cauchy.pdf(x, loc, scale) + y0\n\n\ndef cauchy_fit(x, y, d):\n if d is -1:\n a0 = -(max(y) - min(y))*(max(x) - min(x))/10\n loc0 = x[np.argmin(y)]\n scale0 = (max(x) - min(x))/10\n y00 = max(y)\n elif d is 1:\n a0 = (max(y) - min(y))*(max(x) - min(x))/10\n loc0 = x[np.argmax(y)]\n scale0 = (max(x) - min(x))/10\n y00 = min(y)\n else:\n a0 = 1\n loc0 = np.mean(x)\n scale0 = (max(x) - min(x))/10\n y00 = 1\n p0 = [a0, loc0, scale0, y00]\n print(p0)\n popt, pcov = curve_fit(cauchy_model, x, y, p0)\n print(\"Center Frequency is : \", popt[1]*1e-6, \" MHz\")\n print(\"FWHM is : \", 2*popt[2]*1e-6, \" MHz\")\n print(\"Q is : \", popt[1]/(2*popt[2]))\n return popt\n\n\ndef mw_fscan(fname, d, ax, plotting=True):\n data = pd.read_csv(fname, sep=\"\\t\", comment=\"#\", index_col=False,\n header=None, names=['f', 'b', 's', 'r'])\n data.sort_values(by='f', inplace=True)\n data['sig'] = data['s'] - data['b']\n data['ref'] = data['r'] - data['b']\n data['nrm'] = data['sig'] / data['ref'] # norm by signal / reference\n data['nrm'] = data['nrm']\n popt = cauchy_fit(data['f'].values, data['nrm'].values, d)\n # print(popt)\n if plotting is True:\n data.plot(x='f', y='nrm', ax=ax)\n ax.plot(data['f'].values, cauchy_model(data['f'].values, *popt))\n ax.plot(data['f'].values,\n data['nrm'].values - cauchy_model(data['f'].values, *popt))\n return data\n\n\ndef cavity_resonances():\n \"\"\"Using the dye laser at -180 GHz, the MW f is scanned over the\n cavity resonances, finding center, FWHM, and Q values.\"\"\"\n fig, axes = plt.subplots()\n folder = os.path.join(\"..\", \"2018-09-29\")\n fname = \"3_fscan.txt\"\n fname = os.path.join(folder, fname)\n mw_fscan(fname, -1, axes)\n axes.axhline(0.9, c='k')\n fig.tight_layout()\n return\n\n\ndef mwion_scan():\n \"\"\"Take ratios of MW on / MW off to get ionization rate at different values\n of the Variable Attenuator\"\"\"\n fig, ax = plt.subplots()\n # Data from 2018-09-27, using the SFIP\n fname = \"4_mwion_blnk.txt\" # -180 GHz\n folder = os.path.join(\"..\", \"2018-09-29\")\n fname = os.path.join(folder, fname)\n data = pd.read_csv(fname, sep=\"\\t\", comment=\"#\")\n data['r'] = data['s1']/data['s2']\n data['f'] = np.power(10, data['d']/20) # field equivalent\n data.sort_values(by='f', inplace=True)\n data.plot(x='f', y='r', marker='v', ax=ax, label=\"-180 GHz\")\n return\n\n\nif __name__ == \"__main__\":\n # limit()\n # cavity_resonances()\n mwion_scan()\n",
"step-ids": [
4,
7,
8,
9,
10
]
}
|
[
4,
7,
8,
9,
10
] |
<|reserved_special_token_0|>
def PrintaLog(texto):
t = time.time()
logtime = time.ctime(t)
stringprint = '%s %s\n' % (logtime, texto)
f = open('/var/log/patriot', 'a')
f.write(stringprint)
f.flush()
f.close()
def PrintaMSG(texto):
command = 'python3 alertiqt.py "' + texto + '"'
processalert = subprocess.Popen([command], stdout=subprocess.PIPE,
shell=True, stderr=DEVNULL)
<|reserved_special_token_0|>
def ScanConnections():
initialcon = psutil.net_connections()
netprocess = []
for i in initialcon:
p = psutil.Process(pid=i.pid)
with p.oneshot():
netprocess.append(p.exe())
while True:
runcon = psutil.net_connections()
netprocessrun = []
for e in runcon:
p = psutil.Process(pid=e.pid)
with p.oneshot():
netprocessrun.append(p.exe())
s = set(netprocess)
newpconprogs = [x for x in netprocessrun if x not in s]
if newpconprogs:
for h in newpconprogs:
stringprint = (
'New Process initiating TCP/IP connection: %s' % h)
x = threading.Thread(target=PrintaMSG, args=(stringprint,))
x.setDaemon(True)
x.start()
PrintaLog(stringprint)
netprocess.append(h)
time.sleep(2)
def AuSearch():
auparams = {'modules': 'New module loaded in Kernel', 'code_injection':
'DLL Inject', 'register_injection': 'DLL Inject'}
while True:
tomo = datetime.datetime.now() - datetime.timedelta(minutes=2)
timeraw = str(tomo.time().replace(second=0, microsecond=0))
for key in auparams.keys():
command = 'ausearch -k "' + key + '" --start "' + timeraw + '"'
processausearch = subprocess.Popen([command], stdout=subprocess
.PIPE, shell=True, stderr=DEVNULL)
outputausearch = processausearch.communicate()[0]
if outputausearch:
stringprint = 'Audit Alert: %s' % auparams[key]
x = threading.Thread(target=PrintaMSG, args=(stringprint,))
x.setDaemon(True)
x.start()
PrintaLog(stringprint)
time.sleep(115)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def PrintaLog(texto):
t = time.time()
logtime = time.ctime(t)
stringprint = '%s %s\n' % (logtime, texto)
f = open('/var/log/patriot', 'a')
f.write(stringprint)
f.flush()
f.close()
def PrintaMSG(texto):
command = 'python3 alertiqt.py "' + texto + '"'
processalert = subprocess.Popen([command], stdout=subprocess.PIPE,
shell=True, stderr=DEVNULL)
<|reserved_special_token_0|>
def ScanUnsigned():
pidsinicial = psutil.pids()
while True:
pidsshots = psutil.pids()
s = set(pidsinicial)
newpids = [x for x in pidsshots if x not in s]
if newpids:
for i in newpids:
try:
p = psutil.Process(pid=i)
with p.oneshot():
integrity = TestIntegrity(p.exe())
pidproceso = p.pid
exeproceso = p.exe()
evadeau = bool(re.match(exeproceso,
'/usr/sbin/ausearch'))
if integrity == 1 and evadeau == 0:
stringprint = (
'New process that not belongs to any package or package was modified: %i %s'
% (pidproceso, exeproceso))
x = threading.Thread(target=PrintaMSG, args=(
stringprint,))
x.setDaemon(True)
x.start()
PrintaLog(stringprint)
except Exception as e:
print(e)
pidsinicial = pidsshots
time.sleep(2)
def ScanConnections():
initialcon = psutil.net_connections()
netprocess = []
for i in initialcon:
p = psutil.Process(pid=i.pid)
with p.oneshot():
netprocess.append(p.exe())
while True:
runcon = psutil.net_connections()
netprocessrun = []
for e in runcon:
p = psutil.Process(pid=e.pid)
with p.oneshot():
netprocessrun.append(p.exe())
s = set(netprocess)
newpconprogs = [x for x in netprocessrun if x not in s]
if newpconprogs:
for h in newpconprogs:
stringprint = (
'New Process initiating TCP/IP connection: %s' % h)
x = threading.Thread(target=PrintaMSG, args=(stringprint,))
x.setDaemon(True)
x.start()
PrintaLog(stringprint)
netprocess.append(h)
time.sleep(2)
def AuSearch():
auparams = {'modules': 'New module loaded in Kernel', 'code_injection':
'DLL Inject', 'register_injection': 'DLL Inject'}
while True:
tomo = datetime.datetime.now() - datetime.timedelta(minutes=2)
timeraw = str(tomo.time().replace(second=0, microsecond=0))
for key in auparams.keys():
command = 'ausearch -k "' + key + '" --start "' + timeraw + '"'
processausearch = subprocess.Popen([command], stdout=subprocess
.PIPE, shell=True, stderr=DEVNULL)
outputausearch = processausearch.communicate()[0]
if outputausearch:
stringprint = 'Audit Alert: %s' % auparams[key]
x = threading.Thread(target=PrintaMSG, args=(stringprint,))
x.setDaemon(True)
x.start()
PrintaLog(stringprint)
time.sleep(115)
def KeyBoardSearch():
command = 'xinput --list'
keyfirstcommand = subprocess.Popen([command], stdout=subprocess.PIPE,
shell=True)
outputkeysearch = keyfirstcommand.communicate()[0]
while True:
keyruncommand = subprocess.Popen([command], stdout=subprocess.PIPE,
shell=True)
outputkeyrunsearch = keyruncommand.communicate()[0]
if outputkeyrunsearch != outputkeysearch:
stringprint = 'New keyboard detected'
x = threading.Thread(target=PrintaMSG, args=(stringprint,))
x.setDaemon(True)
x.start()
PrintaLog(stringprint)
outputkeysearch = outputkeyrunsearch
time.sleep(60)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
debian = '/etc/debian_version'
redhat = '/etc/redhat-release'
def PrintaLog(texto):
t = time.time()
logtime = time.ctime(t)
stringprint = '%s %s\n' % (logtime, texto)
f = open('/var/log/patriot', 'a')
f.write(stringprint)
f.flush()
f.close()
def PrintaMSG(texto):
command = 'python3 alertiqt.py "' + texto + '"'
processalert = subprocess.Popen([command], stdout=subprocess.PIPE,
shell=True, stderr=DEVNULL)
def TestIntegrity(File):
if os.path.exists(redhat):
command = 'rpm -Vf "' + File + '"'
processrpm = subprocess.Popen([command], stdout=subprocess.PIPE,
shell=True)
outputrpm = processrpm.communicate()[0]
if outputrpm:
return 1
else:
return 0
else:
commandDPKG = 'dpkg -S "' + File + '"'
processdpkg = subprocess.Popen([commandDPKG], stdout=subprocess.
PIPE, shell=True, stderr=DEVNULL)
outputdpkg = processdpkg.communicate()[0]
if processdpkg.returncode == 1:
fixdpkgbug = re.sub('/usr', '', File)
commandDPKG2 = 'dpkg -S "' + fixdpkgbug + '"'
processdpkg2 = subprocess.Popen([commandDPKG2], stdout=
subprocess.PIPE, shell=True, stderr=DEVNULL)
outputdpkg2 = processdpkg2.communicate()[0]
outputdpkg = outputdpkg2
if processdpkg2.returncode == 1:
return 1
packagename = outputdpkg.split(':')
commandDEBSUM = 'dpkg --verify "' + packagename[0] + '"'
processdebsum = subprocess.Popen([commandDEBSUM], stdout=subprocess
.PIPE, shell=True)
outputdebsum = processdebsum.communicate()[0]
print(outputdebsum)
if outputdebsum:
return 1
else:
return 0
def ScanUnsigned():
pidsinicial = psutil.pids()
while True:
pidsshots = psutil.pids()
s = set(pidsinicial)
newpids = [x for x in pidsshots if x not in s]
if newpids:
for i in newpids:
try:
p = psutil.Process(pid=i)
with p.oneshot():
integrity = TestIntegrity(p.exe())
pidproceso = p.pid
exeproceso = p.exe()
evadeau = bool(re.match(exeproceso,
'/usr/sbin/ausearch'))
if integrity == 1 and evadeau == 0:
stringprint = (
'New process that not belongs to any package or package was modified: %i %s'
% (pidproceso, exeproceso))
x = threading.Thread(target=PrintaMSG, args=(
stringprint,))
x.setDaemon(True)
x.start()
PrintaLog(stringprint)
except Exception as e:
print(e)
pidsinicial = pidsshots
time.sleep(2)
def ScanConnections():
initialcon = psutil.net_connections()
netprocess = []
for i in initialcon:
p = psutil.Process(pid=i.pid)
with p.oneshot():
netprocess.append(p.exe())
while True:
runcon = psutil.net_connections()
netprocessrun = []
for e in runcon:
p = psutil.Process(pid=e.pid)
with p.oneshot():
netprocessrun.append(p.exe())
s = set(netprocess)
newpconprogs = [x for x in netprocessrun if x not in s]
if newpconprogs:
for h in newpconprogs:
stringprint = (
'New Process initiating TCP/IP connection: %s' % h)
x = threading.Thread(target=PrintaMSG, args=(stringprint,))
x.setDaemon(True)
x.start()
PrintaLog(stringprint)
netprocess.append(h)
time.sleep(2)
def AuSearch():
auparams = {'modules': 'New module loaded in Kernel', 'code_injection':
'DLL Inject', 'register_injection': 'DLL Inject'}
while True:
tomo = datetime.datetime.now() - datetime.timedelta(minutes=2)
timeraw = str(tomo.time().replace(second=0, microsecond=0))
for key in auparams.keys():
command = 'ausearch -k "' + key + '" --start "' + timeraw + '"'
processausearch = subprocess.Popen([command], stdout=subprocess
.PIPE, shell=True, stderr=DEVNULL)
outputausearch = processausearch.communicate()[0]
if outputausearch:
stringprint = 'Audit Alert: %s' % auparams[key]
x = threading.Thread(target=PrintaMSG, args=(stringprint,))
x.setDaemon(True)
x.start()
PrintaLog(stringprint)
time.sleep(115)
def KeyBoardSearch():
command = 'xinput --list'
keyfirstcommand = subprocess.Popen([command], stdout=subprocess.PIPE,
shell=True)
outputkeysearch = keyfirstcommand.communicate()[0]
while True:
keyruncommand = subprocess.Popen([command], stdout=subprocess.PIPE,
shell=True)
outputkeyrunsearch = keyruncommand.communicate()[0]
if outputkeyrunsearch != outputkeysearch:
stringprint = 'New keyboard detected'
x = threading.Thread(target=PrintaMSG, args=(stringprint,))
x.setDaemon(True)
x.start()
PrintaLog(stringprint)
outputkeysearch = outputkeyrunsearch
time.sleep(60)
s = threading.Thread(target=KeyBoardSearch)
s.setDaemon(True)
s.start()
x = threading.Thread(target=ScanUnsigned)
x.setDaemon(True)
x.start()
y = threading.Thread(target=ScanConnections)
y.setDaemon(True)
y.start()
z = threading.Thread(target=AuSearch)
z.setDaemon(True)
z.start()
while True:
time.sleep(100)
<|reserved_special_token_1|>
import tkinter as tk
import tkinter.messagebox as tkmb
import psutil
import os
import re
import subprocess
from subprocess import Popen, PIPE, STDOUT, DEVNULL
import filecmp
import re
import time
import threading
import datetime
import re
debian = '/etc/debian_version'
redhat = '/etc/redhat-release'
def PrintaLog(texto):
t = time.time()
logtime = time.ctime(t)
stringprint = '%s %s\n' % (logtime, texto)
f = open('/var/log/patriot', 'a')
f.write(stringprint)
f.flush()
f.close()
def PrintaMSG(texto):
command = 'python3 alertiqt.py "' + texto + '"'
processalert = subprocess.Popen([command], stdout=subprocess.PIPE,
shell=True, stderr=DEVNULL)
def TestIntegrity(File):
if os.path.exists(redhat):
command = 'rpm -Vf "' + File + '"'
processrpm = subprocess.Popen([command], stdout=subprocess.PIPE,
shell=True)
outputrpm = processrpm.communicate()[0]
if outputrpm:
return 1
else:
return 0
else:
commandDPKG = 'dpkg -S "' + File + '"'
processdpkg = subprocess.Popen([commandDPKG], stdout=subprocess.
PIPE, shell=True, stderr=DEVNULL)
outputdpkg = processdpkg.communicate()[0]
if processdpkg.returncode == 1:
fixdpkgbug = re.sub('/usr', '', File)
commandDPKG2 = 'dpkg -S "' + fixdpkgbug + '"'
processdpkg2 = subprocess.Popen([commandDPKG2], stdout=
subprocess.PIPE, shell=True, stderr=DEVNULL)
outputdpkg2 = processdpkg2.communicate()[0]
outputdpkg = outputdpkg2
if processdpkg2.returncode == 1:
return 1
packagename = outputdpkg.split(':')
commandDEBSUM = 'dpkg --verify "' + packagename[0] + '"'
processdebsum = subprocess.Popen([commandDEBSUM], stdout=subprocess
.PIPE, shell=True)
outputdebsum = processdebsum.communicate()[0]
print(outputdebsum)
if outputdebsum:
return 1
else:
return 0
def ScanUnsigned():
pidsinicial = psutil.pids()
while True:
pidsshots = psutil.pids()
s = set(pidsinicial)
newpids = [x for x in pidsshots if x not in s]
if newpids:
for i in newpids:
try:
p = psutil.Process(pid=i)
with p.oneshot():
integrity = TestIntegrity(p.exe())
pidproceso = p.pid
exeproceso = p.exe()
evadeau = bool(re.match(exeproceso,
'/usr/sbin/ausearch'))
if integrity == 1 and evadeau == 0:
stringprint = (
'New process that not belongs to any package or package was modified: %i %s'
% (pidproceso, exeproceso))
x = threading.Thread(target=PrintaMSG, args=(
stringprint,))
x.setDaemon(True)
x.start()
PrintaLog(stringprint)
except Exception as e:
print(e)
pidsinicial = pidsshots
time.sleep(2)
def ScanConnections():
initialcon = psutil.net_connections()
netprocess = []
for i in initialcon:
p = psutil.Process(pid=i.pid)
with p.oneshot():
netprocess.append(p.exe())
while True:
runcon = psutil.net_connections()
netprocessrun = []
for e in runcon:
p = psutil.Process(pid=e.pid)
with p.oneshot():
netprocessrun.append(p.exe())
s = set(netprocess)
newpconprogs = [x for x in netprocessrun if x not in s]
if newpconprogs:
for h in newpconprogs:
stringprint = (
'New Process initiating TCP/IP connection: %s' % h)
x = threading.Thread(target=PrintaMSG, args=(stringprint,))
x.setDaemon(True)
x.start()
PrintaLog(stringprint)
netprocess.append(h)
time.sleep(2)
def AuSearch():
auparams = {'modules': 'New module loaded in Kernel', 'code_injection':
'DLL Inject', 'register_injection': 'DLL Inject'}
while True:
tomo = datetime.datetime.now() - datetime.timedelta(minutes=2)
timeraw = str(tomo.time().replace(second=0, microsecond=0))
for key in auparams.keys():
command = 'ausearch -k "' + key + '" --start "' + timeraw + '"'
processausearch = subprocess.Popen([command], stdout=subprocess
.PIPE, shell=True, stderr=DEVNULL)
outputausearch = processausearch.communicate()[0]
if outputausearch:
stringprint = 'Audit Alert: %s' % auparams[key]
x = threading.Thread(target=PrintaMSG, args=(stringprint,))
x.setDaemon(True)
x.start()
PrintaLog(stringprint)
time.sleep(115)
def KeyBoardSearch():
command = 'xinput --list'
keyfirstcommand = subprocess.Popen([command], stdout=subprocess.PIPE,
shell=True)
outputkeysearch = keyfirstcommand.communicate()[0]
while True:
keyruncommand = subprocess.Popen([command], stdout=subprocess.PIPE,
shell=True)
outputkeyrunsearch = keyruncommand.communicate()[0]
if outputkeyrunsearch != outputkeysearch:
stringprint = 'New keyboard detected'
x = threading.Thread(target=PrintaMSG, args=(stringprint,))
x.setDaemon(True)
x.start()
PrintaLog(stringprint)
outputkeysearch = outputkeyrunsearch
time.sleep(60)
s = threading.Thread(target=KeyBoardSearch)
s.setDaemon(True)
s.start()
x = threading.Thread(target=ScanUnsigned)
x.setDaemon(True)
x.start()
y = threading.Thread(target=ScanConnections)
y.setDaemon(True)
y.start()
z = threading.Thread(target=AuSearch)
z.setDaemon(True)
z.start()
while True:
time.sleep(100)
<|reserved_special_token_1|>
import tkinter as tk
import tkinter.messagebox as tkmb
import psutil
import os
import re
import subprocess
from subprocess import Popen, PIPE, STDOUT, DEVNULL
import filecmp
import re
import time
import threading
import datetime
import re
debian = '/etc/debian_version'
redhat = '/etc/redhat-release'
def PrintaLog(texto):
t = time.time()
logtime= time.ctime(t)
stringprint = "%s %s\n" % (logtime, texto)
f = open("/var/log/patriot", "a")
f.write(stringprint)
f.flush()
f.close()
def PrintaMSG(texto):
command = 'python3 alertiqt.py "'+texto+'"'
processalert = subprocess.Popen([command], stdout=subprocess.PIPE,shell=True, stderr=DEVNULL)
def TestIntegrity(File):
if os.path.exists(redhat) :
command = 'rpm -Vf "'+File+'"'
processrpm = subprocess.Popen([command], stdout=subprocess.PIPE,shell=True)
outputrpm = processrpm.communicate()[0]
if outputrpm :
return(1)
else:
return(0)
else :
commandDPKG = 'dpkg -S "'+File+'"'
processdpkg = subprocess.Popen([commandDPKG], stdout=subprocess.PIPE,shell=True, stderr=DEVNULL)
outputdpkg = processdpkg.communicate()[0]
if processdpkg.returncode == 1:
#dpkg is buggy to find package files
fixdpkgbug= re.sub('/usr', '', File)
commandDPKG2 = 'dpkg -S "'+fixdpkgbug+'"'
processdpkg2 = subprocess.Popen([commandDPKG2], stdout=subprocess.PIPE,shell=True, stderr=DEVNULL)
outputdpkg2 = processdpkg2.communicate()[0]
outputdpkg = outputdpkg2
if processdpkg2.returncode == 1:
return(1)
packagename = outputdpkg.split(":")
commandDEBSUM = 'dpkg --verify "'+packagename[0]+'"'
processdebsum = subprocess.Popen([commandDEBSUM], stdout=subprocess.PIPE,shell=True)
outputdebsum = processdebsum.communicate()[0]
print (outputdebsum)
if outputdebsum :
return(1)
else:
return(0)
def ScanUnsigned():
pidsinicial = psutil.pids()
while True:
pidsshots = psutil.pids()
s = set(pidsinicial)
newpids = [x for x in pidsshots if x not in s]
if newpids:
#print(newpids)
for i in newpids:
#print(i)
try:
p = psutil.Process(pid=i)
with p.oneshot():
integrity= TestIntegrity(p.exe())
#print (integrity)
pidproceso = p.pid
exeproceso = p.exe()
evadeau = bool(re.match(exeproceso, "/usr/sbin/ausearch"))
if integrity == 1 and evadeau == 0:
stringprint = "New process that not belongs to any package or package was modified: %i %s" % (pidproceso, exeproceso)
x = threading.Thread(target=PrintaMSG, args=(stringprint,))
x.setDaemon(True)
x.start()
PrintaLog(stringprint)
except Exception as e:
print (e)
pidsinicial = pidsshots
time.sleep(2)
def ScanConnections():
initialcon =psutil.net_connections()
netprocess =[]
for i in initialcon:
#print (i.pid)
p = psutil.Process(pid=i.pid)
with p.oneshot():
#print (p.exe())
netprocess.append(p.exe())
#print (netprocess)
while True:
runcon =psutil.net_connections()
netprocessrun =[]
for e in runcon:
#print (e.pid)
p = psutil.Process(pid=e.pid)
with p.oneshot():
#print (p.exe())
netprocessrun.append(p.exe())
#print (netprocessrun)
s = set(netprocess)
newpconprogs = [x for x in netprocessrun if x not in s]
if newpconprogs:
#print(newpconprogs)
for h in newpconprogs:
stringprint = "New Process initiating TCP/IP connection: %s" % h
x = threading.Thread(target=PrintaMSG, args=(stringprint,))
x.setDaemon(True)
x.start()
PrintaLog(stringprint)
netprocess.append(h)
time.sleep(2)
def AuSearch():
auparams = {"modules": "New module loaded in Kernel","code_injection": "DLL Inject","register_injection": "DLL Inject"}
while True:
tomo = datetime.datetime.now() - datetime.timedelta(minutes=2)
timeraw = str(tomo.time().replace(second=0, microsecond=0))
for key in auparams.keys():
#print(key)
command = 'ausearch -k "'+key+'" --start "'+timeraw+'"'
processausearch = subprocess.Popen([command], stdout=subprocess.PIPE,shell=True, stderr=DEVNULL)
outputausearch = processausearch.communicate()[0]
if outputausearch:
stringprint = "Audit Alert: %s" % auparams[key]
x = threading.Thread(target=PrintaMSG, args=(stringprint,))
x.setDaemon(True)
x.start()
PrintaLog(stringprint)
time.sleep(115)
def KeyBoardSearch():
command = "xinput --list"
keyfirstcommand = subprocess.Popen([command], stdout=subprocess.PIPE,shell=True)
outputkeysearch= keyfirstcommand.communicate()[0]
while True:
keyruncommand = subprocess.Popen([command], stdout=subprocess.PIPE,shell=True)
outputkeyrunsearch= keyruncommand.communicate()[0]
if outputkeyrunsearch != outputkeysearch:
stringprint = "New keyboard detected"
x = threading.Thread(target=PrintaMSG, args=(stringprint,))
x.setDaemon(True)
x.start()
PrintaLog(stringprint)
outputkeysearch = outputkeyrunsearch
time.sleep(60)
s = threading.Thread(target=KeyBoardSearch)
s.setDaemon(True)
s.start()
x = threading.Thread(target=ScanUnsigned)
x.setDaemon(True)
x.start()
y = threading.Thread(target=ScanConnections)
y.setDaemon(True)
y.start()
z = threading.Thread(target=AuSearch)
z.setDaemon(True)
z.start()
while True:
time.sleep(100)
|
flexible
|
{
"blob_id": "fde62dd3f5ee3cc0a1568b037ada14835c327046",
"index": 6298,
"step-1": "<mask token>\n\n\ndef PrintaLog(texto):\n t = time.time()\n logtime = time.ctime(t)\n stringprint = '%s %s\\n' % (logtime, texto)\n f = open('/var/log/patriot', 'a')\n f.write(stringprint)\n f.flush()\n f.close()\n\n\ndef PrintaMSG(texto):\n command = 'python3 alertiqt.py \"' + texto + '\"'\n processalert = subprocess.Popen([command], stdout=subprocess.PIPE,\n shell=True, stderr=DEVNULL)\n\n\n<mask token>\n\n\ndef ScanConnections():\n initialcon = psutil.net_connections()\n netprocess = []\n for i in initialcon:\n p = psutil.Process(pid=i.pid)\n with p.oneshot():\n netprocess.append(p.exe())\n while True:\n runcon = psutil.net_connections()\n netprocessrun = []\n for e in runcon:\n p = psutil.Process(pid=e.pid)\n with p.oneshot():\n netprocessrun.append(p.exe())\n s = set(netprocess)\n newpconprogs = [x for x in netprocessrun if x not in s]\n if newpconprogs:\n for h in newpconprogs:\n stringprint = (\n 'New Process initiating TCP/IP connection: %s' % h)\n x = threading.Thread(target=PrintaMSG, args=(stringprint,))\n x.setDaemon(True)\n x.start()\n PrintaLog(stringprint)\n netprocess.append(h)\n time.sleep(2)\n\n\ndef AuSearch():\n auparams = {'modules': 'New module loaded in Kernel', 'code_injection':\n 'DLL Inject', 'register_injection': 'DLL Inject'}\n while True:\n tomo = datetime.datetime.now() - datetime.timedelta(minutes=2)\n timeraw = str(tomo.time().replace(second=0, microsecond=0))\n for key in auparams.keys():\n command = 'ausearch -k \"' + key + '\" --start \"' + timeraw + '\"'\n processausearch = subprocess.Popen([command], stdout=subprocess\n .PIPE, shell=True, stderr=DEVNULL)\n outputausearch = processausearch.communicate()[0]\n if outputausearch:\n stringprint = 'Audit Alert: %s' % auparams[key]\n x = threading.Thread(target=PrintaMSG, args=(stringprint,))\n x.setDaemon(True)\n x.start()\n PrintaLog(stringprint)\n time.sleep(115)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef PrintaLog(texto):\n t = time.time()\n logtime = time.ctime(t)\n stringprint = '%s %s\\n' % (logtime, texto)\n f = open('/var/log/patriot', 'a')\n f.write(stringprint)\n f.flush()\n f.close()\n\n\ndef PrintaMSG(texto):\n command = 'python3 alertiqt.py \"' + texto + '\"'\n processalert = subprocess.Popen([command], stdout=subprocess.PIPE,\n shell=True, stderr=DEVNULL)\n\n\n<mask token>\n\n\ndef ScanUnsigned():\n pidsinicial = psutil.pids()\n while True:\n pidsshots = psutil.pids()\n s = set(pidsinicial)\n newpids = [x for x in pidsshots if x not in s]\n if newpids:\n for i in newpids:\n try:\n p = psutil.Process(pid=i)\n with p.oneshot():\n integrity = TestIntegrity(p.exe())\n pidproceso = p.pid\n exeproceso = p.exe()\n evadeau = bool(re.match(exeproceso,\n '/usr/sbin/ausearch'))\n if integrity == 1 and evadeau == 0:\n stringprint = (\n 'New process that not belongs to any package or package was modified: %i %s'\n % (pidproceso, exeproceso))\n x = threading.Thread(target=PrintaMSG, args=(\n stringprint,))\n x.setDaemon(True)\n x.start()\n PrintaLog(stringprint)\n except Exception as e:\n print(e)\n pidsinicial = pidsshots\n time.sleep(2)\n\n\ndef ScanConnections():\n initialcon = psutil.net_connections()\n netprocess = []\n for i in initialcon:\n p = psutil.Process(pid=i.pid)\n with p.oneshot():\n netprocess.append(p.exe())\n while True:\n runcon = psutil.net_connections()\n netprocessrun = []\n for e in runcon:\n p = psutil.Process(pid=e.pid)\n with p.oneshot():\n netprocessrun.append(p.exe())\n s = set(netprocess)\n newpconprogs = [x for x in netprocessrun if x not in s]\n if newpconprogs:\n for h in newpconprogs:\n stringprint = (\n 'New Process initiating TCP/IP connection: %s' % h)\n x = threading.Thread(target=PrintaMSG, args=(stringprint,))\n x.setDaemon(True)\n x.start()\n PrintaLog(stringprint)\n netprocess.append(h)\n time.sleep(2)\n\n\ndef AuSearch():\n auparams = {'modules': 'New module loaded in Kernel', 'code_injection':\n 'DLL Inject', 'register_injection': 'DLL Inject'}\n while True:\n tomo = datetime.datetime.now() - datetime.timedelta(minutes=2)\n timeraw = str(tomo.time().replace(second=0, microsecond=0))\n for key in auparams.keys():\n command = 'ausearch -k \"' + key + '\" --start \"' + timeraw + '\"'\n processausearch = subprocess.Popen([command], stdout=subprocess\n .PIPE, shell=True, stderr=DEVNULL)\n outputausearch = processausearch.communicate()[0]\n if outputausearch:\n stringprint = 'Audit Alert: %s' % auparams[key]\n x = threading.Thread(target=PrintaMSG, args=(stringprint,))\n x.setDaemon(True)\n x.start()\n PrintaLog(stringprint)\n time.sleep(115)\n\n\ndef KeyBoardSearch():\n command = 'xinput --list'\n keyfirstcommand = subprocess.Popen([command], stdout=subprocess.PIPE,\n shell=True)\n outputkeysearch = keyfirstcommand.communicate()[0]\n while True:\n keyruncommand = subprocess.Popen([command], stdout=subprocess.PIPE,\n shell=True)\n outputkeyrunsearch = keyruncommand.communicate()[0]\n if outputkeyrunsearch != outputkeysearch:\n stringprint = 'New keyboard detected'\n x = threading.Thread(target=PrintaMSG, args=(stringprint,))\n x.setDaemon(True)\n x.start()\n PrintaLog(stringprint)\n outputkeysearch = outputkeyrunsearch\n time.sleep(60)\n\n\n<mask token>\n",
"step-3": "<mask token>\ndebian = '/etc/debian_version'\nredhat = '/etc/redhat-release'\n\n\ndef PrintaLog(texto):\n t = time.time()\n logtime = time.ctime(t)\n stringprint = '%s %s\\n' % (logtime, texto)\n f = open('/var/log/patriot', 'a')\n f.write(stringprint)\n f.flush()\n f.close()\n\n\ndef PrintaMSG(texto):\n command = 'python3 alertiqt.py \"' + texto + '\"'\n processalert = subprocess.Popen([command], stdout=subprocess.PIPE,\n shell=True, stderr=DEVNULL)\n\n\ndef TestIntegrity(File):\n if os.path.exists(redhat):\n command = 'rpm -Vf \"' + File + '\"'\n processrpm = subprocess.Popen([command], stdout=subprocess.PIPE,\n shell=True)\n outputrpm = processrpm.communicate()[0]\n if outputrpm:\n return 1\n else:\n return 0\n else:\n commandDPKG = 'dpkg -S \"' + File + '\"'\n processdpkg = subprocess.Popen([commandDPKG], stdout=subprocess.\n PIPE, shell=True, stderr=DEVNULL)\n outputdpkg = processdpkg.communicate()[0]\n if processdpkg.returncode == 1:\n fixdpkgbug = re.sub('/usr', '', File)\n commandDPKG2 = 'dpkg -S \"' + fixdpkgbug + '\"'\n processdpkg2 = subprocess.Popen([commandDPKG2], stdout=\n subprocess.PIPE, shell=True, stderr=DEVNULL)\n outputdpkg2 = processdpkg2.communicate()[0]\n outputdpkg = outputdpkg2\n if processdpkg2.returncode == 1:\n return 1\n packagename = outputdpkg.split(':')\n commandDEBSUM = 'dpkg --verify \"' + packagename[0] + '\"'\n processdebsum = subprocess.Popen([commandDEBSUM], stdout=subprocess\n .PIPE, shell=True)\n outputdebsum = processdebsum.communicate()[0]\n print(outputdebsum)\n if outputdebsum:\n return 1\n else:\n return 0\n\n\ndef ScanUnsigned():\n pidsinicial = psutil.pids()\n while True:\n pidsshots = psutil.pids()\n s = set(pidsinicial)\n newpids = [x for x in pidsshots if x not in s]\n if newpids:\n for i in newpids:\n try:\n p = psutil.Process(pid=i)\n with p.oneshot():\n integrity = TestIntegrity(p.exe())\n pidproceso = p.pid\n exeproceso = p.exe()\n evadeau = bool(re.match(exeproceso,\n '/usr/sbin/ausearch'))\n if integrity == 1 and evadeau == 0:\n stringprint = (\n 'New process that not belongs to any package or package was modified: %i %s'\n % (pidproceso, exeproceso))\n x = threading.Thread(target=PrintaMSG, args=(\n stringprint,))\n x.setDaemon(True)\n x.start()\n PrintaLog(stringprint)\n except Exception as e:\n print(e)\n pidsinicial = pidsshots\n time.sleep(2)\n\n\ndef ScanConnections():\n initialcon = psutil.net_connections()\n netprocess = []\n for i in initialcon:\n p = psutil.Process(pid=i.pid)\n with p.oneshot():\n netprocess.append(p.exe())\n while True:\n runcon = psutil.net_connections()\n netprocessrun = []\n for e in runcon:\n p = psutil.Process(pid=e.pid)\n with p.oneshot():\n netprocessrun.append(p.exe())\n s = set(netprocess)\n newpconprogs = [x for x in netprocessrun if x not in s]\n if newpconprogs:\n for h in newpconprogs:\n stringprint = (\n 'New Process initiating TCP/IP connection: %s' % h)\n x = threading.Thread(target=PrintaMSG, args=(stringprint,))\n x.setDaemon(True)\n x.start()\n PrintaLog(stringprint)\n netprocess.append(h)\n time.sleep(2)\n\n\ndef AuSearch():\n auparams = {'modules': 'New module loaded in Kernel', 'code_injection':\n 'DLL Inject', 'register_injection': 'DLL Inject'}\n while True:\n tomo = datetime.datetime.now() - datetime.timedelta(minutes=2)\n timeraw = str(tomo.time().replace(second=0, microsecond=0))\n for key in auparams.keys():\n command = 'ausearch -k \"' + key + '\" --start \"' + timeraw + '\"'\n processausearch = subprocess.Popen([command], stdout=subprocess\n .PIPE, shell=True, stderr=DEVNULL)\n outputausearch = processausearch.communicate()[0]\n if outputausearch:\n stringprint = 'Audit Alert: %s' % auparams[key]\n x = threading.Thread(target=PrintaMSG, args=(stringprint,))\n x.setDaemon(True)\n x.start()\n PrintaLog(stringprint)\n time.sleep(115)\n\n\ndef KeyBoardSearch():\n command = 'xinput --list'\n keyfirstcommand = subprocess.Popen([command], stdout=subprocess.PIPE,\n shell=True)\n outputkeysearch = keyfirstcommand.communicate()[0]\n while True:\n keyruncommand = subprocess.Popen([command], stdout=subprocess.PIPE,\n shell=True)\n outputkeyrunsearch = keyruncommand.communicate()[0]\n if outputkeyrunsearch != outputkeysearch:\n stringprint = 'New keyboard detected'\n x = threading.Thread(target=PrintaMSG, args=(stringprint,))\n x.setDaemon(True)\n x.start()\n PrintaLog(stringprint)\n outputkeysearch = outputkeyrunsearch\n time.sleep(60)\n\n\ns = threading.Thread(target=KeyBoardSearch)\ns.setDaemon(True)\ns.start()\nx = threading.Thread(target=ScanUnsigned)\nx.setDaemon(True)\nx.start()\ny = threading.Thread(target=ScanConnections)\ny.setDaemon(True)\ny.start()\nz = threading.Thread(target=AuSearch)\nz.setDaemon(True)\nz.start()\nwhile True:\n time.sleep(100)\n",
"step-4": "import tkinter as tk\nimport tkinter.messagebox as tkmb\nimport psutil\nimport os\nimport re\nimport subprocess\nfrom subprocess import Popen, PIPE, STDOUT, DEVNULL\nimport filecmp\nimport re\nimport time\nimport threading\nimport datetime\nimport re\ndebian = '/etc/debian_version'\nredhat = '/etc/redhat-release'\n\n\ndef PrintaLog(texto):\n t = time.time()\n logtime = time.ctime(t)\n stringprint = '%s %s\\n' % (logtime, texto)\n f = open('/var/log/patriot', 'a')\n f.write(stringprint)\n f.flush()\n f.close()\n\n\ndef PrintaMSG(texto):\n command = 'python3 alertiqt.py \"' + texto + '\"'\n processalert = subprocess.Popen([command], stdout=subprocess.PIPE,\n shell=True, stderr=DEVNULL)\n\n\ndef TestIntegrity(File):\n if os.path.exists(redhat):\n command = 'rpm -Vf \"' + File + '\"'\n processrpm = subprocess.Popen([command], stdout=subprocess.PIPE,\n shell=True)\n outputrpm = processrpm.communicate()[0]\n if outputrpm:\n return 1\n else:\n return 0\n else:\n commandDPKG = 'dpkg -S \"' + File + '\"'\n processdpkg = subprocess.Popen([commandDPKG], stdout=subprocess.\n PIPE, shell=True, stderr=DEVNULL)\n outputdpkg = processdpkg.communicate()[0]\n if processdpkg.returncode == 1:\n fixdpkgbug = re.sub('/usr', '', File)\n commandDPKG2 = 'dpkg -S \"' + fixdpkgbug + '\"'\n processdpkg2 = subprocess.Popen([commandDPKG2], stdout=\n subprocess.PIPE, shell=True, stderr=DEVNULL)\n outputdpkg2 = processdpkg2.communicate()[0]\n outputdpkg = outputdpkg2\n if processdpkg2.returncode == 1:\n return 1\n packagename = outputdpkg.split(':')\n commandDEBSUM = 'dpkg --verify \"' + packagename[0] + '\"'\n processdebsum = subprocess.Popen([commandDEBSUM], stdout=subprocess\n .PIPE, shell=True)\n outputdebsum = processdebsum.communicate()[0]\n print(outputdebsum)\n if outputdebsum:\n return 1\n else:\n return 0\n\n\ndef ScanUnsigned():\n pidsinicial = psutil.pids()\n while True:\n pidsshots = psutil.pids()\n s = set(pidsinicial)\n newpids = [x for x in pidsshots if x not in s]\n if newpids:\n for i in newpids:\n try:\n p = psutil.Process(pid=i)\n with p.oneshot():\n integrity = TestIntegrity(p.exe())\n pidproceso = p.pid\n exeproceso = p.exe()\n evadeau = bool(re.match(exeproceso,\n '/usr/sbin/ausearch'))\n if integrity == 1 and evadeau == 0:\n stringprint = (\n 'New process that not belongs to any package or package was modified: %i %s'\n % (pidproceso, exeproceso))\n x = threading.Thread(target=PrintaMSG, args=(\n stringprint,))\n x.setDaemon(True)\n x.start()\n PrintaLog(stringprint)\n except Exception as e:\n print(e)\n pidsinicial = pidsshots\n time.sleep(2)\n\n\ndef ScanConnections():\n initialcon = psutil.net_connections()\n netprocess = []\n for i in initialcon:\n p = psutil.Process(pid=i.pid)\n with p.oneshot():\n netprocess.append(p.exe())\n while True:\n runcon = psutil.net_connections()\n netprocessrun = []\n for e in runcon:\n p = psutil.Process(pid=e.pid)\n with p.oneshot():\n netprocessrun.append(p.exe())\n s = set(netprocess)\n newpconprogs = [x for x in netprocessrun if x not in s]\n if newpconprogs:\n for h in newpconprogs:\n stringprint = (\n 'New Process initiating TCP/IP connection: %s' % h)\n x = threading.Thread(target=PrintaMSG, args=(stringprint,))\n x.setDaemon(True)\n x.start()\n PrintaLog(stringprint)\n netprocess.append(h)\n time.sleep(2)\n\n\ndef AuSearch():\n auparams = {'modules': 'New module loaded in Kernel', 'code_injection':\n 'DLL Inject', 'register_injection': 'DLL Inject'}\n while True:\n tomo = datetime.datetime.now() - datetime.timedelta(minutes=2)\n timeraw = str(tomo.time().replace(second=0, microsecond=0))\n for key in auparams.keys():\n command = 'ausearch -k \"' + key + '\" --start \"' + timeraw + '\"'\n processausearch = subprocess.Popen([command], stdout=subprocess\n .PIPE, shell=True, stderr=DEVNULL)\n outputausearch = processausearch.communicate()[0]\n if outputausearch:\n stringprint = 'Audit Alert: %s' % auparams[key]\n x = threading.Thread(target=PrintaMSG, args=(stringprint,))\n x.setDaemon(True)\n x.start()\n PrintaLog(stringprint)\n time.sleep(115)\n\n\ndef KeyBoardSearch():\n command = 'xinput --list'\n keyfirstcommand = subprocess.Popen([command], stdout=subprocess.PIPE,\n shell=True)\n outputkeysearch = keyfirstcommand.communicate()[0]\n while True:\n keyruncommand = subprocess.Popen([command], stdout=subprocess.PIPE,\n shell=True)\n outputkeyrunsearch = keyruncommand.communicate()[0]\n if outputkeyrunsearch != outputkeysearch:\n stringprint = 'New keyboard detected'\n x = threading.Thread(target=PrintaMSG, args=(stringprint,))\n x.setDaemon(True)\n x.start()\n PrintaLog(stringprint)\n outputkeysearch = outputkeyrunsearch\n time.sleep(60)\n\n\ns = threading.Thread(target=KeyBoardSearch)\ns.setDaemon(True)\ns.start()\nx = threading.Thread(target=ScanUnsigned)\nx.setDaemon(True)\nx.start()\ny = threading.Thread(target=ScanConnections)\ny.setDaemon(True)\ny.start()\nz = threading.Thread(target=AuSearch)\nz.setDaemon(True)\nz.start()\nwhile True:\n time.sleep(100)\n",
"step-5": "import tkinter as tk\nimport tkinter.messagebox as tkmb\nimport psutil\nimport os\nimport re\nimport subprocess\nfrom subprocess import Popen, PIPE, STDOUT, DEVNULL\nimport filecmp\nimport re\nimport time\nimport threading\nimport datetime\nimport re\n\ndebian = '/etc/debian_version'\nredhat = '/etc/redhat-release'\n\ndef PrintaLog(texto):\n\t\n\tt = time.time()\n\tlogtime= time.ctime(t)\n\t\n\tstringprint = \"%s %s\\n\" % (logtime, texto)\n\t\n\tf = open(\"/var/log/patriot\", \"a\")\n\tf.write(stringprint)\n\tf.flush()\n\tf.close()\n\ndef PrintaMSG(texto):\n\n\tcommand = 'python3 alertiqt.py \"'+texto+'\"' \n\t\t\t\t\t\n\tprocessalert = subprocess.Popen([command], stdout=subprocess.PIPE,shell=True, stderr=DEVNULL)\n\ndef TestIntegrity(File):\n\t\n\tif os.path.exists(redhat) : \n\t\n\t\tcommand = 'rpm -Vf \"'+File+'\"' \n\t\t\t\t\t\n\t\tprocessrpm = subprocess.Popen([command], stdout=subprocess.PIPE,shell=True)\n\t\toutputrpm = processrpm.communicate()[0]\n\t\t\t\t\t\n\t\tif outputrpm :\n\t\t\t\t\t\t\n\t\t\treturn(1)\n\t\t\t\t\t\t\t\t\n\t\t\n\t\telse:\n\t\t\t\n\t\t\treturn(0)\n\n\telse :\t\n\t\t\n\t\tcommandDPKG = 'dpkg -S \"'+File+'\"'\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\tprocessdpkg = subprocess.Popen([commandDPKG], stdout=subprocess.PIPE,shell=True, stderr=DEVNULL)\n\t\toutputdpkg = processdpkg.communicate()[0]\n\t\t\t\t\t\t\n\t\tif processdpkg.returncode == 1:\n\t\t\t\t\t\t\t\n\t\t\t#dpkg is buggy to find package files \n\t\t\t\t\t\t\t\n\t\t\tfixdpkgbug= re.sub('/usr', '', File)\n\t\t\t\t\t\t\t\n\t\t\tcommandDPKG2 = 'dpkg -S \"'+fixdpkgbug+'\"'\n\t\t\t\t\t\t\n\t\t\tprocessdpkg2 = subprocess.Popen([commandDPKG2], stdout=subprocess.PIPE,shell=True, stderr=DEVNULL)\n\t\t\toutputdpkg2 = processdpkg2.communicate()[0]\n\t\t\t\t\t\t\t\n\t\t\toutputdpkg = outputdpkg2\n\t\t\t\t\t\t\t\n\t\t\tif processdpkg2.returncode == 1:\n\t\t\t\t\t\t\t\n\t\t\t\treturn(1)\n\t\t\t\t\t\t\t\t\n\t\t\t\t\n\t\tpackagename = outputdpkg.split(\":\")\n\t\t\t\t\t\t\n\t\tcommandDEBSUM = 'dpkg --verify \"'+packagename[0]+'\"'\n\t\t\t\t\t\t\n\t\t\t\t\t\t\t\n\t\tprocessdebsum = subprocess.Popen([commandDEBSUM], stdout=subprocess.PIPE,shell=True)\n\t\toutputdebsum = processdebsum.communicate()[0]\n\t\t\n\t\tprint (outputdebsum)\n\t\t\t\t\t\t\n\t\tif outputdebsum :\n\t\t\t\n\t\t\treturn(1)\n\t\t\t\t\t\t\n\t\telse:\n\t\t\treturn(0)\n\n\ndef ScanUnsigned():\n\t\n\tpidsinicial = psutil.pids()\n\n\twhile True:\n\t\n\t\tpidsshots = psutil.pids()\n\t\n\t\ts = set(pidsinicial)\n\t\tnewpids = [x for x in pidsshots if x not in s]\n\t\n\t\tif newpids:\n\t\n\t\t\t#print(newpids)\n\t\t\n\t\t\tfor i in newpids:\n\t\t\t\n\t\t\t\t#print(i)\n\t\t\t\ttry:\n\t\t\t\t\tp = psutil.Process(pid=i)\n\t\t\t\t\twith p.oneshot():\n\t\t\t\n\t\t\t\t\t\tintegrity= TestIntegrity(p.exe())\n\t\t\t\n\t\t\t\t\t\t#print (integrity)\n\t\t\t\t\t\t\n\t\t\t\t\t\tpidproceso = p.pid\n\t\t\t\t\t\texeproceso = p.exe()\n\t\t\t\t\t\t\n\t\t\t\t\t\tevadeau = bool(re.match(exeproceso, \"/usr/sbin/ausearch\"))\n\t\t\t\t\t\t\n\t\t\t\t\t\tif integrity == 1 and evadeau == 0:\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tstringprint = \"New process that not belongs to any package or package was modified: %i %s\" % (pidproceso, exeproceso)\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tx = threading.Thread(target=PrintaMSG, args=(stringprint,))\n\t\t\t\t\t\t\tx.setDaemon(True)\n\t\t\t\t\t\t\tx.start()\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\tPrintaLog(stringprint)\n\t\t\t\t\t\t\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tprint (e)\n\t\n\t\tpidsinicial = pidsshots\n\t\n\t\ttime.sleep(2)\n\t\t\n\ndef ScanConnections():\n\t\n\tinitialcon =psutil.net_connections()\n\n\tnetprocess =[]\n\n\tfor i in initialcon:\n\t\n\t\t#print (i.pid)\n\t\n\t\tp = psutil.Process(pid=i.pid)\n\t\n\t\twith p.oneshot():\n\t\t\n\t\t\t#print (p.exe())\n\t\t\n\t\t\tnetprocess.append(p.exe())\n\t\t\n\t#print (netprocess)\n\t\n\twhile True:\n\t\t\n\t\truncon =psutil.net_connections()\n\n\t\tnetprocessrun =[]\n\n\t\tfor e in runcon:\n\t\n\t\t\t#print (e.pid)\n\t\n\t\t\tp = psutil.Process(pid=e.pid)\n\t\n\t\t\twith p.oneshot():\n\t\t\n\t\t\t\t#print (p.exe())\n\t\t\n\t\t\t\tnetprocessrun.append(p.exe())\n\t\t\n\t\t#print (netprocessrun)\n\t\t\n\t\ts = set(netprocess)\n\t\tnewpconprogs = [x for x in netprocessrun if x not in s]\n\t\t\n\t\tif newpconprogs:\n\t\n\t\t\t#print(newpconprogs)\n\t\t\n\t\t\tfor h in newpconprogs:\n\t\t\t\t\n\t\t\t\tstringprint = \"New Process initiating TCP/IP connection: %s\" % h\n\t\t\t\t\t\t\n\t\t\t\tx = threading.Thread(target=PrintaMSG, args=(stringprint,))\n\t\t\t\tx.setDaemon(True)\n\t\t\t\tx.start()\n\t\t\t\t\n\t\t\t\tPrintaLog(stringprint)\n\t\t\t\t\n\t\t\t\tnetprocess.append(h)\n\t\t\n\t\t\t\t\n\t\ttime.sleep(2)\n\ndef AuSearch():\n\t\n\tauparams = {\"modules\": \"New module loaded in Kernel\",\"code_injection\": \"DLL Inject\",\"register_injection\": \"DLL Inject\"}\n\t\n\twhile True:\n\t\n\t\ttomo = datetime.datetime.now() - datetime.timedelta(minutes=2)\n\n\t\ttimeraw = str(tomo.time().replace(second=0, microsecond=0))\n\n\t\tfor key in auparams.keys():\n\t\t\t#print(key)\n\t\n\t\t\tcommand = 'ausearch -k \"'+key+'\" --start \"'+timeraw+'\"' \n\t\t\t\t\t\n\t\t\tprocessausearch = subprocess.Popen([command], stdout=subprocess.PIPE,shell=True, stderr=DEVNULL)\n\t\t\toutputausearch = processausearch.communicate()[0]\n\t\n\t\t\tif outputausearch:\n\t\t\t\n\t\t\t\tstringprint = \"Audit Alert: %s\" % auparams[key]\n\t\t\t\t\t\t\n\t\t\t\tx = threading.Thread(target=PrintaMSG, args=(stringprint,))\n\t\t\t\tx.setDaemon(True)\n\t\t\t\tx.start()\n\t\t\t\n\t\t\t\tPrintaLog(stringprint)\n\t\n\t\ttime.sleep(115)\n\ndef KeyBoardSearch():\n\t\n\tcommand = \"xinput --list\" \n\t\n\tkeyfirstcommand = subprocess.Popen([command], stdout=subprocess.PIPE,shell=True)\n\toutputkeysearch= keyfirstcommand.communicate()[0]\n\t\n\twhile True:\n\t\t\n\t\tkeyruncommand = subprocess.Popen([command], stdout=subprocess.PIPE,shell=True)\n\t\toutputkeyrunsearch= keyruncommand.communicate()[0]\n\t\t\n\t\tif outputkeyrunsearch != outputkeysearch:\n\t\t\t\n\t\t\tstringprint = \"New keyboard detected\"\n\t\t\t\n\t\t\tx = threading.Thread(target=PrintaMSG, args=(stringprint,))\n\t\t\tx.setDaemon(True)\n\t\t\tx.start()\n\t\t\t\n\t\t\tPrintaLog(stringprint)\n\t\t\t\n\t\t\toutputkeysearch = outputkeyrunsearch\n\t\t\t\n\t\ttime.sleep(60)\n\t\t\t\n\t\ns = threading.Thread(target=KeyBoardSearch)\ns.setDaemon(True)\ns.start()\t\n\nx = threading.Thread(target=ScanUnsigned)\nx.setDaemon(True)\nx.start()\n\ny = threading.Thread(target=ScanConnections)\ny.setDaemon(True)\ny.start()\n\nz = threading.Thread(target=AuSearch)\nz.setDaemon(True)\nz.start()\n\nwhile True:\n\t\n\ttime.sleep(100)\n",
"step-ids": [
4,
6,
9,
10,
11
]
}
|
[
4,
6,
9,
10,
11
] |
import json
import glob
import sys
searchAreaName = sys.argv[1]
# searchAreaName = "slovenia_177sqkm_shards/20161220-162010-c9e0/slovenia_177sqkm_predicted/predict_slovenia_177sqkm_shard"
print('./{0}_??.txt'.format(searchAreaName))
all_predicts = glob.glob('./{0}_??.txt'.format(searchAreaName))
def getBboxes(bboxes):
return [bb for bb in bboxes if sum(bb) > 0.0]
print(all_predicts)
bboxes = {}
for f in all_predicts:
with open(f) as json_data:
data = json.load(json_data)
outputs = data["outputs"]
for key in outputs:
val = outputs[key]["bbox-list"]
if sum(val[0]) > 0.0:
bboxes[key] = getBboxes(val)
#print outputs
with open('{0}_summary.json'.format(searchAreaName), 'w') as fp:
json.dump(bboxes, fp, indent=2)
print("wrote to {0}_summary.json".format(searchAreaName))
|
normal
|
{
"blob_id": "8f9d823785d42d02a0a3d901d66b46a5cd59cdd7",
"index": 7465,
"step-1": "<mask token>\n\n\ndef getBboxes(bboxes):\n return [bb for bb in bboxes if sum(bb) > 0.0]\n\n\n<mask token>\n",
"step-2": "<mask token>\nprint('./{0}_??.txt'.format(searchAreaName))\n<mask token>\n\n\ndef getBboxes(bboxes):\n return [bb for bb in bboxes if sum(bb) > 0.0]\n\n\nprint(all_predicts)\n<mask token>\nfor f in all_predicts:\n with open(f) as json_data:\n data = json.load(json_data)\n outputs = data['outputs']\n for key in outputs:\n val = outputs[key]['bbox-list']\n if sum(val[0]) > 0.0:\n bboxes[key] = getBboxes(val)\nwith open('{0}_summary.json'.format(searchAreaName), 'w') as fp:\n json.dump(bboxes, fp, indent=2)\n print('wrote to {0}_summary.json'.format(searchAreaName))\n",
"step-3": "<mask token>\nsearchAreaName = sys.argv[1]\nprint('./{0}_??.txt'.format(searchAreaName))\nall_predicts = glob.glob('./{0}_??.txt'.format(searchAreaName))\n\n\ndef getBboxes(bboxes):\n return [bb for bb in bboxes if sum(bb) > 0.0]\n\n\nprint(all_predicts)\nbboxes = {}\nfor f in all_predicts:\n with open(f) as json_data:\n data = json.load(json_data)\n outputs = data['outputs']\n for key in outputs:\n val = outputs[key]['bbox-list']\n if sum(val[0]) > 0.0:\n bboxes[key] = getBboxes(val)\nwith open('{0}_summary.json'.format(searchAreaName), 'w') as fp:\n json.dump(bboxes, fp, indent=2)\n print('wrote to {0}_summary.json'.format(searchAreaName))\n",
"step-4": "import json\nimport glob\nimport sys\nsearchAreaName = sys.argv[1]\nprint('./{0}_??.txt'.format(searchAreaName))\nall_predicts = glob.glob('./{0}_??.txt'.format(searchAreaName))\n\n\ndef getBboxes(bboxes):\n return [bb for bb in bboxes if sum(bb) > 0.0]\n\n\nprint(all_predicts)\nbboxes = {}\nfor f in all_predicts:\n with open(f) as json_data:\n data = json.load(json_data)\n outputs = data['outputs']\n for key in outputs:\n val = outputs[key]['bbox-list']\n if sum(val[0]) > 0.0:\n bboxes[key] = getBboxes(val)\nwith open('{0}_summary.json'.format(searchAreaName), 'w') as fp:\n json.dump(bboxes, fp, indent=2)\n print('wrote to {0}_summary.json'.format(searchAreaName))\n",
"step-5": "import json\nimport glob\nimport sys\nsearchAreaName = sys.argv[1]\n# searchAreaName = \"slovenia_177sqkm_shards/20161220-162010-c9e0/slovenia_177sqkm_predicted/predict_slovenia_177sqkm_shard\"\nprint('./{0}_??.txt'.format(searchAreaName))\nall_predicts = glob.glob('./{0}_??.txt'.format(searchAreaName))\n\ndef getBboxes(bboxes):\n return [bb for bb in bboxes if sum(bb) > 0.0]\nprint(all_predicts)\nbboxes = {}\nfor f in all_predicts:\n with open(f) as json_data:\n data = json.load(json_data)\n\n outputs = data[\"outputs\"]\n\n for key in outputs:\n\n val = outputs[key][\"bbox-list\"]\n if sum(val[0]) > 0.0:\n bboxes[key] = getBboxes(val)\n #print outputs\n\nwith open('{0}_summary.json'.format(searchAreaName), 'w') as fp:\n json.dump(bboxes, fp, indent=2)\n print(\"wrote to {0}_summary.json\".format(searchAreaName))\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Migration(migrations.Migration):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Migration(migrations.Migration):
dependencies = [('tutorials', '0003_auto_20210111_1705')]
operations = [migrations.AlterField(model_name='tutorial', name=
'upload', field=models.ImageField(upload_to='images'))]
<|reserved_special_token_1|>
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [('tutorials', '0003_auto_20210111_1705')]
operations = [migrations.AlterField(model_name='tutorial', name=
'upload', field=models.ImageField(upload_to='images'))]
<|reserved_special_token_1|>
# Generated by Django 3.1.4 on 2021-01-11 16:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tutorials', '0003_auto_20210111_1705'),
]
operations = [
migrations.AlterField(
model_name='tutorial',
name='upload',
field=models.ImageField(upload_to='images'),
),
]
|
flexible
|
{
"blob_id": "ac664cd7d62f89399e37f74e0234b3ad244fe460",
"index": 6158,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('tutorials', '0003_auto_20210111_1705')]\n operations = [migrations.AlterField(model_name='tutorial', name=\n 'upload', field=models.ImageField(upload_to='images'))]\n",
"step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('tutorials', '0003_auto_20210111_1705')]\n operations = [migrations.AlterField(model_name='tutorial', name=\n 'upload', field=models.ImageField(upload_to='images'))]\n",
"step-5": "# Generated by Django 3.1.4 on 2021-01-11 16:06\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('tutorials', '0003_auto_20210111_1705'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='tutorial',\n name='upload',\n field=models.ImageField(upload_to='images'),\n ),\n ]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
def tm():
for i in range(3):
print(time.ctime())
time.sleep(2)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def tm():
for i in range(3):
print(time.ctime())
time.sleep(2)
<|reserved_special_token_0|>
p.start()
print('Name:', p.name)
print('PID:', p.pid)
print('is alive:', p.is_alive())
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def tm():
for i in range(3):
print(time.ctime())
time.sleep(2)
p = Process(target=tm, name='Tarena')
p.daemon = True
p.start()
print('Name:', p.name)
print('PID:', p.pid)
print('is alive:', p.is_alive())
<|reserved_special_token_1|>
<|reserved_special_token_0|>
from multiprocessing import Process
import time
def tm():
for i in range(3):
print(time.ctime())
time.sleep(2)
p = Process(target=tm, name='Tarena')
p.daemon = True
p.start()
print('Name:', p.name)
print('PID:', p.pid)
print('is alive:', p.is_alive())
<|reserved_special_token_1|>
"""
进程对象属性
"""
from multiprocessing import Process
import time
def tm():
for i in range(3):
print(time.ctime())
time.sleep(2)
p = Process(target=tm,name='Tarena')
# 设置子进程随父进程退出
p.daemon = True
p.start()
print("Name:",p.name) # 进程名称
print("PID:",p.pid) # 进程PID
print("is alive:",p.is_alive()) # 是否在生命周期
|
flexible
|
{
"blob_id": "9d7bc2d93b855fbd22a4707a6237ac51069beb53",
"index": 9385,
"step-1": "<mask token>\n\n\ndef tm():\n for i in range(3):\n print(time.ctime())\n time.sleep(2)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef tm():\n for i in range(3):\n print(time.ctime())\n time.sleep(2)\n\n\n<mask token>\np.start()\nprint('Name:', p.name)\nprint('PID:', p.pid)\nprint('is alive:', p.is_alive())\n",
"step-3": "<mask token>\n\n\ndef tm():\n for i in range(3):\n print(time.ctime())\n time.sleep(2)\n\n\np = Process(target=tm, name='Tarena')\np.daemon = True\np.start()\nprint('Name:', p.name)\nprint('PID:', p.pid)\nprint('is alive:', p.is_alive())\n",
"step-4": "<mask token>\nfrom multiprocessing import Process\nimport time\n\n\ndef tm():\n for i in range(3):\n print(time.ctime())\n time.sleep(2)\n\n\np = Process(target=tm, name='Tarena')\np.daemon = True\np.start()\nprint('Name:', p.name)\nprint('PID:', p.pid)\nprint('is alive:', p.is_alive())\n",
"step-5": "\"\"\"\n进程对象属性\n\"\"\"\n\nfrom multiprocessing import Process\nimport time\n\n\ndef tm():\n for i in range(3):\n print(time.ctime())\n time.sleep(2)\n\n\np = Process(target=tm,name='Tarena')\n\n# 设置子进程随父进程退出\np.daemon = True\n\np.start()\nprint(\"Name:\",p.name) # 进程名称\nprint(\"PID:\",p.pid) # 进程PID\nprint(\"is alive:\",p.is_alive()) # 是否在生命周期",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def max_digit(number: int) ->int:
return max(int(i) for i in str(number))
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def max_digit(number: int) ->int:
return max(int(i) for i in str(number))
print(max_digit(634))
print(max_digit(102475))
<|reserved_special_token_1|>
"""
You have a number and you need to determine which digit in this number is the biggest.
Input: A positive int.
Output: An Int (0-9).
Example:
max_digit(0) == 0
max_digit(52) == 5
max_digit(634) == 6
max_digit(10000) == 1
"""
def max_digit(number: int) -> int:
return max(int(i) for i in str(number))
print(max_digit(634))
print(max_digit(102475))
|
flexible
|
{
"blob_id": "b25e9374458ead85535495e77a5c64117a8b1808",
"index": 5761,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef max_digit(number: int) ->int:\n return max(int(i) for i in str(number))\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef max_digit(number: int) ->int:\n return max(int(i) for i in str(number))\n\n\nprint(max_digit(634))\nprint(max_digit(102475))\n",
"step-4": "\"\"\"\nYou have a number and you need to determine which digit in this number is the biggest.\n\nInput: A positive int.\nOutput: An Int (0-9).\n\nExample:\n\nmax_digit(0) == 0\nmax_digit(52) == 5\nmax_digit(634) == 6\nmax_digit(10000) == 1\n\"\"\"\n\n\ndef max_digit(number: int) -> int:\n return max(int(i) for i in str(number))\n\nprint(max_digit(634))\nprint(max_digit(102475))\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
def notify_no_new_mapping_found():
email_str = """
<p>Python script does not find any new creative names from keepingtrac data.
Stage 2 of processing RenTrak data will begin when we load new data to RenTrak tables.
</p>
<p><b>No further action on your part is needed.</b></p>
"""
return email_str
<|reserved_special_token_0|>
def vertica_extract(query, columns, index=None):
with vertica_python.connect(**conn_info) as connection:
cur = connection.cursor()
cur.execute(query)
results = pd.DataFrame(cur.fetchall())
results.columns = columns
if index:
return results.set_index(index)
else:
return results
def set_flag_value(table_name, schema_name, flag_name, value):
return (
"""
UPDATE {1}.{0}
SET run = {3}
WHERE process_name = '{2}';
COMMIT;
"""
.format(table_name, schema_name, flag_name, value))
def set_lock(table_name, schema_name, flag_name, value):
with vertica_python.connect(**conn_info) as connection:
cur = connection.cursor()
cur.execute(set_flag_value(table_name, schema_name, flag_name, value))
connection.commit()
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def notify_no_new_mapping_found():
email_str = """
<p>Python script does not find any new creative names from keepingtrac data.
Stage 2 of processing RenTrak data will begin when we load new data to RenTrak tables.
</p>
<p><b>No further action on your part is needed.</b></p>
"""
return email_str
def send_notification_email(recipients, subject, body, attachment=None):
Mailer().send_email(recipients, subject, body, attachment)
print('Notification email sent.')
def vertica_extract(query, columns, index=None):
with vertica_python.connect(**conn_info) as connection:
cur = connection.cursor()
cur.execute(query)
results = pd.DataFrame(cur.fetchall())
results.columns = columns
if index:
return results.set_index(index)
else:
return results
def set_flag_value(table_name, schema_name, flag_name, value):
return (
"""
UPDATE {1}.{0}
SET run = {3}
WHERE process_name = '{2}';
COMMIT;
"""
.format(table_name, schema_name, flag_name, value))
def set_lock(table_name, schema_name, flag_name, value):
with vertica_python.connect(**conn_info) as connection:
cur = connection.cursor()
cur.execute(set_flag_value(table_name, schema_name, flag_name, value))
connection.commit()
def main():
schema_name = 'gaintheory_us_targetusa_14'
mapping_table = 'incampaign_kt_creative_mappings'
flag_table = 'incampaign_process_switches'
flag = 'rentrak_kt_creative_cleaned'
output_folder = ROOT_FOLDER + 'RenTrak'
output_file = 'kt_creative_cleaned.xlsx'
if not os.path.exists(output_folder):
print('Creating a new local folder for export file:', output_folder)
os.makedirs(output_folder)
extract_query = (
"""
SELECT Air_ISCI as kt_creative_id, Cmml_Title AS kt_creative, kt_creative_clean
FROM {1}.incampaign_keepingtrac_all a
LEFT JOIN {1}.{0} b
ON a.Air_ISCI = b.kt_creative_id
WHERE Air_ISCI IS NOT NULL
GROUP BY a.Air_ISCI, a.Cmml_Title, kt_creative_clean
ORDER BY kt_creative_id
"""
.format(mapping_table, schema_name))
df = vertica_extract(extract_query, ['kt_creative_id', 'kt_creative',
'kt_creative_clean'])
unmapped_creatives = df.isnull().sum()['kt_creative_clean']
if unmapped_creatives > 0:
print('Some unmapped kt_creatives found')
print('Acquiring process lock:', flag,
'so that the second part of RenTrak processing cannot proceed')
set_lock(flag_table, schema_name, flag, 0)
file_to_export = os.path.join(output_folder, output_file)
df[df['kt_creative_clean'].isnull()].to_excel(file_to_export, index
=False)
subject = (
'RenTrak automated processing step 1: new kt_creatives need to be mapped'
)
body = notify_for_manual_mapping(output_file, flag)
send_notification_email(ONSHORE_EMAIL_RECIPIENTS, subject, body,
file_to_export)
print('Notified the team to add manual mapping')
os.remove(file_to_export)
print('Deleted local file=>', file_to_export)
else:
print('Everything is mapped')
print('Releasing process lock:', flag,
'so that the second part of RenTrak processing can proceed')
set_lock(flag_table, schema_name, flag, 1)
subject = (
'RenTrak automated processing step 1: kt_creatives are all mapped. Step 2 will automatically commence.'
)
body = notify_no_new_mapping_found()
send_notification_email(ONSHORE_EMAIL_RECIPIENTS, subject, body)
print(
'Notified the team that no further action on their part is required'
)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def notify_for_manual_mapping(file, process_name):
email_str = (
"""
<p>Python script extracted new creative names from KeepingTrac data.</p>
<p>To run the rest of the RenTrak ETL process smoothly, please do the followings:
<ol>
<li>download the attached file, <b>{0}</b>, from this email</li>
<li>fill up empty (nan/NULL) kt_creative mappings under column C (kt_creative_clean) in that file</b></li>
<li>upload the modified file to the S3 location below
<span style="color: red;">(replace any file with the same name in the S3 folder, if any)</span>:<br>
<b>diap.prod.us-east-1.target/RenTrak/CreativeCleaned</b>
</li>
<li>run this feed in DataVault: <b>InCampaign KT Creative Mappings</b></li>
<li><span style="color: red;">AFTER the DataVault feed successfully loaded the mappings</span>,
run this SQL in Vertica backend: <br>
<b>
UPDATE gaintheory_us_targetusa_14.incampaign_process_switches
SET run = 1
WHERE process_name = '{1}';
</b>
</li>
</ol>
</p>
<p><strong style="color: red;">NOTE: If you forget a step or more above, the second part of RenTrak processing
may not produce correct results.</strong></p>
"""
.format(file, process_name))
return email_str
def notify_no_new_mapping_found():
email_str = """
<p>Python script does not find any new creative names from keepingtrac data.
Stage 2 of processing RenTrak data will begin when we load new data to RenTrak tables.
</p>
<p><b>No further action on your part is needed.</b></p>
"""
return email_str
def send_notification_email(recipients, subject, body, attachment=None):
Mailer().send_email(recipients, subject, body, attachment)
print('Notification email sent.')
def vertica_extract(query, columns, index=None):
with vertica_python.connect(**conn_info) as connection:
cur = connection.cursor()
cur.execute(query)
results = pd.DataFrame(cur.fetchall())
results.columns = columns
if index:
return results.set_index(index)
else:
return results
def set_flag_value(table_name, schema_name, flag_name, value):
return (
"""
UPDATE {1}.{0}
SET run = {3}
WHERE process_name = '{2}';
COMMIT;
"""
.format(table_name, schema_name, flag_name, value))
def set_lock(table_name, schema_name, flag_name, value):
with vertica_python.connect(**conn_info) as connection:
cur = connection.cursor()
cur.execute(set_flag_value(table_name, schema_name, flag_name, value))
connection.commit()
def main():
schema_name = 'gaintheory_us_targetusa_14'
mapping_table = 'incampaign_kt_creative_mappings'
flag_table = 'incampaign_process_switches'
flag = 'rentrak_kt_creative_cleaned'
output_folder = ROOT_FOLDER + 'RenTrak'
output_file = 'kt_creative_cleaned.xlsx'
if not os.path.exists(output_folder):
print('Creating a new local folder for export file:', output_folder)
os.makedirs(output_folder)
extract_query = (
"""
SELECT Air_ISCI as kt_creative_id, Cmml_Title AS kt_creative, kt_creative_clean
FROM {1}.incampaign_keepingtrac_all a
LEFT JOIN {1}.{0} b
ON a.Air_ISCI = b.kt_creative_id
WHERE Air_ISCI IS NOT NULL
GROUP BY a.Air_ISCI, a.Cmml_Title, kt_creative_clean
ORDER BY kt_creative_id
"""
.format(mapping_table, schema_name))
df = vertica_extract(extract_query, ['kt_creative_id', 'kt_creative',
'kt_creative_clean'])
unmapped_creatives = df.isnull().sum()['kt_creative_clean']
if unmapped_creatives > 0:
print('Some unmapped kt_creatives found')
print('Acquiring process lock:', flag,
'so that the second part of RenTrak processing cannot proceed')
set_lock(flag_table, schema_name, flag, 0)
file_to_export = os.path.join(output_folder, output_file)
df[df['kt_creative_clean'].isnull()].to_excel(file_to_export, index
=False)
subject = (
'RenTrak automated processing step 1: new kt_creatives need to be mapped'
)
body = notify_for_manual_mapping(output_file, flag)
send_notification_email(ONSHORE_EMAIL_RECIPIENTS, subject, body,
file_to_export)
print('Notified the team to add manual mapping')
os.remove(file_to_export)
print('Deleted local file=>', file_to_export)
else:
print('Everything is mapped')
print('Releasing process lock:', flag,
'so that the second part of RenTrak processing can proceed')
set_lock(flag_table, schema_name, flag, 1)
subject = (
'RenTrak automated processing step 1: kt_creatives are all mapped. Step 2 will automatically commence.'
)
body = notify_no_new_mapping_found()
send_notification_email(ONSHORE_EMAIL_RECIPIENTS, subject, body)
print(
'Notified the team that no further action on their part is required'
)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def notify_for_manual_mapping(file, process_name):
email_str = (
"""
<p>Python script extracted new creative names from KeepingTrac data.</p>
<p>To run the rest of the RenTrak ETL process smoothly, please do the followings:
<ol>
<li>download the attached file, <b>{0}</b>, from this email</li>
<li>fill up empty (nan/NULL) kt_creative mappings under column C (kt_creative_clean) in that file</b></li>
<li>upload the modified file to the S3 location below
<span style="color: red;">(replace any file with the same name in the S3 folder, if any)</span>:<br>
<b>diap.prod.us-east-1.target/RenTrak/CreativeCleaned</b>
</li>
<li>run this feed in DataVault: <b>InCampaign KT Creative Mappings</b></li>
<li><span style="color: red;">AFTER the DataVault feed successfully loaded the mappings</span>,
run this SQL in Vertica backend: <br>
<b>
UPDATE gaintheory_us_targetusa_14.incampaign_process_switches
SET run = 1
WHERE process_name = '{1}';
</b>
</li>
</ol>
</p>
<p><strong style="color: red;">NOTE: If you forget a step or more above, the second part of RenTrak processing
may not produce correct results.</strong></p>
"""
.format(file, process_name))
return email_str
def notify_no_new_mapping_found():
email_str = """
<p>Python script does not find any new creative names from keepingtrac data.
Stage 2 of processing RenTrak data will begin when we load new data to RenTrak tables.
</p>
<p><b>No further action on your part is needed.</b></p>
"""
return email_str
def send_notification_email(recipients, subject, body, attachment=None):
Mailer().send_email(recipients, subject, body, attachment)
print('Notification email sent.')
def vertica_extract(query, columns, index=None):
with vertica_python.connect(**conn_info) as connection:
cur = connection.cursor()
cur.execute(query)
results = pd.DataFrame(cur.fetchall())
results.columns = columns
if index:
return results.set_index(index)
else:
return results
def set_flag_value(table_name, schema_name, flag_name, value):
return (
"""
UPDATE {1}.{0}
SET run = {3}
WHERE process_name = '{2}';
COMMIT;
"""
.format(table_name, schema_name, flag_name, value))
def set_lock(table_name, schema_name, flag_name, value):
with vertica_python.connect(**conn_info) as connection:
cur = connection.cursor()
cur.execute(set_flag_value(table_name, schema_name, flag_name, value))
connection.commit()
def main():
schema_name = 'gaintheory_us_targetusa_14'
mapping_table = 'incampaign_kt_creative_mappings'
flag_table = 'incampaign_process_switches'
flag = 'rentrak_kt_creative_cleaned'
output_folder = ROOT_FOLDER + 'RenTrak'
output_file = 'kt_creative_cleaned.xlsx'
if not os.path.exists(output_folder):
print('Creating a new local folder for export file:', output_folder)
os.makedirs(output_folder)
extract_query = (
"""
SELECT Air_ISCI as kt_creative_id, Cmml_Title AS kt_creative, kt_creative_clean
FROM {1}.incampaign_keepingtrac_all a
LEFT JOIN {1}.{0} b
ON a.Air_ISCI = b.kt_creative_id
WHERE Air_ISCI IS NOT NULL
GROUP BY a.Air_ISCI, a.Cmml_Title, kt_creative_clean
ORDER BY kt_creative_id
"""
.format(mapping_table, schema_name))
df = vertica_extract(extract_query, ['kt_creative_id', 'kt_creative',
'kt_creative_clean'])
unmapped_creatives = df.isnull().sum()['kt_creative_clean']
if unmapped_creatives > 0:
print('Some unmapped kt_creatives found')
print('Acquiring process lock:', flag,
'so that the second part of RenTrak processing cannot proceed')
set_lock(flag_table, schema_name, flag, 0)
file_to_export = os.path.join(output_folder, output_file)
df[df['kt_creative_clean'].isnull()].to_excel(file_to_export, index
=False)
subject = (
'RenTrak automated processing step 1: new kt_creatives need to be mapped'
)
body = notify_for_manual_mapping(output_file, flag)
send_notification_email(ONSHORE_EMAIL_RECIPIENTS, subject, body,
file_to_export)
print('Notified the team to add manual mapping')
os.remove(file_to_export)
print('Deleted local file=>', file_to_export)
else:
print('Everything is mapped')
print('Releasing process lock:', flag,
'so that the second part of RenTrak processing can proceed')
set_lock(flag_table, schema_name, flag, 1)
subject = (
'RenTrak automated processing step 1: kt_creatives are all mapped. Step 2 will automatically commence.'
)
body = notify_no_new_mapping_found()
send_notification_email(ONSHORE_EMAIL_RECIPIENTS, subject, body)
print(
'Notified the team that no further action on their part is required'
)
if __name__ == '__main__':
main()
<|reserved_special_token_1|>
"""
TODO: update description after everything (requirements) is (are) stable/concrete
Description: Script to extract KeepingTrac's creative names and send
team notification to start manual mapping as necessary.
This step must happen BEFORE the processing of deduping of RenTrak
creative names (step 2 in RenTrak processing).
"""
import pandas as pd
from mailer import Mailer
from vertica_utils import *
from s3_utils import *
def notify_for_manual_mapping(file, process_name):
email_str = """
<p>Python script extracted new creative names from KeepingTrac data.</p>
<p>To run the rest of the RenTrak ETL process smoothly, please do the followings:
<ol>
<li>download the attached file, <b>{0}</b>, from this email</li>
<li>fill up empty (nan/NULL) kt_creative mappings under column C (kt_creative_clean) in that file</b></li>
<li>upload the modified file to the S3 location below
<span style="color: red;">(replace any file with the same name in the S3 folder, if any)</span>:<br>
<b>diap.prod.us-east-1.target/RenTrak/CreativeCleaned</b>
</li>
<li>run this feed in DataVault: <b>InCampaign KT Creative Mappings</b></li>
<li><span style="color: red;">AFTER the DataVault feed successfully loaded the mappings</span>,
run this SQL in Vertica backend: <br>
<b>
UPDATE gaintheory_us_targetusa_14.incampaign_process_switches
SET run = 1
WHERE process_name = '{1}';
</b>
</li>
</ol>
</p>
<p><strong style="color: red;">NOTE: If you forget a step or more above, the second part of RenTrak processing
may not produce correct results.</strong></p>
""".format(file, process_name)
return email_str
def notify_no_new_mapping_found():
email_str = """
<p>Python script does not find any new creative names from keepingtrac data.
Stage 2 of processing RenTrak data will begin when we load new data to RenTrak tables.
</p>
<p><b>No further action on your part is needed.</b></p>
"""
return email_str
def send_notification_email(recipients, subject, body, attachment=None):
Mailer().send_email(recipients, subject, body, attachment)
print("Notification email sent.")
# Function to extract data from vertica into a pandas dataframe
def vertica_extract(query, columns, index=None):
with vertica_python.connect(**conn_info) as connection:
cur = connection.cursor()
cur.execute(query)
results = pd.DataFrame(cur.fetchall())
results.columns = columns
if index:
return results.set_index(index)
else:
return results
def set_flag_value(table_name, schema_name, flag_name, value):
return """
UPDATE {1}.{0}
SET run = {3}
WHERE process_name = '{2}';
COMMIT;
""".format(table_name, schema_name, flag_name, value)
def set_lock(table_name, schema_name, flag_name, value):
with vertica_python.connect(**conn_info) as connection:
cur = connection.cursor()
cur.execute(set_flag_value(table_name, schema_name, flag_name, value))
connection.commit()
def main():
# start_date = (today - datetime.timedelta(weeks=6, days=1)).strftime('%Y-%m-%d')
schema_name = 'gaintheory_us_targetusa_14'
mapping_table = 'incampaign_kt_creative_mappings'
flag_table = 'incampaign_process_switches'
flag = 'rentrak_kt_creative_cleaned'
# Location of sources and destination files
output_folder = ROOT_FOLDER + 'RenTrak'
output_file = 'kt_creative_cleaned.xlsx'
if not os.path.exists(output_folder):
print("Creating a new local folder for export file:", output_folder)
os.makedirs(output_folder)
# Step 1: Download all possible KT combinations and current matching cleaned creative names
extract_query = """
SELECT Air_ISCI as kt_creative_id, Cmml_Title AS kt_creative, kt_creative_clean
FROM {1}.incampaign_keepingtrac_all a
LEFT JOIN {1}.{0} b
ON a.Air_ISCI = b.kt_creative_id
WHERE Air_ISCI IS NOT NULL
GROUP BY a.Air_ISCI, a.Cmml_Title, kt_creative_clean
ORDER BY kt_creative_id
""".format(mapping_table, schema_name)
df = vertica_extract(
extract_query,
['kt_creative_id', 'kt_creative', 'kt_creative_clean']
)
unmapped_creatives = df.isnull().sum()['kt_creative_clean'] # remove blank cells
if unmapped_creatives > 0:
print("Some unmapped kt_creatives found")
print("Acquiring process lock:", flag, "so that the second part of RenTrak processing cannot proceed")
set_lock(flag_table, schema_name, flag, 0)
file_to_export = os.path.join(output_folder, output_file)
df[df['kt_creative_clean'].isnull()].to_excel(file_to_export, index=False)
# Send email to tell the team to start manual mapping
subject = "RenTrak automated processing step 1: new kt_creatives need to be mapped"
body = notify_for_manual_mapping(output_file, flag)
send_notification_email(ONSHORE_EMAIL_RECIPIENTS, subject, body, file_to_export)
print("Notified the team to add manual mapping")
os.remove(file_to_export)
print("Deleted local file=>", file_to_export)
else:
print("Everything is mapped")
print("Releasing process lock:", flag, "so that the second part of RenTrak processing can proceed")
set_lock(flag_table, schema_name, flag, 1)
# insert, set flag to 1 and send email notification about being cleaned
subject = "RenTrak automated processing step 1: kt_creatives are all mapped. Step 2 will automatically commence."
body = notify_no_new_mapping_found()
send_notification_email(ONSHORE_EMAIL_RECIPIENTS, subject, body)
print("Notified the team that no further action on their part is required")
if __name__ == "__main__":
main()
|
flexible
|
{
"blob_id": "71c6d5e385e3db8444d7ef8b0231e72db8538eb7",
"index": 8106,
"step-1": "<mask token>\n\n\ndef notify_no_new_mapping_found():\n email_str = \"\"\"\n <p>Python script does not find any new creative names from keepingtrac data.\n Stage 2 of processing RenTrak data will begin when we load new data to RenTrak tables.\n </p>\n <p><b>No further action on your part is needed.</b></p>\n \"\"\"\n return email_str\n\n\n<mask token>\n\n\ndef vertica_extract(query, columns, index=None):\n with vertica_python.connect(**conn_info) as connection:\n cur = connection.cursor()\n cur.execute(query)\n results = pd.DataFrame(cur.fetchall())\n results.columns = columns\n if index:\n return results.set_index(index)\n else:\n return results\n\n\ndef set_flag_value(table_name, schema_name, flag_name, value):\n return (\n \"\"\"\n UPDATE {1}.{0}\n SET run = {3}\n WHERE process_name = '{2}';\n COMMIT;\n \"\"\"\n .format(table_name, schema_name, flag_name, value))\n\n\ndef set_lock(table_name, schema_name, flag_name, value):\n with vertica_python.connect(**conn_info) as connection:\n cur = connection.cursor()\n cur.execute(set_flag_value(table_name, schema_name, flag_name, value))\n connection.commit()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef notify_no_new_mapping_found():\n email_str = \"\"\"\n <p>Python script does not find any new creative names from keepingtrac data.\n Stage 2 of processing RenTrak data will begin when we load new data to RenTrak tables.\n </p>\n <p><b>No further action on your part is needed.</b></p>\n \"\"\"\n return email_str\n\n\ndef send_notification_email(recipients, subject, body, attachment=None):\n Mailer().send_email(recipients, subject, body, attachment)\n print('Notification email sent.')\n\n\ndef vertica_extract(query, columns, index=None):\n with vertica_python.connect(**conn_info) as connection:\n cur = connection.cursor()\n cur.execute(query)\n results = pd.DataFrame(cur.fetchall())\n results.columns = columns\n if index:\n return results.set_index(index)\n else:\n return results\n\n\ndef set_flag_value(table_name, schema_name, flag_name, value):\n return (\n \"\"\"\n UPDATE {1}.{0}\n SET run = {3}\n WHERE process_name = '{2}';\n COMMIT;\n \"\"\"\n .format(table_name, schema_name, flag_name, value))\n\n\ndef set_lock(table_name, schema_name, flag_name, value):\n with vertica_python.connect(**conn_info) as connection:\n cur = connection.cursor()\n cur.execute(set_flag_value(table_name, schema_name, flag_name, value))\n connection.commit()\n\n\ndef main():\n schema_name = 'gaintheory_us_targetusa_14'\n mapping_table = 'incampaign_kt_creative_mappings'\n flag_table = 'incampaign_process_switches'\n flag = 'rentrak_kt_creative_cleaned'\n output_folder = ROOT_FOLDER + 'RenTrak'\n output_file = 'kt_creative_cleaned.xlsx'\n if not os.path.exists(output_folder):\n print('Creating a new local folder for export file:', output_folder)\n os.makedirs(output_folder)\n extract_query = (\n \"\"\"\n SELECT Air_ISCI as kt_creative_id, Cmml_Title AS kt_creative, kt_creative_clean\n FROM {1}.incampaign_keepingtrac_all a\n LEFT JOIN {1}.{0} b\n ON a.Air_ISCI = b.kt_creative_id\n WHERE Air_ISCI IS NOT NULL\n GROUP BY a.Air_ISCI, a.Cmml_Title, kt_creative_clean\n ORDER BY kt_creative_id\n \"\"\"\n .format(mapping_table, schema_name))\n df = vertica_extract(extract_query, ['kt_creative_id', 'kt_creative',\n 'kt_creative_clean'])\n unmapped_creatives = df.isnull().sum()['kt_creative_clean']\n if unmapped_creatives > 0:\n print('Some unmapped kt_creatives found')\n print('Acquiring process lock:', flag,\n 'so that the second part of RenTrak processing cannot proceed')\n set_lock(flag_table, schema_name, flag, 0)\n file_to_export = os.path.join(output_folder, output_file)\n df[df['kt_creative_clean'].isnull()].to_excel(file_to_export, index\n =False)\n subject = (\n 'RenTrak automated processing step 1: new kt_creatives need to be mapped'\n )\n body = notify_for_manual_mapping(output_file, flag)\n send_notification_email(ONSHORE_EMAIL_RECIPIENTS, subject, body,\n file_to_export)\n print('Notified the team to add manual mapping')\n os.remove(file_to_export)\n print('Deleted local file=>', file_to_export)\n else:\n print('Everything is mapped')\n print('Releasing process lock:', flag,\n 'so that the second part of RenTrak processing can proceed')\n set_lock(flag_table, schema_name, flag, 1)\n subject = (\n 'RenTrak automated processing step 1: kt_creatives are all mapped. Step 2 will automatically commence.'\n )\n body = notify_no_new_mapping_found()\n send_notification_email(ONSHORE_EMAIL_RECIPIENTS, subject, body)\n print(\n 'Notified the team that no further action on their part is required'\n )\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef notify_for_manual_mapping(file, process_name):\n email_str = (\n \"\"\"\n <p>Python script extracted new creative names from KeepingTrac data.</p>\n <p>To run the rest of the RenTrak ETL process smoothly, please do the followings:\n <ol>\n <li>download the attached file, <b>{0}</b>, from this email</li>\n <li>fill up empty (nan/NULL) kt_creative mappings under column C (kt_creative_clean) in that file</b></li>\n <li>upload the modified file to the S3 location below\n <span style=\"color: red;\">(replace any file with the same name in the S3 folder, if any)</span>:<br>\n <b>diap.prod.us-east-1.target/RenTrak/CreativeCleaned</b>\n </li>\n <li>run this feed in DataVault: <b>InCampaign KT Creative Mappings</b></li>\n <li><span style=\"color: red;\">AFTER the DataVault feed successfully loaded the mappings</span>,\n run this SQL in Vertica backend: <br>\n <b>\n UPDATE gaintheory_us_targetusa_14.incampaign_process_switches\n SET run = 1\n WHERE process_name = '{1}';\n </b>\n </li>\n </ol>\n </p>\n <p><strong style=\"color: red;\">NOTE: If you forget a step or more above, the second part of RenTrak processing\n may not produce correct results.</strong></p>\n \"\"\"\n .format(file, process_name))\n return email_str\n\n\ndef notify_no_new_mapping_found():\n email_str = \"\"\"\n <p>Python script does not find any new creative names from keepingtrac data.\n Stage 2 of processing RenTrak data will begin when we load new data to RenTrak tables.\n </p>\n <p><b>No further action on your part is needed.</b></p>\n \"\"\"\n return email_str\n\n\ndef send_notification_email(recipients, subject, body, attachment=None):\n Mailer().send_email(recipients, subject, body, attachment)\n print('Notification email sent.')\n\n\ndef vertica_extract(query, columns, index=None):\n with vertica_python.connect(**conn_info) as connection:\n cur = connection.cursor()\n cur.execute(query)\n results = pd.DataFrame(cur.fetchall())\n results.columns = columns\n if index:\n return results.set_index(index)\n else:\n return results\n\n\ndef set_flag_value(table_name, schema_name, flag_name, value):\n return (\n \"\"\"\n UPDATE {1}.{0}\n SET run = {3}\n WHERE process_name = '{2}';\n COMMIT;\n \"\"\"\n .format(table_name, schema_name, flag_name, value))\n\n\ndef set_lock(table_name, schema_name, flag_name, value):\n with vertica_python.connect(**conn_info) as connection:\n cur = connection.cursor()\n cur.execute(set_flag_value(table_name, schema_name, flag_name, value))\n connection.commit()\n\n\ndef main():\n schema_name = 'gaintheory_us_targetusa_14'\n mapping_table = 'incampaign_kt_creative_mappings'\n flag_table = 'incampaign_process_switches'\n flag = 'rentrak_kt_creative_cleaned'\n output_folder = ROOT_FOLDER + 'RenTrak'\n output_file = 'kt_creative_cleaned.xlsx'\n if not os.path.exists(output_folder):\n print('Creating a new local folder for export file:', output_folder)\n os.makedirs(output_folder)\n extract_query = (\n \"\"\"\n SELECT Air_ISCI as kt_creative_id, Cmml_Title AS kt_creative, kt_creative_clean\n FROM {1}.incampaign_keepingtrac_all a\n LEFT JOIN {1}.{0} b\n ON a.Air_ISCI = b.kt_creative_id\n WHERE Air_ISCI IS NOT NULL\n GROUP BY a.Air_ISCI, a.Cmml_Title, kt_creative_clean\n ORDER BY kt_creative_id\n \"\"\"\n .format(mapping_table, schema_name))\n df = vertica_extract(extract_query, ['kt_creative_id', 'kt_creative',\n 'kt_creative_clean'])\n unmapped_creatives = df.isnull().sum()['kt_creative_clean']\n if unmapped_creatives > 0:\n print('Some unmapped kt_creatives found')\n print('Acquiring process lock:', flag,\n 'so that the second part of RenTrak processing cannot proceed')\n set_lock(flag_table, schema_name, flag, 0)\n file_to_export = os.path.join(output_folder, output_file)\n df[df['kt_creative_clean'].isnull()].to_excel(file_to_export, index\n =False)\n subject = (\n 'RenTrak automated processing step 1: new kt_creatives need to be mapped'\n )\n body = notify_for_manual_mapping(output_file, flag)\n send_notification_email(ONSHORE_EMAIL_RECIPIENTS, subject, body,\n file_to_export)\n print('Notified the team to add manual mapping')\n os.remove(file_to_export)\n print('Deleted local file=>', file_to_export)\n else:\n print('Everything is mapped')\n print('Releasing process lock:', flag,\n 'so that the second part of RenTrak processing can proceed')\n set_lock(flag_table, schema_name, flag, 1)\n subject = (\n 'RenTrak automated processing step 1: kt_creatives are all mapped. Step 2 will automatically commence.'\n )\n body = notify_no_new_mapping_found()\n send_notification_email(ONSHORE_EMAIL_RECIPIENTS, subject, body)\n print(\n 'Notified the team that no further action on their part is required'\n )\n\n\n<mask token>\n",
"step-4": "<mask token>\n\n\ndef notify_for_manual_mapping(file, process_name):\n email_str = (\n \"\"\"\n <p>Python script extracted new creative names from KeepingTrac data.</p>\n <p>To run the rest of the RenTrak ETL process smoothly, please do the followings:\n <ol>\n <li>download the attached file, <b>{0}</b>, from this email</li>\n <li>fill up empty (nan/NULL) kt_creative mappings under column C (kt_creative_clean) in that file</b></li>\n <li>upload the modified file to the S3 location below\n <span style=\"color: red;\">(replace any file with the same name in the S3 folder, if any)</span>:<br>\n <b>diap.prod.us-east-1.target/RenTrak/CreativeCleaned</b>\n </li>\n <li>run this feed in DataVault: <b>InCampaign KT Creative Mappings</b></li>\n <li><span style=\"color: red;\">AFTER the DataVault feed successfully loaded the mappings</span>,\n run this SQL in Vertica backend: <br>\n <b>\n UPDATE gaintheory_us_targetusa_14.incampaign_process_switches\n SET run = 1\n WHERE process_name = '{1}';\n </b>\n </li>\n </ol>\n </p>\n <p><strong style=\"color: red;\">NOTE: If you forget a step or more above, the second part of RenTrak processing\n may not produce correct results.</strong></p>\n \"\"\"\n .format(file, process_name))\n return email_str\n\n\ndef notify_no_new_mapping_found():\n email_str = \"\"\"\n <p>Python script does not find any new creative names from keepingtrac data.\n Stage 2 of processing RenTrak data will begin when we load new data to RenTrak tables.\n </p>\n <p><b>No further action on your part is needed.</b></p>\n \"\"\"\n return email_str\n\n\ndef send_notification_email(recipients, subject, body, attachment=None):\n Mailer().send_email(recipients, subject, body, attachment)\n print('Notification email sent.')\n\n\ndef vertica_extract(query, columns, index=None):\n with vertica_python.connect(**conn_info) as connection:\n cur = connection.cursor()\n cur.execute(query)\n results = pd.DataFrame(cur.fetchall())\n results.columns = columns\n if index:\n return results.set_index(index)\n else:\n return results\n\n\ndef set_flag_value(table_name, schema_name, flag_name, value):\n return (\n \"\"\"\n UPDATE {1}.{0}\n SET run = {3}\n WHERE process_name = '{2}';\n COMMIT;\n \"\"\"\n .format(table_name, schema_name, flag_name, value))\n\n\ndef set_lock(table_name, schema_name, flag_name, value):\n with vertica_python.connect(**conn_info) as connection:\n cur = connection.cursor()\n cur.execute(set_flag_value(table_name, schema_name, flag_name, value))\n connection.commit()\n\n\ndef main():\n schema_name = 'gaintheory_us_targetusa_14'\n mapping_table = 'incampaign_kt_creative_mappings'\n flag_table = 'incampaign_process_switches'\n flag = 'rentrak_kt_creative_cleaned'\n output_folder = ROOT_FOLDER + 'RenTrak'\n output_file = 'kt_creative_cleaned.xlsx'\n if not os.path.exists(output_folder):\n print('Creating a new local folder for export file:', output_folder)\n os.makedirs(output_folder)\n extract_query = (\n \"\"\"\n SELECT Air_ISCI as kt_creative_id, Cmml_Title AS kt_creative, kt_creative_clean\n FROM {1}.incampaign_keepingtrac_all a\n LEFT JOIN {1}.{0} b\n ON a.Air_ISCI = b.kt_creative_id\n WHERE Air_ISCI IS NOT NULL\n GROUP BY a.Air_ISCI, a.Cmml_Title, kt_creative_clean\n ORDER BY kt_creative_id\n \"\"\"\n .format(mapping_table, schema_name))\n df = vertica_extract(extract_query, ['kt_creative_id', 'kt_creative',\n 'kt_creative_clean'])\n unmapped_creatives = df.isnull().sum()['kt_creative_clean']\n if unmapped_creatives > 0:\n print('Some unmapped kt_creatives found')\n print('Acquiring process lock:', flag,\n 'so that the second part of RenTrak processing cannot proceed')\n set_lock(flag_table, schema_name, flag, 0)\n file_to_export = os.path.join(output_folder, output_file)\n df[df['kt_creative_clean'].isnull()].to_excel(file_to_export, index\n =False)\n subject = (\n 'RenTrak automated processing step 1: new kt_creatives need to be mapped'\n )\n body = notify_for_manual_mapping(output_file, flag)\n send_notification_email(ONSHORE_EMAIL_RECIPIENTS, subject, body,\n file_to_export)\n print('Notified the team to add manual mapping')\n os.remove(file_to_export)\n print('Deleted local file=>', file_to_export)\n else:\n print('Everything is mapped')\n print('Releasing process lock:', flag,\n 'so that the second part of RenTrak processing can proceed')\n set_lock(flag_table, schema_name, flag, 1)\n subject = (\n 'RenTrak automated processing step 1: kt_creatives are all mapped. Step 2 will automatically commence.'\n )\n body = notify_no_new_mapping_found()\n send_notification_email(ONSHORE_EMAIL_RECIPIENTS, subject, body)\n print(\n 'Notified the team that no further action on their part is required'\n )\n\n\nif __name__ == '__main__':\n main()\n",
"step-5": "\"\"\"\r\nTODO: update description after everything (requirements) is (are) stable/concrete\r\nDescription: Script to extract KeepingTrac's creative names and send\r\nteam notification to start manual mapping as necessary.\r\n\r\nThis step must happen BEFORE the processing of deduping of RenTrak\r\ncreative names (step 2 in RenTrak processing).\r\n\"\"\"\r\nimport pandas as pd\r\n\r\nfrom mailer import Mailer\r\nfrom vertica_utils import *\r\nfrom s3_utils import *\r\n\r\n\r\ndef notify_for_manual_mapping(file, process_name):\r\n email_str = \"\"\"\r\n <p>Python script extracted new creative names from KeepingTrac data.</p>\r\n <p>To run the rest of the RenTrak ETL process smoothly, please do the followings:\r\n <ol>\r\n <li>download the attached file, <b>{0}</b>, from this email</li>\r\n <li>fill up empty (nan/NULL) kt_creative mappings under column C (kt_creative_clean) in that file</b></li>\r\n <li>upload the modified file to the S3 location below\r\n <span style=\"color: red;\">(replace any file with the same name in the S3 folder, if any)</span>:<br>\r\n <b>diap.prod.us-east-1.target/RenTrak/CreativeCleaned</b>\r\n </li>\r\n <li>run this feed in DataVault: <b>InCampaign KT Creative Mappings</b></li>\r\n <li><span style=\"color: red;\">AFTER the DataVault feed successfully loaded the mappings</span>,\r\n run this SQL in Vertica backend: <br>\r\n <b>\r\n UPDATE gaintheory_us_targetusa_14.incampaign_process_switches\r\n SET run = 1\r\n WHERE process_name = '{1}';\r\n </b>\r\n </li>\r\n </ol>\r\n </p>\r\n <p><strong style=\"color: red;\">NOTE: If you forget a step or more above, the second part of RenTrak processing\r\n may not produce correct results.</strong></p>\r\n \"\"\".format(file, process_name)\r\n return email_str\r\n\r\n\r\ndef notify_no_new_mapping_found():\r\n email_str = \"\"\"\r\n <p>Python script does not find any new creative names from keepingtrac data.\r\n Stage 2 of processing RenTrak data will begin when we load new data to RenTrak tables.\r\n </p>\r\n <p><b>No further action on your part is needed.</b></p>\r\n \"\"\"\r\n return email_str\r\n\r\n\r\ndef send_notification_email(recipients, subject, body, attachment=None):\r\n Mailer().send_email(recipients, subject, body, attachment)\r\n print(\"Notification email sent.\")\r\n\r\n\r\n# Function to extract data from vertica into a pandas dataframe\r\ndef vertica_extract(query, columns, index=None):\r\n with vertica_python.connect(**conn_info) as connection:\r\n cur = connection.cursor()\r\n cur.execute(query)\r\n results = pd.DataFrame(cur.fetchall())\r\n results.columns = columns\r\n if index:\r\n return results.set_index(index)\r\n else:\r\n return results\r\n\r\n\r\ndef set_flag_value(table_name, schema_name, flag_name, value):\r\n return \"\"\"\r\n UPDATE {1}.{0}\r\n SET run = {3}\r\n WHERE process_name = '{2}';\r\n COMMIT;\r\n \"\"\".format(table_name, schema_name, flag_name, value)\r\n\r\n\r\ndef set_lock(table_name, schema_name, flag_name, value):\r\n with vertica_python.connect(**conn_info) as connection:\r\n cur = connection.cursor()\r\n cur.execute(set_flag_value(table_name, schema_name, flag_name, value))\r\n connection.commit()\r\n\r\n\r\ndef main():\r\n # start_date = (today - datetime.timedelta(weeks=6, days=1)).strftime('%Y-%m-%d')\r\n schema_name = 'gaintheory_us_targetusa_14'\r\n mapping_table = 'incampaign_kt_creative_mappings'\r\n flag_table = 'incampaign_process_switches'\r\n flag = 'rentrak_kt_creative_cleaned'\r\n\r\n # Location of sources and destination files\r\n output_folder = ROOT_FOLDER + 'RenTrak'\r\n output_file = 'kt_creative_cleaned.xlsx'\r\n\r\n if not os.path.exists(output_folder):\r\n print(\"Creating a new local folder for export file:\", output_folder)\r\n os.makedirs(output_folder)\r\n\r\n # Step 1: Download all possible KT combinations and current matching cleaned creative names\r\n extract_query = \"\"\"\r\n SELECT Air_ISCI as kt_creative_id, Cmml_Title AS kt_creative, kt_creative_clean\r\n FROM {1}.incampaign_keepingtrac_all a\r\n LEFT JOIN {1}.{0} b\r\n ON a.Air_ISCI = b.kt_creative_id\r\n WHERE Air_ISCI IS NOT NULL\r\n GROUP BY a.Air_ISCI, a.Cmml_Title, kt_creative_clean\r\n ORDER BY kt_creative_id\r\n \"\"\".format(mapping_table, schema_name)\r\n\r\n df = vertica_extract(\r\n extract_query,\r\n ['kt_creative_id', 'kt_creative', 'kt_creative_clean']\r\n )\r\n unmapped_creatives = df.isnull().sum()['kt_creative_clean'] # remove blank cells\r\n\r\n if unmapped_creatives > 0:\r\n print(\"Some unmapped kt_creatives found\")\r\n print(\"Acquiring process lock:\", flag, \"so that the second part of RenTrak processing cannot proceed\")\r\n set_lock(flag_table, schema_name, flag, 0)\r\n\r\n file_to_export = os.path.join(output_folder, output_file)\r\n df[df['kt_creative_clean'].isnull()].to_excel(file_to_export, index=False)\r\n\r\n # Send email to tell the team to start manual mapping\r\n subject = \"RenTrak automated processing step 1: new kt_creatives need to be mapped\"\r\n body = notify_for_manual_mapping(output_file, flag)\r\n send_notification_email(ONSHORE_EMAIL_RECIPIENTS, subject, body, file_to_export)\r\n print(\"Notified the team to add manual mapping\")\r\n\r\n os.remove(file_to_export)\r\n print(\"Deleted local file=>\", file_to_export)\r\n\r\n else:\r\n print(\"Everything is mapped\")\r\n print(\"Releasing process lock:\", flag, \"so that the second part of RenTrak processing can proceed\")\r\n set_lock(flag_table, schema_name, flag, 1)\r\n\r\n # insert, set flag to 1 and send email notification about being cleaned\r\n subject = \"RenTrak automated processing step 1: kt_creatives are all mapped. Step 2 will automatically commence.\"\r\n body = notify_no_new_mapping_found()\r\n send_notification_email(ONSHORE_EMAIL_RECIPIENTS, subject, body)\r\n print(\"Notified the team that no further action on their part is required\")\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n",
"step-ids": [
4,
6,
7,
8,
10
]
}
|
[
4,
6,
7,
8,
10
] |
from whylogs.core.annotation_profiling import Rectangle
def test_rect():
rect = Rectangle([[0, 0], [10, 10]], confidence=0.8, labels=[{"name": "test"}])
test = Rectangle([[0, 0], [5, 5]])
assert rect.area == 100
assert rect.intersection(test) == 25
assert rect.iou(test) == 25 / 100.0
def test_rect():
rect = Rectangle([[0, 0], [0, 0]])
test = Rectangle([[0, 0], [5, 5]])
assert rect.area == 0
assert rect.intersection(test) == 0
assert rect.iou(test) == 0
|
normal
|
{
"blob_id": "b65d25198d55ab4a859b9718b7b225fa92c13a2b",
"index": 1202,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef test_rect():\n rect = Rectangle([[0, 0], [10, 10]], confidence=0.8, labels=[{'name':\n 'test'}])\n test = Rectangle([[0, 0], [5, 5]])\n assert rect.area == 100\n assert rect.intersection(test) == 25\n assert rect.iou(test) == 25 / 100.0\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef test_rect():\n rect = Rectangle([[0, 0], [10, 10]], confidence=0.8, labels=[{'name':\n 'test'}])\n test = Rectangle([[0, 0], [5, 5]])\n assert rect.area == 100\n assert rect.intersection(test) == 25\n assert rect.iou(test) == 25 / 100.0\n\n\ndef test_rect():\n rect = Rectangle([[0, 0], [0, 0]])\n test = Rectangle([[0, 0], [5, 5]])\n assert rect.area == 0\n assert rect.intersection(test) == 0\n assert rect.iou(test) == 0\n",
"step-4": "from whylogs.core.annotation_profiling import Rectangle\n\n\ndef test_rect():\n rect = Rectangle([[0, 0], [10, 10]], confidence=0.8, labels=[{'name':\n 'test'}])\n test = Rectangle([[0, 0], [5, 5]])\n assert rect.area == 100\n assert rect.intersection(test) == 25\n assert rect.iou(test) == 25 / 100.0\n\n\ndef test_rect():\n rect = Rectangle([[0, 0], [0, 0]])\n test = Rectangle([[0, 0], [5, 5]])\n assert rect.area == 0\n assert rect.intersection(test) == 0\n assert rect.iou(test) == 0\n",
"step-5": "from whylogs.core.annotation_profiling import Rectangle\n\n\ndef test_rect():\n\n rect = Rectangle([[0, 0], [10, 10]], confidence=0.8, labels=[{\"name\": \"test\"}])\n test = Rectangle([[0, 0], [5, 5]])\n assert rect.area == 100\n assert rect.intersection(test) == 25\n assert rect.iou(test) == 25 / 100.0\n\n\ndef test_rect():\n\n rect = Rectangle([[0, 0], [0, 0]])\n test = Rectangle([[0, 0], [5, 5]])\n assert rect.area == 0\n assert rect.intersection(test) == 0\n assert rect.iou(test) == 0\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
logger.setLevel(logging.DEBUG)
<|reserved_special_token_0|>
model.fit(X=train, eval_data=val, batch_end_callback=mx.callback.
Speedometer(batch_size, 50), epoch_end_callback=mx.callback.
do_checkpoint(model_prefix))
<|reserved_special_token_1|>
<|reserved_special_token_0|>
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
dev = mx.gpu()
batch_size = 64
data_shape = 3, 36, 36
num_examples = 20000
epoch_size = num_examples / batch_size
lr_factor_epoch = 15
model_prefix = './models/sample_net'
train = mx.io.ImageRecordIter(path_imgrec='tr.rec', mean_r=128, mean_g=128,
mean_b=128, scale=0.0078125, max_aspect_ratio=0.35, data_shape=
data_shape, batch_size=batch_size, rand_crop=True, rand_mirror=True)
val = mx.io.ImageRecordIter(path_imgrec='va.rec', mean_r=128, mean_b=128,
mean_g=128, scale=0.0078125, rand_crop=False, rand_mirror=False,
data_shape=data_shape, batch_size=batch_size)
net = mx.sym.Variable('data')
net = mx.sym.Convolution(data=net, kernel=(5, 5), num_filter=32, pad=(2, 2))
net = mx.sym.Activation(data=net, act_type='relu')
net = mx.sym.Convolution(data=net, kernel=(5, 5), num_filter=64, pad=(2, 2))
net = mx.sym.Activation(data=net, act_type='relu')
net = mx.sym.Pooling(data=net, pool_type='max', kernel=(3, 3), stride=(2, 2))
net = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=64, pad=(1, 1))
net = mx.sym.Activation(data=net, act_type='relu')
net = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=64, pad=(1, 1))
net = mx.sym.Activation(data=net, act_type='relu')
net = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=128, pad=(1, 1))
net = mx.sym.Activation(data=net, act_type='relu')
net = mx.sym.Pooling(data=net, pool_type='max', kernel=(3, 3), stride=(2, 2))
net = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=256, pad=(1, 1))
net = mx.sym.Activation(data=net, act_type='relu')
net = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=256, pad=(1, 1))
net = mx.sym.Activation(data=net, act_type='relu')
net = mx.sym.Pooling(data=net, pool_type='avg', kernel=(9, 9), stride=(1, 1))
net = mx.sym.Flatten(data=net)
net = mx.sym.Dropout(data=net, p=0.25)
net = mx.sym.FullyConnected(data=net, num_hidden=121)
net = mx.symbol.SoftmaxOutput(data=net, name='softmax')
model = mx.model.FeedForward(ctx=dev, symbol=net, num_epoch=35,
learning_rate=0.01, momentum=0.9, wd=0.0001, clip_gradient=5,
lr_scheduler=mx.lr_scheduler.FactorScheduler(step=epoch_size *
lr_factor_epoch, factor=0.1), initializer=mx.init.Xavier(factor_type=
'in', magnitude=2.34))
model.fit(X=train, eval_data=val, batch_end_callback=mx.callback.
Speedometer(batch_size, 50), epoch_end_callback=mx.callback.
do_checkpoint(model_prefix))
<|reserved_special_token_1|>
import mxnet as mx
import numpy as np
import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
dev = mx.gpu()
batch_size = 64
data_shape = 3, 36, 36
num_examples = 20000
epoch_size = num_examples / batch_size
lr_factor_epoch = 15
model_prefix = './models/sample_net'
train = mx.io.ImageRecordIter(path_imgrec='tr.rec', mean_r=128, mean_g=128,
mean_b=128, scale=0.0078125, max_aspect_ratio=0.35, data_shape=
data_shape, batch_size=batch_size, rand_crop=True, rand_mirror=True)
val = mx.io.ImageRecordIter(path_imgrec='va.rec', mean_r=128, mean_b=128,
mean_g=128, scale=0.0078125, rand_crop=False, rand_mirror=False,
data_shape=data_shape, batch_size=batch_size)
net = mx.sym.Variable('data')
net = mx.sym.Convolution(data=net, kernel=(5, 5), num_filter=32, pad=(2, 2))
net = mx.sym.Activation(data=net, act_type='relu')
net = mx.sym.Convolution(data=net, kernel=(5, 5), num_filter=64, pad=(2, 2))
net = mx.sym.Activation(data=net, act_type='relu')
net = mx.sym.Pooling(data=net, pool_type='max', kernel=(3, 3), stride=(2, 2))
net = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=64, pad=(1, 1))
net = mx.sym.Activation(data=net, act_type='relu')
net = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=64, pad=(1, 1))
net = mx.sym.Activation(data=net, act_type='relu')
net = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=128, pad=(1, 1))
net = mx.sym.Activation(data=net, act_type='relu')
net = mx.sym.Pooling(data=net, pool_type='max', kernel=(3, 3), stride=(2, 2))
net = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=256, pad=(1, 1))
net = mx.sym.Activation(data=net, act_type='relu')
net = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=256, pad=(1, 1))
net = mx.sym.Activation(data=net, act_type='relu')
net = mx.sym.Pooling(data=net, pool_type='avg', kernel=(9, 9), stride=(1, 1))
net = mx.sym.Flatten(data=net)
net = mx.sym.Dropout(data=net, p=0.25)
net = mx.sym.FullyConnected(data=net, num_hidden=121)
net = mx.symbol.SoftmaxOutput(data=net, name='softmax')
model = mx.model.FeedForward(ctx=dev, symbol=net, num_epoch=35,
learning_rate=0.01, momentum=0.9, wd=0.0001, clip_gradient=5,
lr_scheduler=mx.lr_scheduler.FactorScheduler(step=epoch_size *
lr_factor_epoch, factor=0.1), initializer=mx.init.Xavier(factor_type=
'in', magnitude=2.34))
model.fit(X=train, eval_data=val, batch_end_callback=mx.callback.
Speedometer(batch_size, 50), epoch_end_callback=mx.callback.
do_checkpoint(model_prefix))
<|reserved_special_token_1|>
import mxnet as mx
import numpy as np
import logging
# Example performance:
# INFO:root:Epoch[34] Train-accuracy=0.601388
# INFO:root:Epoch[34] Validation-accuracy=0.620949
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# running device
dev = mx.gpu()
# batch size and input shape
batch_size = 64
data_shape = (3, 36, 36)
# training data info for learning rate reduction
num_examples = 20000
epoch_size = num_examples / batch_size
lr_factor_epoch = 15
# model saving parameter
model_prefix = "./models/sample_net"
# train data iterator
train = mx.io.ImageRecordIter(
path_imgrec = "tr.rec",
mean_r = 128,
mean_g = 128,
mean_b = 128,
scale = 0.0078125,
max_aspect_ratio = 0.35,
data_shape = data_shape,
batch_size = batch_size,
rand_crop = True,
rand_mirror = True)
# validate data iterator
val = mx.io.ImageRecordIter(
path_imgrec = "va.rec",
mean_r = 128,
mean_b = 128,
mean_g = 128,
scale = 0.0078125,
rand_crop = False,
rand_mirror = False,
data_shape = data_shape,
batch_size = batch_size)
# network definition
# stage 1
net = mx.sym.Variable("data")
net = mx.sym.Convolution(data=net, kernel=(5, 5), num_filter=32, pad=(2, 2))
net = mx.sym.Activation(data=net, act_type="relu")
net = mx.sym.Convolution(data=net, kernel=(5, 5), num_filter=64, pad=(2, 2))
net = mx.sym.Activation(data=net, act_type="relu")
net = mx.sym.Pooling(data=net, pool_type="max", kernel=(3, 3), stride=(2, 2))
# stage 2
net = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=64, pad=(1, 1))
net = mx.sym.Activation(data=net, act_type="relu")
net = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=64, pad=(1, 1))
net = mx.sym.Activation(data=net, act_type="relu")
net = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=128, pad=(1, 1))
net = mx.sym.Activation(data=net, act_type="relu")
net = mx.sym.Pooling(data=net, pool_type="max", kernel=(3, 3), stride=(2, 2))
# stage 3
net = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=256, pad=(1, 1))
net = mx.sym.Activation(data=net, act_type="relu")
net = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=256, pad=(1, 1))
net = mx.sym.Activation(data=net, act_type="relu")
net = mx.sym.Pooling(data=net, pool_type="avg", kernel=(9, 9), stride=(1, 1))
# stage 4
net = mx.sym.Flatten(data=net)
net = mx.sym.Dropout(data=net, p=0.25)
net = mx.sym.FullyConnected(data=net, num_hidden=121)
net = mx.symbol.SoftmaxOutput(data=net, name='softmax')
# Model parameter
# This model will reduce learning rate by factor 0.1 for every 15 epoch
model = mx.model.FeedForward(
ctx = dev,
symbol = net,
num_epoch = 35,
learning_rate = 0.01,
momentum = 0.9,
wd = 0.0001,
clip_gradient = 5,
lr_scheduler = mx.lr_scheduler.FactorScheduler(step=epoch_size * lr_factor_epoch, factor = 0.1),
initializer = mx.init.Xavier(factor_type="in", magnitude=2.34))
# fit the model
model.fit(
X = train,
eval_data = val,
batch_end_callback = mx.callback.Speedometer(batch_size, 50),
epoch_end_callback = mx.callback.do_checkpoint(model_prefix))
|
flexible
|
{
"blob_id": "e82b9aa0f7dc669b3d5622c093b766c7e168221c",
"index": 5757,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nlogger.setLevel(logging.DEBUG)\n<mask token>\nmodel.fit(X=train, eval_data=val, batch_end_callback=mx.callback.\n Speedometer(batch_size, 50), epoch_end_callback=mx.callback.\n do_checkpoint(model_prefix))\n",
"step-3": "<mask token>\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\ndev = mx.gpu()\nbatch_size = 64\ndata_shape = 3, 36, 36\nnum_examples = 20000\nepoch_size = num_examples / batch_size\nlr_factor_epoch = 15\nmodel_prefix = './models/sample_net'\ntrain = mx.io.ImageRecordIter(path_imgrec='tr.rec', mean_r=128, mean_g=128,\n mean_b=128, scale=0.0078125, max_aspect_ratio=0.35, data_shape=\n data_shape, batch_size=batch_size, rand_crop=True, rand_mirror=True)\nval = mx.io.ImageRecordIter(path_imgrec='va.rec', mean_r=128, mean_b=128,\n mean_g=128, scale=0.0078125, rand_crop=False, rand_mirror=False,\n data_shape=data_shape, batch_size=batch_size)\nnet = mx.sym.Variable('data')\nnet = mx.sym.Convolution(data=net, kernel=(5, 5), num_filter=32, pad=(2, 2))\nnet = mx.sym.Activation(data=net, act_type='relu')\nnet = mx.sym.Convolution(data=net, kernel=(5, 5), num_filter=64, pad=(2, 2))\nnet = mx.sym.Activation(data=net, act_type='relu')\nnet = mx.sym.Pooling(data=net, pool_type='max', kernel=(3, 3), stride=(2, 2))\nnet = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=64, pad=(1, 1))\nnet = mx.sym.Activation(data=net, act_type='relu')\nnet = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=64, pad=(1, 1))\nnet = mx.sym.Activation(data=net, act_type='relu')\nnet = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=128, pad=(1, 1))\nnet = mx.sym.Activation(data=net, act_type='relu')\nnet = mx.sym.Pooling(data=net, pool_type='max', kernel=(3, 3), stride=(2, 2))\nnet = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=256, pad=(1, 1))\nnet = mx.sym.Activation(data=net, act_type='relu')\nnet = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=256, pad=(1, 1))\nnet = mx.sym.Activation(data=net, act_type='relu')\nnet = mx.sym.Pooling(data=net, pool_type='avg', kernel=(9, 9), stride=(1, 1))\nnet = mx.sym.Flatten(data=net)\nnet = mx.sym.Dropout(data=net, p=0.25)\nnet = mx.sym.FullyConnected(data=net, num_hidden=121)\nnet = mx.symbol.SoftmaxOutput(data=net, name='softmax')\nmodel = mx.model.FeedForward(ctx=dev, symbol=net, num_epoch=35,\n learning_rate=0.01, momentum=0.9, wd=0.0001, clip_gradient=5,\n lr_scheduler=mx.lr_scheduler.FactorScheduler(step=epoch_size *\n lr_factor_epoch, factor=0.1), initializer=mx.init.Xavier(factor_type=\n 'in', magnitude=2.34))\nmodel.fit(X=train, eval_data=val, batch_end_callback=mx.callback.\n Speedometer(batch_size, 50), epoch_end_callback=mx.callback.\n do_checkpoint(model_prefix))\n",
"step-4": "import mxnet as mx\nimport numpy as np\nimport logging\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\ndev = mx.gpu()\nbatch_size = 64\ndata_shape = 3, 36, 36\nnum_examples = 20000\nepoch_size = num_examples / batch_size\nlr_factor_epoch = 15\nmodel_prefix = './models/sample_net'\ntrain = mx.io.ImageRecordIter(path_imgrec='tr.rec', mean_r=128, mean_g=128,\n mean_b=128, scale=0.0078125, max_aspect_ratio=0.35, data_shape=\n data_shape, batch_size=batch_size, rand_crop=True, rand_mirror=True)\nval = mx.io.ImageRecordIter(path_imgrec='va.rec', mean_r=128, mean_b=128,\n mean_g=128, scale=0.0078125, rand_crop=False, rand_mirror=False,\n data_shape=data_shape, batch_size=batch_size)\nnet = mx.sym.Variable('data')\nnet = mx.sym.Convolution(data=net, kernel=(5, 5), num_filter=32, pad=(2, 2))\nnet = mx.sym.Activation(data=net, act_type='relu')\nnet = mx.sym.Convolution(data=net, kernel=(5, 5), num_filter=64, pad=(2, 2))\nnet = mx.sym.Activation(data=net, act_type='relu')\nnet = mx.sym.Pooling(data=net, pool_type='max', kernel=(3, 3), stride=(2, 2))\nnet = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=64, pad=(1, 1))\nnet = mx.sym.Activation(data=net, act_type='relu')\nnet = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=64, pad=(1, 1))\nnet = mx.sym.Activation(data=net, act_type='relu')\nnet = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=128, pad=(1, 1))\nnet = mx.sym.Activation(data=net, act_type='relu')\nnet = mx.sym.Pooling(data=net, pool_type='max', kernel=(3, 3), stride=(2, 2))\nnet = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=256, pad=(1, 1))\nnet = mx.sym.Activation(data=net, act_type='relu')\nnet = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=256, pad=(1, 1))\nnet = mx.sym.Activation(data=net, act_type='relu')\nnet = mx.sym.Pooling(data=net, pool_type='avg', kernel=(9, 9), stride=(1, 1))\nnet = mx.sym.Flatten(data=net)\nnet = mx.sym.Dropout(data=net, p=0.25)\nnet = mx.sym.FullyConnected(data=net, num_hidden=121)\nnet = mx.symbol.SoftmaxOutput(data=net, name='softmax')\nmodel = mx.model.FeedForward(ctx=dev, symbol=net, num_epoch=35,\n learning_rate=0.01, momentum=0.9, wd=0.0001, clip_gradient=5,\n lr_scheduler=mx.lr_scheduler.FactorScheduler(step=epoch_size *\n lr_factor_epoch, factor=0.1), initializer=mx.init.Xavier(factor_type=\n 'in', magnitude=2.34))\nmodel.fit(X=train, eval_data=val, batch_end_callback=mx.callback.\n Speedometer(batch_size, 50), epoch_end_callback=mx.callback.\n do_checkpoint(model_prefix))\n",
"step-5": "import mxnet as mx\nimport numpy as np\nimport logging\n\n# Example performance:\n# INFO:root:Epoch[34] Train-accuracy=0.601388\n# INFO:root:Epoch[34] Validation-accuracy=0.620949\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\n\n# running device\ndev = mx.gpu()\n# batch size and input shape\nbatch_size = 64\ndata_shape = (3, 36, 36)\n# training data info for learning rate reduction\nnum_examples = 20000\nepoch_size = num_examples / batch_size\nlr_factor_epoch = 15\n# model saving parameter\nmodel_prefix = \"./models/sample_net\"\n\n# train data iterator\ntrain = mx.io.ImageRecordIter(\n path_imgrec = \"tr.rec\",\n mean_r = 128,\n mean_g = 128,\n mean_b = 128,\n scale = 0.0078125,\n max_aspect_ratio = 0.35,\n data_shape = data_shape,\n batch_size = batch_size,\n rand_crop = True,\n rand_mirror = True)\n\n# validate data iterator\nval = mx.io.ImageRecordIter(\n path_imgrec = \"va.rec\",\n mean_r = 128,\n mean_b = 128,\n mean_g = 128,\n scale = 0.0078125,\n rand_crop = False,\n rand_mirror = False,\n data_shape = data_shape,\n batch_size = batch_size)\n\n# network definition\n# stage 1\nnet = mx.sym.Variable(\"data\")\nnet = mx.sym.Convolution(data=net, kernel=(5, 5), num_filter=32, pad=(2, 2))\nnet = mx.sym.Activation(data=net, act_type=\"relu\")\nnet = mx.sym.Convolution(data=net, kernel=(5, 5), num_filter=64, pad=(2, 2))\nnet = mx.sym.Activation(data=net, act_type=\"relu\")\nnet = mx.sym.Pooling(data=net, pool_type=\"max\", kernel=(3, 3), stride=(2, 2))\n# stage 2\nnet = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=64, pad=(1, 1))\nnet = mx.sym.Activation(data=net, act_type=\"relu\")\nnet = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=64, pad=(1, 1))\nnet = mx.sym.Activation(data=net, act_type=\"relu\")\nnet = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=128, pad=(1, 1))\nnet = mx.sym.Activation(data=net, act_type=\"relu\")\nnet = mx.sym.Pooling(data=net, pool_type=\"max\", kernel=(3, 3), stride=(2, 2))\n# stage 3\nnet = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=256, pad=(1, 1))\nnet = mx.sym.Activation(data=net, act_type=\"relu\")\nnet = mx.sym.Convolution(data=net, kernel=(3, 3), num_filter=256, pad=(1, 1))\nnet = mx.sym.Activation(data=net, act_type=\"relu\")\nnet = mx.sym.Pooling(data=net, pool_type=\"avg\", kernel=(9, 9), stride=(1, 1))\n# stage 4\nnet = mx.sym.Flatten(data=net)\nnet = mx.sym.Dropout(data=net, p=0.25)\nnet = mx.sym.FullyConnected(data=net, num_hidden=121)\nnet = mx.symbol.SoftmaxOutput(data=net, name='softmax')\n\n# Model parameter\n# This model will reduce learning rate by factor 0.1 for every 15 epoch\nmodel = mx.model.FeedForward(\n ctx = dev,\n symbol = net,\n num_epoch = 35,\n learning_rate = 0.01,\n momentum = 0.9,\n wd = 0.0001,\n clip_gradient = 5,\n lr_scheduler = mx.lr_scheduler.FactorScheduler(step=epoch_size * lr_factor_epoch, factor = 0.1),\n initializer = mx.init.Xavier(factor_type=\"in\", magnitude=2.34))\n\n# fit the model\nmodel.fit(\n X = train,\n eval_data = val,\n batch_end_callback = mx.callback.Speedometer(batch_size, 50),\n epoch_end_callback = mx.callback.do_checkpoint(model_prefix))\n\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Vertex():
def __init__(self, key):
self.id = key
self.connections = {}
def add_neighbor(self, nbr, weight=0):
self.connections[nbr] = weight
def get_connections(self):
return self.connections.keys()
def get_id(self):
return self.id
def get_weight(self, nbr):
return self.connections[nbr]
def __str__(self):
connections = str([x.id for x in self.connections])
return f'{str(self.id)} connected to: {connections}'
class Graph():
def __init__(self):
self.vertices = {}
self.num_vertices = 0
def add_vertex(self, key):
new_vertex = Vertex(key)
self.num_vertices += 1
self.vertices[key] = new_vertex
return new_vertex
def get_vertex(self, key):
if key in self.vertices:
return self.vertices[key]
else:
return None
def add_edge(self, origin, dest, weight=0):
if origin not in self.vertices:
self.add_vertex(origin)
if dest not in self.vertices:
self.add_vertex(dest)
self.vertices[origin].add_neighbor(self.vertices[dest], weight)
def get_vertices(self):
return self.vertices.keys()
def __iter__(self):
return iter(self.vertices.values())
def __contains__(self, n):
return n in self.vertices
if __name__ == '__main__':
g = Graph()
for i in range(6):
g.add_vertex(i)
print(g.vertices)
g.add_edge(0, 1, 2)
for vertex in g:
print(vertex)
print(vertex.get_connections)
print('---------------------')
|
normal
|
{
"blob_id": "3af78dcc0bb0b6f253af01d2945ad6ada02ca7a0",
"index": 7270,
"step-1": "class Vertex:\n <mask token>\n <mask token>\n\n def get_connections(self):\n return self.connections.keys()\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Graph:\n\n def __init__(self):\n self.vertices = {}\n self.num_vertices = 0\n\n def add_vertex(self, key):\n new_vertex = Vertex(key)\n self.num_vertices += 1\n self.vertices[key] = new_vertex\n return new_vertex\n\n def get_vertex(self, key):\n if key in self.vertices:\n return self.vertices[key]\n else:\n return None\n\n def add_edge(self, origin, dest, weight=0):\n if origin not in self.vertices:\n self.add_vertex(origin)\n if dest not in self.vertices:\n self.add_vertex(dest)\n self.vertices[origin].add_neighbor(self.vertices[dest], weight)\n\n def get_vertices(self):\n return self.vertices.keys()\n\n def __iter__(self):\n return iter(self.vertices.values())\n\n def __contains__(self, n):\n return n in self.vertices\n\n\n<mask token>\n",
"step-2": "class Vertex:\n\n def __init__(self, key):\n self.id = key\n self.connections = {}\n\n def add_neighbor(self, nbr, weight=0):\n self.connections[nbr] = weight\n\n def get_connections(self):\n return self.connections.keys()\n <mask token>\n <mask token>\n <mask token>\n\n\nclass Graph:\n\n def __init__(self):\n self.vertices = {}\n self.num_vertices = 0\n\n def add_vertex(self, key):\n new_vertex = Vertex(key)\n self.num_vertices += 1\n self.vertices[key] = new_vertex\n return new_vertex\n\n def get_vertex(self, key):\n if key in self.vertices:\n return self.vertices[key]\n else:\n return None\n\n def add_edge(self, origin, dest, weight=0):\n if origin not in self.vertices:\n self.add_vertex(origin)\n if dest not in self.vertices:\n self.add_vertex(dest)\n self.vertices[origin].add_neighbor(self.vertices[dest], weight)\n\n def get_vertices(self):\n return self.vertices.keys()\n\n def __iter__(self):\n return iter(self.vertices.values())\n\n def __contains__(self, n):\n return n in self.vertices\n\n\n<mask token>\n",
"step-3": "class Vertex:\n\n def __init__(self, key):\n self.id = key\n self.connections = {}\n\n def add_neighbor(self, nbr, weight=0):\n self.connections[nbr] = weight\n\n def get_connections(self):\n return self.connections.keys()\n <mask token>\n <mask token>\n\n def __str__(self):\n connections = str([x.id for x in self.connections])\n return f'{str(self.id)} connected to: {connections}'\n\n\nclass Graph:\n\n def __init__(self):\n self.vertices = {}\n self.num_vertices = 0\n\n def add_vertex(self, key):\n new_vertex = Vertex(key)\n self.num_vertices += 1\n self.vertices[key] = new_vertex\n return new_vertex\n\n def get_vertex(self, key):\n if key in self.vertices:\n return self.vertices[key]\n else:\n return None\n\n def add_edge(self, origin, dest, weight=0):\n if origin not in self.vertices:\n self.add_vertex(origin)\n if dest not in self.vertices:\n self.add_vertex(dest)\n self.vertices[origin].add_neighbor(self.vertices[dest], weight)\n\n def get_vertices(self):\n return self.vertices.keys()\n\n def __iter__(self):\n return iter(self.vertices.values())\n\n def __contains__(self, n):\n return n in self.vertices\n\n\n<mask token>\n",
"step-4": "class Vertex:\n\n def __init__(self, key):\n self.id = key\n self.connections = {}\n\n def add_neighbor(self, nbr, weight=0):\n self.connections[nbr] = weight\n\n def get_connections(self):\n return self.connections.keys()\n\n def get_id(self):\n return self.id\n\n def get_weight(self, nbr):\n return self.connections[nbr]\n\n def __str__(self):\n connections = str([x.id for x in self.connections])\n return f'{str(self.id)} connected to: {connections}'\n\n\nclass Graph:\n\n def __init__(self):\n self.vertices = {}\n self.num_vertices = 0\n\n def add_vertex(self, key):\n new_vertex = Vertex(key)\n self.num_vertices += 1\n self.vertices[key] = new_vertex\n return new_vertex\n\n def get_vertex(self, key):\n if key in self.vertices:\n return self.vertices[key]\n else:\n return None\n\n def add_edge(self, origin, dest, weight=0):\n if origin not in self.vertices:\n self.add_vertex(origin)\n if dest not in self.vertices:\n self.add_vertex(dest)\n self.vertices[origin].add_neighbor(self.vertices[dest], weight)\n\n def get_vertices(self):\n return self.vertices.keys()\n\n def __iter__(self):\n return iter(self.vertices.values())\n\n def __contains__(self, n):\n return n in self.vertices\n\n\n<mask token>\n",
"step-5": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nclass Vertex():\n\n def __init__(self, key):\n self.id = key\n self.connections = {}\n\n def add_neighbor(self, nbr, weight=0):\n self.connections[nbr] = weight\n\n def get_connections(self):\n return self.connections.keys()\n\n def get_id(self):\n return self.id\n\n def get_weight(self, nbr):\n return self.connections[nbr]\n\n def __str__(self):\n connections = str([x.id for x in self.connections])\n return f'{str(self.id)} connected to: {connections}'\n\n\nclass Graph():\n\n def __init__(self):\n self.vertices = {}\n self.num_vertices = 0\n\n def add_vertex(self, key):\n new_vertex = Vertex(key)\n self.num_vertices += 1\n self.vertices[key] = new_vertex\n return new_vertex\n\n def get_vertex(self, key):\n if key in self.vertices:\n return self.vertices[key]\n else:\n return None\n\n def add_edge(self, origin, dest, weight=0):\n if origin not in self.vertices:\n self.add_vertex(origin)\n if dest not in self.vertices:\n self.add_vertex(dest)\n\n self.vertices[origin].add_neighbor(self.vertices[dest], weight)\n\n def get_vertices(self):\n return self.vertices.keys()\n\n def __iter__(self):\n return iter(self.vertices.values())\n\n def __contains__(self, n):\n return n in self.vertices\n\n\nif __name__ == '__main__':\n g = Graph()\n for i in range(6):\n g.add_vertex(i)\n print(g.vertices)\n g.add_edge(0, 1, 2)\n for vertex in g:\n print(vertex)\n print(vertex.get_connections)\n print('---------------------')\n",
"step-ids": [
10,
12,
13,
15,
17
]
}
|
[
10,
12,
13,
15,
17
] |
from pytube import YouTube, Playlist
import json
import sys
import os
import urllib.request
p = os.path.abspath('appdata')
def collect(yt, dir):
code = yt.thumbnail_url
urllib.request.urlretrieve(code, os.path.join(dir, yt.title + '.jpg'))
out = yt.streams.filter(only_audio=True, file_extension='mp4').order_by(
'abr').desc().first().download(dir)
def list_update(code):
link = 'https://www.youtube.com/playlist?list=' + code
dir = os.path.join(p, code)
list = Playlist(link)
files = [os.path.splitext(filename)[0] for filename in os.listdir(dir)]
for l in list:
yt = YouTube(l)
if yt.title not in files:
collect(yt, dir)
def add_music(code):
dir = os.path.join(p, 'all')
link = 'https://www.youtube.com/watch?v=' + code
yt = YouTube(link)
collect(yt, os.path.join(p, 'all'))
query = sys.argv[1]
if query == 'addlist':
code = sys.argv[2]
list = os.listdir(p)
if code not in list:
os.mkdir(os.path.join(p, code))
list_update(code)
elif query == 'addmusic':
code = sys.argv[2]
add_music(code)
elif query == 'update':
with open(os.path.abspath('playlists.json'), 'r', encoding='utf-8') as f:
dic = json.load(f)
l = dic['dcodes']
for code in l:
list_update(code)
|
normal
|
{
"blob_id": "06dd963b62c0a746438dcf01c67ef5de1a4c5e8f",
"index": 1558,
"step-1": "<mask token>\n\n\ndef collect(yt, dir):\n code = yt.thumbnail_url\n urllib.request.urlretrieve(code, os.path.join(dir, yt.title + '.jpg'))\n out = yt.streams.filter(only_audio=True, file_extension='mp4').order_by(\n 'abr').desc().first().download(dir)\n\n\ndef list_update(code):\n link = 'https://www.youtube.com/playlist?list=' + code\n dir = os.path.join(p, code)\n list = Playlist(link)\n files = [os.path.splitext(filename)[0] for filename in os.listdir(dir)]\n for l in list:\n yt = YouTube(l)\n if yt.title not in files:\n collect(yt, dir)\n\n\ndef add_music(code):\n dir = os.path.join(p, 'all')\n link = 'https://www.youtube.com/watch?v=' + code\n yt = YouTube(link)\n collect(yt, os.path.join(p, 'all'))\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef collect(yt, dir):\n code = yt.thumbnail_url\n urllib.request.urlretrieve(code, os.path.join(dir, yt.title + '.jpg'))\n out = yt.streams.filter(only_audio=True, file_extension='mp4').order_by(\n 'abr').desc().first().download(dir)\n\n\ndef list_update(code):\n link = 'https://www.youtube.com/playlist?list=' + code\n dir = os.path.join(p, code)\n list = Playlist(link)\n files = [os.path.splitext(filename)[0] for filename in os.listdir(dir)]\n for l in list:\n yt = YouTube(l)\n if yt.title not in files:\n collect(yt, dir)\n\n\ndef add_music(code):\n dir = os.path.join(p, 'all')\n link = 'https://www.youtube.com/watch?v=' + code\n yt = YouTube(link)\n collect(yt, os.path.join(p, 'all'))\n\n\n<mask token>\nif query == 'addlist':\n code = sys.argv[2]\n list = os.listdir(p)\n if code not in list:\n os.mkdir(os.path.join(p, code))\n list_update(code)\nelif query == 'addmusic':\n code = sys.argv[2]\n add_music(code)\nelif query == 'update':\n with open(os.path.abspath('playlists.json'), 'r', encoding='utf-8') as f:\n dic = json.load(f)\n l = dic['dcodes']\n for code in l:\n list_update(code)\n",
"step-3": "<mask token>\np = os.path.abspath('appdata')\n\n\ndef collect(yt, dir):\n code = yt.thumbnail_url\n urllib.request.urlretrieve(code, os.path.join(dir, yt.title + '.jpg'))\n out = yt.streams.filter(only_audio=True, file_extension='mp4').order_by(\n 'abr').desc().first().download(dir)\n\n\ndef list_update(code):\n link = 'https://www.youtube.com/playlist?list=' + code\n dir = os.path.join(p, code)\n list = Playlist(link)\n files = [os.path.splitext(filename)[0] for filename in os.listdir(dir)]\n for l in list:\n yt = YouTube(l)\n if yt.title not in files:\n collect(yt, dir)\n\n\ndef add_music(code):\n dir = os.path.join(p, 'all')\n link = 'https://www.youtube.com/watch?v=' + code\n yt = YouTube(link)\n collect(yt, os.path.join(p, 'all'))\n\n\nquery = sys.argv[1]\nif query == 'addlist':\n code = sys.argv[2]\n list = os.listdir(p)\n if code not in list:\n os.mkdir(os.path.join(p, code))\n list_update(code)\nelif query == 'addmusic':\n code = sys.argv[2]\n add_music(code)\nelif query == 'update':\n with open(os.path.abspath('playlists.json'), 'r', encoding='utf-8') as f:\n dic = json.load(f)\n l = dic['dcodes']\n for code in l:\n list_update(code)\n",
"step-4": "from pytube import YouTube, Playlist\nimport json\nimport sys\nimport os\nimport urllib.request\np = os.path.abspath('appdata')\n\n\ndef collect(yt, dir):\n code = yt.thumbnail_url\n urllib.request.urlretrieve(code, os.path.join(dir, yt.title + '.jpg'))\n out = yt.streams.filter(only_audio=True, file_extension='mp4').order_by(\n 'abr').desc().first().download(dir)\n\n\ndef list_update(code):\n link = 'https://www.youtube.com/playlist?list=' + code\n dir = os.path.join(p, code)\n list = Playlist(link)\n files = [os.path.splitext(filename)[0] for filename in os.listdir(dir)]\n for l in list:\n yt = YouTube(l)\n if yt.title not in files:\n collect(yt, dir)\n\n\ndef add_music(code):\n dir = os.path.join(p, 'all')\n link = 'https://www.youtube.com/watch?v=' + code\n yt = YouTube(link)\n collect(yt, os.path.join(p, 'all'))\n\n\nquery = sys.argv[1]\nif query == 'addlist':\n code = sys.argv[2]\n list = os.listdir(p)\n if code not in list:\n os.mkdir(os.path.join(p, code))\n list_update(code)\nelif query == 'addmusic':\n code = sys.argv[2]\n add_music(code)\nelif query == 'update':\n with open(os.path.abspath('playlists.json'), 'r', encoding='utf-8') as f:\n dic = json.load(f)\n l = dic['dcodes']\n for code in l:\n list_update(code)\n",
"step-5": null,
"step-ids": [
3,
4,
5,
6
]
}
|
[
3,
4,
5,
6
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
sys.path.insert(0, '.')
<|reserved_special_token_1|>
import sys
sys.path.insert(0, '.')
<|reserved_special_token_1|>
import sys
sys.path.insert(0, ".")
|
flexible
|
{
"blob_id": "b95eadd60093d5235dc0989205edff54ef611215",
"index": 2399,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nsys.path.insert(0, '.')\n",
"step-3": "import sys\nsys.path.insert(0, '.')\n",
"step-4": "\nimport sys\n\nsys.path.insert(0, \".\")",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
class CRUD(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE
)
name = models.TextField(blank=True, null=True)
content = models.TextField(blank=True, null=True)
image = models.ImageField(upload_to=upload_updated_image, null=True,
blank=True)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
objects = UpdateManager()
def __str__(self):
return self.name or ''
def serialize(self):
try:
image = self.image.url
except:
image = ''
data = {'user': self.user.id, 'id': self.id, 'name': self.name,
'content': self.content, 'image': image}
return json.dumps(data)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class UpdateQueryset(models.QuerySet):
def serialize(self):
list_value = list(self.values('user', 'id', 'name', 'content', 'image')
)
return json.dumps(list_value)
class UpdateManager(models.Manager):
def get_queryset(self):
return UpdateQueryset(self.model, using=self.db)
class CRUD(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE
)
name = models.TextField(blank=True, null=True)
content = models.TextField(blank=True, null=True)
image = models.ImageField(upload_to=upload_updated_image, null=True,
blank=True)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
objects = UpdateManager()
def __str__(self):
return self.name or ''
def serialize(self):
try:
image = self.image.url
except:
image = ''
data = {'user': self.user.id, 'id': self.id, 'name': self.name,
'content': self.content, 'image': image}
return json.dumps(data)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def upload_updated_image(instance, filename):
return '/MyApi/{user}/{filename}'.format(user=instance.user, filename=
filename)
class UpdateQueryset(models.QuerySet):
def serialize(self):
list_value = list(self.values('user', 'id', 'name', 'content', 'image')
)
return json.dumps(list_value)
class UpdateManager(models.Manager):
def get_queryset(self):
return UpdateQueryset(self.model, using=self.db)
class CRUD(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE
)
name = models.TextField(blank=True, null=True)
content = models.TextField(blank=True, null=True)
image = models.ImageField(upload_to=upload_updated_image, null=True,
blank=True)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
objects = UpdateManager()
def __str__(self):
return self.name or ''
def serialize(self):
try:
image = self.image.url
except:
image = ''
data = {'user': self.user.id, 'id': self.id, 'name': self.name,
'content': self.content, 'image': image}
return json.dumps(data)
<|reserved_special_token_1|>
import json
from django.db import models
from django.conf import settings
from django.core.serializers import serialize
def upload_updated_image(instance, filename):
return '/MyApi/{user}/{filename}'.format(user=instance.user, filename=
filename)
class UpdateQueryset(models.QuerySet):
def serialize(self):
list_value = list(self.values('user', 'id', 'name', 'content', 'image')
)
return json.dumps(list_value)
class UpdateManager(models.Manager):
def get_queryset(self):
return UpdateQueryset(self.model, using=self.db)
class CRUD(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE
)
name = models.TextField(blank=True, null=True)
content = models.TextField(blank=True, null=True)
image = models.ImageField(upload_to=upload_updated_image, null=True,
blank=True)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
objects = UpdateManager()
def __str__(self):
return self.name or ''
def serialize(self):
try:
image = self.image.url
except:
image = ''
data = {'user': self.user.id, 'id': self.id, 'name': self.name,
'content': self.content, 'image': image}
return json.dumps(data)
<|reserved_special_token_1|>
import json
from django.db import models
from django.conf import settings
from django.core.serializers import serialize
# Create your models here.
def upload_updated_image(instance,filename):
return '/MyApi/{user}/{filename}'.format(user=instance.user,filename=filename)
class UpdateQueryset(models.QuerySet):
def serialize(self):
# dot value method
list_value=list(self.values("user","id","name","content","image"))
return json.dumps(list_value)
class UpdateManager(models.Manager):
def get_queryset(self):
return UpdateQueryset(self.model,using=self.db)
class CRUD(models.Model):
user =models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)
name =models.TextField(blank=True,null=True)
content =models.TextField(blank=True,null=True)
image =models.ImageField(upload_to=upload_updated_image,null=True,blank=True)
updated =models.DateTimeField(auto_now=True)
timestamp =models.DateTimeField(auto_now_add=True)
# This is modellistview
objects=UpdateManager()
def __str__(self):
return self.name or ""
#This is for modeldetailview
def serialize(self):
try:
image=self.image.url
except:
image=""
data={
"user":self.user.id,
"id":self.id,
"name":self.name,
"content":self.content,
"image":image
}
return json.dumps(data)
|
flexible
|
{
"blob_id": "5749f30d1a1efd5404654d755bca4515adcf4bca",
"index": 1810,
"step-1": "<mask token>\n\n\nclass CRUD(models.Model):\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE\n )\n name = models.TextField(blank=True, null=True)\n content = models.TextField(blank=True, null=True)\n image = models.ImageField(upload_to=upload_updated_image, null=True,\n blank=True)\n updated = models.DateTimeField(auto_now=True)\n timestamp = models.DateTimeField(auto_now_add=True)\n objects = UpdateManager()\n\n def __str__(self):\n return self.name or ''\n\n def serialize(self):\n try:\n image = self.image.url\n except:\n image = ''\n data = {'user': self.user.id, 'id': self.id, 'name': self.name,\n 'content': self.content, 'image': image}\n return json.dumps(data)\n",
"step-2": "<mask token>\n\n\nclass UpdateQueryset(models.QuerySet):\n\n def serialize(self):\n list_value = list(self.values('user', 'id', 'name', 'content', 'image')\n )\n return json.dumps(list_value)\n\n\nclass UpdateManager(models.Manager):\n\n def get_queryset(self):\n return UpdateQueryset(self.model, using=self.db)\n\n\nclass CRUD(models.Model):\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE\n )\n name = models.TextField(blank=True, null=True)\n content = models.TextField(blank=True, null=True)\n image = models.ImageField(upload_to=upload_updated_image, null=True,\n blank=True)\n updated = models.DateTimeField(auto_now=True)\n timestamp = models.DateTimeField(auto_now_add=True)\n objects = UpdateManager()\n\n def __str__(self):\n return self.name or ''\n\n def serialize(self):\n try:\n image = self.image.url\n except:\n image = ''\n data = {'user': self.user.id, 'id': self.id, 'name': self.name,\n 'content': self.content, 'image': image}\n return json.dumps(data)\n",
"step-3": "<mask token>\n\n\ndef upload_updated_image(instance, filename):\n return '/MyApi/{user}/{filename}'.format(user=instance.user, filename=\n filename)\n\n\nclass UpdateQueryset(models.QuerySet):\n\n def serialize(self):\n list_value = list(self.values('user', 'id', 'name', 'content', 'image')\n )\n return json.dumps(list_value)\n\n\nclass UpdateManager(models.Manager):\n\n def get_queryset(self):\n return UpdateQueryset(self.model, using=self.db)\n\n\nclass CRUD(models.Model):\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE\n )\n name = models.TextField(blank=True, null=True)\n content = models.TextField(blank=True, null=True)\n image = models.ImageField(upload_to=upload_updated_image, null=True,\n blank=True)\n updated = models.DateTimeField(auto_now=True)\n timestamp = models.DateTimeField(auto_now_add=True)\n objects = UpdateManager()\n\n def __str__(self):\n return self.name or ''\n\n def serialize(self):\n try:\n image = self.image.url\n except:\n image = ''\n data = {'user': self.user.id, 'id': self.id, 'name': self.name,\n 'content': self.content, 'image': image}\n return json.dumps(data)\n",
"step-4": "import json\nfrom django.db import models\nfrom django.conf import settings\nfrom django.core.serializers import serialize\n\n\ndef upload_updated_image(instance, filename):\n return '/MyApi/{user}/{filename}'.format(user=instance.user, filename=\n filename)\n\n\nclass UpdateQueryset(models.QuerySet):\n\n def serialize(self):\n list_value = list(self.values('user', 'id', 'name', 'content', 'image')\n )\n return json.dumps(list_value)\n\n\nclass UpdateManager(models.Manager):\n\n def get_queryset(self):\n return UpdateQueryset(self.model, using=self.db)\n\n\nclass CRUD(models.Model):\n user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE\n )\n name = models.TextField(blank=True, null=True)\n content = models.TextField(blank=True, null=True)\n image = models.ImageField(upload_to=upload_updated_image, null=True,\n blank=True)\n updated = models.DateTimeField(auto_now=True)\n timestamp = models.DateTimeField(auto_now_add=True)\n objects = UpdateManager()\n\n def __str__(self):\n return self.name or ''\n\n def serialize(self):\n try:\n image = self.image.url\n except:\n image = ''\n data = {'user': self.user.id, 'id': self.id, 'name': self.name,\n 'content': self.content, 'image': image}\n return json.dumps(data)\n",
"step-5": "import json\nfrom django.db import models\nfrom django.conf import settings\nfrom django.core.serializers import serialize\n\n# Create your models here.\n\ndef upload_updated_image(instance,filename):\n return '/MyApi/{user}/{filename}'.format(user=instance.user,filename=filename)\n\nclass UpdateQueryset(models.QuerySet):\n def serialize(self):\n # dot value method\n list_value=list(self.values(\"user\",\"id\",\"name\",\"content\",\"image\")) \n return json.dumps(list_value)\n\nclass UpdateManager(models.Manager):\n def get_queryset(self):\n return UpdateQueryset(self.model,using=self.db)\n\nclass CRUD(models.Model):\n user =models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE)\n name =models.TextField(blank=True,null=True)\n content =models.TextField(blank=True,null=True)\n image =models.ImageField(upload_to=upload_updated_image,null=True,blank=True)\n updated =models.DateTimeField(auto_now=True)\n timestamp =models.DateTimeField(auto_now_add=True)\n \n # This is modellistview\n objects=UpdateManager()\n\n def __str__(self):\n return self.name or \"\"\n\n \n #This is for modeldetailview\n def serialize(self):\n try:\n image=self.image.url\n except:\n image=\"\"\n data={\n \"user\":self.user.id,\n \"id\":self.id,\n \"name\":self.name,\n \"content\":self.content,\n \"image\":image\n }\n\n return json.dumps(data)\n",
"step-ids": [
4,
8,
9,
10,
11
]
}
|
[
4,
8,
9,
10,
11
] |
import wizard
import report
|
normal
|
{
"blob_id": "9d07fd14825ed1e0210fa1f404939f68a3bb039c",
"index": 4762,
"step-1": "<mask token>\n",
"step-2": "import wizard\nimport report\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
}
|
[
0,
1
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Plugin_OBJ:
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Plugin_OBJ:
def __init__(self, fhdhr, plugin_utils):
self.fhdhr = fhdhr
self.plugin_utils = plugin_utils
self.plutotv_html = PlutoTV_HTML(fhdhr, plugin_utils)
<|reserved_special_token_1|>
from .plutotv_html import PlutoTV_HTML
class Plugin_OBJ:
def __init__(self, fhdhr, plugin_utils):
self.fhdhr = fhdhr
self.plugin_utils = plugin_utils
self.plutotv_html = PlutoTV_HTML(fhdhr, plugin_utils)
<|reserved_special_token_1|>
from .plutotv_html import PlutoTV_HTML
class Plugin_OBJ():
def __init__(self, fhdhr, plugin_utils):
self.fhdhr = fhdhr
self.plugin_utils = plugin_utils
self.plutotv_html = PlutoTV_HTML(fhdhr, plugin_utils)
|
flexible
|
{
"blob_id": "ee0cf2325c94821fa9f5115e8848c71143eabdbf",
"index": 4775,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Plugin_OBJ:\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Plugin_OBJ:\n\n def __init__(self, fhdhr, plugin_utils):\n self.fhdhr = fhdhr\n self.plugin_utils = plugin_utils\n self.plutotv_html = PlutoTV_HTML(fhdhr, plugin_utils)\n",
"step-4": "from .plutotv_html import PlutoTV_HTML\n\n\nclass Plugin_OBJ:\n\n def __init__(self, fhdhr, plugin_utils):\n self.fhdhr = fhdhr\n self.plugin_utils = plugin_utils\n self.plutotv_html = PlutoTV_HTML(fhdhr, plugin_utils)\n",
"step-5": "\nfrom .plutotv_html import PlutoTV_HTML\n\n\nclass Plugin_OBJ():\n\n def __init__(self, fhdhr, plugin_utils):\n self.fhdhr = fhdhr\n self.plugin_utils = plugin_utils\n\n self.plutotv_html = PlutoTV_HTML(fhdhr, plugin_utils)\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import numpy as np
import matplotlib.pyplot as plt
import sys
import os
from azavg_util import plot_azav
from binormalized_cbar import MidpointNormalize
from diagnostic_reading import ReferenceState
dirname = sys.argv[1]
datadir = dirname + '/data/'
plotdir = dirname + '/plots/'
if (not os.path.isdir(plotdir)):
os.makedirs(plotdir)
ref = ReferenceState(dirname + '/reference', '')
H_rho = -1./ref.dlnrho
# Get grid info
rr,tt,cost,sint,rr_depth,ri,ro,d = np.load(datadir + 'grid_info.npy')
nr, nt = len(rr), len(tt)
H_rho_2d = H_rho.reshape((1, nr))
vr2_p,vt2_p,vp2_p,vrvp_p,vrvt_p,vtvp_p,\
vr2_m,vt2_m,vp2_m, vrvp_m, vrvt_m, vtvp_m, fplus, fminus\
= np.load(datadir + 'rs_raw.npy')
vrvp_t = vrvp_m + vrvp_p
vrvt_t = vrvt_m + vrvt_p
vtvp_t = vtvp_m + vtvp_p
vr2_t = vr2_m + vr2_p
vt2_t = vt2_m + vt2_p
vp2_t = vp2_m + vp2_p
# Total velocity
v2_p = vr2_p + vt2_p + vp2_p
v2_m = vr2_m + vt2_p + vp2_m
v2_t = vr2_t + vt2_p + vp2_t
Om = 7.8e-6
ro_p = np.sqrt(v2_p)/(2*Om*H_rho_2d)
ro_m = np.sqrt(v2_m)/(2*Om*H_rho_2d)
ro_t = np.sqrt(v2_t)/(2*Om*H_rho_2d)
# Plot radial angular momentum transport
fig, ax = plt.subplots()
plot_azav(fig, ax, ro_m, rr, cost, sint,
contours=False, notfloat=False, units='')
plt.title(r'$({\rm{Ro}}_{\rm{c}})_+$',fontsize=16)
plt.tight_layout()
plt.show()
plt.savefig(plotdir + 'rossby_mer_p.png')
plt.close()
|
normal
|
{
"blob_id": "e5c30488c8c1682171c57a11a8ecedc5ccd4d851",
"index": 5607,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif not os.path.isdir(plotdir):\n os.makedirs(plotdir)\n<mask token>\nplot_azav(fig, ax, ro_m, rr, cost, sint, contours=False, notfloat=False,\n units='')\nplt.title('$({\\\\rm{Ro}}_{\\\\rm{c}})_+$', fontsize=16)\nplt.tight_layout()\nplt.show()\nplt.savefig(plotdir + 'rossby_mer_p.png')\nplt.close()\n",
"step-3": "<mask token>\ndirname = sys.argv[1]\ndatadir = dirname + '/data/'\nplotdir = dirname + '/plots/'\nif not os.path.isdir(plotdir):\n os.makedirs(plotdir)\nref = ReferenceState(dirname + '/reference', '')\nH_rho = -1.0 / ref.dlnrho\nrr, tt, cost, sint, rr_depth, ri, ro, d = np.load(datadir + 'grid_info.npy')\nnr, nt = len(rr), len(tt)\nH_rho_2d = H_rho.reshape((1, nr))\n(vr2_p, vt2_p, vp2_p, vrvp_p, vrvt_p, vtvp_p, vr2_m, vt2_m, vp2_m, vrvp_m,\n vrvt_m, vtvp_m, fplus, fminus) = np.load(datadir + 'rs_raw.npy')\nvrvp_t = vrvp_m + vrvp_p\nvrvt_t = vrvt_m + vrvt_p\nvtvp_t = vtvp_m + vtvp_p\nvr2_t = vr2_m + vr2_p\nvt2_t = vt2_m + vt2_p\nvp2_t = vp2_m + vp2_p\nv2_p = vr2_p + vt2_p + vp2_p\nv2_m = vr2_m + vt2_p + vp2_m\nv2_t = vr2_t + vt2_p + vp2_t\nOm = 7.8e-06\nro_p = np.sqrt(v2_p) / (2 * Om * H_rho_2d)\nro_m = np.sqrt(v2_m) / (2 * Om * H_rho_2d)\nro_t = np.sqrt(v2_t) / (2 * Om * H_rho_2d)\nfig, ax = plt.subplots()\nplot_azav(fig, ax, ro_m, rr, cost, sint, contours=False, notfloat=False,\n units='')\nplt.title('$({\\\\rm{Ro}}_{\\\\rm{c}})_+$', fontsize=16)\nplt.tight_layout()\nplt.show()\nplt.savefig(plotdir + 'rossby_mer_p.png')\nplt.close()\n",
"step-4": "import numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nimport os\nfrom azavg_util import plot_azav\nfrom binormalized_cbar import MidpointNormalize\nfrom diagnostic_reading import ReferenceState\ndirname = sys.argv[1]\ndatadir = dirname + '/data/'\nplotdir = dirname + '/plots/'\nif not os.path.isdir(plotdir):\n os.makedirs(plotdir)\nref = ReferenceState(dirname + '/reference', '')\nH_rho = -1.0 / ref.dlnrho\nrr, tt, cost, sint, rr_depth, ri, ro, d = np.load(datadir + 'grid_info.npy')\nnr, nt = len(rr), len(tt)\nH_rho_2d = H_rho.reshape((1, nr))\n(vr2_p, vt2_p, vp2_p, vrvp_p, vrvt_p, vtvp_p, vr2_m, vt2_m, vp2_m, vrvp_m,\n vrvt_m, vtvp_m, fplus, fminus) = np.load(datadir + 'rs_raw.npy')\nvrvp_t = vrvp_m + vrvp_p\nvrvt_t = vrvt_m + vrvt_p\nvtvp_t = vtvp_m + vtvp_p\nvr2_t = vr2_m + vr2_p\nvt2_t = vt2_m + vt2_p\nvp2_t = vp2_m + vp2_p\nv2_p = vr2_p + vt2_p + vp2_p\nv2_m = vr2_m + vt2_p + vp2_m\nv2_t = vr2_t + vt2_p + vp2_t\nOm = 7.8e-06\nro_p = np.sqrt(v2_p) / (2 * Om * H_rho_2d)\nro_m = np.sqrt(v2_m) / (2 * Om * H_rho_2d)\nro_t = np.sqrt(v2_t) / (2 * Om * H_rho_2d)\nfig, ax = plt.subplots()\nplot_azav(fig, ax, ro_m, rr, cost, sint, contours=False, notfloat=False,\n units='')\nplt.title('$({\\\\rm{Ro}}_{\\\\rm{c}})_+$', fontsize=16)\nplt.tight_layout()\nplt.show()\nplt.savefig(plotdir + 'rossby_mer_p.png')\nplt.close()\n",
"step-5": "import numpy as np\nimport matplotlib.pyplot as plt\nimport sys\nimport os\nfrom azavg_util import plot_azav\nfrom binormalized_cbar import MidpointNormalize\nfrom diagnostic_reading import ReferenceState\n\ndirname = sys.argv[1]\n\ndatadir = dirname + '/data/'\nplotdir = dirname + '/plots/'\n\nif (not os.path.isdir(plotdir)):\n os.makedirs(plotdir)\n\nref = ReferenceState(dirname + '/reference', '')\nH_rho = -1./ref.dlnrho\n\n# Get grid info\nrr,tt,cost,sint,rr_depth,ri,ro,d = np.load(datadir + 'grid_info.npy')\nnr, nt = len(rr), len(tt)\n\nH_rho_2d = H_rho.reshape((1, nr)) \n\nvr2_p,vt2_p,vp2_p,vrvp_p,vrvt_p,vtvp_p,\\\n vr2_m,vt2_m,vp2_m, vrvp_m, vrvt_m, vtvp_m, fplus, fminus\\\n = np.load(datadir + 'rs_raw.npy') \n\nvrvp_t = vrvp_m + vrvp_p\nvrvt_t = vrvt_m + vrvt_p\nvtvp_t = vtvp_m + vtvp_p\n\nvr2_t = vr2_m + vr2_p\nvt2_t = vt2_m + vt2_p\nvp2_t = vp2_m + vp2_p\n\n# Total velocity\nv2_p = vr2_p + vt2_p + vp2_p\nv2_m = vr2_m + vt2_p + vp2_m\nv2_t = vr2_t + vt2_p + vp2_t\n\nOm = 7.8e-6\nro_p = np.sqrt(v2_p)/(2*Om*H_rho_2d)\nro_m = np.sqrt(v2_m)/(2*Om*H_rho_2d)\nro_t = np.sqrt(v2_t)/(2*Om*H_rho_2d)\n\n# Plot radial angular momentum transport\n\nfig, ax = plt.subplots()\nplot_azav(fig, ax, ro_m, rr, cost, sint,\n contours=False, notfloat=False, units='')\nplt.title(r'$({\\rm{Ro}}_{\\rm{c}})_+$',fontsize=16)\nplt.tight_layout()\nplt.show()\nplt.savefig(plotdir + 'rossby_mer_p.png')\nplt.close()\n\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
from import_.Import import Import
from classifier.Classifier import Classifier
from export.Export import Export
from preprocessing.PreProcess import PreProcess
def main():
date_column = "date of last vet visit"
target = "age at death"
export_file_dir = "./output/"
export_model_dir = "./model/xgb_model.dat"
# IMPORT
import_ = Import()
print("""
To predict how long cats will live (in years) please enter the file path
for the cats csv file for example: ./input/cats_pred.csv
""")
cats = import_.import_df("predict")
cats_copy = cats.copy()
# PRE-PROCESSING
pre_process = PreProcess()
print("Pre-processing Imported Data..")
# process date to keep year only
print("Processing date column to keep year only")
pre_process.strip_year(cats, date_column)
# Storing numerical columns in the background
pre_process.get_numerical_cols(cats)
# Convert all columns to float data type
print("Convert all columns to float data type")
pre_process.convert_to_float(cats)
# Replace NaN values with Median
print("Replacing all NaN values with median")
cats = pre_process.replace_nan(cats)
# Normalise dataset
print("Normalising dataset")
cats = pre_process.normalise(cats)
print("""
Cats dataset
{0}
""".format(cats.head()))
# PREDICTION
print("Prediction Starting")
cats_pred = Classifier.predict(export_model_dir, cats)
# EXPORTING
print("Prediction Finished")
Export.export_pred_file(cats_copy, cats_pred, target, export_file_dir)
if __name__ == "__main__":
main()
|
normal
|
{
"blob_id": "696b9db78cc7f6002eb39b640e0e5b2b53e52e91",
"index": 8448,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef main():\n date_column = 'date of last vet visit'\n target = 'age at death'\n export_file_dir = './output/'\n export_model_dir = './model/xgb_model.dat'\n import_ = Import()\n print(\n \"\"\"\nTo predict how long cats will live (in years) please enter the file path\nfor the cats csv file for example: ./input/cats_pred.csv\n \"\"\"\n )\n cats = import_.import_df('predict')\n cats_copy = cats.copy()\n pre_process = PreProcess()\n print('Pre-processing Imported Data..')\n print('Processing date column to keep year only')\n pre_process.strip_year(cats, date_column)\n pre_process.get_numerical_cols(cats)\n print('Convert all columns to float data type')\n pre_process.convert_to_float(cats)\n print('Replacing all NaN values with median')\n cats = pre_process.replace_nan(cats)\n print('Normalising dataset')\n cats = pre_process.normalise(cats)\n print(\"\"\"\n Cats dataset \n {0} \n \"\"\".format(cats.head()))\n print('Prediction Starting')\n cats_pred = Classifier.predict(export_model_dir, cats)\n print('Prediction Finished')\n Export.export_pred_file(cats_copy, cats_pred, target, export_file_dir)\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef main():\n date_column = 'date of last vet visit'\n target = 'age at death'\n export_file_dir = './output/'\n export_model_dir = './model/xgb_model.dat'\n import_ = Import()\n print(\n \"\"\"\nTo predict how long cats will live (in years) please enter the file path\nfor the cats csv file for example: ./input/cats_pred.csv\n \"\"\"\n )\n cats = import_.import_df('predict')\n cats_copy = cats.copy()\n pre_process = PreProcess()\n print('Pre-processing Imported Data..')\n print('Processing date column to keep year only')\n pre_process.strip_year(cats, date_column)\n pre_process.get_numerical_cols(cats)\n print('Convert all columns to float data type')\n pre_process.convert_to_float(cats)\n print('Replacing all NaN values with median')\n cats = pre_process.replace_nan(cats)\n print('Normalising dataset')\n cats = pre_process.normalise(cats)\n print(\"\"\"\n Cats dataset \n {0} \n \"\"\".format(cats.head()))\n print('Prediction Starting')\n cats_pred = Classifier.predict(export_model_dir, cats)\n print('Prediction Finished')\n Export.export_pred_file(cats_copy, cats_pred, target, export_file_dir)\n\n\nif __name__ == '__main__':\n main()\n",
"step-4": "from import_.Import import Import\nfrom classifier.Classifier import Classifier\nfrom export.Export import Export\nfrom preprocessing.PreProcess import PreProcess\n\n\ndef main():\n date_column = 'date of last vet visit'\n target = 'age at death'\n export_file_dir = './output/'\n export_model_dir = './model/xgb_model.dat'\n import_ = Import()\n print(\n \"\"\"\nTo predict how long cats will live (in years) please enter the file path\nfor the cats csv file for example: ./input/cats_pred.csv\n \"\"\"\n )\n cats = import_.import_df('predict')\n cats_copy = cats.copy()\n pre_process = PreProcess()\n print('Pre-processing Imported Data..')\n print('Processing date column to keep year only')\n pre_process.strip_year(cats, date_column)\n pre_process.get_numerical_cols(cats)\n print('Convert all columns to float data type')\n pre_process.convert_to_float(cats)\n print('Replacing all NaN values with median')\n cats = pre_process.replace_nan(cats)\n print('Normalising dataset')\n cats = pre_process.normalise(cats)\n print(\"\"\"\n Cats dataset \n {0} \n \"\"\".format(cats.head()))\n print('Prediction Starting')\n cats_pred = Classifier.predict(export_model_dir, cats)\n print('Prediction Finished')\n Export.export_pred_file(cats_copy, cats_pred, target, export_file_dir)\n\n\nif __name__ == '__main__':\n main()\n",
"step-5": "from import_.Import import Import\nfrom classifier.Classifier import Classifier\nfrom export.Export import Export\nfrom preprocessing.PreProcess import PreProcess\n\n\ndef main():\n\n date_column = \"date of last vet visit\"\n target = \"age at death\"\n export_file_dir = \"./output/\"\n export_model_dir = \"./model/xgb_model.dat\"\n\n # IMPORT\n import_ = Import()\n print(\"\"\"\nTo predict how long cats will live (in years) please enter the file path\nfor the cats csv file for example: ./input/cats_pred.csv\n \"\"\")\n cats = import_.import_df(\"predict\")\n cats_copy = cats.copy()\n\n # PRE-PROCESSING\n pre_process = PreProcess()\n print(\"Pre-processing Imported Data..\")\n\n # process date to keep year only\n print(\"Processing date column to keep year only\")\n pre_process.strip_year(cats, date_column)\n\n # Storing numerical columns in the background\n pre_process.get_numerical_cols(cats)\n\n # Convert all columns to float data type\n print(\"Convert all columns to float data type\")\n pre_process.convert_to_float(cats)\n\n # Replace NaN values with Median\n print(\"Replacing all NaN values with median\")\n cats = pre_process.replace_nan(cats)\n\n # Normalise dataset\n print(\"Normalising dataset\")\n cats = pre_process.normalise(cats)\n print(\"\"\"\n Cats dataset \n {0} \n \"\"\".format(cats.head()))\n\n # PREDICTION\n print(\"Prediction Starting\")\n cats_pred = Classifier.predict(export_model_dir, cats)\n\n # EXPORTING\n print(\"Prediction Finished\")\n Export.export_pred_file(cats_copy, cats_pred, target, export_file_dir)\n\n\nif __name__ == \"__main__\":\n main()\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
from microbit import *
import radio
radio.on()
# receiver will show the distance to the beacon
# the number of receivers should be easily adjustable
while True:
message=radio.receive_full()
# the stronger the signal the higher the number
if message:
strength = message[1]+100
displaystrength = (int((strength/10)+1))
display.show(str(displaystrength))
sleep(200)
# if beacon is too far, also usable as a sixth level of light intensity
else:
display.show(Image.NO)
|
normal
|
{
"blob_id": "dffa5e2f34788c6f5a5ccc7d8375317a830288b5",
"index": 7994,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nradio.on()\nwhile True:\n message = radio.receive_full()\n if message:\n strength = message[1] + 100\n displaystrength = int(strength / 10 + 1)\n display.show(str(displaystrength))\n sleep(200)\n else:\n display.show(Image.NO)\n",
"step-3": "from microbit import *\nimport radio\nradio.on()\nwhile True:\n message = radio.receive_full()\n if message:\n strength = message[1] + 100\n displaystrength = int(strength / 10 + 1)\n display.show(str(displaystrength))\n sleep(200)\n else:\n display.show(Image.NO)\n",
"step-4": "from microbit import *\nimport radio\nradio.on()\n\n# receiver will show the distance to the beacon\n# the number of receivers should be easily adjustable\nwhile True:\n message=radio.receive_full()\n # the stronger the signal the higher the number\n if message:\n strength = message[1]+100\n displaystrength = (int((strength/10)+1))\n display.show(str(displaystrength))\n sleep(200)\n # if beacon is too far, also usable as a sixth level of light intensity\n else:\n display.show(Image.NO)",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
from prediction_model import PredictionModel
import util.nlp as nlp
import re
class NLPPredictionModel(object):
def getPasswordProbabilities(self, sweetwordList):
# can not deal with sweetword that contains no letters
result = []
for s in sweetwordList:
words = re.findall(r"[a-zA-Z']+", s)
if not words:
result.append(0.0)
else:
result.append(sum([nlp.getScore(w) for w in words]) / float(len(words)))
sum_result = sum(result)
return [r / float(sum_result) for r in result]
|
normal
|
{
"blob_id": "1c01fbf7eafd49ada71cb018a62ead5988dcf251",
"index": 2968,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass NLPPredictionModel(object):\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass NLPPredictionModel(object):\n\n def getPasswordProbabilities(self, sweetwordList):\n result = []\n for s in sweetwordList:\n words = re.findall(\"[a-zA-Z']+\", s)\n if not words:\n result.append(0.0)\n else:\n result.append(sum([nlp.getScore(w) for w in words]) / float\n (len(words)))\n sum_result = sum(result)\n return [(r / float(sum_result)) for r in result]\n",
"step-4": "from prediction_model import PredictionModel\nimport util.nlp as nlp\nimport re\n\n\nclass NLPPredictionModel(object):\n\n def getPasswordProbabilities(self, sweetwordList):\n result = []\n for s in sweetwordList:\n words = re.findall(\"[a-zA-Z']+\", s)\n if not words:\n result.append(0.0)\n else:\n result.append(sum([nlp.getScore(w) for w in words]) / float\n (len(words)))\n sum_result = sum(result)\n return [(r / float(sum_result)) for r in result]\n",
"step-5": "from prediction_model import PredictionModel\nimport util.nlp as nlp\nimport re\n\n\nclass NLPPredictionModel(object):\n\n def getPasswordProbabilities(self, sweetwordList):\n # can not deal with sweetword that contains no letters\n\n result = []\n for s in sweetwordList:\n words = re.findall(r\"[a-zA-Z']+\", s)\n if not words:\n result.append(0.0)\n else:\n result.append(sum([nlp.getScore(w) for w in words]) / float(len(words)))\n sum_result = sum(result)\n return [r / float(sum_result) for r in result]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 18 13:39:05 2017
@author: jaredhaeme15
"""
import cv2
import numpy as np
from collections import deque
import imutils
import misc_image_tools
frameFileName = r"H:\Summer Research 2017\Whirligig Beetle pictures and videos\large1.mp4"
cap = cv2.VideoCapture(r"H:\Summer Research 2017\Whirligig Beetle pictures and videos\large1.mp4")
while(1):
successFlag, frame = cap.read()
if not successFlag:
cv2.waitKey(0)
break
lower_hsv_thresholdcr = np.array([0,250,250])
upper_hsv_thresholdcr = np.array([10,255,255])
gray = np.float32(cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY))
dst = cv2.cornerHarris(gray,2,3,0.04)
#result is dilated for marking the corners, not important
dst = cv2.dilate(dst,None)
frameWithRedCorners = np.copy(frame)
# Threshold for an optimal value, it may vary depending on the image.
frameWithRedCorners[dst>0.005*dst.max()]=[0,0,255]
hsv = cv2.cvtColor(frameWithRedCorners, cv2.COLOR_BGR2HSV)
#construct a mask for the color "green", then perform
# a series of dilations and erosions to remove any small
# blobs left in the mask
crmask = cv2.inRange(hsv, lower_hsv_thresholdcr, upper_hsv_thresholdcr)
cntscr = cv2.findContours(crmask.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)[-2]
cv2.imshow("Frame", frameWithRedCorners)
k = cv2.waitKey(10000) & 0xFF
if k == 27: # esc key
break
cv2.destroyAllWindows()
cap.release()
|
normal
|
{
"blob_id": "5ccfad17ede9f685ea9ef9c514c0108a61c2dfd6",
"index": 8699,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nwhile 1:\n successFlag, frame = cap.read()\n if not successFlag:\n cv2.waitKey(0)\n break\n lower_hsv_thresholdcr = np.array([0, 250, 250])\n upper_hsv_thresholdcr = np.array([10, 255, 255])\n gray = np.float32(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY))\n dst = cv2.cornerHarris(gray, 2, 3, 0.04)\n dst = cv2.dilate(dst, None)\n frameWithRedCorners = np.copy(frame)\n frameWithRedCorners[dst > 0.005 * dst.max()] = [0, 0, 255]\n hsv = cv2.cvtColor(frameWithRedCorners, cv2.COLOR_BGR2HSV)\n crmask = cv2.inRange(hsv, lower_hsv_thresholdcr, upper_hsv_thresholdcr)\n cntscr = cv2.findContours(crmask.copy(), cv2.RETR_EXTERNAL, cv2.\n CHAIN_APPROX_SIMPLE)[-2]\n cv2.imshow('Frame', frameWithRedCorners)\n k = cv2.waitKey(10000) & 255\n if k == 27:\n break\ncv2.destroyAllWindows()\ncap.release()\n",
"step-3": "<mask token>\nframeFileName = (\n 'H:\\\\Summer Research 2017\\\\Whirligig Beetle pictures and videos\\\\large1.mp4'\n )\ncap = cv2.VideoCapture(\n 'H:\\\\Summer Research 2017\\\\Whirligig Beetle pictures and videos\\\\large1.mp4'\n )\nwhile 1:\n successFlag, frame = cap.read()\n if not successFlag:\n cv2.waitKey(0)\n break\n lower_hsv_thresholdcr = np.array([0, 250, 250])\n upper_hsv_thresholdcr = np.array([10, 255, 255])\n gray = np.float32(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY))\n dst = cv2.cornerHarris(gray, 2, 3, 0.04)\n dst = cv2.dilate(dst, None)\n frameWithRedCorners = np.copy(frame)\n frameWithRedCorners[dst > 0.005 * dst.max()] = [0, 0, 255]\n hsv = cv2.cvtColor(frameWithRedCorners, cv2.COLOR_BGR2HSV)\n crmask = cv2.inRange(hsv, lower_hsv_thresholdcr, upper_hsv_thresholdcr)\n cntscr = cv2.findContours(crmask.copy(), cv2.RETR_EXTERNAL, cv2.\n CHAIN_APPROX_SIMPLE)[-2]\n cv2.imshow('Frame', frameWithRedCorners)\n k = cv2.waitKey(10000) & 255\n if k == 27:\n break\ncv2.destroyAllWindows()\ncap.release()\n",
"step-4": "<mask token>\nimport cv2\nimport numpy as np\nfrom collections import deque\nimport imutils\nimport misc_image_tools\nframeFileName = (\n 'H:\\\\Summer Research 2017\\\\Whirligig Beetle pictures and videos\\\\large1.mp4'\n )\ncap = cv2.VideoCapture(\n 'H:\\\\Summer Research 2017\\\\Whirligig Beetle pictures and videos\\\\large1.mp4'\n )\nwhile 1:\n successFlag, frame = cap.read()\n if not successFlag:\n cv2.waitKey(0)\n break\n lower_hsv_thresholdcr = np.array([0, 250, 250])\n upper_hsv_thresholdcr = np.array([10, 255, 255])\n gray = np.float32(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY))\n dst = cv2.cornerHarris(gray, 2, 3, 0.04)\n dst = cv2.dilate(dst, None)\n frameWithRedCorners = np.copy(frame)\n frameWithRedCorners[dst > 0.005 * dst.max()] = [0, 0, 255]\n hsv = cv2.cvtColor(frameWithRedCorners, cv2.COLOR_BGR2HSV)\n crmask = cv2.inRange(hsv, lower_hsv_thresholdcr, upper_hsv_thresholdcr)\n cntscr = cv2.findContours(crmask.copy(), cv2.RETR_EXTERNAL, cv2.\n CHAIN_APPROX_SIMPLE)[-2]\n cv2.imshow('Frame', frameWithRedCorners)\n k = cv2.waitKey(10000) & 255\n if k == 27:\n break\ncv2.destroyAllWindows()\ncap.release()\n",
"step-5": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jul 18 13:39:05 2017\n\n@author: jaredhaeme15\n\"\"\"\n\n\nimport cv2\nimport numpy as np\nfrom collections import deque\nimport imutils\nimport misc_image_tools \n\nframeFileName = r\"H:\\Summer Research 2017\\Whirligig Beetle pictures and videos\\large1.mp4\"\ncap = cv2.VideoCapture(r\"H:\\Summer Research 2017\\Whirligig Beetle pictures and videos\\large1.mp4\")\n \nwhile(1): \n \n successFlag, frame = cap.read()\n if not successFlag:\n cv2.waitKey(0)\n break \n lower_hsv_thresholdcr = np.array([0,250,250])\n upper_hsv_thresholdcr = np.array([10,255,255])\n gray = np.float32(cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY))\n dst = cv2.cornerHarris(gray,2,3,0.04)\n #result is dilated for marking the corners, not important\n dst = cv2.dilate(dst,None)\n frameWithRedCorners = np.copy(frame)\n # Threshold for an optimal value, it may vary depending on the image.\n frameWithRedCorners[dst>0.005*dst.max()]=[0,0,255]\n hsv = cv2.cvtColor(frameWithRedCorners, cv2.COLOR_BGR2HSV)\n #construct a mask for the color \"green\", then perform\n # a series of dilations and erosions to remove any small\n # blobs left in the mask\n crmask = cv2.inRange(hsv, lower_hsv_thresholdcr, upper_hsv_thresholdcr)\n cntscr = cv2.findContours(crmask.copy(), cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_SIMPLE)[-2]\n cv2.imshow(\"Frame\", frameWithRedCorners)\n k = cv2.waitKey(10000) & 0xFF\n if k == 27: # esc key\n break\ncv2.destroyAllWindows()\ncap.release()",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
COPY_GOOGLE_DOC_KEY = '1CdafeVmmtNa_PMV99TapPHvLUVzYz0xkvHcpINQtQ6c'
DEPLOY_SLUG = 'al-qassemi'
NUM_SLIDES_AFTER_CONTENT = 2
AUDIO = True
VIDEO = False
FILMSTRIP = False
PROGRESS_BAR = False
<|reserved_special_token_1|>
COPY_GOOGLE_DOC_KEY = '1CdafeVmmtNa_PMV99TapPHvLUVzYz0xkvHcpINQtQ6c'
DEPLOY_SLUG = 'al-qassemi'
NUM_SLIDES_AFTER_CONTENT = 2
# Configuration
AUDIO = True
VIDEO = False
FILMSTRIP = False
PROGRESS_BAR = False
|
flexible
|
{
"blob_id": "f398b724fc28bc25ddb8baf492f34075db0c1f61",
"index": 7703,
"step-1": "<mask token>\n",
"step-2": "COPY_GOOGLE_DOC_KEY = '1CdafeVmmtNa_PMV99TapPHvLUVzYz0xkvHcpINQtQ6c'\nDEPLOY_SLUG = 'al-qassemi'\nNUM_SLIDES_AFTER_CONTENT = 2\nAUDIO = True\nVIDEO = False\nFILMSTRIP = False\nPROGRESS_BAR = False\n",
"step-3": "COPY_GOOGLE_DOC_KEY = '1CdafeVmmtNa_PMV99TapPHvLUVzYz0xkvHcpINQtQ6c'\nDEPLOY_SLUG = 'al-qassemi'\nNUM_SLIDES_AFTER_CONTENT = 2\n\n# Configuration\nAUDIO = True\nVIDEO = False\nFILMSTRIP = False\nPROGRESS_BAR = False",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
<|reserved_special_token_0|>
def on_connect(client, userdata, flags, rc):
"""0: Connection successful
1: Connection refused - incorrect protocol version
2: Connection refused - invalid client identifier
3: Connection refused - server unavailable
4: Connection refused - bad username or password
5: Connection refused - not authorised
6-255: Currently unused."""
print('Connected with result code ' + str(rc))
def on_message(client, userdata, msg):
print(str(datetime.now()) + ' Message Received: ' + str(msg.payload))
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def on_connect(client, userdata, flags, rc):
"""0: Connection successful
1: Connection refused - incorrect protocol version
2: Connection refused - invalid client identifier
3: Connection refused - server unavailable
4: Connection refused - bad username or password
5: Connection refused - not authorised
6-255: Currently unused."""
print('Connected with result code ' + str(rc))
def on_message(client, userdata, msg):
print(str(datetime.now()) + ' Message Received: ' + str(msg.payload))
<|reserved_special_token_0|>
def task():
spread = np.random.normal(loc=0.708727, scale=0.192176)
print('spread')
root.after(interval_time, task)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
MQTT_IP = 'emq'
MQTT_PORT = 8883
username = 'spread_ICAM'
password = 'spread_ICAM'
deviceType = 'spread_ICAM'
version = 'v1'
def on_connect(client, userdata, flags, rc):
"""0: Connection successful
1: Connection refused - incorrect protocol version
2: Connection refused - invalid client identifier
3: Connection refused - server unavailable
4: Connection refused - bad username or password
5: Connection refused - not authorised
6-255: Currently unused."""
print('Connected with result code ' + str(rc))
def on_message(client, userdata, msg):
print(str(datetime.now()) + ' Message Received: ' + str(msg.payload))
publishTopic = '%s_%s/%s/events' % (deviceType, version, username)
subscribeTopic = '%s_%s/%s/operations' % (deviceType, version, username)
client = mqtt.Client(client_id='TentativoRaffo')
client.tls_set(ca_certs='digitalfuture_ca_public.pem', certfile=None,
keyfile=None, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.
PROTOCOL_SSLv23, ciphers=None)
client.tls_insecure_set(False)
client.username_pw_set(username, password=password)
client.on_connect = on_connect
client.on_message = on_message
client.connect(MQTT_IP, MQTT_PORT, 60, bind_address='')
client.loop_start()
root = Tk()
Label(root, text='Spread simulator').grid(row=0, column=1, pady=5)
Label(root, text='Kg').grid(row=1, column=0, pady=5)
text_id = Text(root, height=1, width=10)
text_id.grid(row=1, column=1, padx=5, pady=5)
Label(root, text='Peso in kg del vassoio prelevato (Kg)').grid(row=1,
column=2, pady=5)
Label(root, text='mm_kg').grid(row=2, column=0, pady=5)
text_speed = Text(root, height=1, width=10)
text_speed.grid(row=2, column=1, padx=5, pady=5)
Label(root, text='Di quanti mm affonda per ogni kg prelevato (mm)').grid(row
=2, column=2, pady=5)
Label(root, text='s').grid(row=3, column=0, pady=5)
text_speed = Text(root, height=1, width=10)
text_speed.grid(row=3, column=1, padx=5, pady=5)
Label(root, text='Coefficiente di sovraelongazione delle catene').grid(row=
3, column=2, pady=5)
Label(root, text='interval').grid(row=4, column=0, pady=5)
text_speed = Text(root, height=1, width=10)
text_speed.grid(row=4, column=1, padx=5, pady=5)
Label(root, text='Intervallo di invio dati (s)').grid(row=4, column=2, pady=5)
btn_start = Button(root)
btn_start['text'] = 'Start'
btn_start.grid(row=5, column=1, padx=5, pady=5)
btn_start = Button(root)
btn_start['text'] = 'Stop'
btn_start.grid(row=6, column=1, padx=5, pady=5)
interval_time = 1000
def task():
spread = np.random.normal(loc=0.708727, scale=0.192176)
print('spread')
root.after(interval_time, task)
root.after(interval_time, task)
root.mainloop()
root.destroy()
i = 0
timestamp = 1234567890123
while True:
time.sleep(1)
timestamp += i
print(timestamp)
ordered_obj_to_send = OrderedDict([('spread', 3.0), ('timestamp_',
timestamp), ('date', 'eee')])
client.publish(publishTopic, json.dumps(ordered_obj_to_send), qos=2)
i += 1
<|reserved_special_token_1|>
import json
import paho.mqtt.client as mqtt
from datetime import datetime
import ssl
from collections import OrderedDict
import time
from tkinter import *
import numpy as np
MQTT_IP = 'emq'
MQTT_PORT = 8883
username = 'spread_ICAM'
password = 'spread_ICAM'
deviceType = 'spread_ICAM'
version = 'v1'
def on_connect(client, userdata, flags, rc):
"""0: Connection successful
1: Connection refused - incorrect protocol version
2: Connection refused - invalid client identifier
3: Connection refused - server unavailable
4: Connection refused - bad username or password
5: Connection refused - not authorised
6-255: Currently unused."""
print('Connected with result code ' + str(rc))
def on_message(client, userdata, msg):
print(str(datetime.now()) + ' Message Received: ' + str(msg.payload))
publishTopic = '%s_%s/%s/events' % (deviceType, version, username)
subscribeTopic = '%s_%s/%s/operations' % (deviceType, version, username)
client = mqtt.Client(client_id='TentativoRaffo')
client.tls_set(ca_certs='digitalfuture_ca_public.pem', certfile=None,
keyfile=None, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.
PROTOCOL_SSLv23, ciphers=None)
client.tls_insecure_set(False)
client.username_pw_set(username, password=password)
client.on_connect = on_connect
client.on_message = on_message
client.connect(MQTT_IP, MQTT_PORT, 60, bind_address='')
client.loop_start()
root = Tk()
Label(root, text='Spread simulator').grid(row=0, column=1, pady=5)
Label(root, text='Kg').grid(row=1, column=0, pady=5)
text_id = Text(root, height=1, width=10)
text_id.grid(row=1, column=1, padx=5, pady=5)
Label(root, text='Peso in kg del vassoio prelevato (Kg)').grid(row=1,
column=2, pady=5)
Label(root, text='mm_kg').grid(row=2, column=0, pady=5)
text_speed = Text(root, height=1, width=10)
text_speed.grid(row=2, column=1, padx=5, pady=5)
Label(root, text='Di quanti mm affonda per ogni kg prelevato (mm)').grid(row
=2, column=2, pady=5)
Label(root, text='s').grid(row=3, column=0, pady=5)
text_speed = Text(root, height=1, width=10)
text_speed.grid(row=3, column=1, padx=5, pady=5)
Label(root, text='Coefficiente di sovraelongazione delle catene').grid(row=
3, column=2, pady=5)
Label(root, text='interval').grid(row=4, column=0, pady=5)
text_speed = Text(root, height=1, width=10)
text_speed.grid(row=4, column=1, padx=5, pady=5)
Label(root, text='Intervallo di invio dati (s)').grid(row=4, column=2, pady=5)
btn_start = Button(root)
btn_start['text'] = 'Start'
btn_start.grid(row=5, column=1, padx=5, pady=5)
btn_start = Button(root)
btn_start['text'] = 'Stop'
btn_start.grid(row=6, column=1, padx=5, pady=5)
interval_time = 1000
def task():
spread = np.random.normal(loc=0.708727, scale=0.192176)
print('spread')
root.after(interval_time, task)
root.after(interval_time, task)
root.mainloop()
root.destroy()
i = 0
timestamp = 1234567890123
while True:
time.sleep(1)
timestamp += i
print(timestamp)
ordered_obj_to_send = OrderedDict([('spread', 3.0), ('timestamp_',
timestamp), ('date', 'eee')])
client.publish(publishTopic, json.dumps(ordered_obj_to_send), qos=2)
i += 1
<|reserved_special_token_1|>
import json
import paho.mqtt.client as mqtt
from datetime import datetime
import ssl
from collections import OrderedDict
import time
from tkinter import *
import numpy as np
MQTT_IP = 'emq'
MQTT_PORT = 8883
username = "spread_ICAM"
password = "spread_ICAM"
deviceType = "spread_ICAM"
version = "v1"
def on_connect(client, userdata, flags, rc):
"""0: Connection successful
1: Connection refused - incorrect protocol version
2: Connection refused - invalid client identifier
3: Connection refused - server unavailable
4: Connection refused - bad username or password
5: Connection refused - not authorised
6-255: Currently unused."""
print("Connected with result code " + str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
# If connection successful start publishing data
# if rc == 0:
# client.subscribe(subscribeTopic)
# self.__send_data_loop()
def on_message(client, userdata, msg):
print(str(datetime.now()) + " Message Received: " + str(msg.payload))
publishTopic = "%s_%s/%s/events" % (deviceType, version, username)
subscribeTopic = "%s_%s/%s/operations" % (deviceType, version, username)
# se non imposto il client_id non riesce a connettersi!!!!!
client = mqtt.Client(client_id="TentativoRaffo")
client.tls_set(ca_certs="digitalfuture_ca_public.pem", certfile=None, keyfile=None, cert_reqs=ssl.CERT_REQUIRED,
tls_version=ssl.PROTOCOL_SSLv23, ciphers=None)
client.tls_insecure_set(False)
client.username_pw_set(username, password=password)
client.on_connect = on_connect
client.on_message = on_message
client.connect(MQTT_IP, MQTT_PORT, 60, bind_address="")
client.loop_start()
#########################
#
# CREATE THE GUI
#
#########################
root = Tk()
Label(root, text="Spread simulator").grid(row=0, column=1, pady=5)
Label(root, text="Kg").grid(row=1, column=0, pady=5)
text_id = Text(root, height=1, width=10)
text_id.grid(row=1, column=1, padx=5, pady=5)
Label(root, text="Peso in kg del vassoio prelevato (Kg)").grid(row=1, column=2, pady=5)
Label(root, text="mm_kg").grid(row=2, column=0, pady=5)
text_speed = Text(root, height=1, width=10)
text_speed.grid(row=2, column=1, padx=5, pady=5)
Label(root, text="Di quanti mm affonda per ogni kg prelevato (mm)").grid(row=2, column=2, pady=5)
Label(root, text="s").grid(row=3, column=0, pady=5)
text_speed = Text(root, height=1, width=10)
text_speed.grid(row=3, column=1, padx=5, pady=5)
Label(root, text="Coefficiente di sovraelongazione delle catene").grid(row=3, column=2, pady=5)
Label(root, text="interval").grid(row=4, column=0, pady=5)
text_speed = Text(root, height=1, width=10)
text_speed.grid(row=4, column=1, padx=5, pady=5)
Label(root, text="Intervallo di invio dati (s)").grid(row=4, column=2, pady=5)
btn_start = Button(root)
btn_start["text"] = "Start"
btn_start.grid(row=5, column=1, padx=5, pady=5)
btn_start = Button(root)
btn_start["text"] = "Stop"
btn_start.grid(row=6, column=1, padx=5, pady=5)
interval_time = 1000;
def task():
spread = np.random.normal(loc=0.708727, scale=0.192176)
print("spread")
root.after(interval_time, task) # reschedule event in 2 seconds
root.after(interval_time, task)
root.mainloop()
root.destroy()
i=0
timestamp = 1234567890123
while(True):
time.sleep(1)
timestamp += i
print(timestamp)
ordered_obj_to_send = OrderedDict([
("spread", 3.0),
("timestamp_", timestamp),
("date", "eee")])
client.publish(publishTopic, json.dumps(ordered_obj_to_send), qos=2)
i+=1
#time.sleep(2)
|
flexible
|
{
"blob_id": "f3664f5f69207c3f2dcec96c90cd220003da0904",
"index": 4142,
"step-1": "<mask token>\n\n\ndef on_connect(client, userdata, flags, rc):\n \"\"\"0: Connection successful\n 1: Connection refused - incorrect protocol version\n 2: Connection refused - invalid client identifier\n 3: Connection refused - server unavailable\n 4: Connection refused - bad username or password\n 5: Connection refused - not authorised\n 6-255: Currently unused.\"\"\"\n print('Connected with result code ' + str(rc))\n\n\ndef on_message(client, userdata, msg):\n print(str(datetime.now()) + ' Message Received: ' + str(msg.payload))\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef on_connect(client, userdata, flags, rc):\n \"\"\"0: Connection successful\n 1: Connection refused - incorrect protocol version\n 2: Connection refused - invalid client identifier\n 3: Connection refused - server unavailable\n 4: Connection refused - bad username or password\n 5: Connection refused - not authorised\n 6-255: Currently unused.\"\"\"\n print('Connected with result code ' + str(rc))\n\n\ndef on_message(client, userdata, msg):\n print(str(datetime.now()) + ' Message Received: ' + str(msg.payload))\n\n\n<mask token>\n\n\ndef task():\n spread = np.random.normal(loc=0.708727, scale=0.192176)\n print('spread')\n root.after(interval_time, task)\n\n\n<mask token>\n",
"step-3": "<mask token>\nMQTT_IP = 'emq'\nMQTT_PORT = 8883\nusername = 'spread_ICAM'\npassword = 'spread_ICAM'\ndeviceType = 'spread_ICAM'\nversion = 'v1'\n\n\ndef on_connect(client, userdata, flags, rc):\n \"\"\"0: Connection successful\n 1: Connection refused - incorrect protocol version\n 2: Connection refused - invalid client identifier\n 3: Connection refused - server unavailable\n 4: Connection refused - bad username or password\n 5: Connection refused - not authorised\n 6-255: Currently unused.\"\"\"\n print('Connected with result code ' + str(rc))\n\n\ndef on_message(client, userdata, msg):\n print(str(datetime.now()) + ' Message Received: ' + str(msg.payload))\n\n\npublishTopic = '%s_%s/%s/events' % (deviceType, version, username)\nsubscribeTopic = '%s_%s/%s/operations' % (deviceType, version, username)\nclient = mqtt.Client(client_id='TentativoRaffo')\nclient.tls_set(ca_certs='digitalfuture_ca_public.pem', certfile=None,\n keyfile=None, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.\n PROTOCOL_SSLv23, ciphers=None)\nclient.tls_insecure_set(False)\nclient.username_pw_set(username, password=password)\nclient.on_connect = on_connect\nclient.on_message = on_message\nclient.connect(MQTT_IP, MQTT_PORT, 60, bind_address='')\nclient.loop_start()\nroot = Tk()\nLabel(root, text='Spread simulator').grid(row=0, column=1, pady=5)\nLabel(root, text='Kg').grid(row=1, column=0, pady=5)\ntext_id = Text(root, height=1, width=10)\ntext_id.grid(row=1, column=1, padx=5, pady=5)\nLabel(root, text='Peso in kg del vassoio prelevato (Kg)').grid(row=1,\n column=2, pady=5)\nLabel(root, text='mm_kg').grid(row=2, column=0, pady=5)\ntext_speed = Text(root, height=1, width=10)\ntext_speed.grid(row=2, column=1, padx=5, pady=5)\nLabel(root, text='Di quanti mm affonda per ogni kg prelevato (mm)').grid(row\n =2, column=2, pady=5)\nLabel(root, text='s').grid(row=3, column=0, pady=5)\ntext_speed = Text(root, height=1, width=10)\ntext_speed.grid(row=3, column=1, padx=5, pady=5)\nLabel(root, text='Coefficiente di sovraelongazione delle catene').grid(row=\n 3, column=2, pady=5)\nLabel(root, text='interval').grid(row=4, column=0, pady=5)\ntext_speed = Text(root, height=1, width=10)\ntext_speed.grid(row=4, column=1, padx=5, pady=5)\nLabel(root, text='Intervallo di invio dati (s)').grid(row=4, column=2, pady=5)\nbtn_start = Button(root)\nbtn_start['text'] = 'Start'\nbtn_start.grid(row=5, column=1, padx=5, pady=5)\nbtn_start = Button(root)\nbtn_start['text'] = 'Stop'\nbtn_start.grid(row=6, column=1, padx=5, pady=5)\ninterval_time = 1000\n\n\ndef task():\n spread = np.random.normal(loc=0.708727, scale=0.192176)\n print('spread')\n root.after(interval_time, task)\n\n\nroot.after(interval_time, task)\nroot.mainloop()\nroot.destroy()\ni = 0\ntimestamp = 1234567890123\nwhile True:\n time.sleep(1)\n timestamp += i\n print(timestamp)\n ordered_obj_to_send = OrderedDict([('spread', 3.0), ('timestamp_',\n timestamp), ('date', 'eee')])\n client.publish(publishTopic, json.dumps(ordered_obj_to_send), qos=2)\n i += 1\n",
"step-4": "import json\nimport paho.mqtt.client as mqtt\nfrom datetime import datetime\nimport ssl\nfrom collections import OrderedDict\nimport time\nfrom tkinter import *\nimport numpy as np\nMQTT_IP = 'emq'\nMQTT_PORT = 8883\nusername = 'spread_ICAM'\npassword = 'spread_ICAM'\ndeviceType = 'spread_ICAM'\nversion = 'v1'\n\n\ndef on_connect(client, userdata, flags, rc):\n \"\"\"0: Connection successful\n 1: Connection refused - incorrect protocol version\n 2: Connection refused - invalid client identifier\n 3: Connection refused - server unavailable\n 4: Connection refused - bad username or password\n 5: Connection refused - not authorised\n 6-255: Currently unused.\"\"\"\n print('Connected with result code ' + str(rc))\n\n\ndef on_message(client, userdata, msg):\n print(str(datetime.now()) + ' Message Received: ' + str(msg.payload))\n\n\npublishTopic = '%s_%s/%s/events' % (deviceType, version, username)\nsubscribeTopic = '%s_%s/%s/operations' % (deviceType, version, username)\nclient = mqtt.Client(client_id='TentativoRaffo')\nclient.tls_set(ca_certs='digitalfuture_ca_public.pem', certfile=None,\n keyfile=None, cert_reqs=ssl.CERT_REQUIRED, tls_version=ssl.\n PROTOCOL_SSLv23, ciphers=None)\nclient.tls_insecure_set(False)\nclient.username_pw_set(username, password=password)\nclient.on_connect = on_connect\nclient.on_message = on_message\nclient.connect(MQTT_IP, MQTT_PORT, 60, bind_address='')\nclient.loop_start()\nroot = Tk()\nLabel(root, text='Spread simulator').grid(row=0, column=1, pady=5)\nLabel(root, text='Kg').grid(row=1, column=0, pady=5)\ntext_id = Text(root, height=1, width=10)\ntext_id.grid(row=1, column=1, padx=5, pady=5)\nLabel(root, text='Peso in kg del vassoio prelevato (Kg)').grid(row=1,\n column=2, pady=5)\nLabel(root, text='mm_kg').grid(row=2, column=0, pady=5)\ntext_speed = Text(root, height=1, width=10)\ntext_speed.grid(row=2, column=1, padx=5, pady=5)\nLabel(root, text='Di quanti mm affonda per ogni kg prelevato (mm)').grid(row\n =2, column=2, pady=5)\nLabel(root, text='s').grid(row=3, column=0, pady=5)\ntext_speed = Text(root, height=1, width=10)\ntext_speed.grid(row=3, column=1, padx=5, pady=5)\nLabel(root, text='Coefficiente di sovraelongazione delle catene').grid(row=\n 3, column=2, pady=5)\nLabel(root, text='interval').grid(row=4, column=0, pady=5)\ntext_speed = Text(root, height=1, width=10)\ntext_speed.grid(row=4, column=1, padx=5, pady=5)\nLabel(root, text='Intervallo di invio dati (s)').grid(row=4, column=2, pady=5)\nbtn_start = Button(root)\nbtn_start['text'] = 'Start'\nbtn_start.grid(row=5, column=1, padx=5, pady=5)\nbtn_start = Button(root)\nbtn_start['text'] = 'Stop'\nbtn_start.grid(row=6, column=1, padx=5, pady=5)\ninterval_time = 1000\n\n\ndef task():\n spread = np.random.normal(loc=0.708727, scale=0.192176)\n print('spread')\n root.after(interval_time, task)\n\n\nroot.after(interval_time, task)\nroot.mainloop()\nroot.destroy()\ni = 0\ntimestamp = 1234567890123\nwhile True:\n time.sleep(1)\n timestamp += i\n print(timestamp)\n ordered_obj_to_send = OrderedDict([('spread', 3.0), ('timestamp_',\n timestamp), ('date', 'eee')])\n client.publish(publishTopic, json.dumps(ordered_obj_to_send), qos=2)\n i += 1\n",
"step-5": "import json\nimport paho.mqtt.client as mqtt\nfrom datetime import datetime\nimport ssl\nfrom collections import OrderedDict\nimport time\nfrom tkinter import *\nimport numpy as np\n\nMQTT_IP = 'emq'\nMQTT_PORT = 8883\n\nusername = \"spread_ICAM\"\npassword = \"spread_ICAM\"\ndeviceType = \"spread_ICAM\"\nversion = \"v1\"\n\ndef on_connect(client, userdata, flags, rc):\n \"\"\"0: Connection successful\n 1: Connection refused - incorrect protocol version\n 2: Connection refused - invalid client identifier\n 3: Connection refused - server unavailable\n 4: Connection refused - bad username or password\n 5: Connection refused - not authorised\n 6-255: Currently unused.\"\"\"\n print(\"Connected with result code \" + str(rc))\n # Subscribing in on_connect() means that if we lose the connection and\n # reconnect then subscriptions will be renewed.\n # If connection successful start publishing data\n # if rc == 0:\n # client.subscribe(subscribeTopic)\n # self.__send_data_loop()\n\n\ndef on_message(client, userdata, msg):\n print(str(datetime.now()) + \" Message Received: \" + str(msg.payload))\n\n\npublishTopic = \"%s_%s/%s/events\" % (deviceType, version, username)\nsubscribeTopic = \"%s_%s/%s/operations\" % (deviceType, version, username)\n# se non imposto il client_id non riesce a connettersi!!!!!\nclient = mqtt.Client(client_id=\"TentativoRaffo\")\nclient.tls_set(ca_certs=\"digitalfuture_ca_public.pem\", certfile=None, keyfile=None, cert_reqs=ssl.CERT_REQUIRED,\n tls_version=ssl.PROTOCOL_SSLv23, ciphers=None)\nclient.tls_insecure_set(False)\nclient.username_pw_set(username, password=password)\nclient.on_connect = on_connect\nclient.on_message = on_message\nclient.connect(MQTT_IP, MQTT_PORT, 60, bind_address=\"\")\nclient.loop_start()\n\n\n\n#########################\n#\n# CREATE THE GUI\n#\n#########################\n\n\nroot = Tk()\n\nLabel(root, text=\"Spread simulator\").grid(row=0, column=1, pady=5)\n\nLabel(root, text=\"Kg\").grid(row=1, column=0, pady=5)\ntext_id = Text(root, height=1, width=10)\ntext_id.grid(row=1, column=1, padx=5, pady=5)\nLabel(root, text=\"Peso in kg del vassoio prelevato (Kg)\").grid(row=1, column=2, pady=5)\n\n\nLabel(root, text=\"mm_kg\").grid(row=2, column=0, pady=5)\ntext_speed = Text(root, height=1, width=10)\ntext_speed.grid(row=2, column=1, padx=5, pady=5)\nLabel(root, text=\"Di quanti mm affonda per ogni kg prelevato (mm)\").grid(row=2, column=2, pady=5)\n\nLabel(root, text=\"s\").grid(row=3, column=0, pady=5)\ntext_speed = Text(root, height=1, width=10)\ntext_speed.grid(row=3, column=1, padx=5, pady=5)\nLabel(root, text=\"Coefficiente di sovraelongazione delle catene\").grid(row=3, column=2, pady=5)\n\nLabel(root, text=\"interval\").grid(row=4, column=0, pady=5)\ntext_speed = Text(root, height=1, width=10)\ntext_speed.grid(row=4, column=1, padx=5, pady=5)\nLabel(root, text=\"Intervallo di invio dati (s)\").grid(row=4, column=2, pady=5)\n\nbtn_start = Button(root)\nbtn_start[\"text\"] = \"Start\"\nbtn_start.grid(row=5, column=1, padx=5, pady=5)\n\nbtn_start = Button(root)\nbtn_start[\"text\"] = \"Stop\"\nbtn_start.grid(row=6, column=1, padx=5, pady=5)\n\ninterval_time = 1000;\n\ndef task():\n\n spread = np.random.normal(loc=0.708727, scale=0.192176)\n print(\"spread\")\n root.after(interval_time, task) # reschedule event in 2 seconds\n\nroot.after(interval_time, task)\n\nroot.mainloop()\nroot.destroy()\n\n\ni=0\ntimestamp = 1234567890123\nwhile(True):\n\n\n time.sleep(1)\n timestamp += i\n print(timestamp)\n\n ordered_obj_to_send = OrderedDict([\n (\"spread\", 3.0),\n (\"timestamp_\", timestamp),\n (\"date\", \"eee\")])\n client.publish(publishTopic, json.dumps(ordered_obj_to_send), qos=2)\n i+=1\n#time.sleep(2)",
"step-ids": [
2,
3,
5,
6,
7
]
}
|
[
2,
3,
5,
6,
7
] |
<|reserved_special_token_0|>
@gapit_test('vkCmdCopyQueryPoolResults_test')
class FifthToEighthQueryResultsIn64BitWithWaitBitCopyWithZeroOffsets(GapitTest
):
<|reserved_special_token_0|>
@gapit_test('vkCmdCopyQueryPoolResults_test')
class AllFourQueryResultsIn32BitAnd12StrideWithPartialAndAvailabilityBitWithZeroOffset(
GapitTest):
def expect(self):
"""3. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 0,
queryCount: 4, stride: 12 and dstOffset: 0."""
copy_query_pool_results = require(self.nth_call_of(
'vkCmdCopyQueryPoolResults', 3))
require_not_equal(0, copy_query_pool_results.int_commandBuffer)
require_not_equal(0, copy_query_pool_results.int_queryPool)
require_equal(0, copy_query_pool_results.int_firstQuery)
require_equal(4, copy_query_pool_results.int_queryCount)
require_not_equal(0, copy_query_pool_results.int_dstBuffer)
require_equal(0, copy_query_pool_results.int_dstOffset)
require_equal(12, copy_query_pool_results.int_stride)
require_equal(VK_QUERY_RESULT_PARTIAL_BIT |
VK_QUERY_RESULT_WITH_AVAILABILITY_BIT, copy_query_pool_results.
int_flags)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
@gapit_test('vkCmdCopyQueryPoolResults_test')
class AllFourQueryResultsIn32BitWithNoFlagCopyWithOffsets(GapitTest):
<|reserved_special_token_0|>
@gapit_test('vkCmdCopyQueryPoolResults_test')
class FifthToEighthQueryResultsIn64BitWithWaitBitCopyWithZeroOffsets(GapitTest
):
def expect(self):
"""2. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 4,
queryCount: 4, stride: 8 and dstOffset: 0."""
copy_query_pool_results = require(self.nth_call_of(
'vkCmdCopyQueryPoolResults', 2))
require_not_equal(0, copy_query_pool_results.int_commandBuffer)
require_not_equal(0, copy_query_pool_results.int_queryPool)
require_equal(4, copy_query_pool_results.int_firstQuery)
require_equal(4, copy_query_pool_results.int_queryCount)
require_not_equal(0, copy_query_pool_results.int_dstBuffer)
require_equal(0, copy_query_pool_results.int_dstOffset)
require_equal(8, copy_query_pool_results.int_stride)
require_equal(VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT,
copy_query_pool_results.int_flags)
@gapit_test('vkCmdCopyQueryPoolResults_test')
class AllFourQueryResultsIn32BitAnd12StrideWithPartialAndAvailabilityBitWithZeroOffset(
GapitTest):
def expect(self):
"""3. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 0,
queryCount: 4, stride: 12 and dstOffset: 0."""
copy_query_pool_results = require(self.nth_call_of(
'vkCmdCopyQueryPoolResults', 3))
require_not_equal(0, copy_query_pool_results.int_commandBuffer)
require_not_equal(0, copy_query_pool_results.int_queryPool)
require_equal(0, copy_query_pool_results.int_firstQuery)
require_equal(4, copy_query_pool_results.int_queryCount)
require_not_equal(0, copy_query_pool_results.int_dstBuffer)
require_equal(0, copy_query_pool_results.int_dstOffset)
require_equal(12, copy_query_pool_results.int_stride)
require_equal(VK_QUERY_RESULT_PARTIAL_BIT |
VK_QUERY_RESULT_WITH_AVAILABILITY_BIT, copy_query_pool_results.
int_flags)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
@gapit_test('vkCmdCopyQueryPoolResults_test')
class AllFourQueryResultsIn32BitWithNoFlagCopyWithOffsets(GapitTest):
def expect(self):
"""1. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 0,
queryCount: 4 stride: 4 and dstOffset: 16."""
copy_query_pool_results = require(self.nth_call_of(
'vkCmdCopyQueryPoolResults', 1))
require_not_equal(0, copy_query_pool_results.int_commandBuffer)
require_not_equal(0, copy_query_pool_results.int_queryPool)
require_equal(0, copy_query_pool_results.int_firstQuery)
require_equal(4, copy_query_pool_results.int_queryCount)
require_not_equal(0, copy_query_pool_results.int_dstBuffer)
require_equal(16, copy_query_pool_results.int_dstOffset)
require_equal(4, copy_query_pool_results.int_stride)
require_equal(0, copy_query_pool_results.int_flags)
@gapit_test('vkCmdCopyQueryPoolResults_test')
class FifthToEighthQueryResultsIn64BitWithWaitBitCopyWithZeroOffsets(GapitTest
):
def expect(self):
"""2. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 4,
queryCount: 4, stride: 8 and dstOffset: 0."""
copy_query_pool_results = require(self.nth_call_of(
'vkCmdCopyQueryPoolResults', 2))
require_not_equal(0, copy_query_pool_results.int_commandBuffer)
require_not_equal(0, copy_query_pool_results.int_queryPool)
require_equal(4, copy_query_pool_results.int_firstQuery)
require_equal(4, copy_query_pool_results.int_queryCount)
require_not_equal(0, copy_query_pool_results.int_dstBuffer)
require_equal(0, copy_query_pool_results.int_dstOffset)
require_equal(8, copy_query_pool_results.int_stride)
require_equal(VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT,
copy_query_pool_results.int_flags)
@gapit_test('vkCmdCopyQueryPoolResults_test')
class AllFourQueryResultsIn32BitAnd12StrideWithPartialAndAvailabilityBitWithZeroOffset(
GapitTest):
def expect(self):
"""3. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 0,
queryCount: 4, stride: 12 and dstOffset: 0."""
copy_query_pool_results = require(self.nth_call_of(
'vkCmdCopyQueryPoolResults', 3))
require_not_equal(0, copy_query_pool_results.int_commandBuffer)
require_not_equal(0, copy_query_pool_results.int_queryPool)
require_equal(0, copy_query_pool_results.int_firstQuery)
require_equal(4, copy_query_pool_results.int_queryCount)
require_not_equal(0, copy_query_pool_results.int_dstBuffer)
require_equal(0, copy_query_pool_results.int_dstOffset)
require_equal(12, copy_query_pool_results.int_stride)
require_equal(VK_QUERY_RESULT_PARTIAL_BIT |
VK_QUERY_RESULT_WITH_AVAILABILITY_BIT, copy_query_pool_results.
int_flags)
<|reserved_special_token_1|>
from gapit_test_framework import gapit_test, require, require_equal, require_true
from gapit_test_framework import require_not_equal, little_endian_bytes_to_int
from gapit_test_framework import GapitTest, get_read_offset_function
import gapit_test_framework
from vulkan_constants import *
@gapit_test('vkCmdCopyQueryPoolResults_test')
class AllFourQueryResultsIn32BitWithNoFlagCopyWithOffsets(GapitTest):
def expect(self):
"""1. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 0,
queryCount: 4 stride: 4 and dstOffset: 16."""
copy_query_pool_results = require(self.nth_call_of(
'vkCmdCopyQueryPoolResults', 1))
require_not_equal(0, copy_query_pool_results.int_commandBuffer)
require_not_equal(0, copy_query_pool_results.int_queryPool)
require_equal(0, copy_query_pool_results.int_firstQuery)
require_equal(4, copy_query_pool_results.int_queryCount)
require_not_equal(0, copy_query_pool_results.int_dstBuffer)
require_equal(16, copy_query_pool_results.int_dstOffset)
require_equal(4, copy_query_pool_results.int_stride)
require_equal(0, copy_query_pool_results.int_flags)
@gapit_test('vkCmdCopyQueryPoolResults_test')
class FifthToEighthQueryResultsIn64BitWithWaitBitCopyWithZeroOffsets(GapitTest
):
def expect(self):
"""2. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 4,
queryCount: 4, stride: 8 and dstOffset: 0."""
copy_query_pool_results = require(self.nth_call_of(
'vkCmdCopyQueryPoolResults', 2))
require_not_equal(0, copy_query_pool_results.int_commandBuffer)
require_not_equal(0, copy_query_pool_results.int_queryPool)
require_equal(4, copy_query_pool_results.int_firstQuery)
require_equal(4, copy_query_pool_results.int_queryCount)
require_not_equal(0, copy_query_pool_results.int_dstBuffer)
require_equal(0, copy_query_pool_results.int_dstOffset)
require_equal(8, copy_query_pool_results.int_stride)
require_equal(VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT,
copy_query_pool_results.int_flags)
@gapit_test('vkCmdCopyQueryPoolResults_test')
class AllFourQueryResultsIn32BitAnd12StrideWithPartialAndAvailabilityBitWithZeroOffset(
GapitTest):
def expect(self):
"""3. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 0,
queryCount: 4, stride: 12 and dstOffset: 0."""
copy_query_pool_results = require(self.nth_call_of(
'vkCmdCopyQueryPoolResults', 3))
require_not_equal(0, copy_query_pool_results.int_commandBuffer)
require_not_equal(0, copy_query_pool_results.int_queryPool)
require_equal(0, copy_query_pool_results.int_firstQuery)
require_equal(4, copy_query_pool_results.int_queryCount)
require_not_equal(0, copy_query_pool_results.int_dstBuffer)
require_equal(0, copy_query_pool_results.int_dstOffset)
require_equal(12, copy_query_pool_results.int_stride)
require_equal(VK_QUERY_RESULT_PARTIAL_BIT |
VK_QUERY_RESULT_WITH_AVAILABILITY_BIT, copy_query_pool_results.
int_flags)
<|reserved_special_token_1|>
# Copyright 2017 Google Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from gapit_test_framework import gapit_test, require, require_equal, require_true
from gapit_test_framework import require_not_equal, little_endian_bytes_to_int
from gapit_test_framework import GapitTest, get_read_offset_function
import gapit_test_framework
from vulkan_constants import *
@gapit_test("vkCmdCopyQueryPoolResults_test")
class AllFourQueryResultsIn32BitWithNoFlagCopyWithOffsets(GapitTest):
def expect(self):
"""1. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 0,
queryCount: 4 stride: 4 and dstOffset: 16."""
copy_query_pool_results = require(self.nth_call_of(
"vkCmdCopyQueryPoolResults", 1))
require_not_equal(0, copy_query_pool_results.int_commandBuffer)
require_not_equal(0, copy_query_pool_results.int_queryPool)
require_equal(0, copy_query_pool_results.int_firstQuery)
require_equal(4, copy_query_pool_results.int_queryCount)
require_not_equal(0, copy_query_pool_results.int_dstBuffer)
require_equal(16, copy_query_pool_results.int_dstOffset)
require_equal(4, copy_query_pool_results.int_stride)
require_equal(0, copy_query_pool_results.int_flags)
@gapit_test("vkCmdCopyQueryPoolResults_test")
class FifthToEighthQueryResultsIn64BitWithWaitBitCopyWithZeroOffsets(GapitTest):
def expect(self):
"""2. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 4,
queryCount: 4, stride: 8 and dstOffset: 0."""
copy_query_pool_results = require(self.nth_call_of(
"vkCmdCopyQueryPoolResults", 2))
require_not_equal(0, copy_query_pool_results.int_commandBuffer)
require_not_equal(0, copy_query_pool_results.int_queryPool)
require_equal(4, copy_query_pool_results.int_firstQuery)
require_equal(4, copy_query_pool_results.int_queryCount)
require_not_equal(0, copy_query_pool_results.int_dstBuffer)
require_equal(0, copy_query_pool_results.int_dstOffset)
require_equal(8, copy_query_pool_results.int_stride)
require_equal(VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT,
copy_query_pool_results.int_flags)
@gapit_test("vkCmdCopyQueryPoolResults_test")
class AllFourQueryResultsIn32BitAnd12StrideWithPartialAndAvailabilityBitWithZeroOffset(GapitTest):
def expect(self):
"""3. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 0,
queryCount: 4, stride: 12 and dstOffset: 0."""
copy_query_pool_results = require(self.nth_call_of(
"vkCmdCopyQueryPoolResults", 3))
require_not_equal(0, copy_query_pool_results.int_commandBuffer)
require_not_equal(0, copy_query_pool_results.int_queryPool)
require_equal(0, copy_query_pool_results.int_firstQuery)
require_equal(4, copy_query_pool_results.int_queryCount)
require_not_equal(0, copy_query_pool_results.int_dstBuffer)
require_equal(0, copy_query_pool_results.int_dstOffset)
require_equal(12, copy_query_pool_results.int_stride)
require_equal(VK_QUERY_RESULT_PARTIAL_BIT
| VK_QUERY_RESULT_WITH_AVAILABILITY_BIT,
copy_query_pool_results.int_flags)
|
flexible
|
{
"blob_id": "c2f6fa4d9a6e2ee5f0593bef775ce8f811225613",
"index": 2047,
"step-1": "<mask token>\n\n\n@gapit_test('vkCmdCopyQueryPoolResults_test')\nclass FifthToEighthQueryResultsIn64BitWithWaitBitCopyWithZeroOffsets(GapitTest\n ):\n <mask token>\n\n\n@gapit_test('vkCmdCopyQueryPoolResults_test')\nclass AllFourQueryResultsIn32BitAnd12StrideWithPartialAndAvailabilityBitWithZeroOffset(\n GapitTest):\n\n def expect(self):\n \"\"\"3. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 0,\n queryCount: 4, stride: 12 and dstOffset: 0.\"\"\"\n copy_query_pool_results = require(self.nth_call_of(\n 'vkCmdCopyQueryPoolResults', 3))\n require_not_equal(0, copy_query_pool_results.int_commandBuffer)\n require_not_equal(0, copy_query_pool_results.int_queryPool)\n require_equal(0, copy_query_pool_results.int_firstQuery)\n require_equal(4, copy_query_pool_results.int_queryCount)\n require_not_equal(0, copy_query_pool_results.int_dstBuffer)\n require_equal(0, copy_query_pool_results.int_dstOffset)\n require_equal(12, copy_query_pool_results.int_stride)\n require_equal(VK_QUERY_RESULT_PARTIAL_BIT |\n VK_QUERY_RESULT_WITH_AVAILABILITY_BIT, copy_query_pool_results.\n int_flags)\n",
"step-2": "<mask token>\n\n\n@gapit_test('vkCmdCopyQueryPoolResults_test')\nclass AllFourQueryResultsIn32BitWithNoFlagCopyWithOffsets(GapitTest):\n <mask token>\n\n\n@gapit_test('vkCmdCopyQueryPoolResults_test')\nclass FifthToEighthQueryResultsIn64BitWithWaitBitCopyWithZeroOffsets(GapitTest\n ):\n\n def expect(self):\n \"\"\"2. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 4,\n queryCount: 4, stride: 8 and dstOffset: 0.\"\"\"\n copy_query_pool_results = require(self.nth_call_of(\n 'vkCmdCopyQueryPoolResults', 2))\n require_not_equal(0, copy_query_pool_results.int_commandBuffer)\n require_not_equal(0, copy_query_pool_results.int_queryPool)\n require_equal(4, copy_query_pool_results.int_firstQuery)\n require_equal(4, copy_query_pool_results.int_queryCount)\n require_not_equal(0, copy_query_pool_results.int_dstBuffer)\n require_equal(0, copy_query_pool_results.int_dstOffset)\n require_equal(8, copy_query_pool_results.int_stride)\n require_equal(VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT,\n copy_query_pool_results.int_flags)\n\n\n@gapit_test('vkCmdCopyQueryPoolResults_test')\nclass AllFourQueryResultsIn32BitAnd12StrideWithPartialAndAvailabilityBitWithZeroOffset(\n GapitTest):\n\n def expect(self):\n \"\"\"3. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 0,\n queryCount: 4, stride: 12 and dstOffset: 0.\"\"\"\n copy_query_pool_results = require(self.nth_call_of(\n 'vkCmdCopyQueryPoolResults', 3))\n require_not_equal(0, copy_query_pool_results.int_commandBuffer)\n require_not_equal(0, copy_query_pool_results.int_queryPool)\n require_equal(0, copy_query_pool_results.int_firstQuery)\n require_equal(4, copy_query_pool_results.int_queryCount)\n require_not_equal(0, copy_query_pool_results.int_dstBuffer)\n require_equal(0, copy_query_pool_results.int_dstOffset)\n require_equal(12, copy_query_pool_results.int_stride)\n require_equal(VK_QUERY_RESULT_PARTIAL_BIT |\n VK_QUERY_RESULT_WITH_AVAILABILITY_BIT, copy_query_pool_results.\n int_flags)\n",
"step-3": "<mask token>\n\n\n@gapit_test('vkCmdCopyQueryPoolResults_test')\nclass AllFourQueryResultsIn32BitWithNoFlagCopyWithOffsets(GapitTest):\n\n def expect(self):\n \"\"\"1. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 0,\n queryCount: 4 stride: 4 and dstOffset: 16.\"\"\"\n copy_query_pool_results = require(self.nth_call_of(\n 'vkCmdCopyQueryPoolResults', 1))\n require_not_equal(0, copy_query_pool_results.int_commandBuffer)\n require_not_equal(0, copy_query_pool_results.int_queryPool)\n require_equal(0, copy_query_pool_results.int_firstQuery)\n require_equal(4, copy_query_pool_results.int_queryCount)\n require_not_equal(0, copy_query_pool_results.int_dstBuffer)\n require_equal(16, copy_query_pool_results.int_dstOffset)\n require_equal(4, copy_query_pool_results.int_stride)\n require_equal(0, copy_query_pool_results.int_flags)\n\n\n@gapit_test('vkCmdCopyQueryPoolResults_test')\nclass FifthToEighthQueryResultsIn64BitWithWaitBitCopyWithZeroOffsets(GapitTest\n ):\n\n def expect(self):\n \"\"\"2. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 4,\n queryCount: 4, stride: 8 and dstOffset: 0.\"\"\"\n copy_query_pool_results = require(self.nth_call_of(\n 'vkCmdCopyQueryPoolResults', 2))\n require_not_equal(0, copy_query_pool_results.int_commandBuffer)\n require_not_equal(0, copy_query_pool_results.int_queryPool)\n require_equal(4, copy_query_pool_results.int_firstQuery)\n require_equal(4, copy_query_pool_results.int_queryCount)\n require_not_equal(0, copy_query_pool_results.int_dstBuffer)\n require_equal(0, copy_query_pool_results.int_dstOffset)\n require_equal(8, copy_query_pool_results.int_stride)\n require_equal(VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT,\n copy_query_pool_results.int_flags)\n\n\n@gapit_test('vkCmdCopyQueryPoolResults_test')\nclass AllFourQueryResultsIn32BitAnd12StrideWithPartialAndAvailabilityBitWithZeroOffset(\n GapitTest):\n\n def expect(self):\n \"\"\"3. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 0,\n queryCount: 4, stride: 12 and dstOffset: 0.\"\"\"\n copy_query_pool_results = require(self.nth_call_of(\n 'vkCmdCopyQueryPoolResults', 3))\n require_not_equal(0, copy_query_pool_results.int_commandBuffer)\n require_not_equal(0, copy_query_pool_results.int_queryPool)\n require_equal(0, copy_query_pool_results.int_firstQuery)\n require_equal(4, copy_query_pool_results.int_queryCount)\n require_not_equal(0, copy_query_pool_results.int_dstBuffer)\n require_equal(0, copy_query_pool_results.int_dstOffset)\n require_equal(12, copy_query_pool_results.int_stride)\n require_equal(VK_QUERY_RESULT_PARTIAL_BIT |\n VK_QUERY_RESULT_WITH_AVAILABILITY_BIT, copy_query_pool_results.\n int_flags)\n",
"step-4": "from gapit_test_framework import gapit_test, require, require_equal, require_true\nfrom gapit_test_framework import require_not_equal, little_endian_bytes_to_int\nfrom gapit_test_framework import GapitTest, get_read_offset_function\nimport gapit_test_framework\nfrom vulkan_constants import *\n\n\n@gapit_test('vkCmdCopyQueryPoolResults_test')\nclass AllFourQueryResultsIn32BitWithNoFlagCopyWithOffsets(GapitTest):\n\n def expect(self):\n \"\"\"1. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 0,\n queryCount: 4 stride: 4 and dstOffset: 16.\"\"\"\n copy_query_pool_results = require(self.nth_call_of(\n 'vkCmdCopyQueryPoolResults', 1))\n require_not_equal(0, copy_query_pool_results.int_commandBuffer)\n require_not_equal(0, copy_query_pool_results.int_queryPool)\n require_equal(0, copy_query_pool_results.int_firstQuery)\n require_equal(4, copy_query_pool_results.int_queryCount)\n require_not_equal(0, copy_query_pool_results.int_dstBuffer)\n require_equal(16, copy_query_pool_results.int_dstOffset)\n require_equal(4, copy_query_pool_results.int_stride)\n require_equal(0, copy_query_pool_results.int_flags)\n\n\n@gapit_test('vkCmdCopyQueryPoolResults_test')\nclass FifthToEighthQueryResultsIn64BitWithWaitBitCopyWithZeroOffsets(GapitTest\n ):\n\n def expect(self):\n \"\"\"2. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 4,\n queryCount: 4, stride: 8 and dstOffset: 0.\"\"\"\n copy_query_pool_results = require(self.nth_call_of(\n 'vkCmdCopyQueryPoolResults', 2))\n require_not_equal(0, copy_query_pool_results.int_commandBuffer)\n require_not_equal(0, copy_query_pool_results.int_queryPool)\n require_equal(4, copy_query_pool_results.int_firstQuery)\n require_equal(4, copy_query_pool_results.int_queryCount)\n require_not_equal(0, copy_query_pool_results.int_dstBuffer)\n require_equal(0, copy_query_pool_results.int_dstOffset)\n require_equal(8, copy_query_pool_results.int_stride)\n require_equal(VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT,\n copy_query_pool_results.int_flags)\n\n\n@gapit_test('vkCmdCopyQueryPoolResults_test')\nclass AllFourQueryResultsIn32BitAnd12StrideWithPartialAndAvailabilityBitWithZeroOffset(\n GapitTest):\n\n def expect(self):\n \"\"\"3. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 0,\n queryCount: 4, stride: 12 and dstOffset: 0.\"\"\"\n copy_query_pool_results = require(self.nth_call_of(\n 'vkCmdCopyQueryPoolResults', 3))\n require_not_equal(0, copy_query_pool_results.int_commandBuffer)\n require_not_equal(0, copy_query_pool_results.int_queryPool)\n require_equal(0, copy_query_pool_results.int_firstQuery)\n require_equal(4, copy_query_pool_results.int_queryCount)\n require_not_equal(0, copy_query_pool_results.int_dstBuffer)\n require_equal(0, copy_query_pool_results.int_dstOffset)\n require_equal(12, copy_query_pool_results.int_stride)\n require_equal(VK_QUERY_RESULT_PARTIAL_BIT |\n VK_QUERY_RESULT_WITH_AVAILABILITY_BIT, copy_query_pool_results.\n int_flags)\n",
"step-5": "# Copyright 2017 Google Inc.\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# http://www.apache.org/licenses/LICENSE-2.0\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom gapit_test_framework import gapit_test, require, require_equal, require_true\nfrom gapit_test_framework import require_not_equal, little_endian_bytes_to_int\nfrom gapit_test_framework import GapitTest, get_read_offset_function\nimport gapit_test_framework\nfrom vulkan_constants import *\n\n\n@gapit_test(\"vkCmdCopyQueryPoolResults_test\")\nclass AllFourQueryResultsIn32BitWithNoFlagCopyWithOffsets(GapitTest):\n\n def expect(self):\n \"\"\"1. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 0,\n queryCount: 4 stride: 4 and dstOffset: 16.\"\"\"\n copy_query_pool_results = require(self.nth_call_of(\n \"vkCmdCopyQueryPoolResults\", 1))\n require_not_equal(0, copy_query_pool_results.int_commandBuffer)\n require_not_equal(0, copy_query_pool_results.int_queryPool)\n require_equal(0, copy_query_pool_results.int_firstQuery)\n require_equal(4, copy_query_pool_results.int_queryCount)\n require_not_equal(0, copy_query_pool_results.int_dstBuffer)\n require_equal(16, copy_query_pool_results.int_dstOffset)\n require_equal(4, copy_query_pool_results.int_stride)\n require_equal(0, copy_query_pool_results.int_flags)\n\n\n@gapit_test(\"vkCmdCopyQueryPoolResults_test\")\nclass FifthToEighthQueryResultsIn64BitWithWaitBitCopyWithZeroOffsets(GapitTest):\n\n def expect(self):\n \"\"\"2. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 4,\n queryCount: 4, stride: 8 and dstOffset: 0.\"\"\"\n copy_query_pool_results = require(self.nth_call_of(\n \"vkCmdCopyQueryPoolResults\", 2))\n require_not_equal(0, copy_query_pool_results.int_commandBuffer)\n require_not_equal(0, copy_query_pool_results.int_queryPool)\n require_equal(4, copy_query_pool_results.int_firstQuery)\n require_equal(4, copy_query_pool_results.int_queryCount)\n require_not_equal(0, copy_query_pool_results.int_dstBuffer)\n require_equal(0, copy_query_pool_results.int_dstOffset)\n require_equal(8, copy_query_pool_results.int_stride)\n require_equal(VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT,\n copy_query_pool_results.int_flags)\n\n\n@gapit_test(\"vkCmdCopyQueryPoolResults_test\")\nclass AllFourQueryResultsIn32BitAnd12StrideWithPartialAndAvailabilityBitWithZeroOffset(GapitTest):\n\n def expect(self):\n \"\"\"3. Expects vkCmdCopyQueryPoolResults() is called with firstQuery: 0,\n queryCount: 4, stride: 12 and dstOffset: 0.\"\"\"\n copy_query_pool_results = require(self.nth_call_of(\n \"vkCmdCopyQueryPoolResults\", 3))\n require_not_equal(0, copy_query_pool_results.int_commandBuffer)\n require_not_equal(0, copy_query_pool_results.int_queryPool)\n require_equal(0, copy_query_pool_results.int_firstQuery)\n require_equal(4, copy_query_pool_results.int_queryCount)\n require_not_equal(0, copy_query_pool_results.int_dstBuffer)\n require_equal(0, copy_query_pool_results.int_dstOffset)\n require_equal(12, copy_query_pool_results.int_stride)\n require_equal(VK_QUERY_RESULT_PARTIAL_BIT\n | VK_QUERY_RESULT_WITH_AVAILABILITY_BIT,\n copy_query_pool_results.int_flags)\n",
"step-ids": [
3,
5,
6,
7,
8
]
}
|
[
3,
5,
6,
7,
8
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
EMOTICONS = {'O:)': 'angel', 'o:)': 'angel', 'O:-)': 'angel', 'o:-)':
'angel', 'o:-3': 'angel', 'o:3': 'angel', 'O;^)': 'angel', '>:[':
'annoyed/disappointed', ':-(': 'annoyed/disappointed', ':(':
'annoyed/disappointed', ':((': 'annoyed/disappointed', ':-((':
'annoyed/disappointed', ':-c': 'annoyed/disappointed', ':-<':
'annoyed/disappointed', ':?C': 'annoyed/disappointed', ':<':
'annoyed/disappointed', ':[': 'annoyed/disappointed', ':{':
'annoyed/disappointed', ':=||': 'annoyed/disappointed', ':@':
'annoyed/disappointed', '>:(': 'annoyed/disappointed', ':/':
'annoyed/disappointed', ':\\': 'annoyed/disappointed', '=/':
'annoyed/disappointed', '=\\': 'annoyed/disappointed', '>:/':
'annoyed/disappointed', '>:\\': 'annoyed/disappointed', ':S':
'annoyed/disappointed', ':s': 'annoyed/disappointed', ':-S':
'annoyed/disappointed', ':-s': 'annoyed/disappointed', ':|':
'annoyed/disappointed', ':-|': 'annoyed/disappointed', ':$':
'annoyed/disappointed', '?_?': 'annoyed/disappointed', '(>_<)':
'annoyed/disappointed', '>_<': 'annoyed/disappointed', '>__<':
'annoyed/disappointed', '(>__<)': 'annoyed/disappointed', '(-.-)':
'annoyed/disappointed', '(-_-)': 'annoyed/disappointed', '(._.)':
'annoyed/disappointed', '/:)': 'annoyed/disappointed', ':-$':
'annoyed/disappointed', '>:P': 'annoyed/disappointed', 'K':
'annoyed/disappointed', '3:)': 'devilish', '3:-)': 'devilish', '}:-)':
'devilish', '}:)': 'devilish', '>:)': 'devilish', 'B-)': 'happy', ':-)':
'happy', ':)': 'happy', ':o)': 'happy', ':]': 'happy', ':3': 'happy',
':c)': 'happy', ':>': 'happy', '=]': 'happy', '8)': 'happy', '=)':
'happy', ':}': 'happy', ':^)': 'happy', ':?)': 'happy', ':-))': 'happy',
'<:-P': 'happy', '<:P': 'happy', '<:-p': 'happy', '<:p': 'happy', ';;)':
'happy', 'J': 'happy', '<3': 'heart', '^5': 'high-five', '>_>^':
'high-five', '^<_<': 'high-five', ':*': 'kiss', ':*)': 'kiss', ':^*':
'kiss', '}{': 'kiss', "('}{')": 'kiss', ':-D': 'laughing', ':D':
'laughing', '8-D': 'laughing', '8D': 'laughing', 'x-D': 'laughing',
'xD': 'laughing', 'X-D': 'laughing', 'XD': 'laughing', '=-D':
'laughing', '=D': 'laughing', ';D': 'laughing', '-3': 'laughing', '3':
'laughing', 'B^D': 'laughing', 'D:<': 'laughing', 'D:': 'laughing',
'D8': 'laughing', 'D;': 'laughing', 'D=': 'laughing', 'DX': 'laughing',
':-B': 'nerd', '8-)': 'nerd', '8)': 'nerd', '</3': 'sad', ":'(": 'sad',
":'-(": 'sad', 'QQ': 'sad', 'L': 'sad', ':#': 'sealed mouth', ':-#':
'sealed mouth', ':-X': 'sealed mouth', ':-x': 'sealed mouth', ':X':
'sealed mouth', ':x': 'sealed mouth', '??': 'shooting star', '??':
'shooting star', '~?': 'shooting star', '>:O': 'suprprised/shocked',
'>:o': 'suprprised/shocked', ':-O': 'suprprised/shocked', ':-o':
'suprprised/shocked', ':O': 'suprprised/shocked', ':o':
'suprprised/shocked', 'O_o': 'suprprised/shocked', 'o_O':
'suprprised/shocked', 'O.o': 'suprprised/shocked', 'o.O':
'suprprised/shocked', '(O_o)': 'suprprised/shocked', '(o_O)':
'suprprised/shocked', '(O.o)': 'suprprised/shocked', '(o.O)':
'suprprised/shocked', ":'-)": 'tears of happines', ":')":
'tears of happines', ':P': 'teasing/playful', ':p': 'teasing/playful',
'>:P': 'teasing/playful', '>:p': 'teasing/playful', 'X-P':
'teasing/playful', 'x-p': 'teasing/playful', 'xp': 'teasing/playful',
'XP': 'teasing/playful', ':-P': 'teasing/playful', ':-p':
'teasing/playful', '=P': 'teasing/playful', '=P': 'teasing/playful',
':-?': 'teasing/playful', ':-b': 'teasing/playful', ':b':
'teasing/playful', ';)': 'wink', u'º)': 'wink', ';-)': 'wink', ';]':
'wink', u'^Ü^': 'happy'}
special_tokens = EMOTICONS
<|reserved_special_token_0|>
EASY_WORDS = {u'ليا': [(Prefix(u'ل'), u'يا', Suffix(u''))], u'لي': [(Prefix
(u'ل'), u'ي', Suffix(u''))], u'لكم': [(Prefix(u'ل'), u'كم', Suffix(u'')
)], u'لكما': [(Prefix(u'ل'), u'كما', Suffix(u''))], u'له': [(Prefix(
u'ل'), u'ه', Suffix(u''))], u'لها': [(Prefix(u'ل'), u'ها', Suffix(u''))
], u'لهم': [(Prefix(u'ل'), u'هم', Suffix(u''))], u'لهما': [(Prefix(u'ل'
), u'هما', Suffix(u''))], u'لهن': [(Prefix(u'ل'), u'هم', Suffix(u''))],
u'بيا': [(Prefix(u'ب'), u'يا', Suffix(u''))], u'بي': [(Prefix(u'ب'),
u'ي', Suffix(u''))], u'بك': [(Prefix(u'ب'), u'ك', Suffix(u''))], u'بكم':
[(Prefix(u'ب'), u'كم', Suffix(u''))], u'بكما': [(Prefix(u'ب'), u'كما',
Suffix(u''))], u'به': [(Prefix(u'ب'), u'ه', Suffix(u''))], u'بها': [(
Prefix(u'ب'), u'ها', Suffix(u''))], u'بهما': [(Prefix(u'ب'), u'هما',
Suffix(u''))], u'بهم': [(Prefix(u'ب'), u'هم', Suffix(u''))], u'بهن': [(
Prefix(u'ب'), u'هن', Suffix(u''))], u'عليا': [(Prefix(u''), u'على',
Suffix(u'يا'))], u'فيا': [(Prefix(u'ف'), u'يا', Suffix(u''))]}
EMOTICONS_TAG = 'EMO'
PUNCTUATION_TAG = 'PUNC'
DIGIT_TAG = 'CD'
NOTDEFINED_TAG = 'NN'
<|reserved_special_token_1|>
import os.path
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
EMOTICONS = {'O:)': 'angel', 'o:)': 'angel', 'O:-)': 'angel', 'o:-)':
'angel', 'o:-3': 'angel', 'o:3': 'angel', 'O;^)': 'angel', '>:[':
'annoyed/disappointed', ':-(': 'annoyed/disappointed', ':(':
'annoyed/disappointed', ':((': 'annoyed/disappointed', ':-((':
'annoyed/disappointed', ':-c': 'annoyed/disappointed', ':-<':
'annoyed/disappointed', ':?C': 'annoyed/disappointed', ':<':
'annoyed/disappointed', ':[': 'annoyed/disappointed', ':{':
'annoyed/disappointed', ':=||': 'annoyed/disappointed', ':@':
'annoyed/disappointed', '>:(': 'annoyed/disappointed', ':/':
'annoyed/disappointed', ':\\': 'annoyed/disappointed', '=/':
'annoyed/disappointed', '=\\': 'annoyed/disappointed', '>:/':
'annoyed/disappointed', '>:\\': 'annoyed/disappointed', ':S':
'annoyed/disappointed', ':s': 'annoyed/disappointed', ':-S':
'annoyed/disappointed', ':-s': 'annoyed/disappointed', ':|':
'annoyed/disappointed', ':-|': 'annoyed/disappointed', ':$':
'annoyed/disappointed', '?_?': 'annoyed/disappointed', '(>_<)':
'annoyed/disappointed', '>_<': 'annoyed/disappointed', '>__<':
'annoyed/disappointed', '(>__<)': 'annoyed/disappointed', '(-.-)':
'annoyed/disappointed', '(-_-)': 'annoyed/disappointed', '(._.)':
'annoyed/disappointed', '/:)': 'annoyed/disappointed', ':-$':
'annoyed/disappointed', '>:P': 'annoyed/disappointed', 'K':
'annoyed/disappointed', '3:)': 'devilish', '3:-)': 'devilish', '}:-)':
'devilish', '}:)': 'devilish', '>:)': 'devilish', 'B-)': 'happy', ':-)':
'happy', ':)': 'happy', ':o)': 'happy', ':]': 'happy', ':3': 'happy',
':c)': 'happy', ':>': 'happy', '=]': 'happy', '8)': 'happy', '=)':
'happy', ':}': 'happy', ':^)': 'happy', ':?)': 'happy', ':-))': 'happy',
'<:-P': 'happy', '<:P': 'happy', '<:-p': 'happy', '<:p': 'happy', ';;)':
'happy', 'J': 'happy', '<3': 'heart', '^5': 'high-five', '>_>^':
'high-five', '^<_<': 'high-five', ':*': 'kiss', ':*)': 'kiss', ':^*':
'kiss', '}{': 'kiss', "('}{')": 'kiss', ':-D': 'laughing', ':D':
'laughing', '8-D': 'laughing', '8D': 'laughing', 'x-D': 'laughing',
'xD': 'laughing', 'X-D': 'laughing', 'XD': 'laughing', '=-D':
'laughing', '=D': 'laughing', ';D': 'laughing', '-3': 'laughing', '3':
'laughing', 'B^D': 'laughing', 'D:<': 'laughing', 'D:': 'laughing',
'D8': 'laughing', 'D;': 'laughing', 'D=': 'laughing', 'DX': 'laughing',
':-B': 'nerd', '8-)': 'nerd', '8)': 'nerd', '</3': 'sad', ":'(": 'sad',
":'-(": 'sad', 'QQ': 'sad', 'L': 'sad', ':#': 'sealed mouth', ':-#':
'sealed mouth', ':-X': 'sealed mouth', ':-x': 'sealed mouth', ':X':
'sealed mouth', ':x': 'sealed mouth', '??': 'shooting star', '??':
'shooting star', '~?': 'shooting star', '>:O': 'suprprised/shocked',
'>:o': 'suprprised/shocked', ':-O': 'suprprised/shocked', ':-o':
'suprprised/shocked', ':O': 'suprprised/shocked', ':o':
'suprprised/shocked', 'O_o': 'suprprised/shocked', 'o_O':
'suprprised/shocked', 'O.o': 'suprprised/shocked', 'o.O':
'suprprised/shocked', '(O_o)': 'suprprised/shocked', '(o_O)':
'suprprised/shocked', '(O.o)': 'suprprised/shocked', '(o.O)':
'suprprised/shocked', ":'-)": 'tears of happines', ":')":
'tears of happines', ':P': 'teasing/playful', ':p': 'teasing/playful',
'>:P': 'teasing/playful', '>:p': 'teasing/playful', 'X-P':
'teasing/playful', 'x-p': 'teasing/playful', 'xp': 'teasing/playful',
'XP': 'teasing/playful', ':-P': 'teasing/playful', ':-p':
'teasing/playful', '=P': 'teasing/playful', '=P': 'teasing/playful',
':-?': 'teasing/playful', ':-b': 'teasing/playful', ':b':
'teasing/playful', ';)': 'wink', u'º)': 'wink', ';-)': 'wink', ';]':
'wink', u'^Ü^': 'happy'}
special_tokens = EMOTICONS
from DAPOS.data.variation import Prefix, Suffix
EASY_WORDS = {u'ليا': [(Prefix(u'ل'), u'يا', Suffix(u''))], u'لي': [(Prefix
(u'ل'), u'ي', Suffix(u''))], u'لكم': [(Prefix(u'ل'), u'كم', Suffix(u'')
)], u'لكما': [(Prefix(u'ل'), u'كما', Suffix(u''))], u'له': [(Prefix(
u'ل'), u'ه', Suffix(u''))], u'لها': [(Prefix(u'ل'), u'ها', Suffix(u''))
], u'لهم': [(Prefix(u'ل'), u'هم', Suffix(u''))], u'لهما': [(Prefix(u'ل'
), u'هما', Suffix(u''))], u'لهن': [(Prefix(u'ل'), u'هم', Suffix(u''))],
u'بيا': [(Prefix(u'ب'), u'يا', Suffix(u''))], u'بي': [(Prefix(u'ب'),
u'ي', Suffix(u''))], u'بك': [(Prefix(u'ب'), u'ك', Suffix(u''))], u'بكم':
[(Prefix(u'ب'), u'كم', Suffix(u''))], u'بكما': [(Prefix(u'ب'), u'كما',
Suffix(u''))], u'به': [(Prefix(u'ب'), u'ه', Suffix(u''))], u'بها': [(
Prefix(u'ب'), u'ها', Suffix(u''))], u'بهما': [(Prefix(u'ب'), u'هما',
Suffix(u''))], u'بهم': [(Prefix(u'ب'), u'هم', Suffix(u''))], u'بهن': [(
Prefix(u'ب'), u'هن', Suffix(u''))], u'عليا': [(Prefix(u''), u'على',
Suffix(u'يا'))], u'فيا': [(Prefix(u'ف'), u'يا', Suffix(u''))]}
EMOTICONS_TAG = 'EMO'
PUNCTUATION_TAG = 'PUNC'
DIGIT_TAG = 'CD'
NOTDEFINED_TAG = 'NN'
<|reserved_special_token_1|>
# coding: UTF-8 -*-
import os.path
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
EMOTICONS = {
"O:)": "angel",
"o:)": "angel",
"O:-)": "angel",
"o:-)": "angel",
"o:-3": "angel",
"o:3": "angel",
"O;^)": "angel",
">:[": "annoyed/disappointed",
":-(": "annoyed/disappointed",
":(": "annoyed/disappointed",
":((": "annoyed/disappointed",
":-((": "annoyed/disappointed",
":-c": "annoyed/disappointed",
":-<": "annoyed/disappointed",
":?C": "annoyed/disappointed",
":<": "annoyed/disappointed",
":[": "annoyed/disappointed",
":{": "annoyed/disappointed",
":=||": "annoyed/disappointed",
":@": "annoyed/disappointed",
">:(": "annoyed/disappointed",
":/": "annoyed/disappointed",
":\\": "annoyed/disappointed",
"=/": "annoyed/disappointed",
"=\\": "annoyed/disappointed",
">:/": "annoyed/disappointed",
">:\\": "annoyed/disappointed",
":S": "annoyed/disappointed",
":s": "annoyed/disappointed",
":-S": "annoyed/disappointed",
":-s": "annoyed/disappointed",
":|": "annoyed/disappointed",
":-|": "annoyed/disappointed",
":$": "annoyed/disappointed",
"?_?": "annoyed/disappointed",
"(>_<)": "annoyed/disappointed",
">_<": "annoyed/disappointed",
">__<": "annoyed/disappointed",
"(>__<)": "annoyed/disappointed",
"(-.-)": "annoyed/disappointed",
"(-_-)": "annoyed/disappointed",
"(._.)": "annoyed/disappointed",
"/:)": "annoyed/disappointed",
":-$": "annoyed/disappointed",
">:P": "annoyed/disappointed",
"K": "annoyed/disappointed",
"3:)": "devilish",
"3:-)": "devilish",
"}:-)": "devilish",
"}:)": "devilish",
">:)": "devilish",
"B-)": "happy",
":-)": "happy",
":)": "happy",
":o)": "happy",
":]": "happy",
":3": "happy",
":c)": "happy",
":>": "happy",
"=]": "happy",
"8)": "happy",
"=)": "happy",
":}": "happy",
":^)": "happy",
":?)": "happy",
":-))": "happy",
"<:-P": "happy",
"<:P": "happy",
"<:-p": "happy",
"<:p": "happy",
";;)": "happy",
"J": "happy",
"<3": "heart",
"^5": "high-five",
">_>^": "high-five",
"^<_<": "high-five",
":*": "kiss",
":*)": "kiss",
":^*": "kiss",
"}{": "kiss",
"('}{')": "kiss",
":-D": "laughing",
":D": "laughing",
"8-D": "laughing",
"8D": "laughing",
"x-D": "laughing",
"xD": "laughing",
"X-D": "laughing",
"XD": "laughing",
"=-D": "laughing",
"=D": "laughing",
";D": "laughing",
"-3": "laughing",
"3": "laughing",
"B^D": "laughing",
"D:<": "laughing",
"D:": "laughing",
"D8": "laughing",
"D;": "laughing",
"D=": "laughing",
"DX": "laughing",
":-B": "nerd",
"8-)": "nerd",
"8)": "nerd",
"</3": "sad",
":'(": "sad",
":'-(": "sad",
"QQ": "sad",
"L": "sad",
":#": "sealed mouth",
":-#": "sealed mouth",
":-X": "sealed mouth",
":-x": "sealed mouth",
":X": "sealed mouth",
":x": "sealed mouth",
"??": "shooting star",
"??": "shooting star",
"~?": "shooting star",
">:O": "suprprised/shocked",
">:o": "suprprised/shocked",
":-O": "suprprised/shocked",
":-o": "suprprised/shocked",
":O": "suprprised/shocked",
":o": "suprprised/shocked",
"O_o": "suprprised/shocked",
"o_O": "suprprised/shocked",
"O.o": "suprprised/shocked",
"o.O": "suprprised/shocked",
"(O_o)": "suprprised/shocked",
"(o_O)": "suprprised/shocked",
"(O.o)": "suprprised/shocked",
"(o.O)": "suprprised/shocked",
":'-)": "tears of happines",
":')": "tears of happines",
":P": "teasing/playful",
":p": "teasing/playful",
">:P": "teasing/playful",
">:p": "teasing/playful",
"X-P": "teasing/playful",
"x-p": "teasing/playful",
"xp": "teasing/playful",
"XP": "teasing/playful",
":-P": "teasing/playful",
":-p": "teasing/playful",
"=P": "teasing/playful",
"=P": "teasing/playful",
":-?": "teasing/playful",
":-b": "teasing/playful",
":b": "teasing/playful",
";)": "wink",
u"º)": "wink",
";-)": "wink",
";]": "wink",
u"^Ü^": "happy",
}
special_tokens = EMOTICONS
from DAPOS.data.variation import Prefix, Suffix
EASY_WORDS = {
u"ليا": [(Prefix(u"ل"), u"يا", Suffix(u""))],
u"لي": [(Prefix(u"ل"), u"ي", Suffix(u""))],
u"لكم": [(Prefix(u"ل"), u"كم", Suffix(u""))],
u"لكما": [(Prefix(u"ل"), u"كما", Suffix(u""))],
u"له": [(Prefix(u"ل"), u"ه", Suffix(u""))],
u"لها": [(Prefix(u"ل"), u"ها", Suffix(u""))],
u"لهم": [(Prefix(u"ل"), u"هم", Suffix(u""))],
u"لهما": [(Prefix(u"ل"), u"هما", Suffix(u""))],
u"لهن": [(Prefix(u"ل"), u"هم", Suffix(u""))],
u"بيا": [(Prefix(u"ب"), u"يا", Suffix(u""))],
u"بي": [(Prefix(u"ب"), u"ي", Suffix(u""))],
u"بك": [(Prefix(u"ب"), u"ك", Suffix(u""))],
u"بكم": [(Prefix(u"ب"), u"كم", Suffix(u""))],
u"بكما": [(Prefix(u"ب"), u"كما", Suffix(u""))],
u"به": [(Prefix(u"ب"), u"ه", Suffix(u""))],
u"بها": [(Prefix(u"ب"), u"ها", Suffix(u""))],
u"بهما": [(Prefix(u"ب"), u"هما", Suffix(u""))],
u"بهم": [(Prefix(u"ب"), u"هم", Suffix(u""))],
u"بهن": [(Prefix(u"ب"), u"هن", Suffix(u""))],
u"عليا": [(Prefix(u""), u"على", Suffix(u"يا"))],
u"فيا": [(Prefix(u"ف"), u"يا", Suffix(u""))],
}
EMOTICONS_TAG = 'EMO'
PUNCTUATION_TAG = 'PUNC'
DIGIT_TAG = 'CD'
NOTDEFINED_TAG = 'NN'
|
flexible
|
{
"blob_id": "3f3ed0165120dc135a4ce1f282dbdf9dad57adf8",
"index": 980,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nPROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))\nEMOTICONS = {'O:)': 'angel', 'o:)': 'angel', 'O:-)': 'angel', 'o:-)':\n 'angel', 'o:-3': 'angel', 'o:3': 'angel', 'O;^)': 'angel', '>:[':\n 'annoyed/disappointed', ':-(': 'annoyed/disappointed', ':(':\n 'annoyed/disappointed', ':((': 'annoyed/disappointed', ':-((':\n 'annoyed/disappointed', ':-c': 'annoyed/disappointed', ':-<':\n 'annoyed/disappointed', ':?C': 'annoyed/disappointed', ':<':\n 'annoyed/disappointed', ':[': 'annoyed/disappointed', ':{':\n 'annoyed/disappointed', ':=||': 'annoyed/disappointed', ':@':\n 'annoyed/disappointed', '>:(': 'annoyed/disappointed', ':/':\n 'annoyed/disappointed', ':\\\\': 'annoyed/disappointed', '=/':\n 'annoyed/disappointed', '=\\\\': 'annoyed/disappointed', '>:/':\n 'annoyed/disappointed', '>:\\\\': 'annoyed/disappointed', ':S':\n 'annoyed/disappointed', ':s': 'annoyed/disappointed', ':-S':\n 'annoyed/disappointed', ':-s': 'annoyed/disappointed', ':|':\n 'annoyed/disappointed', ':-|': 'annoyed/disappointed', ':$':\n 'annoyed/disappointed', '?_?': 'annoyed/disappointed', '(>_<)':\n 'annoyed/disappointed', '>_<': 'annoyed/disappointed', '>__<':\n 'annoyed/disappointed', '(>__<)': 'annoyed/disappointed', '(-.-)':\n 'annoyed/disappointed', '(-_-)': 'annoyed/disappointed', '(._.)':\n 'annoyed/disappointed', '/:)': 'annoyed/disappointed', ':-$':\n 'annoyed/disappointed', '>:P': 'annoyed/disappointed', 'K':\n 'annoyed/disappointed', '3:)': 'devilish', '3:-)': 'devilish', '}:-)':\n 'devilish', '}:)': 'devilish', '>:)': 'devilish', 'B-)': 'happy', ':-)':\n 'happy', ':)': 'happy', ':o)': 'happy', ':]': 'happy', ':3': 'happy',\n ':c)': 'happy', ':>': 'happy', '=]': 'happy', '8)': 'happy', '=)':\n 'happy', ':}': 'happy', ':^)': 'happy', ':?)': 'happy', ':-))': 'happy',\n '<:-P': 'happy', '<:P': 'happy', '<:-p': 'happy', '<:p': 'happy', ';;)':\n 'happy', 'J': 'happy', '<3': 'heart', '^5': 'high-five', '>_>^':\n 'high-five', '^<_<': 'high-five', ':*': 'kiss', ':*)': 'kiss', ':^*':\n 'kiss', '}{': 'kiss', \"('}{')\": 'kiss', ':-D': 'laughing', ':D':\n 'laughing', '8-D': 'laughing', '8D': 'laughing', 'x-D': 'laughing',\n 'xD': 'laughing', 'X-D': 'laughing', 'XD': 'laughing', '=-D':\n 'laughing', '=D': 'laughing', ';D': 'laughing', '-3': 'laughing', '3':\n 'laughing', 'B^D': 'laughing', 'D:<': 'laughing', 'D:': 'laughing',\n 'D8': 'laughing', 'D;': 'laughing', 'D=': 'laughing', 'DX': 'laughing',\n ':-B': 'nerd', '8-)': 'nerd', '8)': 'nerd', '</3': 'sad', \":'(\": 'sad',\n \":'-(\": 'sad', 'QQ': 'sad', 'L': 'sad', ':#': 'sealed mouth', ':-#':\n 'sealed mouth', ':-X': 'sealed mouth', ':-x': 'sealed mouth', ':X':\n 'sealed mouth', ':x': 'sealed mouth', '??': 'shooting star', '??':\n 'shooting star', '~?': 'shooting star', '>:O': 'suprprised/shocked',\n '>:o': 'suprprised/shocked', ':-O': 'suprprised/shocked', ':-o':\n 'suprprised/shocked', ':O': 'suprprised/shocked', ':o':\n 'suprprised/shocked', 'O_o': 'suprprised/shocked', 'o_O':\n 'suprprised/shocked', 'O.o': 'suprprised/shocked', 'o.O':\n 'suprprised/shocked', '(O_o)': 'suprprised/shocked', '(o_O)':\n 'suprprised/shocked', '(O.o)': 'suprprised/shocked', '(o.O)':\n 'suprprised/shocked', \":'-)\": 'tears of happines', \":')\":\n 'tears of happines', ':P': 'teasing/playful', ':p': 'teasing/playful',\n '>:P': 'teasing/playful', '>:p': 'teasing/playful', 'X-P':\n 'teasing/playful', 'x-p': 'teasing/playful', 'xp': 'teasing/playful',\n 'XP': 'teasing/playful', ':-P': 'teasing/playful', ':-p':\n 'teasing/playful', '=P': 'teasing/playful', '=P': 'teasing/playful',\n ':-?': 'teasing/playful', ':-b': 'teasing/playful', ':b':\n 'teasing/playful', ';)': 'wink', u'º)': 'wink', ';-)': 'wink', ';]':\n 'wink', u'^Ü^': 'happy'}\nspecial_tokens = EMOTICONS\n<mask token>\nEASY_WORDS = {u'ليا': [(Prefix(u'ل'), u'يا', Suffix(u''))], u'لي': [(Prefix\n (u'ل'), u'ي', Suffix(u''))], u'لكم': [(Prefix(u'ل'), u'كم', Suffix(u'')\n )], u'لكما': [(Prefix(u'ل'), u'كما', Suffix(u''))], u'له': [(Prefix(\n u'ل'), u'ه', Suffix(u''))], u'لها': [(Prefix(u'ل'), u'ها', Suffix(u''))\n ], u'لهم': [(Prefix(u'ل'), u'هم', Suffix(u''))], u'لهما': [(Prefix(u'ل'\n ), u'هما', Suffix(u''))], u'لهن': [(Prefix(u'ل'), u'هم', Suffix(u''))],\n u'بيا': [(Prefix(u'ب'), u'يا', Suffix(u''))], u'بي': [(Prefix(u'ب'),\n u'ي', Suffix(u''))], u'بك': [(Prefix(u'ب'), u'ك', Suffix(u''))], u'بكم':\n [(Prefix(u'ب'), u'كم', Suffix(u''))], u'بكما': [(Prefix(u'ب'), u'كما',\n Suffix(u''))], u'به': [(Prefix(u'ب'), u'ه', Suffix(u''))], u'بها': [(\n Prefix(u'ب'), u'ها', Suffix(u''))], u'بهما': [(Prefix(u'ب'), u'هما',\n Suffix(u''))], u'بهم': [(Prefix(u'ب'), u'هم', Suffix(u''))], u'بهن': [(\n Prefix(u'ب'), u'هن', Suffix(u''))], u'عليا': [(Prefix(u''), u'على',\n Suffix(u'يا'))], u'فيا': [(Prefix(u'ف'), u'يا', Suffix(u''))]}\nEMOTICONS_TAG = 'EMO'\nPUNCTUATION_TAG = 'PUNC'\nDIGIT_TAG = 'CD'\nNOTDEFINED_TAG = 'NN'\n",
"step-3": "import os.path\nPROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))\nEMOTICONS = {'O:)': 'angel', 'o:)': 'angel', 'O:-)': 'angel', 'o:-)':\n 'angel', 'o:-3': 'angel', 'o:3': 'angel', 'O;^)': 'angel', '>:[':\n 'annoyed/disappointed', ':-(': 'annoyed/disappointed', ':(':\n 'annoyed/disappointed', ':((': 'annoyed/disappointed', ':-((':\n 'annoyed/disappointed', ':-c': 'annoyed/disappointed', ':-<':\n 'annoyed/disappointed', ':?C': 'annoyed/disappointed', ':<':\n 'annoyed/disappointed', ':[': 'annoyed/disappointed', ':{':\n 'annoyed/disappointed', ':=||': 'annoyed/disappointed', ':@':\n 'annoyed/disappointed', '>:(': 'annoyed/disappointed', ':/':\n 'annoyed/disappointed', ':\\\\': 'annoyed/disappointed', '=/':\n 'annoyed/disappointed', '=\\\\': 'annoyed/disappointed', '>:/':\n 'annoyed/disappointed', '>:\\\\': 'annoyed/disappointed', ':S':\n 'annoyed/disappointed', ':s': 'annoyed/disappointed', ':-S':\n 'annoyed/disappointed', ':-s': 'annoyed/disappointed', ':|':\n 'annoyed/disappointed', ':-|': 'annoyed/disappointed', ':$':\n 'annoyed/disappointed', '?_?': 'annoyed/disappointed', '(>_<)':\n 'annoyed/disappointed', '>_<': 'annoyed/disappointed', '>__<':\n 'annoyed/disappointed', '(>__<)': 'annoyed/disappointed', '(-.-)':\n 'annoyed/disappointed', '(-_-)': 'annoyed/disappointed', '(._.)':\n 'annoyed/disappointed', '/:)': 'annoyed/disappointed', ':-$':\n 'annoyed/disappointed', '>:P': 'annoyed/disappointed', 'K':\n 'annoyed/disappointed', '3:)': 'devilish', '3:-)': 'devilish', '}:-)':\n 'devilish', '}:)': 'devilish', '>:)': 'devilish', 'B-)': 'happy', ':-)':\n 'happy', ':)': 'happy', ':o)': 'happy', ':]': 'happy', ':3': 'happy',\n ':c)': 'happy', ':>': 'happy', '=]': 'happy', '8)': 'happy', '=)':\n 'happy', ':}': 'happy', ':^)': 'happy', ':?)': 'happy', ':-))': 'happy',\n '<:-P': 'happy', '<:P': 'happy', '<:-p': 'happy', '<:p': 'happy', ';;)':\n 'happy', 'J': 'happy', '<3': 'heart', '^5': 'high-five', '>_>^':\n 'high-five', '^<_<': 'high-five', ':*': 'kiss', ':*)': 'kiss', ':^*':\n 'kiss', '}{': 'kiss', \"('}{')\": 'kiss', ':-D': 'laughing', ':D':\n 'laughing', '8-D': 'laughing', '8D': 'laughing', 'x-D': 'laughing',\n 'xD': 'laughing', 'X-D': 'laughing', 'XD': 'laughing', '=-D':\n 'laughing', '=D': 'laughing', ';D': 'laughing', '-3': 'laughing', '3':\n 'laughing', 'B^D': 'laughing', 'D:<': 'laughing', 'D:': 'laughing',\n 'D8': 'laughing', 'D;': 'laughing', 'D=': 'laughing', 'DX': 'laughing',\n ':-B': 'nerd', '8-)': 'nerd', '8)': 'nerd', '</3': 'sad', \":'(\": 'sad',\n \":'-(\": 'sad', 'QQ': 'sad', 'L': 'sad', ':#': 'sealed mouth', ':-#':\n 'sealed mouth', ':-X': 'sealed mouth', ':-x': 'sealed mouth', ':X':\n 'sealed mouth', ':x': 'sealed mouth', '??': 'shooting star', '??':\n 'shooting star', '~?': 'shooting star', '>:O': 'suprprised/shocked',\n '>:o': 'suprprised/shocked', ':-O': 'suprprised/shocked', ':-o':\n 'suprprised/shocked', ':O': 'suprprised/shocked', ':o':\n 'suprprised/shocked', 'O_o': 'suprprised/shocked', 'o_O':\n 'suprprised/shocked', 'O.o': 'suprprised/shocked', 'o.O':\n 'suprprised/shocked', '(O_o)': 'suprprised/shocked', '(o_O)':\n 'suprprised/shocked', '(O.o)': 'suprprised/shocked', '(o.O)':\n 'suprprised/shocked', \":'-)\": 'tears of happines', \":')\":\n 'tears of happines', ':P': 'teasing/playful', ':p': 'teasing/playful',\n '>:P': 'teasing/playful', '>:p': 'teasing/playful', 'X-P':\n 'teasing/playful', 'x-p': 'teasing/playful', 'xp': 'teasing/playful',\n 'XP': 'teasing/playful', ':-P': 'teasing/playful', ':-p':\n 'teasing/playful', '=P': 'teasing/playful', '=P': 'teasing/playful',\n ':-?': 'teasing/playful', ':-b': 'teasing/playful', ':b':\n 'teasing/playful', ';)': 'wink', u'º)': 'wink', ';-)': 'wink', ';]':\n 'wink', u'^Ü^': 'happy'}\nspecial_tokens = EMOTICONS\nfrom DAPOS.data.variation import Prefix, Suffix\nEASY_WORDS = {u'ليا': [(Prefix(u'ل'), u'يا', Suffix(u''))], u'لي': [(Prefix\n (u'ل'), u'ي', Suffix(u''))], u'لكم': [(Prefix(u'ل'), u'كم', Suffix(u'')\n )], u'لكما': [(Prefix(u'ل'), u'كما', Suffix(u''))], u'له': [(Prefix(\n u'ل'), u'ه', Suffix(u''))], u'لها': [(Prefix(u'ل'), u'ها', Suffix(u''))\n ], u'لهم': [(Prefix(u'ل'), u'هم', Suffix(u''))], u'لهما': [(Prefix(u'ل'\n ), u'هما', Suffix(u''))], u'لهن': [(Prefix(u'ل'), u'هم', Suffix(u''))],\n u'بيا': [(Prefix(u'ب'), u'يا', Suffix(u''))], u'بي': [(Prefix(u'ب'),\n u'ي', Suffix(u''))], u'بك': [(Prefix(u'ب'), u'ك', Suffix(u''))], u'بكم':\n [(Prefix(u'ب'), u'كم', Suffix(u''))], u'بكما': [(Prefix(u'ب'), u'كما',\n Suffix(u''))], u'به': [(Prefix(u'ب'), u'ه', Suffix(u''))], u'بها': [(\n Prefix(u'ب'), u'ها', Suffix(u''))], u'بهما': [(Prefix(u'ب'), u'هما',\n Suffix(u''))], u'بهم': [(Prefix(u'ب'), u'هم', Suffix(u''))], u'بهن': [(\n Prefix(u'ب'), u'هن', Suffix(u''))], u'عليا': [(Prefix(u''), u'على',\n Suffix(u'يا'))], u'فيا': [(Prefix(u'ف'), u'يا', Suffix(u''))]}\nEMOTICONS_TAG = 'EMO'\nPUNCTUATION_TAG = 'PUNC'\nDIGIT_TAG = 'CD'\nNOTDEFINED_TAG = 'NN'\n",
"step-4": "# coding: UTF-8 -*-\nimport os.path\n\nPROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))\n\nEMOTICONS = {\n \"O:)\": \"angel\",\n \"o:)\": \"angel\",\n \"O:-)\": \"angel\",\n \"o:-)\": \"angel\",\n \"o:-3\": \"angel\",\n \"o:3\": \"angel\",\n \"O;^)\": \"angel\",\n \">:[\": \"annoyed/disappointed\",\n \":-(\": \"annoyed/disappointed\",\n \":(\": \"annoyed/disappointed\",\n \":((\": \"annoyed/disappointed\",\n \":-((\": \"annoyed/disappointed\",\n \":-c\": \"annoyed/disappointed\",\n \":-<\": \"annoyed/disappointed\",\n \":?C\": \"annoyed/disappointed\",\n \":<\": \"annoyed/disappointed\",\n \":[\": \"annoyed/disappointed\",\n \":{\": \"annoyed/disappointed\",\n \":=||\": \"annoyed/disappointed\",\n \":@\": \"annoyed/disappointed\",\n \">:(\": \"annoyed/disappointed\",\n \":/\": \"annoyed/disappointed\",\n \":\\\\\": \"annoyed/disappointed\",\n \"=/\": \"annoyed/disappointed\",\n \"=\\\\\": \"annoyed/disappointed\",\n \">:/\": \"annoyed/disappointed\",\n \">:\\\\\": \"annoyed/disappointed\",\n \":S\": \"annoyed/disappointed\",\n \":s\": \"annoyed/disappointed\",\n \":-S\": \"annoyed/disappointed\",\n \":-s\": \"annoyed/disappointed\",\n \":|\": \"annoyed/disappointed\",\n \":-|\": \"annoyed/disappointed\",\n \":$\": \"annoyed/disappointed\",\n \"?_?\": \"annoyed/disappointed\",\n \"(>_<)\": \"annoyed/disappointed\",\n \">_<\": \"annoyed/disappointed\",\n \">__<\": \"annoyed/disappointed\",\n \"(>__<)\": \"annoyed/disappointed\",\n \"(-.-)\": \"annoyed/disappointed\",\n \"(-_-)\": \"annoyed/disappointed\",\n \"(._.)\": \"annoyed/disappointed\",\n \"/:)\": \"annoyed/disappointed\",\n \":-$\": \"annoyed/disappointed\",\n \">:P\": \"annoyed/disappointed\",\n \"K\": \"annoyed/disappointed\",\n \"3:)\": \"devilish\",\n \"3:-)\": \"devilish\",\n \"}:-)\": \"devilish\",\n \"}:)\": \"devilish\",\n \">:)\": \"devilish\",\n \"B-)\": \"happy\",\n \":-)\": \"happy\",\n \":)\": \"happy\",\n \":o)\": \"happy\",\n \":]\": \"happy\",\n \":3\": \"happy\",\n \":c)\": \"happy\",\n \":>\": \"happy\",\n \"=]\": \"happy\",\n \"8)\": \"happy\",\n \"=)\": \"happy\",\n \":}\": \"happy\",\n \":^)\": \"happy\",\n \":?)\": \"happy\",\n \":-))\": \"happy\",\n \"<:-P\": \"happy\",\n \"<:P\": \"happy\",\n \"<:-p\": \"happy\",\n \"<:p\": \"happy\",\n \";;)\": \"happy\",\n \"J\": \"happy\",\n \"<3\": \"heart\",\n \"^5\": \"high-five\",\n \">_>^\": \"high-five\",\n \"^<_<\": \"high-five\",\n \":*\": \"kiss\",\n \":*)\": \"kiss\",\n \":^*\": \"kiss\",\n \"}{\": \"kiss\",\n \"('}{')\": \"kiss\",\n \":-D\": \"laughing\",\n \":D\": \"laughing\",\n \"8-D\": \"laughing\",\n \"8D\": \"laughing\",\n \"x-D\": \"laughing\",\n \"xD\": \"laughing\",\n \"X-D\": \"laughing\",\n \"XD\": \"laughing\",\n \"=-D\": \"laughing\",\n \"=D\": \"laughing\",\n \";D\": \"laughing\",\n \"-3\": \"laughing\",\n \"3\": \"laughing\",\n \"B^D\": \"laughing\",\n \"D:<\": \"laughing\",\n \"D:\": \"laughing\",\n \"D8\": \"laughing\",\n \"D;\": \"laughing\",\n \"D=\": \"laughing\",\n \"DX\": \"laughing\",\n \":-B\": \"nerd\",\n \"8-)\": \"nerd\",\n \"8)\": \"nerd\",\n \"</3\": \"sad\",\n \":'(\": \"sad\",\n \":'-(\": \"sad\",\n \"QQ\": \"sad\",\n \"L\": \"sad\",\n \":#\": \"sealed mouth\",\n \":-#\": \"sealed mouth\",\n \":-X\": \"sealed mouth\",\n \":-x\": \"sealed mouth\",\n \":X\": \"sealed mouth\",\n \":x\": \"sealed mouth\",\n \"??\": \"shooting star\",\n \"??\": \"shooting star\",\n \"~?\": \"shooting star\",\n \">:O\": \"suprprised/shocked\",\n \">:o\": \"suprprised/shocked\",\n \":-O\": \"suprprised/shocked\",\n \":-o\": \"suprprised/shocked\",\n \":O\": \"suprprised/shocked\",\n \":o\": \"suprprised/shocked\",\n \"O_o\": \"suprprised/shocked\",\n \"o_O\": \"suprprised/shocked\",\n \"O.o\": \"suprprised/shocked\",\n \"o.O\": \"suprprised/shocked\",\n \"(O_o)\": \"suprprised/shocked\",\n \"(o_O)\": \"suprprised/shocked\",\n \"(O.o)\": \"suprprised/shocked\",\n \"(o.O)\": \"suprprised/shocked\",\n \":'-)\": \"tears of happines\",\n \":')\": \"tears of happines\",\n \":P\": \"teasing/playful\",\n \":p\": \"teasing/playful\",\n \">:P\": \"teasing/playful\",\n \">:p\": \"teasing/playful\",\n \"X-P\": \"teasing/playful\",\n \"x-p\": \"teasing/playful\",\n \"xp\": \"teasing/playful\",\n \"XP\": \"teasing/playful\",\n \":-P\": \"teasing/playful\",\n \":-p\": \"teasing/playful\",\n \"=P\": \"teasing/playful\",\n \"=P\": \"teasing/playful\",\n \":-?\": \"teasing/playful\",\n \":-b\": \"teasing/playful\",\n \":b\": \"teasing/playful\",\n \";)\": \"wink\",\n u\"º)\": \"wink\",\n \";-)\": \"wink\",\n \";]\": \"wink\",\n u\"^Ü^\": \"happy\",\n}\n\nspecial_tokens = EMOTICONS\n\nfrom DAPOS.data.variation import Prefix, Suffix\n\nEASY_WORDS = {\n u\"ليا\": [(Prefix(u\"ل\"), u\"يا\", Suffix(u\"\"))],\n u\"لي\": [(Prefix(u\"ل\"), u\"ي\", Suffix(u\"\"))],\n u\"لكم\": [(Prefix(u\"ل\"), u\"كم\", Suffix(u\"\"))],\n u\"لكما\": [(Prefix(u\"ل\"), u\"كما\", Suffix(u\"\"))],\n u\"له\": [(Prefix(u\"ل\"), u\"ه\", Suffix(u\"\"))],\n u\"لها\": [(Prefix(u\"ل\"), u\"ها\", Suffix(u\"\"))],\n u\"لهم\": [(Prefix(u\"ل\"), u\"هم\", Suffix(u\"\"))],\n u\"لهما\": [(Prefix(u\"ل\"), u\"هما\", Suffix(u\"\"))],\n u\"لهن\": [(Prefix(u\"ل\"), u\"هم\", Suffix(u\"\"))],\n u\"بيا\": [(Prefix(u\"ب\"), u\"يا\", Suffix(u\"\"))],\n u\"بي\": [(Prefix(u\"ب\"), u\"ي\", Suffix(u\"\"))],\n u\"بك\": [(Prefix(u\"ب\"), u\"ك\", Suffix(u\"\"))],\n u\"بكم\": [(Prefix(u\"ب\"), u\"كم\", Suffix(u\"\"))],\n u\"بكما\": [(Prefix(u\"ب\"), u\"كما\", Suffix(u\"\"))],\n u\"به\": [(Prefix(u\"ب\"), u\"ه\", Suffix(u\"\"))],\n u\"بها\": [(Prefix(u\"ب\"), u\"ها\", Suffix(u\"\"))],\n u\"بهما\": [(Prefix(u\"ب\"), u\"هما\", Suffix(u\"\"))],\n u\"بهم\": [(Prefix(u\"ب\"), u\"هم\", Suffix(u\"\"))],\n u\"بهن\": [(Prefix(u\"ب\"), u\"هن\", Suffix(u\"\"))],\n u\"عليا\": [(Prefix(u\"\"), u\"على\", Suffix(u\"يا\"))],\n u\"فيا\": [(Prefix(u\"ف\"), u\"يا\", Suffix(u\"\"))],\n}\n\n\nEMOTICONS_TAG = 'EMO'\nPUNCTUATION_TAG = 'PUNC'\nDIGIT_TAG = 'CD'\nNOTDEFINED_TAG = 'NN'\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Migration(migrations.Migration):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Migration(migrations.Migration):
dependencies = [('service', '0001_initial')]
operations = [migrations.AlterField(model_name='identification', name=
'id_card_img', field=models.ImageField(blank=True, null=True,
upload_to='images/img_card/')), migrations.AlterField(model_name=
'identification', name='selfie_img', field=models.ImageField(blank=
True, null=True, upload_to='images/img_selfie/'))]
<|reserved_special_token_1|>
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [('service', '0001_initial')]
operations = [migrations.AlterField(model_name='identification', name=
'id_card_img', field=models.ImageField(blank=True, null=True,
upload_to='images/img_card/')), migrations.AlterField(model_name=
'identification', name='selfie_img', field=models.ImageField(blank=
True, null=True, upload_to='images/img_selfie/'))]
<|reserved_special_token_1|>
# Generated by Django 2.2.17 on 2020-12-05 07:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('service', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='identification',
name='id_card_img',
field=models.ImageField(blank=True, null=True, upload_to='images/img_card/'),
),
migrations.AlterField(
model_name='identification',
name='selfie_img',
field=models.ImageField(blank=True, null=True, upload_to='images/img_selfie/'),
),
]
|
flexible
|
{
"blob_id": "b6a0a49e05fbc0ac7673d6c9e8ca4d263c8bb5cd",
"index": 7132,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('service', '0001_initial')]\n operations = [migrations.AlterField(model_name='identification', name=\n 'id_card_img', field=models.ImageField(blank=True, null=True,\n upload_to='images/img_card/')), migrations.AlterField(model_name=\n 'identification', name='selfie_img', field=models.ImageField(blank=\n True, null=True, upload_to='images/img_selfie/'))]\n",
"step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('service', '0001_initial')]\n operations = [migrations.AlterField(model_name='identification', name=\n 'id_card_img', field=models.ImageField(blank=True, null=True,\n upload_to='images/img_card/')), migrations.AlterField(model_name=\n 'identification', name='selfie_img', field=models.ImageField(blank=\n True, null=True, upload_to='images/img_selfie/'))]\n",
"step-5": "# Generated by Django 2.2.17 on 2020-12-05 07:43\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('service', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='identification',\n name='id_card_img',\n field=models.ImageField(blank=True, null=True, upload_to='images/img_card/'),\n ),\n migrations.AlterField(\n model_name='identification',\n name='selfie_img',\n field=models.ImageField(blank=True, null=True, upload_to='images/img_selfie/'),\n ),\n ]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
import utils
from problems_2019 import intcode
def run(commands=None):
memory = utils.get_input()[0]
initial_inputs = intcode.commands_to_input(commands or [])
program = intcode.Program(memory, initial_inputs=initial_inputs, output_mode=intcode.OutputMode.BUFFER)
while True:
_, return_signal = program.run()
for output in program.yield_outputs():
try:
print(chr(output), end='')
except ValueError:
print(output)
if return_signal == intcode.ReturnSignal.AWAITING_INPUT:
# Run in interactive mode if more commands needed
program.add_inputs(*intcode.commands_to_input([input()]))
elif return_signal == intcode.ReturnSignal.RETURN_AND_HALT:
return
else:
raise Exception(f'Unexpected return signal {return_signal}')
@utils.part
def part_1():
commands = [
'south',
'take food ration',
'west',
'north',
'north',
'east',
'take astrolabe',
'west',
'south',
'south',
'east',
'north',
'east',
'south',
'take weather machine',
'west',
'take ornament',
'east',
'north',
'east',
'east',
'east',
'south',
]
run(commands=commands)
|
normal
|
{
"blob_id": "e3aa38b5d01823ed27bca65331e9c7315238750a",
"index": 8974,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\n@utils.part\ndef part_1():\n commands = ['south', 'take food ration', 'west', 'north', 'north',\n 'east', 'take astrolabe', 'west', 'south', 'south', 'east', 'north',\n 'east', 'south', 'take weather machine', 'west', 'take ornament',\n 'east', 'north', 'east', 'east', 'east', 'south']\n run(commands=commands)\n",
"step-3": "<mask token>\n\n\ndef run(commands=None):\n memory = utils.get_input()[0]\n initial_inputs = intcode.commands_to_input(commands or [])\n program = intcode.Program(memory, initial_inputs=initial_inputs,\n output_mode=intcode.OutputMode.BUFFER)\n while True:\n _, return_signal = program.run()\n for output in program.yield_outputs():\n try:\n print(chr(output), end='')\n except ValueError:\n print(output)\n if return_signal == intcode.ReturnSignal.AWAITING_INPUT:\n program.add_inputs(*intcode.commands_to_input([input()]))\n elif return_signal == intcode.ReturnSignal.RETURN_AND_HALT:\n return\n else:\n raise Exception(f'Unexpected return signal {return_signal}')\n\n\n@utils.part\ndef part_1():\n commands = ['south', 'take food ration', 'west', 'north', 'north',\n 'east', 'take astrolabe', 'west', 'south', 'south', 'east', 'north',\n 'east', 'south', 'take weather machine', 'west', 'take ornament',\n 'east', 'north', 'east', 'east', 'east', 'south']\n run(commands=commands)\n",
"step-4": "import utils\nfrom problems_2019 import intcode\n\n\ndef run(commands=None):\n memory = utils.get_input()[0]\n initial_inputs = intcode.commands_to_input(commands or [])\n program = intcode.Program(memory, initial_inputs=initial_inputs,\n output_mode=intcode.OutputMode.BUFFER)\n while True:\n _, return_signal = program.run()\n for output in program.yield_outputs():\n try:\n print(chr(output), end='')\n except ValueError:\n print(output)\n if return_signal == intcode.ReturnSignal.AWAITING_INPUT:\n program.add_inputs(*intcode.commands_to_input([input()]))\n elif return_signal == intcode.ReturnSignal.RETURN_AND_HALT:\n return\n else:\n raise Exception(f'Unexpected return signal {return_signal}')\n\n\n@utils.part\ndef part_1():\n commands = ['south', 'take food ration', 'west', 'north', 'north',\n 'east', 'take astrolabe', 'west', 'south', 'south', 'east', 'north',\n 'east', 'south', 'take weather machine', 'west', 'take ornament',\n 'east', 'north', 'east', 'east', 'east', 'south']\n run(commands=commands)\n",
"step-5": "import utils\n\nfrom problems_2019 import intcode\n\n\ndef run(commands=None):\n memory = utils.get_input()[0]\n initial_inputs = intcode.commands_to_input(commands or [])\n program = intcode.Program(memory, initial_inputs=initial_inputs, output_mode=intcode.OutputMode.BUFFER)\n\n while True:\n _, return_signal = program.run()\n for output in program.yield_outputs():\n try:\n print(chr(output), end='')\n except ValueError:\n print(output)\n\n if return_signal == intcode.ReturnSignal.AWAITING_INPUT:\n # Run in interactive mode if more commands needed\n program.add_inputs(*intcode.commands_to_input([input()]))\n elif return_signal == intcode.ReturnSignal.RETURN_AND_HALT:\n return\n else:\n raise Exception(f'Unexpected return signal {return_signal}')\n\n\n@utils.part\ndef part_1():\n commands = [\n 'south',\n 'take food ration',\n 'west',\n 'north',\n 'north',\n 'east',\n 'take astrolabe',\n 'west',\n 'south',\n 'south',\n 'east',\n 'north',\n 'east',\n 'south',\n 'take weather machine',\n 'west',\n 'take ornament',\n 'east',\n 'north',\n 'east',\n 'east',\n 'east',\n 'south',\n ]\n run(commands=commands)\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
print(tp + (4,))
<|reserved_special_token_1|>
tp = 1, 2, 3
print(tp + (4,))
|
flexible
|
{
"blob_id": "8e9db58488f6ee8aa0d521a19d9d89504d119076",
"index": 6689,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nprint(tp + (4,))\n",
"step-3": "tp = 1, 2, 3\nprint(tp + (4,))\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
<|reserved_special_token_0|>
class TFCompile(TFLayer):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_0|>
class TFComModel(TFModel, TFCompile):
"""
基于TensorFlow的复合模型,即使用一个算子构建模型的和模型的编译
"""
def build_model(self):
raise NotImplementedError
def compile(self):
pass
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class TFCompile(TFLayer):
def compile(self):
raise NotImplementedError
def add_metrics(self, *args, **kwargs):
"""加入模型的评估指标、优化操作等,例如损失值,正确率等张量或者操作
:param args:
:param kwargs:
:return:
"""
metrics = {}
for value in args:
assert isinstance(value, (tf.Operation, tf.Tensor)
), "function add_metrics parameter's value must be tf.Operation"
name = value.name
metrics[name.split(':')[0]] = name
for key, value in kwargs.items():
assert isinstance(value, (tf.Operation, tf.Tensor)
), "function add_metrics parameter's value must be tf.Operation"
metrics[key] = value.name
self.update_metrics(metrics)
@property
def fetches(self):
""" 获取模型输出值或者评估值, 来优化训练模型
:return:
"""
return self.metrics
class TFComModel(TFModel, TFCompile):
"""
基于TensorFlow的复合模型,即使用一个算子构建模型的和模型的编译
"""
def build_model(self):
raise NotImplementedError
def compile(self):
pass
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class TFModel(TFLayer):
<|reserved_special_token_0|>
def add_outputs(self, *args, **kwargs):
"""模型的输出值
:param args:
:param kwargs:
:return:
"""
outputs = {}
for value in args:
assert isinstance(value, tf.Tensor
), "function add_outputs parameter's value must be tf.Tensor"
name = value.name
outputs[name.split(':')[0]] = name
for key, value in kwargs.items():
assert isinstance(value, tf.Tensor
), "function add_outputs parameter's value must be tf.Tensor"
outputs[key] = value.name
self.update_outputs(outputs)
class TFCompile(TFLayer):
def compile(self):
raise NotImplementedError
def add_metrics(self, *args, **kwargs):
"""加入模型的评估指标、优化操作等,例如损失值,正确率等张量或者操作
:param args:
:param kwargs:
:return:
"""
metrics = {}
for value in args:
assert isinstance(value, (tf.Operation, tf.Tensor)
), "function add_metrics parameter's value must be tf.Operation"
name = value.name
metrics[name.split(':')[0]] = name
for key, value in kwargs.items():
assert isinstance(value, (tf.Operation, tf.Tensor)
), "function add_metrics parameter's value must be tf.Operation"
metrics[key] = value.name
self.update_metrics(metrics)
@property
def fetches(self):
""" 获取模型输出值或者评估值, 来优化训练模型
:return:
"""
return self.metrics
class TFComModel(TFModel, TFCompile):
"""
基于TensorFlow的复合模型,即使用一个算子构建模型的和模型的编译
"""
def build_model(self):
raise NotImplementedError
def compile(self):
pass
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class TFModel(TFLayer):
def build_model(self):
raise NotImplementedError
def add_outputs(self, *args, **kwargs):
"""模型的输出值
:param args:
:param kwargs:
:return:
"""
outputs = {}
for value in args:
assert isinstance(value, tf.Tensor
), "function add_outputs parameter's value must be tf.Tensor"
name = value.name
outputs[name.split(':')[0]] = name
for key, value in kwargs.items():
assert isinstance(value, tf.Tensor
), "function add_outputs parameter's value must be tf.Tensor"
outputs[key] = value.name
self.update_outputs(outputs)
class TFCompile(TFLayer):
def compile(self):
raise NotImplementedError
def add_metrics(self, *args, **kwargs):
"""加入模型的评估指标、优化操作等,例如损失值,正确率等张量或者操作
:param args:
:param kwargs:
:return:
"""
metrics = {}
for value in args:
assert isinstance(value, (tf.Operation, tf.Tensor)
), "function add_metrics parameter's value must be tf.Operation"
name = value.name
metrics[name.split(':')[0]] = name
for key, value in kwargs.items():
assert isinstance(value, (tf.Operation, tf.Tensor)
), "function add_metrics parameter's value must be tf.Operation"
metrics[key] = value.name
self.update_metrics(metrics)
@property
def fetches(self):
""" 获取模型输出值或者评估值, 来优化训练模型
:return:
"""
return self.metrics
class TFComModel(TFModel, TFCompile):
"""
基于TensorFlow的复合模型,即使用一个算子构建模型的和模型的编译
"""
def build_model(self):
raise NotImplementedError
def compile(self):
pass
<|reserved_special_token_1|>
#!/usr/bin/env python
# -*- coding:utf-8 _*-
"""
:Author :weijinlong
:Time: :2020/1/10 17:22
:File :graph.py
:content:
"""
import tensorflow as tf
from .base import TFLayer
class TFModel(TFLayer):
def build_model(self):
raise NotImplementedError
def add_outputs(self, *args, **kwargs):
"""模型的输出值
:param args:
:param kwargs:
:return:
"""
outputs = {}
for value in args:
assert isinstance(value, tf.Tensor), "function add_outputs parameter's value must be tf.Tensor"
name = value.name
outputs[name.split(':')[0]] = name
for key, value in kwargs.items():
assert isinstance(value, tf.Tensor), "function add_outputs parameter's value must be tf.Tensor"
outputs[key] = value.name
self.update_outputs(outputs)
class TFCompile(TFLayer):
def compile(self):
raise NotImplementedError
def add_metrics(self, *args, **kwargs):
"""加入模型的评估指标、优化操作等,例如损失值,正确率等张量或者操作
:param args:
:param kwargs:
:return:
"""
metrics = {}
for value in args:
assert isinstance(value, (tf.Operation, tf.Tensor)), \
"function add_metrics parameter's value must be tf.Operation"
name = value.name
metrics[name.split(':')[0]] = name
for key, value in kwargs.items():
assert isinstance(value, (tf.Operation, tf.Tensor)), \
"function add_metrics parameter's value must be tf.Operation"
metrics[key] = value.name
self.update_metrics(metrics)
@property
def fetches(self):
""" 获取模型输出值或者评估值, 来优化训练模型
:return:
"""
return self.metrics
class TFComModel(TFModel, TFCompile):
"""
基于TensorFlow的复合模型,即使用一个算子构建模型的和模型的编译
"""
def build_model(self):
raise NotImplementedError
def compile(self):
pass
|
flexible
|
{
"blob_id": "cdabb4a118cb0ef55c271a446fa190a457ebe142",
"index": 7383,
"step-1": "<mask token>\n\n\nclass TFCompile(TFLayer):\n <mask token>\n <mask token>\n <mask token>\n\n\nclass TFComModel(TFModel, TFCompile):\n \"\"\"\n 基于TensorFlow的复合模型,即使用一个算子构建模型的和模型的编译\n \"\"\"\n\n def build_model(self):\n raise NotImplementedError\n\n def compile(self):\n pass\n",
"step-2": "<mask token>\n\n\nclass TFCompile(TFLayer):\n\n def compile(self):\n raise NotImplementedError\n\n def add_metrics(self, *args, **kwargs):\n \"\"\"加入模型的评估指标、优化操作等,例如损失值,正确率等张量或者操作\n\n :param args:\n :param kwargs:\n :return:\n \"\"\"\n metrics = {}\n for value in args:\n assert isinstance(value, (tf.Operation, tf.Tensor)\n ), \"function add_metrics parameter's value must be tf.Operation\"\n name = value.name\n metrics[name.split(':')[0]] = name\n for key, value in kwargs.items():\n assert isinstance(value, (tf.Operation, tf.Tensor)\n ), \"function add_metrics parameter's value must be tf.Operation\"\n metrics[key] = value.name\n self.update_metrics(metrics)\n\n @property\n def fetches(self):\n \"\"\" 获取模型输出值或者评估值, 来优化训练模型\n\n :return:\n \"\"\"\n return self.metrics\n\n\nclass TFComModel(TFModel, TFCompile):\n \"\"\"\n 基于TensorFlow的复合模型,即使用一个算子构建模型的和模型的编译\n \"\"\"\n\n def build_model(self):\n raise NotImplementedError\n\n def compile(self):\n pass\n",
"step-3": "<mask token>\n\n\nclass TFModel(TFLayer):\n <mask token>\n\n def add_outputs(self, *args, **kwargs):\n \"\"\"模型的输出值\n\n :param args:\n :param kwargs:\n :return:\n \"\"\"\n outputs = {}\n for value in args:\n assert isinstance(value, tf.Tensor\n ), \"function add_outputs parameter's value must be tf.Tensor\"\n name = value.name\n outputs[name.split(':')[0]] = name\n for key, value in kwargs.items():\n assert isinstance(value, tf.Tensor\n ), \"function add_outputs parameter's value must be tf.Tensor\"\n outputs[key] = value.name\n self.update_outputs(outputs)\n\n\nclass TFCompile(TFLayer):\n\n def compile(self):\n raise NotImplementedError\n\n def add_metrics(self, *args, **kwargs):\n \"\"\"加入模型的评估指标、优化操作等,例如损失值,正确率等张量或者操作\n\n :param args:\n :param kwargs:\n :return:\n \"\"\"\n metrics = {}\n for value in args:\n assert isinstance(value, (tf.Operation, tf.Tensor)\n ), \"function add_metrics parameter's value must be tf.Operation\"\n name = value.name\n metrics[name.split(':')[0]] = name\n for key, value in kwargs.items():\n assert isinstance(value, (tf.Operation, tf.Tensor)\n ), \"function add_metrics parameter's value must be tf.Operation\"\n metrics[key] = value.name\n self.update_metrics(metrics)\n\n @property\n def fetches(self):\n \"\"\" 获取模型输出值或者评估值, 来优化训练模型\n\n :return:\n \"\"\"\n return self.metrics\n\n\nclass TFComModel(TFModel, TFCompile):\n \"\"\"\n 基于TensorFlow的复合模型,即使用一个算子构建模型的和模型的编译\n \"\"\"\n\n def build_model(self):\n raise NotImplementedError\n\n def compile(self):\n pass\n",
"step-4": "<mask token>\n\n\nclass TFModel(TFLayer):\n\n def build_model(self):\n raise NotImplementedError\n\n def add_outputs(self, *args, **kwargs):\n \"\"\"模型的输出值\n\n :param args:\n :param kwargs:\n :return:\n \"\"\"\n outputs = {}\n for value in args:\n assert isinstance(value, tf.Tensor\n ), \"function add_outputs parameter's value must be tf.Tensor\"\n name = value.name\n outputs[name.split(':')[0]] = name\n for key, value in kwargs.items():\n assert isinstance(value, tf.Tensor\n ), \"function add_outputs parameter's value must be tf.Tensor\"\n outputs[key] = value.name\n self.update_outputs(outputs)\n\n\nclass TFCompile(TFLayer):\n\n def compile(self):\n raise NotImplementedError\n\n def add_metrics(self, *args, **kwargs):\n \"\"\"加入模型的评估指标、优化操作等,例如损失值,正确率等张量或者操作\n\n :param args:\n :param kwargs:\n :return:\n \"\"\"\n metrics = {}\n for value in args:\n assert isinstance(value, (tf.Operation, tf.Tensor)\n ), \"function add_metrics parameter's value must be tf.Operation\"\n name = value.name\n metrics[name.split(':')[0]] = name\n for key, value in kwargs.items():\n assert isinstance(value, (tf.Operation, tf.Tensor)\n ), \"function add_metrics parameter's value must be tf.Operation\"\n metrics[key] = value.name\n self.update_metrics(metrics)\n\n @property\n def fetches(self):\n \"\"\" 获取模型输出值或者评估值, 来优化训练模型\n\n :return:\n \"\"\"\n return self.metrics\n\n\nclass TFComModel(TFModel, TFCompile):\n \"\"\"\n 基于TensorFlow的复合模型,即使用一个算子构建模型的和模型的编译\n \"\"\"\n\n def build_model(self):\n raise NotImplementedError\n\n def compile(self):\n pass\n",
"step-5": "#!/usr/bin/env python\r\n# -*- coding:utf-8 _*-\r\n\r\n\"\"\"\r\n:Author :weijinlong\r\n:Time: :2020/1/10 17:22\r\n:File :graph.py\r\n:content:\r\n \r\n\"\"\"\r\n\r\nimport tensorflow as tf\r\n\r\nfrom .base import TFLayer\r\n\r\n\r\nclass TFModel(TFLayer):\r\n\r\n def build_model(self):\r\n raise NotImplementedError\r\n\r\n def add_outputs(self, *args, **kwargs):\r\n \"\"\"模型的输出值\r\n\r\n :param args:\r\n :param kwargs:\r\n :return:\r\n \"\"\"\r\n outputs = {}\r\n for value in args:\r\n assert isinstance(value, tf.Tensor), \"function add_outputs parameter's value must be tf.Tensor\"\r\n name = value.name\r\n outputs[name.split(':')[0]] = name\r\n for key, value in kwargs.items():\r\n assert isinstance(value, tf.Tensor), \"function add_outputs parameter's value must be tf.Tensor\"\r\n outputs[key] = value.name\r\n self.update_outputs(outputs)\r\n\r\n\r\nclass TFCompile(TFLayer):\r\n\r\n def compile(self):\r\n raise NotImplementedError\r\n\r\n def add_metrics(self, *args, **kwargs):\r\n \"\"\"加入模型的评估指标、优化操作等,例如损失值,正确率等张量或者操作\r\n\r\n :param args:\r\n :param kwargs:\r\n :return:\r\n \"\"\"\r\n metrics = {}\r\n for value in args:\r\n assert isinstance(value, (tf.Operation, tf.Tensor)), \\\r\n \"function add_metrics parameter's value must be tf.Operation\"\r\n name = value.name\r\n metrics[name.split(':')[0]] = name\r\n for key, value in kwargs.items():\r\n assert isinstance(value, (tf.Operation, tf.Tensor)), \\\r\n \"function add_metrics parameter's value must be tf.Operation\"\r\n metrics[key] = value.name\r\n self.update_metrics(metrics)\r\n\r\n @property\r\n def fetches(self):\r\n \"\"\" 获取模型输出值或者评估值, 来优化训练模型\r\n\r\n :return:\r\n \"\"\"\r\n return self.metrics\r\n\r\n\r\nclass TFComModel(TFModel, TFCompile):\r\n \"\"\"\r\n 基于TensorFlow的复合模型,即使用一个算子构建模型的和模型的编译\r\n \"\"\"\r\n\r\n def build_model(self):\r\n raise NotImplementedError\r\n\r\n def compile(self):\r\n pass\r\n",
"step-ids": [
5,
8,
10,
11,
13
]
}
|
[
5,
8,
10,
11,
13
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
for video_id in list_video_id:
url = ('https://www.googleapis.com/youtube/v3/videos?id=' + video_id +
'&part=statistics&key=' + API_KEY)
response = requests.get(url).json()
for i in response['items']:
rows.append({'videoid': i['id'], 'viewCount': i['statistics'][
'viewCount'], 'likeCount': i['statistics']['likeCount'],
'dislikeCount': i['statistics']['dislikeCount'],
'favoriteCount': i['statistics']['favoriteCount'],
'commentCount': i['statistics']['commentCount']})
print(rows)
with open('get_api_youtube.csv', 'w', encoding='UTF8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for j in rows:
writer.writerow(j)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
API_KEY = 'AIzaSyALrKc3-W0u_Ku-J2OpyjnqFhV5wKlwKGs'
list_video_id = ['7cmvABXyUC0', '9eH-7x7swEM', 'JndzGxbwvG0', 'l0P5_E6J_g0']
fieldnames = ['videoid', 'viewCount', 'likeCount', 'dislikeCount',
'favoriteCount', 'commentCount']
rows = []
for video_id in list_video_id:
url = ('https://www.googleapis.com/youtube/v3/videos?id=' + video_id +
'&part=statistics&key=' + API_KEY)
response = requests.get(url).json()
for i in response['items']:
rows.append({'videoid': i['id'], 'viewCount': i['statistics'][
'viewCount'], 'likeCount': i['statistics']['likeCount'],
'dislikeCount': i['statistics']['dislikeCount'],
'favoriteCount': i['statistics']['favoriteCount'],
'commentCount': i['statistics']['commentCount']})
print(rows)
with open('get_api_youtube.csv', 'w', encoding='UTF8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for j in rows:
writer.writerow(j)
<|reserved_special_token_1|>
import requests
import json, csv
import pandas as pd
API_KEY = 'AIzaSyALrKc3-W0u_Ku-J2OpyjnqFhV5wKlwKGs'
list_video_id = ['7cmvABXyUC0', '9eH-7x7swEM', 'JndzGxbwvG0', 'l0P5_E6J_g0']
fieldnames = ['videoid', 'viewCount', 'likeCount', 'dislikeCount',
'favoriteCount', 'commentCount']
rows = []
for video_id in list_video_id:
url = ('https://www.googleapis.com/youtube/v3/videos?id=' + video_id +
'&part=statistics&key=' + API_KEY)
response = requests.get(url).json()
for i in response['items']:
rows.append({'videoid': i['id'], 'viewCount': i['statistics'][
'viewCount'], 'likeCount': i['statistics']['likeCount'],
'dislikeCount': i['statistics']['dislikeCount'],
'favoriteCount': i['statistics']['favoriteCount'],
'commentCount': i['statistics']['commentCount']})
print(rows)
with open('get_api_youtube.csv', 'w', encoding='UTF8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for j in rows:
writer.writerow(j)
<|reserved_special_token_1|>
import requests
import json, csv
import pandas as pd
API_KEY = 'AIzaSyALrKc3-W0u_Ku-J2OpyjnqFhV5wKlwKGs'
list_video_id = ['7cmvABXyUC0', '9eH-7x7swEM', 'JndzGxbwvG0', 'l0P5_E6J_g0']
fieldnames = ['videoid', 'viewCount', 'likeCount', 'dislikeCount', 'favoriteCount', 'commentCount']
rows = []
for video_id in list_video_id:
url = "https://www.googleapis.com/youtube/v3/videos?id=" + video_id + "&part=statistics&key=" + API_KEY
response = requests.get(url).json()
for i in response['items']:
rows.append({"videoid": i['id'],
"viewCount": i['statistics']['viewCount'],
"likeCount": i['statistics']['likeCount'],
"dislikeCount": i['statistics']['dislikeCount'],
"favoriteCount": i['statistics']['favoriteCount'],
"commentCount": i['statistics']['commentCount']})
print(rows)
with open(r'get_api_youtube.csv', 'w', encoding='UTF8', newline='') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for j in rows:
writer.writerow(j)
|
flexible
|
{
"blob_id": "3c341b17f260cc745c8659ee769493216522ac19",
"index": 2073,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nfor video_id in list_video_id:\n url = ('https://www.googleapis.com/youtube/v3/videos?id=' + video_id +\n '&part=statistics&key=' + API_KEY)\n response = requests.get(url).json()\n for i in response['items']:\n rows.append({'videoid': i['id'], 'viewCount': i['statistics'][\n 'viewCount'], 'likeCount': i['statistics']['likeCount'],\n 'dislikeCount': i['statistics']['dislikeCount'],\n 'favoriteCount': i['statistics']['favoriteCount'],\n 'commentCount': i['statistics']['commentCount']})\nprint(rows)\nwith open('get_api_youtube.csv', 'w', encoding='UTF8', newline='') as f:\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n writer.writeheader()\n for j in rows:\n writer.writerow(j)\n",
"step-3": "<mask token>\nAPI_KEY = 'AIzaSyALrKc3-W0u_Ku-J2OpyjnqFhV5wKlwKGs'\nlist_video_id = ['7cmvABXyUC0', '9eH-7x7swEM', 'JndzGxbwvG0', 'l0P5_E6J_g0']\nfieldnames = ['videoid', 'viewCount', 'likeCount', 'dislikeCount',\n 'favoriteCount', 'commentCount']\nrows = []\nfor video_id in list_video_id:\n url = ('https://www.googleapis.com/youtube/v3/videos?id=' + video_id +\n '&part=statistics&key=' + API_KEY)\n response = requests.get(url).json()\n for i in response['items']:\n rows.append({'videoid': i['id'], 'viewCount': i['statistics'][\n 'viewCount'], 'likeCount': i['statistics']['likeCount'],\n 'dislikeCount': i['statistics']['dislikeCount'],\n 'favoriteCount': i['statistics']['favoriteCount'],\n 'commentCount': i['statistics']['commentCount']})\nprint(rows)\nwith open('get_api_youtube.csv', 'w', encoding='UTF8', newline='') as f:\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n writer.writeheader()\n for j in rows:\n writer.writerow(j)\n",
"step-4": "import requests\nimport json, csv\nimport pandas as pd\nAPI_KEY = 'AIzaSyALrKc3-W0u_Ku-J2OpyjnqFhV5wKlwKGs'\nlist_video_id = ['7cmvABXyUC0', '9eH-7x7swEM', 'JndzGxbwvG0', 'l0P5_E6J_g0']\nfieldnames = ['videoid', 'viewCount', 'likeCount', 'dislikeCount',\n 'favoriteCount', 'commentCount']\nrows = []\nfor video_id in list_video_id:\n url = ('https://www.googleapis.com/youtube/v3/videos?id=' + video_id +\n '&part=statistics&key=' + API_KEY)\n response = requests.get(url).json()\n for i in response['items']:\n rows.append({'videoid': i['id'], 'viewCount': i['statistics'][\n 'viewCount'], 'likeCount': i['statistics']['likeCount'],\n 'dislikeCount': i['statistics']['dislikeCount'],\n 'favoriteCount': i['statistics']['favoriteCount'],\n 'commentCount': i['statistics']['commentCount']})\nprint(rows)\nwith open('get_api_youtube.csv', 'w', encoding='UTF8', newline='') as f:\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n writer.writeheader()\n for j in rows:\n writer.writerow(j)\n",
"step-5": "import requests\nimport json, csv\nimport pandas as pd\n\nAPI_KEY = 'AIzaSyALrKc3-W0u_Ku-J2OpyjnqFhV5wKlwKGs'\nlist_video_id = ['7cmvABXyUC0', '9eH-7x7swEM', 'JndzGxbwvG0', 'l0P5_E6J_g0']\nfieldnames = ['videoid', 'viewCount', 'likeCount', 'dislikeCount', 'favoriteCount', 'commentCount']\nrows = []\nfor video_id in list_video_id:\n url = \"https://www.googleapis.com/youtube/v3/videos?id=\" + video_id + \"&part=statistics&key=\" + API_KEY\n response = requests.get(url).json()\n for i in response['items']:\n rows.append({\"videoid\": i['id'],\n \"viewCount\": i['statistics']['viewCount'],\n \"likeCount\": i['statistics']['likeCount'],\n \"dislikeCount\": i['statistics']['dislikeCount'],\n \"favoriteCount\": i['statistics']['favoriteCount'],\n \"commentCount\": i['statistics']['commentCount']})\nprint(rows)\nwith open(r'get_api_youtube.csv', 'w', encoding='UTF8', newline='') as f:\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n writer.writeheader()\n for j in rows:\n writer.writerow(j)\n\n\n\n\n\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
def is_bad_version(v):
return version_api.is_bad(v)
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def is_bad_version(v):
return version_api.is_bad(v)
def first_bad_version(n):
version_api.n = n
api_calls_count = 0
left, right = 1, n
while left < right:
mid = (left + right) // 2
is_bad = is_bad_version(mid)
api_calls_count += 1
if is_bad:
right = mid
else:
left = mid + 1
return left, api_calls_count
<|reserved_special_token_1|>
<|reserved_special_token_0|>
version_api = api(0)
def is_bad_version(v):
return version_api.is_bad(v)
def first_bad_version(n):
version_api.n = n
api_calls_count = 0
left, right = 1, n
while left < right:
mid = (left + right) // 2
is_bad = is_bad_version(mid)
api_calls_count += 1
if is_bad:
right = mid
else:
left = mid + 1
return left, api_calls_count
<|reserved_special_token_1|>
from api import *
version_api = api(0)
def is_bad_version(v):
return version_api.is_bad(v)
def first_bad_version(n):
version_api.n = n
api_calls_count = 0
left, right = 1, n
while left < right:
mid = (left + right) // 2
is_bad = is_bad_version(mid)
api_calls_count += 1
if is_bad:
right = mid
else:
left = mid + 1
return left, api_calls_count
<|reserved_special_token_1|>
from api import *
version_api = api(0)
def is_bad_version(v):
return version_api.is_bad(v)
def first_bad_version(n):
# -- DO NOT CHANGE THIS SECTION
version_api.n = n
# --
api_calls_count = 0
left, right = 1, n
while left < right:
mid = (left + right) // 2
is_bad = is_bad_version(mid)
api_calls_count += 1
if is_bad:
right = mid
else:
left = mid + 1
return left, api_calls_count
|
flexible
|
{
"blob_id": "df4c03d9faedf2d347593825c7221937a75a9c10",
"index": 5360,
"step-1": "<mask token>\n\n\ndef is_bad_version(v):\n return version_api.is_bad(v)\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef is_bad_version(v):\n return version_api.is_bad(v)\n\n\ndef first_bad_version(n):\n version_api.n = n\n api_calls_count = 0\n left, right = 1, n\n while left < right:\n mid = (left + right) // 2\n is_bad = is_bad_version(mid)\n api_calls_count += 1\n if is_bad:\n right = mid\n else:\n left = mid + 1\n return left, api_calls_count\n",
"step-3": "<mask token>\nversion_api = api(0)\n\n\ndef is_bad_version(v):\n return version_api.is_bad(v)\n\n\ndef first_bad_version(n):\n version_api.n = n\n api_calls_count = 0\n left, right = 1, n\n while left < right:\n mid = (left + right) // 2\n is_bad = is_bad_version(mid)\n api_calls_count += 1\n if is_bad:\n right = mid\n else:\n left = mid + 1\n return left, api_calls_count\n",
"step-4": "from api import *\nversion_api = api(0)\n\n\ndef is_bad_version(v):\n return version_api.is_bad(v)\n\n\ndef first_bad_version(n):\n version_api.n = n\n api_calls_count = 0\n left, right = 1, n\n while left < right:\n mid = (left + right) // 2\n is_bad = is_bad_version(mid)\n api_calls_count += 1\n if is_bad:\n right = mid\n else:\n left = mid + 1\n return left, api_calls_count\n",
"step-5": "from api import *\n\nversion_api = api(0)\n\ndef is_bad_version(v):\n return version_api.is_bad(v)\n\ndef first_bad_version(n):\n# -- DO NOT CHANGE THIS SECTION\n version_api.n = n\n# --\n api_calls_count = 0\n\n left, right = 1, n\n while left < right:\n mid = (left + right) // 2\n\n is_bad = is_bad_version(mid)\n api_calls_count += 1\n\n if is_bad:\n right = mid\n else:\n left = mid + 1\n\n\n return left, api_calls_count\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
__title__ = 'pyaddepar'
__version__ = '0.6.0'
__author__ = 'Thomas Schmelzer'
__license__ = 'MIT'
__copyright__ = 'Copyright 2019 by Lobnek Wealth Management'
|
normal
|
{
"blob_id": "cc985ae061c04696dbf5114273befd62321756ae",
"index": 9569,
"step-1": "<mask token>\n",
"step-2": "__title__ = 'pyaddepar'\n__version__ = '0.6.0'\n__author__ = 'Thomas Schmelzer'\n__license__ = 'MIT'\n__copyright__ = 'Copyright 2019 by Lobnek Wealth Management'\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
}
|
[
0,
1
] |
<|reserved_special_token_0|>
def tf_idf(words):
word_dict = {}
for w in words:
if w in word_dict.keys():
word_dict[w] += 1
else:
word_dict[w] = 1
max_freq = max(word_dict.values())
for w in words:
word_dict[w] = word_dict[w] / max_freq * math.log(N / n_dict[w], 2)
a = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)
return a[:200]
<|reserved_special_token_0|>
def user_prof(b_list):
u_profile_words = []
for b in b_list:
u_profile_words.extend(b_profile_dict[b])
return list(set(u_profile_words))
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def tf_idf(words):
word_dict = {}
for w in words:
if w in word_dict.keys():
word_dict[w] += 1
else:
word_dict[w] = 1
max_freq = max(word_dict.values())
for w in words:
word_dict[w] = word_dict[w] / max_freq * math.log(N / n_dict[w], 2)
a = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)
return a[:200]
<|reserved_special_token_0|>
def user_prof(b_list):
u_profile_words = []
for b in b_list:
u_profile_words.extend(b_profile_dict[b])
return list(set(u_profile_words))
<|reserved_special_token_0|>
for user, u_vector in dict(user_profile.collect()).items():
f.write(json.dumps({'id': user, 'type': 'user', 'vector': u_vector}))
f.write('\n')
for business, b_vector in b_profile_dict.items():
f.write(json.dumps({'id': business, 'type': 'business', 'vector':
b_vector}))
f.write('\n')
<|reserved_special_token_0|>
print('Duration:', duration)
<|reserved_special_token_1|>
<|reserved_special_token_0|>
start_time = datetime.now()
input_file = argv[1]
model_file = argv[2]
stopwords = argv[3]
sc = SparkContext(appName='inf553')
lines = sc.textFile(input_file).map(lambda x: json.loads(x))
stopwords = sc.textFile(stopwords).map(lambda x: (x, 1))
def tf_idf(words):
word_dict = {}
for w in words:
if w in word_dict.keys():
word_dict[w] += 1
else:
word_dict[w] = 1
max_freq = max(word_dict.values())
for w in words:
word_dict[w] = word_dict[w] / max_freq * math.log(N / n_dict[w], 2)
a = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)
return a[:200]
b_text = lines.map(lambda x: (x['business_id'], x['text'])).groupByKey().map(
lambda x: (x[0], list(x[1]))).map(lambda x: (x[0], str(x[1]).replace(
"!'", ''))).map(lambda x: (x[0], x[1].replace(".'", ''))).map(lambda x:
(x[0], x[1].replace(", '", ''))).map(lambda x: (x[0], x[1].replace(
'\\n', ''))).map(lambda x: (x[0], x[1].replace("\\'", "'"))).map(lambda
x: (x[0], re.sub('[{}+=~*%#$@(\\-/[,.!?&:;\\]0-9)"]', ' ', str(x[1]).
lower()))).mapValues(lambda x: x.split())
total_words_num = b_text.flatMap(lambda x: x[1]).count()
rare_words = b_text.flatMap(lambda x: x[1]).map(lambda x: (x, 1)).reduceByKey(
lambda x, y: x + y).filter(lambda x: x[1] < total_words_num * 1e-06).map(
lambda x: (x[0], 1))
b_unset_words = b_text.flatMap(lambda x: [(word, x[0]) for word in x[1]]
).subtractByKey(rare_words).subtractByKey(stopwords)
n = b_unset_words.groupByKey().map(lambda x: (x[0], len(set(x[1]))))
n_dict = dict(n.collect())
N = b_text = lines.map(lambda x: x['business_id']).distinct().count()
b_profile = b_unset_words.map(lambda x: (x[1], x[0])).groupByKey().map(lambda
x: (x[0], list(x[1]))).map(lambda x: (x[0], tf_idf(x[1]))).map(lambda x:
(x[0], [word[0] for word in x[1]]))
words_list = b_profile.flatMap(lambda x: x[1]).distinct().collect()
words = dict([(word, ind) for ind, word in enumerate(words_list)])
b_profile2 = b_profile.map(lambda x: (x[0], [words[word_ind] for word_ind in
x[1]]))
b_profile_dict = dict(b_profile2.collect())
def user_prof(b_list):
u_profile_words = []
for b in b_list:
u_profile_words.extend(b_profile_dict[b])
return list(set(u_profile_words))
user_profile = lines.map(lambda x: (x['user_id'], x['business_id'])
).groupByKey().map(lambda x: (x[0], list(x[1]))).map(lambda x: (x[0],
user_prof(x[1])))
f = open(model_file, 'w')
for user, u_vector in dict(user_profile.collect()).items():
f.write(json.dumps({'id': user, 'type': 'user', 'vector': u_vector}))
f.write('\n')
for business, b_vector in b_profile_dict.items():
f.write(json.dumps({'id': business, 'type': 'business', 'vector':
b_vector}))
f.write('\n')
end_time = datetime.now()
duration = end_time - start_time
print('Duration:', duration)
<|reserved_special_token_1|>
from sys import argv
from pyspark import SparkContext
import json
import re
import math
from _datetime import datetime
start_time = datetime.now()
input_file = argv[1]
model_file = argv[2]
stopwords = argv[3]
sc = SparkContext(appName='inf553')
lines = sc.textFile(input_file).map(lambda x: json.loads(x))
stopwords = sc.textFile(stopwords).map(lambda x: (x, 1))
def tf_idf(words):
word_dict = {}
for w in words:
if w in word_dict.keys():
word_dict[w] += 1
else:
word_dict[w] = 1
max_freq = max(word_dict.values())
for w in words:
word_dict[w] = word_dict[w] / max_freq * math.log(N / n_dict[w], 2)
a = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)
return a[:200]
b_text = lines.map(lambda x: (x['business_id'], x['text'])).groupByKey().map(
lambda x: (x[0], list(x[1]))).map(lambda x: (x[0], str(x[1]).replace(
"!'", ''))).map(lambda x: (x[0], x[1].replace(".'", ''))).map(lambda x:
(x[0], x[1].replace(", '", ''))).map(lambda x: (x[0], x[1].replace(
'\\n', ''))).map(lambda x: (x[0], x[1].replace("\\'", "'"))).map(lambda
x: (x[0], re.sub('[{}+=~*%#$@(\\-/[,.!?&:;\\]0-9)"]', ' ', str(x[1]).
lower()))).mapValues(lambda x: x.split())
total_words_num = b_text.flatMap(lambda x: x[1]).count()
rare_words = b_text.flatMap(lambda x: x[1]).map(lambda x: (x, 1)).reduceByKey(
lambda x, y: x + y).filter(lambda x: x[1] < total_words_num * 1e-06).map(
lambda x: (x[0], 1))
b_unset_words = b_text.flatMap(lambda x: [(word, x[0]) for word in x[1]]
).subtractByKey(rare_words).subtractByKey(stopwords)
n = b_unset_words.groupByKey().map(lambda x: (x[0], len(set(x[1]))))
n_dict = dict(n.collect())
N = b_text = lines.map(lambda x: x['business_id']).distinct().count()
b_profile = b_unset_words.map(lambda x: (x[1], x[0])).groupByKey().map(lambda
x: (x[0], list(x[1]))).map(lambda x: (x[0], tf_idf(x[1]))).map(lambda x:
(x[0], [word[0] for word in x[1]]))
words_list = b_profile.flatMap(lambda x: x[1]).distinct().collect()
words = dict([(word, ind) for ind, word in enumerate(words_list)])
b_profile2 = b_profile.map(lambda x: (x[0], [words[word_ind] for word_ind in
x[1]]))
b_profile_dict = dict(b_profile2.collect())
def user_prof(b_list):
u_profile_words = []
for b in b_list:
u_profile_words.extend(b_profile_dict[b])
return list(set(u_profile_words))
user_profile = lines.map(lambda x: (x['user_id'], x['business_id'])
).groupByKey().map(lambda x: (x[0], list(x[1]))).map(lambda x: (x[0],
user_prof(x[1])))
f = open(model_file, 'w')
for user, u_vector in dict(user_profile.collect()).items():
f.write(json.dumps({'id': user, 'type': 'user', 'vector': u_vector}))
f.write('\n')
for business, b_vector in b_profile_dict.items():
f.write(json.dumps({'id': business, 'type': 'business', 'vector':
b_vector}))
f.write('\n')
end_time = datetime.now()
duration = end_time - start_time
print('Duration:', duration)
<|reserved_special_token_1|>
from sys import argv
from pyspark import SparkContext
import json
import re
import math
from _datetime import datetime
start_time = datetime.now()
input_file = argv[1]
model_file = argv[2]
stopwords = argv[3]
sc = SparkContext(appName='inf553')
lines = sc.textFile(input_file).map(lambda x: json.loads(x))
stopwords = sc.textFile(stopwords).map(lambda x: (x, 1))
def tf_idf(words):
word_dict = {}
for w in words:
if w in word_dict.keys():
word_dict[w] += 1
else:
word_dict[w] = 1
max_freq = max(word_dict.values())
for w in words:
word_dict[w] = (word_dict[w] / max_freq) * math.log((N / n_dict[w]), 2)
a = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)
return a[:200]
b_text = lines.map(lambda x: (x['business_id'], x['text']))\
.groupByKey().map(lambda x: (x[0], list(x[1])))\
.map(lambda x: (x[0], str(x[1]).replace('!\'', '')))\
.map(lambda x: (x[0], x[1].replace('.\'', ''))) \
.map(lambda x: (x[0], x[1].replace(', \'', ''))) \
.map(lambda x: (x[0], x[1].replace('\\n',''))) \
.map(lambda x: (x[0], x[1].replace('\\\'',"'")))\
.map(lambda x: (x[0], re.sub('[{}+=~*%#$@(\-/[,.!?&:;\]0-9)"]', ' ', str(x[1]).lower()))) \
.mapValues(lambda x: x.split())
total_words_num = b_text.flatMap(lambda x: x[1]).count()
rare_words = b_text.flatMap(lambda x: x[1])\
.map(lambda x: (x, 1))\
.reduceByKey(lambda x, y: x+y)\
.filter(lambda x: x[1] < total_words_num * 0.000001)\
.map(lambda x: (x[0], 1))
b_unset_words = b_text.flatMap(lambda x: [(word, x[0]) for word in x[1]])\
.subtractByKey(rare_words)\
.subtractByKey(stopwords)
n = b_unset_words.groupByKey()\
.map(lambda x: (x[0], len(set(x[1]))))
n_dict = dict(n.collect())
N = b_text = lines.map(lambda x: (x['business_id'])).distinct().count()
b_profile = b_unset_words.map(lambda x: (x[1], x[0]))\
.groupByKey().map(lambda x: (x[0], list(x[1])))\
.map(lambda x: (x[0], tf_idf(x[1]))) \
.map(lambda x: (x[0], [word[0] for word in x[1]]))
words_list = b_profile.flatMap(lambda x: x[1]).distinct().collect()
words = dict([(word, ind) for ind, word in enumerate(words_list)])
b_profile2 = b_profile.map(lambda x: (x[0], [words[word_ind] for word_ind in x[1]]))
b_profile_dict = dict(b_profile2.collect())
def user_prof(b_list):
u_profile_words =[]
for b in b_list:
u_profile_words.extend(b_profile_dict[b])
return list(set(u_profile_words))
user_profile = lines.map(lambda x: (x['user_id'], x['business_id']))\
.groupByKey().map(lambda x: (x[0], list(x[1])))\
.map(lambda x: (x[0], user_prof(x[1])))
f = open(model_file, "w")
for user, u_vector in dict(user_profile.collect()).items():
f.write(json.dumps({"id": user, "type": "user", "vector": u_vector}))
f.write('\n')
for business, b_vector in b_profile_dict.items():
f.write(json.dumps({"id": business, "type": "business", "vector": b_vector}))
f.write('\n')
end_time = datetime.now()
duration = end_time - start_time
print("Duration:", duration)
|
flexible
|
{
"blob_id": "e877f16e604682488d85142174ce4f3f6cee3f18",
"index": 7882,
"step-1": "<mask token>\n\n\ndef tf_idf(words):\n word_dict = {}\n for w in words:\n if w in word_dict.keys():\n word_dict[w] += 1\n else:\n word_dict[w] = 1\n max_freq = max(word_dict.values())\n for w in words:\n word_dict[w] = word_dict[w] / max_freq * math.log(N / n_dict[w], 2)\n a = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)\n return a[:200]\n\n\n<mask token>\n\n\ndef user_prof(b_list):\n u_profile_words = []\n for b in b_list:\n u_profile_words.extend(b_profile_dict[b])\n return list(set(u_profile_words))\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef tf_idf(words):\n word_dict = {}\n for w in words:\n if w in word_dict.keys():\n word_dict[w] += 1\n else:\n word_dict[w] = 1\n max_freq = max(word_dict.values())\n for w in words:\n word_dict[w] = word_dict[w] / max_freq * math.log(N / n_dict[w], 2)\n a = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)\n return a[:200]\n\n\n<mask token>\n\n\ndef user_prof(b_list):\n u_profile_words = []\n for b in b_list:\n u_profile_words.extend(b_profile_dict[b])\n return list(set(u_profile_words))\n\n\n<mask token>\nfor user, u_vector in dict(user_profile.collect()).items():\n f.write(json.dumps({'id': user, 'type': 'user', 'vector': u_vector}))\n f.write('\\n')\nfor business, b_vector in b_profile_dict.items():\n f.write(json.dumps({'id': business, 'type': 'business', 'vector':\n b_vector}))\n f.write('\\n')\n<mask token>\nprint('Duration:', duration)\n",
"step-3": "<mask token>\nstart_time = datetime.now()\ninput_file = argv[1]\nmodel_file = argv[2]\nstopwords = argv[3]\nsc = SparkContext(appName='inf553')\nlines = sc.textFile(input_file).map(lambda x: json.loads(x))\nstopwords = sc.textFile(stopwords).map(lambda x: (x, 1))\n\n\ndef tf_idf(words):\n word_dict = {}\n for w in words:\n if w in word_dict.keys():\n word_dict[w] += 1\n else:\n word_dict[w] = 1\n max_freq = max(word_dict.values())\n for w in words:\n word_dict[w] = word_dict[w] / max_freq * math.log(N / n_dict[w], 2)\n a = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)\n return a[:200]\n\n\nb_text = lines.map(lambda x: (x['business_id'], x['text'])).groupByKey().map(\n lambda x: (x[0], list(x[1]))).map(lambda x: (x[0], str(x[1]).replace(\n \"!'\", ''))).map(lambda x: (x[0], x[1].replace(\".'\", ''))).map(lambda x:\n (x[0], x[1].replace(\", '\", ''))).map(lambda x: (x[0], x[1].replace(\n '\\\\n', ''))).map(lambda x: (x[0], x[1].replace(\"\\\\'\", \"'\"))).map(lambda\n x: (x[0], re.sub('[{}+=~*%#$@(\\\\-/[,.!?&:;\\\\]0-9)\"]', ' ', str(x[1]).\n lower()))).mapValues(lambda x: x.split())\ntotal_words_num = b_text.flatMap(lambda x: x[1]).count()\nrare_words = b_text.flatMap(lambda x: x[1]).map(lambda x: (x, 1)).reduceByKey(\n lambda x, y: x + y).filter(lambda x: x[1] < total_words_num * 1e-06).map(\n lambda x: (x[0], 1))\nb_unset_words = b_text.flatMap(lambda x: [(word, x[0]) for word in x[1]]\n ).subtractByKey(rare_words).subtractByKey(stopwords)\nn = b_unset_words.groupByKey().map(lambda x: (x[0], len(set(x[1]))))\nn_dict = dict(n.collect())\nN = b_text = lines.map(lambda x: x['business_id']).distinct().count()\nb_profile = b_unset_words.map(lambda x: (x[1], x[0])).groupByKey().map(lambda\n x: (x[0], list(x[1]))).map(lambda x: (x[0], tf_idf(x[1]))).map(lambda x:\n (x[0], [word[0] for word in x[1]]))\nwords_list = b_profile.flatMap(lambda x: x[1]).distinct().collect()\nwords = dict([(word, ind) for ind, word in enumerate(words_list)])\nb_profile2 = b_profile.map(lambda x: (x[0], [words[word_ind] for word_ind in\n x[1]]))\nb_profile_dict = dict(b_profile2.collect())\n\n\ndef user_prof(b_list):\n u_profile_words = []\n for b in b_list:\n u_profile_words.extend(b_profile_dict[b])\n return list(set(u_profile_words))\n\n\nuser_profile = lines.map(lambda x: (x['user_id'], x['business_id'])\n ).groupByKey().map(lambda x: (x[0], list(x[1]))).map(lambda x: (x[0],\n user_prof(x[1])))\nf = open(model_file, 'w')\nfor user, u_vector in dict(user_profile.collect()).items():\n f.write(json.dumps({'id': user, 'type': 'user', 'vector': u_vector}))\n f.write('\\n')\nfor business, b_vector in b_profile_dict.items():\n f.write(json.dumps({'id': business, 'type': 'business', 'vector':\n b_vector}))\n f.write('\\n')\nend_time = datetime.now()\nduration = end_time - start_time\nprint('Duration:', duration)\n",
"step-4": "from sys import argv\nfrom pyspark import SparkContext\nimport json\nimport re\nimport math\nfrom _datetime import datetime\nstart_time = datetime.now()\ninput_file = argv[1]\nmodel_file = argv[2]\nstopwords = argv[3]\nsc = SparkContext(appName='inf553')\nlines = sc.textFile(input_file).map(lambda x: json.loads(x))\nstopwords = sc.textFile(stopwords).map(lambda x: (x, 1))\n\n\ndef tf_idf(words):\n word_dict = {}\n for w in words:\n if w in word_dict.keys():\n word_dict[w] += 1\n else:\n word_dict[w] = 1\n max_freq = max(word_dict.values())\n for w in words:\n word_dict[w] = word_dict[w] / max_freq * math.log(N / n_dict[w], 2)\n a = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)\n return a[:200]\n\n\nb_text = lines.map(lambda x: (x['business_id'], x['text'])).groupByKey().map(\n lambda x: (x[0], list(x[1]))).map(lambda x: (x[0], str(x[1]).replace(\n \"!'\", ''))).map(lambda x: (x[0], x[1].replace(\".'\", ''))).map(lambda x:\n (x[0], x[1].replace(\", '\", ''))).map(lambda x: (x[0], x[1].replace(\n '\\\\n', ''))).map(lambda x: (x[0], x[1].replace(\"\\\\'\", \"'\"))).map(lambda\n x: (x[0], re.sub('[{}+=~*%#$@(\\\\-/[,.!?&:;\\\\]0-9)\"]', ' ', str(x[1]).\n lower()))).mapValues(lambda x: x.split())\ntotal_words_num = b_text.flatMap(lambda x: x[1]).count()\nrare_words = b_text.flatMap(lambda x: x[1]).map(lambda x: (x, 1)).reduceByKey(\n lambda x, y: x + y).filter(lambda x: x[1] < total_words_num * 1e-06).map(\n lambda x: (x[0], 1))\nb_unset_words = b_text.flatMap(lambda x: [(word, x[0]) for word in x[1]]\n ).subtractByKey(rare_words).subtractByKey(stopwords)\nn = b_unset_words.groupByKey().map(lambda x: (x[0], len(set(x[1]))))\nn_dict = dict(n.collect())\nN = b_text = lines.map(lambda x: x['business_id']).distinct().count()\nb_profile = b_unset_words.map(lambda x: (x[1], x[0])).groupByKey().map(lambda\n x: (x[0], list(x[1]))).map(lambda x: (x[0], tf_idf(x[1]))).map(lambda x:\n (x[0], [word[0] for word in x[1]]))\nwords_list = b_profile.flatMap(lambda x: x[1]).distinct().collect()\nwords = dict([(word, ind) for ind, word in enumerate(words_list)])\nb_profile2 = b_profile.map(lambda x: (x[0], [words[word_ind] for word_ind in\n x[1]]))\nb_profile_dict = dict(b_profile2.collect())\n\n\ndef user_prof(b_list):\n u_profile_words = []\n for b in b_list:\n u_profile_words.extend(b_profile_dict[b])\n return list(set(u_profile_words))\n\n\nuser_profile = lines.map(lambda x: (x['user_id'], x['business_id'])\n ).groupByKey().map(lambda x: (x[0], list(x[1]))).map(lambda x: (x[0],\n user_prof(x[1])))\nf = open(model_file, 'w')\nfor user, u_vector in dict(user_profile.collect()).items():\n f.write(json.dumps({'id': user, 'type': 'user', 'vector': u_vector}))\n f.write('\\n')\nfor business, b_vector in b_profile_dict.items():\n f.write(json.dumps({'id': business, 'type': 'business', 'vector':\n b_vector}))\n f.write('\\n')\nend_time = datetime.now()\nduration = end_time - start_time\nprint('Duration:', duration)\n",
"step-5": "from sys import argv\nfrom pyspark import SparkContext\nimport json\nimport re\nimport math\nfrom _datetime import datetime\nstart_time = datetime.now()\ninput_file = argv[1]\nmodel_file = argv[2]\nstopwords = argv[3]\nsc = SparkContext(appName='inf553')\nlines = sc.textFile(input_file).map(lambda x: json.loads(x))\nstopwords = sc.textFile(stopwords).map(lambda x: (x, 1))\n\n\ndef tf_idf(words):\n word_dict = {}\n for w in words:\n if w in word_dict.keys():\n word_dict[w] += 1\n else:\n word_dict[w] = 1\n max_freq = max(word_dict.values())\n for w in words:\n word_dict[w] = (word_dict[w] / max_freq) * math.log((N / n_dict[w]), 2)\n a = sorted(word_dict.items(), key=lambda x: x[1], reverse=True)\n return a[:200]\n\n\nb_text = lines.map(lambda x: (x['business_id'], x['text']))\\\n .groupByKey().map(lambda x: (x[0], list(x[1])))\\\n .map(lambda x: (x[0], str(x[1]).replace('!\\'', '')))\\\n .map(lambda x: (x[0], x[1].replace('.\\'', ''))) \\\n .map(lambda x: (x[0], x[1].replace(', \\'', ''))) \\\n .map(lambda x: (x[0], x[1].replace('\\\\n',''))) \\\n .map(lambda x: (x[0], x[1].replace('\\\\\\'',\"'\")))\\\n .map(lambda x: (x[0], re.sub('[{}+=~*%#$@(\\-/[,.!?&:;\\]0-9)\"]', ' ', str(x[1]).lower()))) \\\n .mapValues(lambda x: x.split())\n\ntotal_words_num = b_text.flatMap(lambda x: x[1]).count()\nrare_words = b_text.flatMap(lambda x: x[1])\\\n .map(lambda x: (x, 1))\\\n .reduceByKey(lambda x, y: x+y)\\\n .filter(lambda x: x[1] < total_words_num * 0.000001)\\\n .map(lambda x: (x[0], 1))\nb_unset_words = b_text.flatMap(lambda x: [(word, x[0]) for word in x[1]])\\\n .subtractByKey(rare_words)\\\n .subtractByKey(stopwords)\nn = b_unset_words.groupByKey()\\\n .map(lambda x: (x[0], len(set(x[1]))))\n\nn_dict = dict(n.collect())\nN = b_text = lines.map(lambda x: (x['business_id'])).distinct().count()\n\nb_profile = b_unset_words.map(lambda x: (x[1], x[0]))\\\n .groupByKey().map(lambda x: (x[0], list(x[1])))\\\n .map(lambda x: (x[0], tf_idf(x[1]))) \\\n .map(lambda x: (x[0], [word[0] for word in x[1]]))\n\nwords_list = b_profile.flatMap(lambda x: x[1]).distinct().collect()\nwords = dict([(word, ind) for ind, word in enumerate(words_list)])\n\nb_profile2 = b_profile.map(lambda x: (x[0], [words[word_ind] for word_ind in x[1]]))\nb_profile_dict = dict(b_profile2.collect())\n\n\ndef user_prof(b_list):\n u_profile_words =[]\n for b in b_list:\n u_profile_words.extend(b_profile_dict[b])\n return list(set(u_profile_words))\n\n\nuser_profile = lines.map(lambda x: (x['user_id'], x['business_id']))\\\n .groupByKey().map(lambda x: (x[0], list(x[1])))\\\n .map(lambda x: (x[0], user_prof(x[1])))\nf = open(model_file, \"w\")\nfor user, u_vector in dict(user_profile.collect()).items():\n f.write(json.dumps({\"id\": user, \"type\": \"user\", \"vector\": u_vector}))\n f.write('\\n')\nfor business, b_vector in b_profile_dict.items():\n f.write(json.dumps({\"id\": business, \"type\": \"business\", \"vector\": b_vector}))\n f.write('\\n')\n\nend_time = datetime.now()\nduration = end_time - start_time\nprint(\"Duration:\", duration)\n",
"step-ids": [
2,
3,
4,
5,
6
]
}
|
[
2,
3,
4,
5,
6
] |
#função: Definir se o número inserido é ímpar ou par
#autor: João Cândido
p = 0
i = 0
numero = int(input("Insira um número: "))
if numero % 2 == 0:
p = numero
print (p, "é um número par")
else:
i = numero
print (i, "é um número ímpar")
|
normal
|
{
"blob_id": "382bc321c5fd35682bc735ca4d6e293d09be64ec",
"index": 9990,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nif numero % 2 == 0:\n p = numero\n print(p, 'é um número par')\nelse:\n i = numero\n print(i, 'é um número ímpar')\n",
"step-3": "p = 0\ni = 0\nnumero = int(input('Insira um número: '))\nif numero % 2 == 0:\n p = numero\n print(p, 'é um número par')\nelse:\n i = numero\n print(i, 'é um número ímpar')\n",
"step-4": "#função: Definir se o número inserido é ímpar ou par\n#autor: João Cândido\n\np = 0\ni = 0\n\nnumero = int(input(\"Insira um número: \"))\n\nif numero % 2 == 0:\n\tp = numero\n\tprint (p, \"é um número par\")\nelse:\n\ti = numero\n\tprint (i, \"é um número ímpar\")",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
class LoLServerStatusHandler(Handler):
def load_servers(self):
servers_filepath = os.path.join(os.path.dirname(__file__),
'../../data/lol/status.json')
return load_json(servers_filepath)
def get_filepath(self, server):
return '/lol/{region}/status.{locale}.xml'.format(region=server[
'region'], locale=server['locale'])
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class LoLServerStatusHandler(Handler):
def load_servers(self):
servers_filepath = os.path.join(os.path.dirname(__file__),
'../../data/lol/status.json')
return load_json(servers_filepath)
def get_filepath(self, server):
return '/lol/{region}/status.{locale}.xml'.format(region=server[
'region'], locale=server['locale'])
def process_server(self, server):
collector = LOLServerStatusCollector(server)
items = collector.collect()
alternateLink = collector.construct_alternate_link()
feed = Feed()
feed.setTitle(server['title'])
feed.setAlternateLink(alternateLink)
feed.setLanguage(server['locale'])
feed.setItems(items)
return feed
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class LoLServerStatusHandler(Handler):
def load_servers(self):
servers_filepath = os.path.join(os.path.dirname(__file__),
'../../data/lol/status.json')
return load_json(servers_filepath)
def get_filepath(self, server):
return '/lol/{region}/status.{locale}.xml'.format(region=server[
'region'], locale=server['locale'])
def process_server(self, server):
collector = LOLServerStatusCollector(server)
items = collector.collect()
alternateLink = collector.construct_alternate_link()
feed = Feed()
feed.setTitle(server['title'])
feed.setAlternateLink(alternateLink)
feed.setLanguage(server['locale'])
feed.setItems(items)
return feed
def handle(event={}, context={}):
"""Handler for AWS Lambda - LoL Server Status"""
LoLServerStatusHandler().run()
return 'ok'
<|reserved_special_token_1|>
import os
from sources.lol.status import LOLServerStatusCollector
from util.abstract.feed import Feed
from util.abstract.handler import Handler
from util.functions.load_json import load_json
class LoLServerStatusHandler(Handler):
def load_servers(self):
servers_filepath = os.path.join(os.path.dirname(__file__),
'../../data/lol/status.json')
return load_json(servers_filepath)
def get_filepath(self, server):
return '/lol/{region}/status.{locale}.xml'.format(region=server[
'region'], locale=server['locale'])
def process_server(self, server):
collector = LOLServerStatusCollector(server)
items = collector.collect()
alternateLink = collector.construct_alternate_link()
feed = Feed()
feed.setTitle(server['title'])
feed.setAlternateLink(alternateLink)
feed.setLanguage(server['locale'])
feed.setItems(items)
return feed
def handle(event={}, context={}):
"""Handler for AWS Lambda - LoL Server Status"""
LoLServerStatusHandler().run()
return 'ok'
|
flexible
|
{
"blob_id": "493552469943e9f9f0e57bf92b874c8b67943de5",
"index": 6751,
"step-1": "<mask token>\n\n\nclass LoLServerStatusHandler(Handler):\n\n def load_servers(self):\n servers_filepath = os.path.join(os.path.dirname(__file__),\n '../../data/lol/status.json')\n return load_json(servers_filepath)\n\n def get_filepath(self, server):\n return '/lol/{region}/status.{locale}.xml'.format(region=server[\n 'region'], locale=server['locale'])\n <mask token>\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass LoLServerStatusHandler(Handler):\n\n def load_servers(self):\n servers_filepath = os.path.join(os.path.dirname(__file__),\n '../../data/lol/status.json')\n return load_json(servers_filepath)\n\n def get_filepath(self, server):\n return '/lol/{region}/status.{locale}.xml'.format(region=server[\n 'region'], locale=server['locale'])\n\n def process_server(self, server):\n collector = LOLServerStatusCollector(server)\n items = collector.collect()\n alternateLink = collector.construct_alternate_link()\n feed = Feed()\n feed.setTitle(server['title'])\n feed.setAlternateLink(alternateLink)\n feed.setLanguage(server['locale'])\n feed.setItems(items)\n return feed\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\nclass LoLServerStatusHandler(Handler):\n\n def load_servers(self):\n servers_filepath = os.path.join(os.path.dirname(__file__),\n '../../data/lol/status.json')\n return load_json(servers_filepath)\n\n def get_filepath(self, server):\n return '/lol/{region}/status.{locale}.xml'.format(region=server[\n 'region'], locale=server['locale'])\n\n def process_server(self, server):\n collector = LOLServerStatusCollector(server)\n items = collector.collect()\n alternateLink = collector.construct_alternate_link()\n feed = Feed()\n feed.setTitle(server['title'])\n feed.setAlternateLink(alternateLink)\n feed.setLanguage(server['locale'])\n feed.setItems(items)\n return feed\n\n\ndef handle(event={}, context={}):\n \"\"\"Handler for AWS Lambda - LoL Server Status\"\"\"\n LoLServerStatusHandler().run()\n return 'ok'\n",
"step-4": "import os\nfrom sources.lol.status import LOLServerStatusCollector\nfrom util.abstract.feed import Feed\nfrom util.abstract.handler import Handler\nfrom util.functions.load_json import load_json\n\n\nclass LoLServerStatusHandler(Handler):\n\n def load_servers(self):\n servers_filepath = os.path.join(os.path.dirname(__file__),\n '../../data/lol/status.json')\n return load_json(servers_filepath)\n\n def get_filepath(self, server):\n return '/lol/{region}/status.{locale}.xml'.format(region=server[\n 'region'], locale=server['locale'])\n\n def process_server(self, server):\n collector = LOLServerStatusCollector(server)\n items = collector.collect()\n alternateLink = collector.construct_alternate_link()\n feed = Feed()\n feed.setTitle(server['title'])\n feed.setAlternateLink(alternateLink)\n feed.setLanguage(server['locale'])\n feed.setItems(items)\n return feed\n\n\ndef handle(event={}, context={}):\n \"\"\"Handler for AWS Lambda - LoL Server Status\"\"\"\n LoLServerStatusHandler().run()\n return 'ok'\n",
"step-5": null,
"step-ids": [
3,
4,
5,
6
]
}
|
[
3,
4,
5,
6
] |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'qtGSD_DESIGN.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(661, 728)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())
MainWindow.setSizePolicy(sizePolicy)
MainWindow.setMinimumSize(QtCore.QSize(100, 100))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
MainWindow.setFont(font)
MainWindow.setAutoFillBackground(False)
MainWindow.setTabShape(QtGui.QTabWidget.Rounded)
self.centralwidget = QtGui.QWidget(MainWindow)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setMinimumSize(QtCore.QSize(100, 100))
self.centralwidget.setMaximumSize(QtCore.QSize(1000, 1000))
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.groupBox_3 = QtGui.QGroupBox(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox_3.sizePolicy().hasHeightForWidth())
self.groupBox_3.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.groupBox_3.setFont(font)
self.groupBox_3.setLayoutDirection(QtCore.Qt.LeftToRight)
self.groupBox_3.setAutoFillBackground(True)
self.groupBox_3.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
self.groupBox_3.setObjectName(_fromUtf8("groupBox_3"))
self.gridLayout = QtGui.QGridLayout(self.groupBox_3)
self.gridLayout.setSizeConstraint(QtGui.QLayout.SetNoConstraint)
self.gridLayout.setObjectName(_fromUtf8("gridLayout"))
self.MainVertLayout = QtGui.QVBoxLayout()
self.MainVertLayout.setSizeConstraint(QtGui.QLayout.SetMaximumSize)
self.MainVertLayout.setContentsMargins(-1, 10, -1, -1)
self.MainVertLayout.setSpacing(0)
self.MainVertLayout.setObjectName(_fromUtf8("MainVertLayout"))
self.gridLayout.addLayout(self.MainVertLayout, 0, 0, 1, 1)
self.verticalLayout.addWidget(self.groupBox_3)
self.groupBox = QtGui.QGroupBox(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth())
self.groupBox.setSizePolicy(sizePolicy)
self.groupBox.setMinimumSize(QtCore.QSize(100, 200))
font = QtGui.QFont()
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.groupBox.setFont(font)
self.groupBox.setWhatsThis(_fromUtf8(""))
self.groupBox.setObjectName(_fromUtf8("groupBox"))
self.horizontalLayoutWidget_6 = QtGui.QWidget(self.groupBox)
self.horizontalLayoutWidget_6.setGeometry(QtCore.QRect(17, 101, 594, 32))
self.horizontalLayoutWidget_6.setObjectName(_fromUtf8("horizontalLayoutWidget_6"))
self.horizontalLayout_9 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_6)
self.horizontalLayout_9.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_9.setObjectName(_fromUtf8("horizontalLayout_9"))
self.label_7 = QtGui.QLabel(self.horizontalLayoutWidget_6)
self.label_7.setMinimumSize(QtCore.QSize(0, 30))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_7.setFont(font)
self.label_7.setObjectName(_fromUtf8("label_7"))
self.horizontalLayout_9.addWidget(self.label_7)
self.browserButton_7 = QtGui.QPushButton(self.horizontalLayoutWidget_6)
self.browserButton_7.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton_7.sizePolicy().hasHeightForWidth())
self.browserButton_7.setSizePolicy(sizePolicy)
self.browserButton_7.setMinimumSize(QtCore.QSize(80, 15))
self.browserButton_7.setObjectName(_fromUtf8("browserButton_7"))
self.horizontalLayout_9.addWidget(self.browserButton_7)
self.filePathEdit_7 = QtGui.QLineEdit(self.horizontalLayoutWidget_6)
self.filePathEdit_7.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_7.sizePolicy().hasHeightForWidth())
self.filePathEdit_7.setSizePolicy(sizePolicy)
self.filePathEdit_7.setMinimumSize(QtCore.QSize(400, 30))
self.filePathEdit_7.setObjectName(_fromUtf8("filePathEdit_7"))
self.horizontalLayout_9.addWidget(self.filePathEdit_7)
self.horizontalLayoutWidget_9 = QtGui.QWidget(self.groupBox)
self.horizontalLayoutWidget_9.setGeometry(QtCore.QRect(17, 25, 592, 32))
self.horizontalLayoutWidget_9.setObjectName(_fromUtf8("horizontalLayoutWidget_9"))
self.horizontalLayout_10 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_9)
self.horizontalLayout_10.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_10.setObjectName(_fromUtf8("horizontalLayout_10"))
self.label_11 = QtGui.QLabel(self.horizontalLayoutWidget_9)
self.label_11.setMinimumSize(QtCore.QSize(0, 30))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_11.setFont(font)
self.label_11.setObjectName(_fromUtf8("label_11"))
self.horizontalLayout_10.addWidget(self.label_11)
self.browserButton = QtGui.QPushButton(self.horizontalLayoutWidget_9)
self.browserButton.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton.sizePolicy().hasHeightForWidth())
self.browserButton.setSizePolicy(sizePolicy)
self.browserButton.setMinimumSize(QtCore.QSize(80, 15))
self.browserButton.setObjectName(_fromUtf8("browserButton"))
self.horizontalLayout_10.addWidget(self.browserButton)
self.filePathEdit_3 = QtGui.QLineEdit(self.horizontalLayoutWidget_9)
self.filePathEdit_3.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_3.sizePolicy().hasHeightForWidth())
self.filePathEdit_3.setSizePolicy(sizePolicy)
self.filePathEdit_3.setMinimumSize(QtCore.QSize(400, 30))
self.filePathEdit_3.setObjectName(_fromUtf8("filePathEdit_3"))
self.horizontalLayout_10.addWidget(self.filePathEdit_3)
self.horizontalLayoutWidget_10 = QtGui.QWidget(self.groupBox)
self.horizontalLayoutWidget_10.setGeometry(QtCore.QRect(17, 63, 592, 32))
self.horizontalLayoutWidget_10.setObjectName(_fromUtf8("horizontalLayoutWidget_10"))
self.horizontalLayout_11 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_10)
self.horizontalLayout_11.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_11.setObjectName(_fromUtf8("horizontalLayout_11"))
self.label_12 = QtGui.QLabel(self.horizontalLayoutWidget_10)
self.label_12.setMinimumSize(QtCore.QSize(0, 30))
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_12.setFont(font)
self.label_12.setObjectName(_fromUtf8("label_12"))
self.horizontalLayout_11.addWidget(self.label_12)
self.browserButton_3 = QtGui.QPushButton(self.horizontalLayoutWidget_10)
self.browserButton_3.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton_3.sizePolicy().hasHeightForWidth())
self.browserButton_3.setSizePolicy(sizePolicy)
self.browserButton_3.setMinimumSize(QtCore.QSize(80, 15))
self.browserButton_3.setObjectName(_fromUtf8("browserButton_3"))
self.horizontalLayout_11.addWidget(self.browserButton_3)
self.filePathEdit_5 = QtGui.QLineEdit(self.horizontalLayoutWidget_10)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_5.sizePolicy().hasHeightForWidth())
self.filePathEdit_5.setSizePolicy(sizePolicy)
self.filePathEdit_5.setMinimumSize(QtCore.QSize(400, 30))
self.filePathEdit_5.setObjectName(_fromUtf8("filePathEdit_5"))
self.horizontalLayout_11.addWidget(self.filePathEdit_5)
self.runButton = QtGui.QPushButton(self.groupBox)
self.runButton.setGeometry(QtCore.QRect(520, 140, 85, 50))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.runButton.sizePolicy().hasHeightForWidth())
self.runButton.setSizePolicy(sizePolicy)
self.runButton.setMinimumSize(QtCore.QSize(80, 50))
self.runButton.setIconSize(QtCore.QSize(24, 24))
self.runButton.setObjectName(_fromUtf8("runButton"))
self.verticalLayout.addWidget(self.groupBox)
self.groupBox_2 = QtGui.QGroupBox(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.groupBox_2.sizePolicy().hasHeightForWidth())
self.groupBox_2.setSizePolicy(sizePolicy)
self.groupBox_2.setMinimumSize(QtCore.QSize(100, 225))
font = QtGui.QFont()
font.setBold(False)
font.setItalic(False)
font.setWeight(50)
self.groupBox_2.setFont(font)
self.groupBox_2.setAutoFillBackground(True)
self.groupBox_2.setObjectName(_fromUtf8("groupBox_2"))
self.horizontalLayoutWidget_4 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_4.setGeometry(QtCore.QRect(17, 25, 591, 32))
self.horizontalLayoutWidget_4.setObjectName(_fromUtf8("horizontalLayoutWidget_4"))
self.horizontalLayout_6 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_4)
self.horizontalLayout_6.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6"))
self.label_3 = QtGui.QLabel(self.horizontalLayoutWidget_4)
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.label_3.setFont(font)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.horizontalLayout_6.addWidget(self.label_3)
self.browserButton_4 = QtGui.QPushButton(self.horizontalLayoutWidget_4)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.browserButton_4.sizePolicy().hasHeightForWidth())
self.browserButton_4.setSizePolicy(sizePolicy)
self.browserButton_4.setObjectName(_fromUtf8("browserButton_4"))
self.horizontalLayout_6.addWidget(self.browserButton_4)
self.loadButton = QtGui.QPushButton(self.horizontalLayoutWidget_4)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.loadButton.sizePolicy().hasHeightForWidth())
self.loadButton.setSizePolicy(sizePolicy)
self.loadButton.setObjectName(_fromUtf8("loadButton"))
self.horizontalLayout_6.addWidget(self.loadButton)
self.filePathEdit_4 = QtGui.QLineEdit(self.horizontalLayoutWidget_4)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.filePathEdit_4.sizePolicy().hasHeightForWidth())
self.filePathEdit_4.setSizePolicy(sizePolicy)
self.filePathEdit_4.setMinimumSize(QtCore.QSize(300, 30))
self.filePathEdit_4.setObjectName(_fromUtf8("filePathEdit_4"))
self.horizontalLayout_6.addWidget(self.filePathEdit_4)
self.horizontalLayoutWidget_2 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(17, 63, 481, 29))
self.horizontalLayoutWidget_2.setObjectName(_fromUtf8("horizontalLayoutWidget_2"))
self.horizontalLayout_2 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_2)
self.horizontalLayout_2.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.label_4 = QtGui.QLabel(self.horizontalLayoutWidget_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label_4.sizePolicy().hasHeightForWidth())
self.label_4.setSizePolicy(sizePolicy)
self.label_4.setObjectName(_fromUtf8("label_4"))
self.horizontalLayout_2.addWidget(self.label_4)
self.comboBox = QtGui.QComboBox(self.horizontalLayoutWidget_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox.sizePolicy().hasHeightForWidth())
self.comboBox.setSizePolicy(sizePolicy)
self.comboBox.setObjectName(_fromUtf8("comboBox"))
self.horizontalLayout_2.addWidget(self.comboBox)
self.plotButton = QtGui.QPushButton(self.horizontalLayoutWidget_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotButton.sizePolicy().hasHeightForWidth())
self.plotButton.setSizePolicy(sizePolicy)
self.plotButton.setObjectName(_fromUtf8("plotButton"))
self.horizontalLayout_2.addWidget(self.plotButton)
self.horizontalLayoutWidget_3 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(17, 100, 481, 29))
self.horizontalLayoutWidget_3.setObjectName(_fromUtf8("horizontalLayoutWidget_3"))
self.horizontalLayout_3 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_3)
self.horizontalLayout_3.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
self.label_5 = QtGui.QLabel(self.horizontalLayoutWidget_3)
self.label_5.setObjectName(_fromUtf8("label_5"))
self.horizontalLayout_3.addWidget(self.label_5)
self.comboBox_R1 = QtGui.QComboBox(self.horizontalLayoutWidget_3)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox_R1.sizePolicy().hasHeightForWidth())
self.comboBox_R1.setSizePolicy(sizePolicy)
self.comboBox_R1.setMinimumSize(QtCore.QSize(0, 0))
self.comboBox_R1.setObjectName(_fromUtf8("comboBox_R1"))
self.horizontalLayout_3.addWidget(self.comboBox_R1)
self.label = QtGui.QLabel(self.horizontalLayoutWidget_3)
self.label.setEnabled(False)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())
self.label.setSizePolicy(sizePolicy)
self.label.setMinimumSize(QtCore.QSize(30, 0))
self.label.setMaximumSize(QtCore.QSize(30, 29))
font = QtGui.QFont()
font.setBold(True)
font.setItalic(True)
font.setUnderline(False)
font.setWeight(75)
self.label.setFont(font)
self.label.setAutoFillBackground(True)
self.label.setLineWidth(5)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout_3.addWidget(self.label)
self.comboBox_R2 = QtGui.QComboBox(self.horizontalLayoutWidget_3)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox_R2.sizePolicy().hasHeightForWidth())
self.comboBox_R2.setSizePolicy(sizePolicy)
self.comboBox_R2.setObjectName(_fromUtf8("comboBox_R2"))
self.horizontalLayout_3.addWidget(self.comboBox_R2)
self.plotRangeButton = QtGui.QPushButton(self.horizontalLayoutWidget_3)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotRangeButton.sizePolicy().hasHeightForWidth())
self.plotRangeButton.setSizePolicy(sizePolicy)
self.plotRangeButton.setObjectName(_fromUtf8("plotRangeButton"))
self.horizontalLayout_3.addWidget(self.plotRangeButton)
self.horizontalLayoutWidget_7 = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget_7.setGeometry(QtCore.QRect(17, 140, 481, 29))
self.horizontalLayoutWidget_7.setObjectName(_fromUtf8("horizontalLayoutWidget_7"))
self.horizontalLayout_5 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_7)
self.horizontalLayout_5.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5"))
self.label_8 = QtGui.QLabel(self.horizontalLayoutWidget_7)
self.label_8.setObjectName(_fromUtf8("label_8"))
self.horizontalLayout_5.addWidget(self.label_8)
self.comboBox_2 = QtGui.QComboBox(self.horizontalLayoutWidget_7)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.comboBox_2.sizePolicy().hasHeightForWidth())
self.comboBox_2.setSizePolicy(sizePolicy)
self.comboBox_2.setObjectName(_fromUtf8("comboBox_2"))
self.horizontalLayout_5.addWidget(self.comboBox_2)
self.checkBox = QtGui.QCheckBox(self.horizontalLayoutWidget_7)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.checkBox.sizePolicy().hasHeightForWidth())
self.checkBox.setSizePolicy(sizePolicy)
self.checkBox.setObjectName(_fromUtf8("checkBox"))
self.horizontalLayout_5.addWidget(self.checkBox)
self.plotImageButton = QtGui.QPushButton(self.horizontalLayoutWidget_7)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotImageButton.sizePolicy().hasHeightForWidth())
self.plotImageButton.setSizePolicy(sizePolicy)
self.plotImageButton.setMinimumSize(QtCore.QSize(80, 15))
self.plotImageButton.setObjectName(_fromUtf8("plotImageButton"))
self.horizontalLayout_5.addWidget(self.plotImageButton)
self.clearPlotButton = QtGui.QPushButton(self.groupBox_2)
self.clearPlotButton.setGeometry(QtCore.QRect(520, 140, 85, 50))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.clearPlotButton.sizePolicy().hasHeightForWidth())
self.clearPlotButton.setSizePolicy(sizePolicy)
self.clearPlotButton.setMinimumSize(QtCore.QSize(80, 50))
self.clearPlotButton.setObjectName(_fromUtf8("clearPlotButton"))
self.horizontalLayoutWidget = QtGui.QWidget(self.groupBox_2)
self.horizontalLayoutWidget.setGeometry(QtCore.QRect(17, 180, 481, 29))
self.horizontalLayoutWidget.setObjectName(_fromUtf8("horizontalLayoutWidget"))
self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)
self.horizontalLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.label_9 = QtGui.QLabel(self.horizontalLayoutWidget)
self.label_9.setObjectName(_fromUtf8("label_9"))
self.horizontalLayout.addWidget(self.label_9)
self.pushButton = QtGui.QPushButton(self.horizontalLayoutWidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())
self.pushButton.setSizePolicy(sizePolicy)
self.pushButton.setMinimumSize(QtCore.QSize(80, 15))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.horizontalLayout.addWidget(self.pushButton)
self.plotStripsButton = QtGui.QPushButton(self.horizontalLayoutWidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.plotStripsButton.sizePolicy().hasHeightForWidth())
self.plotStripsButton.setSizePolicy(sizePolicy)
self.plotStripsButton.setMinimumSize(QtCore.QSize(80, 15))
self.plotStripsButton.setObjectName(_fromUtf8("plotStripsButton"))
self.horizontalLayout.addWidget(self.plotStripsButton)
self.verticalLayout.addWidget(self.groupBox_2)
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.toolBar = QtGui.QToolBar(MainWindow)
self.toolBar.setObjectName(_fromUtf8("toolBar"))
MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)
self.menuBar = QtGui.QMenuBar(MainWindow)
self.menuBar.setGeometry(QtCore.QRect(0, 0, 661, 22))
self.menuBar.setObjectName(_fromUtf8("menuBar"))
MainWindow.setMenuBar(self.menuBar)
self.actionOpen = QtGui.QAction(MainWindow)
self.actionOpen.setVisible(True)
self.actionOpen.setObjectName(_fromUtf8("actionOpen"))
self.actionQuit = QtGui.QAction(MainWindow)
self.actionQuit.setObjectName(_fromUtf8("actionQuit"))
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
self.groupBox_3.setTitle(_translate("MainWindow", "PLOT WINDOW", None))
self.groupBox.setTitle(_translate("MainWindow", " BINARY DATA CONVERSION", None))
self.label_7.setText(_translate("MainWindow", " OUTPUT FILE ", None))
self.browserButton_7.setText(_translate("MainWindow", "Browse", None))
self.filePathEdit_7.setText(_translate("MainWindow", "D:\\detdev\\maia\\python\\", None))
self.label_11.setText(_translate("MainWindow", " DECODER FILE", None))
self.browserButton.setText(_translate("MainWindow", "Browse", None))
self.filePathEdit_3.setText(_translate("MainWindow", "D:\\detdev\\maia\\python\\qtGSD\\gsd_parse.out", None))
self.label_12.setText(_translate("MainWindow", " INPUT FILE ", None))
self.browserButton_3.setText(_translate("MainWindow", "Browse", None))
self.filePathEdit_5.setText(_translate("MainWindow", "D:\\detdev\\maia\\python\\", None))
self.runButton.setText(_translate("MainWindow", "Run", None))
self.groupBox_2.setTitle(_translate("MainWindow", " PLOT DATA", None))
self.label_3.setText(_translate("MainWindow", " DATA FILE ", None))
self.browserButton_4.setText(_translate("MainWindow", "Browse", None))
self.loadButton.setText(_translate("MainWindow", "Load", None))
self.filePathEdit_4.setText(_translate("MainWindow", "D:\\detdev\\maia\\python\\", None))
self.label_4.setText(_translate("MainWindow", " PLOT STRIP ", None))
self.plotButton.setText(_translate("MainWindow", "Plot", None))
self.label_5.setText(_translate("MainWindow", " PLOT SERIES", None))
self.label.setText(_translate("MainWindow", "to", None))
self.plotRangeButton.setText(_translate("MainWindow", "Plot", None))
self.label_8.setText(_translate("MainWindow", " PLOT SPECTRA AS 2-D IMAGE", None))
self.checkBox.setText(_translate("MainWindow", "Log", None))
self.plotImageButton.setText(_translate("MainWindow", "Plot Image", None))
self.clearPlotButton.setText(_translate("MainWindow", "Clear", None))
self.label_9.setText(_translate("MainWindow", " PLOT TOTAL COUNTS vs STRIP", None))
self.pushButton.setText(_translate("MainWindow", "Update", None))
self.plotStripsButton.setText(_translate("MainWindow", "Plot Strips", None))
self.toolBar.setWindowTitle(_translate("MainWindow", "toolBar", None))
self.actionOpen.setText(_translate("MainWindow", "Open", None))
self.actionQuit.setText(_translate("MainWindow", "Quit", None))
|
normal
|
{
"blob_id": "9dde8e5fd0e83860ee86cf5402ab6eeb5b07ab2c",
"index": 7761,
"step-1": "<mask token>\n\n\nclass Ui_MainWindow(object):\n <mask token>\n <mask token>\n",
"step-2": "<mask token>\n\n\nclass Ui_MainWindow(object):\n\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(_fromUtf8('MainWindow'))\n MainWindow.resize(661, 728)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.\n QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(MainWindow.sizePolicy().\n hasHeightForWidth())\n MainWindow.setSizePolicy(sizePolicy)\n MainWindow.setMinimumSize(QtCore.QSize(100, 100))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n MainWindow.setFont(font)\n MainWindow.setAutoFillBackground(False)\n MainWindow.setTabShape(QtGui.QTabWidget.Rounded)\n self.centralwidget = QtGui.QWidget(MainWindow)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().\n hasHeightForWidth())\n self.centralwidget.setSizePolicy(sizePolicy)\n self.centralwidget.setMinimumSize(QtCore.QSize(100, 100))\n self.centralwidget.setMaximumSize(QtCore.QSize(1000, 1000))\n self.centralwidget.setObjectName(_fromUtf8('centralwidget'))\n self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)\n self.verticalLayout.setObjectName(_fromUtf8('verticalLayout'))\n self.groupBox_3 = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.\n QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox_3.sizePolicy().\n hasHeightForWidth())\n self.groupBox_3.setSizePolicy(sizePolicy)\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox_3.setFont(font)\n self.groupBox_3.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.groupBox_3.setAutoFillBackground(True)\n self.groupBox_3.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.\n AlignLeft | QtCore.Qt.AlignVCenter)\n self.groupBox_3.setObjectName(_fromUtf8('groupBox_3'))\n self.gridLayout = QtGui.QGridLayout(self.groupBox_3)\n self.gridLayout.setSizeConstraint(QtGui.QLayout.SetNoConstraint)\n self.gridLayout.setObjectName(_fromUtf8('gridLayout'))\n self.MainVertLayout = QtGui.QVBoxLayout()\n self.MainVertLayout.setSizeConstraint(QtGui.QLayout.SetMaximumSize)\n self.MainVertLayout.setContentsMargins(-1, 10, -1, -1)\n self.MainVertLayout.setSpacing(0)\n self.MainVertLayout.setObjectName(_fromUtf8('MainVertLayout'))\n self.gridLayout.addLayout(self.MainVertLayout, 0, 0, 1, 1)\n self.verticalLayout.addWidget(self.groupBox_3)\n self.groupBox = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().\n hasHeightForWidth())\n self.groupBox.setSizePolicy(sizePolicy)\n self.groupBox.setMinimumSize(QtCore.QSize(100, 200))\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox.setFont(font)\n self.groupBox.setWhatsThis(_fromUtf8(''))\n self.groupBox.setObjectName(_fromUtf8('groupBox'))\n self.horizontalLayoutWidget_6 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_6.setGeometry(QtCore.QRect(17, 101, 594,\n 32))\n self.horizontalLayoutWidget_6.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_6'))\n self.horizontalLayout_9 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_6)\n self.horizontalLayout_9.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_9.setObjectName(_fromUtf8('horizontalLayout_9'))\n self.label_7 = QtGui.QLabel(self.horizontalLayoutWidget_6)\n self.label_7.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_7.setFont(font)\n self.label_7.setObjectName(_fromUtf8('label_7'))\n self.horizontalLayout_9.addWidget(self.label_7)\n self.browserButton_7 = QtGui.QPushButton(self.horizontalLayoutWidget_6)\n self.browserButton_7.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_7.sizePolicy().\n hasHeightForWidth())\n self.browserButton_7.setSizePolicy(sizePolicy)\n self.browserButton_7.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton_7.setObjectName(_fromUtf8('browserButton_7'))\n self.horizontalLayout_9.addWidget(self.browserButton_7)\n self.filePathEdit_7 = QtGui.QLineEdit(self.horizontalLayoutWidget_6)\n self.filePathEdit_7.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_7.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_7.setSizePolicy(sizePolicy)\n self.filePathEdit_7.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_7.setObjectName(_fromUtf8('filePathEdit_7'))\n self.horizontalLayout_9.addWidget(self.filePathEdit_7)\n self.horizontalLayoutWidget_9 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_9.setGeometry(QtCore.QRect(17, 25, 592, 32)\n )\n self.horizontalLayoutWidget_9.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_9'))\n self.horizontalLayout_10 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_9)\n self.horizontalLayout_10.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_10.setObjectName(_fromUtf8('horizontalLayout_10')\n )\n self.label_11 = QtGui.QLabel(self.horizontalLayoutWidget_9)\n self.label_11.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_11.setFont(font)\n self.label_11.setObjectName(_fromUtf8('label_11'))\n self.horizontalLayout_10.addWidget(self.label_11)\n self.browserButton = QtGui.QPushButton(self.horizontalLayoutWidget_9)\n self.browserButton.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton.sizePolicy().\n hasHeightForWidth())\n self.browserButton.setSizePolicy(sizePolicy)\n self.browserButton.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton.setObjectName(_fromUtf8('browserButton'))\n self.horizontalLayout_10.addWidget(self.browserButton)\n self.filePathEdit_3 = QtGui.QLineEdit(self.horizontalLayoutWidget_9)\n self.filePathEdit_3.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_3.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_3.setSizePolicy(sizePolicy)\n self.filePathEdit_3.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_3.setObjectName(_fromUtf8('filePathEdit_3'))\n self.horizontalLayout_10.addWidget(self.filePathEdit_3)\n self.horizontalLayoutWidget_10 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_10.setGeometry(QtCore.QRect(17, 63, 592,\n 32))\n self.horizontalLayoutWidget_10.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_10'))\n self.horizontalLayout_11 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_10)\n self.horizontalLayout_11.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_11.setObjectName(_fromUtf8('horizontalLayout_11')\n )\n self.label_12 = QtGui.QLabel(self.horizontalLayoutWidget_10)\n self.label_12.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_12.setFont(font)\n self.label_12.setObjectName(_fromUtf8('label_12'))\n self.horizontalLayout_11.addWidget(self.label_12)\n self.browserButton_3 = QtGui.QPushButton(self.horizontalLayoutWidget_10\n )\n self.browserButton_3.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_3.sizePolicy().\n hasHeightForWidth())\n self.browserButton_3.setSizePolicy(sizePolicy)\n self.browserButton_3.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton_3.setObjectName(_fromUtf8('browserButton_3'))\n self.horizontalLayout_11.addWidget(self.browserButton_3)\n self.filePathEdit_5 = QtGui.QLineEdit(self.horizontalLayoutWidget_10)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_5.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_5.setSizePolicy(sizePolicy)\n self.filePathEdit_5.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_5.setObjectName(_fromUtf8('filePathEdit_5'))\n self.horizontalLayout_11.addWidget(self.filePathEdit_5)\n self.runButton = QtGui.QPushButton(self.groupBox)\n self.runButton.setGeometry(QtCore.QRect(520, 140, 85, 50))\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.runButton.sizePolicy().\n hasHeightForWidth())\n self.runButton.setSizePolicy(sizePolicy)\n self.runButton.setMinimumSize(QtCore.QSize(80, 50))\n self.runButton.setIconSize(QtCore.QSize(24, 24))\n self.runButton.setObjectName(_fromUtf8('runButton'))\n self.verticalLayout.addWidget(self.groupBox)\n self.groupBox_2 = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox_2.sizePolicy().\n hasHeightForWidth())\n self.groupBox_2.setSizePolicy(sizePolicy)\n self.groupBox_2.setMinimumSize(QtCore.QSize(100, 225))\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox_2.setFont(font)\n self.groupBox_2.setAutoFillBackground(True)\n self.groupBox_2.setObjectName(_fromUtf8('groupBox_2'))\n self.horizontalLayoutWidget_4 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_4.setGeometry(QtCore.QRect(17, 25, 591, 32)\n )\n self.horizontalLayoutWidget_4.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_4'))\n self.horizontalLayout_6 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_4)\n self.horizontalLayout_6.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_6.setObjectName(_fromUtf8('horizontalLayout_6'))\n self.label_3 = QtGui.QLabel(self.horizontalLayoutWidget_4)\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8('label_3'))\n self.horizontalLayout_6.addWidget(self.label_3)\n self.browserButton_4 = QtGui.QPushButton(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_4.sizePolicy().\n hasHeightForWidth())\n self.browserButton_4.setSizePolicy(sizePolicy)\n self.browserButton_4.setObjectName(_fromUtf8('browserButton_4'))\n self.horizontalLayout_6.addWidget(self.browserButton_4)\n self.loadButton = QtGui.QPushButton(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.loadButton.sizePolicy().\n hasHeightForWidth())\n self.loadButton.setSizePolicy(sizePolicy)\n self.loadButton.setObjectName(_fromUtf8('loadButton'))\n self.horizontalLayout_6.addWidget(self.loadButton)\n self.filePathEdit_4 = QtGui.QLineEdit(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_4.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_4.setSizePolicy(sizePolicy)\n self.filePathEdit_4.setMinimumSize(QtCore.QSize(300, 30))\n self.filePathEdit_4.setObjectName(_fromUtf8('filePathEdit_4'))\n self.horizontalLayout_6.addWidget(self.filePathEdit_4)\n self.horizontalLayoutWidget_2 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(17, 63, 481, 29)\n )\n self.horizontalLayoutWidget_2.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_2'))\n self.horizontalLayout_2 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_2)\n self.horizontalLayout_2.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_2.setObjectName(_fromUtf8('horizontalLayout_2'))\n self.label_4 = QtGui.QLabel(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label_4.sizePolicy().\n hasHeightForWidth())\n self.label_4.setSizePolicy(sizePolicy)\n self.label_4.setObjectName(_fromUtf8('label_4'))\n self.horizontalLayout_2.addWidget(self.label_4)\n self.comboBox = QtGui.QComboBox(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox.sizePolicy().\n hasHeightForWidth())\n self.comboBox.setSizePolicy(sizePolicy)\n self.comboBox.setObjectName(_fromUtf8('comboBox'))\n self.horizontalLayout_2.addWidget(self.comboBox)\n self.plotButton = QtGui.QPushButton(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotButton.sizePolicy().\n hasHeightForWidth())\n self.plotButton.setSizePolicy(sizePolicy)\n self.plotButton.setObjectName(_fromUtf8('plotButton'))\n self.horizontalLayout_2.addWidget(self.plotButton)\n self.horizontalLayoutWidget_3 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(17, 100, 481,\n 29))\n self.horizontalLayoutWidget_3.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_3'))\n self.horizontalLayout_3 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_3)\n self.horizontalLayout_3.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_3.setObjectName(_fromUtf8('horizontalLayout_3'))\n self.label_5 = QtGui.QLabel(self.horizontalLayoutWidget_3)\n self.label_5.setObjectName(_fromUtf8('label_5'))\n self.horizontalLayout_3.addWidget(self.label_5)\n self.comboBox_R1 = QtGui.QComboBox(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_R1.sizePolicy().\n hasHeightForWidth())\n self.comboBox_R1.setSizePolicy(sizePolicy)\n self.comboBox_R1.setMinimumSize(QtCore.QSize(0, 0))\n self.comboBox_R1.setObjectName(_fromUtf8('comboBox_R1'))\n self.horizontalLayout_3.addWidget(self.comboBox_R1)\n self.label = QtGui.QLabel(self.horizontalLayoutWidget_3)\n self.label.setEnabled(False)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label.sizePolicy().\n hasHeightForWidth())\n self.label.setSizePolicy(sizePolicy)\n self.label.setMinimumSize(QtCore.QSize(30, 0))\n self.label.setMaximumSize(QtCore.QSize(30, 29))\n font = QtGui.QFont()\n font.setBold(True)\n font.setItalic(True)\n font.setUnderline(False)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setAutoFillBackground(True)\n self.label.setLineWidth(5)\n self.label.setAlignment(QtCore.Qt.AlignCenter)\n self.label.setObjectName(_fromUtf8('label'))\n self.horizontalLayout_3.addWidget(self.label)\n self.comboBox_R2 = QtGui.QComboBox(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_R2.sizePolicy().\n hasHeightForWidth())\n self.comboBox_R2.setSizePolicy(sizePolicy)\n self.comboBox_R2.setObjectName(_fromUtf8('comboBox_R2'))\n self.horizontalLayout_3.addWidget(self.comboBox_R2)\n self.plotRangeButton = QtGui.QPushButton(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotRangeButton.sizePolicy().\n hasHeightForWidth())\n self.plotRangeButton.setSizePolicy(sizePolicy)\n self.plotRangeButton.setObjectName(_fromUtf8('plotRangeButton'))\n self.horizontalLayout_3.addWidget(self.plotRangeButton)\n self.horizontalLayoutWidget_7 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_7.setGeometry(QtCore.QRect(17, 140, 481,\n 29))\n self.horizontalLayoutWidget_7.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_7'))\n self.horizontalLayout_5 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_7)\n self.horizontalLayout_5.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_5.setObjectName(_fromUtf8('horizontalLayout_5'))\n self.label_8 = QtGui.QLabel(self.horizontalLayoutWidget_7)\n self.label_8.setObjectName(_fromUtf8('label_8'))\n self.horizontalLayout_5.addWidget(self.label_8)\n self.comboBox_2 = QtGui.QComboBox(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_2.sizePolicy().\n hasHeightForWidth())\n self.comboBox_2.setSizePolicy(sizePolicy)\n self.comboBox_2.setObjectName(_fromUtf8('comboBox_2'))\n self.horizontalLayout_5.addWidget(self.comboBox_2)\n self.checkBox = QtGui.QCheckBox(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.checkBox.sizePolicy().\n hasHeightForWidth())\n self.checkBox.setSizePolicy(sizePolicy)\n self.checkBox.setObjectName(_fromUtf8('checkBox'))\n self.horizontalLayout_5.addWidget(self.checkBox)\n self.plotImageButton = QtGui.QPushButton(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotImageButton.sizePolicy().\n hasHeightForWidth())\n self.plotImageButton.setSizePolicy(sizePolicy)\n self.plotImageButton.setMinimumSize(QtCore.QSize(80, 15))\n self.plotImageButton.setObjectName(_fromUtf8('plotImageButton'))\n self.horizontalLayout_5.addWidget(self.plotImageButton)\n self.clearPlotButton = QtGui.QPushButton(self.groupBox_2)\n self.clearPlotButton.setGeometry(QtCore.QRect(520, 140, 85, 50))\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.clearPlotButton.sizePolicy().\n hasHeightForWidth())\n self.clearPlotButton.setSizePolicy(sizePolicy)\n self.clearPlotButton.setMinimumSize(QtCore.QSize(80, 50))\n self.clearPlotButton.setObjectName(_fromUtf8('clearPlotButton'))\n self.horizontalLayoutWidget = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget.setGeometry(QtCore.QRect(17, 180, 481, 29))\n self.horizontalLayoutWidget.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget'))\n self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)\n self.horizontalLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout.setObjectName(_fromUtf8('horizontalLayout'))\n self.label_9 = QtGui.QLabel(self.horizontalLayoutWidget)\n self.label_9.setObjectName(_fromUtf8('label_9'))\n self.horizontalLayout.addWidget(self.label_9)\n self.pushButton = QtGui.QPushButton(self.horizontalLayoutWidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().\n hasHeightForWidth())\n self.pushButton.setSizePolicy(sizePolicy)\n self.pushButton.setMinimumSize(QtCore.QSize(80, 15))\n self.pushButton.setObjectName(_fromUtf8('pushButton'))\n self.horizontalLayout.addWidget(self.pushButton)\n self.plotStripsButton = QtGui.QPushButton(self.horizontalLayoutWidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotStripsButton.sizePolicy().\n hasHeightForWidth())\n self.plotStripsButton.setSizePolicy(sizePolicy)\n self.plotStripsButton.setMinimumSize(QtCore.QSize(80, 15))\n self.plotStripsButton.setObjectName(_fromUtf8('plotStripsButton'))\n self.horizontalLayout.addWidget(self.plotStripsButton)\n self.verticalLayout.addWidget(self.groupBox_2)\n MainWindow.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(MainWindow)\n self.statusbar.setObjectName(_fromUtf8('statusbar'))\n MainWindow.setStatusBar(self.statusbar)\n self.toolBar = QtGui.QToolBar(MainWindow)\n self.toolBar.setObjectName(_fromUtf8('toolBar'))\n MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)\n self.menuBar = QtGui.QMenuBar(MainWindow)\n self.menuBar.setGeometry(QtCore.QRect(0, 0, 661, 22))\n self.menuBar.setObjectName(_fromUtf8('menuBar'))\n MainWindow.setMenuBar(self.menuBar)\n self.actionOpen = QtGui.QAction(MainWindow)\n self.actionOpen.setVisible(True)\n self.actionOpen.setObjectName(_fromUtf8('actionOpen'))\n self.actionQuit = QtGui.QAction(MainWindow)\n self.actionQuit.setObjectName(_fromUtf8('actionQuit'))\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n MainWindow.setWindowTitle(_translate('MainWindow', 'MainWindow', None))\n self.groupBox_3.setTitle(_translate('MainWindow', 'PLOT WINDOW', None))\n self.groupBox.setTitle(_translate('MainWindow',\n ' BINARY DATA CONVERSION', None))\n self.label_7.setText(_translate('MainWindow', ' OUTPUT FILE ', None))\n self.browserButton_7.setText(_translate('MainWindow', 'Browse', None))\n self.filePathEdit_7.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\', None))\n self.label_11.setText(_translate('MainWindow', ' DECODER FILE', None))\n self.browserButton.setText(_translate('MainWindow', 'Browse', None))\n self.filePathEdit_3.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\qtGSD\\\\gsd_parse.out', None))\n self.label_12.setText(_translate('MainWindow', ' INPUT FILE ',\n None))\n self.browserButton_3.setText(_translate('MainWindow', 'Browse', None))\n self.filePathEdit_5.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\', None))\n self.runButton.setText(_translate('MainWindow', 'Run', None))\n self.groupBox_2.setTitle(_translate('MainWindow', ' PLOT DATA', None))\n self.label_3.setText(_translate('MainWindow', ' DATA FILE ', None))\n self.browserButton_4.setText(_translate('MainWindow', 'Browse', None))\n self.loadButton.setText(_translate('MainWindow', 'Load', None))\n self.filePathEdit_4.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\', None))\n self.label_4.setText(_translate('MainWindow', ' PLOT STRIP ', None))\n self.plotButton.setText(_translate('MainWindow', 'Plot', None))\n self.label_5.setText(_translate('MainWindow', ' PLOT SERIES', None))\n self.label.setText(_translate('MainWindow', 'to', None))\n self.plotRangeButton.setText(_translate('MainWindow', 'Plot', None))\n self.label_8.setText(_translate('MainWindow',\n ' PLOT SPECTRA AS 2-D IMAGE', None))\n self.checkBox.setText(_translate('MainWindow', 'Log', None))\n self.plotImageButton.setText(_translate('MainWindow', 'Plot Image',\n None))\n self.clearPlotButton.setText(_translate('MainWindow', 'Clear', None))\n self.label_9.setText(_translate('MainWindow',\n ' PLOT TOTAL COUNTS vs STRIP', None))\n self.pushButton.setText(_translate('MainWindow', 'Update', None))\n self.plotStripsButton.setText(_translate('MainWindow',\n 'Plot Strips', None))\n self.toolBar.setWindowTitle(_translate('MainWindow', 'toolBar', None))\n self.actionOpen.setText(_translate('MainWindow', 'Open', None))\n self.actionQuit.setText(_translate('MainWindow', 'Quit', None))\n",
"step-3": "<mask token>\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n\n def _fromUtf8(s):\n return s\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\n\nclass Ui_MainWindow(object):\n\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(_fromUtf8('MainWindow'))\n MainWindow.resize(661, 728)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.\n QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(MainWindow.sizePolicy().\n hasHeightForWidth())\n MainWindow.setSizePolicy(sizePolicy)\n MainWindow.setMinimumSize(QtCore.QSize(100, 100))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n MainWindow.setFont(font)\n MainWindow.setAutoFillBackground(False)\n MainWindow.setTabShape(QtGui.QTabWidget.Rounded)\n self.centralwidget = QtGui.QWidget(MainWindow)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().\n hasHeightForWidth())\n self.centralwidget.setSizePolicy(sizePolicy)\n self.centralwidget.setMinimumSize(QtCore.QSize(100, 100))\n self.centralwidget.setMaximumSize(QtCore.QSize(1000, 1000))\n self.centralwidget.setObjectName(_fromUtf8('centralwidget'))\n self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)\n self.verticalLayout.setObjectName(_fromUtf8('verticalLayout'))\n self.groupBox_3 = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.\n QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox_3.sizePolicy().\n hasHeightForWidth())\n self.groupBox_3.setSizePolicy(sizePolicy)\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox_3.setFont(font)\n self.groupBox_3.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.groupBox_3.setAutoFillBackground(True)\n self.groupBox_3.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.\n AlignLeft | QtCore.Qt.AlignVCenter)\n self.groupBox_3.setObjectName(_fromUtf8('groupBox_3'))\n self.gridLayout = QtGui.QGridLayout(self.groupBox_3)\n self.gridLayout.setSizeConstraint(QtGui.QLayout.SetNoConstraint)\n self.gridLayout.setObjectName(_fromUtf8('gridLayout'))\n self.MainVertLayout = QtGui.QVBoxLayout()\n self.MainVertLayout.setSizeConstraint(QtGui.QLayout.SetMaximumSize)\n self.MainVertLayout.setContentsMargins(-1, 10, -1, -1)\n self.MainVertLayout.setSpacing(0)\n self.MainVertLayout.setObjectName(_fromUtf8('MainVertLayout'))\n self.gridLayout.addLayout(self.MainVertLayout, 0, 0, 1, 1)\n self.verticalLayout.addWidget(self.groupBox_3)\n self.groupBox = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().\n hasHeightForWidth())\n self.groupBox.setSizePolicy(sizePolicy)\n self.groupBox.setMinimumSize(QtCore.QSize(100, 200))\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox.setFont(font)\n self.groupBox.setWhatsThis(_fromUtf8(''))\n self.groupBox.setObjectName(_fromUtf8('groupBox'))\n self.horizontalLayoutWidget_6 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_6.setGeometry(QtCore.QRect(17, 101, 594,\n 32))\n self.horizontalLayoutWidget_6.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_6'))\n self.horizontalLayout_9 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_6)\n self.horizontalLayout_9.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_9.setObjectName(_fromUtf8('horizontalLayout_9'))\n self.label_7 = QtGui.QLabel(self.horizontalLayoutWidget_6)\n self.label_7.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_7.setFont(font)\n self.label_7.setObjectName(_fromUtf8('label_7'))\n self.horizontalLayout_9.addWidget(self.label_7)\n self.browserButton_7 = QtGui.QPushButton(self.horizontalLayoutWidget_6)\n self.browserButton_7.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_7.sizePolicy().\n hasHeightForWidth())\n self.browserButton_7.setSizePolicy(sizePolicy)\n self.browserButton_7.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton_7.setObjectName(_fromUtf8('browserButton_7'))\n self.horizontalLayout_9.addWidget(self.browserButton_7)\n self.filePathEdit_7 = QtGui.QLineEdit(self.horizontalLayoutWidget_6)\n self.filePathEdit_7.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_7.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_7.setSizePolicy(sizePolicy)\n self.filePathEdit_7.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_7.setObjectName(_fromUtf8('filePathEdit_7'))\n self.horizontalLayout_9.addWidget(self.filePathEdit_7)\n self.horizontalLayoutWidget_9 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_9.setGeometry(QtCore.QRect(17, 25, 592, 32)\n )\n self.horizontalLayoutWidget_9.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_9'))\n self.horizontalLayout_10 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_9)\n self.horizontalLayout_10.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_10.setObjectName(_fromUtf8('horizontalLayout_10')\n )\n self.label_11 = QtGui.QLabel(self.horizontalLayoutWidget_9)\n self.label_11.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_11.setFont(font)\n self.label_11.setObjectName(_fromUtf8('label_11'))\n self.horizontalLayout_10.addWidget(self.label_11)\n self.browserButton = QtGui.QPushButton(self.horizontalLayoutWidget_9)\n self.browserButton.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton.sizePolicy().\n hasHeightForWidth())\n self.browserButton.setSizePolicy(sizePolicy)\n self.browserButton.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton.setObjectName(_fromUtf8('browserButton'))\n self.horizontalLayout_10.addWidget(self.browserButton)\n self.filePathEdit_3 = QtGui.QLineEdit(self.horizontalLayoutWidget_9)\n self.filePathEdit_3.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_3.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_3.setSizePolicy(sizePolicy)\n self.filePathEdit_3.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_3.setObjectName(_fromUtf8('filePathEdit_3'))\n self.horizontalLayout_10.addWidget(self.filePathEdit_3)\n self.horizontalLayoutWidget_10 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_10.setGeometry(QtCore.QRect(17, 63, 592,\n 32))\n self.horizontalLayoutWidget_10.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_10'))\n self.horizontalLayout_11 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_10)\n self.horizontalLayout_11.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_11.setObjectName(_fromUtf8('horizontalLayout_11')\n )\n self.label_12 = QtGui.QLabel(self.horizontalLayoutWidget_10)\n self.label_12.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_12.setFont(font)\n self.label_12.setObjectName(_fromUtf8('label_12'))\n self.horizontalLayout_11.addWidget(self.label_12)\n self.browserButton_3 = QtGui.QPushButton(self.horizontalLayoutWidget_10\n )\n self.browserButton_3.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_3.sizePolicy().\n hasHeightForWidth())\n self.browserButton_3.setSizePolicy(sizePolicy)\n self.browserButton_3.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton_3.setObjectName(_fromUtf8('browserButton_3'))\n self.horizontalLayout_11.addWidget(self.browserButton_3)\n self.filePathEdit_5 = QtGui.QLineEdit(self.horizontalLayoutWidget_10)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_5.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_5.setSizePolicy(sizePolicy)\n self.filePathEdit_5.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_5.setObjectName(_fromUtf8('filePathEdit_5'))\n self.horizontalLayout_11.addWidget(self.filePathEdit_5)\n self.runButton = QtGui.QPushButton(self.groupBox)\n self.runButton.setGeometry(QtCore.QRect(520, 140, 85, 50))\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.runButton.sizePolicy().\n hasHeightForWidth())\n self.runButton.setSizePolicy(sizePolicy)\n self.runButton.setMinimumSize(QtCore.QSize(80, 50))\n self.runButton.setIconSize(QtCore.QSize(24, 24))\n self.runButton.setObjectName(_fromUtf8('runButton'))\n self.verticalLayout.addWidget(self.groupBox)\n self.groupBox_2 = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox_2.sizePolicy().\n hasHeightForWidth())\n self.groupBox_2.setSizePolicy(sizePolicy)\n self.groupBox_2.setMinimumSize(QtCore.QSize(100, 225))\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox_2.setFont(font)\n self.groupBox_2.setAutoFillBackground(True)\n self.groupBox_2.setObjectName(_fromUtf8('groupBox_2'))\n self.horizontalLayoutWidget_4 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_4.setGeometry(QtCore.QRect(17, 25, 591, 32)\n )\n self.horizontalLayoutWidget_4.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_4'))\n self.horizontalLayout_6 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_4)\n self.horizontalLayout_6.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_6.setObjectName(_fromUtf8('horizontalLayout_6'))\n self.label_3 = QtGui.QLabel(self.horizontalLayoutWidget_4)\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8('label_3'))\n self.horizontalLayout_6.addWidget(self.label_3)\n self.browserButton_4 = QtGui.QPushButton(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_4.sizePolicy().\n hasHeightForWidth())\n self.browserButton_4.setSizePolicy(sizePolicy)\n self.browserButton_4.setObjectName(_fromUtf8('browserButton_4'))\n self.horizontalLayout_6.addWidget(self.browserButton_4)\n self.loadButton = QtGui.QPushButton(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.loadButton.sizePolicy().\n hasHeightForWidth())\n self.loadButton.setSizePolicy(sizePolicy)\n self.loadButton.setObjectName(_fromUtf8('loadButton'))\n self.horizontalLayout_6.addWidget(self.loadButton)\n self.filePathEdit_4 = QtGui.QLineEdit(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_4.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_4.setSizePolicy(sizePolicy)\n self.filePathEdit_4.setMinimumSize(QtCore.QSize(300, 30))\n self.filePathEdit_4.setObjectName(_fromUtf8('filePathEdit_4'))\n self.horizontalLayout_6.addWidget(self.filePathEdit_4)\n self.horizontalLayoutWidget_2 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(17, 63, 481, 29)\n )\n self.horizontalLayoutWidget_2.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_2'))\n self.horizontalLayout_2 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_2)\n self.horizontalLayout_2.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_2.setObjectName(_fromUtf8('horizontalLayout_2'))\n self.label_4 = QtGui.QLabel(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label_4.sizePolicy().\n hasHeightForWidth())\n self.label_4.setSizePolicy(sizePolicy)\n self.label_4.setObjectName(_fromUtf8('label_4'))\n self.horizontalLayout_2.addWidget(self.label_4)\n self.comboBox = QtGui.QComboBox(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox.sizePolicy().\n hasHeightForWidth())\n self.comboBox.setSizePolicy(sizePolicy)\n self.comboBox.setObjectName(_fromUtf8('comboBox'))\n self.horizontalLayout_2.addWidget(self.comboBox)\n self.plotButton = QtGui.QPushButton(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotButton.sizePolicy().\n hasHeightForWidth())\n self.plotButton.setSizePolicy(sizePolicy)\n self.plotButton.setObjectName(_fromUtf8('plotButton'))\n self.horizontalLayout_2.addWidget(self.plotButton)\n self.horizontalLayoutWidget_3 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(17, 100, 481,\n 29))\n self.horizontalLayoutWidget_3.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_3'))\n self.horizontalLayout_3 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_3)\n self.horizontalLayout_3.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_3.setObjectName(_fromUtf8('horizontalLayout_3'))\n self.label_5 = QtGui.QLabel(self.horizontalLayoutWidget_3)\n self.label_5.setObjectName(_fromUtf8('label_5'))\n self.horizontalLayout_3.addWidget(self.label_5)\n self.comboBox_R1 = QtGui.QComboBox(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_R1.sizePolicy().\n hasHeightForWidth())\n self.comboBox_R1.setSizePolicy(sizePolicy)\n self.comboBox_R1.setMinimumSize(QtCore.QSize(0, 0))\n self.comboBox_R1.setObjectName(_fromUtf8('comboBox_R1'))\n self.horizontalLayout_3.addWidget(self.comboBox_R1)\n self.label = QtGui.QLabel(self.horizontalLayoutWidget_3)\n self.label.setEnabled(False)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label.sizePolicy().\n hasHeightForWidth())\n self.label.setSizePolicy(sizePolicy)\n self.label.setMinimumSize(QtCore.QSize(30, 0))\n self.label.setMaximumSize(QtCore.QSize(30, 29))\n font = QtGui.QFont()\n font.setBold(True)\n font.setItalic(True)\n font.setUnderline(False)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setAutoFillBackground(True)\n self.label.setLineWidth(5)\n self.label.setAlignment(QtCore.Qt.AlignCenter)\n self.label.setObjectName(_fromUtf8('label'))\n self.horizontalLayout_3.addWidget(self.label)\n self.comboBox_R2 = QtGui.QComboBox(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_R2.sizePolicy().\n hasHeightForWidth())\n self.comboBox_R2.setSizePolicy(sizePolicy)\n self.comboBox_R2.setObjectName(_fromUtf8('comboBox_R2'))\n self.horizontalLayout_3.addWidget(self.comboBox_R2)\n self.plotRangeButton = QtGui.QPushButton(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotRangeButton.sizePolicy().\n hasHeightForWidth())\n self.plotRangeButton.setSizePolicy(sizePolicy)\n self.plotRangeButton.setObjectName(_fromUtf8('plotRangeButton'))\n self.horizontalLayout_3.addWidget(self.plotRangeButton)\n self.horizontalLayoutWidget_7 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_7.setGeometry(QtCore.QRect(17, 140, 481,\n 29))\n self.horizontalLayoutWidget_7.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_7'))\n self.horizontalLayout_5 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_7)\n self.horizontalLayout_5.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_5.setObjectName(_fromUtf8('horizontalLayout_5'))\n self.label_8 = QtGui.QLabel(self.horizontalLayoutWidget_7)\n self.label_8.setObjectName(_fromUtf8('label_8'))\n self.horizontalLayout_5.addWidget(self.label_8)\n self.comboBox_2 = QtGui.QComboBox(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_2.sizePolicy().\n hasHeightForWidth())\n self.comboBox_2.setSizePolicy(sizePolicy)\n self.comboBox_2.setObjectName(_fromUtf8('comboBox_2'))\n self.horizontalLayout_5.addWidget(self.comboBox_2)\n self.checkBox = QtGui.QCheckBox(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.checkBox.sizePolicy().\n hasHeightForWidth())\n self.checkBox.setSizePolicy(sizePolicy)\n self.checkBox.setObjectName(_fromUtf8('checkBox'))\n self.horizontalLayout_5.addWidget(self.checkBox)\n self.plotImageButton = QtGui.QPushButton(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotImageButton.sizePolicy().\n hasHeightForWidth())\n self.plotImageButton.setSizePolicy(sizePolicy)\n self.plotImageButton.setMinimumSize(QtCore.QSize(80, 15))\n self.plotImageButton.setObjectName(_fromUtf8('plotImageButton'))\n self.horizontalLayout_5.addWidget(self.plotImageButton)\n self.clearPlotButton = QtGui.QPushButton(self.groupBox_2)\n self.clearPlotButton.setGeometry(QtCore.QRect(520, 140, 85, 50))\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.clearPlotButton.sizePolicy().\n hasHeightForWidth())\n self.clearPlotButton.setSizePolicy(sizePolicy)\n self.clearPlotButton.setMinimumSize(QtCore.QSize(80, 50))\n self.clearPlotButton.setObjectName(_fromUtf8('clearPlotButton'))\n self.horizontalLayoutWidget = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget.setGeometry(QtCore.QRect(17, 180, 481, 29))\n self.horizontalLayoutWidget.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget'))\n self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)\n self.horizontalLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout.setObjectName(_fromUtf8('horizontalLayout'))\n self.label_9 = QtGui.QLabel(self.horizontalLayoutWidget)\n self.label_9.setObjectName(_fromUtf8('label_9'))\n self.horizontalLayout.addWidget(self.label_9)\n self.pushButton = QtGui.QPushButton(self.horizontalLayoutWidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().\n hasHeightForWidth())\n self.pushButton.setSizePolicy(sizePolicy)\n self.pushButton.setMinimumSize(QtCore.QSize(80, 15))\n self.pushButton.setObjectName(_fromUtf8('pushButton'))\n self.horizontalLayout.addWidget(self.pushButton)\n self.plotStripsButton = QtGui.QPushButton(self.horizontalLayoutWidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotStripsButton.sizePolicy().\n hasHeightForWidth())\n self.plotStripsButton.setSizePolicy(sizePolicy)\n self.plotStripsButton.setMinimumSize(QtCore.QSize(80, 15))\n self.plotStripsButton.setObjectName(_fromUtf8('plotStripsButton'))\n self.horizontalLayout.addWidget(self.plotStripsButton)\n self.verticalLayout.addWidget(self.groupBox_2)\n MainWindow.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(MainWindow)\n self.statusbar.setObjectName(_fromUtf8('statusbar'))\n MainWindow.setStatusBar(self.statusbar)\n self.toolBar = QtGui.QToolBar(MainWindow)\n self.toolBar.setObjectName(_fromUtf8('toolBar'))\n MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)\n self.menuBar = QtGui.QMenuBar(MainWindow)\n self.menuBar.setGeometry(QtCore.QRect(0, 0, 661, 22))\n self.menuBar.setObjectName(_fromUtf8('menuBar'))\n MainWindow.setMenuBar(self.menuBar)\n self.actionOpen = QtGui.QAction(MainWindow)\n self.actionOpen.setVisible(True)\n self.actionOpen.setObjectName(_fromUtf8('actionOpen'))\n self.actionQuit = QtGui.QAction(MainWindow)\n self.actionQuit.setObjectName(_fromUtf8('actionQuit'))\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n MainWindow.setWindowTitle(_translate('MainWindow', 'MainWindow', None))\n self.groupBox_3.setTitle(_translate('MainWindow', 'PLOT WINDOW', None))\n self.groupBox.setTitle(_translate('MainWindow',\n ' BINARY DATA CONVERSION', None))\n self.label_7.setText(_translate('MainWindow', ' OUTPUT FILE ', None))\n self.browserButton_7.setText(_translate('MainWindow', 'Browse', None))\n self.filePathEdit_7.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\', None))\n self.label_11.setText(_translate('MainWindow', ' DECODER FILE', None))\n self.browserButton.setText(_translate('MainWindow', 'Browse', None))\n self.filePathEdit_3.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\qtGSD\\\\gsd_parse.out', None))\n self.label_12.setText(_translate('MainWindow', ' INPUT FILE ',\n None))\n self.browserButton_3.setText(_translate('MainWindow', 'Browse', None))\n self.filePathEdit_5.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\', None))\n self.runButton.setText(_translate('MainWindow', 'Run', None))\n self.groupBox_2.setTitle(_translate('MainWindow', ' PLOT DATA', None))\n self.label_3.setText(_translate('MainWindow', ' DATA FILE ', None))\n self.browserButton_4.setText(_translate('MainWindow', 'Browse', None))\n self.loadButton.setText(_translate('MainWindow', 'Load', None))\n self.filePathEdit_4.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\', None))\n self.label_4.setText(_translate('MainWindow', ' PLOT STRIP ', None))\n self.plotButton.setText(_translate('MainWindow', 'Plot', None))\n self.label_5.setText(_translate('MainWindow', ' PLOT SERIES', None))\n self.label.setText(_translate('MainWindow', 'to', None))\n self.plotRangeButton.setText(_translate('MainWindow', 'Plot', None))\n self.label_8.setText(_translate('MainWindow',\n ' PLOT SPECTRA AS 2-D IMAGE', None))\n self.checkBox.setText(_translate('MainWindow', 'Log', None))\n self.plotImageButton.setText(_translate('MainWindow', 'Plot Image',\n None))\n self.clearPlotButton.setText(_translate('MainWindow', 'Clear', None))\n self.label_9.setText(_translate('MainWindow',\n ' PLOT TOTAL COUNTS vs STRIP', None))\n self.pushButton.setText(_translate('MainWindow', 'Update', None))\n self.plotStripsButton.setText(_translate('MainWindow',\n 'Plot Strips', None))\n self.toolBar.setWindowTitle(_translate('MainWindow', 'toolBar', None))\n self.actionOpen.setText(_translate('MainWindow', 'Open', None))\n self.actionQuit.setText(_translate('MainWindow', 'Quit', None))\n",
"step-4": "from PyQt4 import QtCore, QtGui\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n\n def _fromUtf8(s):\n return s\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\n\nclass Ui_MainWindow(object):\n\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(_fromUtf8('MainWindow'))\n MainWindow.resize(661, 728)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.\n QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(MainWindow.sizePolicy().\n hasHeightForWidth())\n MainWindow.setSizePolicy(sizePolicy)\n MainWindow.setMinimumSize(QtCore.QSize(100, 100))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n MainWindow.setFont(font)\n MainWindow.setAutoFillBackground(False)\n MainWindow.setTabShape(QtGui.QTabWidget.Rounded)\n self.centralwidget = QtGui.QWidget(MainWindow)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().\n hasHeightForWidth())\n self.centralwidget.setSizePolicy(sizePolicy)\n self.centralwidget.setMinimumSize(QtCore.QSize(100, 100))\n self.centralwidget.setMaximumSize(QtCore.QSize(1000, 1000))\n self.centralwidget.setObjectName(_fromUtf8('centralwidget'))\n self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)\n self.verticalLayout.setObjectName(_fromUtf8('verticalLayout'))\n self.groupBox_3 = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.\n QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox_3.sizePolicy().\n hasHeightForWidth())\n self.groupBox_3.setSizePolicy(sizePolicy)\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox_3.setFont(font)\n self.groupBox_3.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.groupBox_3.setAutoFillBackground(True)\n self.groupBox_3.setAlignment(QtCore.Qt.AlignLeading | QtCore.Qt.\n AlignLeft | QtCore.Qt.AlignVCenter)\n self.groupBox_3.setObjectName(_fromUtf8('groupBox_3'))\n self.gridLayout = QtGui.QGridLayout(self.groupBox_3)\n self.gridLayout.setSizeConstraint(QtGui.QLayout.SetNoConstraint)\n self.gridLayout.setObjectName(_fromUtf8('gridLayout'))\n self.MainVertLayout = QtGui.QVBoxLayout()\n self.MainVertLayout.setSizeConstraint(QtGui.QLayout.SetMaximumSize)\n self.MainVertLayout.setContentsMargins(-1, 10, -1, -1)\n self.MainVertLayout.setSpacing(0)\n self.MainVertLayout.setObjectName(_fromUtf8('MainVertLayout'))\n self.gridLayout.addLayout(self.MainVertLayout, 0, 0, 1, 1)\n self.verticalLayout.addWidget(self.groupBox_3)\n self.groupBox = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().\n hasHeightForWidth())\n self.groupBox.setSizePolicy(sizePolicy)\n self.groupBox.setMinimumSize(QtCore.QSize(100, 200))\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox.setFont(font)\n self.groupBox.setWhatsThis(_fromUtf8(''))\n self.groupBox.setObjectName(_fromUtf8('groupBox'))\n self.horizontalLayoutWidget_6 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_6.setGeometry(QtCore.QRect(17, 101, 594,\n 32))\n self.horizontalLayoutWidget_6.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_6'))\n self.horizontalLayout_9 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_6)\n self.horizontalLayout_9.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_9.setObjectName(_fromUtf8('horizontalLayout_9'))\n self.label_7 = QtGui.QLabel(self.horizontalLayoutWidget_6)\n self.label_7.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_7.setFont(font)\n self.label_7.setObjectName(_fromUtf8('label_7'))\n self.horizontalLayout_9.addWidget(self.label_7)\n self.browserButton_7 = QtGui.QPushButton(self.horizontalLayoutWidget_6)\n self.browserButton_7.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_7.sizePolicy().\n hasHeightForWidth())\n self.browserButton_7.setSizePolicy(sizePolicy)\n self.browserButton_7.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton_7.setObjectName(_fromUtf8('browserButton_7'))\n self.horizontalLayout_9.addWidget(self.browserButton_7)\n self.filePathEdit_7 = QtGui.QLineEdit(self.horizontalLayoutWidget_6)\n self.filePathEdit_7.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_7.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_7.setSizePolicy(sizePolicy)\n self.filePathEdit_7.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_7.setObjectName(_fromUtf8('filePathEdit_7'))\n self.horizontalLayout_9.addWidget(self.filePathEdit_7)\n self.horizontalLayoutWidget_9 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_9.setGeometry(QtCore.QRect(17, 25, 592, 32)\n )\n self.horizontalLayoutWidget_9.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_9'))\n self.horizontalLayout_10 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_9)\n self.horizontalLayout_10.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_10.setObjectName(_fromUtf8('horizontalLayout_10')\n )\n self.label_11 = QtGui.QLabel(self.horizontalLayoutWidget_9)\n self.label_11.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_11.setFont(font)\n self.label_11.setObjectName(_fromUtf8('label_11'))\n self.horizontalLayout_10.addWidget(self.label_11)\n self.browserButton = QtGui.QPushButton(self.horizontalLayoutWidget_9)\n self.browserButton.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton.sizePolicy().\n hasHeightForWidth())\n self.browserButton.setSizePolicy(sizePolicy)\n self.browserButton.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton.setObjectName(_fromUtf8('browserButton'))\n self.horizontalLayout_10.addWidget(self.browserButton)\n self.filePathEdit_3 = QtGui.QLineEdit(self.horizontalLayoutWidget_9)\n self.filePathEdit_3.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_3.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_3.setSizePolicy(sizePolicy)\n self.filePathEdit_3.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_3.setObjectName(_fromUtf8('filePathEdit_3'))\n self.horizontalLayout_10.addWidget(self.filePathEdit_3)\n self.horizontalLayoutWidget_10 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_10.setGeometry(QtCore.QRect(17, 63, 592,\n 32))\n self.horizontalLayoutWidget_10.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_10'))\n self.horizontalLayout_11 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_10)\n self.horizontalLayout_11.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_11.setObjectName(_fromUtf8('horizontalLayout_11')\n )\n self.label_12 = QtGui.QLabel(self.horizontalLayoutWidget_10)\n self.label_12.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_12.setFont(font)\n self.label_12.setObjectName(_fromUtf8('label_12'))\n self.horizontalLayout_11.addWidget(self.label_12)\n self.browserButton_3 = QtGui.QPushButton(self.horizontalLayoutWidget_10\n )\n self.browserButton_3.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_3.sizePolicy().\n hasHeightForWidth())\n self.browserButton_3.setSizePolicy(sizePolicy)\n self.browserButton_3.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton_3.setObjectName(_fromUtf8('browserButton_3'))\n self.horizontalLayout_11.addWidget(self.browserButton_3)\n self.filePathEdit_5 = QtGui.QLineEdit(self.horizontalLayoutWidget_10)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_5.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_5.setSizePolicy(sizePolicy)\n self.filePathEdit_5.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_5.setObjectName(_fromUtf8('filePathEdit_5'))\n self.horizontalLayout_11.addWidget(self.filePathEdit_5)\n self.runButton = QtGui.QPushButton(self.groupBox)\n self.runButton.setGeometry(QtCore.QRect(520, 140, 85, 50))\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.runButton.sizePolicy().\n hasHeightForWidth())\n self.runButton.setSizePolicy(sizePolicy)\n self.runButton.setMinimumSize(QtCore.QSize(80, 50))\n self.runButton.setIconSize(QtCore.QSize(24, 24))\n self.runButton.setObjectName(_fromUtf8('runButton'))\n self.verticalLayout.addWidget(self.groupBox)\n self.groupBox_2 = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox_2.sizePolicy().\n hasHeightForWidth())\n self.groupBox_2.setSizePolicy(sizePolicy)\n self.groupBox_2.setMinimumSize(QtCore.QSize(100, 225))\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox_2.setFont(font)\n self.groupBox_2.setAutoFillBackground(True)\n self.groupBox_2.setObjectName(_fromUtf8('groupBox_2'))\n self.horizontalLayoutWidget_4 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_4.setGeometry(QtCore.QRect(17, 25, 591, 32)\n )\n self.horizontalLayoutWidget_4.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_4'))\n self.horizontalLayout_6 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_4)\n self.horizontalLayout_6.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_6.setObjectName(_fromUtf8('horizontalLayout_6'))\n self.label_3 = QtGui.QLabel(self.horizontalLayoutWidget_4)\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8('label_3'))\n self.horizontalLayout_6.addWidget(self.label_3)\n self.browserButton_4 = QtGui.QPushButton(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_4.sizePolicy().\n hasHeightForWidth())\n self.browserButton_4.setSizePolicy(sizePolicy)\n self.browserButton_4.setObjectName(_fromUtf8('browserButton_4'))\n self.horizontalLayout_6.addWidget(self.browserButton_4)\n self.loadButton = QtGui.QPushButton(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.loadButton.sizePolicy().\n hasHeightForWidth())\n self.loadButton.setSizePolicy(sizePolicy)\n self.loadButton.setObjectName(_fromUtf8('loadButton'))\n self.horizontalLayout_6.addWidget(self.loadButton)\n self.filePathEdit_4 = QtGui.QLineEdit(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_4.sizePolicy().\n hasHeightForWidth())\n self.filePathEdit_4.setSizePolicy(sizePolicy)\n self.filePathEdit_4.setMinimumSize(QtCore.QSize(300, 30))\n self.filePathEdit_4.setObjectName(_fromUtf8('filePathEdit_4'))\n self.horizontalLayout_6.addWidget(self.filePathEdit_4)\n self.horizontalLayoutWidget_2 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(17, 63, 481, 29)\n )\n self.horizontalLayoutWidget_2.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_2'))\n self.horizontalLayout_2 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_2)\n self.horizontalLayout_2.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_2.setObjectName(_fromUtf8('horizontalLayout_2'))\n self.label_4 = QtGui.QLabel(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label_4.sizePolicy().\n hasHeightForWidth())\n self.label_4.setSizePolicy(sizePolicy)\n self.label_4.setObjectName(_fromUtf8('label_4'))\n self.horizontalLayout_2.addWidget(self.label_4)\n self.comboBox = QtGui.QComboBox(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox.sizePolicy().\n hasHeightForWidth())\n self.comboBox.setSizePolicy(sizePolicy)\n self.comboBox.setObjectName(_fromUtf8('comboBox'))\n self.horizontalLayout_2.addWidget(self.comboBox)\n self.plotButton = QtGui.QPushButton(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotButton.sizePolicy().\n hasHeightForWidth())\n self.plotButton.setSizePolicy(sizePolicy)\n self.plotButton.setObjectName(_fromUtf8('plotButton'))\n self.horizontalLayout_2.addWidget(self.plotButton)\n self.horizontalLayoutWidget_3 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(17, 100, 481,\n 29))\n self.horizontalLayoutWidget_3.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_3'))\n self.horizontalLayout_3 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_3)\n self.horizontalLayout_3.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_3.setObjectName(_fromUtf8('horizontalLayout_3'))\n self.label_5 = QtGui.QLabel(self.horizontalLayoutWidget_3)\n self.label_5.setObjectName(_fromUtf8('label_5'))\n self.horizontalLayout_3.addWidget(self.label_5)\n self.comboBox_R1 = QtGui.QComboBox(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_R1.sizePolicy().\n hasHeightForWidth())\n self.comboBox_R1.setSizePolicy(sizePolicy)\n self.comboBox_R1.setMinimumSize(QtCore.QSize(0, 0))\n self.comboBox_R1.setObjectName(_fromUtf8('comboBox_R1'))\n self.horizontalLayout_3.addWidget(self.comboBox_R1)\n self.label = QtGui.QLabel(self.horizontalLayoutWidget_3)\n self.label.setEnabled(False)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label.sizePolicy().\n hasHeightForWidth())\n self.label.setSizePolicy(sizePolicy)\n self.label.setMinimumSize(QtCore.QSize(30, 0))\n self.label.setMaximumSize(QtCore.QSize(30, 29))\n font = QtGui.QFont()\n font.setBold(True)\n font.setItalic(True)\n font.setUnderline(False)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setAutoFillBackground(True)\n self.label.setLineWidth(5)\n self.label.setAlignment(QtCore.Qt.AlignCenter)\n self.label.setObjectName(_fromUtf8('label'))\n self.horizontalLayout_3.addWidget(self.label)\n self.comboBox_R2 = QtGui.QComboBox(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_R2.sizePolicy().\n hasHeightForWidth())\n self.comboBox_R2.setSizePolicy(sizePolicy)\n self.comboBox_R2.setObjectName(_fromUtf8('comboBox_R2'))\n self.horizontalLayout_3.addWidget(self.comboBox_R2)\n self.plotRangeButton = QtGui.QPushButton(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotRangeButton.sizePolicy().\n hasHeightForWidth())\n self.plotRangeButton.setSizePolicy(sizePolicy)\n self.plotRangeButton.setObjectName(_fromUtf8('plotRangeButton'))\n self.horizontalLayout_3.addWidget(self.plotRangeButton)\n self.horizontalLayoutWidget_7 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_7.setGeometry(QtCore.QRect(17, 140, 481,\n 29))\n self.horizontalLayoutWidget_7.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget_7'))\n self.horizontalLayout_5 = QtGui.QHBoxLayout(self.\n horizontalLayoutWidget_7)\n self.horizontalLayout_5.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_5.setObjectName(_fromUtf8('horizontalLayout_5'))\n self.label_8 = QtGui.QLabel(self.horizontalLayoutWidget_7)\n self.label_8.setObjectName(_fromUtf8('label_8'))\n self.horizontalLayout_5.addWidget(self.label_8)\n self.comboBox_2 = QtGui.QComboBox(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_2.sizePolicy().\n hasHeightForWidth())\n self.comboBox_2.setSizePolicy(sizePolicy)\n self.comboBox_2.setObjectName(_fromUtf8('comboBox_2'))\n self.horizontalLayout_5.addWidget(self.comboBox_2)\n self.checkBox = QtGui.QCheckBox(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.checkBox.sizePolicy().\n hasHeightForWidth())\n self.checkBox.setSizePolicy(sizePolicy)\n self.checkBox.setObjectName(_fromUtf8('checkBox'))\n self.horizontalLayout_5.addWidget(self.checkBox)\n self.plotImageButton = QtGui.QPushButton(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotImageButton.sizePolicy().\n hasHeightForWidth())\n self.plotImageButton.setSizePolicy(sizePolicy)\n self.plotImageButton.setMinimumSize(QtCore.QSize(80, 15))\n self.plotImageButton.setObjectName(_fromUtf8('plotImageButton'))\n self.horizontalLayout_5.addWidget(self.plotImageButton)\n self.clearPlotButton = QtGui.QPushButton(self.groupBox_2)\n self.clearPlotButton.setGeometry(QtCore.QRect(520, 140, 85, 50))\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.clearPlotButton.sizePolicy().\n hasHeightForWidth())\n self.clearPlotButton.setSizePolicy(sizePolicy)\n self.clearPlotButton.setMinimumSize(QtCore.QSize(80, 50))\n self.clearPlotButton.setObjectName(_fromUtf8('clearPlotButton'))\n self.horizontalLayoutWidget = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget.setGeometry(QtCore.QRect(17, 180, 481, 29))\n self.horizontalLayoutWidget.setObjectName(_fromUtf8(\n 'horizontalLayoutWidget'))\n self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)\n self.horizontalLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout.setObjectName(_fromUtf8('horizontalLayout'))\n self.label_9 = QtGui.QLabel(self.horizontalLayoutWidget)\n self.label_9.setObjectName(_fromUtf8('label_9'))\n self.horizontalLayout.addWidget(self.label_9)\n self.pushButton = QtGui.QPushButton(self.horizontalLayoutWidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().\n hasHeightForWidth())\n self.pushButton.setSizePolicy(sizePolicy)\n self.pushButton.setMinimumSize(QtCore.QSize(80, 15))\n self.pushButton.setObjectName(_fromUtf8('pushButton'))\n self.horizontalLayout.addWidget(self.pushButton)\n self.plotStripsButton = QtGui.QPushButton(self.horizontalLayoutWidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.\n QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotStripsButton.sizePolicy().\n hasHeightForWidth())\n self.plotStripsButton.setSizePolicy(sizePolicy)\n self.plotStripsButton.setMinimumSize(QtCore.QSize(80, 15))\n self.plotStripsButton.setObjectName(_fromUtf8('plotStripsButton'))\n self.horizontalLayout.addWidget(self.plotStripsButton)\n self.verticalLayout.addWidget(self.groupBox_2)\n MainWindow.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(MainWindow)\n self.statusbar.setObjectName(_fromUtf8('statusbar'))\n MainWindow.setStatusBar(self.statusbar)\n self.toolBar = QtGui.QToolBar(MainWindow)\n self.toolBar.setObjectName(_fromUtf8('toolBar'))\n MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)\n self.menuBar = QtGui.QMenuBar(MainWindow)\n self.menuBar.setGeometry(QtCore.QRect(0, 0, 661, 22))\n self.menuBar.setObjectName(_fromUtf8('menuBar'))\n MainWindow.setMenuBar(self.menuBar)\n self.actionOpen = QtGui.QAction(MainWindow)\n self.actionOpen.setVisible(True)\n self.actionOpen.setObjectName(_fromUtf8('actionOpen'))\n self.actionQuit = QtGui.QAction(MainWindow)\n self.actionQuit.setObjectName(_fromUtf8('actionQuit'))\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n MainWindow.setWindowTitle(_translate('MainWindow', 'MainWindow', None))\n self.groupBox_3.setTitle(_translate('MainWindow', 'PLOT WINDOW', None))\n self.groupBox.setTitle(_translate('MainWindow',\n ' BINARY DATA CONVERSION', None))\n self.label_7.setText(_translate('MainWindow', ' OUTPUT FILE ', None))\n self.browserButton_7.setText(_translate('MainWindow', 'Browse', None))\n self.filePathEdit_7.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\', None))\n self.label_11.setText(_translate('MainWindow', ' DECODER FILE', None))\n self.browserButton.setText(_translate('MainWindow', 'Browse', None))\n self.filePathEdit_3.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\qtGSD\\\\gsd_parse.out', None))\n self.label_12.setText(_translate('MainWindow', ' INPUT FILE ',\n None))\n self.browserButton_3.setText(_translate('MainWindow', 'Browse', None))\n self.filePathEdit_5.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\', None))\n self.runButton.setText(_translate('MainWindow', 'Run', None))\n self.groupBox_2.setTitle(_translate('MainWindow', ' PLOT DATA', None))\n self.label_3.setText(_translate('MainWindow', ' DATA FILE ', None))\n self.browserButton_4.setText(_translate('MainWindow', 'Browse', None))\n self.loadButton.setText(_translate('MainWindow', 'Load', None))\n self.filePathEdit_4.setText(_translate('MainWindow',\n 'D:\\\\detdev\\\\maia\\\\python\\\\', None))\n self.label_4.setText(_translate('MainWindow', ' PLOT STRIP ', None))\n self.plotButton.setText(_translate('MainWindow', 'Plot', None))\n self.label_5.setText(_translate('MainWindow', ' PLOT SERIES', None))\n self.label.setText(_translate('MainWindow', 'to', None))\n self.plotRangeButton.setText(_translate('MainWindow', 'Plot', None))\n self.label_8.setText(_translate('MainWindow',\n ' PLOT SPECTRA AS 2-D IMAGE', None))\n self.checkBox.setText(_translate('MainWindow', 'Log', None))\n self.plotImageButton.setText(_translate('MainWindow', 'Plot Image',\n None))\n self.clearPlotButton.setText(_translate('MainWindow', 'Clear', None))\n self.label_9.setText(_translate('MainWindow',\n ' PLOT TOTAL COUNTS vs STRIP', None))\n self.pushButton.setText(_translate('MainWindow', 'Update', None))\n self.plotStripsButton.setText(_translate('MainWindow',\n 'Plot Strips', None))\n self.toolBar.setWindowTitle(_translate('MainWindow', 'toolBar', None))\n self.actionOpen.setText(_translate('MainWindow', 'Open', None))\n self.actionQuit.setText(_translate('MainWindow', 'Quit', None))\n",
"step-5": "# -*- coding: utf-8 -*-\n\n# Form implementation generated from reading ui file 'qtGSD_DESIGN.ui'\n#\n# Created by: PyQt4 UI code generator 4.11.4\n#\n# WARNING! All changes made in this file will be lost!\n\nfrom PyQt4 import QtCore, QtGui\n\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\nclass Ui_MainWindow(object):\n def setupUi(self, MainWindow):\n MainWindow.setObjectName(_fromUtf8(\"MainWindow\"))\n MainWindow.resize(661, 728)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(MainWindow.sizePolicy().hasHeightForWidth())\n MainWindow.setSizePolicy(sizePolicy)\n MainWindow.setMinimumSize(QtCore.QSize(100, 100))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n MainWindow.setFont(font)\n MainWindow.setAutoFillBackground(False)\n MainWindow.setTabShape(QtGui.QTabWidget.Rounded)\n self.centralwidget = QtGui.QWidget(MainWindow)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())\n self.centralwidget.setSizePolicy(sizePolicy)\n self.centralwidget.setMinimumSize(QtCore.QSize(100, 100))\n self.centralwidget.setMaximumSize(QtCore.QSize(1000, 1000))\n self.centralwidget.setObjectName(_fromUtf8(\"centralwidget\"))\n self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)\n self.verticalLayout.setObjectName(_fromUtf8(\"verticalLayout\"))\n self.groupBox_3 = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox_3.sizePolicy().hasHeightForWidth())\n self.groupBox_3.setSizePolicy(sizePolicy)\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox_3.setFont(font)\n self.groupBox_3.setLayoutDirection(QtCore.Qt.LeftToRight)\n self.groupBox_3.setAutoFillBackground(True)\n self.groupBox_3.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)\n self.groupBox_3.setObjectName(_fromUtf8(\"groupBox_3\"))\n self.gridLayout = QtGui.QGridLayout(self.groupBox_3)\n self.gridLayout.setSizeConstraint(QtGui.QLayout.SetNoConstraint)\n self.gridLayout.setObjectName(_fromUtf8(\"gridLayout\"))\n self.MainVertLayout = QtGui.QVBoxLayout()\n self.MainVertLayout.setSizeConstraint(QtGui.QLayout.SetMaximumSize)\n self.MainVertLayout.setContentsMargins(-1, 10, -1, -1)\n self.MainVertLayout.setSpacing(0)\n self.MainVertLayout.setObjectName(_fromUtf8(\"MainVertLayout\"))\n self.gridLayout.addLayout(self.MainVertLayout, 0, 0, 1, 1)\n self.verticalLayout.addWidget(self.groupBox_3)\n self.groupBox = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox.sizePolicy().hasHeightForWidth())\n self.groupBox.setSizePolicy(sizePolicy)\n self.groupBox.setMinimumSize(QtCore.QSize(100, 200))\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox.setFont(font)\n self.groupBox.setWhatsThis(_fromUtf8(\"\"))\n self.groupBox.setObjectName(_fromUtf8(\"groupBox\"))\n self.horizontalLayoutWidget_6 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_6.setGeometry(QtCore.QRect(17, 101, 594, 32))\n self.horizontalLayoutWidget_6.setObjectName(_fromUtf8(\"horizontalLayoutWidget_6\"))\n self.horizontalLayout_9 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_6)\n self.horizontalLayout_9.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_9.setObjectName(_fromUtf8(\"horizontalLayout_9\"))\n self.label_7 = QtGui.QLabel(self.horizontalLayoutWidget_6)\n self.label_7.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_7.setFont(font)\n self.label_7.setObjectName(_fromUtf8(\"label_7\"))\n self.horizontalLayout_9.addWidget(self.label_7)\n self.browserButton_7 = QtGui.QPushButton(self.horizontalLayoutWidget_6)\n self.browserButton_7.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_7.sizePolicy().hasHeightForWidth())\n self.browserButton_7.setSizePolicy(sizePolicy)\n self.browserButton_7.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton_7.setObjectName(_fromUtf8(\"browserButton_7\"))\n self.horizontalLayout_9.addWidget(self.browserButton_7)\n self.filePathEdit_7 = QtGui.QLineEdit(self.horizontalLayoutWidget_6)\n self.filePathEdit_7.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_7.sizePolicy().hasHeightForWidth())\n self.filePathEdit_7.setSizePolicy(sizePolicy)\n self.filePathEdit_7.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_7.setObjectName(_fromUtf8(\"filePathEdit_7\"))\n self.horizontalLayout_9.addWidget(self.filePathEdit_7)\n self.horizontalLayoutWidget_9 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_9.setGeometry(QtCore.QRect(17, 25, 592, 32))\n self.horizontalLayoutWidget_9.setObjectName(_fromUtf8(\"horizontalLayoutWidget_9\"))\n self.horizontalLayout_10 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_9)\n self.horizontalLayout_10.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_10.setObjectName(_fromUtf8(\"horizontalLayout_10\"))\n self.label_11 = QtGui.QLabel(self.horizontalLayoutWidget_9)\n self.label_11.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_11.setFont(font)\n self.label_11.setObjectName(_fromUtf8(\"label_11\"))\n self.horizontalLayout_10.addWidget(self.label_11)\n self.browserButton = QtGui.QPushButton(self.horizontalLayoutWidget_9)\n self.browserButton.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton.sizePolicy().hasHeightForWidth())\n self.browserButton.setSizePolicy(sizePolicy)\n self.browserButton.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton.setObjectName(_fromUtf8(\"browserButton\"))\n self.horizontalLayout_10.addWidget(self.browserButton)\n self.filePathEdit_3 = QtGui.QLineEdit(self.horizontalLayoutWidget_9)\n self.filePathEdit_3.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Expanding)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_3.sizePolicy().hasHeightForWidth())\n self.filePathEdit_3.setSizePolicy(sizePolicy)\n self.filePathEdit_3.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_3.setObjectName(_fromUtf8(\"filePathEdit_3\"))\n self.horizontalLayout_10.addWidget(self.filePathEdit_3)\n self.horizontalLayoutWidget_10 = QtGui.QWidget(self.groupBox)\n self.horizontalLayoutWidget_10.setGeometry(QtCore.QRect(17, 63, 592, 32))\n self.horizontalLayoutWidget_10.setObjectName(_fromUtf8(\"horizontalLayoutWidget_10\"))\n self.horizontalLayout_11 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_10)\n self.horizontalLayout_11.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_11.setObjectName(_fromUtf8(\"horizontalLayout_11\"))\n self.label_12 = QtGui.QLabel(self.horizontalLayoutWidget_10)\n self.label_12.setMinimumSize(QtCore.QSize(0, 30))\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_12.setFont(font)\n self.label_12.setObjectName(_fromUtf8(\"label_12\"))\n self.horizontalLayout_11.addWidget(self.label_12)\n self.browserButton_3 = QtGui.QPushButton(self.horizontalLayoutWidget_10)\n self.browserButton_3.setEnabled(True)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_3.sizePolicy().hasHeightForWidth())\n self.browserButton_3.setSizePolicy(sizePolicy)\n self.browserButton_3.setMinimumSize(QtCore.QSize(80, 15))\n self.browserButton_3.setObjectName(_fromUtf8(\"browserButton_3\"))\n self.horizontalLayout_11.addWidget(self.browserButton_3)\n self.filePathEdit_5 = QtGui.QLineEdit(self.horizontalLayoutWidget_10)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_5.sizePolicy().hasHeightForWidth())\n self.filePathEdit_5.setSizePolicy(sizePolicy)\n self.filePathEdit_5.setMinimumSize(QtCore.QSize(400, 30))\n self.filePathEdit_5.setObjectName(_fromUtf8(\"filePathEdit_5\"))\n self.horizontalLayout_11.addWidget(self.filePathEdit_5)\n self.runButton = QtGui.QPushButton(self.groupBox)\n self.runButton.setGeometry(QtCore.QRect(520, 140, 85, 50))\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.runButton.sizePolicy().hasHeightForWidth())\n self.runButton.setSizePolicy(sizePolicy)\n self.runButton.setMinimumSize(QtCore.QSize(80, 50))\n self.runButton.setIconSize(QtCore.QSize(24, 24))\n self.runButton.setObjectName(_fromUtf8(\"runButton\"))\n self.verticalLayout.addWidget(self.groupBox)\n self.groupBox_2 = QtGui.QGroupBox(self.centralwidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.groupBox_2.sizePolicy().hasHeightForWidth())\n self.groupBox_2.setSizePolicy(sizePolicy)\n self.groupBox_2.setMinimumSize(QtCore.QSize(100, 225))\n font = QtGui.QFont()\n font.setBold(False)\n font.setItalic(False)\n font.setWeight(50)\n self.groupBox_2.setFont(font)\n self.groupBox_2.setAutoFillBackground(True)\n self.groupBox_2.setObjectName(_fromUtf8(\"groupBox_2\"))\n self.horizontalLayoutWidget_4 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_4.setGeometry(QtCore.QRect(17, 25, 591, 32))\n self.horizontalLayoutWidget_4.setObjectName(_fromUtf8(\"horizontalLayoutWidget_4\"))\n self.horizontalLayout_6 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_4)\n self.horizontalLayout_6.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_6.setObjectName(_fromUtf8(\"horizontalLayout_6\"))\n self.label_3 = QtGui.QLabel(self.horizontalLayoutWidget_4)\n font = QtGui.QFont()\n font.setBold(False)\n font.setWeight(50)\n self.label_3.setFont(font)\n self.label_3.setObjectName(_fromUtf8(\"label_3\"))\n self.horizontalLayout_6.addWidget(self.label_3)\n self.browserButton_4 = QtGui.QPushButton(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.browserButton_4.sizePolicy().hasHeightForWidth())\n self.browserButton_4.setSizePolicy(sizePolicy)\n self.browserButton_4.setObjectName(_fromUtf8(\"browserButton_4\"))\n self.horizontalLayout_6.addWidget(self.browserButton_4)\n self.loadButton = QtGui.QPushButton(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.loadButton.sizePolicy().hasHeightForWidth())\n self.loadButton.setSizePolicy(sizePolicy)\n self.loadButton.setObjectName(_fromUtf8(\"loadButton\"))\n self.horizontalLayout_6.addWidget(self.loadButton)\n self.filePathEdit_4 = QtGui.QLineEdit(self.horizontalLayoutWidget_4)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.filePathEdit_4.sizePolicy().hasHeightForWidth())\n self.filePathEdit_4.setSizePolicy(sizePolicy)\n self.filePathEdit_4.setMinimumSize(QtCore.QSize(300, 30))\n self.filePathEdit_4.setObjectName(_fromUtf8(\"filePathEdit_4\"))\n self.horizontalLayout_6.addWidget(self.filePathEdit_4)\n self.horizontalLayoutWidget_2 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_2.setGeometry(QtCore.QRect(17, 63, 481, 29))\n self.horizontalLayoutWidget_2.setObjectName(_fromUtf8(\"horizontalLayoutWidget_2\"))\n self.horizontalLayout_2 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_2)\n self.horizontalLayout_2.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_2.setObjectName(_fromUtf8(\"horizontalLayout_2\"))\n self.label_4 = QtGui.QLabel(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label_4.sizePolicy().hasHeightForWidth())\n self.label_4.setSizePolicy(sizePolicy)\n self.label_4.setObjectName(_fromUtf8(\"label_4\"))\n self.horizontalLayout_2.addWidget(self.label_4)\n self.comboBox = QtGui.QComboBox(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox.sizePolicy().hasHeightForWidth())\n self.comboBox.setSizePolicy(sizePolicy)\n self.comboBox.setObjectName(_fromUtf8(\"comboBox\"))\n self.horizontalLayout_2.addWidget(self.comboBox)\n self.plotButton = QtGui.QPushButton(self.horizontalLayoutWidget_2)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotButton.sizePolicy().hasHeightForWidth())\n self.plotButton.setSizePolicy(sizePolicy)\n self.plotButton.setObjectName(_fromUtf8(\"plotButton\"))\n self.horizontalLayout_2.addWidget(self.plotButton)\n self.horizontalLayoutWidget_3 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_3.setGeometry(QtCore.QRect(17, 100, 481, 29))\n self.horizontalLayoutWidget_3.setObjectName(_fromUtf8(\"horizontalLayoutWidget_3\"))\n self.horizontalLayout_3 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_3)\n self.horizontalLayout_3.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_3.setObjectName(_fromUtf8(\"horizontalLayout_3\"))\n self.label_5 = QtGui.QLabel(self.horizontalLayoutWidget_3)\n self.label_5.setObjectName(_fromUtf8(\"label_5\"))\n self.horizontalLayout_3.addWidget(self.label_5)\n self.comboBox_R1 = QtGui.QComboBox(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_R1.sizePolicy().hasHeightForWidth())\n self.comboBox_R1.setSizePolicy(sizePolicy)\n self.comboBox_R1.setMinimumSize(QtCore.QSize(0, 0))\n self.comboBox_R1.setObjectName(_fromUtf8(\"comboBox_R1\"))\n self.horizontalLayout_3.addWidget(self.comboBox_R1)\n self.label = QtGui.QLabel(self.horizontalLayoutWidget_3)\n self.label.setEnabled(False)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Preferred)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth())\n self.label.setSizePolicy(sizePolicy)\n self.label.setMinimumSize(QtCore.QSize(30, 0))\n self.label.setMaximumSize(QtCore.QSize(30, 29))\n font = QtGui.QFont()\n font.setBold(True)\n font.setItalic(True)\n font.setUnderline(False)\n font.setWeight(75)\n self.label.setFont(font)\n self.label.setAutoFillBackground(True)\n self.label.setLineWidth(5)\n self.label.setAlignment(QtCore.Qt.AlignCenter)\n self.label.setObjectName(_fromUtf8(\"label\"))\n self.horizontalLayout_3.addWidget(self.label)\n self.comboBox_R2 = QtGui.QComboBox(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_R2.sizePolicy().hasHeightForWidth())\n self.comboBox_R2.setSizePolicy(sizePolicy)\n self.comboBox_R2.setObjectName(_fromUtf8(\"comboBox_R2\"))\n self.horizontalLayout_3.addWidget(self.comboBox_R2)\n self.plotRangeButton = QtGui.QPushButton(self.horizontalLayoutWidget_3)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotRangeButton.sizePolicy().hasHeightForWidth())\n self.plotRangeButton.setSizePolicy(sizePolicy)\n self.plotRangeButton.setObjectName(_fromUtf8(\"plotRangeButton\"))\n self.horizontalLayout_3.addWidget(self.plotRangeButton)\n self.horizontalLayoutWidget_7 = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget_7.setGeometry(QtCore.QRect(17, 140, 481, 29))\n self.horizontalLayoutWidget_7.setObjectName(_fromUtf8(\"horizontalLayoutWidget_7\"))\n self.horizontalLayout_5 = QtGui.QHBoxLayout(self.horizontalLayoutWidget_7)\n self.horizontalLayout_5.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout_5.setObjectName(_fromUtf8(\"horizontalLayout_5\"))\n self.label_8 = QtGui.QLabel(self.horizontalLayoutWidget_7)\n self.label_8.setObjectName(_fromUtf8(\"label_8\"))\n self.horizontalLayout_5.addWidget(self.label_8)\n self.comboBox_2 = QtGui.QComboBox(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.comboBox_2.sizePolicy().hasHeightForWidth())\n self.comboBox_2.setSizePolicy(sizePolicy)\n self.comboBox_2.setObjectName(_fromUtf8(\"comboBox_2\"))\n self.horizontalLayout_5.addWidget(self.comboBox_2)\n self.checkBox = QtGui.QCheckBox(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.checkBox.sizePolicy().hasHeightForWidth())\n self.checkBox.setSizePolicy(sizePolicy)\n self.checkBox.setObjectName(_fromUtf8(\"checkBox\"))\n self.horizontalLayout_5.addWidget(self.checkBox)\n self.plotImageButton = QtGui.QPushButton(self.horizontalLayoutWidget_7)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotImageButton.sizePolicy().hasHeightForWidth())\n self.plotImageButton.setSizePolicy(sizePolicy)\n self.plotImageButton.setMinimumSize(QtCore.QSize(80, 15))\n self.plotImageButton.setObjectName(_fromUtf8(\"plotImageButton\"))\n self.horizontalLayout_5.addWidget(self.plotImageButton)\n self.clearPlotButton = QtGui.QPushButton(self.groupBox_2)\n self.clearPlotButton.setGeometry(QtCore.QRect(520, 140, 85, 50))\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.clearPlotButton.sizePolicy().hasHeightForWidth())\n self.clearPlotButton.setSizePolicy(sizePolicy)\n self.clearPlotButton.setMinimumSize(QtCore.QSize(80, 50))\n self.clearPlotButton.setObjectName(_fromUtf8(\"clearPlotButton\"))\n self.horizontalLayoutWidget = QtGui.QWidget(self.groupBox_2)\n self.horizontalLayoutWidget.setGeometry(QtCore.QRect(17, 180, 481, 29))\n self.horizontalLayoutWidget.setObjectName(_fromUtf8(\"horizontalLayoutWidget\"))\n self.horizontalLayout = QtGui.QHBoxLayout(self.horizontalLayoutWidget)\n self.horizontalLayout.setSizeConstraint(QtGui.QLayout.SetFixedSize)\n self.horizontalLayout.setObjectName(_fromUtf8(\"horizontalLayout\"))\n self.label_9 = QtGui.QLabel(self.horizontalLayoutWidget)\n self.label_9.setObjectName(_fromUtf8(\"label_9\"))\n self.horizontalLayout.addWidget(self.label_9)\n self.pushButton = QtGui.QPushButton(self.horizontalLayoutWidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.pushButton.sizePolicy().hasHeightForWidth())\n self.pushButton.setSizePolicy(sizePolicy)\n self.pushButton.setMinimumSize(QtCore.QSize(80, 15))\n self.pushButton.setObjectName(_fromUtf8(\"pushButton\"))\n self.horizontalLayout.addWidget(self.pushButton)\n self.plotStripsButton = QtGui.QPushButton(self.horizontalLayoutWidget)\n sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)\n sizePolicy.setHorizontalStretch(0)\n sizePolicy.setVerticalStretch(0)\n sizePolicy.setHeightForWidth(self.plotStripsButton.sizePolicy().hasHeightForWidth())\n self.plotStripsButton.setSizePolicy(sizePolicy)\n self.plotStripsButton.setMinimumSize(QtCore.QSize(80, 15))\n self.plotStripsButton.setObjectName(_fromUtf8(\"plotStripsButton\"))\n self.horizontalLayout.addWidget(self.plotStripsButton)\n self.verticalLayout.addWidget(self.groupBox_2)\n MainWindow.setCentralWidget(self.centralwidget)\n self.statusbar = QtGui.QStatusBar(MainWindow)\n self.statusbar.setObjectName(_fromUtf8(\"statusbar\"))\n MainWindow.setStatusBar(self.statusbar)\n self.toolBar = QtGui.QToolBar(MainWindow)\n self.toolBar.setObjectName(_fromUtf8(\"toolBar\"))\n MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.toolBar)\n self.menuBar = QtGui.QMenuBar(MainWindow)\n self.menuBar.setGeometry(QtCore.QRect(0, 0, 661, 22))\n self.menuBar.setObjectName(_fromUtf8(\"menuBar\"))\n MainWindow.setMenuBar(self.menuBar)\n self.actionOpen = QtGui.QAction(MainWindow)\n self.actionOpen.setVisible(True)\n self.actionOpen.setObjectName(_fromUtf8(\"actionOpen\"))\n self.actionQuit = QtGui.QAction(MainWindow)\n self.actionQuit.setObjectName(_fromUtf8(\"actionQuit\"))\n\n self.retranslateUi(MainWindow)\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\n\n def retranslateUi(self, MainWindow):\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"MainWindow\", None))\n self.groupBox_3.setTitle(_translate(\"MainWindow\", \"PLOT WINDOW\", None))\n self.groupBox.setTitle(_translate(\"MainWindow\", \" BINARY DATA CONVERSION\", None))\n self.label_7.setText(_translate(\"MainWindow\", \" OUTPUT FILE \", None))\n self.browserButton_7.setText(_translate(\"MainWindow\", \"Browse\", None))\n self.filePathEdit_7.setText(_translate(\"MainWindow\", \"D:\\\\detdev\\\\maia\\\\python\\\\\", None))\n self.label_11.setText(_translate(\"MainWindow\", \" DECODER FILE\", None))\n self.browserButton.setText(_translate(\"MainWindow\", \"Browse\", None))\n self.filePathEdit_3.setText(_translate(\"MainWindow\", \"D:\\\\detdev\\\\maia\\\\python\\\\qtGSD\\\\gsd_parse.out\", None))\n self.label_12.setText(_translate(\"MainWindow\", \" INPUT FILE \", None))\n self.browserButton_3.setText(_translate(\"MainWindow\", \"Browse\", None))\n self.filePathEdit_5.setText(_translate(\"MainWindow\", \"D:\\\\detdev\\\\maia\\\\python\\\\\", None))\n self.runButton.setText(_translate(\"MainWindow\", \"Run\", None))\n self.groupBox_2.setTitle(_translate(\"MainWindow\", \" PLOT DATA\", None))\n self.label_3.setText(_translate(\"MainWindow\", \" DATA FILE \", None))\n self.browserButton_4.setText(_translate(\"MainWindow\", \"Browse\", None))\n self.loadButton.setText(_translate(\"MainWindow\", \"Load\", None))\n self.filePathEdit_4.setText(_translate(\"MainWindow\", \"D:\\\\detdev\\\\maia\\\\python\\\\\", None))\n self.label_4.setText(_translate(\"MainWindow\", \" PLOT STRIP \", None))\n self.plotButton.setText(_translate(\"MainWindow\", \"Plot\", None))\n self.label_5.setText(_translate(\"MainWindow\", \" PLOT SERIES\", None))\n self.label.setText(_translate(\"MainWindow\", \"to\", None))\n self.plotRangeButton.setText(_translate(\"MainWindow\", \"Plot\", None))\n self.label_8.setText(_translate(\"MainWindow\", \" PLOT SPECTRA AS 2-D IMAGE\", None))\n self.checkBox.setText(_translate(\"MainWindow\", \"Log\", None))\n self.plotImageButton.setText(_translate(\"MainWindow\", \"Plot Image\", None))\n self.clearPlotButton.setText(_translate(\"MainWindow\", \"Clear\", None))\n self.label_9.setText(_translate(\"MainWindow\", \" PLOT TOTAL COUNTS vs STRIP\", None))\n self.pushButton.setText(_translate(\"MainWindow\", \"Update\", None))\n self.plotStripsButton.setText(_translate(\"MainWindow\", \"Plot Strips\", None))\n self.toolBar.setWindowTitle(_translate(\"MainWindow\", \"toolBar\", None))\n self.actionOpen.setText(_translate(\"MainWindow\", \"Open\", None))\n self.actionQuit.setText(_translate(\"MainWindow\", \"Quit\", None))\n\n",
"step-ids": [
1,
3,
4,
5,
6
]
}
|
[
1,
3,
4,
5,
6
] |
<|reserved_special_token_0|>
class ImageSelection:
def __init__(self, path):
self.path = path
def brightness_check(self, image):
"""count function to set value of brightness, 0 - full black, 100 - full bright"""
with Image.open(image).convert('L') as img:
z = ImageStat.Stat(img)
stat = 100 * (255 - z.mean[0]) / 255
return int(stat)
def averange_threshold(self, dictionary, img_list):
"""counts thrshold which is RMS of all images value"""
sum = 0
for value in dictionary.values():
sum += value
return int(sum / len(img_list))
def image_analysis(self):
"""execution of class, creates two folders (bright, dark) in path
to images name is added theior value of brightness"""
img_list = os.listdir(self.path)
img_list = [os.path.join(self.path, elem) for elem in img_list]
extend_set = {'.png', '.jpeg', '.jpg'}
dictionary = {os.path.basename(img): ImageSelection.
brightness_check(self, img) for ext in extend_set for img in
img_list if ext in img}
threshold = ImageSelection.averange_threshold(self, dictionary,
img_list)
for key, value in dictionary.items():
if value < threshold:
os.makedirs(os.path.join(self.path, 'bright'), exist_ok=True)
shutil.copy(os.path.join(self.path, key), os.path.join(self
.path, 'bright', key[:key.index('.')] + '_' + str(value
) + key[key.index('.'):]))
else:
os.makedirs(os.path.join(self.path, 'dark'), exist_ok=True)
shutil.copy(os.path.join(self.path, key), os.path.join(self
.path, 'dark', key[:key.index('.')] + '_' + str(value) +
key[key.index('.'):]))
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class ImageSelection:
def __init__(self, path):
self.path = path
def brightness_check(self, image):
"""count function to set value of brightness, 0 - full black, 100 - full bright"""
with Image.open(image).convert('L') as img:
z = ImageStat.Stat(img)
stat = 100 * (255 - z.mean[0]) / 255
return int(stat)
def averange_threshold(self, dictionary, img_list):
"""counts thrshold which is RMS of all images value"""
sum = 0
for value in dictionary.values():
sum += value
return int(sum / len(img_list))
def image_analysis(self):
"""execution of class, creates two folders (bright, dark) in path
to images name is added theior value of brightness"""
img_list = os.listdir(self.path)
img_list = [os.path.join(self.path, elem) for elem in img_list]
extend_set = {'.png', '.jpeg', '.jpg'}
dictionary = {os.path.basename(img): ImageSelection.
brightness_check(self, img) for ext in extend_set for img in
img_list if ext in img}
threshold = ImageSelection.averange_threshold(self, dictionary,
img_list)
for key, value in dictionary.items():
if value < threshold:
os.makedirs(os.path.join(self.path, 'bright'), exist_ok=True)
shutil.copy(os.path.join(self.path, key), os.path.join(self
.path, 'bright', key[:key.index('.')] + '_' + str(value
) + key[key.index('.'):]))
else:
os.makedirs(os.path.join(self.path, 'dark'), exist_ok=True)
shutil.copy(os.path.join(self.path, key), os.path.join(self
.path, 'dark', key[:key.index('.')] + '_' + str(value) +
key[key.index('.'):]))
<|reserved_special_token_0|>
a.image_analysis()
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class ImageSelection:
def __init__(self, path):
self.path = path
def brightness_check(self, image):
"""count function to set value of brightness, 0 - full black, 100 - full bright"""
with Image.open(image).convert('L') as img:
z = ImageStat.Stat(img)
stat = 100 * (255 - z.mean[0]) / 255
return int(stat)
def averange_threshold(self, dictionary, img_list):
"""counts thrshold which is RMS of all images value"""
sum = 0
for value in dictionary.values():
sum += value
return int(sum / len(img_list))
def image_analysis(self):
"""execution of class, creates two folders (bright, dark) in path
to images name is added theior value of brightness"""
img_list = os.listdir(self.path)
img_list = [os.path.join(self.path, elem) for elem in img_list]
extend_set = {'.png', '.jpeg', '.jpg'}
dictionary = {os.path.basename(img): ImageSelection.
brightness_check(self, img) for ext in extend_set for img in
img_list if ext in img}
threshold = ImageSelection.averange_threshold(self, dictionary,
img_list)
for key, value in dictionary.items():
if value < threshold:
os.makedirs(os.path.join(self.path, 'bright'), exist_ok=True)
shutil.copy(os.path.join(self.path, key), os.path.join(self
.path, 'bright', key[:key.index('.')] + '_' + str(value
) + key[key.index('.'):]))
else:
os.makedirs(os.path.join(self.path, 'dark'), exist_ok=True)
shutil.copy(os.path.join(self.path, key), os.path.join(self
.path, 'dark', key[:key.index('.')] + '_' + str(value) +
key[key.index('.'):]))
path = 'D:\\Programy\\z.programowanie\\learning\\to be sorted'
a = ImageSelection(path)
a.image_analysis()
<|reserved_special_token_1|>
from PIL import Image, ImageStat
import os
import shutil
class ImageSelection:
def __init__(self, path):
self.path = path
def brightness_check(self, image):
"""count function to set value of brightness, 0 - full black, 100 - full bright"""
with Image.open(image).convert('L') as img:
z = ImageStat.Stat(img)
stat = 100 * (255 - z.mean[0]) / 255
return int(stat)
def averange_threshold(self, dictionary, img_list):
"""counts thrshold which is RMS of all images value"""
sum = 0
for value in dictionary.values():
sum += value
return int(sum / len(img_list))
def image_analysis(self):
"""execution of class, creates two folders (bright, dark) in path
to images name is added theior value of brightness"""
img_list = os.listdir(self.path)
img_list = [os.path.join(self.path, elem) for elem in img_list]
extend_set = {'.png', '.jpeg', '.jpg'}
dictionary = {os.path.basename(img): ImageSelection.
brightness_check(self, img) for ext in extend_set for img in
img_list if ext in img}
threshold = ImageSelection.averange_threshold(self, dictionary,
img_list)
for key, value in dictionary.items():
if value < threshold:
os.makedirs(os.path.join(self.path, 'bright'), exist_ok=True)
shutil.copy(os.path.join(self.path, key), os.path.join(self
.path, 'bright', key[:key.index('.')] + '_' + str(value
) + key[key.index('.'):]))
else:
os.makedirs(os.path.join(self.path, 'dark'), exist_ok=True)
shutil.copy(os.path.join(self.path, key), os.path.join(self
.path, 'dark', key[:key.index('.')] + '_' + str(value) +
key[key.index('.'):]))
path = 'D:\\Programy\\z.programowanie\\learning\\to be sorted'
a = ImageSelection(path)
a.image_analysis()
<|reserved_special_token_1|>
from PIL import Image, ImageStat
import os
import shutil
# full white photo - 255.0
# full black photo - 0.0
class ImageSelection:
def __init__(self, path):
self.path = path
def brightness_check(self, image):
'''count function to set value of brightness, 0 - full black, 100 - full bright'''
with Image.open(image).convert("L") as img:
z = ImageStat.Stat(img)
stat = 100*(255-z.mean[0])/255
return int(stat)
def averange_threshold(self, dictionary, img_list):
'''counts thrshold which is RMS of all images value'''
sum = 0
for value in dictionary.values():
sum += value
return int(sum/len(img_list))
def image_analysis(self):
'''execution of class, creates two folders (bright, dark) in path
to images name is added theior value of brightness'''
img_list = os.listdir(self.path)
img_list = [os.path.join(self.path,elem) for elem in img_list]
extend_set = {".png", ".jpeg", ".jpg"}
dictionary = {os.path.basename(img): ImageSelection.brightness_check(self, img) for ext in extend_set for img in img_list if ext in img}
threshold = ImageSelection.averange_threshold(self, dictionary, img_list)
for key, value in dictionary.items():
if value < threshold:
os.makedirs(os.path.join(self.path, "bright"), exist_ok=True)
shutil.copy(os.path.join(self.path,key), os.path.join(self.path, "bright", key[:key.index(".")] + "_" + str(value) + key[key.index("."):]))
else:
os.makedirs(os.path.join(self.path, "dark"), exist_ok=True)
shutil.copy(os.path.join(self.path,key), os.path.join(self.path, "dark", key[:key.index(".")] + "_" + str(value) + key[key.index("."):]))
path = r"D:\Programy\z.programowanie\learning\to be sorted"
a = ImageSelection(path)
a.image_analysis()
|
flexible
|
{
"blob_id": "897075810912e8360aa5cdedda3f12ce7c868263",
"index": 4547,
"step-1": "<mask token>\n\n\nclass ImageSelection:\n\n def __init__(self, path):\n self.path = path\n\n def brightness_check(self, image):\n \"\"\"count function to set value of brightness, 0 - full black, 100 - full bright\"\"\"\n with Image.open(image).convert('L') as img:\n z = ImageStat.Stat(img)\n stat = 100 * (255 - z.mean[0]) / 255\n return int(stat)\n\n def averange_threshold(self, dictionary, img_list):\n \"\"\"counts thrshold which is RMS of all images value\"\"\"\n sum = 0\n for value in dictionary.values():\n sum += value\n return int(sum / len(img_list))\n\n def image_analysis(self):\n \"\"\"execution of class, creates two folders (bright, dark) in path\n to images name is added theior value of brightness\"\"\"\n img_list = os.listdir(self.path)\n img_list = [os.path.join(self.path, elem) for elem in img_list]\n extend_set = {'.png', '.jpeg', '.jpg'}\n dictionary = {os.path.basename(img): ImageSelection.\n brightness_check(self, img) for ext in extend_set for img in\n img_list if ext in img}\n threshold = ImageSelection.averange_threshold(self, dictionary,\n img_list)\n for key, value in dictionary.items():\n if value < threshold:\n os.makedirs(os.path.join(self.path, 'bright'), exist_ok=True)\n shutil.copy(os.path.join(self.path, key), os.path.join(self\n .path, 'bright', key[:key.index('.')] + '_' + str(value\n ) + key[key.index('.'):]))\n else:\n os.makedirs(os.path.join(self.path, 'dark'), exist_ok=True)\n shutil.copy(os.path.join(self.path, key), os.path.join(self\n .path, 'dark', key[:key.index('.')] + '_' + str(value) +\n key[key.index('.'):]))\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\nclass ImageSelection:\n\n def __init__(self, path):\n self.path = path\n\n def brightness_check(self, image):\n \"\"\"count function to set value of brightness, 0 - full black, 100 - full bright\"\"\"\n with Image.open(image).convert('L') as img:\n z = ImageStat.Stat(img)\n stat = 100 * (255 - z.mean[0]) / 255\n return int(stat)\n\n def averange_threshold(self, dictionary, img_list):\n \"\"\"counts thrshold which is RMS of all images value\"\"\"\n sum = 0\n for value in dictionary.values():\n sum += value\n return int(sum / len(img_list))\n\n def image_analysis(self):\n \"\"\"execution of class, creates two folders (bright, dark) in path\n to images name is added theior value of brightness\"\"\"\n img_list = os.listdir(self.path)\n img_list = [os.path.join(self.path, elem) for elem in img_list]\n extend_set = {'.png', '.jpeg', '.jpg'}\n dictionary = {os.path.basename(img): ImageSelection.\n brightness_check(self, img) for ext in extend_set for img in\n img_list if ext in img}\n threshold = ImageSelection.averange_threshold(self, dictionary,\n img_list)\n for key, value in dictionary.items():\n if value < threshold:\n os.makedirs(os.path.join(self.path, 'bright'), exist_ok=True)\n shutil.copy(os.path.join(self.path, key), os.path.join(self\n .path, 'bright', key[:key.index('.')] + '_' + str(value\n ) + key[key.index('.'):]))\n else:\n os.makedirs(os.path.join(self.path, 'dark'), exist_ok=True)\n shutil.copy(os.path.join(self.path, key), os.path.join(self\n .path, 'dark', key[:key.index('.')] + '_' + str(value) +\n key[key.index('.'):]))\n\n\n<mask token>\na.image_analysis()\n",
"step-3": "<mask token>\n\n\nclass ImageSelection:\n\n def __init__(self, path):\n self.path = path\n\n def brightness_check(self, image):\n \"\"\"count function to set value of brightness, 0 - full black, 100 - full bright\"\"\"\n with Image.open(image).convert('L') as img:\n z = ImageStat.Stat(img)\n stat = 100 * (255 - z.mean[0]) / 255\n return int(stat)\n\n def averange_threshold(self, dictionary, img_list):\n \"\"\"counts thrshold which is RMS of all images value\"\"\"\n sum = 0\n for value in dictionary.values():\n sum += value\n return int(sum / len(img_list))\n\n def image_analysis(self):\n \"\"\"execution of class, creates two folders (bright, dark) in path\n to images name is added theior value of brightness\"\"\"\n img_list = os.listdir(self.path)\n img_list = [os.path.join(self.path, elem) for elem in img_list]\n extend_set = {'.png', '.jpeg', '.jpg'}\n dictionary = {os.path.basename(img): ImageSelection.\n brightness_check(self, img) for ext in extend_set for img in\n img_list if ext in img}\n threshold = ImageSelection.averange_threshold(self, dictionary,\n img_list)\n for key, value in dictionary.items():\n if value < threshold:\n os.makedirs(os.path.join(self.path, 'bright'), exist_ok=True)\n shutil.copy(os.path.join(self.path, key), os.path.join(self\n .path, 'bright', key[:key.index('.')] + '_' + str(value\n ) + key[key.index('.'):]))\n else:\n os.makedirs(os.path.join(self.path, 'dark'), exist_ok=True)\n shutil.copy(os.path.join(self.path, key), os.path.join(self\n .path, 'dark', key[:key.index('.')] + '_' + str(value) +\n key[key.index('.'):]))\n\n\npath = 'D:\\\\Programy\\\\z.programowanie\\\\learning\\\\to be sorted'\na = ImageSelection(path)\na.image_analysis()\n",
"step-4": "from PIL import Image, ImageStat\nimport os\nimport shutil\n\n\nclass ImageSelection:\n\n def __init__(self, path):\n self.path = path\n\n def brightness_check(self, image):\n \"\"\"count function to set value of brightness, 0 - full black, 100 - full bright\"\"\"\n with Image.open(image).convert('L') as img:\n z = ImageStat.Stat(img)\n stat = 100 * (255 - z.mean[0]) / 255\n return int(stat)\n\n def averange_threshold(self, dictionary, img_list):\n \"\"\"counts thrshold which is RMS of all images value\"\"\"\n sum = 0\n for value in dictionary.values():\n sum += value\n return int(sum / len(img_list))\n\n def image_analysis(self):\n \"\"\"execution of class, creates two folders (bright, dark) in path\n to images name is added theior value of brightness\"\"\"\n img_list = os.listdir(self.path)\n img_list = [os.path.join(self.path, elem) for elem in img_list]\n extend_set = {'.png', '.jpeg', '.jpg'}\n dictionary = {os.path.basename(img): ImageSelection.\n brightness_check(self, img) for ext in extend_set for img in\n img_list if ext in img}\n threshold = ImageSelection.averange_threshold(self, dictionary,\n img_list)\n for key, value in dictionary.items():\n if value < threshold:\n os.makedirs(os.path.join(self.path, 'bright'), exist_ok=True)\n shutil.copy(os.path.join(self.path, key), os.path.join(self\n .path, 'bright', key[:key.index('.')] + '_' + str(value\n ) + key[key.index('.'):]))\n else:\n os.makedirs(os.path.join(self.path, 'dark'), exist_ok=True)\n shutil.copy(os.path.join(self.path, key), os.path.join(self\n .path, 'dark', key[:key.index('.')] + '_' + str(value) +\n key[key.index('.'):]))\n\n\npath = 'D:\\\\Programy\\\\z.programowanie\\\\learning\\\\to be sorted'\na = ImageSelection(path)\na.image_analysis()\n",
"step-5": "from PIL import Image, ImageStat\r\nimport os\r\nimport shutil\r\n\r\n# full white photo - 255.0\r\n# full black photo - 0.0\r\n\r\n\r\nclass ImageSelection:\r\n def __init__(self, path):\r\n self.path = path\r\n\r\n def brightness_check(self, image):\r\n '''count function to set value of brightness, 0 - full black, 100 - full bright'''\r\n with Image.open(image).convert(\"L\") as img:\r\n z = ImageStat.Stat(img)\r\n stat = 100*(255-z.mean[0])/255\r\n return int(stat)\r\n\r\n def averange_threshold(self, dictionary, img_list):\r\n '''counts thrshold which is RMS of all images value'''\r\n sum = 0\r\n for value in dictionary.values():\r\n sum += value\r\n return int(sum/len(img_list))\r\n\r\n def image_analysis(self):\r\n '''execution of class, creates two folders (bright, dark) in path\r\n to images name is added theior value of brightness'''\r\n img_list = os.listdir(self.path)\r\n img_list = [os.path.join(self.path,elem) for elem in img_list]\r\n extend_set = {\".png\", \".jpeg\", \".jpg\"}\r\n dictionary = {os.path.basename(img): ImageSelection.brightness_check(self, img) for ext in extend_set for img in img_list if ext in img}\r\n threshold = ImageSelection.averange_threshold(self, dictionary, img_list)\r\n for key, value in dictionary.items():\r\n if value < threshold:\r\n os.makedirs(os.path.join(self.path, \"bright\"), exist_ok=True)\r\n shutil.copy(os.path.join(self.path,key), os.path.join(self.path, \"bright\", key[:key.index(\".\")] + \"_\" + str(value) + key[key.index(\".\"):]))\r\n else:\r\n os.makedirs(os.path.join(self.path, \"dark\"), exist_ok=True)\r\n shutil.copy(os.path.join(self.path,key), os.path.join(self.path, \"dark\", key[:key.index(\".\")] + \"_\" + str(value) + key[key.index(\".\"):]))\r\n\r\n\r\npath = r\"D:\\Programy\\z.programowanie\\learning\\to be sorted\"\r\na = ImageSelection(path)\r\na.image_analysis()\r\n",
"step-ids": [
5,
6,
7,
8,
9
]
}
|
[
5,
6,
7,
8,
9
] |
import smtplib
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from datetime import datetime
from threading import Thread
FROM = os.getenv('EMAIL_FROM')
TO = os.getenv('EMAIL_TO')
HOST = os.getenv('EMAIL_HOST')
PORT = os.getenv('EMAIL_PORT')
PASSWORD = os.getenv('EMAIL_PASSWORD')
def send_email(body, subject=f'ERROR LOG [{datetime.strftime(datetime.now(), "%b %d, %Y - %I:%M %p")}]'):
"""
Sends an email with the subject formatted as 'ERROR LOG [Jan 01, 1970 - 12:00 AM]'
"""
# Send the email on a separate thread so the server doesn't
# have to wait for it to finish
thread = Thread(target=_send, args=(body, subject))
thread.start()
def _send(body, subject):
msg = MIMEMultipart()
msg['From'] = FROM
msg['To'] = TO
msg['Subject'] = subject
msg.attach(MIMEText(body, 'plain'))
server = smtplib.SMTP(host=HOST, port=int(PORT))
server.starttls()
server.login(FROM, PASSWORD)
senders = server.sendmail(FROM, TO, msg.as_string())
server.quit()
return senders
|
normal
|
{
"blob_id": "60c3f6775d5112ff178bd3774c776819573887bb",
"index": 9367,
"step-1": "<mask token>\n\n\ndef _send(body, subject):\n msg = MIMEMultipart()\n msg['From'] = FROM\n msg['To'] = TO\n msg['Subject'] = subject\n msg.attach(MIMEText(body, 'plain'))\n server = smtplib.SMTP(host=HOST, port=int(PORT))\n server.starttls()\n server.login(FROM, PASSWORD)\n senders = server.sendmail(FROM, TO, msg.as_string())\n server.quit()\n return senders\n",
"step-2": "<mask token>\n\n\ndef send_email(body, subject=\n f\"ERROR LOG [{datetime.strftime(datetime.now(), '%b %d, %Y - %I:%M %p')}]\"\n ):\n \"\"\"\n Sends an email with the subject formatted as 'ERROR LOG [Jan 01, 1970 - 12:00 AM]'\n \"\"\"\n thread = Thread(target=_send, args=(body, subject))\n thread.start()\n\n\ndef _send(body, subject):\n msg = MIMEMultipart()\n msg['From'] = FROM\n msg['To'] = TO\n msg['Subject'] = subject\n msg.attach(MIMEText(body, 'plain'))\n server = smtplib.SMTP(host=HOST, port=int(PORT))\n server.starttls()\n server.login(FROM, PASSWORD)\n senders = server.sendmail(FROM, TO, msg.as_string())\n server.quit()\n return senders\n",
"step-3": "<mask token>\nFROM = os.getenv('EMAIL_FROM')\nTO = os.getenv('EMAIL_TO')\nHOST = os.getenv('EMAIL_HOST')\nPORT = os.getenv('EMAIL_PORT')\nPASSWORD = os.getenv('EMAIL_PASSWORD')\n\n\ndef send_email(body, subject=\n f\"ERROR LOG [{datetime.strftime(datetime.now(), '%b %d, %Y - %I:%M %p')}]\"\n ):\n \"\"\"\n Sends an email with the subject formatted as 'ERROR LOG [Jan 01, 1970 - 12:00 AM]'\n \"\"\"\n thread = Thread(target=_send, args=(body, subject))\n thread.start()\n\n\ndef _send(body, subject):\n msg = MIMEMultipart()\n msg['From'] = FROM\n msg['To'] = TO\n msg['Subject'] = subject\n msg.attach(MIMEText(body, 'plain'))\n server = smtplib.SMTP(host=HOST, port=int(PORT))\n server.starttls()\n server.login(FROM, PASSWORD)\n senders = server.sendmail(FROM, TO, msg.as_string())\n server.quit()\n return senders\n",
"step-4": "import smtplib\nimport os\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom datetime import datetime\nfrom threading import Thread\nFROM = os.getenv('EMAIL_FROM')\nTO = os.getenv('EMAIL_TO')\nHOST = os.getenv('EMAIL_HOST')\nPORT = os.getenv('EMAIL_PORT')\nPASSWORD = os.getenv('EMAIL_PASSWORD')\n\n\ndef send_email(body, subject=\n f\"ERROR LOG [{datetime.strftime(datetime.now(), '%b %d, %Y - %I:%M %p')}]\"\n ):\n \"\"\"\n Sends an email with the subject formatted as 'ERROR LOG [Jan 01, 1970 - 12:00 AM]'\n \"\"\"\n thread = Thread(target=_send, args=(body, subject))\n thread.start()\n\n\ndef _send(body, subject):\n msg = MIMEMultipart()\n msg['From'] = FROM\n msg['To'] = TO\n msg['Subject'] = subject\n msg.attach(MIMEText(body, 'plain'))\n server = smtplib.SMTP(host=HOST, port=int(PORT))\n server.starttls()\n server.login(FROM, PASSWORD)\n senders = server.sendmail(FROM, TO, msg.as_string())\n server.quit()\n return senders\n",
"step-5": "import smtplib\nimport os\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom datetime import datetime\nfrom threading import Thread\n\nFROM = os.getenv('EMAIL_FROM')\nTO = os.getenv('EMAIL_TO')\nHOST = os.getenv('EMAIL_HOST')\nPORT = os.getenv('EMAIL_PORT')\nPASSWORD = os.getenv('EMAIL_PASSWORD')\n\n\ndef send_email(body, subject=f'ERROR LOG [{datetime.strftime(datetime.now(), \"%b %d, %Y - %I:%M %p\")}]'):\n \"\"\"\n Sends an email with the subject formatted as 'ERROR LOG [Jan 01, 1970 - 12:00 AM]'\n \"\"\"\n\n # Send the email on a separate thread so the server doesn't\n # have to wait for it to finish\n thread = Thread(target=_send, args=(body, subject))\n thread.start()\n\n\ndef _send(body, subject):\n msg = MIMEMultipart()\n msg['From'] = FROM\n msg['To'] = TO\n msg['Subject'] = subject\n msg.attach(MIMEText(body, 'plain'))\n\n server = smtplib.SMTP(host=HOST, port=int(PORT))\n server.starttls()\n server.login(FROM, PASSWORD)\n\n senders = server.sendmail(FROM, TO, msg.as_string())\n\n server.quit()\n\n return senders\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014 Vincent Celis
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import webapp2
import handlers
# A list containing webapp2.Route instances to define the routing tables
ROUTE_LIST = [
webapp2.Route(r'/api/history<name:/(?:[a-zA-Z0-9_-]+/?)*>',
handler=handlers.HistoryApi, name='historyApi'),
webapp2.Route(r'/api<name:/(?:[a-zA-Z0-9_-]+/?)*>',
handler=handlers.PageApi, name='pageApi'),
webapp2.Route(r'/signup', handler=handlers.SignupPage, name='signup'),
webapp2.Route(r'/login', handler=handlers.LoginPage, name='login'),
webapp2.Route(r'/logout', handler=handlers.LogoutPage, name='logout'),
webapp2.Route(r'/search', handler=handlers.SearchPage, name='search'),
webapp2.Route(r'/_edit<name:/(?:[a-zA-Z0-9_-]+/?)*>',
handler=handlers.EditPage, name='edit'),
webapp2.Route(r'/_history<name:/(?:[a-zA-Z0-9_-]+/?)*>',
handler=handlers.HistoryPage, name='history'),
webapp2.Route(r'<name:/(?:[a-zA-Z0-9_-]+/?)*>',
handler=handlers.WikiPage, name='wiki')
]
|
normal
|
{
"blob_id": "a61bc654eecb4e44dce3e62df752f80559a2d055",
"index": 9184,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nROUTE_LIST = [webapp2.Route('/api/history<name:/(?:[a-zA-Z0-9_-]+/?)*>',\n handler=handlers.HistoryApi, name='historyApi'), webapp2.Route(\n '/api<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler=handlers.PageApi, name=\n 'pageApi'), webapp2.Route('/signup', handler=handlers.SignupPage, name=\n 'signup'), webapp2.Route('/login', handler=handlers.LoginPage, name=\n 'login'), webapp2.Route('/logout', handler=handlers.LogoutPage, name=\n 'logout'), webapp2.Route('/search', handler=handlers.SearchPage, name=\n 'search'), webapp2.Route('/_edit<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler\n =handlers.EditPage, name='edit'), webapp2.Route(\n '/_history<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler=handlers.HistoryPage,\n name='history'), webapp2.Route('<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler\n =handlers.WikiPage, name='wiki')]\n",
"step-3": "import webapp2\nimport handlers\nROUTE_LIST = [webapp2.Route('/api/history<name:/(?:[a-zA-Z0-9_-]+/?)*>',\n handler=handlers.HistoryApi, name='historyApi'), webapp2.Route(\n '/api<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler=handlers.PageApi, name=\n 'pageApi'), webapp2.Route('/signup', handler=handlers.SignupPage, name=\n 'signup'), webapp2.Route('/login', handler=handlers.LoginPage, name=\n 'login'), webapp2.Route('/logout', handler=handlers.LogoutPage, name=\n 'logout'), webapp2.Route('/search', handler=handlers.SearchPage, name=\n 'search'), webapp2.Route('/_edit<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler\n =handlers.EditPage, name='edit'), webapp2.Route(\n '/_history<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler=handlers.HistoryPage,\n name='history'), webapp2.Route('<name:/(?:[a-zA-Z0-9_-]+/?)*>', handler\n =handlers.WikiPage, name='wiki')]\n",
"step-4": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# Copyright (c) 2014 Vincent Celis\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\nimport webapp2\nimport handlers\n\n# A list containing webapp2.Route instances to define the routing tables\nROUTE_LIST = [\n webapp2.Route(r'/api/history<name:/(?:[a-zA-Z0-9_-]+/?)*>',\n handler=handlers.HistoryApi, name='historyApi'),\n webapp2.Route(r'/api<name:/(?:[a-zA-Z0-9_-]+/?)*>',\n handler=handlers.PageApi, name='pageApi'),\n webapp2.Route(r'/signup', handler=handlers.SignupPage, name='signup'),\n webapp2.Route(r'/login', handler=handlers.LoginPage, name='login'),\n webapp2.Route(r'/logout', handler=handlers.LogoutPage, name='logout'),\n webapp2.Route(r'/search', handler=handlers.SearchPage, name='search'),\n webapp2.Route(r'/_edit<name:/(?:[a-zA-Z0-9_-]+/?)*>',\n handler=handlers.EditPage, name='edit'),\n webapp2.Route(r'/_history<name:/(?:[a-zA-Z0-9_-]+/?)*>',\n handler=handlers.HistoryPage, name='history'),\n webapp2.Route(r'<name:/(?:[a-zA-Z0-9_-]+/?)*>',\n handler=handlers.WikiPage, name='wiki')\n ]",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def gauss_seidel(relax, est, stop):
"""
Método iterativo de Gauss-Seidel para o sistema linear do trabalho.
Onde relax é o fator de relaxação, est é o valor inicial, stop é o
critério de parada, n é a quantidade de linhas do sistema e k é o
número de iterações.
"""
k = 0
dif = 10000
n = len(est)
diff = np.zeros(n)
while dif > stop:
k += 1
est[0] = (1 - relax) * est[0] + relax * (1.5 - est[1])
for i in range(1, int(n / 2)):
est[i] = (1 - relax) * est[i] + relax * ((1.0 - est[i - 1] -
est[i + 1] - est[i + 25]) / 4)
for j in range(int(n / 2), n - 1):
est[j] = (1 - relax) * est[j] + relax * ((2.0 - est[j - 25] -
est[j - 1] - est[j + 1]) / 5)
est[n - 1] = (1 - relax) * est[n - 1] + relax * (3.0 - est[n - 2])
dif = max(abs(np.subtract(est, diff)))
diff = np.copy(est)
return [est, k]
<|reserved_special_token_1|>
import numpy as np
def gauss_seidel(relax, est, stop):
"""
Método iterativo de Gauss-Seidel para o sistema linear do trabalho.
Onde relax é o fator de relaxação, est é o valor inicial, stop é o
critério de parada, n é a quantidade de linhas do sistema e k é o
número de iterações.
"""
k = 0
dif = 10000
n = len(est)
diff = np.zeros(n)
while dif > stop:
k += 1
est[0] = (1 - relax) * est[0] + relax * (1.5 - est[1])
for i in range(1, int(n / 2)):
est[i] = (1 - relax) * est[i] + relax * ((1.0 - est[i - 1] -
est[i + 1] - est[i + 25]) / 4)
for j in range(int(n / 2), n - 1):
est[j] = (1 - relax) * est[j] + relax * ((2.0 - est[j - 25] -
est[j - 1] - est[j + 1]) / 5)
est[n - 1] = (1 - relax) * est[n - 1] + relax * (3.0 - est[n - 2])
dif = max(abs(np.subtract(est, diff)))
diff = np.copy(est)
return [est, k]
<|reserved_special_token_1|>
# -*- coding: utf-8 -*-
import numpy as np
def gauss_seidel(relax, est, stop):
"""
Método iterativo de Gauss-Seidel para o sistema linear do trabalho.
Onde relax é o fator de relaxação, est é o valor inicial, stop é o
critério de parada, n é a quantidade de linhas do sistema e k é o
número de iterações.
"""
k = 0
dif = 10000
n = len(est)
diff = np.zeros(n)
while dif > stop:
k += 1
est[0] = ((1 - relax) * est[0]) + relax * (1.50 - est[1])
for i in range(1, int(n/2)):
est[i] = ((1 - relax) * est[i]) + relax * \
((1.0 - est[i-1] - est[i+1] - est[i+25])/4)
for j in range(int(n/2), n-1):
est[j] = ((1 - relax) * est[j]) + relax * \
((2.0 - est[j-25] - est[j-1] - est[j+1])/5)
est[n-1] = ((1 - relax) * est[n-1]) + relax * (3.00 - est[n-2])
dif = max(abs(np.subtract(est, diff)))
diff = np.copy(est)
return [est, k]
|
flexible
|
{
"blob_id": "51540a80c7b29dc0bbb6342ee45008108d54b6f2",
"index": 714,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef gauss_seidel(relax, est, stop):\n \"\"\"\n Método iterativo de Gauss-Seidel para o sistema linear do trabalho.\n Onde relax é o fator de relaxação, est é o valor inicial, stop é o\n critério de parada, n é a quantidade de linhas do sistema e k é o\n número de iterações.\n \"\"\"\n k = 0\n dif = 10000\n n = len(est)\n diff = np.zeros(n)\n while dif > stop:\n k += 1\n est[0] = (1 - relax) * est[0] + relax * (1.5 - est[1])\n for i in range(1, int(n / 2)):\n est[i] = (1 - relax) * est[i] + relax * ((1.0 - est[i - 1] -\n est[i + 1] - est[i + 25]) / 4)\n for j in range(int(n / 2), n - 1):\n est[j] = (1 - relax) * est[j] + relax * ((2.0 - est[j - 25] -\n est[j - 1] - est[j + 1]) / 5)\n est[n - 1] = (1 - relax) * est[n - 1] + relax * (3.0 - est[n - 2])\n dif = max(abs(np.subtract(est, diff)))\n diff = np.copy(est)\n return [est, k]\n",
"step-3": "import numpy as np\n\n\ndef gauss_seidel(relax, est, stop):\n \"\"\"\n Método iterativo de Gauss-Seidel para o sistema linear do trabalho.\n Onde relax é o fator de relaxação, est é o valor inicial, stop é o\n critério de parada, n é a quantidade de linhas do sistema e k é o\n número de iterações.\n \"\"\"\n k = 0\n dif = 10000\n n = len(est)\n diff = np.zeros(n)\n while dif > stop:\n k += 1\n est[0] = (1 - relax) * est[0] + relax * (1.5 - est[1])\n for i in range(1, int(n / 2)):\n est[i] = (1 - relax) * est[i] + relax * ((1.0 - est[i - 1] -\n est[i + 1] - est[i + 25]) / 4)\n for j in range(int(n / 2), n - 1):\n est[j] = (1 - relax) * est[j] + relax * ((2.0 - est[j - 25] -\n est[j - 1] - est[j + 1]) / 5)\n est[n - 1] = (1 - relax) * est[n - 1] + relax * (3.0 - est[n - 2])\n dif = max(abs(np.subtract(est, diff)))\n diff = np.copy(est)\n return [est, k]\n",
"step-4": "# -*- coding: utf-8 -*-\nimport numpy as np\n\n\ndef gauss_seidel(relax, est, stop):\n \"\"\"\n Método iterativo de Gauss-Seidel para o sistema linear do trabalho.\n Onde relax é o fator de relaxação, est é o valor inicial, stop é o\n critério de parada, n é a quantidade de linhas do sistema e k é o\n número de iterações.\n \"\"\"\n\n k = 0\n dif = 10000\n n = len(est)\n diff = np.zeros(n)\n\n while dif > stop:\n k += 1\n\n est[0] = ((1 - relax) * est[0]) + relax * (1.50 - est[1])\n\n for i in range(1, int(n/2)):\n est[i] = ((1 - relax) * est[i]) + relax * \\\n ((1.0 - est[i-1] - est[i+1] - est[i+25])/4)\n\n for j in range(int(n/2), n-1):\n est[j] = ((1 - relax) * est[j]) + relax * \\\n ((2.0 - est[j-25] - est[j-1] - est[j+1])/5)\n\n est[n-1] = ((1 - relax) * est[n-1]) + relax * (3.00 - est[n-2])\n\n dif = max(abs(np.subtract(est, diff)))\n diff = np.copy(est)\n\n return [est, k]\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
import MySQLdb
import MySQLdb.cursors
from flask import _app_ctx_stack, current_app
class MySQL(object):
def __init__(self, app=None):
self.app = app
if app is not None:
self.init_app(app)
def init_app(self, app):
"""Initialize the `app` for use with this
:class:`~flask_mysqldb.MySQL` class.
This is called automatically if `app` is passed to
:meth:`~MySQL.__init__`.
:param flask.Flask app: the application to configure for use with
this :class:`~flask_mysqldb.MySQL` class.
"""
app.config.setdefault('MYSQL_HOST', 'localhost')
app.config.setdefault('MYSQL_USER', None)
app.config.setdefault('MYSQL_PASSWORD', None)
app.config.setdefault('MYSQL_DB', None)
app.config.setdefault('MYSQL_PORT', 3306)
app.config.setdefault('MYSQL_UNIX_SOCKET', None)
app.config.setdefault('MYSQL_CONNECT_TIMEOUT', 10)
app.config.setdefault('MYSQL_READ_DEFAULT_FILE', None)
app.config.setdefault('MYSQL_USE_UNICODE', True)
app.config.setdefault('MYSQL_CHARSET', 'utf8')
app.config.setdefault('MYSQL_SQL_MODE', None)
app.config.setdefault('MYSQL_CURSORCLASS', None)
if hasattr(app, 'teardown_appcontext'):
app.teardown_appcontext(self.teardown)
@property
def connect(self):
kwargs = {}
if current_app.config['MYSQL_HOST']:
kwargs['host'] = current_app.config['MYSQL_HOST']
if current_app.config['MYSQL_USER']:
kwargs['user'] = current_app.config['MYSQL_USER']
if current_app.config['MYSQL_PASSWORD']:
kwargs['passwd'] = current_app.config['MYSQL_PASSWORD']
if current_app.config['MYSQL_DB']:
kwargs['db'] = current_app.config['MYSQL_DB']
if current_app.config['MYSQL_PORT']:
kwargs['port'] = current_app.config['MYSQL_PORT']
if current_app.config['MYSQL_UNIX_SOCKET']:
kwargs['unix_socket'] = current_app.config['MYSQL_UNIX_SOCKET']
if current_app.config['MYSQL_CONNECT_TIMEOUT']:
kwargs['connect_timeout'] = \
current_app.config['MYSQL_CONNECT_TIMEOUT']
if current_app.config['MYSQL_READ_DEFAULT_FILE']:
kwargs['read_default_file'] = \
current_app.config['MYSQL_READ_DEFAULT_FILE']
if current_app.config['MYSQL_USE_UNICODE']:
kwargs['use_unicode'] = current_app.config['MYSQL_USE_UNICODE']
if current_app.config['MYSQL_CHARSET']:
kwargs['charset'] = current_app.config['MYSQL_CHARSET']
if current_app.config['MYSQL_SQL_MODE']:
kwargs['sql_mode'] = current_app.config['MYSQL_SQL_MODE']
if current_app.config['MYSQL_CURSORCLASS']:
kwargs['cursorclass'] = getattr(MySQLdb.cursors, current_app.config['MYSQL_CURSORCLASS'])
return MySQLdb.connect(**kwargs)
@property
def connection(self):
"""Attempts to connect to the MySQL server.
:return: Bound MySQL connection object if successful or ``None`` if
unsuccessful.
"""
ctx = _app_ctx_stack.top
if ctx is not None:
if not hasattr(ctx, 'mysql_db'):
ctx.mysql_db = self.connect
return ctx.mysql_db
def teardown(self, exception):
ctx = _app_ctx_stack.top
if hasattr(ctx, 'mysql_db'):
ctx.mysql_db.close()
|
normal
|
{
"blob_id": "db8c2f6f5da0b52c268634043e1132984f610eed",
"index": 8405,
"step-1": "<mask token>\n\n\nclass MySQL(object):\n\n def __init__(self, app=None):\n self.app = app\n if app is not None:\n self.init_app(app)\n <mask token>\n\n @property\n def connect(self):\n kwargs = {}\n if current_app.config['MYSQL_HOST']:\n kwargs['host'] = current_app.config['MYSQL_HOST']\n if current_app.config['MYSQL_USER']:\n kwargs['user'] = current_app.config['MYSQL_USER']\n if current_app.config['MYSQL_PASSWORD']:\n kwargs['passwd'] = current_app.config['MYSQL_PASSWORD']\n if current_app.config['MYSQL_DB']:\n kwargs['db'] = current_app.config['MYSQL_DB']\n if current_app.config['MYSQL_PORT']:\n kwargs['port'] = current_app.config['MYSQL_PORT']\n if current_app.config['MYSQL_UNIX_SOCKET']:\n kwargs['unix_socket'] = current_app.config['MYSQL_UNIX_SOCKET']\n if current_app.config['MYSQL_CONNECT_TIMEOUT']:\n kwargs['connect_timeout'] = current_app.config[\n 'MYSQL_CONNECT_TIMEOUT']\n if current_app.config['MYSQL_READ_DEFAULT_FILE']:\n kwargs['read_default_file'] = current_app.config[\n 'MYSQL_READ_DEFAULT_FILE']\n if current_app.config['MYSQL_USE_UNICODE']:\n kwargs['use_unicode'] = current_app.config['MYSQL_USE_UNICODE']\n if current_app.config['MYSQL_CHARSET']:\n kwargs['charset'] = current_app.config['MYSQL_CHARSET']\n if current_app.config['MYSQL_SQL_MODE']:\n kwargs['sql_mode'] = current_app.config['MYSQL_SQL_MODE']\n if current_app.config['MYSQL_CURSORCLASS']:\n kwargs['cursorclass'] = getattr(MySQLdb.cursors, current_app.\n config['MYSQL_CURSORCLASS'])\n return MySQLdb.connect(**kwargs)\n <mask token>\n\n def teardown(self, exception):\n ctx = _app_ctx_stack.top\n if hasattr(ctx, 'mysql_db'):\n ctx.mysql_db.close()\n",
"step-2": "<mask token>\n\n\nclass MySQL(object):\n\n def __init__(self, app=None):\n self.app = app\n if app is not None:\n self.init_app(app)\n\n def init_app(self, app):\n \"\"\"Initialize the `app` for use with this\n :class:`~flask_mysqldb.MySQL` class.\n This is called automatically if `app` is passed to\n :meth:`~MySQL.__init__`.\n\n :param flask.Flask app: the application to configure for use with\n this :class:`~flask_mysqldb.MySQL` class.\n \"\"\"\n app.config.setdefault('MYSQL_HOST', 'localhost')\n app.config.setdefault('MYSQL_USER', None)\n app.config.setdefault('MYSQL_PASSWORD', None)\n app.config.setdefault('MYSQL_DB', None)\n app.config.setdefault('MYSQL_PORT', 3306)\n app.config.setdefault('MYSQL_UNIX_SOCKET', None)\n app.config.setdefault('MYSQL_CONNECT_TIMEOUT', 10)\n app.config.setdefault('MYSQL_READ_DEFAULT_FILE', None)\n app.config.setdefault('MYSQL_USE_UNICODE', True)\n app.config.setdefault('MYSQL_CHARSET', 'utf8')\n app.config.setdefault('MYSQL_SQL_MODE', None)\n app.config.setdefault('MYSQL_CURSORCLASS', None)\n if hasattr(app, 'teardown_appcontext'):\n app.teardown_appcontext(self.teardown)\n\n @property\n def connect(self):\n kwargs = {}\n if current_app.config['MYSQL_HOST']:\n kwargs['host'] = current_app.config['MYSQL_HOST']\n if current_app.config['MYSQL_USER']:\n kwargs['user'] = current_app.config['MYSQL_USER']\n if current_app.config['MYSQL_PASSWORD']:\n kwargs['passwd'] = current_app.config['MYSQL_PASSWORD']\n if current_app.config['MYSQL_DB']:\n kwargs['db'] = current_app.config['MYSQL_DB']\n if current_app.config['MYSQL_PORT']:\n kwargs['port'] = current_app.config['MYSQL_PORT']\n if current_app.config['MYSQL_UNIX_SOCKET']:\n kwargs['unix_socket'] = current_app.config['MYSQL_UNIX_SOCKET']\n if current_app.config['MYSQL_CONNECT_TIMEOUT']:\n kwargs['connect_timeout'] = current_app.config[\n 'MYSQL_CONNECT_TIMEOUT']\n if current_app.config['MYSQL_READ_DEFAULT_FILE']:\n kwargs['read_default_file'] = current_app.config[\n 'MYSQL_READ_DEFAULT_FILE']\n if current_app.config['MYSQL_USE_UNICODE']:\n kwargs['use_unicode'] = current_app.config['MYSQL_USE_UNICODE']\n if current_app.config['MYSQL_CHARSET']:\n kwargs['charset'] = current_app.config['MYSQL_CHARSET']\n if current_app.config['MYSQL_SQL_MODE']:\n kwargs['sql_mode'] = current_app.config['MYSQL_SQL_MODE']\n if current_app.config['MYSQL_CURSORCLASS']:\n kwargs['cursorclass'] = getattr(MySQLdb.cursors, current_app.\n config['MYSQL_CURSORCLASS'])\n return MySQLdb.connect(**kwargs)\n <mask token>\n\n def teardown(self, exception):\n ctx = _app_ctx_stack.top\n if hasattr(ctx, 'mysql_db'):\n ctx.mysql_db.close()\n",
"step-3": "<mask token>\n\n\nclass MySQL(object):\n\n def __init__(self, app=None):\n self.app = app\n if app is not None:\n self.init_app(app)\n\n def init_app(self, app):\n \"\"\"Initialize the `app` for use with this\n :class:`~flask_mysqldb.MySQL` class.\n This is called automatically if `app` is passed to\n :meth:`~MySQL.__init__`.\n\n :param flask.Flask app: the application to configure for use with\n this :class:`~flask_mysqldb.MySQL` class.\n \"\"\"\n app.config.setdefault('MYSQL_HOST', 'localhost')\n app.config.setdefault('MYSQL_USER', None)\n app.config.setdefault('MYSQL_PASSWORD', None)\n app.config.setdefault('MYSQL_DB', None)\n app.config.setdefault('MYSQL_PORT', 3306)\n app.config.setdefault('MYSQL_UNIX_SOCKET', None)\n app.config.setdefault('MYSQL_CONNECT_TIMEOUT', 10)\n app.config.setdefault('MYSQL_READ_DEFAULT_FILE', None)\n app.config.setdefault('MYSQL_USE_UNICODE', True)\n app.config.setdefault('MYSQL_CHARSET', 'utf8')\n app.config.setdefault('MYSQL_SQL_MODE', None)\n app.config.setdefault('MYSQL_CURSORCLASS', None)\n if hasattr(app, 'teardown_appcontext'):\n app.teardown_appcontext(self.teardown)\n\n @property\n def connect(self):\n kwargs = {}\n if current_app.config['MYSQL_HOST']:\n kwargs['host'] = current_app.config['MYSQL_HOST']\n if current_app.config['MYSQL_USER']:\n kwargs['user'] = current_app.config['MYSQL_USER']\n if current_app.config['MYSQL_PASSWORD']:\n kwargs['passwd'] = current_app.config['MYSQL_PASSWORD']\n if current_app.config['MYSQL_DB']:\n kwargs['db'] = current_app.config['MYSQL_DB']\n if current_app.config['MYSQL_PORT']:\n kwargs['port'] = current_app.config['MYSQL_PORT']\n if current_app.config['MYSQL_UNIX_SOCKET']:\n kwargs['unix_socket'] = current_app.config['MYSQL_UNIX_SOCKET']\n if current_app.config['MYSQL_CONNECT_TIMEOUT']:\n kwargs['connect_timeout'] = current_app.config[\n 'MYSQL_CONNECT_TIMEOUT']\n if current_app.config['MYSQL_READ_DEFAULT_FILE']:\n kwargs['read_default_file'] = current_app.config[\n 'MYSQL_READ_DEFAULT_FILE']\n if current_app.config['MYSQL_USE_UNICODE']:\n kwargs['use_unicode'] = current_app.config['MYSQL_USE_UNICODE']\n if current_app.config['MYSQL_CHARSET']:\n kwargs['charset'] = current_app.config['MYSQL_CHARSET']\n if current_app.config['MYSQL_SQL_MODE']:\n kwargs['sql_mode'] = current_app.config['MYSQL_SQL_MODE']\n if current_app.config['MYSQL_CURSORCLASS']:\n kwargs['cursorclass'] = getattr(MySQLdb.cursors, current_app.\n config['MYSQL_CURSORCLASS'])\n return MySQLdb.connect(**kwargs)\n\n @property\n def connection(self):\n \"\"\"Attempts to connect to the MySQL server.\n\n :return: Bound MySQL connection object if successful or ``None`` if\n unsuccessful.\n \"\"\"\n ctx = _app_ctx_stack.top\n if ctx is not None:\n if not hasattr(ctx, 'mysql_db'):\n ctx.mysql_db = self.connect\n return ctx.mysql_db\n\n def teardown(self, exception):\n ctx = _app_ctx_stack.top\n if hasattr(ctx, 'mysql_db'):\n ctx.mysql_db.close()\n",
"step-4": "import MySQLdb\nimport MySQLdb.cursors\nfrom flask import _app_ctx_stack, current_app\n\n\nclass MySQL(object):\n\n def __init__(self, app=None):\n self.app = app\n if app is not None:\n self.init_app(app)\n\n def init_app(self, app):\n \"\"\"Initialize the `app` for use with this\n :class:`~flask_mysqldb.MySQL` class.\n This is called automatically if `app` is passed to\n :meth:`~MySQL.__init__`.\n\n :param flask.Flask app: the application to configure for use with\n this :class:`~flask_mysqldb.MySQL` class.\n \"\"\"\n app.config.setdefault('MYSQL_HOST', 'localhost')\n app.config.setdefault('MYSQL_USER', None)\n app.config.setdefault('MYSQL_PASSWORD', None)\n app.config.setdefault('MYSQL_DB', None)\n app.config.setdefault('MYSQL_PORT', 3306)\n app.config.setdefault('MYSQL_UNIX_SOCKET', None)\n app.config.setdefault('MYSQL_CONNECT_TIMEOUT', 10)\n app.config.setdefault('MYSQL_READ_DEFAULT_FILE', None)\n app.config.setdefault('MYSQL_USE_UNICODE', True)\n app.config.setdefault('MYSQL_CHARSET', 'utf8')\n app.config.setdefault('MYSQL_SQL_MODE', None)\n app.config.setdefault('MYSQL_CURSORCLASS', None)\n if hasattr(app, 'teardown_appcontext'):\n app.teardown_appcontext(self.teardown)\n\n @property\n def connect(self):\n kwargs = {}\n if current_app.config['MYSQL_HOST']:\n kwargs['host'] = current_app.config['MYSQL_HOST']\n if current_app.config['MYSQL_USER']:\n kwargs['user'] = current_app.config['MYSQL_USER']\n if current_app.config['MYSQL_PASSWORD']:\n kwargs['passwd'] = current_app.config['MYSQL_PASSWORD']\n if current_app.config['MYSQL_DB']:\n kwargs['db'] = current_app.config['MYSQL_DB']\n if current_app.config['MYSQL_PORT']:\n kwargs['port'] = current_app.config['MYSQL_PORT']\n if current_app.config['MYSQL_UNIX_SOCKET']:\n kwargs['unix_socket'] = current_app.config['MYSQL_UNIX_SOCKET']\n if current_app.config['MYSQL_CONNECT_TIMEOUT']:\n kwargs['connect_timeout'] = current_app.config[\n 'MYSQL_CONNECT_TIMEOUT']\n if current_app.config['MYSQL_READ_DEFAULT_FILE']:\n kwargs['read_default_file'] = current_app.config[\n 'MYSQL_READ_DEFAULT_FILE']\n if current_app.config['MYSQL_USE_UNICODE']:\n kwargs['use_unicode'] = current_app.config['MYSQL_USE_UNICODE']\n if current_app.config['MYSQL_CHARSET']:\n kwargs['charset'] = current_app.config['MYSQL_CHARSET']\n if current_app.config['MYSQL_SQL_MODE']:\n kwargs['sql_mode'] = current_app.config['MYSQL_SQL_MODE']\n if current_app.config['MYSQL_CURSORCLASS']:\n kwargs['cursorclass'] = getattr(MySQLdb.cursors, current_app.\n config['MYSQL_CURSORCLASS'])\n return MySQLdb.connect(**kwargs)\n\n @property\n def connection(self):\n \"\"\"Attempts to connect to the MySQL server.\n\n :return: Bound MySQL connection object if successful or ``None`` if\n unsuccessful.\n \"\"\"\n ctx = _app_ctx_stack.top\n if ctx is not None:\n if not hasattr(ctx, 'mysql_db'):\n ctx.mysql_db = self.connect\n return ctx.mysql_db\n\n def teardown(self, exception):\n ctx = _app_ctx_stack.top\n if hasattr(ctx, 'mysql_db'):\n ctx.mysql_db.close()\n",
"step-5": "import MySQLdb\nimport MySQLdb.cursors\nfrom flask import _app_ctx_stack, current_app\n\n\nclass MySQL(object):\n\n def __init__(self, app=None):\n self.app = app\n if app is not None:\n self.init_app(app)\n\n def init_app(self, app):\n \"\"\"Initialize the `app` for use with this\n :class:`~flask_mysqldb.MySQL` class.\n This is called automatically if `app` is passed to\n :meth:`~MySQL.__init__`.\n\n :param flask.Flask app: the application to configure for use with\n this :class:`~flask_mysqldb.MySQL` class.\n \"\"\"\n\n app.config.setdefault('MYSQL_HOST', 'localhost')\n app.config.setdefault('MYSQL_USER', None)\n app.config.setdefault('MYSQL_PASSWORD', None)\n app.config.setdefault('MYSQL_DB', None)\n app.config.setdefault('MYSQL_PORT', 3306)\n app.config.setdefault('MYSQL_UNIX_SOCKET', None)\n app.config.setdefault('MYSQL_CONNECT_TIMEOUT', 10)\n app.config.setdefault('MYSQL_READ_DEFAULT_FILE', None)\n app.config.setdefault('MYSQL_USE_UNICODE', True)\n app.config.setdefault('MYSQL_CHARSET', 'utf8')\n app.config.setdefault('MYSQL_SQL_MODE', None)\n app.config.setdefault('MYSQL_CURSORCLASS', None)\n\n if hasattr(app, 'teardown_appcontext'):\n app.teardown_appcontext(self.teardown)\n\n @property\n def connect(self):\n kwargs = {}\n\n if current_app.config['MYSQL_HOST']:\n kwargs['host'] = current_app.config['MYSQL_HOST']\n\n if current_app.config['MYSQL_USER']:\n kwargs['user'] = current_app.config['MYSQL_USER']\n\n if current_app.config['MYSQL_PASSWORD']:\n kwargs['passwd'] = current_app.config['MYSQL_PASSWORD']\n\n if current_app.config['MYSQL_DB']:\n kwargs['db'] = current_app.config['MYSQL_DB']\n\n if current_app.config['MYSQL_PORT']:\n kwargs['port'] = current_app.config['MYSQL_PORT']\n\n if current_app.config['MYSQL_UNIX_SOCKET']:\n kwargs['unix_socket'] = current_app.config['MYSQL_UNIX_SOCKET']\n\n if current_app.config['MYSQL_CONNECT_TIMEOUT']:\n kwargs['connect_timeout'] = \\\n current_app.config['MYSQL_CONNECT_TIMEOUT']\n\n if current_app.config['MYSQL_READ_DEFAULT_FILE']:\n kwargs['read_default_file'] = \\\n current_app.config['MYSQL_READ_DEFAULT_FILE']\n\n if current_app.config['MYSQL_USE_UNICODE']:\n kwargs['use_unicode'] = current_app.config['MYSQL_USE_UNICODE']\n\n if current_app.config['MYSQL_CHARSET']:\n kwargs['charset'] = current_app.config['MYSQL_CHARSET']\n\n if current_app.config['MYSQL_SQL_MODE']:\n kwargs['sql_mode'] = current_app.config['MYSQL_SQL_MODE']\n\n if current_app.config['MYSQL_CURSORCLASS']:\n kwargs['cursorclass'] = getattr(MySQLdb.cursors, current_app.config['MYSQL_CURSORCLASS'])\n\n return MySQLdb.connect(**kwargs)\n\n @property\n def connection(self):\n \"\"\"Attempts to connect to the MySQL server.\n\n :return: Bound MySQL connection object if successful or ``None`` if\n unsuccessful.\n \"\"\"\n\n ctx = _app_ctx_stack.top\n if ctx is not None:\n if not hasattr(ctx, 'mysql_db'):\n ctx.mysql_db = self.connect\n return ctx.mysql_db\n\n def teardown(self, exception):\n ctx = _app_ctx_stack.top\n if hasattr(ctx, 'mysql_db'):\n ctx.mysql_db.close()\n",
"step-ids": [
4,
5,
6,
7,
8
]
}
|
[
4,
5,
6,
7,
8
] |
# -*- coding:ascii -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 10
_modified_time = 1428612037.145222
_enable_loop = True
_template_filename = 'C:\\Users\\Cody\\Desktop\\Heritage\\chf\\templates/account.rentalcart.html'
_template_uri = '/account.rentalcart.html'
_source_encoding = 'ascii'
import os, os.path, re
_exports = ['content']
from datetime import datetime, timedelta
now = datetime.now()
noww = now.strftime('%B %d, %Y')
def _mako_get_namespace(context, name):
try:
return context.namespaces[(__name__, name)]
except KeyError:
_mako_generate_namespaces(context)
return context.namespaces[(__name__, name)]
def _mako_generate_namespaces(context):
pass
def _mako_inherit(template, context):
_mako_generate_namespaces(context)
return runtime._inherit_from(context, 'base_ajax.htm', _template_uri)
def render_body(context,**pageargs):
__M_caller = context.caller_stack._push_frame()
try:
__M_locals = __M_dict_builtin(pageargs=pageargs)
int = context.get('int', UNDEFINED)
str = context.get('str', UNDEFINED)
rentals = context.get('rentals', UNDEFINED)
def content():
return render_content(context._locals(__M_locals))
request = context.get('request', UNDEFINED)
STATIC_URL = context.get('STATIC_URL', UNDEFINED)
__M_writer = context.writer()
__M_writer('\r\n')
__M_writer('\r\n')
__M_writer(str(nowww = noww - timedelta(days=3)))
__M_writer('\r\n')
if 'parent' not in context._data or not hasattr(context._data['parent'], 'content'):
context['self'].content(**pageargs)
__M_writer('\r\n\r\n')
return ''
finally:
context.caller_stack._pop_frame()
def render_content(context,**pageargs):
__M_caller = context.caller_stack._push_frame()
try:
int = context.get('int', UNDEFINED)
str = context.get('str', UNDEFINED)
rentals = context.get('rentals', UNDEFINED)
def content():
return render_content(context)
request = context.get('request', UNDEFINED)
STATIC_URL = context.get('STATIC_URL', UNDEFINED)
__M_writer = context.writer()
__M_writer('\r\n\r\n<table class="table-responsive table-striped">\r\n <th></th>\r\n <th>#</th>\r\n <th>Name</th>\r\n <th>Price per Day</th>\r\n <th># of Days Rented</th>\r\n')
for item in rentals:
__M_writer(' <tr>\r\n <td><button rel="')
__M_writer(str( item.id ))
__M_writer('" class="btn btn-danger btn-sm deleter">Remove</button></td>\r\n <td class="img-col"><img class="shopping_cart_image" src="')
__M_writer(str(STATIC_URL))
__M_writer(str( item.photo.image ))
__M_writer('"/></td>\r\n <td class="name-col">')
__M_writer(str( noww ))
__M_writer('</td>\r\n <td class="price-col">')
__M_writer(str( item.price_per_day ))
__M_writer('</td>\r\n <td class="qty-col">')
__M_writer(str(int(request.session['rental_cart'][str(item.id)])))
__M_writer('</td>\r\n </tr>\r\n')
__M_writer('</table>\r\n<table id="button-table" class="table-responsive">\r\n <tr>\r\n <td id="space"></td>\r\n')
if request.user.is_authenticated():
__M_writer(' <td id=\'checkout\'><a href="/account.checkout" class="btn btn-warning">Checkout</a></td>\r\n')
else:
__M_writer(' <td id=\'checkout\'><a href="/mylogin.cartlogin" class="btn btn-warning">Checkout</a></td>\r\n')
__M_writer(' </tr>\r\n</table>\r\n')
return ''
finally:
context.caller_stack._pop_frame()
"""
__M_BEGIN_METADATA
{"uri": "/account.rentalcart.html", "line_map": {"70": 8, "71": 16, "72": 17, "73": 18, "74": 18, "75": 19, "76": 19, "77": 19, "78": 20, "79": 20, "80": 21, "81": 21, "82": 22, "83": 22, "84": 25, "85": 29, "86": 30, "87": 31, "88": 32, "89": 34, "95": 89, "33": 0, "16": 2, "45": 1, "46": 6, "47": 7, "48": 7, "53": 36, "59": 8}, "filename": "C:\\Users\\Cody\\Desktop\\Heritage\\chf\\templates/account.rentalcart.html", "source_encoding": "ascii"}
__M_END_METADATA
"""
|
normal
|
{
"blob_id": "57967f36a45bb3ea62708bbbb5b2f4ddb0f4bb16",
"index": 29,
"step-1": "<mask token>\n\n\ndef _mako_get_namespace(context, name):\n try:\n return context.namespaces[__name__, name]\n except KeyError:\n _mako_generate_namespaces(context)\n return context.namespaces[__name__, name]\n\n\n<mask token>\n\n\ndef _mako_inherit(template, context):\n _mako_generate_namespaces(context)\n return runtime._inherit_from(context, 'base_ajax.htm', _template_uri)\n\n\n<mask token>\n\n\ndef render_content(context, **pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n int = context.get('int', UNDEFINED)\n str = context.get('str', UNDEFINED)\n rentals = context.get('rentals', UNDEFINED)\n\n def content():\n return render_content(context)\n request = context.get('request', UNDEFINED)\n STATIC_URL = context.get('STATIC_URL', UNDEFINED)\n __M_writer = context.writer()\n __M_writer(\n '\\r\\n\\r\\n<table class=\"table-responsive table-striped\">\\r\\n <th></th>\\r\\n <th>#</th>\\r\\n <th>Name</th>\\r\\n <th>Price per Day</th>\\r\\n <th># of Days Rented</th>\\r\\n'\n )\n for item in rentals:\n __M_writer(' <tr>\\r\\n <td><button rel=\"')\n __M_writer(str(item.id))\n __M_writer(\n '\" class=\"btn btn-danger btn-sm deleter\">Remove</button></td>\\r\\n <td class=\"img-col\"><img class=\"shopping_cart_image\" src=\"'\n )\n __M_writer(str(STATIC_URL))\n __M_writer(str(item.photo.image))\n __M_writer('\"/></td>\\r\\n <td class=\"name-col\">')\n __M_writer(str(noww))\n __M_writer('</td>\\r\\n <td class=\"price-col\">')\n __M_writer(str(item.price_per_day))\n __M_writer('</td>\\r\\n <td class=\"qty-col\">')\n __M_writer(str(int(request.session['rental_cart'][str(item.id)])))\n __M_writer('</td>\\r\\n </tr>\\r\\n')\n __M_writer(\n '</table>\\r\\n<table id=\"button-table\" class=\"table-responsive\">\\r\\n <tr>\\r\\n <td id=\"space\"></td>\\r\\n'\n )\n if request.user.is_authenticated():\n __M_writer(\n ' <td id=\\'checkout\\'><a href=\"/account.checkout\" class=\"btn btn-warning\">Checkout</a></td>\\r\\n'\n )\n else:\n __M_writer(\n ' <td id=\\'checkout\\'><a href=\"/mylogin.cartlogin\" class=\"btn btn-warning\">Checkout</a></td>\\r\\n'\n )\n __M_writer(' </tr>\\r\\n</table>\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n<mask token>\n",
"step-2": "<mask token>\n\n\ndef _mako_get_namespace(context, name):\n try:\n return context.namespaces[__name__, name]\n except KeyError:\n _mako_generate_namespaces(context)\n return context.namespaces[__name__, name]\n\n\ndef _mako_generate_namespaces(context):\n pass\n\n\ndef _mako_inherit(template, context):\n _mako_generate_namespaces(context)\n return runtime._inherit_from(context, 'base_ajax.htm', _template_uri)\n\n\ndef render_body(context, **pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n __M_locals = __M_dict_builtin(pageargs=pageargs)\n int = context.get('int', UNDEFINED)\n str = context.get('str', UNDEFINED)\n rentals = context.get('rentals', UNDEFINED)\n\n def content():\n return render_content(context._locals(__M_locals))\n request = context.get('request', UNDEFINED)\n STATIC_URL = context.get('STATIC_URL', UNDEFINED)\n __M_writer = context.writer()\n __M_writer('\\r\\n')\n __M_writer('\\r\\n')\n __M_writer(str(nowww=noww - timedelta(days=3)))\n __M_writer('\\r\\n')\n if 'parent' not in context._data or not hasattr(context._data[\n 'parent'], 'content'):\n context['self'].content(**pageargs)\n __M_writer('\\r\\n\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_content(context, **pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n int = context.get('int', UNDEFINED)\n str = context.get('str', UNDEFINED)\n rentals = context.get('rentals', UNDEFINED)\n\n def content():\n return render_content(context)\n request = context.get('request', UNDEFINED)\n STATIC_URL = context.get('STATIC_URL', UNDEFINED)\n __M_writer = context.writer()\n __M_writer(\n '\\r\\n\\r\\n<table class=\"table-responsive table-striped\">\\r\\n <th></th>\\r\\n <th>#</th>\\r\\n <th>Name</th>\\r\\n <th>Price per Day</th>\\r\\n <th># of Days Rented</th>\\r\\n'\n )\n for item in rentals:\n __M_writer(' <tr>\\r\\n <td><button rel=\"')\n __M_writer(str(item.id))\n __M_writer(\n '\" class=\"btn btn-danger btn-sm deleter\">Remove</button></td>\\r\\n <td class=\"img-col\"><img class=\"shopping_cart_image\" src=\"'\n )\n __M_writer(str(STATIC_URL))\n __M_writer(str(item.photo.image))\n __M_writer('\"/></td>\\r\\n <td class=\"name-col\">')\n __M_writer(str(noww))\n __M_writer('</td>\\r\\n <td class=\"price-col\">')\n __M_writer(str(item.price_per_day))\n __M_writer('</td>\\r\\n <td class=\"qty-col\">')\n __M_writer(str(int(request.session['rental_cart'][str(item.id)])))\n __M_writer('</td>\\r\\n </tr>\\r\\n')\n __M_writer(\n '</table>\\r\\n<table id=\"button-table\" class=\"table-responsive\">\\r\\n <tr>\\r\\n <td id=\"space\"></td>\\r\\n'\n )\n if request.user.is_authenticated():\n __M_writer(\n ' <td id=\\'checkout\\'><a href=\"/account.checkout\" class=\"btn btn-warning\">Checkout</a></td>\\r\\n'\n )\n else:\n __M_writer(\n ' <td id=\\'checkout\\'><a href=\"/mylogin.cartlogin\" class=\"btn btn-warning\">Checkout</a></td>\\r\\n'\n )\n __M_writer(' </tr>\\r\\n</table>\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n<mask token>\n",
"step-3": "<mask token>\nUNDEFINED = runtime.UNDEFINED\n__M_dict_builtin = dict\n__M_locals_builtin = locals\n_magic_number = 10\n_modified_time = 1428612037.145222\n_enable_loop = True\n_template_filename = (\n 'C:\\\\Users\\\\Cody\\\\Desktop\\\\Heritage\\\\chf\\\\templates/account.rentalcart.html'\n )\n_template_uri = '/account.rentalcart.html'\n_source_encoding = 'ascii'\n<mask token>\n_exports = ['content']\n<mask token>\nnow = datetime.now()\nnoww = now.strftime('%B %d, %Y')\n\n\ndef _mako_get_namespace(context, name):\n try:\n return context.namespaces[__name__, name]\n except KeyError:\n _mako_generate_namespaces(context)\n return context.namespaces[__name__, name]\n\n\ndef _mako_generate_namespaces(context):\n pass\n\n\ndef _mako_inherit(template, context):\n _mako_generate_namespaces(context)\n return runtime._inherit_from(context, 'base_ajax.htm', _template_uri)\n\n\ndef render_body(context, **pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n __M_locals = __M_dict_builtin(pageargs=pageargs)\n int = context.get('int', UNDEFINED)\n str = context.get('str', UNDEFINED)\n rentals = context.get('rentals', UNDEFINED)\n\n def content():\n return render_content(context._locals(__M_locals))\n request = context.get('request', UNDEFINED)\n STATIC_URL = context.get('STATIC_URL', UNDEFINED)\n __M_writer = context.writer()\n __M_writer('\\r\\n')\n __M_writer('\\r\\n')\n __M_writer(str(nowww=noww - timedelta(days=3)))\n __M_writer('\\r\\n')\n if 'parent' not in context._data or not hasattr(context._data[\n 'parent'], 'content'):\n context['self'].content(**pageargs)\n __M_writer('\\r\\n\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_content(context, **pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n int = context.get('int', UNDEFINED)\n str = context.get('str', UNDEFINED)\n rentals = context.get('rentals', UNDEFINED)\n\n def content():\n return render_content(context)\n request = context.get('request', UNDEFINED)\n STATIC_URL = context.get('STATIC_URL', UNDEFINED)\n __M_writer = context.writer()\n __M_writer(\n '\\r\\n\\r\\n<table class=\"table-responsive table-striped\">\\r\\n <th></th>\\r\\n <th>#</th>\\r\\n <th>Name</th>\\r\\n <th>Price per Day</th>\\r\\n <th># of Days Rented</th>\\r\\n'\n )\n for item in rentals:\n __M_writer(' <tr>\\r\\n <td><button rel=\"')\n __M_writer(str(item.id))\n __M_writer(\n '\" class=\"btn btn-danger btn-sm deleter\">Remove</button></td>\\r\\n <td class=\"img-col\"><img class=\"shopping_cart_image\" src=\"'\n )\n __M_writer(str(STATIC_URL))\n __M_writer(str(item.photo.image))\n __M_writer('\"/></td>\\r\\n <td class=\"name-col\">')\n __M_writer(str(noww))\n __M_writer('</td>\\r\\n <td class=\"price-col\">')\n __M_writer(str(item.price_per_day))\n __M_writer('</td>\\r\\n <td class=\"qty-col\">')\n __M_writer(str(int(request.session['rental_cart'][str(item.id)])))\n __M_writer('</td>\\r\\n </tr>\\r\\n')\n __M_writer(\n '</table>\\r\\n<table id=\"button-table\" class=\"table-responsive\">\\r\\n <tr>\\r\\n <td id=\"space\"></td>\\r\\n'\n )\n if request.user.is_authenticated():\n __M_writer(\n ' <td id=\\'checkout\\'><a href=\"/account.checkout\" class=\"btn btn-warning\">Checkout</a></td>\\r\\n'\n )\n else:\n __M_writer(\n ' <td id=\\'checkout\\'><a href=\"/mylogin.cartlogin\" class=\"btn btn-warning\">Checkout</a></td>\\r\\n'\n )\n __M_writer(' </tr>\\r\\n</table>\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n<mask token>\n",
"step-4": "from mako import runtime, filters, cache\nUNDEFINED = runtime.UNDEFINED\n__M_dict_builtin = dict\n__M_locals_builtin = locals\n_magic_number = 10\n_modified_time = 1428612037.145222\n_enable_loop = True\n_template_filename = (\n 'C:\\\\Users\\\\Cody\\\\Desktop\\\\Heritage\\\\chf\\\\templates/account.rentalcart.html'\n )\n_template_uri = '/account.rentalcart.html'\n_source_encoding = 'ascii'\nimport os, os.path, re\n_exports = ['content']\nfrom datetime import datetime, timedelta\nnow = datetime.now()\nnoww = now.strftime('%B %d, %Y')\n\n\ndef _mako_get_namespace(context, name):\n try:\n return context.namespaces[__name__, name]\n except KeyError:\n _mako_generate_namespaces(context)\n return context.namespaces[__name__, name]\n\n\ndef _mako_generate_namespaces(context):\n pass\n\n\ndef _mako_inherit(template, context):\n _mako_generate_namespaces(context)\n return runtime._inherit_from(context, 'base_ajax.htm', _template_uri)\n\n\ndef render_body(context, **pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n __M_locals = __M_dict_builtin(pageargs=pageargs)\n int = context.get('int', UNDEFINED)\n str = context.get('str', UNDEFINED)\n rentals = context.get('rentals', UNDEFINED)\n\n def content():\n return render_content(context._locals(__M_locals))\n request = context.get('request', UNDEFINED)\n STATIC_URL = context.get('STATIC_URL', UNDEFINED)\n __M_writer = context.writer()\n __M_writer('\\r\\n')\n __M_writer('\\r\\n')\n __M_writer(str(nowww=noww - timedelta(days=3)))\n __M_writer('\\r\\n')\n if 'parent' not in context._data or not hasattr(context._data[\n 'parent'], 'content'):\n context['self'].content(**pageargs)\n __M_writer('\\r\\n\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_content(context, **pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n int = context.get('int', UNDEFINED)\n str = context.get('str', UNDEFINED)\n rentals = context.get('rentals', UNDEFINED)\n\n def content():\n return render_content(context)\n request = context.get('request', UNDEFINED)\n STATIC_URL = context.get('STATIC_URL', UNDEFINED)\n __M_writer = context.writer()\n __M_writer(\n '\\r\\n\\r\\n<table class=\"table-responsive table-striped\">\\r\\n <th></th>\\r\\n <th>#</th>\\r\\n <th>Name</th>\\r\\n <th>Price per Day</th>\\r\\n <th># of Days Rented</th>\\r\\n'\n )\n for item in rentals:\n __M_writer(' <tr>\\r\\n <td><button rel=\"')\n __M_writer(str(item.id))\n __M_writer(\n '\" class=\"btn btn-danger btn-sm deleter\">Remove</button></td>\\r\\n <td class=\"img-col\"><img class=\"shopping_cart_image\" src=\"'\n )\n __M_writer(str(STATIC_URL))\n __M_writer(str(item.photo.image))\n __M_writer('\"/></td>\\r\\n <td class=\"name-col\">')\n __M_writer(str(noww))\n __M_writer('</td>\\r\\n <td class=\"price-col\">')\n __M_writer(str(item.price_per_day))\n __M_writer('</td>\\r\\n <td class=\"qty-col\">')\n __M_writer(str(int(request.session['rental_cart'][str(item.id)])))\n __M_writer('</td>\\r\\n </tr>\\r\\n')\n __M_writer(\n '</table>\\r\\n<table id=\"button-table\" class=\"table-responsive\">\\r\\n <tr>\\r\\n <td id=\"space\"></td>\\r\\n'\n )\n if request.user.is_authenticated():\n __M_writer(\n ' <td id=\\'checkout\\'><a href=\"/account.checkout\" class=\"btn btn-warning\">Checkout</a></td>\\r\\n'\n )\n else:\n __M_writer(\n ' <td id=\\'checkout\\'><a href=\"/mylogin.cartlogin\" class=\"btn btn-warning\">Checkout</a></td>\\r\\n'\n )\n __M_writer(' </tr>\\r\\n</table>\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n<mask token>\n",
"step-5": "# -*- coding:ascii -*-\nfrom mako import runtime, filters, cache\nUNDEFINED = runtime.UNDEFINED\n__M_dict_builtin = dict\n__M_locals_builtin = locals\n_magic_number = 10\n_modified_time = 1428612037.145222\n_enable_loop = True\n_template_filename = 'C:\\\\Users\\\\Cody\\\\Desktop\\\\Heritage\\\\chf\\\\templates/account.rentalcart.html'\n_template_uri = '/account.rentalcart.html'\n_source_encoding = 'ascii'\nimport os, os.path, re\n_exports = ['content']\n\n\n\nfrom datetime import datetime, timedelta\nnow = datetime.now()\nnoww = now.strftime('%B %d, %Y')\n\n\ndef _mako_get_namespace(context, name):\n try:\n return context.namespaces[(__name__, name)]\n except KeyError:\n _mako_generate_namespaces(context)\n return context.namespaces[(__name__, name)]\ndef _mako_generate_namespaces(context):\n pass\ndef _mako_inherit(template, context):\n _mako_generate_namespaces(context)\n return runtime._inherit_from(context, 'base_ajax.htm', _template_uri)\ndef render_body(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n __M_locals = __M_dict_builtin(pageargs=pageargs)\n int = context.get('int', UNDEFINED)\n str = context.get('str', UNDEFINED)\n rentals = context.get('rentals', UNDEFINED)\n def content():\n return render_content(context._locals(__M_locals))\n request = context.get('request', UNDEFINED)\n STATIC_URL = context.get('STATIC_URL', UNDEFINED)\n __M_writer = context.writer()\n __M_writer('\\r\\n')\n __M_writer('\\r\\n')\n __M_writer(str(nowww = noww - timedelta(days=3)))\n __M_writer('\\r\\n')\n if 'parent' not in context._data or not hasattr(context._data['parent'], 'content'):\n context['self'].content(**pageargs)\n \n\n __M_writer('\\r\\n\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\ndef render_content(context,**pageargs):\n __M_caller = context.caller_stack._push_frame()\n try:\n int = context.get('int', UNDEFINED)\n str = context.get('str', UNDEFINED)\n rentals = context.get('rentals', UNDEFINED)\n def content():\n return render_content(context)\n request = context.get('request', UNDEFINED)\n STATIC_URL = context.get('STATIC_URL', UNDEFINED)\n __M_writer = context.writer()\n __M_writer('\\r\\n\\r\\n<table class=\"table-responsive table-striped\">\\r\\n <th></th>\\r\\n <th>#</th>\\r\\n <th>Name</th>\\r\\n <th>Price per Day</th>\\r\\n <th># of Days Rented</th>\\r\\n')\n for item in rentals:\n __M_writer(' <tr>\\r\\n <td><button rel=\"')\n __M_writer(str( item.id ))\n __M_writer('\" class=\"btn btn-danger btn-sm deleter\">Remove</button></td>\\r\\n <td class=\"img-col\"><img class=\"shopping_cart_image\" src=\"')\n __M_writer(str(STATIC_URL))\n __M_writer(str( item.photo.image ))\n __M_writer('\"/></td>\\r\\n <td class=\"name-col\">')\n __M_writer(str( noww ))\n __M_writer('</td>\\r\\n <td class=\"price-col\">')\n __M_writer(str( item.price_per_day ))\n __M_writer('</td>\\r\\n <td class=\"qty-col\">')\n __M_writer(str(int(request.session['rental_cart'][str(item.id)])))\n __M_writer('</td>\\r\\n </tr>\\r\\n')\n __M_writer('</table>\\r\\n<table id=\"button-table\" class=\"table-responsive\">\\r\\n <tr>\\r\\n <td id=\"space\"></td>\\r\\n')\n if request.user.is_authenticated():\n __M_writer(' <td id=\\'checkout\\'><a href=\"/account.checkout\" class=\"btn btn-warning\">Checkout</a></td>\\r\\n')\n else:\n __M_writer(' <td id=\\'checkout\\'><a href=\"/mylogin.cartlogin\" class=\"btn btn-warning\">Checkout</a></td>\\r\\n')\n __M_writer(' </tr>\\r\\n</table>\\r\\n')\n return ''\n finally:\n context.caller_stack._pop_frame()\n\n\n\"\"\"\n__M_BEGIN_METADATA\n{\"uri\": \"/account.rentalcart.html\", \"line_map\": {\"70\": 8, \"71\": 16, \"72\": 17, \"73\": 18, \"74\": 18, \"75\": 19, \"76\": 19, \"77\": 19, \"78\": 20, \"79\": 20, \"80\": 21, \"81\": 21, \"82\": 22, \"83\": 22, \"84\": 25, \"85\": 29, \"86\": 30, \"87\": 31, \"88\": 32, \"89\": 34, \"95\": 89, \"33\": 0, \"16\": 2, \"45\": 1, \"46\": 6, \"47\": 7, \"48\": 7, \"53\": 36, \"59\": 8}, \"filename\": \"C:\\\\Users\\\\Cody\\\\Desktop\\\\Heritage\\\\chf\\\\templates/account.rentalcart.html\", \"source_encoding\": \"ascii\"}\n__M_END_METADATA\n\"\"\"\n",
"step-ids": [
3,
5,
6,
7,
8
]
}
|
[
3,
5,
6,
7,
8
] |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from abc import ABCMeta, abstractmethod
import numpy as np
from deeprl.trainers import BaseTrainer
from deeprl.callbacks import EGreedyDecay
from deeprl.policy import EGreedyPolicy
class BaseDQNTrainer(BaseTrainer):
__metaclass__ = ABCMeta
def __init__(self, config, agent, env):
super(BaseDQNTrainer, self).__init__(config, agent, env)
self.discount_factor = config.discount_factor
self.policy = EGreedyPolicy(config.e)
self.callbacks.append(EGreedyDecay(self.policy, config.e_min,
config.e_decay))
def choose_action(self, state):
q_value = self.agent.model.get_one_q(state)
return self.policy.choose_action(q_value)
def update_model(self, batch):
batch_s = np.array([i[0] for i in batch])
batch_a = np.array([i[1] for i in batch])
batch_r = np.array([i[2] for i in batch])
batch_s1 = np.array([i[3] for i in batch])
batch_done = np.array([i[4] for i in batch])
q_target = self.get_q_target(batch_r, batch_s1, batch_done)
loss = self.agent.model.train(batch_s, batch_a, q_target)
return loss
@abstractmethod
def get_q_target(self, batch_rewards, batch_next_states, batch_dones):
pass
|
normal
|
{
"blob_id": "8bf0141cee2832134d61e49652330c7d21583dcd",
"index": 5201,
"step-1": "<mask token>\n\n\nclass BaseDQNTrainer(BaseTrainer):\n <mask token>\n <mask token>\n <mask token>\n\n def update_model(self, batch):\n batch_s = np.array([i[0] for i in batch])\n batch_a = np.array([i[1] for i in batch])\n batch_r = np.array([i[2] for i in batch])\n batch_s1 = np.array([i[3] for i in batch])\n batch_done = np.array([i[4] for i in batch])\n q_target = self.get_q_target(batch_r, batch_s1, batch_done)\n loss = self.agent.model.train(batch_s, batch_a, q_target)\n return loss\n\n @abstractmethod\n def get_q_target(self, batch_rewards, batch_next_states, batch_dones):\n pass\n",
"step-2": "<mask token>\n\n\nclass BaseDQNTrainer(BaseTrainer):\n <mask token>\n <mask token>\n\n def choose_action(self, state):\n q_value = self.agent.model.get_one_q(state)\n return self.policy.choose_action(q_value)\n\n def update_model(self, batch):\n batch_s = np.array([i[0] for i in batch])\n batch_a = np.array([i[1] for i in batch])\n batch_r = np.array([i[2] for i in batch])\n batch_s1 = np.array([i[3] for i in batch])\n batch_done = np.array([i[4] for i in batch])\n q_target = self.get_q_target(batch_r, batch_s1, batch_done)\n loss = self.agent.model.train(batch_s, batch_a, q_target)\n return loss\n\n @abstractmethod\n def get_q_target(self, batch_rewards, batch_next_states, batch_dones):\n pass\n",
"step-3": "<mask token>\n\n\nclass BaseDQNTrainer(BaseTrainer):\n __metaclass__ = ABCMeta\n\n def __init__(self, config, agent, env):\n super(BaseDQNTrainer, self).__init__(config, agent, env)\n self.discount_factor = config.discount_factor\n self.policy = EGreedyPolicy(config.e)\n self.callbacks.append(EGreedyDecay(self.policy, config.e_min,\n config.e_decay))\n\n def choose_action(self, state):\n q_value = self.agent.model.get_one_q(state)\n return self.policy.choose_action(q_value)\n\n def update_model(self, batch):\n batch_s = np.array([i[0] for i in batch])\n batch_a = np.array([i[1] for i in batch])\n batch_r = np.array([i[2] for i in batch])\n batch_s1 = np.array([i[3] for i in batch])\n batch_done = np.array([i[4] for i in batch])\n q_target = self.get_q_target(batch_r, batch_s1, batch_done)\n loss = self.agent.model.train(batch_s, batch_a, q_target)\n return loss\n\n @abstractmethod\n def get_q_target(self, batch_rewards, batch_next_states, batch_dones):\n pass\n",
"step-4": "from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom abc import ABCMeta, abstractmethod\nimport numpy as np\nfrom deeprl.trainers import BaseTrainer\nfrom deeprl.callbacks import EGreedyDecay\nfrom deeprl.policy import EGreedyPolicy\n\n\nclass BaseDQNTrainer(BaseTrainer):\n __metaclass__ = ABCMeta\n\n def __init__(self, config, agent, env):\n super(BaseDQNTrainer, self).__init__(config, agent, env)\n self.discount_factor = config.discount_factor\n self.policy = EGreedyPolicy(config.e)\n self.callbacks.append(EGreedyDecay(self.policy, config.e_min,\n config.e_decay))\n\n def choose_action(self, state):\n q_value = self.agent.model.get_one_q(state)\n return self.policy.choose_action(q_value)\n\n def update_model(self, batch):\n batch_s = np.array([i[0] for i in batch])\n batch_a = np.array([i[1] for i in batch])\n batch_r = np.array([i[2] for i in batch])\n batch_s1 = np.array([i[3] for i in batch])\n batch_done = np.array([i[4] for i in batch])\n q_target = self.get_q_target(batch_r, batch_s1, batch_done)\n loss = self.agent.model.train(batch_s, batch_a, q_target)\n return loss\n\n @abstractmethod\n def get_q_target(self, batch_rewards, batch_next_states, batch_dones):\n pass\n",
"step-5": null,
"step-ids": [
3,
4,
6,
7
]
}
|
[
3,
4,
6,
7
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
urlpatterns = [url('^admin/', admin.site.urls), url('^logout/$', auth_views
.logout, {'next_page': '/'}, name='logout'), url('^$', index_view, name
='index'), url('^login/$', login_view, name='login'), url('^register/$',
register_view, name='register'), url('^profile/$', profile_view, name=
'profile'), url('^my-products/$', my_products_view, name='my-products'),
url('^my-products/(?P<filter>[\\w-]+)', my_products_view, name=
'my-products'), url('^delete-product/(?P<id>\\d+)/', delete_product,
name='delete-product'), url('^add-new-product/$', add_new_product, name
='add-new-product'), url('^validate-product/$', validate_product, name=
'validate-product'), url('^dashboard/$', dashboard_view, name=
'dashboard'), url('^edit-profile/$', edit_profile_view, name=
'edit-profile'), url('^display-product/(?P<id>\\d+)/', display_product,
name='display-product'), url('^product-details/(?P<id>\\d+)/',
product_details_view, name='product-details'), url(
'^test_notifications/$', test_email_notifications, name='test-view'),
url('^test_update_prices/(?P<id>\\w+)/', test_update_prices, name=
'update-prices'), url('^test_update_all_prices/$',
test_update_all_prices, name='update-all-prices')]
<|reserved_special_token_1|>
<|reserved_special_token_0|>
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from .views import validate_product, display_product
from .views import index_view, login_view, register_view, profile_view
from .views import my_products_view, delete_product, add_new_product, dashboard_view, test_email_notifications, edit_profile_view, product_details_view, test_update_prices, test_update_all_prices
urlpatterns = [url('^admin/', admin.site.urls), url('^logout/$', auth_views
.logout, {'next_page': '/'}, name='logout'), url('^$', index_view, name
='index'), url('^login/$', login_view, name='login'), url('^register/$',
register_view, name='register'), url('^profile/$', profile_view, name=
'profile'), url('^my-products/$', my_products_view, name='my-products'),
url('^my-products/(?P<filter>[\\w-]+)', my_products_view, name=
'my-products'), url('^delete-product/(?P<id>\\d+)/', delete_product,
name='delete-product'), url('^add-new-product/$', add_new_product, name
='add-new-product'), url('^validate-product/$', validate_product, name=
'validate-product'), url('^dashboard/$', dashboard_view, name=
'dashboard'), url('^edit-profile/$', edit_profile_view, name=
'edit-profile'), url('^display-product/(?P<id>\\d+)/', display_product,
name='display-product'), url('^product-details/(?P<id>\\d+)/',
product_details_view, name='product-details'), url(
'^test_notifications/$', test_email_notifications, name='test-view'),
url('^test_update_prices/(?P<id>\\w+)/', test_update_prices, name=
'update-prices'), url('^test_update_all_prices/$',
test_update_all_prices, name='update-all-prices')]
<|reserved_special_token_1|>
"""PriceTrail URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.conf.urls import url, include
2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))
"""
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from .views import validate_product, display_product
#user related views
from .views import index_view, login_view, register_view, profile_view
#products related views
from .views import my_products_view, delete_product, add_new_product, dashboard_view, test_email_notifications, edit_profile_view, product_details_view, \
test_update_prices, test_update_all_prices
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),
# implemented views
url(r'^$', index_view, name='index'),#this will became index
url(r'^login/$', login_view, name='login'),
url(r'^register/$', register_view, name='register'),
url(r'^profile/$', profile_view, name='profile'),
url(r'^my-products/$', my_products_view, name='my-products'),
url(r'^my-products/(?P<filter>[\w-]+)', my_products_view, name='my-products'),
url(r'^delete-product/(?P<id>\d+)/', delete_product, name='delete-product'),
url(r'^add-new-product/$', add_new_product, name='add-new-product'),
url(r'^validate-product/$', validate_product, name='validate-product'),
url(r'^dashboard/$', dashboard_view, name='dashboard'),
url(r'^edit-profile/$', edit_profile_view, name='edit-profile'),
#modal window
url(r'^display-product/(?P<id>\d+)/', display_product, name='display-product'),
url(r'^product-details/(?P<id>\d+)/', product_details_view, name='product-details'),
#superuser endpoints
url(r'^test_notifications/$', test_email_notifications, name='test-view'),
url(r'^test_update_prices/(?P<id>\w+)/', test_update_prices, name='update-prices'),
url(r'^test_update_all_prices/$', test_update_all_prices, name='update-all-prices'),
]
|
flexible
|
{
"blob_id": "06627821c09d02543974a3c90664e84e11c980ed",
"index": 7631,
"step-1": "<mask token>\n",
"step-2": "<mask token>\nurlpatterns = [url('^admin/', admin.site.urls), url('^logout/$', auth_views\n .logout, {'next_page': '/'}, name='logout'), url('^$', index_view, name\n ='index'), url('^login/$', login_view, name='login'), url('^register/$',\n register_view, name='register'), url('^profile/$', profile_view, name=\n 'profile'), url('^my-products/$', my_products_view, name='my-products'),\n url('^my-products/(?P<filter>[\\\\w-]+)', my_products_view, name=\n 'my-products'), url('^delete-product/(?P<id>\\\\d+)/', delete_product,\n name='delete-product'), url('^add-new-product/$', add_new_product, name\n ='add-new-product'), url('^validate-product/$', validate_product, name=\n 'validate-product'), url('^dashboard/$', dashboard_view, name=\n 'dashboard'), url('^edit-profile/$', edit_profile_view, name=\n 'edit-profile'), url('^display-product/(?P<id>\\\\d+)/', display_product,\n name='display-product'), url('^product-details/(?P<id>\\\\d+)/',\n product_details_view, name='product-details'), url(\n '^test_notifications/$', test_email_notifications, name='test-view'),\n url('^test_update_prices/(?P<id>\\\\w+)/', test_update_prices, name=\n 'update-prices'), url('^test_update_all_prices/$',\n test_update_all_prices, name='update-all-prices')]\n",
"step-3": "<mask token>\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom django.contrib.auth import views as auth_views\nfrom .views import validate_product, display_product\nfrom .views import index_view, login_view, register_view, profile_view\nfrom .views import my_products_view, delete_product, add_new_product, dashboard_view, test_email_notifications, edit_profile_view, product_details_view, test_update_prices, test_update_all_prices\nurlpatterns = [url('^admin/', admin.site.urls), url('^logout/$', auth_views\n .logout, {'next_page': '/'}, name='logout'), url('^$', index_view, name\n ='index'), url('^login/$', login_view, name='login'), url('^register/$',\n register_view, name='register'), url('^profile/$', profile_view, name=\n 'profile'), url('^my-products/$', my_products_view, name='my-products'),\n url('^my-products/(?P<filter>[\\\\w-]+)', my_products_view, name=\n 'my-products'), url('^delete-product/(?P<id>\\\\d+)/', delete_product,\n name='delete-product'), url('^add-new-product/$', add_new_product, name\n ='add-new-product'), url('^validate-product/$', validate_product, name=\n 'validate-product'), url('^dashboard/$', dashboard_view, name=\n 'dashboard'), url('^edit-profile/$', edit_profile_view, name=\n 'edit-profile'), url('^display-product/(?P<id>\\\\d+)/', display_product,\n name='display-product'), url('^product-details/(?P<id>\\\\d+)/',\n product_details_view, name='product-details'), url(\n '^test_notifications/$', test_email_notifications, name='test-view'),\n url('^test_update_prices/(?P<id>\\\\w+)/', test_update_prices, name=\n 'update-prices'), url('^test_update_all_prices/$',\n test_update_all_prices, name='update-all-prices')]\n",
"step-4": "\"\"\"PriceTrail URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom django.contrib.auth import views as auth_views\nfrom .views import validate_product, display_product\n\n#user related views\nfrom .views import index_view, login_view, register_view, profile_view\n#products related views\nfrom .views import my_products_view, delete_product, add_new_product, dashboard_view, test_email_notifications, edit_profile_view, product_details_view, \\\n test_update_prices, test_update_all_prices\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'^logout/$', auth_views.logout, {'next_page': '/'}, name='logout'),\n\n # implemented views\n url(r'^$', index_view, name='index'),#this will became index\n url(r'^login/$', login_view, name='login'),\n url(r'^register/$', register_view, name='register'),\n url(r'^profile/$', profile_view, name='profile'),\n url(r'^my-products/$', my_products_view, name='my-products'),\n url(r'^my-products/(?P<filter>[\\w-]+)', my_products_view, name='my-products'),\n url(r'^delete-product/(?P<id>\\d+)/', delete_product, name='delete-product'),\n url(r'^add-new-product/$', add_new_product, name='add-new-product'),\n url(r'^validate-product/$', validate_product, name='validate-product'),\n url(r'^dashboard/$', dashboard_view, name='dashboard'),\n url(r'^edit-profile/$', edit_profile_view, name='edit-profile'),\n\n #modal window\n url(r'^display-product/(?P<id>\\d+)/', display_product, name='display-product'),\n url(r'^product-details/(?P<id>\\d+)/', product_details_view, name='product-details'),\n\n #superuser endpoints\n url(r'^test_notifications/$', test_email_notifications, name='test-view'),\n url(r'^test_update_prices/(?P<id>\\w+)/', test_update_prices, name='update-prices'),\n url(r'^test_update_all_prices/$', test_update_all_prices, name='update-all-prices'),\n]\n",
"step-5": null,
"step-ids": [
0,
1,
2,
3
]
}
|
[
0,
1,
2,
3
] |
<|reserved_special_token_0|>
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
<|reserved_special_token_0|>
@app.route('/get_suggestion', methods=['GET', 'POST'])
def get_suggestion():
if 'words' not in request.values.keys():
raise InvalidUsage('No words were specified for prediction.',
status_code=400)
text = request.values['words']
prediction = []
if len(text.split(' ')) > 1:
prediction = autocomplete.split_predict(text, 10)
else:
prediction = autocomplete.predict_currword(text, 10)
return jsonify(prediction)
@app.route('/send_text', methods=['GET', 'POST'])
def send_text():
if 'text' not in request.values.keys():
raise InvalidUsage('The text message was not found in the request.',
status_code=400)
if 'to' not in request.values.keys():
raise InvalidUsage('The to-number was not found in the request',
status_code=400)
text = request.values['text']
to_number = request.values['to']
account_sid = 'ACbbd2cff98bcbbad08f76b03701a0f2d9'
auth_token = '7d786ff14c6b4572a6e8e78f8ad6aee5'
client = Client(account_sid, auth_token)
message = client.messages.create(from_='+12267992139', to=to_number,
body=text)
return jsonify({'to': to_number, 'message': message.body, 'error code':
message.error_code})
<|reserved_special_token_1|>
<|reserved_special_token_0|>
@app.route('/')
def index():
return render_template('index.html')
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.route('/convert_text_to_speech', methods=['POST'])
def convert_text_to_speech():
if 'text_to_convert' not in request.values.keys():
raise InvalidUsage('No text included for conversion', status_code=400)
tts = gTTS(text=request.values['text_to_convert'], lang='en')
tts.save('converted_text.mp3')
os.system('start converted_text.mp3')
return send_file('converted_text.mp3', mimetype='audio/mpeg')
@app.route('/get_suggestion', methods=['GET', 'POST'])
def get_suggestion():
if 'words' not in request.values.keys():
raise InvalidUsage('No words were specified for prediction.',
status_code=400)
text = request.values['words']
prediction = []
if len(text.split(' ')) > 1:
prediction = autocomplete.split_predict(text, 10)
else:
prediction = autocomplete.predict_currword(text, 10)
return jsonify(prediction)
@app.route('/send_text', methods=['GET', 'POST'])
def send_text():
if 'text' not in request.values.keys():
raise InvalidUsage('The text message was not found in the request.',
status_code=400)
if 'to' not in request.values.keys():
raise InvalidUsage('The to-number was not found in the request',
status_code=400)
text = request.values['text']
to_number = request.values['to']
account_sid = 'ACbbd2cff98bcbbad08f76b03701a0f2d9'
auth_token = '7d786ff14c6b4572a6e8e78f8ad6aee5'
client = Client(account_sid, auth_token)
message = client.messages.create(from_='+12267992139', to=to_number,
body=text)
return jsonify({'to': to_number, 'message': message.body, 'error code':
message.error_code})
<|reserved_special_token_1|>
<|reserved_special_token_0|>
autocomplete.load()
<|reserved_special_token_0|>
CORS(app)
@app.route('/')
def index():
return render_template('index.html')
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.route('/convert_text_to_speech', methods=['POST'])
def convert_text_to_speech():
if 'text_to_convert' not in request.values.keys():
raise InvalidUsage('No text included for conversion', status_code=400)
tts = gTTS(text=request.values['text_to_convert'], lang='en')
tts.save('converted_text.mp3')
os.system('start converted_text.mp3')
return send_file('converted_text.mp3', mimetype='audio/mpeg')
@app.route('/get_suggestion', methods=['GET', 'POST'])
def get_suggestion():
if 'words' not in request.values.keys():
raise InvalidUsage('No words were specified for prediction.',
status_code=400)
text = request.values['words']
prediction = []
if len(text.split(' ')) > 1:
prediction = autocomplete.split_predict(text, 10)
else:
prediction = autocomplete.predict_currword(text, 10)
return jsonify(prediction)
@app.route('/send_text', methods=['GET', 'POST'])
def send_text():
if 'text' not in request.values.keys():
raise InvalidUsage('The text message was not found in the request.',
status_code=400)
if 'to' not in request.values.keys():
raise InvalidUsage('The to-number was not found in the request',
status_code=400)
text = request.values['text']
to_number = request.values['to']
account_sid = 'ACbbd2cff98bcbbad08f76b03701a0f2d9'
auth_token = '7d786ff14c6b4572a6e8e78f8ad6aee5'
client = Client(account_sid, auth_token)
message = client.messages.create(from_='+12267992139', to=to_number,
body=text)
return jsonify({'to': to_number, 'message': message.body, 'error code':
message.error_code})
<|reserved_special_token_1|>
<|reserved_special_token_0|>
autocomplete.load()
app = Flask(__name__)
CORS(app)
@app.route('/')
def index():
return render_template('index.html')
class InvalidUsage(Exception):
status_code = 400
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
@app.route('/convert_text_to_speech', methods=['POST'])
def convert_text_to_speech():
if 'text_to_convert' not in request.values.keys():
raise InvalidUsage('No text included for conversion', status_code=400)
tts = gTTS(text=request.values['text_to_convert'], lang='en')
tts.save('converted_text.mp3')
os.system('start converted_text.mp3')
return send_file('converted_text.mp3', mimetype='audio/mpeg')
@app.route('/get_suggestion', methods=['GET', 'POST'])
def get_suggestion():
if 'words' not in request.values.keys():
raise InvalidUsage('No words were specified for prediction.',
status_code=400)
text = request.values['words']
prediction = []
if len(text.split(' ')) > 1:
prediction = autocomplete.split_predict(text, 10)
else:
prediction = autocomplete.predict_currword(text, 10)
return jsonify(prediction)
@app.route('/send_text', methods=['GET', 'POST'])
def send_text():
if 'text' not in request.values.keys():
raise InvalidUsage('The text message was not found in the request.',
status_code=400)
if 'to' not in request.values.keys():
raise InvalidUsage('The to-number was not found in the request',
status_code=400)
text = request.values['text']
to_number = request.values['to']
account_sid = 'ACbbd2cff98bcbbad08f76b03701a0f2d9'
auth_token = '7d786ff14c6b4572a6e8e78f8ad6aee5'
client = Client(account_sid, auth_token)
message = client.messages.create(from_='+12267992139', to=to_number,
body=text)
return jsonify({'to': to_number, 'message': message.body, 'error code':
message.error_code})
<|reserved_special_token_1|>
from flask import Flask, jsonify, request, send_file, render_template
from flask_cors import CORS
from twilio.rest import Client
import autocomplete
from gtts import gTTS
import os
# Set up the model.
autocomplete.load()
app = Flask(__name__)
CORS(app)
# The application
@app.route("/")
def index():
return render_template("index.html")
# Create a class for custom error messages (reference: http://flask.pocoo.org/docs/0.12/patterns/apierrors/).
class InvalidUsage(Exception):
status_code = 400
# Initialize the InvalidUsage exception.
def __init__(self, message, status_code=None, payload=None):
Exception.__init__(self)
self.message = message
if status_code is not None:
self.status_code = status_code
self.payload = payload
# Convert the exception information into a dictionary.
def to_dict(self):
rv = dict(self.payload or ())
rv['message'] = self.message
return rv
# Register the custom exception with the error handler (reference: http://flask.pocoo.org/docs/0.12/patterns/apierrors/).
@app.errorhandler(InvalidUsage)
def handle_invalid_usage(error):
response = jsonify(error.to_dict())
response.status_code = error.status_code
return response
# Converts English text to speech.
@app.route('/convert_text_to_speech', methods=['POST'])
def convert_text_to_speech():
# Check to see if the required parameters are present.
if 'text_to_convert' not in request.values.keys():
raise InvalidUsage("No text included for conversion", status_code = 400)
# Send the post request.
tts = gTTS(text=request.values['text_to_convert'], lang='en')
tts.save('converted_text.mp3')
os.system('start converted_text.mp3')
# Return the sound file.
return send_file('converted_text.mp3', mimetype='audio/mpeg')
# Get suggestions for words that the user typed in.
@app.route('/get_suggestion', methods=['GET','POST'])
def get_suggestion():
# Raise an exception if the required parameters are not specified.
if "words" not in request.values.keys():
raise InvalidUsage("No words were specified for prediction.", status_code = 400)
# Predict the next word.
text = request.values['words']
prediction = [];
if len(text.split(" ")) > 1:
prediction = autocomplete.split_predict(text, 10)
else:
prediction = autocomplete.predict_currword(text, 10)
return jsonify(prediction)
# Adds text message support to allow Don to send text messages.
@app.route('/send_text', methods=['GET', 'POST'])
def send_text():
# Raise an exception if the required parameters are not specified.
if "text" not in request.values.keys():
raise InvalidUsage("The text message was not found in the request.", status_code = 400)
if "to" not in request.values.keys():
raise InvalidUsage("The to-number was not found in the request", status_code = 400)
# Extract the required information from the request body.
text = request.values['text']
to_number = request.values['to']
# Set up the account credentials - in a production project, this would be placed in a "secrets" file.
account_sid = "ACbbd2cff98bcbbad08f76b03701a0f2d9"
auth_token = "7d786ff14c6b4572a6e8e78f8ad6aee5"
# Send the text message.
client = Client(account_sid, auth_token)
message = client.messages.create(
from_="+12267992139",
to=to_number,
body=text)
return jsonify({"to":to_number, "message":message.body, "error code":message.error_code})
|
flexible
|
{
"blob_id": "8980ac4db2657d3dbd2b70b33a4d13a077d4590e",
"index": 2266,
"step-1": "<mask token>\n\n\nclass InvalidUsage(Exception):\n status_code = 400\n\n def __init__(self, message, status_code=None, payload=None):\n Exception.__init__(self)\n self.message = message\n if status_code is not None:\n self.status_code = status_code\n self.payload = payload\n\n def to_dict(self):\n rv = dict(self.payload or ())\n rv['message'] = self.message\n return rv\n\n\n@app.errorhandler(InvalidUsage)\ndef handle_invalid_usage(error):\n response = jsonify(error.to_dict())\n response.status_code = error.status_code\n return response\n\n\n<mask token>\n\n\n@app.route('/get_suggestion', methods=['GET', 'POST'])\ndef get_suggestion():\n if 'words' not in request.values.keys():\n raise InvalidUsage('No words were specified for prediction.',\n status_code=400)\n text = request.values['words']\n prediction = []\n if len(text.split(' ')) > 1:\n prediction = autocomplete.split_predict(text, 10)\n else:\n prediction = autocomplete.predict_currword(text, 10)\n return jsonify(prediction)\n\n\n@app.route('/send_text', methods=['GET', 'POST'])\ndef send_text():\n if 'text' not in request.values.keys():\n raise InvalidUsage('The text message was not found in the request.',\n status_code=400)\n if 'to' not in request.values.keys():\n raise InvalidUsage('The to-number was not found in the request',\n status_code=400)\n text = request.values['text']\n to_number = request.values['to']\n account_sid = 'ACbbd2cff98bcbbad08f76b03701a0f2d9'\n auth_token = '7d786ff14c6b4572a6e8e78f8ad6aee5'\n client = Client(account_sid, auth_token)\n message = client.messages.create(from_='+12267992139', to=to_number,\n body=text)\n return jsonify({'to': to_number, 'message': message.body, 'error code':\n message.error_code})\n",
"step-2": "<mask token>\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\nclass InvalidUsage(Exception):\n status_code = 400\n\n def __init__(self, message, status_code=None, payload=None):\n Exception.__init__(self)\n self.message = message\n if status_code is not None:\n self.status_code = status_code\n self.payload = payload\n\n def to_dict(self):\n rv = dict(self.payload or ())\n rv['message'] = self.message\n return rv\n\n\n@app.errorhandler(InvalidUsage)\ndef handle_invalid_usage(error):\n response = jsonify(error.to_dict())\n response.status_code = error.status_code\n return response\n\n\n@app.route('/convert_text_to_speech', methods=['POST'])\ndef convert_text_to_speech():\n if 'text_to_convert' not in request.values.keys():\n raise InvalidUsage('No text included for conversion', status_code=400)\n tts = gTTS(text=request.values['text_to_convert'], lang='en')\n tts.save('converted_text.mp3')\n os.system('start converted_text.mp3')\n return send_file('converted_text.mp3', mimetype='audio/mpeg')\n\n\n@app.route('/get_suggestion', methods=['GET', 'POST'])\ndef get_suggestion():\n if 'words' not in request.values.keys():\n raise InvalidUsage('No words were specified for prediction.',\n status_code=400)\n text = request.values['words']\n prediction = []\n if len(text.split(' ')) > 1:\n prediction = autocomplete.split_predict(text, 10)\n else:\n prediction = autocomplete.predict_currword(text, 10)\n return jsonify(prediction)\n\n\n@app.route('/send_text', methods=['GET', 'POST'])\ndef send_text():\n if 'text' not in request.values.keys():\n raise InvalidUsage('The text message was not found in the request.',\n status_code=400)\n if 'to' not in request.values.keys():\n raise InvalidUsage('The to-number was not found in the request',\n status_code=400)\n text = request.values['text']\n to_number = request.values['to']\n account_sid = 'ACbbd2cff98bcbbad08f76b03701a0f2d9'\n auth_token = '7d786ff14c6b4572a6e8e78f8ad6aee5'\n client = Client(account_sid, auth_token)\n message = client.messages.create(from_='+12267992139', to=to_number,\n body=text)\n return jsonify({'to': to_number, 'message': message.body, 'error code':\n message.error_code})\n",
"step-3": "<mask token>\nautocomplete.load()\n<mask token>\nCORS(app)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\nclass InvalidUsage(Exception):\n status_code = 400\n\n def __init__(self, message, status_code=None, payload=None):\n Exception.__init__(self)\n self.message = message\n if status_code is not None:\n self.status_code = status_code\n self.payload = payload\n\n def to_dict(self):\n rv = dict(self.payload or ())\n rv['message'] = self.message\n return rv\n\n\n@app.errorhandler(InvalidUsage)\ndef handle_invalid_usage(error):\n response = jsonify(error.to_dict())\n response.status_code = error.status_code\n return response\n\n\n@app.route('/convert_text_to_speech', methods=['POST'])\ndef convert_text_to_speech():\n if 'text_to_convert' not in request.values.keys():\n raise InvalidUsage('No text included for conversion', status_code=400)\n tts = gTTS(text=request.values['text_to_convert'], lang='en')\n tts.save('converted_text.mp3')\n os.system('start converted_text.mp3')\n return send_file('converted_text.mp3', mimetype='audio/mpeg')\n\n\n@app.route('/get_suggestion', methods=['GET', 'POST'])\ndef get_suggestion():\n if 'words' not in request.values.keys():\n raise InvalidUsage('No words were specified for prediction.',\n status_code=400)\n text = request.values['words']\n prediction = []\n if len(text.split(' ')) > 1:\n prediction = autocomplete.split_predict(text, 10)\n else:\n prediction = autocomplete.predict_currword(text, 10)\n return jsonify(prediction)\n\n\n@app.route('/send_text', methods=['GET', 'POST'])\ndef send_text():\n if 'text' not in request.values.keys():\n raise InvalidUsage('The text message was not found in the request.',\n status_code=400)\n if 'to' not in request.values.keys():\n raise InvalidUsage('The to-number was not found in the request',\n status_code=400)\n text = request.values['text']\n to_number = request.values['to']\n account_sid = 'ACbbd2cff98bcbbad08f76b03701a0f2d9'\n auth_token = '7d786ff14c6b4572a6e8e78f8ad6aee5'\n client = Client(account_sid, auth_token)\n message = client.messages.create(from_='+12267992139', to=to_number,\n body=text)\n return jsonify({'to': to_number, 'message': message.body, 'error code':\n message.error_code})\n",
"step-4": "<mask token>\nautocomplete.load()\napp = Flask(__name__)\nCORS(app)\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\nclass InvalidUsage(Exception):\n status_code = 400\n\n def __init__(self, message, status_code=None, payload=None):\n Exception.__init__(self)\n self.message = message\n if status_code is not None:\n self.status_code = status_code\n self.payload = payload\n\n def to_dict(self):\n rv = dict(self.payload or ())\n rv['message'] = self.message\n return rv\n\n\n@app.errorhandler(InvalidUsage)\ndef handle_invalid_usage(error):\n response = jsonify(error.to_dict())\n response.status_code = error.status_code\n return response\n\n\n@app.route('/convert_text_to_speech', methods=['POST'])\ndef convert_text_to_speech():\n if 'text_to_convert' not in request.values.keys():\n raise InvalidUsage('No text included for conversion', status_code=400)\n tts = gTTS(text=request.values['text_to_convert'], lang='en')\n tts.save('converted_text.mp3')\n os.system('start converted_text.mp3')\n return send_file('converted_text.mp3', mimetype='audio/mpeg')\n\n\n@app.route('/get_suggestion', methods=['GET', 'POST'])\ndef get_suggestion():\n if 'words' not in request.values.keys():\n raise InvalidUsage('No words were specified for prediction.',\n status_code=400)\n text = request.values['words']\n prediction = []\n if len(text.split(' ')) > 1:\n prediction = autocomplete.split_predict(text, 10)\n else:\n prediction = autocomplete.predict_currword(text, 10)\n return jsonify(prediction)\n\n\n@app.route('/send_text', methods=['GET', 'POST'])\ndef send_text():\n if 'text' not in request.values.keys():\n raise InvalidUsage('The text message was not found in the request.',\n status_code=400)\n if 'to' not in request.values.keys():\n raise InvalidUsage('The to-number was not found in the request',\n status_code=400)\n text = request.values['text']\n to_number = request.values['to']\n account_sid = 'ACbbd2cff98bcbbad08f76b03701a0f2d9'\n auth_token = '7d786ff14c6b4572a6e8e78f8ad6aee5'\n client = Client(account_sid, auth_token)\n message = client.messages.create(from_='+12267992139', to=to_number,\n body=text)\n return jsonify({'to': to_number, 'message': message.body, 'error code':\n message.error_code})\n",
"step-5": "from flask import Flask, jsonify, request, send_file, render_template\nfrom flask_cors import CORS\nfrom twilio.rest import Client\nimport autocomplete\nfrom gtts import gTTS\nimport os\n\n# Set up the model.\nautocomplete.load()\napp = Flask(__name__)\nCORS(app)\n\n# The application\n@app.route(\"/\")\ndef index():\n\treturn render_template(\"index.html\")\n\n# Create a class for custom error messages (reference: http://flask.pocoo.org/docs/0.12/patterns/apierrors/).\nclass InvalidUsage(Exception):\n\tstatus_code = 400\n\n\t# Initialize the InvalidUsage exception.\n\tdef __init__(self, message, status_code=None, payload=None):\n\t\tException.__init__(self)\n\t\tself.message = message\n\t\tif status_code is not None:\n\t\t\tself.status_code = status_code\n\t\tself.payload = payload\n\n\t# Convert the exception information into a dictionary.\n\tdef to_dict(self):\n\t\trv = dict(self.payload or ())\n\t\trv['message'] = self.message\n\t\treturn rv\n\n# Register the custom exception with the error handler (reference: http://flask.pocoo.org/docs/0.12/patterns/apierrors/).\n@app.errorhandler(InvalidUsage)\ndef handle_invalid_usage(error):\n\tresponse = jsonify(error.to_dict())\n\tresponse.status_code = error.status_code\n\treturn response\n\n# Converts English text to speech.\n@app.route('/convert_text_to_speech', methods=['POST'])\ndef convert_text_to_speech():\n\t# Check to see if the required parameters are present.\n\tif 'text_to_convert' not in request.values.keys():\n\t\traise InvalidUsage(\"No text included for conversion\", status_code = 400)\n\t\t\n\t# Send the post request.\n\ttts = gTTS(text=request.values['text_to_convert'], lang='en')\n\ttts.save('converted_text.mp3')\n\tos.system('start converted_text.mp3')\n\t\n\t# Return the sound file.\n\treturn send_file('converted_text.mp3', mimetype='audio/mpeg')\n\n# Get suggestions for words that the user typed in.\n@app.route('/get_suggestion', methods=['GET','POST'])\ndef get_suggestion():\n\t# Raise an exception if the required parameters are not specified.\n\tif \"words\" not in request.values.keys():\n\t\traise InvalidUsage(\"No words were specified for prediction.\", status_code = 400)\n\t\n\t# Predict the next word.\n\ttext = request.values['words']\n\tprediction = [];\n\tif len(text.split(\" \")) > 1:\n\t\tprediction = autocomplete.split_predict(text, 10)\n\telse:\n\t\tprediction = autocomplete.predict_currword(text, 10)\n\t\t\n\treturn jsonify(prediction)\n\t\n# Adds text message support to allow Don to send text messages.\n@app.route('/send_text', methods=['GET', 'POST'])\ndef send_text():\n\t# Raise an exception if the required parameters are not specified.\n\tif \"text\" not in request.values.keys():\n\t\traise InvalidUsage(\"The text message was not found in the request.\", status_code = 400)\n\tif \"to\" not in request.values.keys():\n\t\traise InvalidUsage(\"The to-number was not found in the request\", status_code = 400)\n\t\n\t# Extract the required information from the request body.\n\ttext = request.values['text']\n\tto_number = request.values['to']\n\t\n\t# Set up the account credentials - in a production project, this would be placed in a \"secrets\" file.\n\taccount_sid = \"ACbbd2cff98bcbbad08f76b03701a0f2d9\"\n\tauth_token = \"7d786ff14c6b4572a6e8e78f8ad6aee5\"\n\t\n\t# Send the text message.\n\tclient = Client(account_sid, auth_token)\n\tmessage = client.messages.create(\n\t\tfrom_=\"+12267992139\",\n\t\tto=to_number,\n\t\tbody=text)\n\n\treturn jsonify({\"to\":to_number, \"message\":message.body, \"error code\":message.error_code})\n\t",
"step-ids": [
7,
9,
10,
11,
13
]
}
|
[
7,
9,
10,
11,
13
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
import brainlit.algorithms.generate_fragments
from brainlit.algorithms.generate_fragments import *
|
flexible
|
{
"blob_id": "a52743fc911beb7e51644073131b25c177d4ad29",
"index": 852,
"step-1": "<mask token>\n",
"step-2": "import brainlit.algorithms.generate_fragments\nfrom brainlit.algorithms.generate_fragments import *\n",
"step-3": null,
"step-4": null,
"step-5": null,
"step-ids": [
0,
1
]
}
|
[
0,
1
] |
<|reserved_special_token_0|>
def convolve(image, fltr):
r_p = 0
c_p = 0
conv_list = []
while r_p + 1 <= image.shape[0] - 1:
while c_p + 1 <= image.shape[1] - 1:
x = np.sum(np.multiply(image[r_p:r_p + 2, c_p:c_p + 2], fltr))
conv_list.append(x)
c_p += 1
r_p += 1
c_p = 0
return conv_list
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
print('Num GPUs Available: ', len(tf.config.experimental.
list_physical_devices('GPU')))
<|reserved_special_token_0|>
plt.imshow(train_X[7], cmap='binary')
def convolve(image, fltr):
r_p = 0
c_p = 0
conv_list = []
while r_p + 1 <= image.shape[0] - 1:
while c_p + 1 <= image.shape[1] - 1:
x = np.sum(np.multiply(image[r_p:r_p + 2, c_p:c_p + 2], fltr))
conv_list.append(x)
c_p += 1
r_p += 1
c_p = 0
return conv_list
<|reserved_special_token_0|>
plt.imshow(img_matrix, cmap='gray')
plt.show()
plt.imshow(conv, cmap='gray')
plt.show()
with tf.device('GPU:0'):
model = keras.Sequential([keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(2560, activation='relu'), keras.layers.Dense(
2560, activation='relu'), keras.layers.Dense(10, activation='softmax')]
)
print(model.summary())
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
import time
tic = time.time()
from warnings import filterwarnings
filterwarnings
model.fit(train_X, train_y, batch_size=1024, epochs=3)
toc = time.time()
print('time : {:0.1f} sec '.format(toc - tic))
<|reserved_special_token_0|>
print('trin_accuracy : {}'.format(train_accuracy))
print('test_accuracy : {}'.format(test_accuracy))
<|reserved_special_token_0|>
plt.imshow(test_X[26], cmap='binary')
plt.title(class_names[test_y[26]])
<|reserved_special_token_1|>
<|reserved_special_token_0|>
print('Num GPUs Available: ', len(tf.config.experimental.
list_physical_devices('GPU')))
<|reserved_special_token_0|>
data = keras.datasets.fashion_mnist
(train_X, train_y), (test_X, test_y) = data.load_data()
class_names = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal',
'shirt', 'sneaker', 'bag', 'ankle boot']
train_X = train_X / 255
test_X = test_X / 255
plt.imshow(train_X[7], cmap='binary')
def convolve(image, fltr):
r_p = 0
c_p = 0
conv_list = []
while r_p + 1 <= image.shape[0] - 1:
while c_p + 1 <= image.shape[1] - 1:
x = np.sum(np.multiply(image[r_p:r_p + 2, c_p:c_p + 2], fltr))
conv_list.append(x)
c_p += 1
r_p += 1
c_p = 0
return conv_list
img_matrix = np.array(train.iloc[6, 1:]).reshape(28, 28)
flt = np.matrix([[1, 1], [0, 0]])
conv = np.array(convolve(img_matrix, flt)).reshape(27, 27)
plt.imshow(img_matrix, cmap='gray')
plt.show()
plt.imshow(conv, cmap='gray')
plt.show()
with tf.device('GPU:0'):
model = keras.Sequential([keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(2560, activation='relu'), keras.layers.Dense(
2560, activation='relu'), keras.layers.Dense(10, activation='softmax')]
)
print(model.summary())
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
import time
tic = time.time()
from warnings import filterwarnings
filterwarnings
model.fit(train_X, train_y, batch_size=1024, epochs=3)
toc = time.time()
print('time : {:0.1f} sec '.format(toc - tic))
train_loss, train_accuracy = model.evaluate(train_X, train_y, verbose=False)
test_loss, test_accuracy = model.evaluate(test_X, test_y, verbose=False)
print('trin_accuracy : {}'.format(train_accuracy))
print('test_accuracy : {}'.format(test_accuracy))
predictions = model.predict(test_X)
plt.imshow(test_X[26], cmap='binary')
plt.title(class_names[test_y[26]])
<|reserved_special_token_1|>
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
print('Num GPUs Available: ', len(tf.config.experimental.
list_physical_devices('GPU')))
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow import keras
data = keras.datasets.fashion_mnist
(train_X, train_y), (test_X, test_y) = data.load_data()
class_names = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal',
'shirt', 'sneaker', 'bag', 'ankle boot']
train_X = train_X / 255
test_X = test_X / 255
plt.imshow(train_X[7], cmap='binary')
def convolve(image, fltr):
r_p = 0
c_p = 0
conv_list = []
while r_p + 1 <= image.shape[0] - 1:
while c_p + 1 <= image.shape[1] - 1:
x = np.sum(np.multiply(image[r_p:r_p + 2, c_p:c_p + 2], fltr))
conv_list.append(x)
c_p += 1
r_p += 1
c_p = 0
return conv_list
img_matrix = np.array(train.iloc[6, 1:]).reshape(28, 28)
flt = np.matrix([[1, 1], [0, 0]])
conv = np.array(convolve(img_matrix, flt)).reshape(27, 27)
plt.imshow(img_matrix, cmap='gray')
plt.show()
plt.imshow(conv, cmap='gray')
plt.show()
with tf.device('GPU:0'):
model = keras.Sequential([keras.layers.Flatten(input_shape=(28, 28)),
keras.layers.Dense(2560, activation='relu'), keras.layers.Dense(
2560, activation='relu'), keras.layers.Dense(10, activation='softmax')]
)
print(model.summary())
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
import time
tic = time.time()
from warnings import filterwarnings
filterwarnings
model.fit(train_X, train_y, batch_size=1024, epochs=3)
toc = time.time()
print('time : {:0.1f} sec '.format(toc - tic))
train_loss, train_accuracy = model.evaluate(train_X, train_y, verbose=False)
test_loss, test_accuracy = model.evaluate(test_X, test_y, verbose=False)
print('trin_accuracy : {}'.format(train_accuracy))
print('test_accuracy : {}'.format(test_accuracy))
predictions = model.predict(test_X)
plt.imshow(test_X[26], cmap='binary')
plt.title(class_names[test_y[26]])
<|reserved_special_token_1|>
#!/usr/bin/env python
# coding: utf-8
# In[2]:
from __future__ import absolute_import, division, print_function, unicode_literals
import tensorflow as tf
print("Num GPUs Available: ", len(tf.config.experimental.list_physical_devices('GPU')))
# In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
#tf.config.allow_growth = True
#config.gpu_options.allow_growth = True
#session = tf.Session(config=config....)
from tensorflow import keras
# In[5]:
data = keras.datasets.fashion_mnist
(train_X, train_y), (test_X,test_y) = data.load_data()
class_names = ['t-shirt', 'trouser', 'pullover', 'dress'
,'coat', 'sandal', 'shirt', 'sneaker'
, 'bag', 'ankle boot']
train_X = train_X/255
test_X = test_X/255
# In[7]:
plt.imshow(train_X[7], cmap= 'binary')
# In[ ]:
def convolve(image,fltr):
r_p = 0
c_p = 0
conv_list = []
while (r_p+1) <= image.shape[0]-1 :
while (c_p+1) <= image.shape[1]-1 :
x = np.sum(np.multiply(image[r_p : r_p+2 , c_p : c_p+2],fltr))
conv_list.append(x)
c_p += 1
r_p += 1
c_p = 0
return conv_list
img_matrix = np.array(train.iloc[6,1:]).reshape(28,28)
flt = np.matrix([[1,1],[0,0]])
conv = np.array(convolve(img_matrix,flt)).reshape(27,27)
plt.imshow(img_matrix, cmap='gray')
plt.show()
plt.imshow(conv, cmap='gray')
plt.show()
# In[33]:
with tf.device('GPU:0'):
model = keras.Sequential([
#keras.layers.Conv2D(filters=32 ,kernel_size=3, activation='relu',input_shape=(28,28,1)),
keras.layers.Flatten(input_shape=(28,28)),
#keras.layers.Dense(128, activation='relu'),
keras.layers.Dense(2560, activation='relu'),
keras.layers.Dense(2560, activation='relu'),
#keras.layers.Dense(2560, activation='relu'),
keras.layers.Dense(10, activation='softmax')
])
print(model.summary())
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
import time
tic = time.time()
from warnings import filterwarnings
filterwarnings
model.fit(train_X, train_y,batch_size=1024, epochs=3)
toc = time.time()
print('time : {:0.1f} sec '.format(toc-tic))
# In[72]:
#predictions
train_loss, train_accuracy = model.evaluate(train_X, train_y,verbose=False )
test_loss, test_accuracy = model.evaluate(test_X, test_y, verbose = False )
# In[73]:
print('trin_accuracy : {}'.format(train_accuracy))
print('test_accuracy : {}'.format(test_accuracy))
# In[74]:
predictions = model.predict(test_X)
# In[76]:
plt.imshow(test_X[26], cmap='binary')
plt.title(class_names[test_y[26]])
|
flexible
|
{
"blob_id": "aea92827753e12d2dc95d63ddd0fe4eb8ced5d14",
"index": 3815,
"step-1": "<mask token>\n\n\ndef convolve(image, fltr):\n r_p = 0\n c_p = 0\n conv_list = []\n while r_p + 1 <= image.shape[0] - 1:\n while c_p + 1 <= image.shape[1] - 1:\n x = np.sum(np.multiply(image[r_p:r_p + 2, c_p:c_p + 2], fltr))\n conv_list.append(x)\n c_p += 1\n r_p += 1\n c_p = 0\n return conv_list\n\n\n<mask token>\n",
"step-2": "<mask token>\nprint('Num GPUs Available: ', len(tf.config.experimental.\n list_physical_devices('GPU')))\n<mask token>\nplt.imshow(train_X[7], cmap='binary')\n\n\ndef convolve(image, fltr):\n r_p = 0\n c_p = 0\n conv_list = []\n while r_p + 1 <= image.shape[0] - 1:\n while c_p + 1 <= image.shape[1] - 1:\n x = np.sum(np.multiply(image[r_p:r_p + 2, c_p:c_p + 2], fltr))\n conv_list.append(x)\n c_p += 1\n r_p += 1\n c_p = 0\n return conv_list\n\n\n<mask token>\nplt.imshow(img_matrix, cmap='gray')\nplt.show()\nplt.imshow(conv, cmap='gray')\nplt.show()\nwith tf.device('GPU:0'):\n model = keras.Sequential([keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(2560, activation='relu'), keras.layers.Dense(\n 2560, activation='relu'), keras.layers.Dense(10, activation='softmax')]\n )\n print(model.summary())\n model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n import time\n tic = time.time()\n from warnings import filterwarnings\n filterwarnings\n model.fit(train_X, train_y, batch_size=1024, epochs=3)\n toc = time.time()\n print('time : {:0.1f} sec '.format(toc - tic))\n<mask token>\nprint('trin_accuracy : {}'.format(train_accuracy))\nprint('test_accuracy : {}'.format(test_accuracy))\n<mask token>\nplt.imshow(test_X[26], cmap='binary')\nplt.title(class_names[test_y[26]])\n",
"step-3": "<mask token>\nprint('Num GPUs Available: ', len(tf.config.experimental.\n list_physical_devices('GPU')))\n<mask token>\ndata = keras.datasets.fashion_mnist\n(train_X, train_y), (test_X, test_y) = data.load_data()\nclass_names = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal',\n 'shirt', 'sneaker', 'bag', 'ankle boot']\ntrain_X = train_X / 255\ntest_X = test_X / 255\nplt.imshow(train_X[7], cmap='binary')\n\n\ndef convolve(image, fltr):\n r_p = 0\n c_p = 0\n conv_list = []\n while r_p + 1 <= image.shape[0] - 1:\n while c_p + 1 <= image.shape[1] - 1:\n x = np.sum(np.multiply(image[r_p:r_p + 2, c_p:c_p + 2], fltr))\n conv_list.append(x)\n c_p += 1\n r_p += 1\n c_p = 0\n return conv_list\n\n\nimg_matrix = np.array(train.iloc[6, 1:]).reshape(28, 28)\nflt = np.matrix([[1, 1], [0, 0]])\nconv = np.array(convolve(img_matrix, flt)).reshape(27, 27)\nplt.imshow(img_matrix, cmap='gray')\nplt.show()\nplt.imshow(conv, cmap='gray')\nplt.show()\nwith tf.device('GPU:0'):\n model = keras.Sequential([keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(2560, activation='relu'), keras.layers.Dense(\n 2560, activation='relu'), keras.layers.Dense(10, activation='softmax')]\n )\n print(model.summary())\n model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n import time\n tic = time.time()\n from warnings import filterwarnings\n filterwarnings\n model.fit(train_X, train_y, batch_size=1024, epochs=3)\n toc = time.time()\n print('time : {:0.1f} sec '.format(toc - tic))\ntrain_loss, train_accuracy = model.evaluate(train_X, train_y, verbose=False)\ntest_loss, test_accuracy = model.evaluate(test_X, test_y, verbose=False)\nprint('trin_accuracy : {}'.format(train_accuracy))\nprint('test_accuracy : {}'.format(test_accuracy))\npredictions = model.predict(test_X)\nplt.imshow(test_X[26], cmap='binary')\nplt.title(class_names[test_y[26]])\n",
"step-4": "from __future__ import absolute_import, division, print_function, unicode_literals\nimport tensorflow as tf\nprint('Num GPUs Available: ', len(tf.config.experimental.\n list_physical_devices('GPU')))\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow import keras\ndata = keras.datasets.fashion_mnist\n(train_X, train_y), (test_X, test_y) = data.load_data()\nclass_names = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal',\n 'shirt', 'sneaker', 'bag', 'ankle boot']\ntrain_X = train_X / 255\ntest_X = test_X / 255\nplt.imshow(train_X[7], cmap='binary')\n\n\ndef convolve(image, fltr):\n r_p = 0\n c_p = 0\n conv_list = []\n while r_p + 1 <= image.shape[0] - 1:\n while c_p + 1 <= image.shape[1] - 1:\n x = np.sum(np.multiply(image[r_p:r_p + 2, c_p:c_p + 2], fltr))\n conv_list.append(x)\n c_p += 1\n r_p += 1\n c_p = 0\n return conv_list\n\n\nimg_matrix = np.array(train.iloc[6, 1:]).reshape(28, 28)\nflt = np.matrix([[1, 1], [0, 0]])\nconv = np.array(convolve(img_matrix, flt)).reshape(27, 27)\nplt.imshow(img_matrix, cmap='gray')\nplt.show()\nplt.imshow(conv, cmap='gray')\nplt.show()\nwith tf.device('GPU:0'):\n model = keras.Sequential([keras.layers.Flatten(input_shape=(28, 28)),\n keras.layers.Dense(2560, activation='relu'), keras.layers.Dense(\n 2560, activation='relu'), keras.layers.Dense(10, activation='softmax')]\n )\n print(model.summary())\n model.compile(optimizer='adam', loss='sparse_categorical_crossentropy',\n metrics=['accuracy'])\n import time\n tic = time.time()\n from warnings import filterwarnings\n filterwarnings\n model.fit(train_X, train_y, batch_size=1024, epochs=3)\n toc = time.time()\n print('time : {:0.1f} sec '.format(toc - tic))\ntrain_loss, train_accuracy = model.evaluate(train_X, train_y, verbose=False)\ntest_loss, test_accuracy = model.evaluate(test_X, test_y, verbose=False)\nprint('trin_accuracy : {}'.format(train_accuracy))\nprint('test_accuracy : {}'.format(test_accuracy))\npredictions = model.predict(test_X)\nplt.imshow(test_X[26], cmap='binary')\nplt.title(class_names[test_y[26]])\n",
"step-5": "#!/usr/bin/env python\n# coding: utf-8\n\n# In[2]:\n\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport tensorflow as tf\nprint(\"Num GPUs Available: \", len(tf.config.experimental.list_physical_devices('GPU')))\n\n\n# In[1]:\n\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n#tf.config.allow_growth = True\n#config.gpu_options.allow_growth = True\n#session = tf.Session(config=config....)\nfrom tensorflow import keras\n\n\n# In[5]:\n\n\ndata = keras.datasets.fashion_mnist\n\n(train_X, train_y), (test_X,test_y) = data.load_data()\n\nclass_names = ['t-shirt', 'trouser', 'pullover', 'dress'\n ,'coat', 'sandal', 'shirt', 'sneaker'\n , 'bag', 'ankle boot']\n\ntrain_X = train_X/255\ntest_X = test_X/255\n\n\n# In[7]:\n\n\nplt.imshow(train_X[7], cmap= 'binary')\n\n\n# In[ ]:\n\n\ndef convolve(image,fltr):\n r_p = 0\n c_p = 0\n conv_list = []\n while (r_p+1) <= image.shape[0]-1 :\n while (c_p+1) <= image.shape[1]-1 :\n x = np.sum(np.multiply(image[r_p : r_p+2 , c_p : c_p+2],fltr))\n conv_list.append(x)\n c_p += 1\n r_p += 1\n c_p = 0\n return conv_list\nimg_matrix = np.array(train.iloc[6,1:]).reshape(28,28)\nflt = np.matrix([[1,1],[0,0]])\nconv = np.array(convolve(img_matrix,flt)).reshape(27,27)\nplt.imshow(img_matrix, cmap='gray')\nplt.show()\nplt.imshow(conv, cmap='gray')\nplt.show()\n\n\n# In[33]:\n\n\nwith tf.device('GPU:0'):\n model = keras.Sequential([ \n #keras.layers.Conv2D(filters=32 ,kernel_size=3, activation='relu',input_shape=(28,28,1)),\n keras.layers.Flatten(input_shape=(28,28)),\n #keras.layers.Dense(128, activation='relu'),\n keras.layers.Dense(2560, activation='relu'),\n keras.layers.Dense(2560, activation='relu'),\n #keras.layers.Dense(2560, activation='relu'),\n keras.layers.Dense(10, activation='softmax')\n ])\n print(model.summary())\n model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n\n import time\n tic = time.time()\n from warnings import filterwarnings\n filterwarnings\n model.fit(train_X, train_y,batch_size=1024, epochs=3)\n toc = time.time()\n print('time : {:0.1f} sec '.format(toc-tic))\n\n\n# In[72]:\n\n\n#predictions\ntrain_loss, train_accuracy = model.evaluate(train_X, train_y,verbose=False )\ntest_loss, test_accuracy = model.evaluate(test_X, test_y, verbose = False )\n\n\n# In[73]:\n\n\nprint('trin_accuracy : {}'.format(train_accuracy))\nprint('test_accuracy : {}'.format(test_accuracy))\n\n\n# In[74]:\n\n\npredictions = model.predict(test_X)\n\n\n# In[76]:\n\n\nplt.imshow(test_X[26], cmap='binary')\nplt.title(class_names[test_y[26]])\n\n",
"step-ids": [
1,
2,
3,
4,
5
]
}
|
[
1,
2,
3,
4,
5
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Migration(migrations.Migration):
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
class Migration(migrations.Migration):
dependencies = [('articals', '0001_initial')]
operations = [migrations.AddField(model_name='artical', name='thumb',
field=models.ImageField(blank=True, default='default.png',
upload_to='media/'))]
<|reserved_special_token_1|>
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [('articals', '0001_initial')]
operations = [migrations.AddField(model_name='artical', name='thumb',
field=models.ImageField(blank=True, default='default.png',
upload_to='media/'))]
<|reserved_special_token_1|>
# Generated by Django 3.1.1 on 2020-10-07 04:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('articals', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='artical',
name='thumb',
field=models.ImageField(blank=True, default='default.png', upload_to='media/'),
),
]
|
flexible
|
{
"blob_id": "d69bffb85d81ab3969bfe7dfe2759fa809890208",
"index": 503,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\nclass Migration(migrations.Migration):\n <mask token>\n <mask token>\n",
"step-3": "<mask token>\n\n\nclass Migration(migrations.Migration):\n dependencies = [('articals', '0001_initial')]\n operations = [migrations.AddField(model_name='artical', name='thumb',\n field=models.ImageField(blank=True, default='default.png',\n upload_to='media/'))]\n",
"step-4": "from django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n dependencies = [('articals', '0001_initial')]\n operations = [migrations.AddField(model_name='artical', name='thumb',\n field=models.ImageField(blank=True, default='default.png',\n upload_to='media/'))]\n",
"step-5": "# Generated by Django 3.1.1 on 2020-10-07 04:04\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('articals', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='artical',\n name='thumb',\n field=models.ImageField(blank=True, default='default.png', upload_to='media/'),\n ),\n ]\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def ratio(area, width, height):
ratio = float(width) / float(height)
if ratio < 1:
ratio = 1 / ratio
if (area < 1063.62 or area > 73862.5) or (ratio < 3 or ratio > 6):
return False
return True
<|reserved_special_token_0|>
<|reserved_special_token_1|>
<|reserved_special_token_0|>
def ratio(area, width, height):
ratio = float(width) / float(height)
if ratio < 1:
ratio = 1 / ratio
if (area < 1063.62 or area > 73862.5) or (ratio < 3 or ratio > 6):
return False
return True
def max_White(plates):
avg = np.mean(plates)
if avg >= 115:
return True
else:
return False
<|reserved_special_token_1|>
import numpy as np
import cv2
from PIL import Image
import pytesseract as tess
def ratio(area, width, height):
ratio = float(width) / float(height)
if ratio < 1:
ratio = 1 / ratio
if (area < 1063.62 or area > 73862.5) or (ratio < 3 or ratio > 6):
return False
return True
def max_White(plates):
avg = np.mean(plates)
if avg >= 115:
return True
else:
return False
<|reserved_special_token_1|>
import numpy as np
import cv2
from PIL import Image
import pytesseract as tess
#Function to check the area range and width-height ratio
def ratio(area, width,height):
ratio = float(width)/float(height)
if ratio < 1:
ratio = 1/ ratio
if (area<1063.62 or area> 73862.5) or (ratio<3 or ratio> 6):
return False
return True
#Average of image matrix
def max_White(plates):
avg= np.mean(plates)
if(avg >= 115):
return True
else:
return False
|
flexible
|
{
"blob_id": "ab610af97d2b31575ea496b8fddda693353da8eb",
"index": 2870,
"step-1": "<mask token>\n",
"step-2": "<mask token>\n\n\ndef ratio(area, width, height):\n ratio = float(width) / float(height)\n if ratio < 1:\n ratio = 1 / ratio\n if (area < 1063.62 or area > 73862.5) or (ratio < 3 or ratio > 6):\n return False\n return True\n\n\n<mask token>\n",
"step-3": "<mask token>\n\n\ndef ratio(area, width, height):\n ratio = float(width) / float(height)\n if ratio < 1:\n ratio = 1 / ratio\n if (area < 1063.62 or area > 73862.5) or (ratio < 3 or ratio > 6):\n return False\n return True\n\n\ndef max_White(plates):\n avg = np.mean(plates)\n if avg >= 115:\n return True\n else:\n return False\n",
"step-4": "import numpy as np\nimport cv2\nfrom PIL import Image\nimport pytesseract as tess\n\n\ndef ratio(area, width, height):\n ratio = float(width) / float(height)\n if ratio < 1:\n ratio = 1 / ratio\n if (area < 1063.62 or area > 73862.5) or (ratio < 3 or ratio > 6):\n return False\n return True\n\n\ndef max_White(plates):\n avg = np.mean(plates)\n if avg >= 115:\n return True\n else:\n return False\n",
"step-5": "import numpy as np \nimport cv2\nfrom PIL import Image\nimport pytesseract as tess \n\n\n\n#Function to check the area range and width-height ratio\n\ndef ratio(area, width,height):\n\tratio = float(width)/float(height)\n\tif ratio < 1:\n\t\tratio = 1/ ratio\n\tif (area<1063.62 or area> 73862.5) or (ratio<3 or ratio> 6):\n\t\treturn False\n\treturn True\n\n#Average of image matrix\n\ndef max_White(plates):\n\n\tavg= np.mean(plates)\n\tif(avg >= 115):\n\t\treturn True\n\telse:\n\t\treturn False\n\n\n\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
while True:
print('running')
<|reserved_special_token_1|>
while True:
print("running")
|
flexible
|
{
"blob_id": "8917481957ecd4c9692cfa93df0b759feaa344af",
"index": 4944,
"step-1": "<mask token>\n",
"step-2": "while True:\n print('running')\n",
"step-3": "while True:\n print(\"running\")\n",
"step-4": null,
"step-5": null,
"step-ids": [
0,
1,
2
]
}
|
[
0,
1,
2
] |
<|reserved_special_token_0|>
<|reserved_special_token_1|>
class Solution:
<|reserved_special_token_0|>
<|reserved_special_token_0|>
<|reserved_special_token_1|>
class Solution:
<|reserved_special_token_0|>
def longestSubstring(self, s: str, k: int) ->int:
def helper(s, k):
if len(s) < k:
return 0
ch = min(set(s), key=s.count)
if s.count(ch) >= k:
return len(s)
else:
return max(helper(t, k) for t in s.split(ch))
return helper(s, k)
<|reserved_special_token_1|>
class Solution:
"""
先遍历整个string,并记录最小的character的出现次数。
如果最小character出现次数都不小于k,那么说明整个string就是满足条件的longest substring,返回原string的长度即可;
如果character的出现次数小于k,假设这个character是c,因为满足条件的substring永远不会包含c,所以满足条件的substring一定是在以c为分割参考下的某个substring中。所以我们需要做的就是把c当做是split的参考,在得到的String[]中再次调用我们的method,找到最大的返回值即可。
"""
def longestSubstring(self, s: str, k: int) ->int:
def helper(s, k):
if len(s) < k:
return 0
ch = min(set(s), key=s.count)
if s.count(ch) >= k:
return len(s)
else:
return max(helper(t, k) for t in s.split(ch))
return helper(s, k)
<|reserved_special_token_1|>
class Solution:
'''
先遍历整个string,并记录最小的character的出现次数。
如果最小character出现次数都不小于k,那么说明整个string就是满足条件的longest substring,返回原string的长度即可;
如果character的出现次数小于k,假设这个character是c,因为满足条件的substring永远不会包含c,所以满足条件的substring一定是在以c为分割参考下的某个substring中。所以我们需要做的就是把c当做是split的参考,在得到的String[]中再次调用我们的method,找到最大的返回值即可。
'''
def longestSubstring(self, s: str, k: int) -> int:
def helper(s, k):
if len(s) < k:
return 0
ch = min(set(s), key=s.count)
if s.count(ch) >= k:
return len(s)
else:
return max(helper(t, k) for t in s.split(ch))
return helper(s, k)
|
flexible
|
{
"blob_id": "6ba830aafbe8e4b42a0b927328ebcad1424cda5e",
"index": 8381,
"step-1": "<mask token>\n",
"step-2": "class Solution:\n <mask token>\n <mask token>\n",
"step-3": "class Solution:\n <mask token>\n\n def longestSubstring(self, s: str, k: int) ->int:\n\n def helper(s, k):\n if len(s) < k:\n return 0\n ch = min(set(s), key=s.count)\n if s.count(ch) >= k:\n return len(s)\n else:\n return max(helper(t, k) for t in s.split(ch))\n return helper(s, k)\n",
"step-4": "class Solution:\n \"\"\"\n 先遍历整个string,并记录最小的character的出现次数。\n 如果最小character出现次数都不小于k,那么说明整个string就是满足条件的longest substring,返回原string的长度即可;\n 如果character的出现次数小于k,假设这个character是c,因为满足条件的substring永远不会包含c,所以满足条件的substring一定是在以c为分割参考下的某个substring中。所以我们需要做的就是把c当做是split的参考,在得到的String[]中再次调用我们的method,找到最大的返回值即可。\n \"\"\"\n\n def longestSubstring(self, s: str, k: int) ->int:\n\n def helper(s, k):\n if len(s) < k:\n return 0\n ch = min(set(s), key=s.count)\n if s.count(ch) >= k:\n return len(s)\n else:\n return max(helper(t, k) for t in s.split(ch))\n return helper(s, k)\n",
"step-5": "class Solution:\n '''\n 先遍历整个string,并记录最小的character的出现次数。\n 如果最小character出现次数都不小于k,那么说明整个string就是满足条件的longest substring,返回原string的长度即可;\n 如果character的出现次数小于k,假设这个character是c,因为满足条件的substring永远不会包含c,所以满足条件的substring一定是在以c为分割参考下的某个substring中。所以我们需要做的就是把c当做是split的参考,在得到的String[]中再次调用我们的method,找到最大的返回值即可。\n '''\n\n def longestSubstring(self, s: str, k: int) -> int:\n def helper(s, k):\n if len(s) < k:\n return 0\n ch = min(set(s), key=s.count)\n if s.count(ch) >= k:\n return len(s)\n else:\n return max(helper(t, k) for t in s.split(ch))\n return helper(s, k)\n",
"step-ids": [
0,
1,
2,
3,
4
]
}
|
[
0,
1,
2,
3,
4
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.