nwo
stringlengths
5
106
sha
stringlengths
40
40
path
stringlengths
4
174
language
stringclasses
1 value
identifier
stringlengths
1
140
parameters
stringlengths
0
87.7k
argument_list
stringclasses
1 value
return_statement
stringlengths
0
426k
docstring
stringlengths
0
64.3k
docstring_summary
stringlengths
0
26.3k
docstring_tokens
list
function
stringlengths
18
4.83M
function_tokens
list
url
stringlengths
83
304
rikdz/GraphWriter
f228420aa48697dfb7a1ced3a62f955031664ed3
models/beam.py
python
Beam.dup_obj
(self,obj)
return new_obj
[]
def dup_obj(self,obj): new_obj = beam_obj(None,None,None,None,None) new_obj.words = [x for x in obj.words] new_obj.score = obj.score new_obj.prevent = obj.prevent new_obj.firstwords = [x for x in obj.firstwords] new_obj.isstart = obj.isstart return new_obj
[ "def", "dup_obj", "(", "self", ",", "obj", ")", ":", "new_obj", "=", "beam_obj", "(", "None", ",", "None", ",", "None", ",", "None", ",", "None", ")", "new_obj", ".", "words", "=", "[", "x", "for", "x", "in", "obj", ".", "words", "]", "new_obj", ...
https://github.com/rikdz/GraphWriter/blob/f228420aa48697dfb7a1ced3a62f955031664ed3/models/beam.py#L38-L45
tensorflow/tfx
b4a6b83269815ed12ba9df9e9154c7376fef2ea0
tfx/examples/cifar10/cifar10_utils_native_keras.py
python
run_fn
(fn_args: FnArgs)
Train the model based on given args. Args: fn_args: Holds args used to train the model as name/value pairs. Raises: ValueError: if invalid inputs.
Train the model based on given args.
[ "Train", "the", "model", "based", "on", "given", "args", "." ]
def run_fn(fn_args: FnArgs): """Train the model based on given args. Args: fn_args: Holds args used to train the model as name/value pairs. Raises: ValueError: if invalid inputs. """ tf_transform_output = tft.TFTransformOutput(fn_args.transform_output) train_dataset = _input_fn( fn_args.train_files, fn_args.data_accessor, tf_transform_output, is_train=True, batch_size=_TRAIN_BATCH_SIZE) eval_dataset = _input_fn( fn_args.eval_files, fn_args.data_accessor, tf_transform_output, is_train=False, batch_size=_EVAL_BATCH_SIZE) model, base_model = _build_keras_model() absl.logging.info('Tensorboard logging to {}'.format(fn_args.model_run_dir)) # Write logs to path tensorboard_callback = tf.keras.callbacks.TensorBoard( log_dir=fn_args.model_run_dir, update_freq='batch') # Our training regime has two phases: we first freeze the backbone and train # the newly added classifier only, then unfreeze part of the backbone and # fine-tune with classifier jointly. steps_per_epoch = int(_TRAIN_DATA_SIZE / _TRAIN_BATCH_SIZE) total_epochs = int(fn_args.train_steps / steps_per_epoch) if _CLASSIFIER_EPOCHS > total_epochs: raise ValueError('Classifier epochs is greater than the total epochs') absl.logging.info('Start training the top classifier') model.fit( train_dataset, epochs=_CLASSIFIER_EPOCHS, steps_per_epoch=steps_per_epoch, validation_data=eval_dataset, validation_steps=fn_args.eval_steps, callbacks=[tensorboard_callback]) absl.logging.info('Start fine-tuning the model') # Unfreeze the top MobileNet layers and do joint fine-tuning _freeze_model_by_percentage(base_model, 0.9) # We need to recompile the model because layer properties have changed model.compile( loss='sparse_categorical_crossentropy', optimizer=tf.keras.optimizers.RMSprop(lr=_FINETUNE_LEARNING_RATE), metrics=['sparse_categorical_accuracy']) model.summary(print_fn=absl.logging.info) model.fit( train_dataset, initial_epoch=_CLASSIFIER_EPOCHS, epochs=total_epochs, steps_per_epoch=steps_per_epoch, validation_data=eval_dataset, validation_steps=fn_args.eval_steps, callbacks=[tensorboard_callback]) # Prepare the TFLite model used for serving in MLKit signatures = { 'serving_default': _get_serve_image_fn(model).get_concrete_function( tf.TensorSpec( shape=[None, 224, 224, 3], dtype=tf.float32, name=_transformed_name(_IMAGE_KEY))) } temp_saving_model_dir = os.path.join(fn_args.serving_model_dir, 'temp') model.save(temp_saving_model_dir, save_format='tf', signatures=signatures) tfrw = rewriter_factory.create_rewriter( rewriter_factory.TFLITE_REWRITER, name='tflite_rewriter') converters.rewrite_saved_model(temp_saving_model_dir, fn_args.serving_model_dir, tfrw, rewriter.ModelType.TFLITE_MODEL) # Add necessary TFLite metadata to the model in order to use it within MLKit # TODO(dzats@): Handle label map file path more properly, currently # hard-coded. tflite_model_path = os.path.join(fn_args.serving_model_dir, _TFLITE_MODEL_NAME) # TODO(dzats@): Extend the TFLite rewriter to be able to add TFLite metadata #@ to the model. _write_metadata( model_path=tflite_model_path, label_map_path=fn_args.custom_config['labels_path'], mean=[127.5], std=[127.5]) fileio.rmtree(temp_saving_model_dir)
[ "def", "run_fn", "(", "fn_args", ":", "FnArgs", ")", ":", "tf_transform_output", "=", "tft", ".", "TFTransformOutput", "(", "fn_args", ".", "transform_output", ")", "train_dataset", "=", "_input_fn", "(", "fn_args", ".", "train_files", ",", "fn_args", ".", "da...
https://github.com/tensorflow/tfx/blob/b4a6b83269815ed12ba9df9e9154c7376fef2ea0/tfx/examples/cifar10/cifar10_utils_native_keras.py#L304-L405
fedora-infra/bodhi
2b1df12d85eb2e575d8e481a3936c4f92d1fe29a
bodhi/server/migrations/versions/5c86a3f9dc03_drop_support_for_cve_tracking.py
python
downgrade
()
Recreate the cves table and related association tables.
Recreate the cves table and related association tables.
[ "Recreate", "the", "cves", "table", "and", "related", "association", "tables", "." ]
def downgrade(): """Recreate the cves table and related association tables.""" op.create_table( 'cves', sa.Column('id', sa.INTEGER(), server_default=sa.text("nextval('cves_id_seq'::regclass)"), autoincrement=True, nullable=False), sa.Column('cve_id', sa.VARCHAR(length=13), autoincrement=False, nullable=False), sa.PrimaryKeyConstraint('id', name='cves_pkey'), sa.UniqueConstraint('cve_id', name='cves_cve_id_key'), postgresql_ignore_search_path=False) op.create_table( 'bug_cve_table', sa.Column('bug_id', sa.INTEGER(), autoincrement=False, nullable=True), sa.Column('cve_id', sa.INTEGER(), autoincrement=False, nullable=True), sa.ForeignKeyConstraint(['bug_id'], ['bugs.id'], name='bug_cve_table_bug_id_fkey'), sa.ForeignKeyConstraint(['cve_id'], ['cves.id'], name='bug_cve_table_cve_id_fkey')) op.create_table( 'update_cve_table', sa.Column('update_id', sa.INTEGER(), autoincrement=False, nullable=True), sa.Column('cve_id', sa.INTEGER(), autoincrement=False, nullable=True), sa.ForeignKeyConstraint(['cve_id'], ['cves.id'], name='update_cve_table_cve_id_fkey'), sa.ForeignKeyConstraint(['update_id'], ['updates.id'], name='update_cve_table_update_id_fkey'))
[ "def", "downgrade", "(", ")", ":", "op", ".", "create_table", "(", "'cves'", ",", "sa", ".", "Column", "(", "'id'", ",", "sa", ".", "INTEGER", "(", ")", ",", "server_default", "=", "sa", ".", "text", "(", "\"nextval('cves_id_seq'::regclass)\"", ")", ",",...
https://github.com/fedora-infra/bodhi/blob/2b1df12d85eb2e575d8e481a3936c4f92d1fe29a/bodhi/server/migrations/versions/5c86a3f9dc03_drop_support_for_cve_tracking.py#L41-L63
lovelylain/pyctp
fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d
example/pyctp2/trader/position.py
python
Position.volume_accomplished2
(self)
return num_opened - num_closed
[]
def volume_accomplished2(self): num_opened = self._get_accomplished2(self._open_orders) num_closed = self._get_accomplished2(self._close_orders) return num_opened - num_closed
[ "def", "volume_accomplished2", "(", "self", ")", ":", "num_opened", "=", "self", ".", "_get_accomplished2", "(", "self", ".", "_open_orders", ")", "num_closed", "=", "self", ".", "_get_accomplished2", "(", "self", ".", "_close_orders", ")", "return", "num_opened...
https://github.com/lovelylain/pyctp/blob/fd304de4b50c4ddc31a4190b1caaeb5dec66bc5d/example/pyctp2/trader/position.py#L395-L398
openshift/openshift-tools
1188778e728a6e4781acf728123e5b356380fe6f
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_adm_router.py
python
DeploymentConfig.update_env_var
(self, key, value)
return True
place an env in the env var list
place an env in the env var list
[ "place", "an", "env", "in", "the", "env", "var", "list" ]
def update_env_var(self, key, value): '''place an env in the env var list''' env_vars_array = self.get_env_vars() idx = None for env_idx, env_var in enumerate(env_vars_array): if env_var['name'] == key: idx = env_idx break if idx: env_vars_array[idx]['value'] = value else: self.add_env_value(key, value) return True
[ "def", "update_env_var", "(", "self", ",", "key", ",", "value", ")", ":", "env_vars_array", "=", "self", ".", "get_env_vars", "(", ")", "idx", "=", "None", "for", "env_idx", ",", "env_var", "in", "enumerate", "(", "env_vars_array", ")", ":", "if", "env_v...
https://github.com/openshift/openshift-tools/blob/1188778e728a6e4781acf728123e5b356380fe6f/openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/lib_vendored_deps/library/oc_adm_router.py#L1942-L1957
python/cpython
e13cdca0f5224ec4e23bdd04bb3120506964bc8b
Lib/_pydecimal.py
python
Context.copy
(self)
return nc
Returns a deep copy from self.
Returns a deep copy from self.
[ "Returns", "a", "deep", "copy", "from", "self", "." ]
def copy(self): """Returns a deep copy from self.""" nc = Context(self.prec, self.rounding, self.Emin, self.Emax, self.capitals, self.clamp, self.flags.copy(), self.traps.copy(), self._ignored_flags) return nc
[ "def", "copy", "(", "self", ")", ":", "nc", "=", "Context", "(", "self", ".", "prec", ",", "self", ".", "rounding", ",", "self", ".", "Emin", ",", "self", ".", "Emax", ",", "self", ".", "capitals", ",", "self", ".", "clamp", ",", "self", ".", "...
https://github.com/python/cpython/blob/e13cdca0f5224ec4e23bdd04bb3120506964bc8b/Lib/_pydecimal.py#L4015-L4021
tendenci/tendenci
0f2c348cc0e7d41bc56f50b00ce05544b083bf1d
tendenci/apps/make_payments/utils.py
python
make_payment_inv_add
(user, make_payment, **kwargs)
return inv
[]
def make_payment_inv_add(user, make_payment, **kwargs): inv = Invoice() # field to be populated to invoice inv.title = _("Make Payment Invoice") inv.bill_to = make_payment.first_name + ' ' + make_payment.last_name inv.bill_to_first_name = make_payment.first_name inv.bill_to_last_name = make_payment.last_name inv.bill_to_company = make_payment.company inv.bill_to_address = '%s %s' % (make_payment.address, make_payment.address2) inv.bill_to_city = make_payment.city inv.bill_to_state = make_payment.state inv.bill_to_zip_code = make_payment.zip_code inv.bill_to_country = make_payment.country inv.bill_to_phone = make_payment.phone inv.bill_to_email = make_payment.email inv.ship_to = make_payment.first_name + ' ' + make_payment.last_name inv.ship_to_first_name = make_payment.first_name inv.ship_to_last_name = make_payment.last_name inv.ship_to_company = make_payment.company inv.ship_to_address = '%s %s' % (make_payment.address, make_payment.address2) inv.ship_to_city = make_payment.city or '' inv.ship_to_state = make_payment.state or '' inv.ship_to_zip_code = make_payment.zip_code or '' inv.ship_to_country = make_payment.country or '' inv.ship_to_phone = make_payment.phone or '' inv.ship_to_email = make_payment.email or '' inv.terms = "Due on Receipt" inv.due_date = datetime.now() inv.ship_date = datetime.now() inv.message = 'Thank You.' inv.status = True inv.estimate = True inv.status_detail = 'estimate' inv.object_type = ContentType.objects.get(app_label=make_payment._meta.app_label, model=make_payment._meta.model_name) inv.object_id = make_payment.id inv.subtotal = make_payment.payment_amount inv.total = make_payment.payment_amount inv.balance = make_payment.payment_amount if user and not user.is_anonymous: inv.set_creator(user) inv.set_owner(user) inv.save(user) # tender the invoice inv.tender(user) make_payment.invoice_id = inv.id return inv
[ "def", "make_payment_inv_add", "(", "user", ",", "make_payment", ",", "*", "*", "kwargs", ")", ":", "inv", "=", "Invoice", "(", ")", "# field to be populated to invoice", "inv", ".", "title", "=", "_", "(", "\"Make Payment Invoice\"", ")", "inv", ".", "bill_to...
https://github.com/tendenci/tendenci/blob/0f2c348cc0e7d41bc56f50b00ce05544b083bf1d/tendenci/apps/make_payments/utils.py#L8-L59
SheffieldML/GPy
bb1bc5088671f9316bc92a46d356734e34c2d5c0
GPy/inference/latent_function_inference/var_dtc_parallel.py
python
VarDTC_minibatch.inference_minibatch
(self, kern, X, Z, likelihood, Y)
return isEnd, (n_start,n_end), grad_dict
The second phase of inference: Computing the derivatives over a minibatch of Y Compute: dL_dpsi0, dL_dpsi1, dL_dpsi2, dL_dthetaL return a flag showing whether it reached the end of Y (isEnd)
The second phase of inference: Computing the derivatives over a minibatch of Y Compute: dL_dpsi0, dL_dpsi1, dL_dpsi2, dL_dthetaL return a flag showing whether it reached the end of Y (isEnd)
[ "The", "second", "phase", "of", "inference", ":", "Computing", "the", "derivatives", "over", "a", "minibatch", "of", "Y", "Compute", ":", "dL_dpsi0", "dL_dpsi1", "dL_dpsi2", "dL_dthetaL", "return", "a", "flag", "showing", "whether", "it", "reached", "the", "en...
def inference_minibatch(self, kern, X, Z, likelihood, Y): """ The second phase of inference: Computing the derivatives over a minibatch of Y Compute: dL_dpsi0, dL_dpsi1, dL_dpsi2, dL_dthetaL return a flag showing whether it reached the end of Y (isEnd) """ num_data, output_dim = Y.shape if isinstance(X, VariationalPosterior): uncertain_inputs = True else: uncertain_inputs = False #see whether we've got a different noise variance for each datum beta = 1./np.fmax(likelihood.variance, 1e-6) het_noise = beta.size > 1 # VVT_factor is a matrix such that tdot(VVT_factor) = VVT...this is for efficiency! #self.YYTfactor = beta*self.get_YYTfactor(Y) if self.Y_speedup and not het_noise: YYT_factor = self.get_YYTfactor(Y) else: YYT_factor = Y n_start = self.batch_pos batchsize = num_data if self.batchsize is None else self.batchsize n_end = min(batchsize+n_start, num_data) if n_end==num_data: isEnd = True self.batch_pos = 0 else: isEnd = False self.batch_pos = n_end if batchsize==num_data: Y_slice = YYT_factor X_slice =X else: Y_slice = YYT_factor[n_start:n_end] X_slice = X[n_start:n_end] if not uncertain_inputs: psi0 = kern.Kdiag(X_slice) psi1 = kern.K(X_slice, Z) psi2 = None betapsi1 = np.einsum('n,nm->nm',beta,psi1) elif het_noise: psi0 = kern.psi0(Z, X_slice) psi1 = kern.psi1(Z, X_slice) psi2 = kern.psi2(Z, X_slice) betapsi1 = np.einsum('n,nm->nm',beta,psi1) if het_noise: beta = beta[n_start] # assuming batchsize==1 betaY = beta*Y_slice #====================================================================== # Load Intermediate Results #====================================================================== dL_dpsi2R = self.midRes['dL_dpsi2R'] v = self.midRes['v'] #====================================================================== # Compute dL_dpsi #====================================================================== dL_dpsi0 = -output_dim * (beta * np.ones((n_end-n_start,)))/2. dL_dpsi1 = np.dot(betaY,v.T) if uncertain_inputs: dL_dpsi2 = beta* dL_dpsi2R else: dL_dpsi1 += np.dot(betapsi1,dL_dpsi2R)*2. dL_dpsi2 = None #====================================================================== # Compute dL_dthetaL #====================================================================== if het_noise: if uncertain_inputs: psiR = np.einsum('mo,mo->',dL_dpsi2R,psi2) else: psiR = np.einsum('nm,no,mo->',psi1,psi1,dL_dpsi2R) dL_dthetaL = ((np.square(betaY)).sum(axis=-1) + np.square(beta)*(output_dim*psi0)-output_dim*beta)/2. - np.square(beta)*psiR- (betaY*np.dot(betapsi1,v)).sum(axis=-1) else: if isEnd: dL_dthetaL = self.midRes['dL_dthetaL'] else: dL_dthetaL = 0. if uncertain_inputs: grad_dict = {'dL_dpsi0':dL_dpsi0, 'dL_dpsi1':dL_dpsi1, 'dL_dpsi2':dL_dpsi2, 'dL_dthetaL':dL_dthetaL} else: grad_dict = {'dL_dKdiag':dL_dpsi0, 'dL_dKnm':dL_dpsi1, 'dL_dthetaL':dL_dthetaL} return isEnd, (n_start,n_end), grad_dict
[ "def", "inference_minibatch", "(", "self", ",", "kern", ",", "X", ",", "Z", ",", "likelihood", ",", "Y", ")", ":", "num_data", ",", "output_dim", "=", "Y", ".", "shape", "if", "isinstance", "(", "X", ",", "VariationalPosterior", ")", ":", "uncertain_inpu...
https://github.com/SheffieldML/GPy/blob/bb1bc5088671f9316bc92a46d356734e34c2d5c0/GPy/inference/latent_function_inference/var_dtc_parallel.py#L229-L334
awslabs/autogluon
7309118f2ab1c9519f25acf61a283a95af95842b
tabular/src/autogluon/tabular/models/fastainn/tabular_nn_fastai.py
python
NNFastAiTabularModel.__get_objective_func_to_monitor
(self, objective_func_name)
return objective_func_name_to_monitor
[]
def __get_objective_func_to_monitor(self, objective_func_name): monitor_obj_func = { **{k: m.name if hasattr(m, 'name') else m.__name__ for k, m in self.__get_metrics_map().items() if m is not None}, 'log_loss': 'valid_loss' } objective_func_name_to_monitor = objective_func_name if objective_func_name in monitor_obj_func: objective_func_name_to_monitor = monitor_obj_func[objective_func_name] return objective_func_name_to_monitor
[ "def", "__get_objective_func_to_monitor", "(", "self", ",", "objective_func_name", ")", ":", "monitor_obj_func", "=", "{", "*", "*", "{", "k", ":", "m", ".", "name", "if", "hasattr", "(", "m", ",", "'name'", ")", "else", "m", ".", "__name__", "for", "k",...
https://github.com/awslabs/autogluon/blob/7309118f2ab1c9519f25acf61a283a95af95842b/tabular/src/autogluon/tabular/models/fastainn/tabular_nn_fastai.py#L365-L373
holzschu/Carnets
44effb10ddfc6aa5c8b0687582a724ba82c6b547
Library/lib/python3.7/tkinter/__init__.py
python
Listbox.itemconfigure
(self, index, cnf=None, **kw)
return self._configure(('itemconfigure', index), cnf, kw)
Configure resources of an ITEM. The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method without arguments. Valid resource names: background, bg, foreground, fg, selectbackground, selectforeground.
Configure resources of an ITEM.
[ "Configure", "resources", "of", "an", "ITEM", "." ]
def itemconfigure(self, index, cnf=None, **kw): """Configure resources of an ITEM. The values for resources are specified as keyword arguments. To get an overview about the allowed keyword arguments call the method without arguments. Valid resource names: background, bg, foreground, fg, selectbackground, selectforeground.""" return self._configure(('itemconfigure', index), cnf, kw)
[ "def", "itemconfigure", "(", "self", ",", "index", ",", "cnf", "=", "None", ",", "*", "*", "kw", ")", ":", "return", "self", ".", "_configure", "(", "(", "'itemconfigure'", ",", "index", ")", ",", "cnf", ",", "kw", ")" ]
https://github.com/holzschu/Carnets/blob/44effb10ddfc6aa5c8b0687582a724ba82c6b547/Library/lib/python3.7/tkinter/__init__.py#L2848-L2856
mapillary/seamseg
77195ff7829af6e3076caefe49c4c69c817e30d6
seamseg/utils/misc.py
python
norm_act_from_config
(body_config)
return norm_act_static, norm_act_dynamic
Make normalization + activation function from configuration Available normalization modes are: - `bn`: Standard In-Place Batch Normalization - `syncbn`: Synchronized In-Place Batch Normalization - `syncbn+bn`: Synchronized In-Place Batch Normalization in the "static" part of the network, Standard In-Place Batch Normalization in the "dynamic" parts - `gn`: Group Normalization - `syncbn+gn`: Synchronized In-Place Batch Normalization in the "static" part of the network, Group Normalization in the "dynamic" parts - `off`: No normalization (preserve scale and bias parameters) The "static" part of the network includes the backbone, FPN and semantic segmentation components, while the "dynamic" part of the network includes the RPN, detection and instance segmentation components. Note that this distinction is due to historical reasons and for back-compatibility with the CVPR2019 pre-trained models. Parameters ---------- body_config Configuration object containing the following fields: `normalization_mode`, `activation`, `activation_slope` and `gn_groups` Returns ------- norm_act_static : callable Function that returns norm_act modules for the static parts of the network norm_act_dynamic : callable Function that returns norm_act modules for the dynamic parts of the network
Make normalization + activation function from configuration
[ "Make", "normalization", "+", "activation", "function", "from", "configuration" ]
def norm_act_from_config(body_config): """Make normalization + activation function from configuration Available normalization modes are: - `bn`: Standard In-Place Batch Normalization - `syncbn`: Synchronized In-Place Batch Normalization - `syncbn+bn`: Synchronized In-Place Batch Normalization in the "static" part of the network, Standard In-Place Batch Normalization in the "dynamic" parts - `gn`: Group Normalization - `syncbn+gn`: Synchronized In-Place Batch Normalization in the "static" part of the network, Group Normalization in the "dynamic" parts - `off`: No normalization (preserve scale and bias parameters) The "static" part of the network includes the backbone, FPN and semantic segmentation components, while the "dynamic" part of the network includes the RPN, detection and instance segmentation components. Note that this distinction is due to historical reasons and for back-compatibility with the CVPR2019 pre-trained models. Parameters ---------- body_config Configuration object containing the following fields: `normalization_mode`, `activation`, `activation_slope` and `gn_groups` Returns ------- norm_act_static : callable Function that returns norm_act modules for the static parts of the network norm_act_dynamic : callable Function that returns norm_act modules for the dynamic parts of the network """ mode = body_config["normalization_mode"] activation = body_config["activation"] slope = body_config.getfloat("activation_slope") groups = body_config.getint("gn_groups") if mode == "bn": norm_act_static = norm_act_dynamic = partial(InPlaceABN, activation=activation, activation_param=slope) elif mode == "syncbn": norm_act_static = norm_act_dynamic = partial(InPlaceABNSync, activation=activation, activation_param=slope) elif mode == "syncbn+bn": norm_act_static = partial(InPlaceABNSync, activation=activation, activation_param=slope) norm_act_dynamic = partial(InPlaceABN, activation=activation, activation_param=slope) elif mode == "gn": norm_act_static = norm_act_dynamic = partial( ActivatedGroupNorm, num_groups=groups, activation=activation, activation_param=slope) elif mode == "syncbn+gn": norm_act_static = partial(InPlaceABNSync, activation=activation, activation_param=slope) norm_act_dynamic = partial(ActivatedGroupNorm, num_groups=groups, activation=activation, activation_param=slope) elif mode == "off": norm_act_static = norm_act_dynamic = partial(ActivatedAffine, activation=activation, activation_param=slope) else: raise ValueError("Unrecognized normalization_mode {}, valid options: 'bn', 'syncbn', 'syncbn+bn', 'gn', " "'syncbn+gn', 'off'".format(mode)) return norm_act_static, norm_act_dynamic
[ "def", "norm_act_from_config", "(", "body_config", ")", ":", "mode", "=", "body_config", "[", "\"normalization_mode\"", "]", "activation", "=", "body_config", "[", "\"activation\"", "]", "slope", "=", "body_config", ".", "getfloat", "(", "\"activation_slope\"", ")",...
https://github.com/mapillary/seamseg/blob/77195ff7829af6e3076caefe49c4c69c817e30d6/seamseg/utils/misc.py#L75-L129
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/Python-2.7.9/Lib/xml/sax/saxutils.py
python
XMLFilterBase.warning
(self, exception)
[]
def warning(self, exception): self._err_handler.warning(exception)
[ "def", "warning", "(", "self", ",", "exception", ")", ":", "self", ".", "_err_handler", ".", "warning", "(", "exception", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/Python-2.7.9/Lib/xml/sax/saxutils.py#L219-L220
linuxscout/mishkal
4f4ae0ebc2d6acbeb3de3f0303151ec7b54d2f76
interfaces/web/lib/paste/wsgiwrappers.py
python
WSGIRequest.urlvars
(self)
Return any variables matched in the URL (e.g., ``wsgiorg.routing_args``).
Return any variables matched in the URL (e.g., ``wsgiorg.routing_args``).
[ "Return", "any", "variables", "matched", "in", "the", "URL", "(", "e", ".", "g", ".", "wsgiorg", ".", "routing_args", ")", "." ]
def urlvars(self): """ Return any variables matched in the URL (e.g., ``wsgiorg.routing_args``). """ if 'paste.urlvars' in self.environ: return self.environ['paste.urlvars'] elif 'wsgiorg.routing_args' in self.environ: return self.environ['wsgiorg.routing_args'][1] else: return {}
[ "def", "urlvars", "(", "self", ")", ":", "if", "'paste.urlvars'", "in", "self", ".", "environ", ":", "return", "self", ".", "environ", "[", "'paste.urlvars'", "]", "elif", "'wsgiorg.routing_args'", "in", "self", ".", "environ", ":", "return", "self", ".", ...
https://github.com/linuxscout/mishkal/blob/4f4ae0ebc2d6acbeb3de3f0303151ec7b54d2f76/interfaces/web/lib/paste/wsgiwrappers.py#L128-L138
emesene/emesene
4548a4098310e21b16437bb36223a7f632a4f7bc
emesene/e3/xmpp/SleekXMPP/sleekxmpp/stanza/htmlim.py
python
HTMLIM.del_body
(self)
Remove the HTML body contents.
Remove the HTML body contents.
[ "Remove", "the", "HTML", "body", "contents", "." ]
def del_body(self): """Remove the HTML body contents.""" if self.parent is not None: self.parent().xml.remove(self.xml)
[ "def", "del_body", "(", "self", ")", ":", "if", "self", ".", "parent", "is", "not", "None", ":", "self", ".", "parent", "(", ")", ".", "xml", ".", "remove", "(", "self", ".", "xml", ")" ]
https://github.com/emesene/emesene/blob/4548a4098310e21b16437bb36223a7f632a4f7bc/emesene/e3/xmpp/SleekXMPP/sleekxmpp/stanza/htmlim.py#L74-L77
Azure/azure-linux-extensions
a42ef718c746abab2b3c6a21da87b29e76364558
AzureMonitorAgent/agent.py
python
set_os_arch
()
Checks if the current system architecture is present in the SupportedArch set and replaces the package name accordingly
Checks if the current system architecture is present in the SupportedArch set and replaces the package name accordingly
[ "Checks", "if", "the", "current", "system", "architecture", "is", "present", "in", "the", "SupportedArch", "set", "and", "replaces", "the", "package", "name", "accordingly" ]
def set_os_arch(): """ Checks if the current system architecture is present in the SupportedArch set and replaces the package name accordingly """ global BundleFileName, SupportedArch current_arch = platform.machine() if current_arch in SupportedArch: BundleFileName = BundleFileName.replace('x86_64', current_arch)
[ "def", "set_os_arch", "(", ")", ":", "global", "BundleFileName", ",", "SupportedArch", "current_arch", "=", "platform", ".", "machine", "(", ")", "if", "current_arch", "in", "SupportedArch", ":", "BundleFileName", "=", "BundleFileName", ".", "replace", "(", "'x8...
https://github.com/Azure/azure-linux-extensions/blob/a42ef718c746abab2b3c6a21da87b29e76364558/AzureMonitorAgent/agent.py#L1005-L1014
cloudera/hue
23f02102d4547c17c32bd5ea0eb24e9eadd657a4
apps/rdbms/src/rdbms/views.py
python
execute_query
(request, design_id=None, query_history_id=None)
return render('execute.mako', request, { 'action': action, 'doc_id': json.dumps(design.id and design.doc.get().id or -1), 'design': design, 'autocomplete_base_url': reverse('rdbms:api_autocomplete_databases', kwargs={}), 'can_edit_name': design.id and not design.is_auto, })
View function for executing an arbitrary synchronously query.
View function for executing an arbitrary synchronously query.
[ "View", "function", "for", "executing", "an", "arbitrary", "synchronously", "query", "." ]
def execute_query(request, design_id=None, query_history_id=None): """ View function for executing an arbitrary synchronously query. """ action = request.path app_name = get_app_name(request) query_type = beeswax_models.SavedQuery.TYPES_MAPPING[app_name] design = safe_get_design(request, query_type, design_id) return render('execute.mako', request, { 'action': action, 'doc_id': json.dumps(design.id and design.doc.get().id or -1), 'design': design, 'autocomplete_base_url': reverse('rdbms:api_autocomplete_databases', kwargs={}), 'can_edit_name': design.id and not design.is_auto, })
[ "def", "execute_query", "(", "request", ",", "design_id", "=", "None", ",", "query_history_id", "=", "None", ")", ":", "action", "=", "request", ".", "path", "app_name", "=", "get_app_name", "(", "request", ")", "query_type", "=", "beeswax_models", ".", "Sav...
https://github.com/cloudera/hue/blob/23f02102d4547c17c32bd5ea0eb24e9eadd657a4/apps/rdbms/src/rdbms/views.py#L69-L84
hatRiot/zarp
2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad
src/modules/scanner/service_scan.py
python
service_scan.ftp_info
(self, ip)
[]
def ftp_info(self, ip): con = FTP(ip) banner = con.getwelcome() # dump banner for line in banner.split('\n'): print '\t |-' + line print '\t [+] Checking anonymous access...' try: con.login() except: print '\t [-] No anonymous access.' con.close() return # get the logged in dir data = con.pwd() if data is not None: print '\t [+] Anonymous access available.' print '\t [+] Directory: ', data con.close()
[ "def", "ftp_info", "(", "self", ",", "ip", ")", ":", "con", "=", "FTP", "(", "ip", ")", "banner", "=", "con", ".", "getwelcome", "(", ")", "# dump banner", "for", "line", "in", "banner", ".", "split", "(", "'\\n'", ")", ":", "print", "'\\t |-'", "...
https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/modules/scanner/service_scan.py#L180-L200
hatRiot/zarp
2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad
src/lib/libmproxy/contrib/html2text.py
python
HTML2Text.replaceEntities
(self, s)
[]
def replaceEntities(self, s): s = s.group(1) if s[0] == "#": return self.charref(s[1:]) else: return self.entityref(s)
[ "def", "replaceEntities", "(", "self", ",", "s", ")", ":", "s", "=", "s", ".", "group", "(", "1", ")", "if", "s", "[", "0", "]", "==", "\"#\"", ":", "return", "self", ".", "charref", "(", "s", "[", "1", ":", "]", ")", "else", ":", "return", ...
https://github.com/hatRiot/zarp/blob/2e772350a01c2aeed3f4da9685cd0cc5d6b3ecad/src/lib/libmproxy/contrib/html2text.py#L675-L679
oilshell/oil
94388e7d44a9ad879b12615f6203b38596b5a2d3
Python-2.7.13/Lib/mimetools.py
python
Message.parsetype
(self)
[]
def parsetype(self): str = self.typeheader if str is None: str = 'text/plain' if ';' in str: i = str.index(';') self.plisttext = str[i:] str = str[:i] else: self.plisttext = '' fields = str.split('/') for i in range(len(fields)): fields[i] = fields[i].strip().lower() self.type = '/'.join(fields) self.maintype = fields[0] self.subtype = '/'.join(fields[1:])
[ "def", "parsetype", "(", "self", ")", ":", "str", "=", "self", ".", "typeheader", "if", "str", "is", "None", ":", "str", "=", "'text/plain'", "if", "';'", "in", "str", ":", "i", "=", "str", ".", "index", "(", "';'", ")", "self", ".", "plisttext", ...
https://github.com/oilshell/oil/blob/94388e7d44a9ad879b12615f6203b38596b5a2d3/Python-2.7.13/Lib/mimetools.py#L33-L48
clinton-hall/nzbToMedia
27669389216902d1085660167e7bda0bd8527ecf
libs/common/beets/ui/__init__.py
python
CommonOptionsParser.add_album_option
(self, flags=('-a', '--album'))
Add a -a/--album option to match albums instead of tracks. If used then the format option can auto-detect whether we're setting the format for items or albums. Sets the album property on the options extracted from the CLI.
Add a -a/--album option to match albums instead of tracks.
[ "Add", "a", "-", "a", "/", "--", "album", "option", "to", "match", "albums", "instead", "of", "tracks", "." ]
def add_album_option(self, flags=('-a', '--album')): """Add a -a/--album option to match albums instead of tracks. If used then the format option can auto-detect whether we're setting the format for items or albums. Sets the album property on the options extracted from the CLI. """ album = optparse.Option(*flags, action='store_true', help=u'match albums instead of tracks') self.add_option(album) self._album_flags = set(flags)
[ "def", "add_album_option", "(", "self", ",", "flags", "=", "(", "'-a'", ",", "'--album'", ")", ")", ":", "album", "=", "optparse", ".", "Option", "(", "*", "flags", ",", "action", "=", "'store_true'", ",", "help", "=", "u'match albums instead of tracks'", ...
https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/beets/ui/__init__.py#L823-L833
awslabs/deeplearning-benchmark
3e9a906422b402869537f91056ae771b66487a8e
image_classification/predict_image.py
python
InferenceTesting.__getImage
(self)
return img
[]
def __getImage(self): try: fname = mx.test_utils.download(self.url) except Exception as e: print("Error in downloading the image {}".format(e)) img = cv2.cvtColor(cv2.imread(fname), cv2.COLOR_BGR2RGB) if img is None: return None # convert into format (batch, RGB, width, height) img = cv2.resize(img, (224, 224)) img = np.swapaxes(img, 0, 2) img = np.swapaxes(img, 1, 2) img = img[np.newaxis, :] return img
[ "def", "__getImage", "(", "self", ")", ":", "try", ":", "fname", "=", "mx", ".", "test_utils", ".", "download", "(", "self", ".", "url", ")", "except", "Exception", "as", "e", ":", "print", "(", "\"Error in downloading the image {}\"", ".", "format", "(", ...
https://github.com/awslabs/deeplearning-benchmark/blob/3e9a906422b402869537f91056ae771b66487a8e/image_classification/predict_image.py#L51-L64
malicialab/avclass
707c06e0a5e362b6a2f08e4cb1c6c81787c08a8d
avclass2/avclass2_update_module.py
python
Update.is_blacklisted_rel
(self, rel)
return (rel.t1 in self.blist) or (rel.t2 in self.blist)
Return true if relationship is blacklisted
Return true if relationship is blacklisted
[ "Return", "true", "if", "relationship", "is", "blacklisted" ]
def is_blacklisted_rel(self, rel): ''' Return true if relationship is blacklisted ''' return (rel.t1 in self.blist) or (rel.t2 in self.blist)
[ "def", "is_blacklisted_rel", "(", "self", ",", "rel", ")", ":", "return", "(", "rel", ".", "t1", "in", "self", ".", "blist", ")", "or", "(", "rel", ".", "t2", "in", "self", ".", "blist", ")" ]
https://github.com/malicialab/avclass/blob/707c06e0a5e362b6a2f08e4cb1c6c81787c08a8d/avclass2/avclass2_update_module.py#L71-L73
garywiz/chaperone
9ff2c3a5b9c6820f8750320a564ea214042df06f
chaperone/cutil/notify.py
python
NotifyListener.is_client
(self)
return False
[]
def is_client(self): return False
[ "def", "is_client", "(", "self", ")", ":", "return", "False" ]
https://github.com/garywiz/chaperone/blob/9ff2c3a5b9c6820f8750320a564ea214042df06f/chaperone/cutil/notify.py#L29-L30
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py
python
Environment.__getitem__
(self, project_name)
return self._distmap.get(distribution_key, [])
Return a newest-to-oldest list of distributions for `project_name` Uses case-insensitive `project_name` comparison, assuming all the project's distributions use their project's name converted to all lowercase as their key.
Return a newest-to-oldest list of distributions for `project_name`
[ "Return", "a", "newest", "-", "to", "-", "oldest", "list", "of", "distributions", "for", "project_name" ]
def __getitem__(self, project_name): """Return a newest-to-oldest list of distributions for `project_name` Uses case-insensitive `project_name` comparison, assuming all the project's distributions use their project's name converted to all lowercase as their key. """ distribution_key = project_name.lower() return self._distmap.get(distribution_key, [])
[ "def", "__getitem__", "(", "self", ",", "project_name", ")", ":", "distribution_key", "=", "project_name", ".", "lower", "(", ")", "return", "self", ".", "_distmap", ".", "get", "(", "distribution_key", ",", "[", "]", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py#L1007-L1016
JiYou/openstack
8607dd488bde0905044b303eb6e52bdea6806923
packages/source/nova/nova/virt/xenapi/agent.py
python
_call_agent
(session, instance, vm_ref, method, addl_args=None, timeout=None)
Abstracts out the interaction with the agent xenapi plugin.
Abstracts out the interaction with the agent xenapi plugin.
[ "Abstracts", "out", "the", "interaction", "with", "the", "agent", "xenapi", "plugin", "." ]
def _call_agent(session, instance, vm_ref, method, addl_args=None, timeout=None): """Abstracts out the interaction with the agent xenapi plugin.""" if addl_args is None: addl_args = {} if timeout is None: timeout = CONF.agent_timeout vm_rec = session.call_xenapi("VM.get_record", vm_ref) args = { 'id': str(uuid.uuid4()), 'dom_id': vm_rec['domid'], 'timeout': str(timeout), } args.update(addl_args) try: ret = session.call_plugin('agent', method, args) except session.XenAPI.Failure, e: err_msg = e.details[-1].splitlines()[-1] if 'TIMEOUT:' in err_msg: LOG.error(_('TIMEOUT: The call to %(method)s timed out. ' 'args=%(args)r'), locals(), instance=instance) return {'returncode': 'timeout', 'message': err_msg} elif 'NOT IMPLEMENTED:' in err_msg: LOG.error(_('NOT IMPLEMENTED: The call to %(method)s is not' ' supported by the agent. args=%(args)r'), locals(), instance=instance) return {'returncode': 'notimplemented', 'message': err_msg} else: LOG.error(_('The call to %(method)s returned an error: %(e)s. ' 'args=%(args)r'), locals(), instance=instance) return {'returncode': 'error', 'message': err_msg} return None if isinstance(ret, dict): return ret try: return jsonutils.loads(ret) except TypeError: LOG.error(_('The agent call to %(method)s returned an invalid' ' response: %(ret)r. path=%(path)s; args=%(args)r'), locals(), instance=instance) return {'returncode': 'error', 'message': 'unable to deserialize response'}
[ "def", "_call_agent", "(", "session", ",", "instance", ",", "vm_ref", ",", "method", ",", "addl_args", "=", "None", ",", "timeout", "=", "None", ")", ":", "if", "addl_args", "is", "None", ":", "addl_args", "=", "{", "}", "if", "timeout", "is", "None", ...
https://github.com/JiYou/openstack/blob/8607dd488bde0905044b303eb6e52bdea6806923/packages/source/nova/nova/virt/xenapi/agent.py#L66-L111
pwnieexpress/pwn_plug_sources
1a23324f5dc2c3de20f9c810269b6a29b2758cad
src/plecost/xgoogle/search.py
python
GoogleSearch._get_page
(self)
return self._page
[]
def _get_page(self): return self._page
[ "def", "_get_page", "(", "self", ")", ":", "return", "self", ".", "_page" ]
https://github.com/pwnieexpress/pwn_plug_sources/blob/1a23324f5dc2c3de20f9c810269b6a29b2758cad/src/plecost/xgoogle/search.py#L79-L80
clinton-hall/nzbToMedia
27669389216902d1085660167e7bda0bd8527ecf
libs/common/setuptools/py33compat.py
python
Bytecode_compat.__iter__
(self)
Yield '(op,arg)' pair for each operation in code object 'code
Yield '(op,arg)' pair for each operation in code object 'code
[ "Yield", "(", "op", "arg", ")", "pair", "for", "each", "operation", "in", "code", "object", "code" ]
def __iter__(self): """Yield '(op,arg)' pair for each operation in code object 'code'""" bytes = array.array('b', self.code.co_code) eof = len(self.code.co_code) ptr = 0 extended_arg = 0 while ptr < eof: op = bytes[ptr] if op >= dis.HAVE_ARGUMENT: arg = bytes[ptr + 1] + bytes[ptr + 2] * 256 + extended_arg ptr += 3 if op == dis.EXTENDED_ARG: long_type = six.integer_types[-1] extended_arg = arg * long_type(65536) continue else: arg = None ptr += 1 yield OpArg(op, arg)
[ "def", "__iter__", "(", "self", ")", ":", "bytes", "=", "array", ".", "array", "(", "'b'", ",", "self", ".", "code", ".", "co_code", ")", "eof", "=", "len", "(", "self", ".", "code", ".", "co_code", ")", "ptr", "=", "0", "extended_arg", "=", "0",...
https://github.com/clinton-hall/nzbToMedia/blob/27669389216902d1085660167e7bda0bd8527ecf/libs/common/setuptools/py33compat.py#L22-L49
wger-project/wger
3a17a2cf133d242d1f8c357faa53cf675a7b3223
wger/core/models/language.py
python
Language.get_absolute_url
(self)
return reverse('core:language:view', kwargs={'pk': self.id})
Returns the canonical URL to view a language
Returns the canonical URL to view a language
[ "Returns", "the", "canonical", "URL", "to", "view", "a", "language" ]
def get_absolute_url(self): """ Returns the canonical URL to view a language """ return reverse('core:language:view', kwargs={'pk': self.id})
[ "def", "get_absolute_url", "(", "self", ")", ":", "return", "reverse", "(", "'core:language:view'", ",", "kwargs", "=", "{", "'pk'", ":", "self", ".", "id", "}", ")" ]
https://github.com/wger-project/wger/blob/3a17a2cf133d242d1f8c357faa53cf675a7b3223/wger/core/models/language.py#L51-L55
jazzband/tablib
94ffe67e50eb5bfd99d73a4f010e463478a98928
src/tablib/core.py
python
Dataset.rpop
(self)
return cache
Removes and returns the last row of the :class:`Dataset`.
Removes and returns the last row of the :class:`Dataset`.
[ "Removes", "and", "returns", "the", "last", "row", "of", "the", ":", "class", ":", "Dataset", "." ]
def rpop(self): """Removes and returns the last row of the :class:`Dataset`.""" cache = self[-1] del self[-1] return cache
[ "def", "rpop", "(", "self", ")", ":", "cache", "=", "self", "[", "-", "1", "]", "del", "self", "[", "-", "1", "]", "return", "cache" ]
https://github.com/jazzband/tablib/blob/94ffe67e50eb5bfd99d73a4f010e463478a98928/src/tablib/core.py#L482-L488
kozistr/Awesome-GANs
b4b9a3b8c3fd1d32c864dc5655d80c0650aebee1
awesome_gans/ebgan/ebgan_model.py
python
EBGAN.encoder
(self, x, reuse=None)
(64)4c2s - (128)4c2s - (256)4c2s :param x: images :param reuse: re-usable :return: logits
(64)4c2s - (128)4c2s - (256)4c2s :param x: images :param reuse: re-usable :return: logits
[ "(", "64", ")", "4c2s", "-", "(", "128", ")", "4c2s", "-", "(", "256", ")", "4c2s", ":", "param", "x", ":", "images", ":", "param", "reuse", ":", "re", "-", "usable", ":", "return", ":", "logits" ]
def encoder(self, x, reuse=None): """ (64)4c2s - (128)4c2s - (256)4c2s :param x: images :param reuse: re-usable :return: logits """ with tf.variable_scope('encoder', reuse=reuse): x = t.conv2d(x, self.df_dim * 1, 4, 2, name='enc-conv2d-1') x = tf.nn.leaky_relu(x) x = t.conv2d(x, self.df_dim * 2, 4, 2, name='enc-conv2d-2') x = t.batch_norm(x, name='enc-bn-1') x = tf.nn.leaky_relu(x) x = t.conv2d(x, self.df_dim * 4, 4, 2, name='enc-conv2d-3') x = t.batch_norm(x, name='enc-bn-2') x = tf.nn.leaky_relu(x) return x
[ "def", "encoder", "(", "self", ",", "x", ",", "reuse", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "'encoder'", ",", "reuse", "=", "reuse", ")", ":", "x", "=", "t", ".", "conv2d", "(", "x", ",", "self", ".", "df_dim", "*", ...
https://github.com/kozistr/Awesome-GANs/blob/b4b9a3b8c3fd1d32c864dc5655d80c0650aebee1/awesome_gans/ebgan/ebgan_model.py#L104-L122
mozillazg/pypy
2ff5cd960c075c991389f842c6d59e71cf0cb7d0
rpython/rtyper/lltypesystem/lltype.py
python
_ptr._expose
(self, offset, val)
return val
XXX A nice docstring here
XXX A nice docstring here
[ "XXX", "A", "nice", "docstring", "here" ]
def _expose(self, offset, val): """XXX A nice docstring here""" T = typeOf(val) if isinstance(T, ContainerType): if (self._T._gckind == 'gc' and T._gckind == 'raw' and not isinstance(T, OpaqueType)): val = _interior_ptr(T, self._obj, [offset]) else: val = _ptr(Ptr(T), val, solid=self._solid) return val
[ "def", "_expose", "(", "self", ",", "offset", ",", "val", ")", ":", "T", "=", "typeOf", "(", "val", ")", "if", "isinstance", "(", "T", ",", "ContainerType", ")", ":", "if", "(", "self", ".", "_T", ".", "_gckind", "==", "'gc'", "and", "T", ".", ...
https://github.com/mozillazg/pypy/blob/2ff5cd960c075c991389f842c6d59e71cf0cb7d0/rpython/rtyper/lltypesystem/lltype.py#L1506-L1515
google/ml-fairness-gym
5b1cd336b844059aa4e4426b54d1f0e6b8c4c7e9
environments/lending.py
python
BaseLendingEnv.render
(self, mode='human')
Renders the history and current state using matplotlib. Args: mode: string indicating the rendering mode. The only supported mode is `human`.
Renders the history and current state using matplotlib.
[ "Renders", "the", "history", "and", "current", "state", "using", "matplotlib", "." ]
def render(self, mode='human'): """Renders the history and current state using matplotlib. Args: mode: string indicating the rendering mode. The only supported mode is `human`. """ if mode == 'human': if self.state.params.applicant_distribution.dim != 2: raise NotImplementedError( 'Cannot render if applicant features are not exactly 2 dimensional. ' 'Got %d dimensional applicant features.' % self.state.params.applicant_distribution.dim) plt.figure(figsize=(12, 4)) plt.subplot(1, 2, 1) plt.xlim(-2, 2) plt.ylim(-2, 2) plt.title('Applicant Features') plt.xticks([], []) plt.yticks([], []) for state, action in self.history: if action == 1: x, y = state.applicant_features color = 'r' if state.will_default else 'b' plt.plot([x], [y], _MARKERS[state.group_id] + color, markersize=12) plt.xlabel('Feature 1') plt.ylabel('Feature 2') x, y = self.state.applicant_features plt.plot([x], [y], _MARKERS[self.state.group_id] + 'k', markersize=15) plt.subplot(1, 2, 2) plt.title('Cash') plt.plot([state.bank_cash for state, _ in self.history] + [self.state.bank_cash]) plt.ylabel('# loans available') plt.xlabel('Time') plt.tight_layout() else: super(BaseLendingEnv, self).render(mode)
[ "def", "render", "(", "self", ",", "mode", "=", "'human'", ")", ":", "if", "mode", "==", "'human'", ":", "if", "self", ".", "state", ".", "params", ".", "applicant_distribution", ".", "dim", "!=", "2", ":", "raise", "NotImplementedError", "(", "'Cannot r...
https://github.com/google/ml-fairness-gym/blob/5b1cd336b844059aa4e4426b54d1f0e6b8c4c7e9/environments/lending.py#L195-L237
guoruoqian/DetNet_pytorch
735e2c51eea0ee4e91d2ec3f28e441ac4e076551
lib/model/rpn/bbox_transform.py
python
bbox_overlaps_batch
(anchors, gt_boxes)
return overlaps
anchors: (N, 4) ndarray of float gt_boxes: (b, K, 5) ndarray of float overlaps: (N, K) ndarray of overlap between boxes and query_boxes
anchors: (N, 4) ndarray of float gt_boxes: (b, K, 5) ndarray of float
[ "anchors", ":", "(", "N", "4", ")", "ndarray", "of", "float", "gt_boxes", ":", "(", "b", "K", "5", ")", "ndarray", "of", "float" ]
def bbox_overlaps_batch(anchors, gt_boxes): """ anchors: (N, 4) ndarray of float gt_boxes: (b, K, 5) ndarray of float overlaps: (N, K) ndarray of overlap between boxes and query_boxes """ batch_size = gt_boxes.size(0) if anchors.dim() == 2: N = anchors.size(0) K = gt_boxes.size(1) anchors = anchors.view(1, N, 4).expand(batch_size, N, 4).contiguous() gt_boxes = gt_boxes[:,:,:4].contiguous() gt_boxes_x = (gt_boxes[:,:,2] - gt_boxes[:,:,0] + 1) gt_boxes_y = (gt_boxes[:,:,3] - gt_boxes[:,:,1] + 1) gt_boxes_area = (gt_boxes_x * gt_boxes_y).view(batch_size, 1, K) anchors_boxes_x = (anchors[:,:,2] - anchors[:,:,0] + 1) anchors_boxes_y = (anchors[:,:,3] - anchors[:,:,1] + 1) anchors_area = (anchors_boxes_x * anchors_boxes_y).view(batch_size, N, 1) gt_area_zero = (gt_boxes_x == 1) & (gt_boxes_y == 1) anchors_area_zero = (anchors_boxes_x == 1) & (anchors_boxes_y == 1) boxes = anchors.view(batch_size, N, 1, 4).expand(batch_size, N, K, 4) query_boxes = gt_boxes.view(batch_size, 1, K, 4).expand(batch_size, N, K, 4) iw = (torch.min(boxes[:,:,:,2], query_boxes[:,:,:,2]) - torch.max(boxes[:,:,:,0], query_boxes[:,:,:,0]) + 1) iw[iw < 0] = 0 ih = (torch.min(boxes[:,:,:,3], query_boxes[:,:,:,3]) - torch.max(boxes[:,:,:,1], query_boxes[:,:,:,1]) + 1) ih[ih < 0] = 0 ua = anchors_area + gt_boxes_area - (iw * ih) overlaps = iw * ih / ua # mask the overlap here. overlaps.masked_fill_(gt_area_zero.view(batch_size, 1, K).expand(batch_size, N, K), 0) overlaps.masked_fill_(anchors_area_zero.view(batch_size, N, 1).expand(batch_size, N, K), -1) elif anchors.dim() == 3: N = anchors.size(1) K = gt_boxes.size(1) if anchors.size(2) == 4: anchors = anchors[:,:,:4].contiguous() else: anchors = anchors[:,:,1:5].contiguous() gt_boxes = gt_boxes[:,:,:4].contiguous() gt_boxes_x = (gt_boxes[:,:,2] - gt_boxes[:,:,0] + 1) gt_boxes_y = (gt_boxes[:,:,3] - gt_boxes[:,:,1] + 1) gt_boxes_area = (gt_boxes_x * gt_boxes_y).view(batch_size, 1, K) anchors_boxes_x = (anchors[:,:,2] - anchors[:,:,0] + 1) anchors_boxes_y = (anchors[:,:,3] - anchors[:,:,1] + 1) anchors_area = (anchors_boxes_x * anchors_boxes_y).view(batch_size, N, 1) gt_area_zero = (gt_boxes_x == 1) & (gt_boxes_y == 1) anchors_area_zero = (anchors_boxes_x == 1) & (anchors_boxes_y == 1) boxes = anchors.view(batch_size, N, 1, 4).expand(batch_size, N, K, 4) query_boxes = gt_boxes.view(batch_size, 1, K, 4).expand(batch_size, N, K, 4) iw = (torch.min(boxes[:,:,:,2], query_boxes[:,:,:,2]) - torch.max(boxes[:,:,:,0], query_boxes[:,:,:,0]) + 1) iw[iw < 0] = 0 ih = (torch.min(boxes[:,:,:,3], query_boxes[:,:,:,3]) - torch.max(boxes[:,:,:,1], query_boxes[:,:,:,1]) + 1) ih[ih < 0] = 0 ua = anchors_area + gt_boxes_area - (iw * ih) overlaps = iw * ih / ua # mask the overlap here. overlaps.masked_fill_(gt_area_zero.view(batch_size, 1, K).expand(batch_size, N, K), 0) overlaps.masked_fill_(anchors_area_zero.view(batch_size, N, 1).expand(batch_size, N, K), -1) else: raise ValueError('anchors input dimension is not correct.') return overlaps
[ "def", "bbox_overlaps_batch", "(", "anchors", ",", "gt_boxes", ")", ":", "batch_size", "=", "gt_boxes", ".", "size", "(", "0", ")", "if", "anchors", ".", "dim", "(", ")", "==", "2", ":", "N", "=", "anchors", ".", "size", "(", "0", ")", "K", "=", ...
https://github.com/guoruoqian/DetNet_pytorch/blob/735e2c51eea0ee4e91d2ec3f28e441ac4e076551/lib/model/rpn/bbox_transform.py#L168-L257
openstack/trove
be86b79119d16ee77f596172f43b0c97cb2617bd
trove/guestagent/common/configuration.py
python
ConfigurationManager.get_value
(self, key, section=None, default=None)
return self._value_cache.get(key, default)
Return the current value at a given key or 'default'.
Return the current value at a given key or 'default'.
[ "Return", "the", "current", "value", "at", "a", "given", "key", "or", "default", "." ]
def get_value(self, key, section=None, default=None): """Return the current value at a given key or 'default'. """ if self._value_cache is None: self.refresh_cache() if section: return self._value_cache.get(section, {}).get(key, default) return self._value_cache.get(key, default)
[ "def", "get_value", "(", "self", ",", "key", ",", "section", "=", "None", ",", "default", "=", "None", ")", ":", "if", "self", ".", "_value_cache", "is", "None", ":", "self", ".", "refresh_cache", "(", ")", "if", "section", ":", "return", "self", "."...
https://github.com/openstack/trove/blob/be86b79119d16ee77f596172f43b0c97cb2617bd/trove/guestagent/common/configuration.py#L107-L116
lbryio/lbry-sdk
f78e3825ca0f130834d3876a824f9d380501ced8
lbry/wallet/server/session.py
python
LBRYElectrumX.transaction_broadcast
(self, raw_tx)
Broadcast a raw transaction to the network. raw_tx: the raw transaction as a hexadecimal string
Broadcast a raw transaction to the network.
[ "Broadcast", "a", "raw", "transaction", "to", "the", "network", "." ]
async def transaction_broadcast(self, raw_tx): """Broadcast a raw transaction to the network. raw_tx: the raw transaction as a hexadecimal string""" # This returns errors as JSON RPC errors, as is natural try: hex_hash = await self.session_mgr.broadcast_transaction(raw_tx) self.txs_sent += 1 self.mempool.wakeup.set() self.logger.info(f'sent tx: {hex_hash}') return hex_hash except DaemonError as e: error, = e.args message = error['message'] self.logger.info(f'error sending transaction: {message}') raise RPCError(BAD_REQUEST, 'the transaction was rejected by ' f'network rules.\n\n{message}\n[{raw_tx}]')
[ "async", "def", "transaction_broadcast", "(", "self", ",", "raw_tx", ")", ":", "# This returns errors as JSON RPC errors, as is natural", "try", ":", "hex_hash", "=", "await", "self", ".", "session_mgr", ".", "broadcast_transaction", "(", "raw_tx", ")", "self", ".", ...
https://github.com/lbryio/lbry-sdk/blob/f78e3825ca0f130834d3876a824f9d380501ced8/lbry/wallet/server/session.py#L1432-L1448
XinJCheng/CSPN
b3e487bdcdcd8a63333656e69b3268698e543181
cspn_pytorch/data_transform.py
python
Rotation.__call__
(self, img)
return img.rotate(self.degrees, self.resample, self.expand, self.center)
img (PIL Image): Image to be rotated. Returns: PIL Image: Rotated image.
img (PIL Image): Image to be rotated. Returns: PIL Image: Rotated image.
[ "img", "(", "PIL", "Image", ")", ":", "Image", "to", "be", "rotated", ".", "Returns", ":", "PIL", "Image", ":", "Rotated", "image", "." ]
def __call__(self, img): """ img (PIL Image): Image to be rotated. Returns: PIL Image: Rotated image. """ if not _is_pil_image(img): raise TypeError('img should be PIL Image. Got {}'.format(type(img))) return img.rotate(self.degrees, self.resample, self.expand, self.center)
[ "def", "__call__", "(", "self", ",", "img", ")", ":", "if", "not", "_is_pil_image", "(", "img", ")", ":", "raise", "TypeError", "(", "'img should be PIL Image. Got {}'", ".", "format", "(", "type", "(", "img", ")", ")", ")", "return", "img", ".", "rotate...
https://github.com/XinJCheng/CSPN/blob/b3e487bdcdcd8a63333656e69b3268698e543181/cspn_pytorch/data_transform.py#L480-L490
iMoonLab/MeshNet
70f9115a121cef71f62d774088771337c3beaf4b
models/layers.py
python
FaceRotateConvolution.__init__
(self)
[]
def __init__(self): super(FaceRotateConvolution, self).__init__() self.rotate_mlp = nn.Sequential( nn.Conv1d(6, 32, 1), nn.BatchNorm1d(32), nn.ReLU(), nn.Conv1d(32, 32, 1), nn.BatchNorm1d(32), nn.ReLU() ) self.fusion_mlp = nn.Sequential( nn.Conv1d(32, 64, 1), nn.BatchNorm1d(64), nn.ReLU(), nn.Conv1d(64, 64, 1), nn.BatchNorm1d(64), nn.ReLU() )
[ "def", "__init__", "(", "self", ")", ":", "super", "(", "FaceRotateConvolution", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "rotate_mlp", "=", "nn", ".", "Sequential", "(", "nn", ".", "Conv1d", "(", "6", ",", "32", ",", "1", ")", ","...
https://github.com/iMoonLab/MeshNet/blob/70f9115a121cef71f62d774088771337c3beaf4b/models/layers.py#L9-L26
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/data/owtable.py
python
TableSliceProxy.setRowSlice
(self, rowslice)
[]
def setRowSlice(self, rowslice): if rowslice.step is not None and rowslice.step != 1: raise ValueError("invalid stride") if self.__rowslice != rowslice: self.beginResetModel() self.__rowslice = rowslice self.endResetModel()
[ "def", "setRowSlice", "(", "self", ",", "rowslice", ")", ":", "if", "rowslice", ".", "step", "is", "not", "None", "and", "rowslice", ".", "step", "!=", "1", ":", "raise", "ValueError", "(", "\"invalid stride\"", ")", "if", "self", ".", "__rowslice", "!="...
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/data/owtable.py#L130-L137
microsoft/bistring
e23443e495f762967b09670b27bb1ff46ff4fef1
python/bistring/_builder.py
python
BistrBuilder.current
(self)
return self._original.modified
The current string before modifications.
The current string before modifications.
[ "The", "current", "string", "before", "modifications", "." ]
def current(self) -> str: """ The current string before modifications. """ return self._original.modified
[ "def", "current", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_original", ".", "modified" ]
https://github.com/microsoft/bistring/blob/e23443e495f762967b09670b27bb1ff46ff4fef1/python/bistring/_builder.py#L84-L88
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_hxb2/lib/python3.5/site-packages/django/forms/models.py
python
ModelChoiceIterator.choice
(self, obj)
return (self.field.prepare_value(obj), self.field.label_from_instance(obj))
[]
def choice(self, obj): return (self.field.prepare_value(obj), self.field.label_from_instance(obj))
[ "def", "choice", "(", "self", ",", "obj", ")", ":", "return", "(", "self", ".", "field", ".", "prepare_value", "(", "obj", ")", ",", "self", ".", "field", ".", "label_from_instance", "(", "obj", ")", ")" ]
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_hxb2/lib/python3.5/site-packages/django/forms/models.py#L1124-L1125
misterch0c/shadowbroker
e3a069bea47a2c1009697941ac214adc6f90aa8d
windows/Resources/Python/Core/Lib/logging/handlers.py
python
NTEventLogHandler.emit
(self, record)
Emit a record. Determine the message ID, event category and event type. Then log the message in the NT event log.
Emit a record. Determine the message ID, event category and event type. Then log the message in the NT event log.
[ "Emit", "a", "record", ".", "Determine", "the", "message", "ID", "event", "category", "and", "event", "type", ".", "Then", "log", "the", "message", "in", "the", "NT", "event", "log", "." ]
def emit(self, record): """ Emit a record. Determine the message ID, event category and event type. Then log the message in the NT event log. """ if self._welu: try: id = self.getMessageID(record) cat = self.getEventCategory(record) type = self.getEventType(record) msg = self.format(record) self._welu.ReportEvent(self.appname, id, cat, type, [msg]) except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record)
[ "def", "emit", "(", "self", ",", "record", ")", ":", "if", "self", ".", "_welu", ":", "try", ":", "id", "=", "self", ".", "getMessageID", "(", "record", ")", "cat", "=", "self", ".", "getEventCategory", "(", "record", ")", "type", "=", "self", ".",...
https://github.com/misterch0c/shadowbroker/blob/e3a069bea47a2c1009697941ac214adc6f90aa8d/windows/Resources/Python/Core/Lib/logging/handlers.py#L890-L907
Te-k/harpoon
654381fff282aacc7e3c8264fd4cead40eedf48d
harpoon/lib/koodous.py
python
Koodous.analysis
(self, hash)
return self._query("/" + hash + "/analysis")
[]
def analysis(self, hash): return self._query("/" + hash + "/analysis")
[ "def", "analysis", "(", "self", ",", "hash", ")", ":", "return", "self", ".", "_query", "(", "\"/\"", "+", "hash", "+", "\"/analysis\"", ")" ]
https://github.com/Te-k/harpoon/blob/654381fff282aacc7e3c8264fd4cead40eedf48d/harpoon/lib/koodous.py#L42-L43
microsoft/azure-devops-python-api
451cade4c475482792cbe9e522c1fee32393139e
azure-devops/azure/devops/v6_0/feature_availability/feature_availability_client.py
python
FeatureAvailabilityClient.get_all_feature_flags
(self, user_email=None)
return self._deserialize('[FeatureFlag]', self._unwrap_collection(response))
GetAllFeatureFlags. [Preview API] Retrieve a listing of all feature flags and their current states for a user :param str user_email: The email of the user to check :rtype: [FeatureFlag]
GetAllFeatureFlags. [Preview API] Retrieve a listing of all feature flags and their current states for a user :param str user_email: The email of the user to check :rtype: [FeatureFlag]
[ "GetAllFeatureFlags", ".", "[", "Preview", "API", "]", "Retrieve", "a", "listing", "of", "all", "feature", "flags", "and", "their", "current", "states", "for", "a", "user", ":", "param", "str", "user_email", ":", "The", "email", "of", "the", "user", "to", ...
def get_all_feature_flags(self, user_email=None): """GetAllFeatureFlags. [Preview API] Retrieve a listing of all feature flags and their current states for a user :param str user_email: The email of the user to check :rtype: [FeatureFlag] """ query_parameters = {} if user_email is not None: query_parameters['userEmail'] = self._serialize.query('user_email', user_email, 'str') response = self._send(http_method='GET', location_id='3e2b80f8-9e6f-441e-8393-005610692d9c', version='6.0-preview.1', query_parameters=query_parameters) return self._deserialize('[FeatureFlag]', self._unwrap_collection(response))
[ "def", "get_all_feature_flags", "(", "self", ",", "user_email", "=", "None", ")", ":", "query_parameters", "=", "{", "}", "if", "user_email", "is", "not", "None", ":", "query_parameters", "[", "'userEmail'", "]", "=", "self", ".", "_serialize", ".", "query",...
https://github.com/microsoft/azure-devops-python-api/blob/451cade4c475482792cbe9e522c1fee32393139e/azure-devops/azure/devops/v6_0/feature_availability/feature_availability_client.py#L28-L41
Azure/azure-devops-cli-extension
11334cd55806bef0b99c3bee5a438eed71e44037
azure-devops/azext_devops/devops_sdk/released/work_item_tracking/work_item_tracking_client.py
python
WorkItemTrackingClient.get_update
(self, id, update_number, project=None)
return self._deserialize('WorkItemUpdate', response)
GetUpdate. Returns a single update for a work item :param int id: :param int update_number: :param str project: Project ID or project name :rtype: :class:`<WorkItemUpdate> <azure.devops.v5_1.work_item_tracking.models.WorkItemUpdate>`
GetUpdate. Returns a single update for a work item :param int id: :param int update_number: :param str project: Project ID or project name :rtype: :class:`<WorkItemUpdate> <azure.devops.v5_1.work_item_tracking.models.WorkItemUpdate>`
[ "GetUpdate", ".", "Returns", "a", "single", "update", "for", "a", "work", "item", ":", "param", "int", "id", ":", ":", "param", "int", "update_number", ":", ":", "param", "str", "project", ":", "Project", "ID", "or", "project", "name", ":", "rtype", ":...
def get_update(self, id, update_number, project=None): """GetUpdate. Returns a single update for a work item :param int id: :param int update_number: :param str project: Project ID or project name :rtype: :class:`<WorkItemUpdate> <azure.devops.v5_1.work_item_tracking.models.WorkItemUpdate>` """ route_values = {} if project is not None: route_values['project'] = self._serialize.url('project', project, 'str') if id is not None: route_values['id'] = self._serialize.url('id', id, 'int') if update_number is not None: route_values['updateNumber'] = self._serialize.url('update_number', update_number, 'int') response = self._send(http_method='GET', location_id='6570bf97-d02c-4a91-8d93-3abe9895b1a9', version='5.1', route_values=route_values) return self._deserialize('WorkItemUpdate', response)
[ "def", "get_update", "(", "self", ",", "id", ",", "update_number", ",", "project", "=", "None", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", "'project'", "]", "=", "self", ".", "_serialize", "...
https://github.com/Azure/azure-devops-cli-extension/blob/11334cd55806bef0b99c3bee5a438eed71e44037/azure-devops/azext_devops/devops_sdk/released/work_item_tracking/work_item_tracking_client.py#L657-L676
chaoss/grimoirelab-perceval
ba19bfd5e40bffdd422ca8e68526326b47f97491
perceval/backends/core/gitlab.py
python
GitLab.fetch_items
(self, category, **kwargs)
return items
Fetch the items (issues or merge_requests) :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items
Fetch the items (issues or merge_requests)
[ "Fetch", "the", "items", "(", "issues", "or", "merge_requests", ")" ]
def fetch_items(self, category, **kwargs): """Fetch the items (issues or merge_requests) :param category: the category of items to fetch :param kwargs: backend arguments :returns: a generator of items """ from_date = kwargs['from_date'] if category == CATEGORY_ISSUE: items = self.__fetch_issues(from_date) else: items = self.__fetch_merge_requests(from_date) return items
[ "def", "fetch_items", "(", "self", ",", "category", ",", "*", "*", "kwargs", ")", ":", "from_date", "=", "kwargs", "[", "'from_date'", "]", "if", "category", "==", "CATEGORY_ISSUE", ":", "items", "=", "self", ".", "__fetch_issues", "(", "from_date", ")", ...
https://github.com/chaoss/grimoirelab-perceval/blob/ba19bfd5e40bffdd422ca8e68526326b47f97491/perceval/backends/core/gitlab.py#L178-L193
CJWorkbench/cjworkbench
e0b878d8ff819817fa049a4126efcbfcec0b50e6
renderer/execute/renderprep.py
python
_Cleaner._
(self, schema: ParamSchema.File, value: Optional[str])
return value
Convert a `file` String-encoded UUID to a tempfile `pathlib.Path`. The return value: * Points to a temporary file containing all bytes * Has the same suffix as the originally-uploaded file * Will have its file deleted when it goes out of scope If the file is in the database but does not exist on s3, return `None`.
Convert a `file` String-encoded UUID to a tempfile `pathlib.Path`.
[ "Convert", "a", "file", "String", "-", "encoded", "UUID", "to", "a", "tempfile", "pathlib", ".", "Path", "." ]
def _(self, schema: ParamSchema.File, value: Optional[str]) -> Optional[Path]: """Convert a `file` String-encoded UUID to a tempfile `pathlib.Path`. The return value: * Points to a temporary file containing all bytes * Has the same suffix as the originally-uploaded file * Will have its file deleted when it goes out of scope If the file is in the database but does not exist on s3, return `None`. """ if value is None: return None try: uploaded_file = UploadedFileModel.objects.get( uuid=value, step_id=self.step_id ) except UploadedFileModel.DoesNotExist: return None # UploadedFileModel.name may not be POSIX-compliant. We want the filename to # have the same suffix as the original: that helps with filetype # detection. We also put the UUID in the name so debug messages help # devs find the original file. safe_name = FilesystemUnsafeChars.sub("-", uploaded_file.name) path = self.basedir / (value + "_" + safe_name) self.exit_stack.enter_context(deferred_delete(path)) try: # Overwrite the file s3.download(s3.UserFilesBucket, uploaded_file.key, path) except FileNotFoundError: # tempfile will be deleted by self.exit_stack return None self.uploaded_files[value] = UploadedFile( name=uploaded_file.name, filename=path.name, uploaded_at=uploaded_file.created_at, ) return value
[ "def", "_", "(", "self", ",", "schema", ":", "ParamSchema", ".", "File", ",", "value", ":", "Optional", "[", "str", "]", ")", "->", "Optional", "[", "Path", "]", ":", "if", "value", "is", "None", ":", "return", "None", "try", ":", "uploaded_file", ...
https://github.com/CJWorkbench/cjworkbench/blob/e0b878d8ff819817fa049a4126efcbfcec0b50e6/renderer/execute/renderprep.py#L168-L207
ayoolaolafenwa/PixelLib
ae56003c416a98780141a1170c9d888fe9a31317
pixellib/torchbackend/instance/engine/train_loop.py
python
TrainerBase.train
(self, start_iter: int, max_iter: int)
Args: start_iter, max_iter (int): See docs above
Args: start_iter, max_iter (int): See docs above
[ "Args", ":", "start_iter", "max_iter", "(", "int", ")", ":", "See", "docs", "above" ]
def train(self, start_iter: int, max_iter: int): """ Args: start_iter, max_iter (int): See docs above """ logger = logging.getLogger(__name__) logger.info("Starting training from iteration {}".format(start_iter)) self.iter = self.start_iter = start_iter self.max_iter = max_iter with EventStorage(start_iter) as self.storage: try: self.before_train() for self.iter in range(start_iter, max_iter): self.before_step() self.run_step() self.after_step() # self.iter == max_iter can be used by `after_train` to # tell whether the training successfully finished or failed # due to exceptions. self.iter += 1 except Exception: logger.exception("Exception during training:") raise finally: self.after_train()
[ "def", "train", "(", "self", ",", "start_iter", ":", "int", ",", "max_iter", ":", "int", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "__name__", ")", "logger", ".", "info", "(", "\"Starting training from iteration {}\"", ".", "format", "(", ...
https://github.com/ayoolaolafenwa/PixelLib/blob/ae56003c416a98780141a1170c9d888fe9a31317/pixellib/torchbackend/instance/engine/train_loop.py#L133-L159
tobegit3hub/deep_image_model
8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e
java_predict_client/src/main/proto/tensorflow/python/ops/control_flow_grad.py
python
_EnterGrad
(op, grad)
return result
Gradients for an Enter are calculated using an Exit op. For loop variables, grad is the gradient so just add an exit. For loop invariants, we need to add an accumulator loop.
Gradients for an Enter are calculated using an Exit op.
[ "Gradients", "for", "an", "Enter", "are", "calculated", "using", "an", "Exit", "op", "." ]
def _EnterGrad(op, grad): """Gradients for an Enter are calculated using an Exit op. For loop variables, grad is the gradient so just add an exit. For loop invariants, we need to add an accumulator loop. """ graph = ops.get_default_graph() # pylint: disable=protected-access grad_ctxt = graph._get_control_flow_context() # pylint: enable=protected-access if not grad_ctxt.back_prop: # Skip gradient computation, if the attribute `back_prop` is false. return grad if grad_ctxt.grad_state is None: # Pass the gradient grough if we are not in a gradient while context. return grad if op.get_attr("is_constant"): # Add a gradient accumulator for each loop invariant. if isinstance(grad, ops.Tensor): result = grad_ctxt.AddBackPropAccumulator(op, grad) elif isinstance(grad, ops.IndexedSlices): result = grad_ctxt.AddBackPropIndexedSlicesAccumulator(op, grad) else: # TODO(yuanbyu, lukasr): Add support for SparseTensor. raise TypeError("Type %s not supported" % type(grad)) else: result = exit(grad) grad_ctxt.ExitResult([result]) return result
[ "def", "_EnterGrad", "(", "op", ",", "grad", ")", ":", "graph", "=", "ops", ".", "get_default_graph", "(", ")", "# pylint: disable=protected-access", "grad_ctxt", "=", "graph", ".", "_get_control_flow_context", "(", ")", "# pylint: enable=protected-access", "if", "n...
https://github.com/tobegit3hub/deep_image_model/blob/8a53edecd9e00678b278bb10f6fb4bdb1e4ee25e/java_predict_client/src/main/proto/tensorflow/python/ops/control_flow_grad.py#L190-L218
peeringdb/peeringdb
47c6a699267b35663898f8d261159bdae9720f04
peeringdb_server/mock.py
python
Mock.create
(self, reftag, **kwargs)
return obj
Create a new instance of model specified in `reftag` Any arguments passed as kwargs will override mock field values. Note: Unless there are no relationships passed in kwargs, required parent objects will be automatically created as well. Returns: The created instance.
Create a new instance of model specified in `reftag`
[ "Create", "a", "new", "instance", "of", "model", "specified", "in", "reftag" ]
def create(self, reftag, **kwargs): """ Create a new instance of model specified in `reftag` Any arguments passed as kwargs will override mock field values. Note: Unless there are no relationships passed in kwargs, required parent objects will be automatically created as well. Returns: The created instance. """ model = REFTAG_MAP.get(reftag) data = {} data.update(**kwargs) # first we create any required parent relation ships for field in model._meta.get_fields(): if field.name in data: continue if field.is_relation and field.many_to_one: if hasattr(field.related_model, "ref_tag"): data[field.name] = self.create(field.related_model.handleref.tag) # then we set the other fields to mock values provided by this class for field in model._meta.get_fields(): # field value specified alrady, skip if field.name in data: continue # these we don't care about if field.name in ["id", "logo", "version", "created", "updated"]: continue # if reftag == "ixlan" and field.name != "id": # continue # elif reftag != "ixlan": # continue # this we don't care about either if field.name.find("geocode") == 0: continue # choice fields should automatically select a value from # the available choices # # PDB choices often have Not Disclosed at index 0 and 1 # so we try index 2 first. if ( not field.is_relation and field.choices and not hasattr(self, field.name) ): try: data[field.name] = field.choices[2][0] except IndexError: data[field.name] = field.choices[0][0] # bool fields set to True elif isinstance(field, models.BooleanField): data[field.name] = True # every other field elif not field.is_relation: # emails if field.name.find("email") > -1: data[field.name] = "test@peeringdb.com" # phone numbers elif field.name.find("phone") > -1: data[field.name] = "+12065550199" # URLs elif field.name.find("url") > -1: data[field.name] = "{}/{}".format( self.website(data, reftag=reftag), field.name ) # everything else is routed to the apropriate method # with the same name as the field name else: data[field.name] = getattr(self, field.name)(data, reftag=reftag) obj = model(**data) obj.clean() obj.save() return obj
[ "def", "create", "(", "self", ",", "reftag", ",", "*", "*", "kwargs", ")", ":", "model", "=", "REFTAG_MAP", ".", "get", "(", "reftag", ")", "data", "=", "{", "}", "data", ".", "update", "(", "*", "*", "kwargs", ")", "# first we create any required pare...
https://github.com/peeringdb/peeringdb/blob/47c6a699267b35663898f8d261159bdae9720f04/peeringdb_server/mock.py#L67-L152
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
ext/github/Repository.py
python
Repository.edit
( self, name=None, description=github.GithubObject.NotSet, homepage=github.GithubObject.NotSet, private=github.GithubObject.NotSet, has_issues=github.GithubObject.NotSet, has_projects=github.GithubObject.NotSet, has_wiki=github.GithubObject.NotSet, has_downloads=github.GithubObject.NotSet, default_branch=github.GithubObject.NotSet, allow_squash_merge=github.GithubObject.NotSet, allow_merge_commit=github.GithubObject.NotSet, allow_rebase_merge=github.GithubObject.NotSet, archived=github.GithubObject.NotSet, )
:calls: `PATCH /repos/:owner/:repo <http://developer.github.com/v3/repos>`_ :param name: string :param description: string :param homepage: string :param private: bool :param has_issues: bool :param has_projects: bool :param has_wiki: bool :param has_downloads: bool :param default_branch: string :param allow_squash_merge: bool :param allow_merge_commit: bool :param allow_rebase_merge: bool :param archived: bool. Unarchiving repositories is currently not supported through API (https://developer.github.com/v3/repos/#edit) :rtype: None
:calls: `PATCH /repos/:owner/:repo <http://developer.github.com/v3/repos>`_ :param name: string :param description: string :param homepage: string :param private: bool :param has_issues: bool :param has_projects: bool :param has_wiki: bool :param has_downloads: bool :param default_branch: string :param allow_squash_merge: bool :param allow_merge_commit: bool :param allow_rebase_merge: bool :param archived: bool. Unarchiving repositories is currently not supported through API (https://developer.github.com/v3/repos/#edit) :rtype: None
[ ":", "calls", ":", "PATCH", "/", "repos", "/", ":", "owner", "/", ":", "repo", "<http", ":", "//", "developer", ".", "github", ".", "com", "/", "v3", "/", "repos", ">", "_", ":", "param", "name", ":", "string", ":", "param", "description", ":", "...
def edit( self, name=None, description=github.GithubObject.NotSet, homepage=github.GithubObject.NotSet, private=github.GithubObject.NotSet, has_issues=github.GithubObject.NotSet, has_projects=github.GithubObject.NotSet, has_wiki=github.GithubObject.NotSet, has_downloads=github.GithubObject.NotSet, default_branch=github.GithubObject.NotSet, allow_squash_merge=github.GithubObject.NotSet, allow_merge_commit=github.GithubObject.NotSet, allow_rebase_merge=github.GithubObject.NotSet, archived=github.GithubObject.NotSet, ): """ :calls: `PATCH /repos/:owner/:repo <http://developer.github.com/v3/repos>`_ :param name: string :param description: string :param homepage: string :param private: bool :param has_issues: bool :param has_projects: bool :param has_wiki: bool :param has_downloads: bool :param default_branch: string :param allow_squash_merge: bool :param allow_merge_commit: bool :param allow_rebase_merge: bool :param archived: bool. Unarchiving repositories is currently not supported through API (https://developer.github.com/v3/repos/#edit) :rtype: None """ if name is None: name = self.name assert isinstance(name, (str, six.text_type)), name assert description is github.GithubObject.NotSet or isinstance( description, (str, six.text_type) ), description assert homepage is github.GithubObject.NotSet or isinstance( homepage, (str, six.text_type) ), homepage assert private is github.GithubObject.NotSet or isinstance( private, bool ), private assert has_issues is github.GithubObject.NotSet or isinstance( has_issues, bool ), has_issues assert has_projects is github.GithubObject.NotSet or isinstance( has_projects, bool ), has_projects assert has_wiki is github.GithubObject.NotSet or isinstance( has_wiki, bool ), has_wiki assert has_downloads is github.GithubObject.NotSet or isinstance( has_downloads, bool ), has_downloads assert default_branch is github.GithubObject.NotSet or isinstance( default_branch, (str, six.text_type) ), default_branch assert allow_squash_merge is github.GithubObject.NotSet or isinstance( allow_squash_merge, bool ), allow_squash_merge assert allow_merge_commit is github.GithubObject.NotSet or isinstance( allow_merge_commit, bool ), allow_merge_commit assert allow_rebase_merge is github.GithubObject.NotSet or isinstance( allow_rebase_merge, bool ), allow_rebase_merge assert archived is github.GithubObject.NotSet or ( isinstance(archived, bool) and archived is True ), archived post_parameters = { "name": name, } if description is not github.GithubObject.NotSet: post_parameters["description"] = description if homepage is not github.GithubObject.NotSet: post_parameters["homepage"] = homepage if private is not github.GithubObject.NotSet: post_parameters["private"] = private if has_issues is not github.GithubObject.NotSet: post_parameters["has_issues"] = has_issues if has_projects is not github.GithubObject.NotSet: post_parameters["has_projects"] = has_projects if has_wiki is not github.GithubObject.NotSet: post_parameters["has_wiki"] = has_wiki if has_downloads is not github.GithubObject.NotSet: post_parameters["has_downloads"] = has_downloads if default_branch is not github.GithubObject.NotSet: post_parameters["default_branch"] = default_branch if allow_squash_merge is not github.GithubObject.NotSet: post_parameters["allow_squash_merge"] = allow_squash_merge if allow_merge_commit is not github.GithubObject.NotSet: post_parameters["allow_merge_commit"] = allow_merge_commit if allow_rebase_merge is not github.GithubObject.NotSet: post_parameters["allow_rebase_merge"] = allow_rebase_merge if archived is not github.GithubObject.NotSet: post_parameters["archived"] = archived headers, data = self._requester.requestJsonAndCheck( "PATCH", self.url, input=post_parameters ) self._useAttributes(data)
[ "def", "edit", "(", "self", ",", "name", "=", "None", ",", "description", "=", "github", ".", "GithubObject", ".", "NotSet", ",", "homepage", "=", "github", ".", "GithubObject", ".", "NotSet", ",", "private", "=", "github", ".", "GithubObject", ".", "Not...
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/ext/github/Repository.py#L1395-L1497
jsonpickle/jsonpickle
1594d3fdb6717cb06d05c79e46f93330cc38eb36
jsonpickle/pickler.py
python
_mktyperef
(obj)
return {tags.TYPE: util.importable_name(obj)}
Return a typeref dictionary >>> _mktyperef(AssertionError) == {'py/type': 'builtins.AssertionError'} True
Return a typeref dictionary
[ "Return", "a", "typeref", "dictionary" ]
def _mktyperef(obj): """Return a typeref dictionary >>> _mktyperef(AssertionError) == {'py/type': 'builtins.AssertionError'} True """ return {tags.TYPE: util.importable_name(obj)}
[ "def", "_mktyperef", "(", "obj", ")", ":", "return", "{", "tags", ".", "TYPE", ":", "util", ".", "importable_name", "(", "obj", ")", "}" ]
https://github.com/jsonpickle/jsonpickle/blob/1594d3fdb6717cb06d05c79e46f93330cc38eb36/jsonpickle/pickler.py#L743-L750
hubblestack/hubble
763142474edcecdec5fd25591dc29c3536e8f969
hubblestack/modules/win_status.py
python
uptime
(human_readable=False)
return str(uptime) if human_readable else uptime.total_seconds()
.. versionadded:: 2015.8.0 Return the system uptime for the machine Args: human_readable (bool): Return uptime in human readable format if ``True``, otherwise return seconds. Default is ``False`` .. note:: Human readable format is ``days, hours:min:sec``. Days will only be displayed if more than 0 Returns: str: The uptime in seconds or human readable format depending on the value of ``human_readable`` CLI Example: .. code-block:: bash salt '*' status.uptime salt '*' status.uptime human_readable=True
.. versionadded:: 2015.8.0
[ "..", "versionadded", "::", "2015", ".", "8", ".", "0" ]
def uptime(human_readable=False): ''' .. versionadded:: 2015.8.0 Return the system uptime for the machine Args: human_readable (bool): Return uptime in human readable format if ``True``, otherwise return seconds. Default is ``False`` .. note:: Human readable format is ``days, hours:min:sec``. Days will only be displayed if more than 0 Returns: str: The uptime in seconds or human readable format depending on the value of ``human_readable`` CLI Example: .. code-block:: bash salt '*' status.uptime salt '*' status.uptime human_readable=True ''' # Get startup time startup_time = datetime.datetime.fromtimestamp(psutil.boot_time()) # Subtract startup time from current time to get the uptime of the system uptime = datetime.datetime.now() - startup_time return str(uptime) if human_readable else uptime.total_seconds()
[ "def", "uptime", "(", "human_readable", "=", "False", ")", ":", "# Get startup time", "startup_time", "=", "datetime", ".", "datetime", ".", "fromtimestamp", "(", "psutil", ".", "boot_time", "(", ")", ")", "# Subtract startup time from current time to get the uptime of ...
https://github.com/hubblestack/hubble/blob/763142474edcecdec5fd25591dc29c3536e8f969/hubblestack/modules/win_status.py#L74-L108
Qirky/FoxDot
76318f9630bede48ff3994146ed644affa27bfa4
FoxDot/lib/ServerManager.py
python
SCLangServerManager.set_midi_nudge
(self, value)
return
[]
def set_midi_nudge(self, value): self.midi_nudge = value return
[ "def", "set_midi_nudge", "(", "self", ",", "value", ")", ":", "self", ".", "midi_nudge", "=", "value", "return" ]
https://github.com/Qirky/FoxDot/blob/76318f9630bede48ff3994146ed644affa27bfa4/FoxDot/lib/ServerManager.py#L301-L303
TengXiaoDai/DistributedCrawling
f5c2439e6ce68dd9b49bde084d76473ff9ed4963
Lib/random.py
python
Random.vonmisesvariate
(self, mu, kappa)
return theta
Circular data distribution. mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi.
Circular data distribution.
[ "Circular", "data", "distribution", "." ]
def vonmisesvariate(self, mu, kappa): """Circular data distribution. mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi. """ # mu: mean angle (in radians between 0 and 2*pi) # kappa: concentration parameter kappa (>= 0) # if kappa = 0 generate uniform random angle # Based upon an algorithm published in: Fisher, N.I., # "Statistical Analysis of Circular Data", Cambridge # University Press, 1993. # Thanks to Magnus Kessler for a correction to the # implementation of step 4. random = self.random if kappa <= 1e-6: return TWOPI * random() s = 0.5 / kappa r = s + _sqrt(1.0 + s * s) while 1: u1 = random() z = _cos(_pi * u1) d = z / (r + z) u2 = random() if u2 < 1.0 - d * d or u2 <= (1.0 - d) * _exp(d): break q = 1.0 / r f = (q + z) / (1.0 + q * z) u3 = random() if u3 > 0.5: theta = (mu + _acos(f)) % TWOPI else: theta = (mu - _acos(f)) % TWOPI return theta
[ "def", "vonmisesvariate", "(", "self", ",", "mu", ",", "kappa", ")", ":", "# mu: mean angle (in radians between 0 and 2*pi)", "# kappa: concentration parameter kappa (>= 0)", "# if kappa = 0 generate uniform random angle", "# Based upon an algorithm published in: Fisher, N.I.,", "# \"...
https://github.com/TengXiaoDai/DistributedCrawling/blob/f5c2439e6ce68dd9b49bde084d76473ff9ed4963/Lib/random.py#L435-L479
smart-mobile-software/gitstack
d9fee8f414f202143eb6e620529e8e5539a2af56
python/Lib/site-packages/django/core/files/uploadhandler.py
python
load_handler
(path, *args, **kwargs)
return cls(*args, **kwargs)
Given a path to a handler, return an instance of that handler. E.g.:: >>> load_handler('django.core.files.uploadhandler.TemporaryFileUploadHandler', request) <TemporaryFileUploadHandler object at 0x...>
Given a path to a handler, return an instance of that handler.
[ "Given", "a", "path", "to", "a", "handler", "return", "an", "instance", "of", "that", "handler", "." ]
def load_handler(path, *args, **kwargs): """ Given a path to a handler, return an instance of that handler. E.g.:: >>> load_handler('django.core.files.uploadhandler.TemporaryFileUploadHandler', request) <TemporaryFileUploadHandler object at 0x...> """ i = path.rfind('.') module, attr = path[:i], path[i+1:] try: mod = importlib.import_module(module) except ImportError, e: raise ImproperlyConfigured('Error importing upload handler module %s: "%s"' % (module, e)) except ValueError, e: raise ImproperlyConfigured('Error importing upload handler module. Is FILE_UPLOAD_HANDLERS a correctly defined list or tuple?') try: cls = getattr(mod, attr) except AttributeError: raise ImproperlyConfigured('Module "%s" does not define a "%s" upload handler backend' % (module, attr)) return cls(*args, **kwargs)
[ "def", "load_handler", "(", "path", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "i", "=", "path", ".", "rfind", "(", "'.'", ")", "module", ",", "attr", "=", "path", "[", ":", "i", "]", ",", "path", "[", "i", "+", "1", ":", "]", "tr...
https://github.com/smart-mobile-software/gitstack/blob/d9fee8f414f202143eb6e620529e8e5539a2af56/python/Lib/site-packages/django/core/files/uploadhandler.py#L194-L215
openhatch/oh-mainline
ce29352a034e1223141dcc2f317030bbc3359a51
vendor/packages/twisted/twisted/names/client.py
python
lookupResponsibility
(name, timeout=None)
return getResolver().lookupResponsibility(name, timeout)
Perform an RP record lookup. @type name: C{str} @param name: DNS name to resolve. @type timeout: Sequence of C{int} @param timeout: Number of seconds after which to reissue the query. When the last timeout expires, the query is considered failed. @rtype: C{Deferred}
Perform an RP record lookup.
[ "Perform", "an", "RP", "record", "lookup", "." ]
def lookupResponsibility(name, timeout=None): """ Perform an RP record lookup. @type name: C{str} @param name: DNS name to resolve. @type timeout: Sequence of C{int} @param timeout: Number of seconds after which to reissue the query. When the last timeout expires, the query is considered failed. @rtype: C{Deferred} """ return getResolver().lookupResponsibility(name, timeout)
[ "def", "lookupResponsibility", "(", "name", ",", "timeout", "=", "None", ")", ":", "return", "getResolver", "(", ")", ".", "lookupResponsibility", "(", "name", ",", "timeout", ")" ]
https://github.com/openhatch/oh-mainline/blob/ce29352a034e1223141dcc2f317030bbc3359a51/vendor/packages/twisted/twisted/names/client.py#L869-L882
kozec/syncthing-gtk
01eeeb9ed485232e145bf39d90142832e1c9751e
syncthing_gtk/foldereditor.py
python
FolderEditorDialog.mark_device
(self, nid)
Marks (checks) checkbox for specified device
Marks (checks) checkbox for specified device
[ "Marks", "(", "checks", ")", "checkbox", "for", "specified", "device" ]
def mark_device(self, nid): """ Marks (checks) checkbox for specified device """ if "vdevices" in self: # ... only if there are checkboxes here for child in self["vdevices"].get_children(): if child.get_tooltip_text() == nid: l = child.get_children()[0] # Label in checkbox l.set_markup("<b>%s</b>" % (l.get_label())) child.set_active(True)
[ "def", "mark_device", "(", "self", ",", "nid", ")", ":", "if", "\"vdevices\"", "in", "self", ":", "# ... only if there are checkboxes here", "for", "child", "in", "self", "[", "\"vdevices\"", "]", ".", "get_children", "(", ")", ":", "if", "child", ".", "get_...
https://github.com/kozec/syncthing-gtk/blob/01eeeb9ed485232e145bf39d90142832e1c9751e/syncthing_gtk/foldereditor.py#L296-L303
MDAnalysis/mdanalysis
3488df3cdb0c29ed41c4fb94efe334b541e31b21
package/MDAnalysis/core/groups.py
python
SegmentGroup.n_atoms
(self)
return len(self.atoms)
Number of atoms present in the :class:`SegmentGroup`, including duplicate segments (and thus, duplicate atoms). Equivalent to ``len(self.atoms)``.
Number of atoms present in the :class:`SegmentGroup`, including duplicate segments (and thus, duplicate atoms).
[ "Number", "of", "atoms", "present", "in", "the", ":", "class", ":", "SegmentGroup", "including", "duplicate", "segments", "(", "and", "thus", "duplicate", "atoms", ")", "." ]
def n_atoms(self): """Number of atoms present in the :class:`SegmentGroup`, including duplicate segments (and thus, duplicate atoms). Equivalent to ``len(self.atoms)``. """ return len(self.atoms)
[ "def", "n_atoms", "(", "self", ")", ":", "return", "len", "(", "self", ".", "atoms", ")" ]
https://github.com/MDAnalysis/mdanalysis/blob/3488df3cdb0c29ed41c4fb94efe334b541e31b21/package/MDAnalysis/core/groups.py#L3797-L3803
zhl2008/awd-platform
0416b31abea29743387b10b3914581fbe8e7da5e
web_flaskbb/lib/python2.7/site-packages/sqlalchemy/orm/instrumentation.py
python
ClassManager.__init__
(self, class_)
[]
def __init__(self, class_): self.class_ = class_ self.info = {} self.new_init = None self.local_attrs = {} self.originals = {} self._bases = [mgr for mgr in [ manager_of_class(base) for base in self.class_.__bases__ if isinstance(base, type) ] if mgr is not None] for base in self._bases: self.update(base) self.dispatch._events._new_classmanager_instance(class_, self) # events._InstanceEventsHold.populate(class_, self) for basecls in class_.__mro__: mgr = manager_of_class(basecls) if mgr is not None: self.dispatch._update(mgr.dispatch) self.manage() self._instrument_init() if '__del__' in class_.__dict__: util.warn("__del__() method on class %s will " "cause unreachable cycles and memory leaks, " "as SQLAlchemy instrumentation often creates " "reference cycles. Please remove this method." % class_)
[ "def", "__init__", "(", "self", ",", "class_", ")", ":", "self", ".", "class_", "=", "class_", "self", ".", "info", "=", "{", "}", "self", ".", "new_init", "=", "None", "self", ".", "local_attrs", "=", "{", "}", "self", ".", "originals", "=", "{", ...
https://github.com/zhl2008/awd-platform/blob/0416b31abea29743387b10b3914581fbe8e7da5e/web_flaskbb/lib/python2.7/site-packages/sqlalchemy/orm/instrumentation.py#L55-L86
feliam/pysymemu
ad02e52122099d537372eb4d11fd5024b8a3857f
cpu.py
python
Cpu.JNZ
(cpu, target)
Jumps short if not zero. @param cpu: current CPU. @param target: destination operand.
Jumps short if not zero.
[ "Jumps", "short", "if", "not", "zero", "." ]
def JNZ(cpu, target): ''' Jumps short if not zero. @param cpu: current CPU. @param target: destination operand. ''' cpu.JNE(target)
[ "def", "JNZ", "(", "cpu", ",", "target", ")", ":", "cpu", ".", "JNE", "(", "target", ")" ]
https://github.com/feliam/pysymemu/blob/ad02e52122099d537372eb4d11fd5024b8a3857f/cpu.py#L3507-L3514
xolox/python-humanfriendly
6758ac61f906cd8528682003070a57febe4ad3cf
humanfriendly/prompts.py
python
prompt_for_confirmation
(question, default=None, padding=True)
Prompt the user for confirmation. :param question: The text that explains what the user is confirming (a string). :param default: The default value (a boolean) or :data:`None`. :param padding: Refer to the documentation of :func:`prompt_for_input()`. :returns: - If the user enters 'yes' or 'y' then :data:`True` is returned. - If the user enters 'no' or 'n' then :data:`False` is returned. - If the user doesn't enter any text or standard input is not connected to a terminal (which makes it impossible to prompt the user) the value of the keyword argument ``default`` is returned (if that value is not :data:`None`). :raises: - Any exceptions raised by :func:`retry_limit()`. - Any exceptions raised by :func:`prompt_for_input()`. When `default` is :data:`False` and the user doesn't enter any text an error message is printed and the prompt is repeated: >>> prompt_for_confirmation("Are you sure?") <BLANKLINE> Are you sure? [y/n] <BLANKLINE> Error: Please enter 'yes' or 'no' (there's no default choice). <BLANKLINE> Are you sure? [y/n] The same thing happens when the user enters text that isn't recognized: >>> prompt_for_confirmation("Are you sure?") <BLANKLINE> Are you sure? [y/n] about what? <BLANKLINE> Error: Please enter 'yes' or 'no' (the text 'about what?' is not recognized). <BLANKLINE> Are you sure? [y/n]
Prompt the user for confirmation.
[ "Prompt", "the", "user", "for", "confirmation", "." ]
def prompt_for_confirmation(question, default=None, padding=True): """ Prompt the user for confirmation. :param question: The text that explains what the user is confirming (a string). :param default: The default value (a boolean) or :data:`None`. :param padding: Refer to the documentation of :func:`prompt_for_input()`. :returns: - If the user enters 'yes' or 'y' then :data:`True` is returned. - If the user enters 'no' or 'n' then :data:`False` is returned. - If the user doesn't enter any text or standard input is not connected to a terminal (which makes it impossible to prompt the user) the value of the keyword argument ``default`` is returned (if that value is not :data:`None`). :raises: - Any exceptions raised by :func:`retry_limit()`. - Any exceptions raised by :func:`prompt_for_input()`. When `default` is :data:`False` and the user doesn't enter any text an error message is printed and the prompt is repeated: >>> prompt_for_confirmation("Are you sure?") <BLANKLINE> Are you sure? [y/n] <BLANKLINE> Error: Please enter 'yes' or 'no' (there's no default choice). <BLANKLINE> Are you sure? [y/n] The same thing happens when the user enters text that isn't recognized: >>> prompt_for_confirmation("Are you sure?") <BLANKLINE> Are you sure? [y/n] about what? <BLANKLINE> Error: Please enter 'yes' or 'no' (the text 'about what?' is not recognized). <BLANKLINE> Are you sure? [y/n] """ # Generate the text for the prompt. prompt_text = prepare_prompt_text(question, bold=True) # Append the valid replies (and default reply) to the prompt text. hint = "[Y/n]" if default else "[y/N]" if default is not None else "[y/n]" prompt_text += " %s " % prepare_prompt_text(hint, color=HIGHLIGHT_COLOR) # Loop until a valid response is given. logger.debug("Requesting interactive confirmation from terminal: %r", ansi_strip(prompt_text).rstrip()) for attempt in retry_limit(): reply = prompt_for_input(prompt_text, '', padding=padding, strip=True) if reply.lower() in ('y', 'yes'): logger.debug("Confirmation granted by reply (%r).", reply) return True elif reply.lower() in ('n', 'no'): logger.debug("Confirmation denied by reply (%r).", reply) return False elif (not reply) and default is not None: logger.debug("Default choice selected by empty reply (%r).", "granted" if default else "denied") return default else: details = ("the text '%s' is not recognized" % reply if reply else "there's no default choice") logger.debug("Got %s reply (%s), retrying (%i/%i) ..", "invalid" if reply else "empty", details, attempt, MAX_ATTEMPTS) warning("{indent}Error: Please enter 'yes' or 'no' ({details}).", indent=' ' if padding else '', details=details)
[ "def", "prompt_for_confirmation", "(", "question", ",", "default", "=", "None", ",", "padding", "=", "True", ")", ":", "# Generate the text for the prompt.", "prompt_text", "=", "prepare_prompt_text", "(", "question", ",", "bold", "=", "True", ")", "# Append the val...
https://github.com/xolox/python-humanfriendly/blob/6758ac61f906cd8528682003070a57febe4ad3cf/humanfriendly/prompts.py#L54-L117
IronLanguages/main
a949455434b1fda8c783289e897e78a9a0caabb5
External.LCA_RESTRICTED/Languages/IronPython/27/Lib/_strptime.py
python
_strptime
(data_string, format="%a %b %d %H:%M:%S %Y")
return (time.struct_time((year, month, day, hour, minute, second, weekday, julian, tz)), fraction)
Return a time struct based on the input string and the format string.
Return a time struct based on the input string and the format string.
[ "Return", "a", "time", "struct", "based", "on", "the", "input", "string", "and", "the", "format", "string", "." ]
def _strptime(data_string, format="%a %b %d %H:%M:%S %Y"): """Return a time struct based on the input string and the format string.""" global _TimeRE_cache, _regex_cache with _cache_lock: locale_time = _TimeRE_cache.locale_time if (_getlang() != locale_time.lang or time.tzname != locale_time.tzname or time.daylight != locale_time.daylight): _TimeRE_cache = TimeRE() _regex_cache.clear() locale_time = _TimeRE_cache.locale_time if len(_regex_cache) > _CACHE_MAX_SIZE: _regex_cache.clear() format_regex = _regex_cache.get(format) if not format_regex: try: format_regex = _TimeRE_cache.compile(format) # KeyError raised when a bad format is found; can be specified as # \\, in which case it was a stray % but with a space after it except KeyError, err: bad_directive = err.args[0] if bad_directive == "\\": bad_directive = "%" del err raise ValueError("'%s' is a bad directive in format '%s'" % (bad_directive, format)) # IndexError only occurs when the format string is "%" except IndexError: raise ValueError("stray %% in format '%s'" % format) _regex_cache[format] = format_regex found = format_regex.match(data_string) if not found: raise ValueError("time data %r does not match format %r" % (data_string, format)) if len(data_string) != found.end(): raise ValueError("unconverted data remains: %s" % data_string[found.end():]) year = None month = day = 1 hour = minute = second = fraction = 0 tz = -1 # Default to -1 to signify that values not known; not critical to have, # though week_of_year = -1 week_of_year_start = -1 # weekday and julian defaulted to None so as to signal need to calculate # values weekday = julian = None found_dict = found.groupdict() for group_key in found_dict.iterkeys(): # Directives not explicitly handled below: # c, x, X # handled by making out of other directives # U, W # worthless without day of the week if group_key == 'y': year = int(found_dict['y']) # Open Group specification for strptime() states that a %y #value in the range of [00, 68] is in the century 2000, while #[69,99] is in the century 1900 if year <= 68: year += 2000 else: year += 1900 elif group_key == 'Y': year = int(found_dict['Y']) elif group_key == 'm': month = int(found_dict['m']) elif group_key == 'B': month = locale_time.f_month.index(found_dict['B'].lower()) elif group_key == 'b': month = locale_time.a_month.index(found_dict['b'].lower()) elif group_key == 'd': day = int(found_dict['d']) elif group_key == 'H': hour = int(found_dict['H']) elif group_key == 'I': hour = int(found_dict['I']) ampm = found_dict.get('p', '').lower() # If there was no AM/PM indicator, we'll treat this like AM if ampm in ('', locale_time.am_pm[0]): # We're in AM so the hour is correct unless we're # looking at 12 midnight. # 12 midnight == 12 AM == hour 0 if hour == 12: hour = 0 elif ampm == locale_time.am_pm[1]: # We're in PM so we need to add 12 to the hour unless # we're looking at 12 noon. # 12 noon == 12 PM == hour 12 if hour != 12: hour += 12 elif group_key == 'M': minute = int(found_dict['M']) elif group_key == 'S': second = int(found_dict['S']) elif group_key == 'f': s = found_dict['f'] # Pad to always return microseconds. s += "0" * (6 - len(s)) fraction = int(s) elif group_key == 'A': weekday = locale_time.f_weekday.index(found_dict['A'].lower()) elif group_key == 'a': weekday = locale_time.a_weekday.index(found_dict['a'].lower()) elif group_key == 'w': weekday = int(found_dict['w']) if weekday == 0: weekday = 6 else: weekday -= 1 elif group_key == 'j': julian = int(found_dict['j']) elif group_key in ('U', 'W'): week_of_year = int(found_dict[group_key]) if group_key == 'U': # U starts week on Sunday. week_of_year_start = 6 else: # W starts week on Monday. week_of_year_start = 0 elif group_key == 'Z': # Since -1 is default value only need to worry about setting tz if # it can be something other than -1. found_zone = found_dict['Z'].lower() for value, tz_values in enumerate(locale_time.timezone): if found_zone in tz_values: # Deal with bad locale setup where timezone names are the # same and yet time.daylight is true; too ambiguous to # be able to tell what timezone has daylight savings if (time.tzname[0] == time.tzname[1] and time.daylight and found_zone not in ("utc", "gmt")): break else: tz = value break leap_year_fix = False if year is None and month == 2 and day == 29: year = 1904 # 1904 is first leap year of 20th century leap_year_fix = True elif year is None: year = 1900 # If we know the week of the year and what day of that week, we can figure # out the Julian day of the year. if julian is None and week_of_year != -1 and weekday is not None: week_starts_Mon = True if week_of_year_start == 0 else False julian = _calc_julian_from_U_or_W(year, week_of_year, weekday, week_starts_Mon) if julian <= 0: year -= 1 yday = 366 if calendar.isleap(year) else 365 julian += yday # Cannot pre-calculate datetime_date() since can change in Julian # calculation and thus could have different value for the day of the week # calculation. if julian is None: # Need to add 1 to result since first day of the year is 1, not 0. julian = datetime_date(year, month, day).toordinal() - \ datetime_date(year, 1, 1).toordinal() + 1 else: # Assume that if they bothered to include Julian day it will # be accurate. datetime_result = datetime_date.fromordinal((julian - 1) + datetime_date(year, 1, 1).toordinal()) year = datetime_result.year month = datetime_result.month day = datetime_result.day if weekday is None: weekday = datetime_date(year, month, day).weekday() if leap_year_fix: # the caller didn't supply a year but asked for Feb 29th. We couldn't # use the default of 1900 for computations. We set it back to ensure # that February 29th is smaller than March 1st. year = 1900 return (time.struct_time((year, month, day, hour, minute, second, weekday, julian, tz)), fraction)
[ "def", "_strptime", "(", "data_string", ",", "format", "=", "\"%a %b %d %H:%M:%S %Y\"", ")", ":", "global", "_TimeRE_cache", ",", "_regex_cache", "with", "_cache_lock", ":", "locale_time", "=", "_TimeRE_cache", ".", "locale_time", "if", "(", "_getlang", "(", ")", ...
https://github.com/IronLanguages/main/blob/a949455434b1fda8c783289e897e78a9a0caabb5/External.LCA_RESTRICTED/Languages/IronPython/27/Lib/_strptime.py#L299-L475
gxcuizy/Python
72167d12439a615a8fd4b935eae1fb6516ed4e69
从零学Python-掘金活动/day22/matplotlib_use.py
python
fun_8
()
Image 图片
Image 图片
[ "Image", "图片" ]
def fun_8(): """Image 图片""" # 用这样 3x3 的 2D-array 来表示点的颜色 a = numpy.array( [0.313660827978, 0.365348418405, 0.423733120134, 0.365348418405, 0.439599930621, 0.525083754405, 0.423733120134, 0.525083754405, 0.651536351379]).reshape(3, 3) pyplot.imshow(a, interpolation='nearest', cmap='bone', origin='lower') pyplot.colorbar(shrink=.92) # 去掉xy的刻度 pyplot.xticks(()) pyplot.yticks(()) # 显示图像 pyplot.show()
[ "def", "fun_8", "(", ")", ":", "# 用这样 3x3 的 2D-array 来表示点的颜色", "a", "=", "numpy", ".", "array", "(", "[", "0.313660827978", ",", "0.365348418405", ",", "0.423733120134", ",", "0.365348418405", ",", "0.439599930621", ",", "0.525083754405", ",", "0.423733120134", ",...
https://github.com/gxcuizy/Python/blob/72167d12439a615a8fd4b935eae1fb6516ed4e69/从零学Python-掘金活动/day22/matplotlib_use.py#L163-L175
roam-qgis/Roam
6bfa836a2735f611b7f26de18ae4a4581f7e83ef
src/configmanager/ui/layerwidgets.py
python
InfoNode.update_panel_status
(self, *args)
Update if the SQL panel is enabled or disable if the source is SQL Server or SQLite.
Update if the SQL panel is enabled or disable if the source is SQL Server or SQLite.
[ "Update", "if", "the", "SQL", "panel", "is", "enabled", "or", "disable", "if", "the", "source", "is", "SQL", "Server", "or", "SQLite", "." ]
def update_panel_status(self, *args): """ Update if the SQL panel is enabled or disable if the source is SQL Server or SQLite. """ layer = self.layer if not layer: self.queryframe.setEnabled(False) return False source = layer.source() name = layer.dataProvider().name() if ".sqlite" in source or name == "mssql" and layer.isValid(): keys = layer.primaryKeyAttributes() fields = layer.fields() if keys: fieldnames = " + ".join(fields[key].name() for key in keys) elif fields.count() > 0: fieldnames = fields.at(0).name() else: fieldnames = "" self.keyColumnLabel.setText(fieldnames) self.queryframe.setEnabled(True) self.queryframe.show() return True else: self.keyColumnLabel.setText("") self.queryframe.setEnabled(False) self.queryframe.hide() return False
[ "def", "update_panel_status", "(", "self", ",", "*", "args", ")", ":", "layer", "=", "self", ".", "layer", "if", "not", "layer", ":", "self", ".", "queryframe", ".", "setEnabled", "(", "False", ")", "return", "False", "source", "=", "layer", ".", "sour...
https://github.com/roam-qgis/Roam/blob/6bfa836a2735f611b7f26de18ae4a4581f7e83ef/src/configmanager/ui/layerwidgets.py#L951-L982
fab-jul/imgcomp-cvpr
f03ce0bfa846f7ba1bf9b7ba415b082efe5c192c
code/inputpipeline.py
python
InputPipeline.get_batch
(self)
return self._batch
[]
def get_batch(self): return self._batch
[ "def", "get_batch", "(", "self", ")", ":", "return", "self", ".", "_batch" ]
https://github.com/fab-jul/imgcomp-cvpr/blob/f03ce0bfa846f7ba1bf9b7ba415b082efe5c192c/code/inputpipeline.py#L168-L169
brainix/pottery
0a57ef51949e13f10ffbe5a8b499ea9cb1909ffc
pottery/base.py
python
Primitive.key
(self)
return self.__key
[]
def key(self) -> str: return self.__key
[ "def", "key", "(", "self", ")", "->", "str", ":", "return", "self", ".", "__key" ]
https://github.com/brainix/pottery/blob/0a57ef51949e13f10ffbe5a8b499ea9cb1909ffc/pottery/base.py#L327-L328
robotlearn/pyrobolearn
9cd7c060723fda7d2779fa255ac998c2c82b8436
pyrobolearn/distributions/gmm.py
python
GMM.__mul__
(self, other)
return self.multiply(other)
r""" Multiply two GMMs, or a GMM by a Gaussian, matrix, or float. See the `multiply` method for more information. Warnings: the multiplication of two GMMs performed here is NOT the one that multiply the components element-wise. For this one, have a look at `multiply_element_wise` method, or the `__and__` operator. Args: other (GMM, Gaussian, torch.float[D,D], float): GMM, Gaussian, or square matrix (to rotate or scale), or float Returns: GMM: resulting GMM
r""" Multiply two GMMs, or a GMM by a Gaussian, matrix, or float. See the `multiply` method for more information.
[ "r", "Multiply", "two", "GMMs", "or", "a", "GMM", "by", "a", "Gaussian", "matrix", "or", "float", ".", "See", "the", "multiply", "method", "for", "more", "information", "." ]
def __mul__(self, other): r""" Multiply two GMMs, or a GMM by a Gaussian, matrix, or float. See the `multiply` method for more information. Warnings: the multiplication of two GMMs performed here is NOT the one that multiply the components element-wise. For this one, have a look at `multiply_element_wise` method, or the `__and__` operator. Args: other (GMM, Gaussian, torch.float[D,D], float): GMM, Gaussian, or square matrix (to rotate or scale), or float Returns: GMM: resulting GMM """ return self.multiply(other)
[ "def", "__mul__", "(", "self", ",", "other", ")", ":", "return", "self", ".", "multiply", "(", "other", ")" ]
https://github.com/robotlearn/pyrobolearn/blob/9cd7c060723fda7d2779fa255ac998c2c82b8436/pyrobolearn/distributions/gmm.py#L1578-L1591
autotest/autotest
4614ae5f550cc888267b9a419e4b90deb54f8fae
client/harness.py
python
harness.run_complete
(self)
A run within this job is completing (all done)
A run within this job is completing (all done)
[ "A", "run", "within", "this", "job", "is", "completing", "(", "all", "done", ")" ]
def run_complete(self): """A run within this job is completing (all done)""" pass
[ "def", "run_complete", "(", "self", ")", ":", "pass" ]
https://github.com/autotest/autotest/blob/4614ae5f550cc888267b9a419e4b90deb54f8fae/client/harness.py#L64-L66
ClusterHQ/flocker
eaa586248986d7cd681c99c948546c2b507e44de
flocker/control/_model.py
python
DeploymentState.update_node
(self, node_state)
return self.transform(["nodes", updated_node.uuid], updated_node)
Create new ``DeploymentState`` based on this one which updates an existing ``NodeState`` with any known information from the given ``NodeState``. Attributes which are set to ``None` on the given update, indicating ignorance, will not be changed in the result. The given ``NodeState`` will simply be added if it doesn't represent a node that is already part of the ``DeploymentState`` (based on UUID comparison). :param NodeState node: An update for ``NodeState`` with same UUID in this ``DeploymentState``. :return DeploymentState: Updated with new ``NodeState``.
Create new ``DeploymentState`` based on this one which updates an existing ``NodeState`` with any known information from the given ``NodeState``. Attributes which are set to ``None` on the given update, indicating ignorance, will not be changed in the result.
[ "Create", "new", "DeploymentState", "based", "on", "this", "one", "which", "updates", "an", "existing", "NodeState", "with", "any", "known", "information", "from", "the", "given", "NodeState", ".", "Attributes", "which", "are", "set", "to", "None", "on", "the"...
def update_node(self, node_state): """ Create new ``DeploymentState`` based on this one which updates an existing ``NodeState`` with any known information from the given ``NodeState``. Attributes which are set to ``None` on the given update, indicating ignorance, will not be changed in the result. The given ``NodeState`` will simply be added if it doesn't represent a node that is already part of the ``DeploymentState`` (based on UUID comparison). :param NodeState node: An update for ``NodeState`` with same UUID in this ``DeploymentState``. :return DeploymentState: Updated with new ``NodeState``. """ original_node = self.nodes.get(node_state.uuid) if original_node is None: return self.transform(["nodes", node_state.uuid], node_state) updated_node = original_node.evolver() for key, value in node_state.items(): if value is not None: updated_node = updated_node.set(key, value) updated_node = updated_node.persistent() return self.transform(["nodes", updated_node.uuid], updated_node)
[ "def", "update_node", "(", "self", ",", "node_state", ")", ":", "original_node", "=", "self", ".", "nodes", ".", "get", "(", "node_state", ".", "uuid", ")", "if", "original_node", "is", "None", ":", "return", "self", ".", "transform", "(", "[", "\"nodes\...
https://github.com/ClusterHQ/flocker/blob/eaa586248986d7cd681c99c948546c2b507e44de/flocker/control/_model.py#L1168-L1192
spectacles/CodeComplice
8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62
libs/langinfo.py
python
LangInfo.__init__
(self, db)
[]
def __init__(self, db): self._db = db
[ "def", "__init__", "(", "self", ",", "db", ")", ":", "self", ".", "_db", "=", "db" ]
https://github.com/spectacles/CodeComplice/blob/8ca8ee4236f72b58caa4209d2fbd5fa56bd31d62/libs/langinfo.py#L177-L178
bruderstein/PythonScript
df9f7071ddf3a079e3a301b9b53a6dc78cf1208f
PythonLib/full/tarfile.py
python
_LowLevelFile.read
(self, size)
return os.read(self.fd, size)
[]
def read(self, size): return os.read(self.fd, size)
[ "def", "read", "(", "self", ",", "size", ")", ":", "return", "os", ".", "read", "(", "self", ".", "fd", ",", "size", ")" ]
https://github.com/bruderstein/PythonScript/blob/df9f7071ddf3a079e3a301b9b53a6dc78cf1208f/PythonLib/full/tarfile.py#L322-L323
AppScale/gts
46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9
AppServer/lib/django-1.5/django/contrib/gis/gdal/geomtype.py
python
OGRGeomType.__eq__
(self, other)
Does an equivalence test on the OGR type with the given other OGRGeomType, the short-hand string, or the integer.
Does an equivalence test on the OGR type with the given other OGRGeomType, the short-hand string, or the integer.
[ "Does", "an", "equivalence", "test", "on", "the", "OGR", "type", "with", "the", "given", "other", "OGRGeomType", "the", "short", "-", "hand", "string", "or", "the", "integer", "." ]
def __eq__(self, other): """ Does an equivalence test on the OGR type with the given other OGRGeomType, the short-hand string, or the integer. """ if isinstance(other, OGRGeomType): return self.num == other.num elif isinstance(other, six.string_types): return self.name.lower() == other.lower() elif isinstance(other, int): return self.num == other else: return False
[ "def", "__eq__", "(", "self", ",", "other", ")", ":", "if", "isinstance", "(", "other", ",", "OGRGeomType", ")", ":", "return", "self", ".", "num", "==", "other", ".", "num", "elif", "isinstance", "(", "other", ",", "six", ".", "string_types", ")", "...
https://github.com/AppScale/gts/blob/46f909cf5dc5ba81faf9d81dc9af598dcf8a82a9/AppServer/lib/django-1.5/django/contrib/gis/gdal/geomtype.py#L57-L69
deanishe/alfred-fakeum
12a7e64d9c099c0f11416ee99fae064d6360aab2
src/libs/faker/providers/address/ja_JP/__init__.py
python
Provider.town
(self)
return self.random_element(self.towns)
:example '浅草'
:example '浅草'
[ ":", "example", "浅草" ]
def town(self): """ :example '浅草' """ return self.random_element(self.towns)
[ "def", "town", "(", "self", ")", ":", "return", "self", ".", "random_element", "(", "self", ".", "towns", ")" ]
https://github.com/deanishe/alfred-fakeum/blob/12a7e64d9c099c0f11416ee99fae064d6360aab2/src/libs/faker/providers/address/ja_JP/__init__.py#L320-L324
chromium/web-page-replay
472351e1122bb1beb936952c7e75ae58bf8a69f1
third_party/dns/message.py
python
Message.want_dnssec
(self, wanted=True)
Enable or disable 'DNSSEC desired' flag in requests. @param wanted: Is DNSSEC desired? If True, EDNS is enabled if required, and then the DO bit is set. If False, the DO bit is cleared if EDNS is enabled. @type wanted: bool
Enable or disable 'DNSSEC desired' flag in requests.
[ "Enable", "or", "disable", "DNSSEC", "desired", "flag", "in", "requests", "." ]
def want_dnssec(self, wanted=True): """Enable or disable 'DNSSEC desired' flag in requests. @param wanted: Is DNSSEC desired? If True, EDNS is enabled if required, and then the DO bit is set. If False, the DO bit is cleared if EDNS is enabled. @type wanted: bool """ if wanted: if self.edns < 0: self.use_edns() self.ednsflags |= dns.flags.DO elif self.edns >= 0: self.ednsflags &= ~dns.flags.DO
[ "def", "want_dnssec", "(", "self", ",", "wanted", "=", "True", ")", ":", "if", "wanted", ":", "if", "self", ".", "edns", "<", "0", ":", "self", ".", "use_edns", "(", ")", "self", ".", "ednsflags", "|=", "dns", ".", "flags", ".", "DO", "elif", "se...
https://github.com/chromium/web-page-replay/blob/472351e1122bb1beb936952c7e75ae58bf8a69f1/third_party/dns/message.py#L507-L519
JetBrains/python-skeletons
95ad24b666e475998e5d1cc02ed53a2188036167
numpy/core/__init__.py
python
generic.trace
(self, *args, **kwargs)
Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest.
Not implemented (virtual attribute)
[ "Not", "implemented", "(", "virtual", "attribute", ")" ]
def trace(self, *args, **kwargs): # real signature unknown """ Not implemented (virtual attribute) Class generic exists solely to derive numpy scalars from, and possesses, albeit unimplemented, all the attributes of the ndarray class so as to provide a uniform API. See Also -------- The corresponding attribute of the derived class of interest. """ pass
[ "def", "trace", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# real signature unknown", "pass" ]
https://github.com/JetBrains/python-skeletons/blob/95ad24b666e475998e5d1cc02ed53a2188036167/numpy/core/__init__.py#L702-L714
sabnzbd/sabnzbd
52d21e94d3cc6e30764a833fe2a256783d1a8931
sabnzbd/scheduler.py
python
enable_server
(server)
Enable server (scheduler only)
Enable server (scheduler only)
[ "Enable", "server", "(", "scheduler", "only", ")" ]
def enable_server(server): """Enable server (scheduler only)""" try: config.get_config("servers", server).enable.set(1) except: logging.warning(T("Trying to set status of non-existing server %s"), server) return config.save_config() sabnzbd.Downloader.update_server(server, server)
[ "def", "enable_server", "(", "server", ")", ":", "try", ":", "config", ".", "get_config", "(", "\"servers\"", ",", "server", ")", ".", "enable", ".", "set", "(", "1", ")", "except", ":", "logging", ".", "warning", "(", "T", "(", "\"Trying to set status o...
https://github.com/sabnzbd/sabnzbd/blob/52d21e94d3cc6e30764a833fe2a256783d1a8931/sabnzbd/scheduler.py#L488-L496
adobe/antialiased-cnns
b27a34a26f3ab039113d44d83c54d0428598ac9c
antialiased_cnns/resnet.py
python
conv3x3
(in_planes, out_planes, stride=1, groups=1, dilation=1)
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
3x3 convolution with padding
3x3 convolution with padding
[ "3x3", "convolution", "with", "padding" ]
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): """3x3 convolution with padding""" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, bias=False, dilation=dilation)
[ "def", "conv3x3", "(", "in_planes", ",", "out_planes", ",", "stride", "=", "1", ",", "groups", "=", "1", ",", "dilation", "=", "1", ")", ":", "return", "nn", ".", "Conv2d", "(", "in_planes", ",", "out_planes", ",", "kernel_size", "=", "3", ",", "stri...
https://github.com/adobe/antialiased-cnns/blob/b27a34a26f3ab039113d44d83c54d0428598ac9c/antialiased_cnns/resnet.py#L77-L80
mesonbuild/meson
a22d0f9a0a787df70ce79b05d0c45de90a970048
mesonbuild/compilers/mixins/clike.py
python
CLikeCompiler.compiler_args
(self, args: T.Optional[T.Iterable[str]] = None)
return CLikeCompilerArgs(self, args)
[]
def compiler_args(self, args: T.Optional[T.Iterable[str]] = None) -> CLikeCompilerArgs: # This is correct, mypy just doesn't understand co-operative inheritance return CLikeCompilerArgs(self, args)
[ "def", "compiler_args", "(", "self", ",", "args", ":", "T", ".", "Optional", "[", "T", ".", "Iterable", "[", "str", "]", "]", "=", "None", ")", "->", "CLikeCompilerArgs", ":", "# This is correct, mypy just doesn't understand co-operative inheritance", "return", "C...
https://github.com/mesonbuild/meson/blob/a22d0f9a0a787df70ce79b05d0c45de90a970048/mesonbuild/compilers/mixins/clike.py#L148-L150
stepjam/PyRep
d778d5d4ffa3be366d4e699f6e2941553fd47ecc
pyrep/objects/shape.py
python
Shape.add_force_and_torque
(self, force: np.ndarray, torque: np.ndarray, reset_force: bool = False, reset_torque: bool = False)
Adds a force and/or torque to a shape object that is dynamically enabled. Forces are applied at the center of mass. Added forces and torques are cumulative. :param force: The force (in absolute coordinates) to add. :param torque: The torque (in absolute coordinates) to add. :param reset_force: Clears the accumulated force. :param reset_torque: Clears the accumulated torque.
Adds a force and/or torque to a shape object that is dynamically enabled. Forces are applied at the center of mass. Added forces and torques are cumulative.
[ "Adds", "a", "force", "and", "/", "or", "torque", "to", "a", "shape", "object", "that", "is", "dynamically", "enabled", ".", "Forces", "are", "applied", "at", "the", "center", "of", "mass", ".", "Added", "forces", "and", "torques", "are", "cumulative", "...
def add_force_and_torque(self, force: np.ndarray, torque: np.ndarray, reset_force: bool = False, reset_torque: bool = False) -> None: """ Adds a force and/or torque to a shape object that is dynamically enabled. Forces are applied at the center of mass. Added forces and torques are cumulative. :param force: The force (in absolute coordinates) to add. :param torque: The torque (in absolute coordinates) to add. :param reset_force: Clears the accumulated force. :param reset_torque: Clears the accumulated torque. """ h = self._handle if reset_force: h |= sim.sim_handleflag_resetforce if reset_torque: h |= sim.sim_handleflag_resettorque sim.simAddForceAndTorque(h, None if force is None else list(force), None if torque is None else list(torque))
[ "def", "add_force_and_torque", "(", "self", ",", "force", ":", "np", ".", "ndarray", ",", "torque", ":", "np", ".", "ndarray", ",", "reset_force", ":", "bool", "=", "False", ",", "reset_torque", ":", "bool", "=", "False", ")", "->", "None", ":", "h", ...
https://github.com/stepjam/PyRep/blob/d778d5d4ffa3be366d4e699f6e2941553fd47ecc/pyrep/objects/shape.py#L561-L581
Azure/azure-linux-extensions
a42ef718c746abab2b3c6a21da87b29e76364558
Common/libpsutil/py2.6-glibc-2.12-pre/psutil/_pswindows.py
python
net_connections
(kind, _pid=-1)
return ret
Return socket connections. If pid == -1 return system-wide connections (as opposed to connections opened by one process only).
Return socket connections. If pid == -1 return system-wide connections (as opposed to connections opened by one process only).
[ "Return", "socket", "connections", ".", "If", "pid", "==", "-", "1", "return", "system", "-", "wide", "connections", "(", "as", "opposed", "to", "connections", "opened", "by", "one", "process", "only", ")", "." ]
def net_connections(kind, _pid=-1): """Return socket connections. If pid == -1 return system-wide connections (as opposed to connections opened by one process only). """ if kind not in conn_tmap: raise ValueError("invalid %r kind argument; choose between %s" % (kind, ', '.join([repr(x) for x in conn_tmap]))) families, types = conn_tmap[kind] rawlist = cext.net_connections(_pid, families, types) ret = [] for item in rawlist: fd, fam, type, laddr, raddr, status, pid = item status = TCP_STATUSES[status] if _pid == -1: nt = _common.sconn(fd, fam, type, laddr, raddr, status, pid) else: nt = _common.pconn(fd, fam, type, laddr, raddr, status) ret.append(nt) return ret
[ "def", "net_connections", "(", "kind", ",", "_pid", "=", "-", "1", ")", ":", "if", "kind", "not", "in", "conn_tmap", ":", "raise", "ValueError", "(", "\"invalid %r kind argument; choose between %s\"", "%", "(", "kind", ",", "', '", ".", "join", "(", "[", "...
https://github.com/Azure/azure-linux-extensions/blob/a42ef718c746abab2b3c6a21da87b29e76364558/Common/libpsutil/py2.6-glibc-2.12-pre/psutil/_pswindows.py#L161-L179
limodou/ulipad
4c7d590234f39cac80bb1d36dca095b646e287fb
mixins/ShellWindow.py
python
NEInterpreter.push
(self, command)
return more
Send command to the interpreter to be executed. Because this may be called recursively, we append a new list onto the commandBuffer list and then append commands into that. If the passed in command is part of a multi-line command we keep appending the pieces to the last list in commandBuffer until we have a complete command. If not, we delete that last list.
Send command to the interpreter to be executed.
[ "Send", "command", "to", "the", "interpreter", "to", "be", "executed", "." ]
def push(self, command): """Send command to the interpreter to be executed. Because this may be called recursively, we append a new list onto the commandBuffer list and then append commands into that. If the passed in command is part of a multi-line command we keep appending the pieces to the last list in commandBuffer until we have a complete command. If not, we delete that last list.""" if isinstance(command, types.UnicodeType): command = command.encode(common.defaultencoding) if not self.more: try: del self.commandBuffer[-1] except IndexError: pass if not self.more: self.commandBuffer.append([]) self.commandBuffer[-1].append(command) source = os.linesep.join(self.commandBuffer[-1]) more = self.more = self.runsource(source) dispatcher.send(signal='Interpreter.push', sender=self, command=command, more=more, source=source) return more
[ "def", "push", "(", "self", ",", "command", ")", ":", "if", "isinstance", "(", "command", ",", "types", ".", "UnicodeType", ")", ":", "command", "=", "command", ".", "encode", "(", "common", ".", "defaultencoding", ")", "if", "not", "self", ".", "more"...
https://github.com/limodou/ulipad/blob/4c7d590234f39cac80bb1d36dca095b646e287fb/mixins/ShellWindow.py#L232-L253
ctxis/canape
5f0e03424577296bcc60c2008a60a98ec5307e4b
CANAPE.Scripting/Lib/logging/__init__.py
python
Manager.setLoggerClass
(self, klass)
Set the class to be used when instantiating a logger with this Manager.
Set the class to be used when instantiating a logger with this Manager.
[ "Set", "the", "class", "to", "be", "used", "when", "instantiating", "a", "logger", "with", "this", "Manager", "." ]
def setLoggerClass(self, klass): """ Set the class to be used when instantiating a logger with this Manager. """ if klass != Logger: if not issubclass(klass, Logger): raise TypeError("logger not derived from logging.Logger: " + klass.__name__) self.loggerClass = klass
[ "def", "setLoggerClass", "(", "self", ",", "klass", ")", ":", "if", "klass", "!=", "Logger", ":", "if", "not", "issubclass", "(", "klass", ",", "Logger", ")", ":", "raise", "TypeError", "(", "\"logger not derived from logging.Logger: \"", "+", "klass", ".", ...
https://github.com/ctxis/canape/blob/5f0e03424577296bcc60c2008a60a98ec5307e4b/CANAPE.Scripting/Lib/logging/__init__.py#L1026-L1034
knipknap/exscript
a20e83ae3a78ea7e5ba25f07c1d9de4e9b961e83
Exscript/protocols/telnetlib.py
python
Telnet.read_lazy
(self)
return self.read_very_lazy()
Process and return data that's already in the queues (lazy). Raise EOFError if connection closed and no data available. Return '' if no cooked data available otherwise. Don't block unless in the midst of an IAC sequence.
Process and return data that's already in the queues (lazy).
[ "Process", "and", "return", "data", "that", "s", "already", "in", "the", "queues", "(", "lazy", ")", "." ]
def read_lazy(self): """Process and return data that's already in the queues (lazy). Raise EOFError if connection closed and no data available. Return '' if no cooked data available otherwise. Don't block unless in the midst of an IAC sequence. """ self.process_rawq() return self.read_very_lazy()
[ "def", "read_lazy", "(", "self", ")", ":", "self", ".", "process_rawq", "(", ")", "return", "self", ".", "read_very_lazy", "(", ")" ]
https://github.com/knipknap/exscript/blob/a20e83ae3a78ea7e5ba25f07c1d9de4e9b961e83/Exscript/protocols/telnetlib.py#L368-L377
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/benchmarks/src/benchmarks/sympy/sympy/geometry/line.py
python
LinearEntity.is_similar
(self, other)
return _norm(*self.coefficients) == _norm(*other.coefficients)
Return True if self and other are contained in the same line. Examples ======== >>> from sympy import Point, Line >>> p1, p2, p3 = Point(0, 1), Point(3, 4), Point(2, 3) >>> l1 = Line(p1, p2) >>> l2 = Line(p1, p3) >>> l1.is_similar(l2) True
Return True if self and other are contained in the same line.
[ "Return", "True", "if", "self", "and", "other", "are", "contained", "in", "the", "same", "line", "." ]
def is_similar(self, other): """ Return True if self and other are contained in the same line. Examples ======== >>> from sympy import Point, Line >>> p1, p2, p3 = Point(0, 1), Point(3, 4), Point(2, 3) >>> l1 = Line(p1, p2) >>> l2 = Line(p1, p3) >>> l1.is_similar(l2) True """ def _norm(a, b, c): if a != 0: return 1, b/a, c/a elif b != 0: return a/b, 1, c/b else: return c return _norm(*self.coefficients) == _norm(*other.coefficients)
[ "def", "is_similar", "(", "self", ",", "other", ")", ":", "def", "_norm", "(", "a", ",", "b", ",", "c", ")", ":", "if", "a", "!=", "0", ":", "return", "1", ",", "b", "/", "a", ",", "c", "/", "a", "elif", "b", "!=", "0", ":", "return", "a"...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/benchmarks/src/benchmarks/sympy/sympy/geometry/line.py#L905-L926
BigBrotherBot/big-brother-bot
848823c71413c86e7f1ff9584f43e08d40a7f2c0
b3/plugins/customcommands/__init__.py
python
CustomcommandsPlugin._validate_cmd_template
(self, template)
Makes sure a command template is correct. Raise ValueError if invalid.
Makes sure a command template is correct. Raise ValueError if invalid.
[ "Makes", "sure", "a", "command", "template", "is", "correct", ".", "Raise", "ValueError", "if", "invalid", "." ]
def _validate_cmd_template(self, template): """ Makes sure a command template is correct. Raise ValueError if invalid. """ assert template is not None if template.strip() == '': raise ValueError("command template cannot be blank") if template.count("<ARG:") > 1: raise ValueError("command template cannot have more than one 'ARG' placeholder")
[ "def", "_validate_cmd_template", "(", "self", ",", "template", ")", ":", "assert", "template", "is", "not", "None", "if", "template", ".", "strip", "(", ")", "==", "''", ":", "raise", "ValueError", "(", "\"command template cannot be blank\"", ")", "if", "templ...
https://github.com/BigBrotherBot/big-brother-bot/blob/848823c71413c86e7f1ff9584f43e08d40a7f2c0/b3/plugins/customcommands/__init__.py#L145-L154
ramusus/kinopoiskpy
e49b41eff7ae4252987636ec14c060109a50fad6
kinopoisk/utils.py
python
Manager.get_url_with_params
(self, query)
return 'http://www.kinopoisk.ru/index.php', {'kp_query': query}
[]
def get_url_with_params(self, query): return 'http://www.kinopoisk.ru/index.php', {'kp_query': query}
[ "def", "get_url_with_params", "(", "self", ",", "query", ")", ":", "return", "'http://www.kinopoisk.ru/index.php'", ",", "{", "'kp_query'", ":", "query", "}" ]
https://github.com/ramusus/kinopoiskpy/blob/e49b41eff7ae4252987636ec14c060109a50fad6/kinopoisk/utils.py#L52-L53
google/vimdoc
58b7b8b0c0d153ca3f689928f64c20953c14ded0
vimdoc/output.py
python
Helpfile.Print
(self, line, end='\n', wide=False)
Outputs a line to the file.
Outputs a line to the file.
[ "Outputs", "a", "line", "to", "the", "file", "." ]
def Print(self, line, end='\n', wide=False): """Outputs a line to the file.""" if not wide: assert len(line) <= self.WIDTH if self.file is None: raise ValueError('Helpfile writer not yet given helpfile to write.') self.file.write(line + end)
[ "def", "Print", "(", "self", ",", "line", ",", "end", "=", "'\\n'", ",", "wide", "=", "False", ")", ":", "if", "not", "wide", ":", "assert", "len", "(", "line", ")", "<=", "self", ".", "WIDTH", "if", "self", ".", "file", "is", "None", ":", "rai...
https://github.com/google/vimdoc/blob/58b7b8b0c0d153ca3f689928f64c20953c14ded0/vimdoc/output.py#L192-L198
learningequality/kolibri
d056dbc477aaf651ab843caa141a6a1e0a491046
kolibri/utils/server.py
python
get_status
()
return pid, LISTEN_ADDRESS, listen_port
Tries to get the PID of a running server. The behavior is also quite redundant given that `kolibri start` should always create a PID file, and if its been started directly with the runserver command, then its up to the developer to know what's happening. :returns: (PID, address, port), where address is not currently detected in a valid way because it's not configurable, and we might be listening on several IPs. :raises: NotRunning
Tries to get the PID of a running server.
[ "Tries", "to", "get", "the", "PID", "of", "a", "running", "server", "." ]
def get_status(): # noqa: max-complexity=16 """ Tries to get the PID of a running server. The behavior is also quite redundant given that `kolibri start` should always create a PID file, and if its been started directly with the runserver command, then its up to the developer to know what's happening. :returns: (PID, address, port), where address is not currently detected in a valid way because it's not configurable, and we might be listening on several IPs. :raises: NotRunning """ # PID file exists and startup has finished, check if it is running pid, port, _, status = _read_pid_file(PID_FILE) if status not in IS_RUNNING: raise NotRunning(status) if status == STATUS_STARTING_UP: try: wait_for_occupied_port(LISTEN_ADDRESS, port) except OSError: raise NotRunning(STATUS_FAILED_TO_START) if status == STATUS_SHUTTING_DOWN: try: wait_for_free_port(LISTEN_ADDRESS, port) except OSError: raise NotRunning(STATUS_UNCLEAN_SHUTDOWN) raise NotRunning(STATUS_STOPPED) # PID file exists, but process is dead if pid is None or not pid_exists(pid): raise NotRunning(STATUS_UNCLEAN_SHUTDOWN) # Unclean shutdown listen_port = port prefix = ( conf.OPTIONS["Deployment"]["URL_PATH_PREFIX"] if conf.OPTIONS["Deployment"]["URL_PATH_PREFIX"] == "/" else "/" + conf.OPTIONS["Deployment"]["URL_PATH_PREFIX"] ) check_url = "http://{}:{}{}status/".format("127.0.0.1", listen_port, prefix) if conf.OPTIONS["Server"]["CHERRYPY_START"]: try: # Timeout is 3 seconds, we don't want the status command to be slow # TODO: Using 127.0.0.1 is a hardcode default from Kolibri, it could # be configurable # TODO: HTTP might not be the protocol if server has SSL response = requests.get(check_url, timeout=3) except (requests.exceptions.ReadTimeout, requests.exceptions.ConnectionError): raise NotRunning(STATUS_NOT_RESPONDING) except (requests.exceptions.RequestException): raise NotRunning(STATUS_UNCLEAN_SHUTDOWN) if response.status_code == 404: raise NotRunning(STATUS_UNKNOWN_INSTANCE) # Unknown HTTP server if response.status_code != 200: # Probably a mis-configured kolibri sys.stderr.write("---Debug information---\n") sys.stderr.write(response.text) sys.stderr.write("\n-----------------------\n") raise NotRunning(STATUS_SERVER_CONFIGURATION_ERROR) else: try: requests.get(check_url, timeout=3) except (requests.exceptions.ReadTimeout, requests.exceptions.ConnectionError): raise NotRunning(STATUS_NOT_RESPONDING) except (requests.exceptions.RequestException): return pid, "", "" return pid, LISTEN_ADDRESS, listen_port
[ "def", "get_status", "(", ")", ":", "# noqa: max-complexity=16", "# PID file exists and startup has finished, check if it is running", "pid", ",", "port", ",", "_", ",", "status", "=", "_read_pid_file", "(", "PID_FILE", ")", "if", "status", "not", "in", "IS_RUNNING", ...
https://github.com/learningequality/kolibri/blob/d056dbc477aaf651ab843caa141a6a1e0a491046/kolibri/utils/server.py#L817-L894
pymedusa/Medusa
1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38
medusa/tv/series.py
python
SeriesIdentifier.from_id
(cls, indexer, indexer_id)
return SeriesIdentifier(indexer, indexer_id)
Create SeriesIdentifier from tuple (indexer, indexer_id).
Create SeriesIdentifier from tuple (indexer, indexer_id).
[ "Create", "SeriesIdentifier", "from", "tuple", "(", "indexer", "indexer_id", ")", "." ]
def from_id(cls, indexer, indexer_id): """Create SeriesIdentifier from tuple (indexer, indexer_id).""" return SeriesIdentifier(indexer, indexer_id)
[ "def", "from_id", "(", "cls", ",", "indexer", ",", "indexer_id", ")", ":", "return", "SeriesIdentifier", "(", "indexer", ",", "indexer_id", ")" ]
https://github.com/pymedusa/Medusa/blob/1405fbb6eb8ef4d20fcca24c32ddca52b11f0f38/medusa/tv/series.py#L158-L160
biolab/orange3
41685e1c7b1d1babe680113685a2d44bcc9fec0b
Orange/widgets/visualize/owviolinplot.py
python
BoxItem._create_box_plot
(data: np.ndarray)
return min_, q25, q75, max_
[]
def _create_box_plot(data: np.ndarray) -> Tuple: if data.size == 0: return (0,) * 4 q25, q75 = np.percentile(data, [25, 75]) whisker_lim = 1.5 * stats.iqr(data) min_ = np.min(data[data >= (q25 - whisker_lim)]) max_ = np.max(data[data <= (q75 + whisker_lim)]) return min_, q25, q75, max_
[ "def", "_create_box_plot", "(", "data", ":", "np", ".", "ndarray", ")", "->", "Tuple", ":", "if", "data", ".", "size", "==", "0", ":", "return", "(", "0", ",", ")", "*", "4", "q25", ",", "q75", "=", "np", ".", "percentile", "(", "data", ",", "[...
https://github.com/biolab/orange3/blob/41685e1c7b1d1babe680113685a2d44bcc9fec0b/Orange/widgets/visualize/owviolinplot.py#L284-L292
peterbrittain/asciimatics
9a490faddf484ee5b9b845316f921f5888b23b18
samples/terminal.py
python
Terminal._add_stream
(self, value)
Process any output from the TTY.
Process any output from the TTY.
[ "Process", "any", "output", "from", "the", "TTY", "." ]
def _add_stream(self, value): """ Process any output from the TTY. """ lines = value.split("\n") for i, line in enumerate(lines): self._parser.reset(line, self._current_colours) for offset, command, params in self._parser.parse(): if command == Parser.DISPLAY_TEXT: # Just display the text... allowing for line wrapping. if self._cursor_x + len(params) > self._w: part_1 = params[:self._w - self._cursor_x] part_2 = params[self._w - self._cursor_x:] self._print_at(part_1, self._cursor_x, self._cursor_y) self._print_at(part_2, 0, self._cursor_y + 1) self._cursor_x = len(part_2) self._cursor_y += 1 if self._cursor_y - self._canvas.start_line >= self._h: self._canvas.scroll() else: self._print_at(params, self._cursor_x, self._cursor_y) self._cursor_x += len(params) elif command == Parser.CHANGE_COLOURS: # Change current text colours. self._current_colours = params elif command == Parser.NEXT_TAB: # Move to next tab stop - hard-coded to default of 8 characters. self._cursor_x = (self._cursor_x // 8) * 8 + 8 elif command == Parser.MOVE_RELATIVE: # Move cursor relative to current position. self._cursor_x += params[0] self._cursor_y += params[1] if self._cursor_y < self._canvas.start_line: self._canvas.scroll(self._cursor_y - self._canvas.start_line) elif command == Parser.MOVE_ABSOLUTE: # Move cursor relative to specified absolute position. if params[0] is not None: self._cursor_x = params[0] if params[1] is not None: self._cursor_y = params[1] + self._canvas.start_line elif command == Parser.DELETE_LINE: # Delete some/all of the current line. if params == 0: self._print_at(" " * (self._w - self._cursor_x), self._cursor_x, self._cursor_y) elif params == 1: self._print_at(" " * self._cursor_x, 0, self._cursor_y) elif params == 2: self._print_at(" " * self._w, 0, self._cursor_y) elif command == Parser.DELETE_CHARS: # Delete n characters under the cursor. for x in range(self._cursor_x, self._w): if x + params < self._w: cell = self._canvas.get_from(x + params, self._cursor_y) else: cell = (ord(" "), self._current_colours[0], self._current_colours[1], self._current_colours[2]) self._canvas.print_at( chr(cell[0]), x, self._cursor_y, colour=cell[1], attr=cell[2], bg=cell[3]) elif command == Parser.SHOW_CURSOR: # Show/hide the cursor. self._show_cursor = params elif command == Parser.CLEAR_SCREEN: # Clear the screen. self._canvas.clear_buffer( self._current_colours[0], self._current_colours[1], self._current_colours[2]) # Move to next line, scrolling buffer as needed. if i != len(lines) - 1: self._cursor_x = 0 self._cursor_y += 1 if self._cursor_y - self._canvas.start_line >= self._h: self._canvas.scroll()
[ "def", "_add_stream", "(", "self", ",", "value", ")", ":", "lines", "=", "value", ".", "split", "(", "\"\\n\"", ")", "for", "i", ",", "line", "in", "enumerate", "(", "lines", ")", ":", "self", ".", "_parser", ".", "reset", "(", "line", ",", "self",...
https://github.com/peterbrittain/asciimatics/blob/9a490faddf484ee5b9b845316f921f5888b23b18/samples/terminal.py#L114-L186
spacetx/starfish
0e879d995d5c49b6f5a842e201e3be04c91afc7e
starfish/core/spots/AssignTargets/_base.py
python
AssignTargetsAlgorithm.run
( self, masks: BinaryMaskCollection, decoded_intensity_table: DecodedIntensityTable, verbose: bool = False, in_place: bool = False, )
Performs target (e.g. gene) assignment given the spots and the regions.
Performs target (e.g. gene) assignment given the spots and the regions.
[ "Performs", "target", "(", "e", ".", "g", ".", "gene", ")", "assignment", "given", "the", "spots", "and", "the", "regions", "." ]
def run( self, masks: BinaryMaskCollection, decoded_intensity_table: DecodedIntensityTable, verbose: bool = False, in_place: bool = False, ) -> DecodedIntensityTable: """Performs target (e.g. gene) assignment given the spots and the regions.""" raise NotImplementedError()
[ "def", "run", "(", "self", ",", "masks", ":", "BinaryMaskCollection", ",", "decoded_intensity_table", ":", "DecodedIntensityTable", ",", "verbose", ":", "bool", "=", "False", ",", "in_place", ":", "bool", "=", "False", ",", ")", "->", "DecodedIntensityTable", ...
https://github.com/spacetx/starfish/blob/0e879d995d5c49b6f5a842e201e3be04c91afc7e/starfish/core/spots/AssignTargets/_base.py#L15-L23
ym2011/ScanBackdoor
3a10de49c3ebd90c2f0eb62304877e00d2a52396
scan.py
python
Version
()
[]
def Version(): print 'scan 0.02 BASE'
[ "def", "Version", "(", ")", ":", "print", "'scan 0.02 BASE'" ]
https://github.com/ym2011/ScanBackdoor/blob/3a10de49c3ebd90c2f0eb62304877e00d2a52396/scan.py#L19-L20
plotly/plotly.py
cfad7862594b35965c0e000813bd7805e8494a5b
packages/python/plotly/plotly/graph_objs/barpolar/marker/colorbar/_title.py
python
Title.side
(self)
return self["side"]
Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". Note that the title's location used to be set by the now deprecated `titleside` attribute. The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['right', 'top', 'bottom'] Returns ------- Any
Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". Note that the title's location used to be set by the now deprecated `titleside` attribute. The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['right', 'top', 'bottom']
[ "Determines", "the", "location", "of", "color", "bar", "s", "title", "with", "respect", "to", "the", "color", "bar", ".", "Defaults", "to", "top", "when", "orientation", "if", "v", "and", "defaults", "to", "right", "when", "orientation", "if", "h", ".", ...
def side(self): """ Determines the location of color bar's title with respect to the color bar. Defaults to "top" when `orientation` if "v" and defaults to "right" when `orientation` if "h". Note that the title's location used to be set by the now deprecated `titleside` attribute. The 'side' property is an enumeration that may be specified as: - One of the following enumeration values: ['right', 'top', 'bottom'] Returns ------- Any """ return self["side"]
[ "def", "side", "(", "self", ")", ":", "return", "self", "[", "\"side\"", "]" ]
https://github.com/plotly/plotly.py/blob/cfad7862594b35965c0e000813bd7805e8494a5b/packages/python/plotly/plotly/graph_objs/barpolar/marker/colorbar/_title.py#L63-L79
maas/maas
db2f89970c640758a51247c59bf1ec6f60cf4ab5
src/provisioningserver/utils/network.py
python
IPRangeStatistics.available_percentage
(self)
return float(self.num_available) / float(self.total_addresses)
Returns the utilization percentage for this set of addresses. :return:float
Returns the utilization percentage for this set of addresses. :return:float
[ "Returns", "the", "utilization", "percentage", "for", "this", "set", "of", "addresses", ".", ":", "return", ":", "float" ]
def available_percentage(self): """Returns the utilization percentage for this set of addresses. :return:float""" return float(self.num_available) / float(self.total_addresses)
[ "def", "available_percentage", "(", "self", ")", ":", "return", "float", "(", "self", ".", "num_available", ")", "/", "float", "(", "self", ".", "total_addresses", ")" ]
https://github.com/maas/maas/blob/db2f89970c640758a51247c59bf1ec6f60cf4ab5/src/provisioningserver/utils/network.py#L332-L335
wucng/TensorExpand
4ea58f64f5c5082b278229b799c9f679536510b7
TensorExpand/Object detection/faster rcnn/CharlesShang-TFFRCNN-master/lib/datasets/nthu.py
python
nthu.image_path_at
(self, i)
return self.image_path_from_index(self.image_index[i])
Return the absolute path to image i in the image sequence.
Return the absolute path to image i in the image sequence.
[ "Return", "the", "absolute", "path", "to", "image", "i", "in", "the", "image", "sequence", "." ]
def image_path_at(self, i): """ Return the absolute path to image i in the image sequence. """ return self.image_path_from_index(self.image_index[i])
[ "def", "image_path_at", "(", "self", ",", "i", ")", ":", "return", "self", ".", "image_path_from_index", "(", "self", ".", "image_index", "[", "i", "]", ")" ]
https://github.com/wucng/TensorExpand/blob/4ea58f64f5c5082b278229b799c9f679536510b7/TensorExpand/Object detection/faster rcnn/CharlesShang-TFFRCNN-master/lib/datasets/nthu.py#L62-L66
ceph/ceph-deploy
a16316fc4dd364135b11226df42d9df65c0c60a2
ceph_deploy/mon.py
python
get_mon_initial_members
(args, error_on_empty=False, _cfg=None)
return mon_initial_members
Read the Ceph config file and return the value of mon_initial_members Optionally, a NeedHostError can be raised if the value is None.
Read the Ceph config file and return the value of mon_initial_members Optionally, a NeedHostError can be raised if the value is None.
[ "Read", "the", "Ceph", "config", "file", "and", "return", "the", "value", "of", "mon_initial_members", "Optionally", "a", "NeedHostError", "can", "be", "raised", "if", "the", "value", "is", "None", "." ]
def get_mon_initial_members(args, error_on_empty=False, _cfg=None): """ Read the Ceph config file and return the value of mon_initial_members Optionally, a NeedHostError can be raised if the value is None. """ if _cfg: cfg = _cfg else: cfg = conf.ceph.load(args) mon_initial_members = cfg.safe_get('global', 'mon_initial_members') if not mon_initial_members: if error_on_empty: raise exc.NeedHostError( 'could not find `mon initial members` defined in ceph.conf' ) else: mon_initial_members = re.split(r'[,\s]+', mon_initial_members) return mon_initial_members
[ "def", "get_mon_initial_members", "(", "args", ",", "error_on_empty", "=", "False", ",", "_cfg", "=", "None", ")", ":", "if", "_cfg", ":", "cfg", "=", "_cfg", "else", ":", "cfg", "=", "conf", ".", "ceph", ".", "load", "(", "args", ")", "mon_initial_mem...
https://github.com/ceph/ceph-deploy/blob/a16316fc4dd364135b11226df42d9df65c0c60a2/ceph_deploy/mon.py#L552-L569
securesystemslab/zippy
ff0e84ac99442c2c55fe1d285332cfd4e185e089
zippy/lib-python/3/modulefinder.py
python
ModuleFinder.replace_paths_in_code
(self, co)
return types.CodeType(co.co_argcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, tuple(consts), co.co_names, co.co_varnames, new_filename, co.co_name, co.co_firstlineno, co.co_lnotab, co.co_freevars, co.co_cellvars)
[]
def replace_paths_in_code(self, co): new_filename = original_filename = os.path.normpath(co.co_filename) for f, r in self.replace_paths: if original_filename.startswith(f): new_filename = r + original_filename[len(f):] break if self.debug and original_filename not in self.processed_paths: if new_filename != original_filename: self.msgout(2, "co_filename %r changed to %r" \ % (original_filename,new_filename,)) else: self.msgout(2, "co_filename %r remains unchanged" \ % (original_filename,)) self.processed_paths.append(original_filename) consts = list(co.co_consts) for i in range(len(consts)): if isinstance(consts[i], type(co)): consts[i] = self.replace_paths_in_code(consts[i]) return types.CodeType(co.co_argcount, co.co_nlocals, co.co_stacksize, co.co_flags, co.co_code, tuple(consts), co.co_names, co.co_varnames, new_filename, co.co_name, co.co_firstlineno, co.co_lnotab, co.co_freevars, co.co_cellvars)
[ "def", "replace_paths_in_code", "(", "self", ",", "co", ")", ":", "new_filename", "=", "original_filename", "=", "os", ".", "path", ".", "normpath", "(", "co", ".", "co_filename", ")", "for", "f", ",", "r", "in", "self", ".", "replace_paths", ":", "if", ...
https://github.com/securesystemslab/zippy/blob/ff0e84ac99442c2c55fe1d285332cfd4e185e089/zippy/lib-python/3/modulefinder.py#L574-L599
CheckPointSW/Karta
b845928487b50a5b41acd532ae0399177a4356aa
src/thumbs_up/utils/switch_table.py
python
SwitchIdentifier.isSwitchCase
(self, ea)
return ea in self._switch_case_cases
Check if the given address is the beginning of a seen switch case. Args: ea (int): effective address to be checked Return Value: True iff the given address matches the beginning of a seen switch case
Check if the given address is the beginning of a seen switch case.
[ "Check", "if", "the", "given", "address", "is", "the", "beginning", "of", "a", "seen", "switch", "case", "." ]
def isSwitchCase(self, ea): """Check if the given address is the beginning of a seen switch case. Args: ea (int): effective address to be checked Return Value: True iff the given address matches the beginning of a seen switch case """ return ea in self._switch_case_cases
[ "def", "isSwitchCase", "(", "self", ",", "ea", ")", ":", "return", "ea", "in", "self", ".", "_switch_case_cases" ]
https://github.com/CheckPointSW/Karta/blob/b845928487b50a5b41acd532ae0399177a4356aa/src/thumbs_up/utils/switch_table.py#L123-L132
sony/nnabla-examples
068be490aacf73740502a1c3b10f8b2d15a52d32
language-modeling/BERT-finetuning/external/processors.py
python
DataProcessor.get_dev_examples
(self, data_dir)
Gets a collection of `InputExample`s for the dev set.
Gets a collection of `InputExample`s for the dev set.
[ "Gets", "a", "collection", "of", "InputExample", "s", "for", "the", "dev", "set", "." ]
def get_dev_examples(self, data_dir): """Gets a collection of `InputExample`s for the dev set.""" raise NotImplementedError()
[ "def", "get_dev_examples", "(", "self", ",", "data_dir", ")", ":", "raise", "NotImplementedError", "(", ")" ]
https://github.com/sony/nnabla-examples/blob/068be490aacf73740502a1c3b10f8b2d15a52d32/language-modeling/BERT-finetuning/external/processors.py#L184-L186