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
e23324f4336eb8a2e64e8047
train
function
def install_nbextension(path, overwrite=False, symlink=False, user=False, prefix=None, nbextensions_dir=None, destination=None, verbose=1): """Install a Javascript extension for the notebook Stages files and/or directories into the nbextensions directory. By default, this compares modification time, an...
def install_nbextension(path, overwrite=False, symlink=False, user=False, prefix=None, nbextensions_dir=None, destination=None, verbose=1):
"""Install a Javascript extension for the notebook Stages files and/or directories into the nbextensions directory. By default, this compares modification time, and only stages files that need updating. If `overwrite` is specified, matching files are purged before proceeding. Parameters ...
installed Returns True if all files are found, False if any are missing. Parameters ---------- files : list(paths) a list of relative paths within nbextensions. user : bool [default: False] Whether to check the user's .ipython/nbextensions directory. Otherwise check a...
256
256
1,167
31
225
wangyum/anaconda
pkgs/notebook-4.1.0-py27_1/lib/python2.7/site-packages/notebook/nbextensions.py
Python
install_nbextension
install_nbextension
110
220
110
110
295da83fa9f38cae1b02c42d1c1baacc2b7f65fa
bigcode/the-stack
train
4a38ec66468a7f754a029917
train
class
class DisableNBExtensionApp(JupyterApp): name = "jupyter nbextension disable" version = __version__ description = "Remove the configuration to automatically load an extension" section = Unicode('notebook', config=True, help=("Which config section to remove the extension from. " ...
class DisableNBExtensionApp(JupyterApp):
name = "jupyter nbextension disable" version = __version__ description = "Remove the configuration to automatically load an extension" section = Unicode('notebook', config=True, help=("Which config section to remove the extension from. " "This should match the one it was previ...
=self.config) cm.update(self.section, {"load_extensions": {name: True}}) def start(self): if not self.extra_args: sys.exit('No extensions specified') elif len(self.extra_args) > 1: sys.exit('Please specify one extension at a time') self.enable_nbextension(se...
82
82
274
9
73
wangyum/anaconda
pkgs/notebook-4.1.0-py27_1/lib/python2.7/site-packages/notebook/nbextensions.py
Python
DisableNBExtensionApp
DisableNBExtensionApp
358
389
358
358
0f5cd184ee44b5942729e4583db436b589eb4d0a
bigcode/the-stack
train
4d0ef7014340ab7f46f6ffcd
train
function
def _get_nbext_dir(nbextensions_dir=None, user=False, prefix=None): """Return the nbextension directory specified""" if sum(map(bool, [user, prefix, nbextensions_dir])) > 1: raise ArgumentConflict("Cannot specify more than one of user, prefix, or nbextensions_dir.") if user: nbext = pjoin(ju...
def _get_nbext_dir(nbextensions_dir=None, user=False, prefix=None):
"""Return the nbextension directory specified""" if sum(map(bool, [user, prefix, nbextensions_dir])) > 1: raise ArgumentConflict("Cannot specify more than one of user, prefix, or nbextensions_dir.") if user: nbext = pjoin(jupyter_data_dir(), u'nbextensions') else: if prefix: ...
2(src, dest) def _safe_is_tarfile(path): """safe version of is_tarfile, return False on IOError""" try: return tarfile.is_tarfile(path) except IOError: return False def _get_nbext_dir(nbextensions_dir=None, user=False, prefix=None):
64
64
153
17
46
wangyum/anaconda
pkgs/notebook-4.1.0-py27_1/lib/python2.7/site-packages/notebook/nbextensions.py
Python
_get_nbext_dir
_get_nbext_dir
63
76
63
63
5f0a988b23c45b210ac934b9d892b32a0b84cc9b
bigcode/the-stack
train
67dcd5b3a17020e87b0ac996
train
class
class ArgumentConflict(ValueError): pass
class ArgumentConflict(ValueError):
pass
jupyter_path, SYSTEM_JUPYTER_PATH from ipython_genutils.path import ensure_dir_exists from ipython_genutils.py3compat import string_types, cast_unicode_py2 from ipython_genutils.tempdir import TemporaryDirectory from ._version import __version__ class ArgumentConflict(ValueError):
64
64
9
6
58
wangyum/anaconda
pkgs/notebook-4.1.0-py27_1/lib/python2.7/site-packages/notebook/nbextensions.py
Python
ArgumentConflict
ArgumentConflict
29
30
29
29
d3bbb1742feb686f35c80d4bece04a0ef43a5571
bigcode/the-stack
train
45f3368ad5f4b1034fde5cca
train
class
class InstallNBExtensionApp(JupyterApp): """Entry point for installing notebook extensions""" version = __version__ description = """Install Jupyter notebook extensions Usage jupyter nbextension install path/url This copies a file or a folder into the Jupyter nbextensions dire...
class InstallNBExtensionApp(JupyterApp):
"""Entry point for installing notebook extensions""" version = __version__ description = """Install Jupyter notebook extensions Usage jupyter nbextension install path/url This copies a file or a folder into the Jupyter nbextensions directory. If a URL is given, it will be ...
, }}, "Minimal output" ), "symlink" : ({ "InstallNBExtensionApp" : { "symlink" : True, }}, "Create symlink instead of copying files" ), "user" : ({ "InstallNBExtensionApp" : { "user" : True, }}, "Install to the user's IPython directory" ...
147
147
493
9
138
wangyum/anaconda
pkgs/notebook-4.1.0-py27_1/lib/python2.7/site-packages/notebook/nbextensions.py
Python
InstallNBExtensionApp
InstallNBExtensionApp
264
324
264
264
751145411ba2bd6b574a2ce5082273329b0cb704
bigcode/the-stack
train
12deefb89f1f95f58192db91
train
function
def _safe_is_tarfile(path): """safe version of is_tarfile, return False on IOError""" try: return tarfile.is_tarfile(path) except IOError: return False
def _safe_is_tarfile(path):
"""safe version of is_tarfile, return False on IOError""" try: return tarfile.is_tarfile(path) except IOError: return False
=1): """copy a file if it needs updating""" if _should_copy(src, dest, verbose): if verbose >= 1: print("copying %s -> %s" % (src, dest)) shutil.copy2(src, dest) def _safe_is_tarfile(path):
64
64
42
8
56
wangyum/anaconda
pkgs/notebook-4.1.0-py27_1/lib/python2.7/site-packages/notebook/nbextensions.py
Python
_safe_is_tarfile
_safe_is_tarfile
55
60
55
55
6b02130d6987c50481d5496db101088173f22e80
bigcode/the-stack
train
0e3227cc1961aafa175c6247
train
function
def _maybe_copy(src, dest, verbose=1): """copy a file if it needs updating""" if _should_copy(src, dest, verbose): if verbose >= 1: print("copying %s -> %s" % (src, dest)) shutil.copy2(src, dest)
def _maybe_copy(src, dest, verbose=1):
"""copy a file if it needs updating""" if _should_copy(src, dest, verbose): if verbose >= 1: print("copying %s -> %s" % (src, dest)) shutil.copy2(src, dest)
.org/issue12904 if verbose >= 2: print("%s is out of date" % dest) return True if verbose >= 2: print("%s is up to date" % dest) return False def _maybe_copy(src, dest, verbose=1):
64
64
65
12
51
wangyum/anaconda
pkgs/notebook-4.1.0-py27_1/lib/python2.7/site-packages/notebook/nbextensions.py
Python
_maybe_copy
_maybe_copy
48
53
48
48
01276c7a4621b532b2a11806ead60a09f6cf6e99
bigcode/the-stack
train
7d951d963f1edfd1e2182ae2
train
class
class EnableNBExtensionApp(JupyterApp): name = "jupyter nbextension enable" version = __version__ description = "Configure an nbextension to be automatically loaded" section = Unicode('notebook', config=True, help=("Which config section to add the extension to. " "'common' wil...
class EnableNBExtensionApp(JupyterApp):
name = "jupyter nbextension enable" version = __version__ description = "Configure an nbextension to be automatically loaded" section = Unicode('notebook', config=True, help=("Which config section to add the extension to. " "'common' will affect all pages.") ) aliases...
% nbext) for ext in os.listdir(nbext): print(u" %s" % ext) else: try: self.install_extensions() except ArgumentConflict as e: print(str(e), file=sys.stderr) self.exit(1) class EnableNBExtensio...
66
66
220
9
57
wangyum/anaconda
pkgs/notebook-4.1.0-py27_1/lib/python2.7/site-packages/notebook/nbextensions.py
Python
EnableNBExtensionApp
EnableNBExtensionApp
327
355
327
327
490bdf1a1cffac3469586833c311c734891d9056
bigcode/the-stack
train
ea6679177e1d252f67d4c939
train
function
def time_this(func): ''' Get how much this function took to execute ''' def wrapper(*args, **kwargs): ''' the inner wrapper function ''' start = time.time() return_value = func(*args, **kwargs) end = time.time() logging.warning('%s_%s took %s secon...
def time_this(func):
''' Get how much this function took to execute ''' def wrapper(*args, **kwargs): ''' the inner wrapper function ''' start = time.time() return_value = func(*args, **kwargs) end = time.time() logging.warning('%s_%s took %s seconds', func.__qualname_...
''' Timing decorators ''' import os import time import logging LOG_DIR = 'logs' if not os.path.exists(LOG_DIR): os.makedirs(LOG_DIR) logging.basicConfig(filename='%s/log.log' % LOG_DIR, level=logging.DEBUG) def time_this(func):
56
64
95
5
51
ammarnajjar/ammarnajjar.github.io
tests/helper/timing.py
Python
time_this
time_this
15
28
15
15
57eebf70e64a45f134f4d331e8d6d60ee858a331
bigcode/the-stack
train
3c4988a4de49c07774f7a051
train
function
def train(train_op, global_step, step, accuracy, learning_rate): log_frequency = 20 start_time = time.time() batch_x, batch_y = train_generator.next() # perform the operations we defined earlier on batch loss_value, step_value = sess.run( [train_op, global_step], feed_dict={ ...
def train(train_op, global_step, step, accuracy, learning_rate):
log_frequency = 20 start_time = time.time() batch_x, batch_y = train_generator.next() # perform the operations we defined earlier on batch loss_value, step_value = sess.run( [train_op, global_step], feed_dict={ model.inputs[0]: batch_x, targets: batch_...
name="train") accuracy = tf.contrib.metrics.accuracy(labels=tf.argmax(targets, 1), predictions=tf.argmax(predictions, 1)) return (train_op, loss, predictions, accuracy, optimizer._learning_rate) # Train the model (a single step) def train(train_op, global_...
73
73
244
15
58
starcell/deepcell-ncluster
applications/cli/example-python/alexnet/alexnet_multi_node_keras.py
Python
train
train
157
180
157
157
fb72d5e808573452f6bf4fca5fb2375fb1a8331b
bigcode/the-stack
train
04ed6a33aa485239aacec8b5
train
function
def create_model(): DROPOUT = 0.5 model_input = keras.layers.Input(shape=(227, 227, 3)) # First convolutional Layer (96x11x11) z = keras.layers.Conv2D(filters=96, kernel_size=(11, 11), strides=(4, 4), activation="relu")(model_input) z = keras.layers.MaxPooling2D(pool_size=(3, 3), strides=(2, ...
def create_model():
DROPOUT = 0.5 model_input = keras.layers.Input(shape=(227, 227, 3)) # First convolutional Layer (96x11x11) z = keras.layers.Conv2D(filters=96, kernel_size=(11, 11), strides=(4, 4), activation="relu")(model_input) z = keras.layers.MaxPooling2D(pool_size=(3, 3), strides=(2, 2))(z) z = keras...
server server = tf.train.Server(cluster, job_name=FLAGS.job_name, task_index=FLAGS.task_index) N_CATEGORY = 1000 def load_data(): global train_generator global validation_generator datagen = keras.preprocessing.image.ImageDataGenerator(data_...
165
165
552
4
161
starcell/deepcell-ncluster
applications/cli/example-python/alexnet/alexnet_multi_node_keras.py
Python
create_model
create_model
74
114
74
74
78ab59eb49a01c6ba0464b1e4cdc5436eb35d664
bigcode/the-stack
train
b685d6e69eb21f1671c41308
train
function
def load_data(): global train_generator global validation_generator datagen = keras.preprocessing.image.ImageDataGenerator(data_format='channels_last') train_generator = datagen.flow_from_directory(os.path.join(FLAGS.data_dir, 'i1k-extracted/train'), ...
def load_data():
global train_generator global validation_generator datagen = keras.preprocessing.image.ImageDataGenerator(data_format='channels_last') train_generator = datagen.flow_from_directory(os.path.join(FLAGS.data_dir, 'i1k-extracted/train'), target_size=(2...
localhost:2225"]}) cluster = tf.train.ClusterSpec({"ps": ps_hosts, "worker": worker_hosts}) # Start the server server = tf.train.Server(cluster, job_name=FLAGS.job_name, task_index=FLAGS.task_index) N_CATEGORY = 1000 def load_data():
64
64
129
4
59
starcell/deepcell-ncluster
applications/cli/example-python/alexnet/alexnet_multi_node_keras.py
Python
load_data
load_data
57
71
57
57
f6cf32927a7571e0db12bf347cbb50c05efee897
bigcode/the-stack
train
4e1f3797c1566e673956752e
train
function
def validate(epoch, total_loss, accuracy): batch_test_x, batch_test_y = validation_generator.next() test_accuracies = [] test_losses = [] test_batch_index = 0 while test_batch_index * 128 < 50000: test_batch_loss, test_batch_acc = sess.run([total_loss, accuracy], ...
def validate(epoch, total_loss, accuracy):
batch_test_x, batch_test_y = validation_generator.next() test_accuracies = [] test_losses = [] test_batch_index = 0 while test_batch_index * 128 < 50000: test_batch_loss, test_batch_acc = sess.run([total_loss, accuracy], feed_dict={ ...
f," % loss_value, "Accuracy: %.16f" % acc, "AvgTime: %3.2fms" % float(elapsed_time * 1000 / log_frequency), "Learning rate: %.16f" % lr_val) def validate(epoch, total_loss, accuracy):
64
64
194
9
55
starcell/deepcell-ncluster
applications/cli/example-python/alexnet/alexnet_multi_node_keras.py
Python
validate
validate
183
204
183
183
9dc91489de78290b21a5ae46de062e86a0d0b989
bigcode/the-stack
train
32f28da7763bfaeb0e716307
train
function
def create_optimizer(model, targets): WEIGHT_DECAY = 0.0005 MOMENTUM = 0.9 LEARNING_RATE = 0.01 predictions = model.output loss = tf.reduce_mean( keras.losses.categorical_crossentropy(targets, predictions)) # Keras-like learning rate descent function learning_rate = tf.co...
def create_optimizer(model, targets):
WEIGHT_DECAY = 0.0005 MOMENTUM = 0.9 LEARNING_RATE = 0.01 predictions = model.output loss = tf.reduce_mean( keras.losses.categorical_crossentropy(targets, predictions)) # Keras-like learning rate descent function learning_rate = tf.constant(LEARNING_RATE, dtype=tf.float32)...
keras.layers.Dense(4096, activation="relu")(z) z = keras.layers.Dropout(DROPOUT)(z) final_dim = 1 if N_CATEGORY == 2 else N_CATEGORY final_act = "sigmoid" if N_CATEGORY == 2 else "softmax" model_output = keras.layers.Dense(final_dim, activation=final_act)(z) model = keras.models.Model(mode...
106
106
354
7
98
starcell/deepcell-ncluster
applications/cli/example-python/alexnet/alexnet_multi_node_keras.py
Python
create_optimizer
create_optimizer
117
153
117
117
110aa8f7cf56ce226b435be4c68b1e1469de6082
bigcode/the-stack
train
d772a0f0727994ecae8af716
train
function
def load_all(module_name): import os dircts = [] path = os.getcwd() for root, dirs, files in os.walk(path): for file in files: script = '{}.py'.format(module_name) if file.endswith(script): filepath = os.path.join(root, file) if 'env' not ...
def load_all(module_name):
import os dircts = [] path = os.getcwd() for root, dirs, files in os.walk(path): for file in files: script = '{}.py'.format(module_name) if file.endswith(script): filepath = os.path.join(root, file) if 'env' not in filepath: ...
def load_all(module_name):
6
64
131
6
0
cattod/fajr-py-backend
infrastructure/module_loader.py
Python
load_all
load_all
1
19
1
1
ea8b06a0e8a0e5334ed9b5cf0c2be43d2de7051b
bigcode/the-stack
train
3db9e6d6d05b746c8fd273aa
train
function
def unregister(): bpy.utils.unregister_module(__name__) bpy.types.TOPBAR_MT_file_import.remove(gnd_importer.GND_OT_ImportOperator.menu_func_import) bpy.types.TOPBAR_MT_file_import.remove(rsm_importer.RSM_OT_ImportOperator.menu_func_import) bpy.types.TOPBAR_MT_file_import.remove(rsw_importer.RSW_OT_Impor...
def unregister():
bpy.utils.unregister_module(__name__) bpy.types.TOPBAR_MT_file_import.remove(gnd_importer.GND_OT_ImportOperator.menu_func_import) bpy.types.TOPBAR_MT_file_import.remove(rsm_importer.RSM_OT_ImportOperator.menu_func_import) bpy.types.TOPBAR_MT_file_import.remove(rsw_importer.RSW_OT_ImportOperator.menu_fun...
.append(gnd_importer.GND_OT_ImportOperator.menu_func_import) bpy.types.TOPBAR_MT_file_import.append(rsm_importer.RSM_OT_ImportOperator.menu_func_import) bpy.types.TOPBAR_MT_file_import.append(rsw_importer.RSW_OT_ImportOperator.menu_func_import) def unregister():
64
64
93
3
61
cmbasnett/io_scene_rsw
src/__init__.py
Python
unregister
unregister
48
55
48
48
ffd90376e3091604723a1463d95c0357399c5d77
bigcode/the-stack
train
1b8dfe2b7b9ab8cc215f378c
train
function
def register(): for cls in classes: bpy.utils.register_class(cls) bpy.types.TOPBAR_MT_file_import.append(gnd_importer.GND_OT_ImportOperator.menu_func_import) bpy.types.TOPBAR_MT_file_import.append(rsm_importer.RSM_OT_ImportOperator.menu_func_import) bpy.types.TOPBAR_MT_file_import.append(rsw_im...
def register():
for cls in classes: bpy.utils.register_class(cls) bpy.types.TOPBAR_MT_file_import.append(gnd_importer.GND_OT_ImportOperator.menu_func_import) bpy.types.TOPBAR_MT_file_import.append(rsm_importer.RSM_OT_ImportOperator.menu_func_import) bpy.types.TOPBAR_MT_file_import.append(rsw_importer.RSW_OT_Im...
sm import importer as rsm_importer from .rsw import importer as rsw_importer classes = ( gnd_importer.GND_OT_ImportOperator, rsm_importer.RSM_OT_ImportOperator, rsw_importer.RSW_OT_ImportOperator, ) def register():
64
64
85
3
61
cmbasnett/io_scene_rsw
src/__init__.py
Python
register
register
39
45
39
39
95c54b329b440eb9d5cf93cf78a5be8afd58a6b4
bigcode/the-stack
train
ac8d53030c68dc8148eef74a
train
function
def _get_struct_I(): global _struct_I return _struct_I
def _get_struct_I():
global _struct_I return _struct_I
,) = _get_struct_2B15f2Bi6H2B().unpack(str[start:end]) return self except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill _struct_I = genpy.struct_I def _get_struct_I():
64
64
18
6
57
jessecha/OPCAS
Catkin_PKG_Car/devel/lib/python2.7/dist-packages/drive_ros_msgs/msg/_mav_cc16_TELEMETRY.py
Python
_get_struct_I
_get_struct_I
310
312
310
310
72b073a01b474fd54b1e1016eaaaa07c0526f426
bigcode/the-stack
train
1560286ade91a7a2cd34442e
train
function
def _get_struct_3I(): global _struct_3I if _struct_3I is None: _struct_3I = struct.Struct("<3I") return _struct_3I
def _get_struct_3I():
global _struct_3I if _struct_3I is None: _struct_3I = struct.Struct("<3I") return _struct_3I
except struct.error as e: raise genpy.DeserializationError(e) #most likely buffer underfill _struct_I = genpy.struct_I def _get_struct_I(): global _struct_I return _struct_I _struct_3I = None def _get_struct_3I():
64
64
47
8
55
jessecha/OPCAS
Catkin_PKG_Car/devel/lib/python2.7/dist-packages/drive_ros_msgs/msg/_mav_cc16_TELEMETRY.py
Python
_get_struct_3I
_get_struct_3I
314
318
314
314
9c95827b70581032c875cafeefcea847b1166539
bigcode/the-stack
train
4ebfc03a088c42d8af54feb2
train
class
class mav_cc16_TELEMETRY(genpy.Message): _md5sum = "432f9dfb0037d5f65f83be8d10976087" _type = "drive_ros_msgs/mav_cc16_TELEMETRY" _has_header = True #flag to mark the presence of a Header object _full_text = """# Automatically Generated in 2017-06-12 22:33:47.452753 # MESSAGE: TELEMETRY # Description:Telemetry ...
class mav_cc16_TELEMETRY(genpy.Message):
_md5sum = "432f9dfb0037d5f65f83be8d10976087" _type = "drive_ros_msgs/mav_cc16_TELEMETRY" _has_header = True #flag to mark the presence of a Header object _full_text = """# Automatically Generated in 2017-06-12 22:33:47.452753 # MESSAGE: TELEMETRY # Description:Telemetry Header header uint8 ID = 3 uint8 sysid u...
# This Python file uses the following encoding: utf-8 """autogenerated by genpy from drive_ros_msgs/mav_cc16_TELEMETRY.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct import std_msgs.msg class mav_cc16_TELEMETRY(genpy.Message):
82
256
3,680
12
69
jessecha/OPCAS
Catkin_PKG_Car/devel/lib/python2.7/dist-packages/drive_ros_msgs/msg/_mav_cc16_TELEMETRY.py
Python
mav_cc16_TELEMETRY
mav_cc16_TELEMETRY
10
307
10
10
29da60cad8ac18d3464e556fc7f48881c5ecfc9d
bigcode/the-stack
train
d6355a63e95f106fdbbfc2be
train
function
def _get_struct_2B15f2Bi6H2B(): global _struct_2B15f2Bi6H2B if _struct_2B15f2Bi6H2B is None: _struct_2B15f2Bi6H2B = struct.Struct("<2B15f2Bi6H2B") return _struct_2B15f2Bi6H2B
def _get_struct_2B15f2Bi6H2B():
global _struct_2B15f2Bi6H2B if _struct_2B15f2Bi6H2B is None: _struct_2B15f2Bi6H2B = struct.Struct("<2B15f2Bi6H2B") return _struct_2B15f2Bi6H2B
I if _struct_3I is None: _struct_3I = struct.Struct("<3I") return _struct_3I _struct_2B15f2Bi6H2B = None def _get_struct_2B15f2Bi6H2B():
64
64
95
16
47
jessecha/OPCAS
Catkin_PKG_Car/devel/lib/python2.7/dist-packages/drive_ros_msgs/msg/_mav_cc16_TELEMETRY.py
Python
_get_struct_2B15f2Bi6H2B
_get_struct_2B15f2Bi6H2B
320
324
320
320
8791d99a1b0963c3111235acfd882356dc828ed7
bigcode/the-stack
train
bb405dffa30e4cbe8f6233fe
train
class
class AzureContainerVolumeHook(BaseHook): """ A hook which wraps an Azure Volume. :param wasb_conn_id: connection id of a Azure storage account of which file shares should be mounted :type wasb_conn_id: str """ def __init__(self, wasb_conn_id: str = 'wasb_default') -> None: sup...
class AzureContainerVolumeHook(BaseHook):
""" A hook which wraps an Azure Volume. :param wasb_conn_id: connection id of a Azure storage account of which file shares should be mounted :type wasb_conn_id: str """ def __init__(self, wasb_conn_id: str = 'wasb_default') -> None: super().__init__() self.conn_id = was...
software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from azure.mgmt.containerinstance.models import AzureFileVolum...
84
84
283
8
75
gtossou/airflow
airflow/providers/microsoft/azure/hooks/azure_container_volume.py
Python
AzureContainerVolumeHook
AzureContainerVolumeHook
24
61
24
24
56ccab778c80ef4d281cfaf58fd9191038810309
bigcode/the-stack
train
de21c6c84bcd41a59a7961cc
train
function
def deprecated(f): @functools.wraps(f) def wrapper(*args, **kwargs): warnings.warn( "This name is deprecated, use %s instead" % f.__name__, DeprecationWarning, stacklevel=2) return f(*args, **kwargs) return wrapper
def deprecated(f): @functools.wraps(f)
def wrapper(*args, **kwargs): warnings.warn( "This name is deprecated, use %s instead" % f.__name__, DeprecationWarning, stacklevel=2) return f(*args, **kwargs) return wrapper
Byte = UBInt8 Bytes = Field Const = ConstAdapter Tunnel = TunnelAdapter Embed = Embedded #=============================================================================== # Deprecated names # Next scheduled name cleanout: 2.1 #=============================================================================== import functo...
64
64
67
13
50
seemoo-lab/polypyus_pdom
import/elftools/construct/__init__.py
Python
deprecated
deprecated
62
69
62
63
cd14aa560e7f69a1cb8536be17f3586cea5ccfeb
bigcode/the-stack
train
93a07fa7ffacd7d2b9ae8ba2
train
class
class IncidentClassifier(IncidentClassifierBase): def run(self, options): self.add_classify_files(options["classifier-directory"]) out = options.stdout for f in options.files: abs_fn = os.path.expanduser(f) incident = self.load_incident(abs_fn) categories ...
class IncidentClassifier(IncidentClassifierBase):
def run(self, options): self.add_classify_files(options["classifier-directory"]) out = options.stdout for f in options.files: abs_fn = os.path.expanduser(f) incident = self.load_incident(abs_fn) categories = self.classify_incident(incident) pri...
f(trigger) if c: # allow the classifier to return None, or [], or ["foo"] if isinstance(c, str): c = [c] # or just "foo" categories.update(c) if not categories: categories.add("unknown") return categories class IncidentClassifi...
68
68
227
8
59
jaraco/foolscap
src/foolscap/logging/incident.py
Python
IncidentClassifier
IncidentClassifier
235
256
235
235
b1714ccf3da225ccb381b2996dc9c0b737af636f
bigcode/the-stack
train
669848050243667d72b19439
train
class
class IncidentQualifier: """I am responsible for deciding what qualifies as an Incident. I look at the event stream and watch for a 'triggering event', then signal my handler when the events that I've seen are severe enought to warrant recording the recent history in an 'incident log file'. My even...
class IncidentQualifier:
"""I am responsible for deciding what qualifies as an Incident. I look at the event stream and watch for a 'triggering event', then signal my handler when the events that I've seen are severe enought to warrant recording the recent history in an 'incident log file'. My event() method should be call...
Reporter from foolscap.logging import levels, app_versions, flogfile from foolscap.eventual import eventually from foolscap.util import move_into_place from foolscap import base32 TIME_FORMAT = "%Y-%m-%d--%H-%M-%S" class IncidentQualifier:
64
64
204
4
60
jaraco/foolscap
src/foolscap/logging/incident.py
Python
IncidentQualifier
IncidentQualifier
16
39
16
16
5e3dd4556b2063fdec2a914ecf865138c4a4706a
bigcode/the-stack
train
fdf1c06c49602d24914cb24e
train
class
class ClassifyOptions(usage.Options): stdout = sys.stdout stderr = sys.stderr synopsis = "Usage: flogtool classify-incident [options] INCIDENTFILE.." optFlags = [ ("verbose", "v", "show trigger details for unclassifiable incidents"), ] optParameters = [ ("classifier-director...
class ClassifyOptions(usage.Options):
stdout = sys.stdout stderr = sys.stderr synopsis = "Usage: flogtool classify-incident [options] INCIDENTFILE.." optFlags = [ ("verbose", "v", "show trigger details for unclassifiable incidents"), ] optParameters = [ ("classifier-directory", "c", ".", "directory with...
.abs_filename) # now we can tell the world about our new incident report eventually(self.logger.incident_recorded, self.abs_filename_bz2, self.name, self.trigger) class NonTrailingIncidentReporter(IncidentReporter): TRAILING_DELAY = None class ClassifyOptions(usage.Options):
64
64
106
8
55
jaraco/foolscap
src/foolscap/logging/incident.py
Python
ClassifyOptions
ClassifyOptions
178
192
178
178
f87adec3702f588a0eba8ace6b922a6f6d2c0e26
bigcode/the-stack
train
fb1b4c7ef7fe10e31c8f4d3c
train
class
class NonTrailingIncidentReporter(IncidentReporter): TRAILING_DELAY = None
class NonTrailingIncidentReporter(IncidentReporter):
TRAILING_DELAY = None
the uncompressed one. self.f1.close() os.unlink(self.abs_filename) # now we can tell the world about our new incident report eventually(self.logger.incident_recorded, self.abs_filename_bz2, self.name, self.trigger) class NonTrailingIncidentReporter(IncidentReporter):...
64
64
16
9
55
jaraco/foolscap
src/foolscap/logging/incident.py
Python
NonTrailingIncidentReporter
NonTrailingIncidentReporter
174
175
174
174
8e8887bcfaced3ccd069ff660dab49159c0ff2da
bigcode/the-stack
train
716e536ddc27c9199ee9f53c
train
class
class IncidentClassifierBase: def __init__(self): self.classifiers = [] def add_classifier(self, f): # there are old .tac files that call this explicitly self.classifiers.append(f) def add_classify_files(self, plugindir): plugindir = os.path.expanduser(plugindir) f...
class IncidentClassifierBase:
def __init__(self): self.classifiers = [] def add_classifier(self, f): # there are old .tac files that call this explicitly self.classifiers.append(f) def add_classify_files(self, plugindir): plugindir = os.path.expanduser(plugindir) for fn in os.listdir(plugindir):...
synopsis = "Usage: flogtool classify-incident [options] INCIDENTFILE.." optFlags = [ ("verbose", "v", "show trigger details for unclassifiable incidents"), ] optParameters = [ ("classifier-directory", "c", ".", "directory with classify_*.py functions to import"), ] ...
91
91
305
5
85
jaraco/foolscap
src/foolscap/logging/incident.py
Python
IncidentClassifierBase
IncidentClassifierBase
195
233
195
196
d8c455406c96731ae4f04c800dd0e40b48429d3b
bigcode/the-stack
train
53ea9347dbaf65db9573dc05
train
class
@implementer(IIncidentReporter) class IncidentReporter: """Once an Incident has been declared, I am responsible for making a durable record all relevant log events. I do this by creating a logfile (a series of JSON lines, one per log event dictionary) and copying everything from the history buffer into ...
@implementer(IIncidentReporter) class IncidentReporter:
"""Once an Incident has been declared, I am responsible for making a durable record all relevant log events. I do this by creating a logfile (a series of JSON lines, one per log event dictionary) and copying everything from the history buffer into it. I can copy a small number of future events into ...
ap.eventual import eventually from foolscap.util import move_into_place from foolscap import base32 TIME_FORMAT = "%Y-%m-%d--%H-%M-%S" class IncidentQualifier: """I am responsible for deciding what qualifies as an Incident. I look at the event stream and watch for a 'triggering event', then signal my hand...
256
256
1,157
11
245
jaraco/foolscap
src/foolscap/logging/incident.py
Python
IncidentReporter
IncidentReporter
41
172
41
42
e13b992b8e33182140923aad3d8b5421320ff53f
bigcode/the-stack
train
3afd64c17f7f5ee12a839e1a
train
class
class EnzoPFieldInfo(FieldInfoContainer): known_other_fields = ( ("velocity_x", (vel_units, ["velocity_x"], None)), ("velocity_y", (vel_units, ["velocity_y"], None)), ("velocity_z", (vel_units, ["velocity_z"], None)), ("acceleration_x", (acc_units, ["acceleration_x"], None)), ...
class EnzoPFieldInfo(FieldInfoContainer):
known_other_fields = ( ("velocity_x", (vel_units, ["velocity_x"], None)), ("velocity_y", (vel_units, ["velocity_y"], None)), ("velocity_z", (vel_units, ["velocity_z"], None)), ("acceleration_x", (acc_units, ["acceleration_x"], None)), ("acceleration_y", (acc_units, ["accelera...
from yt.fields.field_info_container import FieldInfoContainer from yt.fields.particle_fields import add_union_field from yt.frontends.enzo_p.misc import nested_dict_get rho_units = "code_mass / code_length**3" vel_units = "code_velocity" acc_units = "code_velocity / code_time" energy_units = "code_velocity**2" known_...
88
208
695
10
78
munkm/yt
yt/frontends/enzo_p/fields.py
Python
EnzoPFieldInfo
EnzoPFieldInfo
13
85
13
13
5cecf9376a7841d1c05ffbda1dd0876148cd7e9b
bigcode/the-stack
train
39a0941f42442cdb3b411ebe
train
class
class Relation(object): def __init__(self): self.__relations = {} def get_keys(self): return list(map(AttrDict, self.__relations.keys())) def add_relation(self, dict1, dict2, directed=False): key1 = tuple(dict1.items()) key2 = tuple(dict2.items()) if key1 == key2: ...
class Relation(object):
def __init__(self): self.__relations = {} def get_keys(self): return list(map(AttrDict, self.__relations.keys())) def add_relation(self, dict1, dict2, directed=False): key1 = tuple(dict1.items()) key2 = tuple(dict2.items()) if key1 == key2: return False ...
#!/usr/bin/env python # coding: utf-8 from ams import AttrDict class Relation(object):
24
131
438
4
19
CPFL/AMS
ams/utilities/relation.py
Python
Relation
Relation
7
62
7
8
77dfe98f2fc79436f5d810a8df619e6a1ceda6cc
bigcode/the-stack
train
af0ea1c4396c43de434de313
train
class
class NetWeaverMetricClient(ABC): #__metaclass__ = ABCMeta def __init__(self, tracer: logging.Logger): self.tracer = tracer @abstractproperty def Hostname(self) -> str: pass @abstractproperty def InstanceNr(self) -> str: pass # validate that ...
class NetWeaverMetricClient(ABC): #__metaclass__ = ABCMeta
def __init__(self, tracer: logging.Logger): self.tracer = tracer @abstractproperty def Hostname(self) -> str: pass @abstractproperty def InstanceNr(self) -> str: pass # validate that config settings and that client can establish connection @ab...
features: ABAP, J2EE, JEE @abstractmethod def getQueueStatistic(self, logTag: str) -> list: pass # invoke EnqGetStatistic SOAP API - metrics from ENQUE server around enqueue lock statistics # applies to hosts with features: ENQUE @abstractmethod def getEnqueueServerStatistic(self, lo...
188
188
629
19
169
hsridharan/AzureMonitorForSAPSolutions
sapmon/payload/netweaver/metricclientfactory.py
Python
NetWeaverMetricClient
NetWeaverMetricClient
78
155
78
80
6313d9b68ab18981ac59e9b3bb4ecdc5b94fc021
bigcode/the-stack
train
18eadf291d716f249216b5da
train
class
class NetWeaverSoapClientBase(ABC): def __init__(self, tracer: logging.Logger): self.tracer = tracer # the fully qualified WSDL url that was used to initialize this SOAP client @abstractproperty def Wsdl(self) -> str: pass # invoke GetSystemInstanceList SOAP API - returns list of ...
class NetWeaverSoapClientBase(ABC):
def __init__(self, tracer: logging.Logger): self.tracer = tracer # the fully qualified WSDL url that was used to initialize this SOAP client @abstractproperty def Wsdl(self) -> str: pass # invoke GetSystemInstanceList SOAP API - returns list of metadata for all server instances in ...
antiation attempts will be refreshed SOAP_CLIENT_CACHE_EXPIRATIION = timedelta(minutes=10) ########## # Abstract base class to represent interface for querying Server/System time from SAP system ########## class ServerTimeClientBase(ABC): def __init__(self, tracer: logging.Logger): self.tracer = tracer ...
121
121
405
10
111
hsridharan/AzureMonitorForSAPSolutions
sapmon/payload/netweaver/metricclientfactory.py
Python
NetWeaverSoapClientBase
NetWeaverSoapClientBase
29
73
29
30
0e2c62a465a41a5453bc47700ddb3de43463803a
bigcode/the-stack
train
474928d51c8000f3a549733d
train
class
class MetricClientFactory: # static class variable to keep cache of all successfully initialized SOAP metric clients # using a lookup key of the WSDL url. _soapClientCache= {} @staticmethod def getMetricClient(tracer: logging.Logger, logTag: str, ...
class MetricClientFactory: # static class variable to keep cache of all successfully initialized SOAP metric clients # using a lookup key of the WSDL url.
_soapClientCache= {} @staticmethod def getMetricClient(tracer: logging.Logger, logTag: str, sapHostName: str, sapSubdomain: str, sapSysNr: str, sapClient: str, s...
method def getFailedUpdatesMetrics(self, logTag: str) -> str: pass # fetch BAPI_XBP_JOB_SELECT metrics and return as json string @abstractmethod def getBatchJobMetrics(self, startDateTime: datetime, endDateTime: datetime, logTag: str) -> str: pass # fetch TRFC_QIN_GET_CURRENT_...
256
256
1,723
33
223
hsridharan/AzureMonitorForSAPSolutions
sapmon/payload/netweaver/metricclientfactory.py
Python
MetricClientFactory
MetricClientFactory
160
333
160
163
f6d97e5a086c819fd6f40ba7083fd0126781873e
bigcode/the-stack
train
7c995820b349f594c8562373
train
class
class ServerTimeClientBase(ABC): def __init__(self, tracer: logging.Logger): self.tracer = tracer @abstractmethod def getServerTimestamp(self, logTag: str) -> datetime: pass
class ServerTimeClientBase(ABC):
def __init__(self, tracer: logging.Logger): self.tracer = tracer @abstractmethod def getServerTimestamp(self, logTag: str) -> datetime: pass
soap client cache expiration, after which amount of time both successful + failed soap client instantiation attempts will be refreshed SOAP_CLIENT_CACHE_EXPIRATIION = timedelta(minutes=10) ########## # Abstract base class to represent interface for querying Server/System time from SAP system ########## class ServerTi...
64
64
50
8
56
hsridharan/AzureMonitorForSAPSolutions
sapmon/payload/netweaver/metricclientfactory.py
Python
ServerTimeClientBase
ServerTimeClientBase
17
24
17
18
c9728b39f176c7971ae542d5dad0b11996f3765d
bigcode/the-stack
train
843e9dfd3978148c6929e123
train
function
def makeWebhookResult(data,data_1): #results = data.get('results') #if results is None: # return {} formatted_address_1 = data['results'][0]['formatted_address'] name = data['results'][0]['name'] if formatted_address_1 is None: return {} place_id_1=data['results'][0]['place_id'] ...
def makeWebhookResult(data,data_1): #results = data.get('results') #if results is None: # return {}
formatted_address_1 = data['results'][0]['formatted_address'] name = data['results'][0]['name'] if formatted_address_1 is None: return {} place_id_1=data['results'][0]['place_id'] if place_id_1 is None: return {} phone=data_1['result']['formatted_phone_number'] if 'o...
+ i url_1=url_1+ '+'+"office"+"&key=" +"AIzaSyD0HnUitzdPovQlJ-ifc2BbU6lm04QTtxE" return url_1''' url_2="https://maps.googleapis.com/maps/api/place/details/json?placeid="+place_id_1+"&key=AIzaSyD0HnUitzdPovQlJ-ifc2BbU6lm04QTtxE" return url_2 def makeWebhookResult(data,data_1): ...
139
139
465
30
108
ranjan1110/google-map
app.py
Python
makeWebhookResult
makeWebhookResult
127
172
127
131
014549a15be38492a9f5cde6e260ad747c1ad7c5
bigcode/the-stack
train
05ded415eb808e03054af9f3
train
function
def makeYqlQuery(req): result = req.get("result") parameters = result.get("parameters") city = parameters.get("geo-city") item = parameters.get("itemssss") cityarr=city.split(" ") itemarr=item.split(" ") if city is None: return None url_1="https://maps.googleapis.com/maps/ap...
def makeYqlQuery(req):
result = req.get("result") parameters = result.get("parameters") city = parameters.get("geo-city") item = parameters.get("itemssss") cityarr=city.split(" ") itemarr=item.split(" ") if city is None: return None url_1="https://maps.googleapis.com/maps/api/place/textsearch/json...
1) if yql_url_1 is None: return {} result_1 = urlopen(yql_url_1).read() data_1 = json.loads(result_1) res = makeWebhookResult(data,data_1) return res def makeYqlQuery(req):
64
64
197
7
56
ranjan1110/google-map
app.py
Python
makeYqlQuery
makeYqlQuery
74
97
74
74
ca0a026c9894132f131db371c42f3f478b4757ad
bigcode/the-stack
train
938fdbe7815432aa07edba0b
train
function
def processRequest(req): if req.get("result").get("action") != "map": return {} #baseurl = "https://maps.googleapis.com/maps/api/place/textsearch/json" yql_url = makeYqlQuery(req) if yql_url is None: return {} result = urlopen(yql_url).read() data = json.loads(result) pl...
def processRequest(req):
if req.get("result").get("action") != "map": return {} #baseurl = "https://maps.googleapis.com/maps/api/place/textsearch/json" yql_url = makeYqlQuery(req) if yql_url is None: return {} result = urlopen(yql_url).read() data = json.loads(result) place_id_1=data['results'][...
("Request:") print(json.dumps(req, indent=4)) res = processRequest(req) res = json.dumps(res, indent=4) # print(res) r = make_response(res) r.headers['Content-Type'] = 'application/json' return r def processRequest(req):
64
64
171
5
58
ranjan1110/google-map
app.py
Python
processRequest
processRequest
52
71
52
52
c0bd14d795bb35ecafe9e0aa5f45679c3862eaf7
bigcode/the-stack
train
cb6d2c634325240c1c7b431b
train
function
def makeYqlQuery1(req,place_id_1): result = req.get("result") parameters = result.get("parameters") city = parameters.get("geo-city") item = parameters.get("itemssss") cityarr=city.split(" ") itemarr=item.split(" ") if city is None: return None '''url_1="https://maps.googlea...
def makeYqlQuery1(req,place_id_1):
result = req.get("result") parameters = result.get("parameters") city = parameters.get("geo-city") item = parameters.get("itemssss") cityarr=city.split(" ") itemarr=item.split(" ") if city is None: return None '''url_1="https://maps.googleapis.com/maps/api/place/textsearch/j...
itemarr: url_1 = url_1 + '+' + i url_1=url_1+ '+'+"office"+"&key=" +"AIzaSyD0HnUitzdPovQlJ-ifc2BbU6lm04QTtxE" return url_1 def makeYqlQuery1(req,place_id_1):
78
78
261
13
64
ranjan1110/google-map
app.py
Python
makeYqlQuery1
makeYqlQuery1
99
124
99
99
4d5cc321bcf84e894577dcfe1be0939e82bf091e
bigcode/the-stack
train
b8853d2ab4acb2de4e8e7ef3
train
function
@app.route('/webhook', methods=['POST']) def webhook(): req = request.get_json(silent=True, force=True) print("Request:") print(json.dumps(req, indent=4)) res = processRequest(req) res = json.dumps(res, indent=4) # print(res) r = make_response(res) r.headers['Content-Type'] = 'applica...
@app.route('/webhook', methods=['POST']) def webhook():
req = request.get_json(silent=True, force=True) print("Request:") print(json.dumps(req, indent=4)) res = processRequest(req) res = json.dumps(res, indent=4) # print(res) r = make_response(res) r.headers['Content-Type'] = 'application/json' return r
.request import urlopen, Request from urllib.error import HTTPError import json import os from flask import Flask from flask import request from flask import make_response # Flask app should start in global layout app = Flask(__name__) @app.route('/webhook', methods=['POST']) def webhook():
64
64
87
13
51
ranjan1110/google-map
app.py
Python
webhook
webhook
36
49
36
37
67de1e1d0afa54beee5979af6dc65f5459cafcc9
bigcode/the-stack
train
2a93634e1a30a92b798d55aa
train
function
def create(kernel): result = Tangible() result.template = "object/tangible/wearables/bodysuit/shared_bodysuit_bwing_quest.iff" result.attribute_template_id = 11 result.stfName("wearables_name","bodysuit_bwing_quest") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
def create(kernel):
result = Tangible() result.template = "object/tangible/wearables/bodysuit/shared_bodysuit_bwing_quest.iff" result.attribute_template_id = 11 result.stfName("wearables_name","bodysuit_bwing_quest") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel):
46
64
81
4
42
obi-two/GameServer
data/scripts/templates/object/tangible/wearables/bodysuit/shared_bodysuit_bwing_quest.py
Python
create
create
7
17
7
7
ab16f1a757407394d6bc45df374bc28dc0ae287c
bigcode/the-stack
train
428a07b4cc867ff75d544777
train
function
def action_set(action, name, value): action[name] = value
def action_set(action, name, value):
action[name] = value
logs = [] return { "method": method, "url": url, "logs": logs, "request_body": request_body, "response_body": response_body, "completed": completed, "success": success, } def action_set(action, name, value):
64
64
16
9
55
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
action_set
action_set
358
359
358
358
a4bf20433429a272fc961fc0dccacfb0057cb187
bigcode/the-stack
train
e3a714e2334829af9aa0643d
train
function
def set_hsm_component(state, xname, action): if action.get('success'): component_list = json.loads(action.get('response_body')) for c in component_list: component = state.create_component(xname) component.in_hsm() response = json.loads(action.get('response_body'))...
def set_hsm_component(state, xname, action):
if action.get('success'): component_list = json.loads(action.get('response_body')) for c in component_list: component = state.create_component(xname) component.in_hsm() response = json.loads(action.get('response_body')) t = response.get('Type', '') ...
_component(xname) component.in_hsm() response = json.loads(action.get('response_body')) t = response.get('Type', '') if t: component.type = t component.redfish_endpoint_enabled = response.get('Enabled') def set_hsm_component(state, xname, action):
64
64
83
12
52
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
set_hsm_component
set_hsm_component
527
536
527
527
4c7fa952dee16e12b2e1f4b64d5006493dde1e93
bigcode/the-stack
train
85ef1c072610d139de303c34
train
class
class Ncns: def __init__(self): self.first_master_hostname = '' self.workers = [] self.masters = [] self.storage = [] def add_worker(self, name, xname): self.workers.append((name, xname)) def add_master(self, name, xname): self.masters.append((name, xname)) ...
class Ncns:
def __init__(self): self.first_master_hostname = '' self.workers = [] self.masters = [] self.storage = [] def add_worker(self, name, xname): self.workers.append((name, xname)) def add_master(self, name, xname): self.masters.append((name, xname)) def add...
join([v[3] for v in ips])) _append_str(lines, 'ip_reservations_mac', ', '.join([v[4] for v in ips])) _append_str_bool(lines, 'redfish_endpoint_enabled', self.redfish_endpoint_enabled) _append_str_bool(lines, 'ifnames', ', '.join(self.ifnames)) return tab + f'\n{tab}'.join(lines) class N...
91
91
305
4
87
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
Ncns
Ncns
118
154
118
118
80686293e9cd273cabced22375e2053c81720fc6
bigcode/the-stack
train
b278813ca248a34cb83dae93
train
function
def print_urls(): log.debug(f'BSS_URL: {BSS_URL}') log.debug(f'HSM_URL: {HSM_URL}') log.debug(f'SLS_URL: {SLS_URL}') log.debug(f'KEA_URL: {KEA_URL}')
def print_urls():
log.debug(f'BSS_URL: {BSS_URL}') log.debug(f'HSM_URL: {HSM_URL}') log.debug(f'SLS_URL: {SLS_URL}') log.debug(f'KEA_URL: {KEA_URL}')
= args.sls_url elif args.test_urls: SLS_URL = 'http://localhost:8376/v1' else: SLS_URL = f'{BASE_URL}/sls/v1' KEA_URL = f'{BASE_URL}/dhcp-kea' def print_urls():
64
64
56
4
60
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
print_urls
print_urls
294
298
294
294
d28e26e7fb83a643fcea496898f7cd1c96bb9955
bigcode/the-stack
train
a4480b64948e770f319456c1
train
function
def print_actions(actions): for action in actions: print_action(action)
def print_actions(actions):
for action in actions: print_action(action)
Planned: {action['method'].upper()} {action['url']}") # if action.get('body'): # print(json.dumps(action.get('body'), indent=2)) for a_log in action.get('logs'): log.debug(' ' + a_log) def print_actions(actions):
64
64
16
5
59
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
print_actions
print_actions
317
319
317
317
51582f540112fb2858c801fbf0baff7882f43c8f
bigcode/the-stack
train
82c7cb3f87551ef7d68bdc92
train
function
def print_command_actions(actions): for action in actions: print_command_action(action)
def print_command_actions(actions):
for action in actions: print_command_action(action)
{action.stderr}') elif action.verbose: log.info(f' stdout:\n{action.stdout}') if action.stderr: log.info(f' stderr:\n{action.stderr}') else: log.debug(f'Planned: {" ".join(action.command)}') def print_command_actions(actions):
64
64
18
6
58
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
print_command_actions
print_command_actions
338
340
338
338
87cbe9199411a2771bd72fbaec54a75a1274f5ec
bigcode/the-stack
train
54a85191d0ab68a152482ab8
train
function
def print_action(action): if action['completed']: if action['success']: log.debug(f"Called: {action['method'].upper()} {action['url']}") else: log.debug(f"Failed: {action['method'].upper()} {action['url']}") log.debug(json.dumps(action.get('response_body'), inde...
def print_action(action):
if action['completed']: if action['success']: log.debug(f"Called: {action['method'].upper()} {action['url']}") else: log.debug(f"Failed: {action['method'].upper()} {action['url']}") log.debug(json.dumps(action.get('response_body'), indent=2)) else: l...
kea' def print_urls(): log.debug(f'BSS_URL: {BSS_URL}') log.debug(f'HSM_URL: {HSM_URL}') log.debug(f'SLS_URL: {SLS_URL}') log.debug(f'KEA_URL: {KEA_URL}') def print_action(action):
63
64
144
5
58
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
print_action
print_action
301
314
301
301
76d84743d8589e7e818a7c7187eeba4a393c4c64
bigcode/the-stack
train
b8080acc8402a252a0c7f972
train
function
def set_hsm_redfish(state, xname, action): if action.get('success'): component = state.create_component(xname) component.in_hsm() response = json.loads(action.get('response_body')) t = response.get('Type', '') if t: component.type = t component.redfish_end...
def set_hsm_redfish(state, xname, action):
if action.get('success'): component = state.create_component(xname) component.in_hsm() response = json.loads(action.get('response_body')) t = response.get('Type', '') if t: component.type = t component.redfish_endpoint_enabled = response.get('Enabled')
mac = ethernet.get('MACAddress') ip_addresses = ethernet.get('IPAddresses', []) for i in ip_addresses: ip = i.get('IPAddress') if ip: component.add_ip_reservation(ip, mac=mac) def set_hsm_redfish(state, xname...
64
64
77
13
51
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
set_hsm_redfish
set_hsm_redfish
516
524
516
516
f7a8e41d51f25aa5cce15c83865631a39a281d34
bigcode/the-stack
train
e10125846ac050ba6ae46aa9
train
function
def create_hsm_actions(session, state): actions = [] # ------------------------------------------- # ethernet interfaces if state.xname: xname_ethernet_action = http_get(session, actions, f'{HSM_URL}/Inventory/EthernetInterfaces?ComponentId={state.xname}...
def create_hsm_actions(session, state):
actions = [] # ------------------------------------------- # ethernet interfaces if state.xname: xname_ethernet_action = http_get(session, actions, f'{HSM_URL}/Inventory/EthernetInterfaces?ComponentId={state.xname}') set_hsm_ethernet(state, state...
component.type = t component.redfish_endpoint_enabled = response.get('Enabled') def set_hsm_component(state, xname, action): if action.get('success'): component_list = json.loads(action.get('response_body')) for c in component_list: component = state.create_component(xname) ...
109
109
366
9
99
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
create_hsm_actions
create_hsm_actions
539
575
539
539
32d2ef38794163a14dc52478f3423aebf6e61e88
bigcode/the-stack
train
57eddaa9e658374897bfb7cc
train
function
def action_create(method, url, logs=None, request_body="", response_body="", completed=False, success=False): if logs is None: logs = [] return { "method": method, "url": url, "logs": logs, "request_body": request_body, "response_body": response_body, "co...
def action_create(method, url, logs=None, request_body="", response_body="", completed=False, success=False):
if logs is None: logs = [] return { "method": method, "url": url, "logs": logs, "request_body": request_body, "response_body": response_body, "completed": completed, "success": success, }
:\n{action.stderr}') else: log.debug(f'Planned: {" ".join(action.command)}') def print_command_actions(actions): for action in actions: print_command_action(action) def action_create(method, url, logs=None, request_body="", response_body="", completed=False, success=False):
64
64
83
22
42
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
action_create
action_create
343
355
343
343
74f19a0762a68815a72e975f3e1c7ee68b195250
bigcode/the-stack
train
2fa28784f8977e4d6907720d
train
function
def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1)
def log_error_and_exit(actions, message):
print_actions(actions) log.error(f'{message}') sys.exit(1)
actions.append(action) action_set(action, 'response', r) if r.status_code == http.HTTPStatus.OK: action_set(action, 'success', True) elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message):
64
64
27
9
54
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
log_error_and_exit
log_error_and_exit
378
381
378
378
7af5d40e1b284d70357e43de16b26445e6f30b29
bigcode/the-stack
train
6bf4a3dbfb49919a7c29479d
train
function
def run_action(session, action): method = action.get('method') url = action.get('url') r = None if method == 'get': r = session.get(url) elif method == 'post': r = session.post(url, action.get('request_body')) else: log.error(f"Unimplemented method {method}") sys....
def run_action(session, action):
method = action.get('method') url = action.get('url') r = None if method == 'get': r = session.get(url) elif method == 'post': r = session.post(url, action.get('request_body')) else: log.error(f"Unimplemented method {method}") sys.exit(1) if r: action...
requires this.') if not state.ipmi_password: log.debug(f' Environment variable IPMI_PASSWORD was not set. The ipmitool requires this.') return command_actions def is_2xx(http_status): return http_status // 200 == 1 def run_action(session, action):
64
64
124
7
56
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
run_action
run_action
733
748
733
733
b3d5c934d485ed3fbfa9c5f097aff34526b29eb5
bigcode/the-stack
train
37a6eaf2d21d68ec406243c7
train
function
def _append_str_bool(lines, name, value): if value is not None: lines.append(f'{name}: {value}')
def _append_str_bool(lines, name, value):
if value is not None: lines.append(f'{name}: {value}')
BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' log = logging def _append_str(lines, name, value): if value: lines.append(f'{name}: {value}') def _append_str_bool(lines, name, value):
63
64
28
11
52
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
_append_str_bool
_append_str_bool
50
52
50
50
50b665c7f59eb980ab01dbf0f8da9cde13fe73cb
bigcode/the-stack
train
27afef23f33aad8c5983af54
train
function
def run_command_actions(command_actions): for command in command_actions: if command.has_run: pass else: run_command_action(command) print_command_action(command)
def run_command_actions(command_actions):
for command in command_actions: if command.has_run: pass else: run_command_action(command) print_command_action(command)
None if not result[1] else result[1].decode('utf-8') return cmd.returncode, stdout, stderr def run_command_action(command): command.return_code, command.stdout, command.stderr = run_command(command.command) command.has_run = True def run_command_actions(command_actions):
64
64
38
7
56
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
run_command_actions
run_command_actions
645
651
645
645
743a76cd092e92ac17a42a4364a56ed9ede5e2a0
bigcode/the-stack
train
4f27595238cb6c362a641515
train
function
def create_sls_actions(session, state): actions = [] hardware_action = http_get(session, actions, f'{SLS_URL}/hardware') networks_action = http_get(session, actions, f'{SLS_URL}/networks') # Find xname in hardware and get aliases hardware_list = json.loads(hardware_action.get('response_body')) ...
def create_sls_actions(session, state):
actions = [] hardware_action = http_get(session, actions, f'{SLS_URL}/hardware') networks_action = http_get(session, actions, f'{SLS_URL}/networks') # Find xname in hardware and get aliases hardware_list = json.loads(hardware_action.get('response_body')) if state.xname: for hardware in...
def http_get(session, actions, url, exit_on_error=False): r = session.get(url) action = action_create('get', url, response_body=r.text, completed=True) actions.append(action) action_set(action, 'response', r) if r.status_code == http.HTTPStatus.OK: action_set(action, 'success', True) eli...
256
256
1,015
9
246
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
create_sls_actions
create_sls_actions
393
498
393
393
3f9a2dac2c1b009b34c0699f2f1d48cf37e28ee8
bigcode/the-stack
train
09c09573d45312b85e05839f
train
function
def action_log(action, message): action.get('logs').append(message)
def action_log(action, message):
action.get('logs').append(message)
"url": url, "logs": logs, "request_body": request_body, "response_body": response_body, "completed": completed, "success": success, } def action_set(action, name, value): action[name] = value def action_log(action, message):
64
64
16
7
56
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
action_log
action_log
362
363
362
362
121105f993bf175b422ae86f7caf680ed786c869
bigcode/the-stack
train
e321a1622b12bf997d9064b5
train
function
def set_hsm_ethernet(state, xname, action): if action.get('success'): ethernet_list = json.loads(action.get('response_body')) if ethernet_list: component = state.create_component(xname) component.in_hsm() for ethernet in ethernet_list: mac = ethern...
def set_hsm_ethernet(state, xname, action):
if action.get('success'): ethernet_list = json.loads(action.get('response_body')) if ethernet_list: component = state.create_component(xname) component.in_hsm() for ethernet in ethernet_list: mac = ethernet.get('MACAddress') ip_addr...
_reservations.append(ip_reservation) else: state.add_ip_reservation( ip_reservation.get('IPAddress', ''), ip_reservation.get('Name', ''), ip_reservation.get('Aliases', [])) return actions ...
64
64
111
14
49
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
set_hsm_ethernet
set_hsm_ethernet
501
513
501
501
c690da60b5c9193d32784c89c1bce8267653506c
bigcode/the-stack
train
df00837f6aeb23faec0a8f61
train
class
class Component: def __init__(self, xname): self.xname = xname self.name = None self.parent = None self.type = '' self.role = '' self.subrole = '' self.sources = set() self.connectors = [] self.ip_reservations = {} self.redfish_endpoint...
class Component:
def __init__(self, xname): self.xname = xname self.name = None self.parent = None self.type = '' self.role = '' self.subrole = '' self.sources = set() self.connectors = [] self.ip_reservations = {} self.redfish_endpoint_enabled = None ...
, DAMAGES OR # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR # OTHER DEALINGS IN THE SOFTWARE. import argparse import http import json import logging import os import re import requests import subprocess import sys import u...
160
161
538
3
157
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
Component
Component
55
115
55
55
d4a47ebcf5bd2a9c4ff288a4558c4105fcc0c0fc
bigcode/the-stack
train
eeea64038fadc5be92ab676d
train
function
def create_bss_actions(session, state): actions = [] # ------------------------------------------- # Global global_bp_action = http_get(session, actions, f'{BSS_URL}/bootparameters?name=Global') global_bp = json.loads(global_bp_action.get('response_body')) if len(global_bp) == 0: log_e...
def create_bss_actions(session, state):
actions = [] # ------------------------------------------- # Global global_bp_action = http_get(session, actions, f'{BSS_URL}/bootparameters?name=Global') global_bp = json.loads(global_bp_action.get('response_body')) if len(global_bp) == 0: log_error_and_exit(actions, "Failed to find G...
= http_get(session, actions, f'{HSM_URL}/State/Components/{node_enclosure_xname}') set_hsm_component(state, node_enclosure_xname, enclosure_component_action) return actions def bss_params_to_ifnames(params): result = [] arg_list = params.split(' ') for arg in arg_list: if arg.startsw...
113
113
379
9
103
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
create_bss_actions
create_bss_actions
588
628
588
588
3627471d675edcea79d35d9c7c1bf28d3402e8e0
bigcode/the-stack
train
62238bdd857750add76a20df
train
class
class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose
class CommandAction:
def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose
value set the environment variable, ' + 'IPMI_PASSWORD, with the password for the BMC') else: lines.append(f' bmc_mac: # Unknown. This script is always unable to collect this for ncn-m001') return '\n'.join(lines) class CommandAction:...
64
64
55
4
60
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
CommandAction
CommandAction
248
255
248
248
deafa6dc4b5c6533c1dba1ea0a474a12f673f246
bigcode/the-stack
train
ca72b3b975802ce24ff0c0ab
train
function
def http_get(session, actions, url, exit_on_error=False): r = session.get(url) action = action_create('get', url, response_body=r.text, completed=True) actions.append(action) action_set(action, 'response', r) if r.status_code == http.HTTPStatus.OK: action_set(action, 'success', True) eli...
def http_get(session, actions, url, exit_on_error=False):
r = session.get(url) action = action_create('get', url, response_body=r.text, completed=True) actions.append(action) action_set(action, 'response', r) if r.status_code == http.HTTPStatus.OK: action_set(action, 'success', True) elif exit_on_error: log_error_and_exit(actions, str(a...
": response_body, "completed": completed, "success": success, } def action_set(action, name, value): action[name] = value def action_log(action, message): action.get('logs').append(message) def http_get(session, actions, url, exit_on_error=False):
64
64
95
14
50
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
http_get
http_get
366
375
366
366
52d87f7d07680a43c015a840699bf27231aa9bfd
bigcode/the-stack
train
8501d4e3c91f3b61d1997d24
train
function
def _append_str(lines, name, value): if value: lines.append(f'{name}: {value}')
def _append_str(lines, name, value):
if value: lines.append(f'{name}: {value}')
json import logging import os import re import requests import subprocess import sys import urllib3 import collections BASE_URL = '' BSS_URL = '' HSM_URL = '' SLS_URL = '' KEA_URL = '' log = logging def _append_str(lines, name, value):
64
64
24
10
53
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
_append_str
_append_str
45
47
45
45
6d3aa930e4d5cad936377ddbdf7ed467f0408f5a
bigcode/the-stack
train
01d8fc475682b22dae5300e4
train
function
def create_ipmitool_actions(state): command_actions = [] if not state.run_ipmitool: return command_actions if state.ncn_name and state.ipmi_password and state.ipmi_username: mc_info_action = CommandAction([ 'ipmitool', '-I', 'lanplus', '-U', state.ipmi_username, '-E', '-H', f'{s...
def create_ipmitool_actions(state):
command_actions = [] if not state.run_ipmitool: return command_actions if state.ncn_name and state.ipmi_password and state.ipmi_username: mc_info_action = CommandAction([ 'ipmitool', '-I', 'lanplus', '-U', state.ipmi_username, '-E', '-H', f'{state.ncn_name}-mgmt', 'm...
log.debug(' '.join(command_wide)) _, wide_stdout, wide_stderr = run_command(command_wide) log.debug(wide_stdout) if wide_stderr: log.debug(wide_stderr) log.error(f'there are pods on {alias}.') sy...
133
134
447
8
125
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
create_ipmitool_actions
create_ipmitool_actions
688
726
688
688
bb30e37f54eeb4ed090a9fc85b2fdc0a6c53fe04
bigcode/the-stack
train
606c76634481e3021c416f3a
train
function
def is_2xx(http_status): return http_status // 200 == 1
def is_2xx(http_status):
return http_status // 200 == 1
log.debug(f' Environment variable IPMI_USERNAME was not set. The ipmitool requires this.') if not state.ipmi_password: log.debug(f' Environment variable IPMI_PASSWORD was not set. The ipmitool requires this.') return command_actions def is_2xx(http_status):
64
64
19
8
55
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
is_2xx
is_2xx
729
730
729
729
d16140b504b2a12942a1b4298d984d06f118fe00
bigcode/the-stack
train
571b9493e25bfbeb6439b3b6
train
function
def run_command(command): log.debug(f'Running: {" ".join(command)}') cmd = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) result = cmd.communicate() stdout = None if not result[0] else result[0].decode('utf-8') stderr = None if not result[1] else result[1].decode('utf-8') ...
def run_command(command):
log.debug(f'Running: {" ".join(command)}') cmd = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE) result = cmd.communicate() stdout = None if not result[0] else result[0].decode('utf-8') stderr = None if not result[1] else result[1].decode('utf-8') return cmd.returncode,...
xname_bp_list[0] if len(xname_bp_list) > 0 else {} # save interfaces from params params = xname_bp.get('params') if params: bss_component.ifnames = bss_params_to_ifnames(params) return actions def run_command(command):
64
64
92
5
58
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
run_command
run_command
631
637
631
631
d0b18161c341c806fdc866102b407425dfaacb3f
bigcode/the-stack
train
7447fd9721cad648cdef96c3
train
function
def print_command_action(action): if action.has_run: log.debug(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{acti...
def print_command_action(action):
if action.has_run: log.debug(f'Ran: {" ".join(action.command)}') if action.return_code != 0: log.error(f' Failed: {action.return_code}') log.info(f' stdout:\n{action.stdout}') log.info(f' stderr:\n{action.stderr}') elif action.v...
# if action.get('body'): # print(json.dumps(action.get('body'), indent=2)) for a_log in action.get('logs'): log.debug(' ' + a_log) def print_actions(actions): for action in actions: print_action(action) def print_command_action(action):
64
64
129
6
58
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
print_command_action
print_command_action
322
335
322
322
b14229215960ae02d3e2311f91755aab82c9a142
bigcode/the-stack
train
73d01d176ec8f5ef75aa04e3
train
class
class State: def __init__(self, xname=None, verbose=False): self.xname = xname self.verbose = verbose self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_ips = set() self.ip_reservation_aliases = set() self.workers = set() ...
class State:
def __init__(self, xname=None, verbose=False): self.xname = xname self.verbose = verbose self.parent = None self.ncn_name = "" self.aliases = set() self.ip_reservation_ips = set() self.ip_reservation_aliases = set() self.workers = set() self.re...
name, xname)) def add_storage(self, name, xname): self.storage.append((name, xname)) def to_str(self, indent=0): tab = " " * indent second_tab = " " * (4 if indent == 0 else indent * 2) lines = [] _append_str(lines, 'first_master_hostname', self.first_master_hostname) ...
234
234
780
3
231
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
State
State
157
245
157
157
277be2a19a54dbecc0a0e33b428801eefdeb1866
bigcode/the-stack
train
46b63a61de52d876cfeb9a70
train
function
def check_for_running_pods_on_ncn(state): for alias in state.aliases: command_wide = ['kubectl', 'get', 'pods', '--all-namespaces', '--field-selector', f'spec.nodeName={alias}', '-o', 'wide'] command = ['kubectl', 'get', 'pods', '--all-namespaces', '--field-selector', f'spec.nodeName={alias}', '-o',...
def check_for_running_pods_on_ncn(state):
for alias in state.aliases: command_wide = ['kubectl', 'get', 'pods', '--all-namespaces', '--field-selector', f'spec.nodeName={alias}', '-o', 'wide'] command = ['kubectl', 'get', 'pods', '--all-namespaces', '--field-selector', f'spec.nodeName={alias}', '-o', 'json'] return_code, stdout, stde...
[1] else result[1].decode('utf-8') return cmd.returncode, stdout, stderr def run_command_action(command): command.return_code, command.stdout, command.stderr = run_command(command.command) command.has_run = True def run_command_actions(command_actions): for command in command_actions: if com...
102
102
343
11
91
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
check_for_running_pods_on_ncn
check_for_running_pods_on_ncn
654
685
654
654
7345ee9231e072adac1f96bc801d4c4dbd89fcac
bigcode/the-stack
train
c18d4afd85ef3439f2c5ca5f
train
function
def node_bmc_to_enclosure(xname_for_bmc): p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if xname_for_bmc and p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure ...
def node_bmc_to_enclosure(xname_for_bmc):
p = re.compile('^(x[0-9]{1,4}c0s[0-9]+)(b)([0-9]+)$') if xname_for_bmc and p.match(xname_for_bmc): # convert node bmc to enclosure, for example, convert x3000c0s36b0 to x3000c0s36e0 enclosure = re.sub(p, r'\1e\3', xname_for_bmc) return enclosure return None
success', True) elif exit_on_error: log_error_and_exit(actions, str(action)) return action def log_error_and_exit(actions, message): print_actions(actions) log.error(f'{message}') sys.exit(1) def node_bmc_to_enclosure(xname_for_bmc):
64
64
125
13
51
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
node_bmc_to_enclosure
node_bmc_to_enclosure
384
390
384
384
bda6fd5252b8d8439a780d623a23eb869d933913
bigcode/the-stack
train
bf26bdfd11736420610212ba
train
function
def setup_urls(args): global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls:...
def setup_urls(args):
global BASE_URL global BSS_URL global HSM_URL global SLS_URL global KEA_URL if args.base_url: BASE_URL = args.base_url else: BASE_URL = 'https://api-gw-service-nmn.local/apis' if args.bss_url: BSS_URL = args.bss_url elif args.test_urls: BSS_URL = 'ht...
to collect this for ncn-m001') return '\n'.join(lines) class CommandAction: def __init__(self, command, verbose=False): self.command = command self.has_run = False self.return_code = -1 self.stdout = None self.stderr = None self.verbose = verbose def setup...
77
77
258
5
71
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
setup_urls
setup_urls
258
291
258
258
577e3c186f6d93f01da15e835269d1f92e5b4f1f
bigcode/the-stack
train
760b5a4ad126070220793d95
train
function
def main(argv): parser = argparse.ArgumentParser() parser.add_argument("--xname", help="The xname of the ncn to remove") parser.add_argument("--all", action="store_true", help="List all NCNs") parser.add_argument("-v", action="store_true", help="Print verbose output") # hidden arguments used for te...
def main(argv):
parser = argparse.ArgumentParser() parser.add_argument("--xname", help="The xname of the ncn to remove") parser.add_argument("--all", action="store_true", help="List all NCNs") parser.add_argument("-v", action="store_true", help="Print verbose output") # hidden arguments used for testing parser...
: log.debug(f' Environment variable IPMI_PASSWORD was not set. The ipmitool requires this.') return command_actions def is_2xx(http_status): return http_status // 200 == 1 def run_action(session, action): method = action.get('method') url = action.get('url') r = None if ...
215
215
717
4
211
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
main
main
760
827
760
760
5c36e44e24659298a148a6dd306cac1818ca50f6
bigcode/the-stack
train
aeca28ab720c6edb3695874a
train
function
def run_command_action(command): command.return_code, command.stdout, command.stderr = run_command(command.command) command.has_run = True
def run_command_action(command):
command.return_code, command.stdout, command.stderr = run_command(command.command) command.has_run = True
result = cmd.communicate() stdout = None if not result[0] else result[0].decode('utf-8') stderr = None if not result[1] else result[1].decode('utf-8') return cmd.returncode, stdout, stderr def run_command_action(command):
64
64
29
6
57
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
run_command_action
run_command_action
640
642
640
640
8d037f4ce082d777177aff5f8b7dd96a7db2b5b0
bigcode/the-stack
train
24dec4218aa11358cbe9bbf6
train
function
def bss_params_to_ifnames(params): result = [] arg_list = params.split(' ') for arg in arg_list: if arg.startswith('ifname='): key_value = arg.split('=', 2) result.append(key_value[1]) return result
def bss_params_to_ifnames(params):
result = [] arg_list = params.split(' ') for arg in arg_list: if arg.startswith('ifname='): key_value = arg.split('=', 2) result.append(key_value[1]) return result
if node_enclosure_xname: enclosure_component_action = http_get(session, actions, f'{HSM_URL}/State/Components/{node_enclosure_xname}') set_hsm_component(state, node_enclosure_xname, enclosure_component_action) return actions def bss_params_to_ifnames(params):
64
64
60
9
54
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
bss_params_to_ifnames
bss_params_to_ifnames
578
585
578
578
fe6d7bbcc9c10978fda3023326e8e8b88c9bb8c7
bigcode/the-stack
train
00955f6aff86ec09c550c1ee
train
function
def run_actions(session, actions): for action in actions: if action.get('completed'): print_action(action) else: run_action(session, action) print_action(action)
def run_actions(session, actions):
for action in actions: if action.get('completed'): print_action(action) else: run_action(session, action) print_action(action)
.error(f"Unimplemented method {method}") sys.exit(1) if r: action_set(action, 'response_body', r.text) action_set(action, 'completed', True) action_set(action, 'success', is_2xx(r.status_code)) def run_actions(session, actions):
64
64
40
7
57
rambabubolla/docs-csm
scripts/operations/node_management/Add_Remove_Replace_NCNs/ncn_status.py
Python
run_actions
run_actions
751
757
751
751
2ec193307ecfe25eab22ad38c3503d9c70d60c11
bigcode/the-stack
train
a1373773f68a38fcb3a6eaf9
train
class
class TestTZConvert(object): @pytest.mark.parametrize('tz', ['UTC', 'Asia/Tokyo', 'US/Eastern', 'Europe/Moscow']) def test_tz_convert_single_matches_tz_convert_hourly(self, tz): # US: 2014-03-09 - 2014-11-11 # MOSCOW: 2014-10-26 / 2014-12-31 tz_didx...
class TestTZConvert(object): @pytest.mark.parametrize('tz', ['UTC', 'Asia/Tokyo', 'US/Eastern', 'Europe/Moscow'])
def test_tz_convert_single_matches_tz_convert_hourly(self, tz): # US: 2014-03-09 - 2014-11-11 # MOSCOW: 2014-10-26 / 2014-12-31 tz_didx = date_range('2014-03-01', '2015-01-10', freq='H', tz=tz) utc_didx = date_range('2014-03-01', '2015-01-10', freq='H') compare_utc_to_local...
asi8) tm.assert_numpy_array_equal(result, result_single) def compare_local_to_utc(tz_didx, utc_didx): f = lambda x: conversion.tz_convert_single(x, tz_didx.tz, 'UTC') result = conversion.tz_convert(utc_didx.asi8, tz_didx.tz, 'UTC') result_single = np.vectorize(f)(utc_didx.asi8) tm.assert_numpy_arr...
136
136
456
34
102
JustinZhengBC/pandas
pandas/tests/tslibs/test_conversion.py
Python
TestTZConvert
TestTZConvert
27
58
27
30
4330b11eea32325435c17eb35e303471b25c1a21
bigcode/the-stack
train
a8cf8fd3ba0019d0f933e352
train
function
def compare_local_to_utc(tz_didx, utc_didx): f = lambda x: conversion.tz_convert_single(x, tz_didx.tz, 'UTC') result = conversion.tz_convert(utc_didx.asi8, tz_didx.tz, 'UTC') result_single = np.vectorize(f)(utc_didx.asi8) tm.assert_numpy_array_equal(result, result_single)
def compare_local_to_utc(tz_didx, utc_didx):
f = lambda x: conversion.tz_convert_single(x, tz_didx.tz, 'UTC') result = conversion.tz_convert(utc_didx.asi8, tz_didx.tz, 'UTC') result_single = np.vectorize(f)(utc_didx.asi8) tm.assert_numpy_array_equal(result, result_single)
= conversion.tz_convert(tz_didx.asi8, 'UTC', tz_didx.tz) result_single = np.vectorize(f)(tz_didx.asi8) tm.assert_numpy_array_equal(result, result_single) def compare_local_to_utc(tz_didx, utc_didx):
64
64
88
15
49
JustinZhengBC/pandas
pandas/tests/tslibs/test_conversion.py
Python
compare_local_to_utc
compare_local_to_utc
20
24
20
20
3bdac59adfb04783c907da1ef7b6e028cc1fcc30
bigcode/the-stack
train
66402a8f3ffedd0a91bbcc35
train
function
def compare_utc_to_local(tz_didx, utc_didx): f = lambda x: conversion.tz_convert_single(x, 'UTC', tz_didx.tz) result = conversion.tz_convert(tz_didx.asi8, 'UTC', tz_didx.tz) result_single = np.vectorize(f)(tz_didx.asi8) tm.assert_numpy_array_equal(result, result_single)
def compare_utc_to_local(tz_didx, utc_didx):
f = lambda x: conversion.tz_convert_single(x, 'UTC', tz_didx.tz) result = conversion.tz_convert(tz_didx.asi8, 'UTC', tz_didx.tz) result_single = np.vectorize(f)(tz_didx.asi8) tm.assert_numpy_array_equal(result, result_single)
-8 -*- import numpy as np import pytest from pandas._libs.tslib import iNaT from pandas._libs.tslibs import conversion, timezones from pandas import date_range import pandas.util.testing as tm def compare_utc_to_local(tz_didx, utc_didx):
64
64
88
15
48
JustinZhengBC/pandas
pandas/tests/tslibs/test_conversion.py
Python
compare_utc_to_local
compare_utc_to_local
13
17
13
13
cf47c3eb7827e3fb506a2a2ed4a39cebe437b63d
bigcode/the-stack
train
4ac89fb5fcb464ad5128784d
train
function
@app.callback( Output("slider-svm-parameter-gamma-power", "disabled"), [Input("dropdown-svm-parameter-kernel", "value")], ) def disable_slider_param_gamma_power(kernel): return kernel not in ["rbf", "poly", "sigmoid"]
@app.callback( Output("slider-svm-parameter-gamma-power", "disabled"), [Input("dropdown-svm-parameter-kernel", "value")], ) def disable_slider_param_gamma_power(kernel):
return kernel not in ["rbf", "poly", "sigmoid"]
_gamma_coef(kernel): return kernel not in ["rbf", "poly", "sigmoid"] @app.callback( Output("slider-svm-parameter-gamma-power", "disabled"), [Input("dropdown-svm-parameter-kernel", "value")], ) def disable_slider_param_gamma_power(kernel):
63
64
59
43
20
nathanrooy/dash-sample-apps
apps/dash-svm/app.py
Python
disable_slider_param_gamma_power
disable_slider_param_gamma_power
334
339
334
338
74614d0f2d757f37dfba2538966d22addc227172
bigcode/the-stack
train
1b6979349e55effaa46bbcbe
train
function
@app.callback( Output("slider-svm-parameter-C-coef", "marks"), [Input("slider-svm-parameter-C-power", "value")], ) def update_slider_svm_parameter_C_coef(power): scale = 10 ** power return {i: str(round(i * scale, 8)) for i in range(1, 10, 2)}
@app.callback( Output("slider-svm-parameter-C-coef", "marks"), [Input("slider-svm-parameter-C-power", "value")], ) def update_slider_svm_parameter_C_coef(power):
scale = 10 ** power return {i: str(round(i * scale, 8)) for i in range(1, 10, 2)}
scale, 8)) for i in range(1, 10, 2)} @app.callback( Output("slider-svm-parameter-C-coef", "marks"), [Input("slider-svm-parameter-C-power", "value")], ) def update_slider_svm_parameter_C_coef(power):
63
64
80
45
18
nathanrooy/dash-sample-apps
apps/dash-svm/app.py
Python
update_slider_svm_parameter_C_coef
update_slider_svm_parameter_C_coef
294
300
294
298
dead8769ccd47f180cfbd25925e20ebca9e7408c
bigcode/the-stack
train
05939b3602739b0093c6e9d2
train
function
@app.callback( Output("slider-svm-parameter-gamma-coef", "marks"), [Input("slider-svm-parameter-gamma-power", "value")], ) def update_slider_svm_parameter_gamma_coef(power): scale = 10 ** power return {i: str(round(i * scale, 8)) for i in range(1, 10, 2)}
@app.callback( Output("slider-svm-parameter-gamma-coef", "marks"), [Input("slider-svm-parameter-gamma-power", "value")], ) def update_slider_svm_parameter_gamma_coef(power):
scale = 10 ** power return {i: str(round(i * scale, 8)) for i in range(1, 10, 2)}
), ), ), ], ) ], ), ] ) @app.callback( Output("slider-svm-parameter-gamma-coef", "marks"), [Input("slider-svm-parameter-gamma-power", "value")], ) def update_slider_svm...
64
64
82
47
17
nathanrooy/dash-sample-apps
apps/dash-svm/app.py
Python
update_slider_svm_parameter_gamma_coef
update_slider_svm_parameter_gamma_coef
285
291
285
289
f20488cb19edf2d541030294e6f6319d1e5c9afc
bigcode/the-stack
train
ec5461b268d1cc2f0c435ce1
train
function
@app.callback( Output("slider-svm-parameter-gamma-coef", "disabled"), [Input("dropdown-svm-parameter-kernel", "value")], ) def disable_slider_param_gamma_coef(kernel): return kernel not in ["rbf", "poly", "sigmoid"]
@app.callback( Output("slider-svm-parameter-gamma-coef", "disabled"), [Input("dropdown-svm-parameter-kernel", "value")], ) def disable_slider_param_gamma_coef(kernel):
return kernel not in ["rbf", "poly", "sigmoid"]
", "value")], ) def disable_slider_param_degree(kernel): return kernel != "poly" @app.callback( Output("slider-svm-parameter-gamma-coef", "disabled"), [Input("dropdown-svm-parameter-kernel", "value")], ) def disable_slider_param_gamma_coef(kernel):
64
64
60
44
20
nathanrooy/dash-sample-apps
apps/dash-svm/app.py
Python
disable_slider_param_gamma_coef
disable_slider_param_gamma_coef
326
331
326
330
252ad72e28f84bb7900c3aac8517320f2f651fe6
bigcode/the-stack
train
6dfe366a31b34ed2b3578908
train
function
@app.callback( Output("div-graphs", "children"), [ Input("dropdown-svm-parameter-kernel", "value"), Input("slider-svm-parameter-degree", "value"), Input("slider-svm-parameter-C-coef", "value"), Input("slider-svm-parameter-C-power", "value"), Input("slider-svm-parameter-ga...
@app.callback( Output("div-graphs", "children"), [ Input("dropdown-svm-parameter-kernel", "value"), Input("slider-svm-parameter-degree", "value"), Input("slider-svm-parameter-C-coef", "value"), Input("slider-svm-parameter-C-power", "value"), Input("slider-svm-parameter-ga...
t_start = time.time() h = 0.3 # step size in the mesh # Data Pre-processing X, y = generate_data(n_samples=sample_size, dataset=dataset, noise=noise) X = StandardScaler().fit_transform(X) X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.4, random_state=42 ) ...
disabled"), [Input("dropdown-svm-parameter-kernel", "value")], ) def disable_slider_param_gamma_power(kernel): return kernel not in ["rbf", "poly", "sigmoid"] @app.callback( Output("div-graphs", "children"), [ Input("dropdown-svm-parameter-kernel", "value"), Input("slider-svm-parameter-d...
255
256
866
212
43
nathanrooy/dash-sample-apps
apps/dash-svm/app.py
Python
update_svm_graph
update_svm_graph
342
449
342
370
35ccb7537ccb07ea128b1beb87c73957a61e7735
bigcode/the-stack
train
2d60b0c6b72888040fd8876b
train
function
def generate_data(n_samples, dataset, noise): if dataset == "moons": return datasets.make_moons(n_samples=n_samples, noise=noise, random_state=0) elif dataset == "circles": return datasets.make_circles( n_samples=n_samples, noise=noise, factor=0.5, random_state=1 ) elif...
def generate_data(n_samples, dataset, noise):
if dataset == "moons": return datasets.make_moons(n_samples=n_samples, noise=noise, random_state=0) elif dataset == "circles": return datasets.make_circles( n_samples=n_samples, noise=noise, factor=0.5, random_state=1 ) elif dataset == "linear": X, y = datasets....
drc import utils.figures as figs app = dash.Dash( __name__, meta_tags=[ {"name": "viewport", "content": "width=device-width, initial-scale=1.0"} ], ) server = app.server def generate_data(n_samples, dataset, noise):
64
64
201
10
53
nathanrooy/dash-sample-apps
apps/dash-svm/app.py
Python
generate_data
generate_data
26
54
26
26
d688656b81c0b88eb39efc0a4459dd5f8d8de601
bigcode/the-stack
train
0d112d9cfa809ccaa41ec948
train
function
@app.callback( Output("slider-threshold", "value"), [Input("button-zero-threshold", "n_clicks")], [State("graph-sklearn-svm", "figure")], ) def reset_threshold_center(n_clicks, figure): if n_clicks: Z = np.array(figure["data"][0]["z"]) value = -Z.min() / (Z.max() - Z.min()) else: ...
@app.callback( Output("slider-threshold", "value"), [Input("button-zero-threshold", "n_clicks")], [State("graph-sklearn-svm", "figure")], ) def reset_threshold_center(n_clicks, figure):
if n_clicks: Z = np.array(figure["data"][0]["z"]) value = -Z.min() / (Z.max() - Z.min()) else: value = 0.4959986285375595 return value
(1, 10, 2)} @app.callback( Output("slider-threshold", "value"), [Input("button-zero-threshold", "n_clicks")], [State("graph-sklearn-svm", "figure")], ) def reset_threshold_center(n_clicks, figure):
63
64
110
54
9
nathanrooy/dash-sample-apps
apps/dash-svm/app.py
Python
reset_threshold_center
reset_threshold_center
303
314
303
308
8c18b45a00570fbcd90d2fac213118fdbcc5edc8
bigcode/the-stack
train
94da9dacfe16ef9f4b06a69f
train
function
@app.callback( Output("slider-svm-parameter-degree", "disabled"), [Input("dropdown-svm-parameter-kernel", "value")], ) def disable_slider_param_degree(kernel): return kernel != "poly"
@app.callback( Output("slider-svm-parameter-degree", "disabled"), [Input("dropdown-svm-parameter-kernel", "value")], ) def disable_slider_param_degree(kernel):
return kernel != "poly"
.4959986285375595 return value # Disable Sliders if kernel not in the given list @app.callback( Output("slider-svm-parameter-degree", "disabled"), [Input("dropdown-svm-parameter-kernel", "value")], ) def disable_slider_param_degree(kernel):
64
64
47
40
23
nathanrooy/dash-sample-apps
apps/dash-svm/app.py
Python
disable_slider_param_degree
disable_slider_param_degree
318
323
318
322
3e69204522c82889335493306b9dc420059b4584
bigcode/the-stack
train
3375e622c22478be52029682
train
class
class SCREENSHOT: SC_DATA = b"" def __init__(self): self.generate() def generate(self): obj = io.BytesIO() im = pyscreenshot.grab() im.save(obj, format="PNG") self.SC_DATA = obj.getvalue() def get_data(self): return self.SC_DATA
class SCREENSHOT:
SC_DATA = b"" def __init__(self): self.generate() def generate(self): obj = io.BytesIO() im = pyscreenshot.grab() im.save(obj, format="PNG") self.SC_DATA = obj.getvalue() def get_data(self): return self.SC_DATA
class SCREENSHOT:
4
64
72
4
0
hirusha-adi/UnSillyRAT
mods/screenshot.py
Python
SCREENSHOT
SCREENSHOT
1
15
1
2
68c42a94e80e637eb0f7d219efdfa7d6b2c44f16
bigcode/the-stack
train
693d3a1f4ba68945a26b74e3
train
function
def main(): # print headers print("Seconds\t\tDistance in Meters") print("----------------------------------") # to pass arguments from 1 to 10 write an for loop for t in range(1, 11, 1): distance = falling_distance(t) print(t, "\t\t", format(distance, ",.2f"))
def main(): # print headers
print("Seconds\t\tDistance in Meters") print("----------------------------------") # to pass arguments from 1 to 10 write an for loop for t in range(1, 11, 1): distance = falling_distance(t) print(t, "\t\t", format(distance, ",.2f"))
# falling distance G = 9.8 def main(): # print headers
19
64
77
8
10
SergeHall/Tony-Gaddis-Python-4th
chapter_05/14_falling_distance.py
Python
main
main
6
13
6
7
8447ba84e4a634e7babd5f806fdd963346daf7ca
bigcode/the-stack
train
e4dc1c96fee9ef2d8b69a356
train
function
def falling_distance(falling_time): distance = (1 / 2) * G * (falling_time) ** 2 return distance
def falling_distance(falling_time):
distance = (1 / 2) * G * (falling_time) ** 2 return distance
for t in range(1, 11, 1): distance = falling_distance(t) print(t, "\t\t", format(distance, ",.2f")) # this is our falling_distance function. return distance to main function where # it is called. def falling_distance(falling_time):
64
64
32
7
57
SergeHall/Tony-Gaddis-Python-4th
chapter_05/14_falling_distance.py
Python
falling_distance
falling_distance
18
20
18
18
efce8e9b846e7b381db46246b65abc4e4eaa38e4
bigcode/the-stack
train
e46a4bf3b75ecb1fa6f4423c
train
function
def on_btn(pressed): global running if pressed: running = False
def on_btn(pressed):
global running if pressed: running = False
= Vernie() running = True criterion = min cur_luminosity = 0 def on_change_lum(lumn, unknown): del unknown global cur_luminosity cur_luminosity = lumn lum_values = {} def on_btn(pressed):
63
64
19
6
57
adamfazzari/pylgbst
examples/vernie/go_towards_light.py
Python
on_btn
on_btn
24
27
24
24
806b9afe933e30ceae3f776b9178fac14c919077
bigcode/the-stack
train
fbf36ad38e0d065e52976e93
train
function
def on_turn(angl): lum_values[angl] = cur_luminosity
def on_turn(angl):
lum_values[angl] = cur_luminosity
def on_change_lum(lumn, unknown): del unknown global cur_luminosity cur_luminosity = lumn lum_values = {} def on_btn(pressed): global running if pressed: running = False def on_turn(angl):
64
64
21
7
56
adamfazzari/pylgbst
examples/vernie/go_towards_light.py
Python
on_turn
on_turn
30
31
30
30
79dc9612d02b28467f01b15f964fc94445f95832
bigcode/the-stack
train
feabad8ba9b4cbd0d44098c3
train
function
def on_change_lum(lumn, unknown): del unknown global cur_luminosity cur_luminosity = lumn
def on_change_lum(lumn, unknown):
del unknown global cur_luminosity cur_luminosity = lumn
import logging from examples.vernie import Vernie from pylgbst.peripherals import VisionSensor logging.basicConfig(level=logging.INFO) robot = Vernie() running = True criterion = min cur_luminosity = 0 def on_change_lum(lumn, unknown):
60
64
32
10
49
adamfazzari/pylgbst
examples/vernie/go_towards_light.py
Python
on_change_lum
on_change_lum
15
18
15
15
376ac554e830f75078029a142ae26f87fc701a21
bigcode/the-stack
train
b2ba7a6d3382e4604252b310
train
class
class ImportGraphDefTest(test.TestCase): def _MakeGraphDef(self, text, producer=versions.GRAPH_DEF_VERSION, min_consumer=versions.GRAPH_DEF_VERSION_MIN_CONSUMER): text = "versions: { producer: %d min_consumer: %d };\n%s" % (producer, ...
class ImportGraphDefTest(test.TestCase):
def _MakeGraphDef(self, text, producer=versions.GRAPH_DEF_VERSION, min_consumer=versions.GRAPH_DEF_VERSION_MIN_CONSUMER): text = "versions: { producer: %d min_consumer: %d };\n%s" % (producer, ...
. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for tensorflow.python.framework.importer.""" from __future__ import absolute_import from __future__ import division from __f...
256
256
12,116
9
246
irvifa/tensorflow
tensorflow/python/framework/importer_test.py
Python
ImportGraphDefTest
ImportGraphDefTest
48
1,274
48
49
3ea08af85e8cbb0111fc574828bc76add34fee41
bigcode/the-stack
train
51b653ea304de5513cd589b3
train
class
@utils.registerPlexObject class Collection(PlexPartialObject, ArtMixin, PosterMixin, LabelMixin): """ Represents a single Collection. Attributes: TAG (str): 'Directory' TYPE (str): 'collection' addedAt (datetime): Datetime the collection was added to the library. ...
@utils.registerPlexObject class Collection(PlexPartialObject, ArtMixin, PosterMixin, LabelMixin):
""" Represents a single Collection. Attributes: TAG (str): 'Directory' TYPE (str): 'collection' addedAt (datetime): Datetime the collection was added to the library. art (str): URL to artwork image (/library/metadata/<ratingKey>/art/<artid>). artB...
# -*- coding: utf-8 -*- from plexapi import media, utils from plexapi.base import PlexPartialObject from plexapi.exceptions import BadRequest from plexapi.mixins import ArtMixin, PosterMixin from plexapi.mixins import LabelMixin from plexapi.settings import Setting from plexapi.utils import deprecated @utils.registerPl...
91
256
1,598
23
67
JonnyWong16/python-plexapi
plexapi/collection.py
Python
Collection
Collection
11
163
11
12
6916c6ade1dab38373052613fc67752036e948c1
bigcode/the-stack
train
7ca40ef3d372b2a3f1d9ef61
train
function
def histogram(vals, thresholds): nbins = int(np.sqrt(vals.size)) h_up = np.histogram(vals, bins=nbins)[0].max() hist = go.Histogram(x=vals, nbinsx=nbins) fig = go.Figure(data=[hist] + [ go.Scatter(x=[x, x], y=[0, h_up], mode='lines', name='Threshold {0}'.format(idx + 1)) ...
def histogram(vals, thresholds):
nbins = int(np.sqrt(vals.size)) h_up = np.histogram(vals, bins=nbins)[0].max() hist = go.Histogram(x=vals, nbinsx=nbins) fig = go.Figure(data=[hist] + [ go.Scatter(x=[x, x], y=[0, h_up], mode='lines', name='Threshold {0}'.format(idx + 1)) for idx, x in enumerate(thresh...
import numpy as np import plotly.graph_objects as go from scipy.stats import norm def histogram(vals, thresholds):
25
64
115
6
18
gmrukwa/msi-preprocessing-pipeline
plot.py
Python
histogram
histogram
6
15
6
6
8a6fb4a68233bd7914977c6b6df0fe67bbcaf935
bigcode/the-stack
train
afb316085bc3187ad37e9f14
train
function
def save_decomposition(vals, thresholds, path): fig = histogram(vals, thresholds) with path.temporary_path() as tmp_path: fig.write_html(tmp_path)
def save_decomposition(vals, thresholds, path):
fig = histogram(vals, thresholds) with path.temporary_path() as tmp_path: fig.write_html(tmp_path)
] + [ go.Scatter(x=[x, x], y=[0, h_up], mode='lines', name='Threshold {0}'.format(idx + 1)) for idx, x in enumerate(thresholds) ]) return fig def save_decomposition(vals, thresholds, path):
64
64
36
10
53
gmrukwa/msi-preprocessing-pipeline
plot.py
Python
save_decomposition
save_decomposition
18
21
18
18
45541cbe8986a8da8c1b12c0e605886089af6cce
bigcode/the-stack
train
ffa57779f085efd211cf0a16
train
function
def train(): if args.dataset == 'COCO': if args.dataset_root == VOC_ROOT: if not os.path.exists(COCO_ROOT): parser.error('Must specify dataset_root if specifying dataset') print("WARNING: Using default COCO dataset_root because " + "--dataset_root wa...
def train():
if args.dataset == 'COCO': if args.dataset_root == VOC_ROOT: if not os.path.exists(COCO_ROOT): parser.error('Must specify dataset_root if specifying dataset') print("WARNING: Using default COCO dataset_root because " + "--dataset_root was not specifi...
') parser.add_argument('--lr', '--learning-rate', default=1e-3, type=float, help='initial learning rate') parser.add_argument('--momentum', default=0.9, type=float, help='Momentum value for optim') parser.add_argument('--weight_decay', default=5e-4, type=float, ...
256
256
1,098
3
253
vanellope666/ssd.pytorch
train.py
Python
train
train
71
203
71
71
fd76aa82db6a7a2a1c760d591a5759f7ab43cbd3
bigcode/the-stack
train
ac1546d3987f6a84dc234c3d
train
function
def weights_init(m): if isinstance(m, nn.Conv2d): xavier(m.weight.data) m.bias.data.zero_()
def weights_init(m):
if isinstance(m, nn.Conv2d): xavier(m.weight.data) m.bias.data.zero_()
ERROR: type should be string, got " https://github.com/pytorch/examples/blob/master/imagenet/main.py\n \"\"\"\n lr = args.lr * (gamma ** (step))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\n\ndef xavier(param):\n init.xavier_uniform(param)\ndef weights_init(m):\n"
64
64
29
5
59
vanellope666/ssd.pytorch
train.py
Python
weights_init
weights_init
221
224
221
221
11c7e4a7df1ad15a78dc4d6f6eb84363b46a981a
bigcode/the-stack
train
6f5b641f96d42b3ae7033938
train
function
def adjust_learning_rate(optimizer, gamma, step): """Sets the learning rate to the initial LR decayed by 10 at every specified step # Adapted from PyTorch Imagenet example: # https://github.com/pytorch/examples/blob/master/imagenet/main.py """ lr = args.lr * (gamma ** (step)) for param_g...
def adjust_learning_rate(optimizer, gamma, step):
"""Sets the learning rate to the initial LR decayed by 10 at every specified step # Adapted from PyTorch Imagenet example: # https://github.com/pytorch/examples/blob/master/imagenet/main.py """ lr = args.lr * (gamma ** (step)) for param_group in optimizer.param_groups: param_grou...
, iter:', iteration) torch.save(ssd_net.state_dict(), 'weights/ssd300_VOC_' + repr(iteration) + '.pth') torch.save(ssd_net.state_dict(), args.save_folder + '' + args.dataset + '.pth') def adjust_learning_rate(optimizer, gamma, step):
64
64
93
11
53
vanellope666/ssd.pytorch
train.py
Python
adjust_learning_rate
adjust_learning_rate
206
214
206
206
64288de75530dc7a6808662a056f84ef5f4c30de
bigcode/the-stack
train
e21c9ea3154425cab82183cc
train
function
def str2bool(v): return v.lower() in ("yes", "true", "t", "1")
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
import time import torch from torch.autograd import Variable import torch.nn as nn import torch.optim as optim import torch.backends.cudnn as cudnn import torch.nn.init as init import torch.utils.data as data import numpy as np import argparse def str2bool(v):
64
64
24
6
57
vanellope666/ssd.pytorch
train.py
Python
str2bool
str2bool
19
20
19
19
e41af02bac2983779a4f54de7a33049b3bc88a55
bigcode/the-stack
train