uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
fa137a44e89ab9868ebf69a6
train
function
def test_indent(): for description, input, output in ( ("Sanity check: 1 line string", 'Test', ' Test'), ("List of strings turns in to strings joined by \\n", ["Test", "Test"], ' Test\n Test'), ): eq_.description = "indent(): %s" % description yie...
def test_indent():
for description, input, output in ( ("Sanity check: 1 line string", 'Test', ' Test'), ("List of strings turns in to strings joined by \\n", ["Test", "Test"], ' Test\n Test'), ): eq_.description = "indent(): %s" % description yield eq_, indent(inpu...
@mock_streams('stderr') @with_patched_object(output, 'warnings', True) def test_warn(): """ warn() should print 'Warning' plus given text """ warn("Test") assert "\nWarning: Test\n\n" == sys.stderr.getvalue() def test_indent():
64
64
91
4
60
objectified/fabric
tests/test_utils.py
Python
test_indent
test_indent
26
35
26
26
6e8a71e4234fae1545c1bc1cdd8cbee382f729c8
bigcode/the-stack
train
4a37b16eb79719f123b04fff
train
function
@with_fakes def test_fastprint_calls_puts(): """ fastprint() is just an alias to puts() """ text = "Some output" fake_puts = Fake('puts', expect_call=True).with_args( text=text, show_prefix=False, end="", flush=True ) with patched_context(utils, 'puts', fake_puts): fastprint(...
@with_fakes def test_fastprint_calls_puts():
""" fastprint() is just an alias to puts() """ text = "Some output" fake_puts = Fake('puts', expect_call=True).with_args( text=text, show_prefix=False, end="", flush=True ) with patched_context(utils, 'puts', fake_puts): fastprint(text)
with env.host_string if show_prefix is False """ s = "my output" h = "localhost" puts(s, show_prefix=False) eq_(sys.stdout.getvalue(), "%s" % (s + "\n")) @with_fakes def test_fastprint_calls_puts():
64
64
84
13
51
objectified/fabric
tests/test_utils.py
Python
test_fastprint_calls_puts
test_fastprint_calls_puts
118
128
118
119
f237ceb605e79c9edfb4596efdc8827cd5b1b99d
bigcode/the-stack
train
53eb773cc3e06f38d5f67a43
train
function
def test_indent_with_strip(): for description, input, output in ( ("Sanity check: 1 line string", indent('Test', strip=True), ' Test'), ("Check list of strings", indent(["Test", "Test"], strip=True), ' Test\n Test'), ("Check list of strings", inde...
def test_indent_with_strip():
for description, input, output in ( ("Sanity check: 1 line string", indent('Test', strip=True), ' Test'), ("Check list of strings", indent(["Test", "Test"], strip=True), ' Test\n Test'), ("Check list of strings", indent([" Test", " T...
("List of strings turns in to strings joined by \\n", ["Test", "Test"], ' Test\n Test'), ): eq_.description = "indent(): %s" % description yield eq_, indent(input), output del eq_.description def test_indent_with_strip():
64
64
123
6
57
objectified/fabric
tests/test_utils.py
Python
test_indent_with_strip
test_indent_with_strip
38
50
38
38
8b7c3a364b93e261c1a086f78a311b5b51da6247
bigcode/the-stack
train
7fde2ff6339a4ef838b973e7
train
function
@mock_streams('stdout') def test_puts_with_user_output_off(): """ puts() shouldn't print input to sys.stdout if "user" output level is off """ output.user = False puts("You aren't reading this.") eq_(sys.stdout.getvalue(), "")
@mock_streams('stdout') def test_puts_with_user_output_off():
""" puts() shouldn't print input to sys.stdout if "user" output level is off """ output.user = False puts("You aren't reading this.") eq_(sys.stdout.getvalue(), "")
input to sys.stdout if "user" output level is on """ s = "string!" output.user = True puts(s, show_prefix=False) eq_(sys.stdout.getvalue(), s + "\n") @mock_streams('stdout') def test_puts_with_user_output_off():
64
64
61
16
48
objectified/fabric
tests/test_utils.py
Python
test_puts_with_user_output_off
test_puts_with_user_output_off
86
93
86
87
26c43d5a89619711c1263e1267b85eb2f5f85709
bigcode/the-stack
train
4363e41e4b85f39cfefcff29
train
function
@mock_streams('stdout') def test_puts_with_user_output_on(): """ puts() should print input to sys.stdout if "user" output level is on """ s = "string!" output.user = True puts(s, show_prefix=False) eq_(sys.stdout.getvalue(), s + "\n")
@mock_streams('stdout') def test_puts_with_user_output_on():
""" puts() should print input to sys.stdout if "user" output level is on """ s = "string!" output.user = True puts(s, show_prefix=False) eq_(sys.stdout.getvalue(), s + "\n")
plus exception value """ try: abort("Test") except SystemExit: pass result = sys.stderr.getvalue() eq_("\nFatal error: Test\n\nAborting.\n", result) @mock_streams('stdout') def test_puts_with_user_output_on():
64
64
71
16
48
objectified/fabric
tests/test_utils.py
Python
test_puts_with_user_output_on
test_puts_with_user_output_on
75
83
75
76
dbdb861646b9d184a79bee588fc7bc06a266eeb6
bigcode/the-stack
train
88278d675502f293dc405789
train
function
@mock_streams('stdout') def test_puts_with_prefix(): """ puts() should prefix output with env.host_string if non-empty """ s = "my output" h = "localhost" with settings(host_string=h): puts(s) eq_(sys.stdout.getvalue(), "[%s] %s" % (h, s + "\n"))
@mock_streams('stdout') def test_puts_with_prefix():
""" puts() should prefix output with env.host_string if non-empty """ s = "my output" h = "localhost" with settings(host_string=h): puts(s) eq_(sys.stdout.getvalue(), "[%s] %s" % (h, s + "\n"))
_user_output_off(): """ puts() shouldn't print input to sys.stdout if "user" output level is off """ output.user = False puts("You aren't reading this.") eq_(sys.stdout.getvalue(), "") @mock_streams('stdout') def test_puts_with_prefix():
63
64
80
14
49
objectified/fabric
tests/test_utils.py
Python
test_puts_with_prefix
test_puts_with_prefix
96
105
96
97
a6a80ab024a8e7abb08f6eaadceb19fa0b27c945
bigcode/the-stack
train
4fa640b1e2fc295d8245e17b
train
function
@mock_streams('stderr') @with_patched_object(output, 'aborts', True) def test_abort_message(): """ abort() should print 'Fatal error' plus exception value """ try: abort("Test") except SystemExit: pass result = sys.stderr.getvalue() eq_("\nFatal error: Test\n\nAborting.\n", r...
@mock_streams('stderr') @with_patched_object(output, 'aborts', True) def test_abort_message():
""" abort() should print 'Fatal error' plus exception value """ try: abort("Test") except SystemExit: pass result = sys.stderr.getvalue() eq_("\nFatal error: Test\n\nAborting.\n", result)
yield eq_, input, output del eq_.description @aborts def test_abort(): """ abort() should raise SystemExit """ abort("Test") @mock_streams('stderr') @with_patched_object(output, 'aborts', True) def test_abort_message():
64
64
84
25
39
objectified/fabric
tests/test_utils.py
Python
test_abort_message
test_abort_message
61
72
61
63
94df562b05bcdc77acc24dfdee4ded57c93a4026
bigcode/the-stack
train
63d4b293476c9767a992c54e
train
class
class training(object): def __init__(self, options): self.initializer = options.get('initializer') self.activation = options.get('activation') self.optimizer = options.get('optimizer') self.filterSize = options.get('filterSize') def model(self, imageTrain, convDense): fashionModel = keras.Sequ...
class training(object):
def __init__(self, options): self.initializer = options.get('initializer') self.activation = options.get('activation') self.optimizer = options.get('optimizer') self.filterSize = options.get('filterSize') def model(self, imageTrain, convDense): fashionModel = keras.Sequential() for dense in...
import tensorflow as tf from tensorflow import keras import numpy as np class training(object):
19
81
272
4
14
ivokun/fashion-mnist-tensorflow
utils.py
Python
training
training
6
35
6
7
99ead7e85a056ac2dbee253d9d73fd13fd5adfcb
bigcode/the-stack
train
3bfbf6ce76b2fdbdb092bf94
train
function
def main(_): #1.load data(X:list of lint,y:int). #if os.path.exists(FLAGS.cache_path): # 如果文件系统中存在,那么加载故事(词汇表索引化的) # with open(FLAGS.cache_path, 'r') as data_f: # trainX, trainY, testX, testY, vocabulary_index2word=pickle.load(data_f) # vocab_size=len(vocabulary_index2word) #el...
def main(_): #1.load data(X:list of lint,y:int). #if os.path.exists(FLAGS.cache_path): # 如果文件系统中存在,那么加载故事(词汇表索引化的) # with open(FLAGS.cache_path, 'r') as data_f: # trainX, trainY, testX, testY, vocabulary_index2word=pickle.load(data_f) # vocab_size=len(vocabulary_index2word) #el...
if 1==1: trainX, trainY, testX, testY = None, None, None, None vocabulary_word2index, vocabulary_index2word = create_voabulary(word2vec_model_path=FLAGS.word2vec_model_path,name_scope="rcnn") #simple='simple' vocab_size = len(vocabulary_word2index) print("cnn_model.vocab_size:",vocab...
#O.K.train-zhihu4-only-title-all.txt-->training-data/test-zhihu4-only-title.txt--->'training-data/train-zhihu5-only-title-multilabel.txt' tf.flags.DEFINE_string("word2vec_model_path","zhihu-word2vec-title-desc.bin-100","word2vec's vocabulary and vectors") #zhihu-word2vec.bin-100-->zhihu-word2vec-multilabel-minicount15...
256
256
1,251
104
152
sliderSun/pynlp
text-classification/a03_TextRCNN/p71_TextRCNN_train.py
Python
main
main
37
115
37
43
75d7cbfec8445a0c177e3b84fb7d5ffb706f55f2
bigcode/the-stack
train
ee598514d343f4e7f34eb276
train
function
def get_label_using_logits(logits,vocabulary_index2word_label,top_number=1): #print("get_label_using_logits.logits:",logits) #1-d array: array([-5.69036102, -8.54903221, -5.63954401, ..., -5.83969498,-5.84496021, -6.13911009], dtype=float32)) index_list=np.argsort(logits)[-top_number:] index_list=index_list...
def get_label_using_logits(logits,vocabulary_index2word_label,top_number=1): #print("get_label_using_logits.logits:",logits) #1-d array: array([-5.69036102, -8.54903221, -5.63954401, ..., -5.83969498,-5.84496021, -6.13911009], dtype=float32))
index_list=np.argsort(logits)[-top_number:] index_list=index_list[::-1] #label_list=[] #for index in index_list: # label=vocabulary_index2word_label[index] # label_list.append(label) #('get_label_using_logits.label_list:', [u'-3423450385060590478', u'2838091149470021485', u'-31749070029424...
def get_label_using_logits(logits,vocabulary_index2word_label,top_number=1): #print("get_label_using_logits.logits:",logits) #1-d array: array([-5.69036102, -8.54903221, -5.63954401, ..., -5.83969498,-5.84496021, -6.13911009], dtype=float32))
85
64
204
85
0
sliderSun/pynlp
text-classification/a03_TextRCNN/p71_TextRCNN_train.py
Python
get_label_using_logits
get_label_using_logits
166
174
166
167
bb8239a95f9cbc62f955a1e9b10326e398603c13
bigcode/the-stack
train
6f43449579e42f0aab3c102f
train
function
def do_eval(sess,textCNN,evalX,evalY,batch_size,vocabulary_index2word_label): number_examples=len(evalX) eval_loss,eval_acc,eval_counter=0.0,0.0,0 for start,end in zip(range(0,number_examples,batch_size),range(batch_size,number_examples,batch_size)): feed_dict = {textCNN.input_x: evalX[start:end], t...
def do_eval(sess,textCNN,evalX,evalY,batch_size,vocabulary_index2word_label):
number_examples=len(evalX) eval_loss,eval_acc,eval_counter=0.0,0.0,0 for start,end in zip(range(0,number_examples,batch_size),range(batch_size,number_examples,batch_size)): feed_dict = {textCNN.input_x: evalX[start:end], textCNN.dropout_keep_prob: 1} if not FLAGS.multi_label_flag: ...
. sess.run(t_assign_embedding) print("word. exists embedding:", count_exist, " ;word not exist embedding:", count_not_exist) print("using pre-trained word emebedding.ended...") # 在验证集上做验证,报告损失、精确度 def do_eval(sess,textCNN,evalX,evalY,batch_size,vocabulary_index2word_label):
82
82
274
22
59
sliderSun/pynlp
text-classification/a03_TextRCNN/p71_TextRCNN_train.py
Python
do_eval
do_eval
150
163
150
150
92964d4dbba9b41a1a9f76f94debf7f9e7dd4c1d
bigcode/the-stack
train
b5cbecb27886c7c86e35353a
train
function
def calculate_accuracy(labels_predicted, labels,eval_counter): label_nozero=[] #print("labels:",labels) labels=list(labels) for index,label in enumerate(labels): if label>0: label_nozero.append(index) if eval_counter<2: print("labels_predicted:",labels_predicted," ;labels...
def calculate_accuracy(labels_predicted, labels,eval_counter):
label_nozero=[] #print("labels:",labels) labels=list(labels) for index,label in enumerate(labels): if label>0: label_nozero.append(index) if eval_counter<2: print("labels_predicted:",labels_predicted," ;labels_nozero:",label_nozero) count = 0 label_dict = {x: x fo...
u'2838091149470021485', u'-3174907002942471215', u'-1812694399780494968', u'6815248286057533876']) return index_list #统计预测的准确率 def calculate_accuracy(labels_predicted, labels,eval_counter):
64
64
141
12
51
sliderSun/pynlp
text-classification/a03_TextRCNN/p71_TextRCNN_train.py
Python
calculate_accuracy
calculate_accuracy
177
192
177
177
46cc0ad89e3e311af9b074e8975093922f0a5e15
bigcode/the-stack
train
147a5ab62c9ea9d01fac38f0
train
function
def assign_pretrained_word_embedding(sess,vocabulary_index2word,vocab_size,textRCNN,word2vec_model_path=None): print("using pre-trained word emebedding.started.word2vec_model_path:",word2vec_model_path) # word2vecc=word2vec.load('word_embedding.txt') #load vocab-vector fiel.word2vecc['w91874'] word2vec_mode...
def assign_pretrained_word_embedding(sess,vocabulary_index2word,vocab_size,textRCNN,word2vec_model_path=None):
print("using pre-trained word emebedding.started.word2vec_model_path:",word2vec_model_path) # word2vecc=word2vec.load('word_embedding.txt') #load vocab-vector fiel.word2vecc['w91874'] word2vec_model = gensim.models.KeyedVectors.load_word2vec_format(word2vec_model_path, binary=True) word2vec_dict = {} ...
,testX,testY,batch_size,vocabulary_index2word_label) print("Epoch %d Validation Loss:%.3f\tValidation Accuracy: %.3f" % (epoch,eval_loss,eval_acc)) #save model to checkpoint save_path=FLAGS.ckpt_dir+"model.ckpt" saver.save(sess,save_path,global_step=epoch)...
155
155
517
26
128
sliderSun/pynlp
text-classification/a03_TextRCNN/p71_TextRCNN_train.py
Python
assign_pretrained_word_embedding
assign_pretrained_word_embedding
117
147
117
117
09c847295d102b3010b4cd470610da6166ee2b1c
bigcode/the-stack
train
a7d6ede0c03443f7c5db76ba
train
function
def generate_instance_config(metrics, template=None): template = template if template else SNMP_CONF instance_config = copy.copy(template) instance_config['metrics'] = metrics instance_config['name'] = HOST return instance_config
def generate_instance_config(metrics, template=None):
template = template if template else SNMP_CONF instance_config = copy.copy(template) instance_config['metrics'] = metrics instance_config['name'] = HOST return instance_config
"name": "needFallback" }, { "OID": "1.3.6.1.2.1.4.31.3.1.3.2.1", "name": "noFallbackAndSameResult" } ] def generate_instance_config(metrics, template=None):
64
64
51
9
55
tylerbenson/integrations-core
snmp/tests/common.py
Python
generate_instance_config
generate_instance_config
177
182
177
177
11d4159b6ea76eb1d3c744c217b2f4c0e5a0bd52
bigcode/the-stack
train
9df192a274074bf00b2a421a
train
function
def generate_v3_instance_config(metrics, name=None, user=None, auth=None, auth_key=None, priv=None, priv_key=None): instance_config = generate_instance_config(metrics, SNMP_V3_CONF) if name: instance_config['name'] = name if user: instance_config['user'] = us...
def generate_v3_instance_config(metrics, name=None, user=None, auth=None, auth_key=None, priv=None, priv_key=None):
instance_config = generate_instance_config(metrics, SNMP_V3_CONF) if name: instance_config['name'] = name if user: instance_config['user'] = user if auth: instance_config['authProtocol'] = auth if auth_key: instance_config['authKey'] = auth_key if priv: i...
SNMP_CONF instance_config = copy.copy(template) instance_config['metrics'] = metrics instance_config['name'] = HOST return instance_config def generate_v3_instance_config(metrics, name=None, user=None, auth=None, auth_key=None, priv=None, priv_key=None):
64
64
135
29
34
tylerbenson/integrations-core
snmp/tests/common.py
Python
generate_v3_instance_config
generate_v3_instance_config
185
202
185
186
a8444f851f7bb0550a0ea6a82319656638451a8e
bigcode/the-stack
train
dff44001288a61c8511ef433
train
function
@register.inclusion_tag("django_plotly_dash/plotly_direct.html", takes_context=True) def plotly_direct(context, name=None, slug=None, da=None): 'Direct insertion of a Dash app' da, app = _locate_daapp(name, slug, da) view_func = app.locate_endpoint_function() # Load embedded holder inserted by middle...
@register.inclusion_tag("django_plotly_dash/plotly_direct.html", takes_context=True) def plotly_direct(context, name=None, slug=None, da=None):
'Direct insertion of a Dash app' da, app = _locate_daapp(name, slug, da) view_func = app.locate_endpoint_function() # Load embedded holder inserted by middleware eh = context.request.dpd_content_handler.embedded_holder # Need to add in renderer launcher renderer_launcher = '<script id="_...
ly_footer(context): 'Insert placeholder for django-plotly-dash footer content' return context.request.dpd_content_handler.footer_placeholder @register.inclusion_tag("django_plotly_dash/plotly_direct.html", takes_context=True) def plotly_direct(context, name=None, slug=None, da=None):
64
64
166
35
28
aboulang/django-plotly-dash-pivot-demo
django_plotly_dash/templatetags/plotly_dash.py
Python
plotly_direct
plotly_direct
90
111
90
91
26c9bd172fb91ee050d849d10670cfba007c9d0b
bigcode/the-stack
train
352d7b4800a6fb20f917a78c
train
function
@register.simple_tag(takes_context=True) def plotly_footer(context): 'Insert placeholder for django-plotly-dash footer content' return context.request.dpd_content_handler.footer_placeholder
@register.simple_tag(takes_context=True) def plotly_footer(context):
'Insert placeholder for django-plotly-dash footer content' return context.request.dpd_content_handler.footer_placeholder
_id=cache_id) return locals() @register.simple_tag(takes_context=True) def plotly_header(context): 'Insert placeholder for django-plotly-dash header content' return context.request.dpd_content_handler.header_placeholder @register.simple_tag(takes_context=True) def plotly_footer(context):
64
64
40
15
48
aboulang/django-plotly-dash-pivot-demo
django_plotly_dash/templatetags/plotly_dash.py
Python
plotly_footer
plotly_footer
85
88
85
86
953f1e42612e35c75cc846b55948c180d29a2406
bigcode/the-stack
train
58613e4a5e2c93c815c0b11c
train
function
@register.simple_tag(takes_context=True) def site_root_url(context): 'Provide the root url of the demo site' current_site_url = get_current_site(context.request) return current_site_url.domain
@register.simple_tag(takes_context=True) def site_root_url(context):
'Provide the root url of the demo site' current_site_url = get_current_site(context.request) return current_site_url.domain
'Return a string of space-separated class names' da, app = _locate_daapp(name, slug, da) return app.extra_html_properties(prefix=prefix, postfix=postfix, template_type=template_type) @register.simple_tag(takes_context=True) def site_ro...
64
64
44
15
49
aboulang/django-plotly-dash-pivot-demo
django_plotly_dash/templatetags/plotly_dash.py
Python
site_root_url
site_root_url
141
145
141
142
a03eca607d417931179ecd3b8c427e7624f8a8ef
bigcode/the-stack
train
26cba48def8ac5bb1d1459db
train
function
@register.inclusion_tag("django_plotly_dash/plotly_messaging.html", takes_context=True) def plotly_message_pipe(context, url=None): 'Insert script for providing background websocket connection' url = url if url else ws_default_url return locals()
@register.inclusion_tag("django_plotly_dash/plotly_messaging.html", takes_context=True) def plotly_message_pipe(context, url=None):
'Insert script for providing background websocket connection' url = url if url else ws_default_url return locals()
edded(eh) try: resp = view_func() finally: eh.add_scripts(renderer_launcher) app.exit_embedded() return locals() @register.inclusion_tag("django_plotly_dash/plotly_messaging.html", takes_context=True) def plotly_message_pipe(context, url=None):
64
64
56
31
33
aboulang/django-plotly-dash-pivot-demo
django_plotly_dash/templatetags/plotly_dash.py
Python
plotly_message_pipe
plotly_message_pipe
113
117
113
114
e9598a123cf1cbd34fcfea8933e2f0bc8b079e69
bigcode/the-stack
train
05f36eef9a281e985262d91f
train
function
@register.simple_tag(takes_context=True) def plotly_header(context): 'Insert placeholder for django-plotly-dash header content' return context.request.dpd_content_handler.header_placeholder
@register.simple_tag(takes_context=True) def plotly_header(context):
'Insert placeholder for django-plotly-dash header content' return context.request.dpd_content_handler.header_placeholder
%; height: 100%; """ cache_id = store_initial_arguments(context['request'], initial_arguments) da, app = _locate_daapp(name, slug, da, cache_id=cache_id) return locals() @register.simple_tag(takes_context=True) def plotly_header(context):
64
64
40
15
49
aboulang/django-plotly-dash-pivot-demo
django_plotly_dash/templatetags/plotly_dash.py
Python
plotly_header
plotly_header
80
83
80
81
1db44848f96df22266c6dbf86df9dbcc640db999
bigcode/the-stack
train
9fe498a189a4815869521f1f
train
function
def _locate_daapp(name, slug, da, cache_id=None): app = None if name is not None: da, app = DashApp.locate_item(name, stateless=True, cache_id=cache_id) if slug is not None: da, app = DashApp.locate_item(slug, stateless=False, cache_id=cache_id) if not app: app = da.as_dash_i...
def _locate_daapp(name, slug, da, cache_id=None):
app = None if name is not None: da, app = DashApp.locate_item(name, stateless=True, cache_id=cache_id) if slug is not None: da, app = DashApp.locate_item(slug, stateless=False, cache_id=cache_id) if not app: app = da.as_dash_instance() return da, app
_current_site from django_plotly_dash.models import DashApp from django_plotly_dash.util import pipe_ws_endpoint_name, store_initial_arguments register = template.Library() ws_default_url = "/%s" % pipe_ws_endpoint_name() def _locate_daapp(name, slug, da, cache_id=None):
64
64
99
16
48
aboulang/django-plotly-dash-pivot-demo
django_plotly_dash/templatetags/plotly_dash.py
Python
_locate_daapp
_locate_daapp
38
51
38
39
bff72a86e43c0d82f8af4be294f7086a3924c4ec
bigcode/the-stack
train
a297a742f419683c84230af7
train
function
@register.inclusion_tag("django_plotly_dash/plotly_app.html", takes_context=True) def plotly_app(context, name=None, slug=None, da=None, ratio=0.1, use_frameborder=False, initial_arguments=None): 'Insert a dash application using a html iframe' fbs = '1' if use_frameborder else '0' dstyle = """ positio...
@register.inclusion_tag("django_plotly_dash/plotly_app.html", takes_context=True) def plotly_app(context, name=None, slug=None, da=None, ratio=0.1, use_frameborder=False, initial_arguments=None):
'Insert a dash application using a html iframe' fbs = '1' if use_frameborder else '0' dstyle = """ position: relative; padding-bottom: %s%%; height: 0; overflow:hidden; """ % (ratio*100) istyle = """ position: absolute; top: 0; left: 0; width: 100%; height: 100...
app = da.as_dash_instance() return da, app @register.inclusion_tag("django_plotly_dash/plotly_app.html", takes_context=True) def plotly_app(context, name=None, slug=None, da=None, ratio=0.1, use_frameborder=False, initial_arguments=None):
64
64
189
50
13
aboulang/django-plotly-dash-pivot-demo
django_plotly_dash/templatetags/plotly_dash.py
Python
plotly_app
plotly_app
53
78
53
54
a66a9c1dfe8d7d6a488d19e45e74944413c465a5
bigcode/the-stack
train
fcbf918ee8595245c8f45446
train
function
@register.simple_tag() def plotly_class(name=None, slug=None, da=None, prefix=None, postfix=None, template_type=None): 'Return a string of space-separated class names' da, app = _locate_daapp(name, slug, da) return app.extra_html_properties(prefix=prefix, postfix=postf...
@register.simple_tag() def plotly_class(name=None, slug=None, da=None, prefix=None, postfix=None, template_type=None):
'Return a string of space-separated class names' da, app = _locate_daapp(name, slug, da) return app.extra_html_properties(prefix=prefix, postfix=postfix, template_type=template_type)
da) slugified_id = app.slugified_id() if postfix: return "%s-%s" %(slugified_id, postfix) return slugified_id @register.simple_tag() def plotly_class(name=None, slug=None, da=None, prefix=None, postfix=None, template_type=None):
64
64
78
28
35
aboulang/django-plotly-dash-pivot-demo
django_plotly_dash/templatetags/plotly_dash.py
Python
plotly_class
plotly_class
131
139
131
132
a60f974a2ea8ddb9c8bef6bf5829d753e30864d5
bigcode/the-stack
train
2b2ee7f4838943ff24ba53d7
train
function
@register.simple_tag() def plotly_app_identifier(name=None, slug=None, da=None, postfix=None): 'Return a slug-friendly identifier' da, app = _locate_daapp(name, slug, da) slugified_id = app.slugified_id() if postfix: return "%s-%s" %(slugified_id, postfix) return slugified_id
@register.simple_tag() def plotly_app_identifier(name=None, slug=None, da=None, postfix=None):
'Return a slug-friendly identifier' da, app = _locate_daapp(name, slug, da) slugified_id = app.slugified_id() if postfix: return "%s-%s" %(slugified_id, postfix) return slugified_id
essaging.html", takes_context=True) def plotly_message_pipe(context, url=None): 'Insert script for providing background websocket connection' url = url if url else ws_default_url return locals() @register.simple_tag() def plotly_app_identifier(name=None, slug=None, da=None, postfix=None):
64
64
80
22
42
aboulang/django-plotly-dash-pivot-demo
django_plotly_dash/templatetags/plotly_dash.py
Python
plotly_app_identifier
plotly_app_identifier
119
129
119
120
eacaa16139b39e935e0572ed67f333fc630e2f2c
bigcode/the-stack
train
e4dfe4a9b51a892ce6689dac
train
class
class DirectoryRequests(object): # This module make requests (of 'path' type) to the shakti API and convert the raw data returned from the API # in an DataType object (data_types.py), where the data will be more easily accessible netflix_session = None @cache_utils.cache_output(cache_utils.CACHE_MYLIS...
class DirectoryRequests(object): # This module make requests (of 'path' type) to the shakti API and convert the raw data returned from the API # in an DataType object (data_types.py), where the data will be more easily accessible
netflix_session = None @cache_utils.cache_output(cache_utils.CACHE_MYLIST, fixed_identifier='my_list_items', ignore_self_class=True) def req_mylist_items(self): """Return the 'my list' video list as videoid items""" common.debug('Requesting "my list" video list as videoid items') tr...
original implementation module) Methods to make 'path' requests through the Shakti API SPDX-License-Identifier: MIT See LICENSES/MIT.md for more information. """ from __future__ import absolute_import, division, unicode_literals from future.utils import iteritems from resources.lib import common from res...
256
256
3,028
54
201
kevenli/plugin.video.netflix
resources/lib/services/directorybuilder/dir_builder_requests.py
Python
DirectoryRequests
DirectoryRequests
25
255
25
28
4894ca5498434addb2da3fba70d2475b5a171883
bigcode/the-stack
train
ff2521738ab382b22b466756
train
class
class StorageGetBlobTest(StorageTestCase): def _setup(self, storage_account, key): # test chunking functionality by reducing the threshold # for chunking and the size of each chunk, otherwise # the tests would take too long to execute self.bsc = BlobServiceClient( self.ac...
class StorageGetBlobTest(StorageTestCase):
def _setup(self, storage_account, key): # test chunking functionality by reducing the threshold # for chunking and the size of each chunk, otherwise # the tests would take too long to execute self.bsc = BlobServiceClient( self.account_url(storage_account, "blob"), ...
# coding: utf-8 # ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # --------------------------------------------------------------------...
164
256
8,506
9
155
iscai-msft/azure-sdk-for-python
sdk/storage/azure-storage-blob/tests/test_get_blob.py
Python
StorageGetBlobTest
StorageGetBlobTest
31
928
31
31
2b752e9e8a03fe65e8acec4ef3c235cda6544924
bigcode/the-stack
train
f6d9b7c6e54abe964897f6d4
train
class
@viewer_registry("imviz-image-viewer", label="Image 2D (Imviz)") class ImvizImageView(BqplotImageView, AstrowidgetsImageViewerMixin): # Whether to inherit tools from glue-jupyter automatically. Set this to # False to have full control here over which tools are shown in case new # ones are added in glue-jup...
@viewer_registry("imviz-image-viewer", label="Image 2D (Imviz)") class ImvizImageView(BqplotImageView, AstrowidgetsImageViewerMixin): # Whether to inherit tools from glue-jupyter automatically. Set this to # False to have full control here over which tools are shown in case new # ones are added in glue-jup...
inherit_tools = False tools = ['bqplot:home', 'jdaviz:boxzoom', 'jdaviz:boxzoommatch', 'bqplot:panzoom', 'jdaviz:panzoommatch', 'jdaviz:contrastbias', 'jdaviz:blinkonce', 'bqplot:rectangle', 'bqplot:circle', 'bqplot:ellipse'] default_class = None def __init__(sel...
import numpy as np from glue.core.link_helpers import LinkSame from glue_jupyter.bqplot.image import BqplotImageView from jdaviz.configs.imviz.helper import data_has_valid_wcs, layer_is_image_data from jdaviz.core.astrowidgets_api import AstrowidgetsImageViewerMixin from jdaviz.core.events import SnackbarMessage from...
187
256
2,055
88
99
check-spelling/jdaviz
jdaviz/configs/imviz/plugins/viewers.py
Python
ImvizImageView
ImvizImageView
14
231
14
19
71628f375ea7ffa894e4e1c993f5e3b02f2b83ed
bigcode/the-stack
train
e19cdef6e5044df50947bacc
train
class
class KeyStoneInfo(object): """To generate Keystone Authentication information Contrail Driver expects Keystone auth info for testing purpose. """ auth_protocol = 'http' auth_host = 'host' auth_port = 5000 admin_user = 'neutron' admin_password = 'neutron' admin_token = 'neutron' ...
class KeyStoneInfo(object):
"""To generate Keystone Authentication information Contrail Driver expects Keystone auth info for testing purpose. """ auth_protocol = 'http' auth_host = 'host' auth_port = 5000 admin_user = 'neutron' admin_password = 'neutron' admin_token = 'neutron' admin_tenant_name = 'neut...
.datetime.now() self.auth_token = None self._session = None self._is_admin = True self.admin = uuid.uuid4().hex.decode() self.request_id = 'req-' + str(uuid.uuid4()) self.tenant = tenant_id class KeyStoneInfo(object):
64
64
84
6
57
armando-migliaccio/neutron-1
neutron/tests/unit/opencontrail/test_contrail_plugin.py
Python
KeyStoneInfo
KeyStoneInfo
200
210
200
200
8df280a432e978be0382e4eb5f48c1c9fd8318d0
bigcode/the-stack
train
ccd1afdcec0088a2e51b54e5
train
class
class ContrailPluginTestCase(test_plugin.NeutronDbPluginV2TestCase): _plugin_name = ('%s.NeutronPluginContrailCoreV2' % CONTRAIL_PKG_PATH) def setUp(self, plugin=None, ext_mgr=None): cfg.CONF.keystone_authtoken = KeyStoneInfo() mock.patch('requests.post').start().side_effect = FAKE_SERVER.requ...
class ContrailPluginTestCase(test_plugin.NeutronDbPluginV2TestCase):
_plugin_name = ('%s.NeutronPluginContrailCoreV2' % CONTRAIL_PKG_PATH) def setUp(self, plugin=None, ext_mgr=None): cfg.CONF.keystone_authtoken = KeyStoneInfo() mock.patch('requests.post').start().side_effect = FAKE_SERVER.request super(ContrailPluginTestCase, self).setUp(self._plugin_na...
_host = 'host' auth_port = 5000 admin_user = 'neutron' admin_password = 'neutron' admin_token = 'neutron' admin_tenant_name = 'neutron' class ContrailPluginTestCase(test_plugin.NeutronDbPluginV2TestCase):
64
64
103
17
47
armando-migliaccio/neutron-1
neutron/tests/unit/opencontrail/test_contrail_plugin.py
Python
ContrailPluginTestCase
ContrailPluginTestCase
213
220
213
213
766054985365020ebf7990e0cff2adc610d5e1f0
bigcode/the-stack
train
dfda30491fa9647214d4f955
train
class
class TestContrailL3NatTestCase(ContrailPluginTestCase, test_l3_plugin.L3NatDBIntTestCase): mock_rescheduling = False def setUp(self): super(TestContrailL3NatTestCase, self).setUp()
class TestContrailL3NatTestCase(ContrailPluginTestCase, test_l3_plugin.L3NatDBIntTestCase):
mock_rescheduling = False def setUp(self): super(TestContrailL3NatTestCase, self).setUp()
bindings.VIF_TYPE_VROUTER HAS_PORT_FILTER = True def setUp(self): super(TestContrailPortBinding, self).setUp() class TestContrailL3NatTestCase(ContrailPluginTestCase, test_l3_plugin.L3NatDBIntTestCase):
64
64
58
29
35
armando-migliaccio/neutron-1
neutron/tests/unit/opencontrail/test_contrail_plugin.py
Python
TestContrailL3NatTestCase
TestContrailL3NatTestCase
307
312
307
308
5d45c6ed693bc036548e10cee62632361d9019ee
bigcode/the-stack
train
dfd0da4f88e0841cf1f0dc06
train
class
class TestContrailSubnetsV2(test_plugin.TestSubnetsV2, ContrailPluginTestCase): def setUp(self): super(TestContrailSubnetsV2, self).setUp() # Support ipv6 in contrail is planned in Juno def test_update_subnet_ipv6_attributes(self): self.skipTest("Contrail isn't s...
class TestContrailSubnetsV2(test_plugin.TestSubnetsV2, ContrailPluginTestCase):
def setUp(self): super(TestContrailSubnetsV2, self).setUp() # Support ipv6 in contrail is planned in Juno def test_update_subnet_ipv6_attributes(self): self.skipTest("Contrail isn't supporting ipv6 yet") def test_update_subnet_ipv6_inconsistent_address_attribute(self): self.ski...
=None, ext_mgr=None): cfg.CONF.keystone_authtoken = KeyStoneInfo() mock.patch('requests.post').start().side_effect = FAKE_SERVER.request super(ContrailPluginTestCase, self).setUp(self._plugin_name) class TestContrailNetworksV2(test_plugin.TestNetworksV2, ContrailP...
119
119
398
23
96
armando-migliaccio/neutron-1
neutron/tests/unit/opencontrail/test_contrail_plugin.py
Python
TestContrailSubnetsV2
TestContrailSubnetsV2
229
268
229
230
583228ed84bb13544b9d97ada2e804efbdc5c40a
bigcode/the-stack
train
37944d02055039c4217cf7dd
train
class
class FakeServer(db_base_plugin_v2.NeutronDbPluginV2, external_net_db.External_net_db_mixin, securitygroups_db.SecurityGroupDbMixin, l3_db.L3_NAT_db_mixin): """FakeServer for contrail api server. This class mocks behaviour of contrail API server. """ s...
class FakeServer(db_base_plugin_v2.NeutronDbPluginV2, external_net_db.External_net_db_mixin, securitygroups_db.SecurityGroupDbMixin, l3_db.L3_NAT_db_mixin):
"""FakeServer for contrail api server. This class mocks behaviour of contrail API server. """ supported_extension_aliases = ['external-net', 'router', 'floatingip'] @property def _core_plugin(self): return self def create_port(self, context, port): self._ensure_default_sec...
import uuid import mock import netaddr from oslo.config import cfg from testtools import matchers import webob.exc from neutron.api import extensions from neutron.api.v2 import attributes as attr from neutron.api.v2 import base as api_base from neutron.common import exceptions as exc from neutron import context as n...
256
256
1,197
46
210
armando-migliaccio/neutron-1
neutron/tests/unit/opencontrail/test_contrail_plugin.py
Python
FakeServer
FakeServer
48
179
48
51
7c201ad78e53d1d4a4a313aea19796e95bc94787
bigcode/the-stack
train
ae6d52d7f0403f03f8ed6d5c
train
class
class TestContrailPortsV2(test_plugin.TestPortsV2, ContrailPluginTestCase): def setUp(self): super(TestContrailPortsV2, self).setUp() def test_delete_ports_by_device_id(self): self.skipTest("This method tests rpc API of " "which contrail isn't usi...
class TestContrailPortsV2(test_plugin.TestPortsV2, ContrailPluginTestCase):
def setUp(self): super(TestContrailPortsV2, self).setUp() def test_delete_ports_by_device_id(self): self.skipTest("This method tests rpc API of " "which contrail isn't using") def test_delete_ports_by_device_id_second_call_failure(self): self.skipTest("This me...
validate_subnet, neutron_context.get_admin_context( load_admin_roles=False), subnet) self.assertThat( str(error), matchers.Not(matchers.Contains('built-in fun...
63
64
137
21
42
armando-migliaccio/neutron-1
neutron/tests/unit/opencontrail/test_contrail_plugin.py
Python
TestContrailPortsV2
TestContrailPortsV2
271
286
271
272
1f179ef8d0d1f5109f0ae822d47d27c6714dd9ca
bigcode/the-stack
train
dcbdca9228454faf2de2b116
train
class
class TestContrailSecurityGroups(test_sg.TestSecurityGroups, ContrailPluginTestCase): def setUp(self, plugin=None, ext_mgr=None): super(TestContrailSecurityGroups, self).setUp(self._plugin_name, ext_mgr) ext_mgr =...
class TestContrailSecurityGroups(test_sg.TestSecurityGroups, ContrailPluginTestCase):
def setUp(self, plugin=None, ext_mgr=None): super(TestContrailSecurityGroups, self).setUp(self._plugin_name, ext_mgr) ext_mgr = extensions.PluginAwareExtensionManager.get_instance() self.ext_api = test_extensions.setup_extensions_middlewa...
API of " "which contrail isn't using") def test_delete_ports_ignores_port_not_found(self): self.skipTest("This method tests private method of " "which contrail isn't using") class TestContrailSecurityGroups(test_sg.TestSecurityGroups, ...
64
64
80
20
44
armando-migliaccio/neutron-1
neutron/tests/unit/opencontrail/test_contrail_plugin.py
Python
TestContrailSecurityGroups
TestContrailSecurityGroups
289
295
289
290
ea572a382963d7778188eff26eb2b8de01a7c292
bigcode/the-stack
train
d499a68e305a0a0d88dd5883
train
class
class Context(object): def __init__(self, tenant_id=''): self.read_only = False self.show_deleted = False self.roles = [u'admin', u'KeystoneServiceAdmin', u'KeystoneAdmin'] self._read_deleted = 'no' self.timestamp = datetime.datetime.now() self.auth_token = None ...
class Context(object):
def __init__(self, tenant_id=''): self.read_only = False self.show_deleted = False self.roles = [u'admin', u'KeystoneServiceAdmin', u'KeystoneAdmin'] self._read_deleted = 'no' self.timestamp = datetime.datetime.now() self.auth_token = None self._session = None...
if data.get('id'): obj['id'] = data.get('id') response = mock.MagicMock() response.status_code = code def return_obj(): return obj response.json = return_obj return response FAKE_SERVER = FakeServer() class Context(object):
64
64
123
4
60
armando-migliaccio/neutron-1
neutron/tests/unit/opencontrail/test_contrail_plugin.py
Python
Context
Context
185
197
185
185
0bc846c74e1cd55f8ccaf79e68110ddc866bfc4e
bigcode/the-stack
train
b5754d813c78a4c03f440d93
train
class
class TestContrailPortBinding(ContrailPluginTestCase, test_bindings.PortBindingsTestCase): VIF_TYPE = portbindings.VIF_TYPE_VROUTER HAS_PORT_FILTER = True def setUp(self): super(TestContrailPortBinding, self).setUp()
class TestContrailPortBinding(ContrailPluginTestCase, test_bindings.PortBindingsTestCase):
VIF_TYPE = portbindings.VIF_TYPE_VROUTER HAS_PORT_FILTER = True def setUp(self): super(TestContrailPortBinding, self).setUp()
SecurityGroups, self).setUp(self._plugin_name, ext_mgr) ext_mgr = extensions.PluginAwareExtensionManager.get_instance() self.ext_api = test_extensions.setup_extensions_middleware(ext_mgr) class TestContrailPortBinding(ContrailPluginTestCase, ...
64
64
63
22
42
armando-migliaccio/neutron-1
neutron/tests/unit/opencontrail/test_contrail_plugin.py
Python
TestContrailPortBinding
TestContrailPortBinding
298
304
298
299
c7e4fe249aa02177cd976e00f302e696c8f18228
bigcode/the-stack
train
570dd891ab7bd77a1fc7aa90
train
class
class TestContrailNetworksV2(test_plugin.TestNetworksV2, ContrailPluginTestCase): def setUp(self): super(TestContrailNetworksV2, self).setUp()
class TestContrailNetworksV2(test_plugin.TestNetworksV2, ContrailPluginTestCase):
def setUp(self): super(TestContrailNetworksV2, self).setUp()
_authtoken = KeyStoneInfo() mock.patch('requests.post').start().side_effect = FAKE_SERVER.request super(ContrailPluginTestCase, self).setUp(self._plugin_name) class TestContrailNetworksV2(test_plugin.TestNetworksV2, ContrailPluginTestCase):
64
64
41
21
43
armando-migliaccio/neutron-1
neutron/tests/unit/opencontrail/test_contrail_plugin.py
Python
TestContrailNetworksV2
TestContrailNetworksV2
223
226
223
224
97a7c1b1ab2f0bcc2cfec9859012643f58b28d2e
bigcode/the-stack
train
c17c60cb034bc6ffdffb0660
train
function
def bad(): nonlocal missing global missing
def bad():
nonlocal missing global missing
##Patterns: E0115 ##Err: E0115 def bad():
17
64
12
3
13
mrfyda/codacy-pylint-python3
docs/tests/E0115.py
Python
bad
bad
4
6
4
4
dafb70f6df6f12e5db01c30983976b6347f1f11d
bigcode/the-stack
train
8335f2954adf4a3fda3a8eb2
train
function
def good(): nonlocal missing def test(): global missing return test
def good():
nonlocal missing def test(): global missing return test
##Patterns: E0115 ##Err: E0115 def bad(): nonlocal missing global missing def good():
29
64
20
3
25
mrfyda/codacy-pylint-python3
docs/tests/E0115.py
Python
good
good
8
12
8
8
f235a7b5e4f17aa557134fb78f8982611a5a20b9
bigcode/the-stack
train
c00de702e3933de6a379ccef
train
function
def uplink_callback(msg, client): print("Received uplink from ", msg.dev_id) print(msg)
def uplink_callback(msg, client):
print("Received uplink from ", msg.dev_id) print(msg)
1") USERNAME = os.environ.get("USERNAME") PASSWORD = os.environ.get("PASSWORD") HOSTNAME = os.environ.get("HOSTNAME") PORT = os.environ.get("PORT") app_id = os.environ.get("APP_ID") access_key = os.environ.get("ACCESS_KEY") def uplink_callback(msg, client):
64
64
24
8
56
didx-xyz/pypeerdid
bitlinq_peerdid/old_test_scripts/ttn_api_gw.py
Python
uplink_callback
uplink_callback
21
23
21
21
94ad1713cfd5039aa4f70a53fe343aac7ccf6b33
bigcode/the-stack
train
2b8207539683339a3ca02fef
train
function
def deck_list(ctx, organization_id: str = None, project_id: str = None) -> Union[None, str]: # GraphQL try: graph_ql = GraphQL(authentication=ctx.auth) data = graph_ql.query( """ query($organization_id: UUID, $project_id: UUID) { allDecks(organizationId: $...
def deck_list(ctx, organization_id: str = None, project_id: str = None) -> Union[None, str]: # GraphQL
try: graph_ql = GraphQL(authentication=ctx.auth) data = graph_ql.query( """ query($organization_id: UUID, $project_id: UUID) { allDecks(organizationId: $organization_id, projectId: $project_id) { results { title ...
from typing import Union import src.cli.console as console from src.cli.console.input import get_identifier_or_pass from src.context.helper import convert_deck_argument_to_uuid from src.graphql import GraphQL def deck_list(ctx, organization_id: str = None, project_id: str = None) -> Union[None, str]: # GraphQL
74
94
316
31
42
blackappsolutions/cli
src/cli/console/deck.py
Python
deck_list
deck_list
9
57
9
10
a26317701037de5e1c3b6e388c05bd7dc5b47a1b
bigcode/the-stack
train
2d6bbfe3abfef7ea54c38a14
train
class
class Gitlab(GitServer): tokenSpace = 'gitlab' baseUrl = 'https://gitlab.com/api/v4' def open( self, title: str, body: str, fromBranch: Branch, toBranch: Branch ) -> bool: token = self.configPersonal.getToken(self.tokenSpace) if token is not None...
class Gitlab(GitServer):
tokenSpace = 'gitlab' baseUrl = 'https://gitlab.com/api/v4' def open( self, title: str, body: str, fromBranch: Branch, toBranch: Branch ) -> bool: token = self.configPersonal.getToken(self.tokenSpace) if token is not None: projectId =...
from gitcd.git.server import GitServer from gitcd.git.branch import Branch from gitcd.exceptions import GitcdGithubApiException import requests class Gitlab(GitServer):
38
256
1,356
7
30
pchr-srf/gitcd
gitcd/git/server/gitlab.py
Python
Gitlab
Gitlab
9
221
9
10
3ac7dbe36a7fde5529dd46eab5261081eddd8c20
bigcode/the-stack
train
76b6d1ad7db17d7e3d3fc2ee
train
function
def _any_start_rule(tag, rules): "Return any rule that has the given tag as a start tag or None" try: return next(rule for rule in rules if rule.is_starttag(tag)) except StopIteration: return None
def _any_start_rule(tag, rules):
"Return any rule that has the given tag as a start tag or None" try: return next(rule for rule in rules if rule.is_starttag(tag)) except StopIteration: return None
taking a list of all tags except the end tag. """ def is_starttag(self, tag): return tag.__class__ == self.startcls def is_endtag(self, tag): return tag.__class__ == self.endcls def _any_start_rule(tag, rules):
64
64
53
9
54
ulikoehler/ODBPy
ODBPy/Treeifier.py
Python
_any_start_rule
_any_start_rule
37
42
37
37
2446dc435bca540f9b21a30a5f2cecb9f0ff265e
bigcode/the-stack
train
2fed383c9d2d6a3d3c771623
train
class
class TreeifierRule(namedtuple("TreeifierRule", ["startcls", "endcls", "function"])): """ A rule for the treefier that idenfies the start and corresponding end element of a nested structure. Once the end tag is encountered, the unary "function" is executed taking a list of all tags except the e...
class TreeifierRule(namedtuple("TreeifierRule", ["startcls", "endcls", "function"])):
""" A rule for the treefier that idenfies the start and corresponding end element of a nested structure. Once the end tag is encountered, the unary "function" is executed taking a list of all tags except the end tag. """ def is_starttag(self, tag): return tag.__class__ == self.s...
every time and end tag is encountered, the innermost element is processed on the fly. """ from collections import namedtuple, deque __all__ = ["TreeifierRule", "treeify"] class TreeifierRule(namedtuple("TreeifierRule", ["startcls", "endcls", "function"])):
64
64
122
23
41
ulikoehler/ODBPy
ODBPy/Treeifier.py
Python
TreeifierRule
TreeifierRule
23
34
23
23
584ea03671067cd70cbe01b14fa51133bb62ac1c
bigcode/the-stack
train
a33472b801c0c0dc7f9627ac
train
function
def treeify(tags, rules): """ From a flattened list of tag-like objects (i.e. parsed lines) generate a nested tree by using start-tag/end-tag rule pairs. """ hierarchy = deque() elementlist = deque([[]]) # Contains toplevel element list for tag in tags: # Check if this is an end tag ...
def treeify(tags, rules):
""" From a flattened list of tag-like objects (i.e. parsed lines) generate a nested tree by using start-tag/end-tag rule pairs. """ hierarchy = deque() elementlist = deque([[]]) # Contains toplevel element list for tag in tags: # Check if this is an end tag if len(hierarchy) ...
class__ == self.endcls def _any_start_rule(tag, rules): "Return any rule that has the given tag as a start tag or None" try: return next(rule for rule in rules if rule.is_starttag(tag)) except StopIteration: return None def treeify(tags, rules):
67
67
225
7
59
ulikoehler/ODBPy
ODBPy/Treeifier.py
Python
treeify
treeify
45
69
45
45
5e20bf50e40a01fdc2332e00943da85a2149c8b1
bigcode/the-stack
train
2cac855fe0bb8d10de2a0200
train
class
class AnnouncementAPI(APIView): def get(self, request): announcements = Announcement1.objects.filter(visible=True) return self.success(self.paginate_data(request, announcements, AnnouncementSerializer))
class AnnouncementAPI(APIView):
def get(self, request): announcements = Announcement1.objects.filter(visible=True) return self.success(self.paginate_data(request, announcements, AnnouncementSerializer))
from utils.api import APIView from companyAnnounce1.models import Announcement1 from companyAnnounce1.serializers import AnnouncementSerializer class AnnouncementAPI(APIView):
34
64
39
6
27
scintiller/OnlineJudge
companyAnnounce1/views/oj.py
Python
AnnouncementAPI
AnnouncementAPI
7
10
7
7
f08f674f15781139547a5860d8a98f6d2259da69
bigcode/the-stack
train
c0bb14ffc060c9a07d9bdde8
train
class
class MurphiTokens: ssp_prefix = "SSP_" mutex = "mutex" defaccess = "none" defload = "load" defstore = "store" defval = "undefined" defset = "undefine" statesuf = "s_" vectorsuf = "v_" countsuf = "cnt_" instsuf = "i_" TemplateDir = "MurphiTemp" fconst = "const.m" ...
class MurphiTokens:
ssp_prefix = "SSP_" mutex = "mutex" defaccess = "none" defload = "load" defstore = "store" defval = "undefined" defset = "undefine" statesuf = "s_" vectorsuf = "v_" countsuf = "cnt_" instsuf = "i_" TemplateDir = "MurphiTemp" fconst = "const.m" # Lock framewor...
class MurphiTokens:
5
256
1,481
5
0
icsa-caps/HieraGen
Murphi/ModularMurphi/MurphiTokens.py
Python
MurphiTokens
MurphiTokens
1
202
1
1
2fc22f168be7eab526978939c2074466d33fcef0
bigcode/the-stack
train
45e7118faa94bc846289852e
train
function
def generate(hop_size=256): while True: shuffled = sklearn.utils.shuffle(files) for f in shuffled: with open(f, 'rb') as fopen: wav, f0, mel = pickle.load(fopen) batch_max_steps = random.randint(16384, 55125) batch_max_frames = batch_max_steps // ...
def generate(hop_size=256):
while True: shuffled = sklearn.utils.shuffle(files) for f in shuffled: with open(f, 'rb') as fopen: wav, f0, mel = pickle.load(fopen) batch_max_steps = random.randint(16384, 55125) batch_max_frames = batch_max_steps // hop_size if len...
') sr = 22050 def pad_seq(x, base=8): len_out = int(base * ceil(float(x.shape[0]) / base)) len_pad = len_out - x.shape[0] assert len_pad >= 0 return np.pad(x, ((0, len_pad), (0, 0)), 'constant'), x.shape[0] def generate(hop_size=256):
87
87
291
8
79
ishine/malaya-speech
pretrained-model/speechsplit-conversion/speechsplit.py
Python
generate
generate
29
62
29
29
72234dfd002e348abb0f336d851c041491f2d834
bigcode/the-stack
train
660fe303ce84348e63d9bb8d
train
function
def pad_seq(x, base=8): len_out = int(base * ceil(float(x.shape[0]) / base)) len_pad = len_out - x.shape[0] assert len_pad >= 0 return np.pad(x, ((0, len_pad), (0, 0)), 'constant'), x.shape[0]
def pad_seq(x, base=8):
len_out = int(base * ceil(float(x.shape[0]) / base)) len_pad = len_out - x.shape[0] assert len_pad >= 0 return np.pad(x, ((0, len_pad), (0, 0)), 'constant'), x.shape[0]
aya_speech import train import malaya_speech import sklearn import pickle speaker_model = malaya_speech.speaker_vector.deep_model('vggvox-v2') files = glob('speechsplit-dataset/*.pkl') sr = 22050 def pad_seq(x, base=8):
64
64
72
9
54
ishine/malaya-speech
pretrained-model/speechsplit-conversion/speechsplit.py
Python
pad_seq
pad_seq
22
26
22
22
43d73084d403780435731906f34fadf2fb19f06f
bigcode/the-stack
train
46b151c7e185933225fb4fda
train
function
def model_fn(features, labels, mode, params): vectors = features['v'] X = features['mel'] len_X = features['mel_length'][:, 0] X_f0 = features['f0'] len_X_f0 = features['f0_length'][:, 0] hparams = speechsplit.hparams interplnr = speechsplit.InterpLnr(hparams) model = speechsplit.Model(h...
def model_fn(features, labels, mode, params):
vectors = features['v'] X = features['mel'] len_X = features['mel_length'][:, 0] X_f0 = features['f0'] len_X_f0 = features['f0_length'][:, 0] hparams = speechsplit.hparams interplnr = speechsplit.InterpLnr(hparams) model = speechsplit.Model(hparams) model_F0 = speechsplit.Model_F0(hp...
={ 'audio': tf.TensorShape([None]), 'mel': tf.TensorShape([None, 80]), 'mel_length': tf.TensorShape([None]), 'f0': tf.TensorShape([None, 1]), 'f0_length': tf.TensorShape([None]), 'v': tf.TensorShape([512]), }, ...
195
195
653
11
183
ishine/malaya-speech
pretrained-model/speechsplit-conversion/speechsplit.py
Python
model_fn
model_fn
114
181
114
114
0366de5086480eabe95aa1280067e1693bd2e7b4
bigcode/the-stack
train
124fd5c78cf5788abf393b35
train
function
def get_dataset(batch_size=4): def get(): dataset = tf.data.Dataset.from_generator( generate, { 'mel': tf.float32, 'mel_length': tf.int32, 'f0': tf.float32, 'f0_length': tf.int32, 'audio': tf.float32, ...
def get_dataset(batch_size=4):
def get(): dataset = tf.data.Dataset.from_generator( generate, { 'mel': tf.float32, 'mel_length': tf.int32, 'f0': tf.float32, 'f0_length': tf.int32, 'audio': tf.float32, 'v': tf.float32, ...
pad_seq(f0) wav_16k = malaya_speech.resample(wav, sr, 16000) v = speaker_model([wav_16k])[0] v = v / v.max() yield { 'mel': mel, 'mel_length': [len(mel)], 'f0': f0, 'f0_length': [len(f0)], ...
107
107
358
8
99
ishine/malaya-speech
pretrained-model/speechsplit-conversion/speechsplit.py
Python
get_dataset
get_dataset
65
108
65
65
1e9928586843ff3d578763318130f107d9676156
bigcode/the-stack
train
2b56dcc9df9f176dc6223adc
train
class
class TestUpdater(TestCase): def setUp(self): self.sentry_app = self.create_sentry_app() self.service_hook = self.create_service_hook( application=self.sentry_app.application ) self.updater = Updater(service_hook=self.service_hook) def test_updates_application(self)...
class TestUpdater(TestCase):
def setUp(self): self.sentry_app = self.create_sentry_app() self.service_hook = self.create_service_hook( application=self.sentry_app.application ) self.updater = Updater(service_hook=self.service_hook) def test_updates_application(self): app = self.create_s...
from __future__ import absolute_import from sentry.mediators.service_hooks import Updater from sentry.testutils import TestCase class TestUpdater(TestCase):
35
78
260
6
28
detouched/sentry
tests/sentry/mediators/service_hooks/test_updater.py
Python
TestUpdater
TestUpdater
7
42
7
7
1a71474d0db4ad24359c8b3595448e3d7889ba2f
bigcode/the-stack
train
d820d91f73e085c083d691a8
train
class
class ManafaMethodCoverageAnalyzer(AbstractAnalyzer): """Implements AbstractAnalyzer interface to allow analyze results with EManafa profiler. Calculate statistics about the produced results to analyze, validate and characterize executions. """ def __init__(self, profiler): self.supported_filte...
class ManafaMethodCoverageAnalyzer(AbstractAnalyzer):
"""Implements AbstractAnalyzer interface to allow analyze results with EManafa profiler. Calculate statistics about the produced results to analyze, validate and characterize executions. """ def __init__(self, profiler): self.supported_filters = {"method_coverage"} super(ManafaMethodCov...
import json import os from anadroid.results_analysis.AbstractAnalyzer import AbstractAnalyzer from anadroid.utils.Utils import loge, mega_find class ManafaMethodCoverageAnalyzer(AbstractAnalyzer):
40
256
1,225
9
30
greensoftwarelab/PyAnaDroid
anadroid/results_analysis/ManafaMethodCoverageAnalyzer.py
Python
ManafaMethodCoverageAnalyzer
ManafaMethodCoverageAnalyzer
8
136
8
8
9a8e4247150562201353a75fa8cc9128000c076a
bigcode/the-stack
train
1f80c89ea0587f057621d4b0
train
class
class FlaxAutoModelForNextSentencePrediction(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING
class FlaxAutoModelForNextSentencePrediction(_BaseAutoModelClass):
_model_mapping = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING
MultipleChoice(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING FlaxAutoModelForMultipleChoice = auto_class_update(FlaxAutoModelForMultipleChoice, head_doc="multiple choice") class FlaxAutoModelForNextSentencePrediction(_BaseAutoModelClass):
64
64
33
15
49
liminghao1630/transformers
src/transformers/models/auto/modeling_flax_auto.py
Python
FlaxAutoModelForNextSentencePrediction
FlaxAutoModelForNextSentencePrediction
280
281
280
280
f7872a6164ebf6a04952309053aed768aaad3ec0
bigcode/the-stack
train
cc784f03b686290042c8f3b1
train
class
class FlaxAutoModelForVision2Seq(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING
class FlaxAutoModelForVision2Seq(_BaseAutoModelClass):
_model_mapping = FLAX_MODEL_FOR_VISION_2_SEQ_MAPPING
Classification(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING FlaxAutoModelForImageClassification = auto_class_update( FlaxAutoModelForImageClassification, head_doc="image classification" ) class FlaxAutoModelForVision2Seq(_BaseAutoModelClass):
64
64
31
15
49
liminghao1630/transformers
src/transformers/models/auto/modeling_flax_auto.py
Python
FlaxAutoModelForVision2Seq
FlaxAutoModelForVision2Seq
298
299
298
298
6bbe289f9df5a600f30d129eef011c841bad9a9a
bigcode/the-stack
train
9e1972c0d005e81b4eb2f9e2
train
class
class FlaxAutoModelForPreTraining(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_FOR_PRETRAINING_MAPPING
class FlaxAutoModelForPreTraining(_BaseAutoModelClass):
_model_mapping = FLAX_MODEL_FOR_PRETRAINING_MAPPING
FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) class FlaxAutoModel(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_MAPPING FlaxAutoModel = auto_class_update(FlaxAutoModel) class FlaxAutoModelForPreTraining(_BaseAutoModelClass):
64
64
28
14
50
liminghao1630/transformers
src/transformers/models/auto/modeling_flax_auto.py
Python
FlaxAutoModelForPreTraining
FlaxAutoModelForPreTraining
218
219
218
218
8c32c4410c5c0c2ea6c89896e10b6fb7e70be402
bigcode/the-stack
train
3d358e8ad273cc660d6f6406
train
class
class FlaxAutoModel(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_MAPPING
class FlaxAutoModel(_BaseAutoModelClass):
_model_mapping = FLAX_MODEL_MAPPING
_MAPPING_NAMES, FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES ) FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING = _LazyAutoMapping( CONFIG_MAPPING_NAMES, FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES ) class FlaxAutoModel(_BaseAutoModelClass):
64
64
21
11
53
liminghao1630/transformers
src/transformers/models/auto/modeling_flax_auto.py
Python
FlaxAutoModel
FlaxAutoModel
211
212
211
211
bcded07c585623ef5aa060be219e520e503dc20d
bigcode/the-stack
train
19746c13dffe533d1a4c009c
train
class
class FlaxAutoModelForSequenceClassification(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
class FlaxAutoModelForSequenceClassification(_BaseAutoModelClass):
_model_mapping = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
USAL_LM_MAPPING FlaxAutoModelForSeq2SeqLM = auto_class_update( FlaxAutoModelForSeq2SeqLM, head_doc="sequence-to-sequence language modeling", checkpoint_for_example="t5-base" ) class FlaxAutoModelForSequenceClassification(_BaseAutoModelClass):
64
64
28
14
50
liminghao1630/transformers
src/transformers/models/auto/modeling_flax_auto.py
Python
FlaxAutoModelForSequenceClassification
FlaxAutoModelForSequenceClassification
248
249
248
248
e29b5b3d8f72217c98d5815a2eadf39c13358e2e
bigcode/the-stack
train
e72aad913e8f66a7ac85ad06
train
class
class FlaxAutoModelForQuestionAnswering(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING
class FlaxAutoModelForQuestionAnswering(_BaseAutoModelClass):
_model_mapping = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING
Classification(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING FlaxAutoModelForSequenceClassification = auto_class_update( FlaxAutoModelForSequenceClassification, head_doc="sequence classification" ) class FlaxAutoModelForQuestionAnswering(_BaseAutoModelClass):
64
64
31
15
49
liminghao1630/transformers
src/transformers/models/auto/modeling_flax_auto.py
Python
FlaxAutoModelForQuestionAnswering
FlaxAutoModelForQuestionAnswering
257
258
257
257
f8db87ebb51171f119810fbd9b189848671a794e
bigcode/the-stack
train
06389d0c532472745aae196a
train
class
class FlaxAutoModelForMaskedLM(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_FOR_MASKED_LM_MAPPING
class FlaxAutoModelForMaskedLM(_BaseAutoModelClass):
_model_mapping = FLAX_MODEL_FOR_MASKED_LM_MAPPING
AutoModelClass): _model_mapping = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING FlaxAutoModelForCausalLM = auto_class_update(FlaxAutoModelForCausalLM, head_doc="causal language modeling") class FlaxAutoModelForMaskedLM(_BaseAutoModelClass):
64
64
29
14
50
liminghao1630/transformers
src/transformers/models/auto/modeling_flax_auto.py
Python
FlaxAutoModelForMaskedLM
FlaxAutoModelForMaskedLM
232
233
232
232
81c120de6c9aff0d77defde2295aaf5775faff3e
bigcode/the-stack
train
ba999f68302d9bbf3fd07b9b
train
class
class FlaxAutoModelForTokenClassification(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING
class FlaxAutoModelForTokenClassification(_BaseAutoModelClass):
_model_mapping = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING
(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_FOR_QUESTION_ANSWERING_MAPPING FlaxAutoModelForQuestionAnswering = auto_class_update(FlaxAutoModelForQuestionAnswering, head_doc="question answering") class FlaxAutoModelForTokenClassification(_BaseAutoModelClass):
64
64
28
14
50
liminghao1630/transformers
src/transformers/models/auto/modeling_flax_auto.py
Python
FlaxAutoModelForTokenClassification
FlaxAutoModelForTokenClassification
264
265
264
264
720950c38050497a3d86319437e4a8ea3bc4ea53
bigcode/the-stack
train
1561d2855228cb42a5aeabe4
train
class
class FlaxAutoModelForImageClassification(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
class FlaxAutoModelForImageClassification(_BaseAutoModelClass):
_model_mapping = FLAX_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
): _model_mapping = FLAX_MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING FlaxAutoModelForNextSentencePrediction = auto_class_update( FlaxAutoModelForNextSentencePrediction, head_doc="next sentence prediction" ) class FlaxAutoModelForImageClassification(_BaseAutoModelClass):
64
64
28
14
50
liminghao1630/transformers
src/transformers/models/auto/modeling_flax_auto.py
Python
FlaxAutoModelForImageClassification
FlaxAutoModelForImageClassification
289
290
289
289
a9d34a73a494129241cc289d78222fe03099c442
bigcode/the-stack
train
8e4a6ded8cb2f5161e53784d
train
class
class FlaxAutoModelForMultipleChoice(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING
class FlaxAutoModelForMultipleChoice(_BaseAutoModelClass):
_model_mapping = FLAX_MODEL_FOR_MULTIPLE_CHOICE_MAPPING
TokenClassification(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING FlaxAutoModelForTokenClassification = auto_class_update( FlaxAutoModelForTokenClassification, head_doc="token classification" ) class FlaxAutoModelForMultipleChoice(_BaseAutoModelClass):
64
64
29
14
50
liminghao1630/transformers
src/transformers/models/auto/modeling_flax_auto.py
Python
FlaxAutoModelForMultipleChoice
FlaxAutoModelForMultipleChoice
273
274
273
273
6531bee8fb72fc69874810ad445b87f5a8eecd39
bigcode/the-stack
train
08d1ccefe60ef9cf05b2162a
train
class
class FlaxAutoModelForCausalLM(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING
class FlaxAutoModelForCausalLM(_BaseAutoModelClass):
_model_mapping = FLAX_MODEL_FOR_CAUSAL_LM_MAPPING
ForPreTraining(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_FOR_PRETRAINING_MAPPING FlaxAutoModelForPreTraining = auto_class_update(FlaxAutoModelForPreTraining, head_doc="pretraining") class FlaxAutoModelForCausalLM(_BaseAutoModelClass):
64
64
31
15
49
liminghao1630/transformers
src/transformers/models/auto/modeling_flax_auto.py
Python
FlaxAutoModelForCausalLM
FlaxAutoModelForCausalLM
225
226
225
225
b9e10350625e4a50d853e22b16e7e48a38dcae83
bigcode/the-stack
train
c6e21d1a4598c8f455fe024b
train
class
class FlaxAutoModelForSeq2SeqLM(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
class FlaxAutoModelForSeq2SeqLM(_BaseAutoModelClass):
_model_mapping = FLAX_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
(_BaseAutoModelClass): _model_mapping = FLAX_MODEL_FOR_MASKED_LM_MAPPING FlaxAutoModelForMaskedLM = auto_class_update(FlaxAutoModelForMaskedLM, head_doc="masked language modeling") class FlaxAutoModelForSeq2SeqLM(_BaseAutoModelClass):
64
64
35
16
48
liminghao1630/transformers
src/transformers/models/auto/modeling_flax_auto.py
Python
FlaxAutoModelForSeq2SeqLM
FlaxAutoModelForSeq2SeqLM
239
240
239
239
f3b5c6194b0414cf9f49a424a131e47b553dc001
bigcode/the-stack
train
18bea6e6398ddf8ac9c7ede6
train
function
def shape(fig, alpha, color, edge_c, edge_w, grid, sides, edges, multi_pi, radius, height): # Definition of x def x_(u, v): x = u return x # Definition of y def y_(u, v): y = (a * cos(v)) / u return y # Definition of z def z_(u, v): z = (a * sin(v)) /u return z a = radius # changes radius of the ...
def shape(fig, alpha, color, edge_c, edge_w, grid, sides, edges, multi_pi, radius, height): # Definition of x
def x_(u, v): x = u return x # Definition of y def y_(u, v): y = (a * cos(v)) / u return y # Definition of z def z_(u, v): z = (a * sin(v)) /u return z a = radius # changes radius of the entire thing h = height # Value of the angles s = sides u = linspace(1, h, s + 1) v = linspace(0, 2 * pi...
# A Gabriel's Horn, brought to you by PharaohCola13 import mpl_toolkits.mplot3d.axes3d as p3 import matplotlib.pyplot as plt from matplotlib import * from numpy import * from mpl_toolkits.mplot3d.art3d import * from matplotlib.animation import * name = "Gabriel's-Horn" def shape(fig, alpha, color, edge_c, edge_w, gri...
104
109
364
33
71
gitter-badger/GeoMetrics
src/GUI/compile_space/gabriel_horn.py
Python
shape
shape
12
64
12
13
dc5276c87a367e2d6d1c9abecc125bee1de2bc10
bigcode/the-stack
train
f058f1eb3c4f725b1d523149
train
function
def init_unix_connection_engine( db_user: str, db_pass: str, db_name: str, instance_connection_name: str, db_socket_dir: str, ) -> sqlalchemy.engine.base.Engine: # Remember - storing secrets in plaintext is potentially unsafe. Consider using # something like https://cloud.google.com/secret-m...
def init_unix_connection_engine( db_user: str, db_pass: str, db_name: str, instance_connection_name: str, db_socket_dir: str, ) -> sqlalchemy.engine.base.Engine: # Remember - storing secrets in plaintext is potentially unsafe. Consider using # something like https://cloud.google.com/secret-m...
pool = sqlalchemy.create_engine( # Equivalent URL: # mpostgresql+pg8000://<db_user>:<db_pass>@/<db_name>?unix_socket=<socket_path>/<cloud_sql_instance_name> sqlalchemy.engine.url.URL.create( drivername="postgresql+pg8000", username=db_user, # e.g. "my-database-user" ...
def init_unix_connection_engine( db_user: str, db_pass: str, db_name: str, instance_connection_name: str, db_socket_dir: str, ) -> sqlalchemy.engine.base.Engine: # Remember - storing secrets in plaintext is potentially unsafe. Consider using # something like https://cloud.google.com/secret-m...
85
82
276
85
0
InstantDomain/python-docs-samples
cloud-sql/postgres/client-side-encryption/snippets/cloud_sql_connection_pool.py
Python
init_unix_connection_engine
init_unix_connection_engine
46
73
46
56
b1416f34badeb90185cc515c6392792d6c5be9d5
bigcode/the-stack
train
ed592939dc6eeb2c97484083
train
function
def init_db( db_user: str, db_pass: str, db_name: str, table_name: str, instance_connection_name: str = None, db_socket_dir: str = None, db_host: str = None, ) -> sqlalchemy.engine.base.Engine: if db_host: db = init_tcp_connection_engine(db_user, db_pass, db_name, db_host) e...
def init_db( db_user: str, db_pass: str, db_name: str, table_name: str, instance_connection_name: str = None, db_socket_dir: str = None, db_host: str = None, ) -> sqlalchemy.engine.base.Engine:
if db_host: db = init_tcp_connection_engine(db_user, db_pass, db_name, db_host) else: db = init_unix_connection_engine( db_user, db_pass, db_name, instance_connection_name, db_socket_dir ) # Create tables (if they don't already exist) with db.connect() as conn: ...
return pool def init_db( db_user: str, db_pass: str, db_name: str, table_name: str, instance_connection_name: str = None, db_socket_dir: str = None, db_host: str = None, ) -> sqlalchemy.engine.base.Engine:
64
64
216
61
2
InstantDomain/python-docs-samples
cloud-sql/postgres/client-side-encryption/snippets/cloud_sql_connection_pool.py
Python
init_db
init_db
76
103
76
85
045deafee25924021f357573ec1c18f8003069a9
bigcode/the-stack
train
e41307d939ea3bde300b03e1
train
function
def init_tcp_connection_engine( db_user: str, db_pass: str, db_name: str, db_host: str ) -> sqlalchemy.engine.base.Engine: # Remember - storing secrets in plaintext is potentially unsafe. Consider using # something like https://cloud.google.com/secret-manager/docs/overview to help keep # secrets secret....
def init_tcp_connection_engine( db_user: str, db_pass: str, db_name: str, db_host: str ) -> sqlalchemy.engine.base.Engine: # Remember - storing secrets in plaintext is potentially unsafe. Consider using # something like https://cloud.google.com/secret-manager/docs/overview to help keep # secrets secret....
host_args = db_host.split(":") db_hostname, db_port = host_args[0], int(host_args[1]) pool = sqlalchemy.create_engine( # Equivalent URL: # postgresql+pg8000://<db_user>:<db_pass>@<db_host>:<db_port>/<db_name> sqlalchemy.engine.url.URL.create( drivername="postgresql+pg800...
def init_tcp_connection_engine( db_user: str, db_pass: str, db_name: str, db_host: str ) -> sqlalchemy.engine.base.Engine: # Remember - storing secrets in plaintext is potentially unsafe. Consider using # something like https://cloud.google.com/secret-manager/docs/overview to help keep # secrets secret....
83
79
265
83
0
InstantDomain/python-docs-samples
cloud-sql/postgres/client-side-encryption/snippets/cloud_sql_connection_pool.py
Python
init_tcp_connection_engine
init_tcp_connection_engine
19
43
19
26
f1796e86b57cc83485283238513aefd3198ad828
bigcode/the-stack
train
e8ac0f9fd84ec6806bf12bac
train
class
class TestDungeons(TestVanillaOWG): def testFirstDungeonChests(self): self.run_location_tests([ ["Hyrule Castle - Map Chest", True, []], ["Sanctuary", True, []], ["Sewers - Secret Room - Left", False, []], ["Sewers - Secret Room - Left", True, ['Progressive...
class TestDungeons(TestVanillaOWG):
def testFirstDungeonChests(self): self.run_location_tests([ ["Hyrule Castle - Map Chest", True, []], ["Sanctuary", True, []], ["Sewers - Secret Room - Left", False, []], ["Sewers - Secret Room - Left", True, ['Progressive Glove']], ["Sewers - Sec...
from test.owg.TestVanillaOWG import TestVanillaOWG class TestDungeons(TestVanillaOWG):
27
256
2,399
10
16
RoflCopter69/MultiWorld-Utilities
test/owg/TestDungeons.py
Python
TestDungeons
TestDungeons
4
131
4
5
d1b80ae6ce21bb2ebb71d510a855d2baba68bd0e
bigcode/the-stack
train
c55fac6b604d82849f42a9f5
train
class
class DueDiligenceController(BaseController): """Due Diligence Controller class""" CHOICES_COMMANDS = ["load", "oi", "active", "change", "nonzero", "eb"] SPECIFIC_CHOICES = { "cp": [ "events", "twitter", "ex", "mkt", "ps", "ba...
class DueDiligenceController(BaseController):
"""Due Diligence Controller class""" CHOICES_COMMANDS = ["load", "oi", "active", "change", "nonzero", "eb"] SPECIFIC_CHOICES = { "cp": [ "events", "twitter", "ex", "mkt", "ps", "basic", ], "cg": [ "...
List from datetime import datetime, timedelta import pandas as pd from prompt_toolkit.completion import NestedCompleter from gamestonk_terminal.rich_config import console from gamestonk_terminal.parent_classes import BaseController from gamestonk_terminal.cryptocurrency.due_diligence import ( coinglass_model, ...
255
256
7,923
9
246
JakubPluta/GamestonkTerminal
gamestonk_terminal/cryptocurrency/due_diligence/dd_controller.py
Python
DueDiligenceController
DueDiligenceController
44
1,210
44
44
5e8bcaf6fdb6a5c2930dacc7a38b8a3eb6b4ba5e
bigcode/the-stack
train
9d60f71ef362f5f23fa015ba
train
class
class icons: logo = b'x\xda-V\xc7\x1a\xa20\x10~ \x0f\x02\x02\xcaa\x0f\t\xbd7A\xe0&-A\xaa\x14\x01\x9f~q\xbf\r\x04\xc8\xf4\xf9g\x92\x8f*\x84\xb6\xb7\x12\xba\x8czp\x0c\xcb\x0f\xb0\x18\xa0\xe3Kv\x8f\x07\xacy`\xfe\xde\x8a#\x87\xedO\x00\xca9\xbc\x07"\x00\x86\xec\xf0\xe7\r\xc3\x9f\x18\x90\xbeA\x9d\xf3@\xbf\xda\x8a]\x1fk\xa...
class icons:
logo = b'x\xda-V\xc7\x1a\xa20\x10~ \x0f\x02\x02\xcaa\x0f\t\xbd7A\xe0&-A\xaa\x14\x01\x9f~q\xbf\r\x04\xc8\xf4\xf9g\x92\x8f*\x84\xb6\xb7\x12\xba\x8czp\x0c\xcb\x0f\xb0\x18\xa0\xe3Kv\x8f\x07\xacy`\xfe\xde\x8a#\x87\xedO\x00\xca9\xbc\x07"\x00\x86\xec\xf0\xe7\r\xc3\x9f\x18\x90\xbeA\x9d\xf3@\xbf\xda\x8a]\x1fk\xa3\x0f\xc4-\xf0...
except OSError: temp_dir = Path(Path(__file__).parent.resolve(), 'temp') os.mkdir(temp_dir+'\\Whirledit\\') configuration = """ Key Bindings: Close: <Control-w> Fullscreen: <F11> New: <Control-n> Open: <Control-o> Open cmd: <Control-Shift-t> Run: <F5> Save: <Control-s> Lo...
256
256
3,086
3
252
Redysz/WhirlEdit
data.py
Python
icons
icons
50
62
50
50
7f419e3f4e74810a00faed807ae0b6bb381ec775
bigcode/the-stack
train
0ad75d375d38ea12bde7653d
train
function
def execute_testcase(testcase, session=None, request_options={}): """ Executes a testcase """ # Construct a new session if one has not been provided, whose scope will# # only last through this testcase if not session: session = requests.Session() # Set a default User-Agent (this ca...
def execute_testcase(testcase, session=None, request_options={}):
""" Executes a testcase """ # Construct a new session if one has not been provided, whose scope will# # only last through this testcase if not session: session = requests.Session() # Set a default User-Agent (this can be overriden by user options) headers = { "User-Agen...
from __future__ import absolute_import, division, print_function, with_statement, unicode_literals import catnap import requests # Python2/3 compatible way of coercing values to unicode via str() try: str = unicode except NameError: pass def execute_testcase(testcase, session=None, request_options={}):
70
190
634
14
55
dailymuse/catnap
catnap/worker.py
Python
execute_testcase
execute_testcase
12
89
12
12
dd276d536a590bf677dda38e830bf6931b2ba289
bigcode/the-stack
train
902c6a3675f5fba663185800
train
function
def _get_defun_inputs_from_args(args, names, flat_shapes=None): """Maps Python function positional args to graph-construction inputs.""" return _get_defun_inputs( args, names, structure=args, flat_shapes=flat_shapes)
def _get_defun_inputs_from_args(args, names, flat_shapes=None):
"""Maps Python function positional args to graph-construction inputs.""" return _get_defun_inputs( args, names, structure=args, flat_shapes=flat_shapes)
shape = value.shape with ops.control_dependencies(None): placeholder = graph_placeholder( dtype=dtype or value.dtype, shape=shape, name=name) custom_gradient.copy_handle_data(value, placeholder) return placeholder def _get_defun_inputs_from_args(args, names, flat_shapes=None):
64
64
51
16
47
RickeyEstes/tensorflow
tensorflow/python/framework/func_graph.py
Python
_get_defun_inputs_from_args
_get_defun_inputs_from_args
1,145
1,148
1,145
1,145
6f26d05dff979d32146b29876942898bad449e3e
bigcode/the-stack
train
7d90f4ae2b86f0d6a54f1231
train
function
def pack_sequence_as(structure, flat_sequence): """Like `nest.pack_sequence_as` but also builds TensorArrays from flows. Args: structure: The structure to pack into. May contain Tensors, CompositeTensors, or TensorArrays. flat_sequence: An iterable containing tensors. Returns: A nested structu...
def pack_sequence_as(structure, flat_sequence):
"""Like `nest.pack_sequence_as` but also builds TensorArrays from flows. Args: structure: The structure to pack into. May contain Tensors, CompositeTensors, or TensorArrays. flat_sequence: An iterable containing tensors. Returns: A nested structure. Raises: AssertionError if `structure`...
nest.flatten(sequence, expand_composites=True) return [ item.flow if isinstance(item, tensor_array_ops.TensorArray) else item for item in flat_sequence] # TODO(edloper): If TensorArray becomes a CompositeTensor, then delete this. def pack_sequence_as(structure, flat_sequence):
64
64
211
10
54
RickeyEstes/tensorflow
tensorflow/python/framework/func_graph.py
Python
pack_sequence_as
pack_sequence_as
1,107
1,129
1,107
1,107
41ed6836d9ea469f54296661cca00438207d3ab1
bigcode/the-stack
train
d1ba3dc873c6956d80589976
train
function
def maybe_captured(tensor): """If t is a captured value placeholder, returns the original captured value. Args: tensor: Tensor. Returns: A tensor, potentially from a different Graph/FuncGraph. """ if (not isinstance(tensor, ops.EagerTensor) and tensor.op.graph.building_function and tensor.op.t...
def maybe_captured(tensor):
"""If t is a captured value placeholder, returns the original captured value. Args: tensor: Tensor. Returns: A tensor, potentially from a different Graph/FuncGraph. """ if (not isinstance(tensor, ops.EagerTensor) and tensor.op.graph.building_function and tensor.op.type == "Placeholder"): f...
None) func_graph.variables = variables if add_control_dependencies: func_graph.control_outputs.extend(deps_control_manager.ops_which_must_run) func_graph.collective_manager_ids_used = ( deps_control_manager.collective_manager_ids_used) return func_graph def maybe_captured(tensor):
64
64
122
7
56
RickeyEstes/tensorflow
tensorflow/python/framework/func_graph.py
Python
maybe_captured
maybe_captured
1,046
1,061
1,046
1,046
825cbecfb64aa5f7f613241c6b1548ddf9eea6f3
bigcode/the-stack
train
7fae1c1e6688fe75870e16ea
train
function
def dismantle_func_graph(func_graph): """Removes reference cycles in `func_graph` FuncGraph. Helpful for making sure the garbage collector doesn't need to run when the FuncGraph goes out of scope, e.g. in tests using defun with @test_util.run_in_graph_and_eager_modes(assert_no_eager_garbage=True). Args: ...
def dismantle_func_graph(func_graph):
"""Removes reference cycles in `func_graph` FuncGraph. Helpful for making sure the garbage collector doesn't need to run when the FuncGraph goes out of scope, e.g. in tests using defun with @test_util.run_in_graph_and_eager_modes(assert_no_eager_garbage=True). Args: func_graph: A `FuncGraph` object to d...
args to graph-construction inputs.""" if kwargs: names, args = zip(*sorted(kwargs.items())) else: names = [] args = [] return _get_defun_inputs( args, names, structure=kwargs, flat_shapes=flat_shapes) def dismantle_func_graph(func_graph):
64
64
124
8
56
RickeyEstes/tensorflow
tensorflow/python/framework/func_graph.py
Python
dismantle_func_graph
dismantle_func_graph
1,281
1,293
1,281
1,281
59b270d4a63fa89884af3672ca416c3b65efab41
bigcode/the-stack
train
d8366e4847fa692d998dfbf7
train
function
def _create_substitute_placeholder(value, name=None, dtype=None, shape=None): """Creates a placeholder for `value` and propagates shape info to it.""" # Note: setting ops.control_dependencies(None) ensures we always put # capturing placeholders outside of any control flow context. if shape is None: shape = ...
def _create_substitute_placeholder(value, name=None, dtype=None, shape=None):
"""Creates a placeholder for `value` and propagates shape info to it.""" # Note: setting ops.control_dependencies(None) ensures we always put # capturing placeholders outside of any control flow context. if shape is None: shape = value.shape with ops.control_dependencies(None): placeholder = graph_pla...
[i] = tensor_array_ops.build_ta_with_new_flow( old_ta=flattened_structure[i], flow=flat_sequence[i]) return nest.pack_sequence_as(structure, flat_sequence, expand_composites=True) def _create_substitute_placeholder(value, name=None, dtype=None, shape=None):
64
64
114
17
47
RickeyEstes/tensorflow
tensorflow/python/framework/func_graph.py
Python
_create_substitute_placeholder
_create_substitute_placeholder
1,132
1,142
1,132
1,132
86d814727b84d99be6e23f403e98c421431a05fe
bigcode/the-stack
train
b1b15e23f20f6123a5d9f0e9
train
function
def _get_defun_inputs_from_kwargs(kwargs, flat_shapes): """Maps Python function keyword args to graph-construction inputs.""" if kwargs: names, args = zip(*sorted(kwargs.items())) else: names = [] args = [] return _get_defun_inputs( args, names, structure=kwargs, flat_shapes=flat_shapes)
def _get_defun_inputs_from_kwargs(kwargs, flat_shapes):
"""Maps Python function keyword args to graph-construction inputs.""" if kwargs: names, args = zip(*sorted(kwargs.items())) else: names = [] args = [] return _get_defun_inputs( args, names, structure=kwargs, flat_shapes=flat_shapes)
saw arg: '%s', shape: '%s'. args: %s" % (arg, shape, args)) function_inputs.append(arg) return nest.pack_sequence_as(structure, function_inputs, expand_composites=True) def _get_defun_inputs_from_kwargs(kwargs, flat_shapes):
64
64
75
13
51
RickeyEstes/tensorflow
tensorflow/python/framework/func_graph.py
Python
_get_defun_inputs_from_kwargs
_get_defun_inputs_from_kwargs
1,270
1,278
1,270
1,270
db2cd3a43271786c465ead7759597ba83f9249eb
bigcode/the-stack
train
ae7cf425670b60e7c78f2f7a
train
function
def _get_defun_inputs(args, names, structure, flat_shapes=None): """Maps python function args to graph-construction inputs. Args: args: A flat list of user-specified arguments. names: A list of strings with user-specified argument names, same length as `args`. May be `None`, in which case a generic n...
def _get_defun_inputs(args, names, structure, flat_shapes=None):
"""Maps python function args to graph-construction inputs. Args: args: A flat list of user-specified arguments. names: A list of strings with user-specified argument names, same length as `args`. May be `None`, in which case a generic name is used. structure: The original argument list or diction...
]) return nest.pack_sequence_as(structure, flat_sequence, expand_composites=True) def _create_substitute_placeholder(value, name=None, dtype=None, shape=None): """Creates a placeholder for `value` and propagates shape info to it.""" # Note: setting ops.control_dependencies(None) ensures we always put # captur...
256
256
1,073
16
240
RickeyEstes/tensorflow
tensorflow/python/framework/func_graph.py
Python
_get_defun_inputs
_get_defun_inputs
1,157
1,267
1,157
1,157
1e32aefff62150e485d1065e9da27781ca5dca43
bigcode/the-stack
train
23a23b0fd9cc2db65b47ca0e
train
function
def flatten(sequence): """Like nest.flatten w/ expand_composites, but returns flow for TensorArrays. Args: sequence: A nested structure of Tensors, CompositeTensors, and TensorArrays. Returns: A list of tensors. """ flat_sequence = nest.flatten(sequence, expand_composites=True) return [ ...
def flatten(sequence):
"""Like nest.flatten w/ expand_composites, but returns flow for TensorArrays. Args: sequence: A nested structure of Tensors, CompositeTensors, and TensorArrays. Returns: A list of tensors. """ flat_sequence = nest.flatten(sequence, expand_composites=True) return [ item.flow if isinstan...
in zip(nest.flatten(n1, expand_composites=True), nest.flatten(n2, expand_composites=True)): if arg1 is not arg2: raise ValueError(errmsg) # TODO(edloper): If TensorArray becomes a CompositeTensor, then delete this. def flatten(sequence):
64
64
97
4
60
RickeyEstes/tensorflow
tensorflow/python/framework/func_graph.py
Python
flatten
flatten
1,090
1,103
1,090
1,090
e482e6172498cf5263b717c520c2248b42501f21
bigcode/the-stack
train
2e49da2f9a249205fec3c234
train
function
def check_mutation(n1, n2, func): """Check if two list of arguments are exactly the same.""" func_name = getattr(func, "__name__", func) errmsg = ("{}() should not modify its Python input arguments." " Check if it modifies any lists or dicts passed as" " arguments. Modifying a copy is all...
def check_mutation(n1, n2, func):
"""Check if two list of arguments are exactly the same.""" func_name = getattr(func, "__name__", func) errmsg = ("{}() should not modify its Python input arguments." " Check if it modifies any lists or dicts passed as" " arguments. Modifying a copy is allowed.".format(func_name)) try: ...
return tensor def device_stack_has_callable(device_stack): """Checks whether a device stack contains a callable.""" return any(callable(spec._device_name_or_function) # pylint: disable=protected-access for spec in device_stack.peek_objs()) def check_mutation(n1, n2, func):
64
64
179
12
52
RickeyEstes/tensorflow
tensorflow/python/framework/func_graph.py
Python
check_mutation
check_mutation
1,070
1,086
1,070
1,070
f86c3b7384bbb7d4eacd79e7a1d1510d288bb1bf
bigcode/the-stack
train
0ffd0b04e8b7e2d48dc7447f
train
function
def override_func_graph_name_scope(func_graph, name_scope): func_graph._name_stack = name_scope # pylint: disable=protected-access
def override_func_graph_name_scope(func_graph, name_scope):
func_graph._name_stack = name_scope # pylint: disable=protected-access
bage=True). Args: func_graph: A `FuncGraph` object to destroy. `func_graph` is unusable after this function. """ func_graph.clear_captures() ops.dismantle_graph(func_graph) def override_func_graph_name_scope(func_graph, name_scope):
64
64
30
12
52
RickeyEstes/tensorflow
tensorflow/python/framework/func_graph.py
Python
override_func_graph_name_scope
override_func_graph_name_scope
1,296
1,297
1,296
1,296
b88aa1c7e3cb76b6bf05052080bc055094566329
bigcode/the-stack
train
894fc98417ce8c166b6a9b9b
train
function
def _get_composite_tensor_spec(x): """Returns the TypeSpec for x if it's a composite tensor, or x otherwise.""" return (x._type_spec # pylint: disable=protected-access if isinstance(x, composite_tensor.CompositeTensor) else x)
def _get_composite_tensor_spec(x):
"""Returns the TypeSpec for x if it's a composite tensor, or x otherwise.""" return (x._type_spec # pylint: disable=protected-access if isinstance(x, composite_tensor.CompositeTensor) else x)
return placeholder def _get_defun_inputs_from_args(args, names, flat_shapes=None): """Maps Python function positional args to graph-construction inputs.""" return _get_defun_inputs( args, names, structure=args, flat_shapes=flat_shapes) def _get_composite_tensor_spec(x):
64
64
56
9
55
RickeyEstes/tensorflow
tensorflow/python/framework/func_graph.py
Python
_get_composite_tensor_spec
_get_composite_tensor_spec
1,151
1,154
1,151
1,151
169a4c6536679e2f9356b6a85f30ea5f84972579
bigcode/the-stack
train
05e5d5aa5fa109d3d6c15a68
train
class
class FuncGraph(ops.Graph): """Graph representing a function body. Attributes: name: The name of the function. inputs: Placeholder tensors representing the inputs to this function. The tensors are in this FuncGraph. This represents "regular" inputs as well as captured inputs (i.e. the values of...
class FuncGraph(ops.Graph):
"""Graph representing a function body. Attributes: name: The name of the function. inputs: Placeholder tensors representing the inputs to this function. The tensors are in this FuncGraph. This represents "regular" inputs as well as captured inputs (i.e. the values of self.captures), with the re...
"/".join(str(p) for p in path) return resource_variable_ops.VariableSpec(arg.shape, arg.dtype, name) if isinstance(arg, ( int, float, bool, type(None), dtypes.DType, tensor_spec.TensorSpec, type_spec.TypeSpec, )): return arg return Unknown...
256
256
6,145
7
249
RickeyEstes/tensorflow
tensorflow/python/framework/func_graph.py
Python
FuncGraph
FuncGraph
135
807
135
135
a7bb4ddd67f9015b9efbd21e758081d355cfcdad
bigcode/the-stack
train
494bf01067273036b8d181ea
train
function
def convert_structure_to_signature(structure, arg_names=None): """Convert a potentially nested structure to a signature. Args: structure: Structure to convert, where top level collection is a list or a tuple. arg_names: Optional list of arguments that has equal number of elements as `structure`...
def convert_structure_to_signature(structure, arg_names=None):
"""Convert a potentially nested structure to a signature. Args: structure: Structure to convert, where top level collection is a list or a tuple. arg_names: Optional list of arguments that has equal number of elements as `structure` and is used for naming corresponding TensorSpecs. Returns: ...
_ops from tensorflow.python.ops import variable_scope from tensorflow.python.util import compat from tensorflow.python.util import memory from tensorflow.python.util import nest from tensorflow.python.util import object_identity from tensorflow.python.util import tf_contextlib from tensorflow.python.util import tf_deco...
167
167
557
12
154
RickeyEstes/tensorflow
tensorflow/python/framework/func_graph.py
Python
convert_structure_to_signature
convert_structure_to_signature
70
132
70
70
1a9fa120e88571fef66cbc2b93eb802ed6eb7b43
bigcode/the-stack
train
79a260d52df688f97641ea8c
train
function
def device_stack_has_callable(device_stack): """Checks whether a device stack contains a callable.""" return any(callable(spec._device_name_or_function) # pylint: disable=protected-access for spec in device_stack.peek_objs())
def device_stack_has_callable(device_stack):
"""Checks whether a device stack contains a callable.""" return any(callable(spec._device_name_or_function) # pylint: disable=protected-access for spec in device_stack.peek_objs())
.op.graph.building_function and tensor.op.type == "Placeholder"): for input_t, placeholder_t in tensor.op.graph.captures: if tensor == placeholder_t: return maybe_captured(input_t) # pylint: enable=protected-access return tensor def device_stack_has_callable(device_stack):
64
64
49
8
55
RickeyEstes/tensorflow
tensorflow/python/framework/func_graph.py
Python
device_stack_has_callable
device_stack_has_callable
1,064
1,067
1,064
1,064
231242fe4e2a103358c9a973198e28dec4774620
bigcode/the-stack
train
57b8916302b7e143e0a54be8
train
class
class UnknownArgument(object): """Signifies an argument which is not currently handled.""" pass
class UnknownArgument(object):
"""Signifies an argument which is not currently handled.""" pass
.LOCAL_VARIABLES, ops.GraphKeys.TRAINABLE_VARIABLES, variable_scope._VARSTORE_KEY, # pylint: disable=protected-access variable_scope._VARSCOPESTORE_KEY # pylint: disable=protected-access ] _EAGER_CONST_THRESHOLD = 128 class UnknownArgument(object):
64
64
20
5
58
RickeyEstes/tensorflow
tensorflow/python/framework/func_graph.py
Python
UnknownArgument
UnknownArgument
65
67
65
65
81dda575f92cb008ee093c6f7fe0a942a306dedf
bigcode/the-stack
train
10c96299b614d3ce68328915
train
function
def func_graph_from_py_func(name, python_func, args, kwargs, signature=None, func_graph=None, autograph=False, autograph_opt...
def func_graph_from_py_func(name, python_func, args, kwargs, signature=None, func_graph=None, autograph=False, autograph_opt...
"""Returns a `FuncGraph` generated from `python_func`. Args: name: an identifier for the function. python_func: the Python function to trace. args: the positional args with which the Python function should be called; ignored if a signature is provided. kwargs: the keyword args with which the ...
_message = [error_message] self._saving_errors.update(error_message) @property def saveable(self): """Returns whether this FuncGraph is saveable.""" return self._saveable @property def saving_errors(self): """Returns set of errors preventing this FuncGraph from being saved.""" return self....
256
256
2,195
70
186
RickeyEstes/tensorflow
tensorflow/python/framework/func_graph.py
Python
func_graph_from_py_func
func_graph_from_py_func
810
1,043
810
823
11fc636fe9b5e2f89d914c5fa08213120f815858
bigcode/the-stack
train
9d6bd4fbd466712131b11626
train
function
def flush(proc, proc_log): while True: proc_out = proc.stdout.readline() if proc_out == "" and proc.poll() is not None: proc_log.close() break elif proc_out: sys.stdout.write(proc_out) proc_log.write(proc_out) proc_log.flush()
def flush(proc, proc_log):
while True: proc_out = proc.stdout.readline() if proc_out == "" and proc.poll() is not None: proc_log.close() break elif proc_out: sys.stdout.write(proc_out) proc_log.write(proc_out) proc_log.flush()
import os import argparse import time from dask.distributed import Client import sys, uuid import threading import subprocess import socket import mlflow from notebook.notebookapp import list_running_servers def flush(proc, proc_log):
52
64
65
7
44
sewald101/azureml-examples
cli/jobs/single-step/dask/nyctaxi/src/startDask.py
Python
flush
flush
14
23
14
14
038b6f132f82a189e89eebd88687fb67e34305c5
bigcode/the-stack
train
b16018d6fab38c3dbe06f96c
train
function
def to_omrs_date(value): """ Drop the time and timezone to export date-only values >>> to_omrs_date('2017-06-27T12:00:00+0530') == '2017-06-27' True """ if isinstance(value, six.string_types): soft_assert_type_text(value) if not re.match(r'\d{4}-\d{2}-\d{2}', value): ...
def to_omrs_date(value):
""" Drop the time and timezone to export date-only values >>> to_omrs_date('2017-06-27T12:00:00+0530') == '2017-06-27' True """ if isinstance(value, six.string_types): soft_assert_type_text(value) if not re.match(r'\d{4}-\d{2}-\d{2}', value): raise ValueError('"{}" ...
otech.openmrs.const import ( OPENMRS_DATA_TYPE_BOOLEAN, OPENMRS_DATA_TYPE_DATE, OPENMRS_DATA_TYPE_DATETIME, ) from corehq.motech.serializers import serializers from corehq.util.python_compatibility import soft_assert_type_text def to_omrs_date(value):
64
64
151
8
55
kkrampa/commcare-hq
corehq/motech/openmrs/serializers.py
Python
to_omrs_date
to_omrs_date
24
38
24
24
b1c7035399049ce701d925b01fac99001daafa00
bigcode/the-stack
train
12b1b08b7e42590682783de1
train
function
def to_omrs_boolean(value): if ( isinstance(value, six.string_types) and value.lower() in ('false', '0') ): return False return bool(value)
def to_omrs_boolean(value):
if ( isinstance(value, six.string_types) and value.lower() in ('false', '0') ): return False return bool(value)
RS tz = value.strftime('%z') or '+0000' # If we don't know, lie return value.strftime('%Y-%m-%dT%H:%M:%S.{f}{z}'.format(f=micros, z=tz)) def to_omrs_boolean(value):
64
64
42
8
56
kkrampa/commcare-hq
corehq/motech/openmrs/serializers.py
Python
to_omrs_boolean
to_omrs_boolean
60
66
60
60
fe1a2da64a752a06ae4b246d7d852a903de37a94
bigcode/the-stack
train
863a848417d215198db64e91
train
function
def to_omrs_datetime(value): """ Converts CommCare dates and datetimes to OpenMRS datetimes. >>> to_omrs_datetime('2017-06-27') == '2017-06-27T00:00:00.000+0000' True """ if isinstance(value, six.string_types): soft_assert_type_text(value) if not re.match(r'\d{4}-\d{2}-\d{2}', ...
def to_omrs_datetime(value):
""" Converts CommCare dates and datetimes to OpenMRS datetimes. >>> to_omrs_datetime('2017-06-27') == '2017-06-27T00:00:00.000+0000' True """ if isinstance(value, six.string_types): soft_assert_type_text(value) if not re.match(r'\d{4}-\d{2}-\d{2}', value): raise Val...
d{2}', value): raise ValueError('"{}" is not recognised as a date or a datetime'.format(value)) value = dateutil_parser.parse(value) if isinstance(value, (datetime.date, datetime.datetime)): return value.strftime('%Y-%m-%d') def to_omrs_datetime(value):
66
66
221
8
58
kkrampa/commcare-hq
corehq/motech/openmrs/serializers.py
Python
to_omrs_datetime
to_omrs_datetime
41
57
41
41
71f4c68f3116ed3f88a8b20225b30dadd14ee186
bigcode/the-stack
train
9d40f22da42589011162a4ee
train
function
def omrs_datetime_to_date(value): """ Converts an OpenMRS datetime to a CommCare date >>> omrs_datetime_to_date('2017-06-27T00:00:00.000+0000') == '2017-06-27' True """ if value and 'T' in value: return value.split('T')[0] return value
def omrs_datetime_to_date(value):
""" Converts an OpenMRS datetime to a CommCare date >>> omrs_datetime_to_date('2017-06-27T00:00:00.000+0000') == '2017-06-27' True """ if value and 'T' in value: return value.split('T')[0] return value
f}{z}'.format(f=micros, z=tz)) def to_omrs_boolean(value): if ( isinstance(value, six.string_types) and value.lower() in ('false', '0') ): return False return bool(value) def omrs_datetime_to_date(value):
64
64
86
8
56
kkrampa/commcare-hq
corehq/motech/openmrs/serializers.py
Python
omrs_datetime_to_date
omrs_datetime_to_date
69
79
69
69
e05cb4c87738508e1ee7235b7f07fa8132b6048d
bigcode/the-stack
train
24410ccaf792725707065101
train
function
def omrs_boolean_to_text(value): return 'true' if value else 'false'
def omrs_boolean_to_text(value):
return 'true' if value else 'false'
('2017-06-27T00:00:00.000+0000') == '2017-06-27' True """ if value and 'T' in value: return value.split('T')[0] return value def omrs_boolean_to_text(value):
64
64
19
8
55
kkrampa/commcare-hq
corehq/motech/openmrs/serializers.py
Python
omrs_boolean_to_text
omrs_boolean_to_text
82
83
82
82
3ac75e0db5f7b8abcfbdfc257ff7322fa37fbe2f
bigcode/the-stack
train
849623e72eaaa7b827d78a83
train
function
@app.route('/', methods=['POST']) def sms(): number = request.form['From'] message_body = request.form['Body'] response_str = mpd_controller.handle_sms_request(request) resp = MessagingResponse() resp.message(response_str) return str(resp)
@app.route('/', methods=['POST']) def sms():
number = request.form['From'] message_body = request.form['Body'] response_str = mpd_controller.handle_sms_request(request) resp = MessagingResponse() resp.message(response_str) return str(resp)
from flask import Flask, request from twilio.twiml.messaging_response import Message, MessagingResponse from MPDController import MPDController app = Flask(__name__) mpd_controller = MPDController() @app.route('/', methods=['POST']) def sms():
54
64
57
10
44
phuston/sms-mpd
run.py
Python
sms
sms
9
19
9
10
b809674d5676154c66716ab164421dcfc53a39f6
bigcode/the-stack
train
ab4ae150ba5a77b2737b91d3
train
class
class Test(BaseGPUTest): def test_simple_input_internal_inf(self): net = BasicModel_MultiLayer(inplace=True).cuda() inp = torch.tensor( [ [0.0, 100.0, 0.0], [20.0, 100.0, 120.0], [30.0, 10.0, 0.0], [0.0, 0.0, 2.0], ...
class Test(BaseGPUTest):
def test_simple_input_internal_inf(self): net = BasicModel_MultiLayer(inplace=True).cuda() inp = torch.tensor( [ [0.0, 100.0, 0.0], [20.0, 100.0, 120.0], [30.0, 10.0, 0.0], [0.0, 0.0, 2.0], ] ).cuda() ...
from captum.attr._core.layer.layer_gradient_x_activation import LayerGradientXActivation from captum.attr._core.layer.layer_deep_lift import LayerDeepLift, LayerDeepLiftShap from captum.attr._core.layer.layer_gradient_shap import LayerGradientShap from captum.attr._core.neuron.neuron_conductance import NeuronConductan...
256
256
4,222
7
248
gorogoroyasu/captum
tests/attr/test_data_parallel.py
Python
Test
Test
39
549
39
39
d9061167ddee3ec7e538548a76349d21970b9f59
bigcode/the-stack
train
6e482d0d6f17e6360462208e
train
class
class MB8CoinRPC: def __init__(self, host, port, username, password): authpair = "%s:%s" % (username, password) self.authhdr = "Basic %s" % (base64.b64encode(authpair)) self.conn = httplib.HTTPConnection(host, port, False, 30) def execute(self, obj): self.conn.request('POST', '/', json.dumps(obj), { 'Auth...
class MB8CoinRPC:
def __init__(self, host, port, username, password): authpair = "%s:%s" % (username, password) self.authhdr = "Basic %s" % (base64.b64encode(authpair)) self.conn = httplib.HTTPConnection(host, port, False, 30) def execute(self, obj): self.conn.request('POST', '/', json.dumps(obj), { 'Authorization' : self....
c) 2013-2014 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # from __future__ import print_function import json import struct import re import base64 import httplib import sys settings = {} class MB8C...
78
78
261
6
72
MB8Coin/mb8coin-core
contrib/linearize/linearize-hashes.py
Python
MB8CoinRPC
MB8CoinRPC
20
53
20
20
5286bf792bde0451bc1e2282a53d05425f8fe476
bigcode/the-stack
train
bf86f2935442a01905ae9435
train
function
def get_block_hashes(settings, max_blocks_per_call=10000): rpc = MB8CoinRPC(settings['host'], settings['port'], settings['rpcuser'], settings['rpcpassword']) height = settings['min_height'] while height < settings['max_height']+1: num_blocks = min(settings['max_height']+1-height, max_blocks_per_call) batch ...
def get_block_hashes(settings, max_blocks_per_call=10000):
rpc = MB8CoinRPC(settings['host'], settings['port'], settings['rpcuser'], settings['rpcpassword']) height = settings['min_height'] while height < settings['max_height']+1: num_blocks = min(settings['max_height']+1-height, max_blocks_per_call) batch = [] for x in range(num_blocks): batch.append(rpc.buil...
['params'] = [] else: obj['params'] = params return obj @staticmethod def response_is_error(resp_obj): return 'error' in resp_obj and resp_obj['error'] is not None def get_block_hashes(settings, max_blocks_per_call=10000):
64
64
198
15
48
MB8Coin/mb8coin-core
contrib/linearize/linearize-hashes.py
Python
get_block_hashes
get_block_hashes
55
75
55
55
8e757591b83464df1e3880b416b7d61dd49ee8ce
bigcode/the-stack
train
2c81ac96dbca7d92791dce4f
train
function
def max_canon(expr, args): x = args[0] shape = expr.shape axis = expr.axis t = Variable(shape) if axis is None: # shape = (1, 1) promoted_t = promote(t, x.shape) elif axis == 0: # shape = (1, n) promoted_t = Constant(np.ones((x.shape[0], 1))) * reshape( ...
def max_canon(expr, args):
x = args[0] shape = expr.shape axis = expr.axis t = Variable(shape) if axis is None: # shape = (1, 1) promoted_t = promote(t, x.shape) elif axis == 0: # shape = (1, n) promoted_t = Constant(np.ones((x.shape[0], 1))) * reshape( ...
or implied. See the License for the specific language governing permissions and limitations under the License. """ from cvxpy.atoms import promote, reshape from cvxpy.expressions.constants import Constant from cvxpy.expressions.variable import Variable import numpy as np def max_canon(expr, args):
64
64
164
8
55
mostafaelaraby/cvxpy
cvxpy/reductions/eliminate_pwl/atom_canonicalizers/max_canon.py
Python
max_canon
max_canon
23
39
23
23
cfa26b429e7c9d7eabf7c8832e0ba40aef19aa75
bigcode/the-stack
train