body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1
value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
66d08e7481dfec795c9a20edcc776201fa10b428b2ec26d453755a3dcd027222 | def testMultipleFuncs(self):
'Tests if multiple decorators produce aggregate stats.'
stats.STATS.RegisterCounterMetric('test_multiple_count')
stats.STATS.RegisterEventMetric('test_multiple_timing', bins=[0, 1, 2])
self.Func1(0)
self.Func2(0)
self.assertEqual(stats.STATS.GetMetricValue('test_mult... | Tests if multiple decorators produce aggregate stats. | lib/stats_test.py | testMultipleFuncs | strcrzy/grr | 6 | python | def testMultipleFuncs(self):
stats.STATS.RegisterCounterMetric('test_multiple_count')
stats.STATS.RegisterEventMetric('test_multiple_timing', bins=[0, 1, 2])
self.Func1(0)
self.Func2(0)
self.assertEqual(stats.STATS.GetMetricValue('test_multiple_count'), 2)
self.Func3(0)
self.Func4(1)
... | def testMultipleFuncs(self):
stats.STATS.RegisterCounterMetric('test_multiple_count')
stats.STATS.RegisterEventMetric('test_multiple_timing', bins=[0, 1, 2])
self.Func1(0)
self.Func2(0)
self.assertEqual(stats.STATS.GetMetricValue('test_multiple_count'), 2)
self.Func3(0)
self.Func4(1)
... |
594a5796d70c7d019dd275751f4f5f6e2c8ca30811d7921782cceaa1a88933af | def format_exception(exc_obj: Exception, incl_traceback: bool=False) -> str:
'Takes in an exception object and parses out class, message and traceback (if desired)'
msg = f'{exc_obj.__class__.__name__}: {exc_obj}'
if incl_traceback:
tb = '\n'.join(traceback.format_tb(exc_obj.__traceback__))
... | Takes in an exception object and parses out class, message and traceback (if desired) | kavalkilu/errors.py | format_exception | barretobrock/kavalkilu | 0 | python | def format_exception(exc_obj: Exception, incl_traceback: bool=False) -> str:
msg = f'{exc_obj.__class__.__name__}: {exc_obj}'
if incl_traceback:
tb = '\n'.join(traceback.format_tb(exc_obj.__traceback__))
msg = f'{tb}
{msg}'
return msg | def format_exception(exc_obj: Exception, incl_traceback: bool=False) -> str:
msg = f'{exc_obj.__class__.__name__}: {exc_obj}'
if incl_traceback:
tb = '\n'.join(traceback.format_tb(exc_obj.__traceback__))
msg = f'{tb}
{msg}'
return msg<|docstring|>Takes in an exception object and parses ... |
bed492326808fa337d580d76dbc39bd3d704c12cca503399b5746ceb0c046c69 | @classmethod
def get_iterators(cls, batch_size):
'\n Load dataset and return iterators\n '
grammar_dataset = cls()
grammar_dataset.fields = [('answer', grammar_dataset.answer), ('key', grammar_dataset.key)]
if ((not os.path.exists(PROCESSED_DATASET['train'])) or (not os.path.exists(PROCESS... | Load dataset and return iterators | FITBGenerator/SequenceLabeling/datasetloader.py | get_iterators | shivammehta007/NLPinEnglishLearning | 1 | python | @classmethod
def get_iterators(cls, batch_size):
'\n \n '
grammar_dataset = cls()
grammar_dataset.fields = [('answer', grammar_dataset.answer), ('key', grammar_dataset.key)]
if ((not os.path.exists(PROCESSED_DATASET['train'])) or (not os.path.exists(PROCESSED_DATASET['test']))):
ra... | @classmethod
def get_iterators(cls, batch_size):
'\n \n '
grammar_dataset = cls()
grammar_dataset.fields = [('answer', grammar_dataset.answer), ('key', grammar_dataset.key)]
if ((not os.path.exists(PROCESSED_DATASET['train'])) or (not os.path.exists(PROCESSED_DATASET['test']))):
ra... |
a122f70bb5eb280c49693d71514c642ef44d8029f39db815198a39feb0897d43 | def _check_same_device(device, argument_str, *args):
'Check that all tensor arguments in *args reside on the same device as the input device'
assert isinstance(device, torch.device), '`device` must be a valid `torch.device` object'
for arg in args:
if ((arg is not None) and isinstance(arg, torch.Ten... | Check that all tensor arguments in *args reside on the same device as the input device | orttraining/orttraining/python/training/ortmodule/_utils.py | _check_same_device | asamadiya/onnxruntime | 1 | python | def _check_same_device(device, argument_str, *args):
assert isinstance(device, torch.device), '`device` must be a valid `torch.device` object'
for arg in args:
if ((arg is not None) and isinstance(arg, torch.Tensor)):
arg_device = torch.device(arg.device)
if (arg_device != d... | def _check_same_device(device, argument_str, *args):
assert isinstance(device, torch.device), '`device` must be a valid `torch.device` object'
for arg in args:
if ((arg is not None) and isinstance(arg, torch.Tensor)):
arg_device = torch.device(arg.device)
if (arg_device != d... |
04f967c2dd925023f42ea32bcb07b8eb896377a74833ec9c7b0cb8c434776c78 | def get_device_from_module(module):
"Returns the first device found in the `module`'s parameters or None\n\n Args:\n module (torch.nn.Module): PyTorch model to extract device from\n\n Raises:\n ORTModuleFallbackException: When more than one device is found at `module`\n "
device = None
... | Returns the first device found in the `module`'s parameters or None
Args:
module (torch.nn.Module): PyTorch model to extract device from
Raises:
ORTModuleFallbackException: When more than one device is found at `module` | orttraining/orttraining/python/training/ortmodule/_utils.py | get_device_from_module | asamadiya/onnxruntime | 1 | python | def get_device_from_module(module):
"Returns the first device found in the `module`'s parameters or None\n\n Args:\n module (torch.nn.Module): PyTorch model to extract device from\n\n Raises:\n ORTModuleFallbackException: When more than one device is found at `module`\n "
device = None
... | def get_device_from_module(module):
"Returns the first device found in the `module`'s parameters or None\n\n Args:\n module (torch.nn.Module): PyTorch model to extract device from\n\n Raises:\n ORTModuleFallbackException: When more than one device is found at `module`\n "
device = None
... |
0506442dcc896e21a07e061c4f9da1b4e32965818c9f239d9dd87cd651d4589e | def get_device_from_inputs(args, kwargs):
'Returns device from first PyTorch Tensor within args or kwargs\n\n Args:\n args: List with inputs\n kwargs: Dictionary with inputs\n '
device = None
if args:
device = torch.device(args[0].device)
elif kwargs:
device = torch.d... | Returns device from first PyTorch Tensor within args or kwargs
Args:
args: List with inputs
kwargs: Dictionary with inputs | orttraining/orttraining/python/training/ortmodule/_utils.py | get_device_from_inputs | asamadiya/onnxruntime | 1 | python | def get_device_from_inputs(args, kwargs):
'Returns device from first PyTorch Tensor within args or kwargs\n\n Args:\n args: List with inputs\n kwargs: Dictionary with inputs\n '
device = None
if args:
device = torch.device(args[0].device)
elif kwargs:
device = torch.d... | def get_device_from_inputs(args, kwargs):
'Returns device from first PyTorch Tensor within args or kwargs\n\n Args:\n args: List with inputs\n kwargs: Dictionary with inputs\n '
device = None
if args:
device = torch.device(args[0].device)
elif kwargs:
device = torch.d... |
23260d4de10d32aa85ed3bce07c1ec92a6f6c4bc67c41c3137fc46c52edc5ba4 | def _create_iobinding(io_binding, inputs, model, device):
'Creates IO binding for a `model` inputs and output'
for (idx, value_info) in enumerate(model.graph.input):
io_binding.bind_ortvalue_input(value_info.name, OrtValue(_ortvalue_from_torch_tensor(inputs[idx])))
for value_info in model.graph.outp... | Creates IO binding for a `model` inputs and output | orttraining/orttraining/python/training/ortmodule/_utils.py | _create_iobinding | asamadiya/onnxruntime | 1 | python | def _create_iobinding(io_binding, inputs, model, device):
for (idx, value_info) in enumerate(model.graph.input):
io_binding.bind_ortvalue_input(value_info.name, OrtValue(_ortvalue_from_torch_tensor(inputs[idx])))
for value_info in model.graph.output:
io_binding.bind_output(value_info.name, ... | def _create_iobinding(io_binding, inputs, model, device):
for (idx, value_info) in enumerate(model.graph.input):
io_binding.bind_ortvalue_input(value_info.name, OrtValue(_ortvalue_from_torch_tensor(inputs[idx])))
for value_info in model.graph.output:
io_binding.bind_output(value_info.name, ... |
8a58646e488c647f3b22379df331422e0a1c453dd44725029c92fe051710da52 | def make_html_safe(s):
'Rouge use html, has to make output html safe'
return s.replace('<', '<').replace('>', '>') | Rouge use html, has to make output html safe | models/model_zero/decoding.py | make_html_safe | azagsam/cross-lingual-summarization | 0 | python | def make_html_safe(s):
return s.replace('<', '<').replace('>', '>') | def make_html_safe(s):
return s.replace('<', '<').replace('>', '>')<|docstring|>Rouge use html, has to make output html safe<|endoftext|> |
23ba07c287c95630d887b4ccd161c23664f6aa766012967034f22e0c904ca71d | def load_best_ckpt(model_dir, reverse=False):
' reverse=False->loss, reverse=True->reward/score'
ckpts = os.listdir(join(model_dir, 'ckpt'))
ckpt_matcher = re.compile('^ckpt-.*-[0-9]*')
ckpts = sorted([c for c in ckpts if ckpt_matcher.match(c)], key=(lambda c: float(c.split('-')[1])), reverse=reverse)
... | reverse=False->loss, reverse=True->reward/score | models/model_zero/decoding.py | load_best_ckpt | azagsam/cross-lingual-summarization | 0 | python | def load_best_ckpt(model_dir, reverse=False):
' '
ckpts = os.listdir(join(model_dir, 'ckpt'))
ckpt_matcher = re.compile('^ckpt-.*-[0-9]*')
ckpts = sorted([c for c in ckpts if ckpt_matcher.match(c)], key=(lambda c: float(c.split('-')[1])), reverse=reverse)
print('loading checkpoint {}...'.format(ckpt... | def load_best_ckpt(model_dir, reverse=False):
' '
ckpts = os.listdir(join(model_dir, 'ckpt'))
ckpt_matcher = re.compile('^ckpt-.*-[0-9]*')
ckpts = sorted([c for c in ckpts if ckpt_matcher.match(c)], key=(lambda c: float(c.split('-')[1])), reverse=reverse)
print('loading checkpoint {}...'.format(ckpt... |
ae12d5ba3b731e2d0a6a3e59c94798800a44f4ba894df68ca7ae59a745cdb6e7 | def generate_batch(dataset: DeconvolutionDataset, device: torch.device, dtype: torch.dtype):
'Generate a full training batch\n \n :param dataset: DeconvolutionDataset\n :param device: torch device\n :param dtype: torch dataset\n '
return {'x_mg': dataset.bulk_raw_gex_mg.clone().detach().to(device... | Generate a full training batch
:param dataset: DeconvolutionDataset
:param device: torch device
:param dtype: torch dataset | ternadecov/time_deconv.py | generate_batch | broadinstitute/temporal-rna-seq-deconvolution | 0 | python | def generate_batch(dataset: DeconvolutionDataset, device: torch.device, dtype: torch.dtype):
'Generate a full training batch\n \n :param dataset: DeconvolutionDataset\n :param device: torch device\n :param dtype: torch dataset\n '
return {'x_mg': dataset.bulk_raw_gex_mg.clone().detach().to(device... | def generate_batch(dataset: DeconvolutionDataset, device: torch.device, dtype: torch.dtype):
'Generate a full training batch\n \n :param dataset: DeconvolutionDataset\n :param device: torch device\n :param dtype: torch dataset\n '
return {'x_mg': dataset.bulk_raw_gex_mg.clone().detach().to(device... |
005c76a5e61ff2ce98bd7527bbdd27f8fde2c4f955e4cc7fdb8cc6dc4c9065c1 | def __init__(self, dataset: DeconvolutionDataset, types: DeconvolutionDatatypeParametrization, use_betas: bool=True, trajectory_model_type: str='polynomial', hyperparameters=None, trajectory_hyperparameters=None, **kwargs):
'Initializer for TimeRegularizedDeconvolutionModel\n \n :param self:\n ... | Initializer for TimeRegularizedDeconvolutionModel
:param self:
:param dataset:
:param types:
:param use_betas:
:param trajectory_model_type:
:param hyperparameters:
:param trajectory_hyperparameters:
See below
:Keyword Arguments:
* basis_functions (``str``)--
set of basis functions
* polynomial_degr... | ternadecov/time_deconv.py | __init__ | broadinstitute/temporal-rna-seq-deconvolution | 0 | python | def __init__(self, dataset: DeconvolutionDataset, types: DeconvolutionDatatypeParametrization, use_betas: bool=True, trajectory_model_type: str='polynomial', hyperparameters=None, trajectory_hyperparameters=None, **kwargs):
'Initializer for TimeRegularizedDeconvolutionModel\n \n :param self:\n ... | def __init__(self, dataset: DeconvolutionDataset, types: DeconvolutionDatatypeParametrization, use_betas: bool=True, trajectory_model_type: str='polynomial', hyperparameters=None, trajectory_hyperparameters=None, **kwargs):
'Initializer for TimeRegularizedDeconvolutionModel\n \n :param self:\n ... |
45ad1a246ded23a8d42b50a1712aa1533eb79a8a4afa431f109052dcc1858200 | def model(self, x_mg: torch.Tensor, t_m: torch.Tensor):
'Main model\n\n :param self: instance of Object\n :param x_mg: gene expression\n :param t_m: obseration time\n '
log_phi_g = pyro.sample('log_phi_g', dist.Normal(loc=(self.log_phi_prior_loc * torch.ones((self.dataset.num_genes,)... | Main model
:param self: instance of Object
:param x_mg: gene expression
:param t_m: obseration time | ternadecov/time_deconv.py | model | broadinstitute/temporal-rna-seq-deconvolution | 0 | python | def model(self, x_mg: torch.Tensor, t_m: torch.Tensor):
'Main model\n\n :param self: instance of Object\n :param x_mg: gene expression\n :param t_m: obseration time\n '
log_phi_g = pyro.sample('log_phi_g', dist.Normal(loc=(self.log_phi_prior_loc * torch.ones((self.dataset.num_genes,)... | def model(self, x_mg: torch.Tensor, t_m: torch.Tensor):
'Main model\n\n :param self: instance of Object\n :param x_mg: gene expression\n :param t_m: obseration time\n '
log_phi_g = pyro.sample('log_phi_g', dist.Normal(loc=(self.log_phi_prior_loc * torch.ones((self.dataset.num_genes,)... |
cd1261fd66e4c9b4c4c687ee773b86fa4637dd595f2001b1b0dbbf2d6564444e | def guide(self, x_mg: torch.Tensor, t_m: torch.Tensor):
'Main guide\n \n :param self: instance of object\n :param x_mg: expression matrix\n :param t_m: times\n \n :return: posterior draw\n '
log_phi_posterior_loc_g = pyro.param('log_phi_posterior_loc_g', (self.lo... | Main guide
:param self: instance of object
:param x_mg: expression matrix
:param t_m: times
:return: posterior draw | ternadecov/time_deconv.py | guide | broadinstitute/temporal-rna-seq-deconvolution | 0 | python | def guide(self, x_mg: torch.Tensor, t_m: torch.Tensor):
'Main guide\n \n :param self: instance of object\n :param x_mg: expression matrix\n :param t_m: times\n \n :return: posterior draw\n '
log_phi_posterior_loc_g = pyro.param('log_phi_posterior_loc_g', (self.lo... | def guide(self, x_mg: torch.Tensor, t_m: torch.Tensor):
'Main guide\n \n :param self: instance of object\n :param x_mg: expression matrix\n :param t_m: times\n \n :return: posterior draw\n '
log_phi_posterior_loc_g = pyro.param('log_phi_posterior_loc_g', (self.lo... |
0fdd704ded6ac8453505a2f14e120c46f509f3a3c332e2616b9bc8c2e652f40f | def fit_model(self, n_iters=3000, log_frequency=100, verbose=True, clear_param_store=True, keep_param_store_history=False):
'Iteratively fit the mode\n \n :param self: instance of object\n :param n_inters: number of iterations to execute\n :param log_frequency: log frequncy (in iteration... | Iteratively fit the mode
:param self: instance of object
:param n_inters: number of iterations to execute
:param log_frequency: log frequncy (in iterations)
:param verbose: verbosity flat
:param clear_param_store: flag to clear parameter store before starting iterations
:param keep_param_store_history: flag to keep fu... | ternadecov/time_deconv.py | fit_model | broadinstitute/temporal-rna-seq-deconvolution | 0 | python | def fit_model(self, n_iters=3000, log_frequency=100, verbose=True, clear_param_store=True, keep_param_store_history=False):
'Iteratively fit the mode\n \n :param self: instance of object\n :param n_inters: number of iterations to execute\n :param log_frequency: log frequncy (in iteration... | def fit_model(self, n_iters=3000, log_frequency=100, verbose=True, clear_param_store=True, keep_param_store_history=False):
'Iteratively fit the mode\n \n :param self: instance of object\n :param n_inters: number of iterations to execute\n :param log_frequency: log frequncy (in iteration... |
d3375a638aaff027c84128c58afab6404f8bb65c94ffbb6fcb67323d7a8904ee | def sample_composition_default(self):
'Return the sample composition in a pandas DataFrame\n \n :param self: instance of object\n :return: return the current sample composition in pandas dataframe format\n '
cell_pop_mc = pyro.param('cell_pop_posterior_loc_mc').clone().detach().cpu()... | Return the sample composition in a pandas DataFrame
:param self: instance of object
:return: return the current sample composition in pandas dataframe format | ternadecov/time_deconv.py | sample_composition_default | broadinstitute/temporal-rna-seq-deconvolution | 0 | python | def sample_composition_default(self):
'Return the sample composition in a pandas DataFrame\n \n :param self: instance of object\n :return: return the current sample composition in pandas dataframe format\n '
cell_pop_mc = pyro.param('cell_pop_posterior_loc_mc').clone().detach().cpu()... | def sample_composition_default(self):
'Return the sample composition in a pandas DataFrame\n \n :param self: instance of object\n :return: return the current sample composition in pandas dataframe format\n '
cell_pop_mc = pyro.param('cell_pop_posterior_loc_mc').clone().detach().cpu()... |
d27108f5be03714c304f277e5f23a149f6c78eb559a6885d7d5d2724041f162f | def write_sample_compositions(self, csv_filename, ignore_hypercluster=False):
'Write sample composition to csv file\n \n :param self: instance of object\n :param csv_filename: filename to save the results to\n :param ignore_hypercluster: Flag to ignore hyperclustering if present\n ... | Write sample composition to csv file
:param self: instance of object
:param csv_filename: filename to save the results to
:param ignore_hypercluster: Flag to ignore hyperclustering if present | ternadecov/time_deconv.py | write_sample_compositions | broadinstitute/temporal-rna-seq-deconvolution | 0 | python | def write_sample_compositions(self, csv_filename, ignore_hypercluster=False):
'Write sample composition to csv file\n \n :param self: instance of object\n :param csv_filename: filename to save the results to\n :param ignore_hypercluster: Flag to ignore hyperclustering if present\n ... | def write_sample_compositions(self, csv_filename, ignore_hypercluster=False):
'Write sample composition to csv file\n \n :param self: instance of object\n :param csv_filename: filename to save the results to\n :param ignore_hypercluster: Flag to ignore hyperclustering if present\n ... |
91225616600ef801d0c3bfc7f57583e371a0e4c5c1fd46eb79dfbfba5d40c25a | def write_sample_composition_default(self, csv_filename):
'Write sample composition proportions to csv file\n\n :param self: instance of object\n :param csv_filename: filename of csv file to write to\n '
composition_df = self.sample_composition_default()
composition_df.to_csv(csv_filena... | Write sample composition proportions to csv file
:param self: instance of object
:param csv_filename: filename of csv file to write to | ternadecov/time_deconv.py | write_sample_composition_default | broadinstitute/temporal-rna-seq-deconvolution | 0 | python | def write_sample_composition_default(self, csv_filename):
'Write sample composition proportions to csv file\n\n :param self: instance of object\n :param csv_filename: filename of csv file to write to\n '
composition_df = self.sample_composition_default()
composition_df.to_csv(csv_filena... | def write_sample_composition_default(self, csv_filename):
'Write sample composition proportions to csv file\n\n :param self: instance of object\n :param csv_filename: filename of csv file to write to\n '
composition_df = self.sample_composition_default()
composition_df.to_csv(csv_filena... |
03078b2416908004c20a95a8647e1c4c69216a16c918c3c8a1db2872d7583743 | def save_opti_dictionary(self):
'Save the opti dictionary in a file'
self._loop_over_all_tabs()
total_dictionary = self.optimization_dictionary_obj.get_dictionary()
filename = QtWidgets.QFileDialog.getSaveFileName(self, 'Save config file', os.getcwd(), 'json (*.json)', options=QtWidgets.QFileDialog.Dont... | Save the opti dictionary in a file | src/quocspyside2interface/gui/algorithms/GeneralOptimizationDialog.py | save_opti_dictionary | Quantum-OCS/QuOCS-pyside2interface | 1 | python | def save_opti_dictionary(self):
self._loop_over_all_tabs()
total_dictionary = self.optimization_dictionary_obj.get_dictionary()
filename = QtWidgets.QFileDialog.getSaveFileName(self, 'Save config file', os.getcwd(), 'json (*.json)', options=QtWidgets.QFileDialog.DontUseNativeDialog)
from quocspysid... | def save_opti_dictionary(self):
self._loop_over_all_tabs()
total_dictionary = self.optimization_dictionary_obj.get_dictionary()
filename = QtWidgets.QFileDialog.getSaveFileName(self, 'Save config file', os.getcwd(), 'json (*.json)', options=QtWidgets.QFileDialog.DontUseNativeDialog)
from quocspysid... |
47438f24d3fb0a6c90f853cfe96a4323f4989ff809260afc9685687248c1a688 | def load_opti_dictionary(self):
'Send a signal to the main window with the total dictionary and close the dialog'
self._loop_over_all_tabs()
self.load_full_dictionary_signal.emit(self.optimization_dictionary_obj.get_dictionary())
self.close() | Send a signal to the main window with the total dictionary and close the dialog | src/quocspyside2interface/gui/algorithms/GeneralOptimizationDialog.py | load_opti_dictionary | Quantum-OCS/QuOCS-pyside2interface | 1 | python | def load_opti_dictionary(self):
self._loop_over_all_tabs()
self.load_full_dictionary_signal.emit(self.optimization_dictionary_obj.get_dictionary())
self.close() | def load_opti_dictionary(self):
self._loop_over_all_tabs()
self.load_full_dictionary_signal.emit(self.optimization_dictionary_obj.get_dictionary())
self.close()<|docstring|>Send a signal to the main window with the total dictionary and close the dialog<|endoftext|> |
53e447cd0b22f46a88062a2b2a86694622a899833b642c5c5ebe8ceb75701d8d | def pe30():
'\n >>> pe30()\n 443839\n '
return sum((n for n in range(11, 200000) if (pod(n, 5) == n))) | >>> pe30()
443839 | py/pe/pe30.py | pe30 | kittttttan/pe | 0 | python | def pe30():
'\n >>> pe30()\n 443839\n '
return sum((n for n in range(11, 200000) if (pod(n, 5) == n))) | def pe30():
'\n >>> pe30()\n 443839\n '
return sum((n for n in range(11, 200000) if (pod(n, 5) == n)))<|docstring|>>>> pe30()
443839<|endoftext|> |
3ad57ce67a0042ba67afb5f5463441acf304a0675ce07d37af90c1a8aeee7e4b | def plot_data(data, labels):
'Plot the data and colour by class.\n \n Args:\n data (array[float]): Input data. A list with shape N x 2\n representing points on a 2D plane.\n labels (array[int]): Integers identifying the class/label of \n each data point.\n '
plt.scat... | Plot the data and colour by class.
Args:
data (array[float]): Input data. A list with shape N x 2
representing points on a 2D plane.
labels (array[int]): Integers identifying the class/label of
each data point. | demos/lecture14_helpers.py | plot_data | annabellegrimes/CPEN-400Q | 6 | python | def plot_data(data, labels):
'Plot the data and colour by class.\n \n Args:\n data (array[float]): Input data. A list with shape N x 2\n representing points on a 2D plane.\n labels (array[int]): Integers identifying the class/label of \n each data point.\n '
plt.scat... | def plot_data(data, labels):
'Plot the data and colour by class.\n \n Args:\n data (array[float]): Input data. A list with shape N x 2\n representing points on a 2D plane.\n labels (array[int]): Integers identifying the class/label of \n each data point.\n '
plt.scat... |
96aeaf16d5e82e3c7cc5a6c8c632bc4cdc0292a2a0a1c3366fe6b612336427b7 | def make_predictions(data, model, weights):
'Predict the labels of all points in a data set for a given model.\n \n Args:\n data (array[float]): Input data. A list with shape N x 2\n representing points on a 2D plane.\n model (qml.QNode): A QNode whose output expectation value will be... | Predict the labels of all points in a data set for a given model.
Args:
data (array[float]): Input data. A list with shape N x 2
representing points on a 2D plane.
model (qml.QNode): A QNode whose output expectation value will be
used to make predictions of the labels of data.
weights (arra... | demos/lecture14_helpers.py | make_predictions | annabellegrimes/CPEN-400Q | 6 | python | def make_predictions(data, model, weights):
'Predict the labels of all points in a data set for a given model.\n \n Args:\n data (array[float]): Input data. A list with shape N x 2\n representing points on a 2D plane.\n model (qml.QNode): A QNode whose output expectation value will be... | def make_predictions(data, model, weights):
'Predict the labels of all points in a data set for a given model.\n \n Args:\n data (array[float]): Input data. A list with shape N x 2\n representing points on a 2D plane.\n model (qml.QNode): A QNode whose output expectation value will be... |
a30c876e194150fa1b7c9fee9621c49586f4a0f9d4565a4dc8a6ba5b961a8c03 | def compute_accuracy(predictions, true_labels):
'Compute the accuracy of our predictions.\n \n Args:\n predictions (array[int]): Predicted values to \n true_labels (array[int]): Integers identifying the class/label of \n each data point.\n \n Returns:\n float: Accuracy of... | Compute the accuracy of our predictions.
Args:
predictions (array[int]): Predicted values to
true_labels (array[int]): Integers identifying the class/label of
each data point.
Returns:
float: Accuracy of the predictions, returned as a percentage. | demos/lecture14_helpers.py | compute_accuracy | annabellegrimes/CPEN-400Q | 6 | python | def compute_accuracy(predictions, true_labels):
'Compute the accuracy of our predictions.\n \n Args:\n predictions (array[int]): Predicted values to \n true_labels (array[int]): Integers identifying the class/label of \n each data point.\n \n Returns:\n float: Accuracy of... | def compute_accuracy(predictions, true_labels):
'Compute the accuracy of our predictions.\n \n Args:\n predictions (array[int]): Predicted values to \n true_labels (array[int]): Integers identifying the class/label of \n each data point.\n \n Returns:\n float: Accuracy of... |
060eec239a38795a577304cea59cd29436ebffadc0b53a9c82242328dfadf31c | def get_code(self, obj):
'Returns initial and final code for non-toplevel objects/classes.\n final is mainly used for sizers to call SetSizer(sizer_1) at the end'
return ([], []) | Returns initial and final code for non-toplevel objects/classes.
final is mainly used for sizers to call SetSizer(sizer_1) at the end | wcodegen/__init__.py | get_code | Jalkhov/wxGlade | 225 | python | def get_code(self, obj):
'Returns initial and final code for non-toplevel objects/classes.\n final is mainly used for sizers to call SetSizer(sizer_1) at the end'
return ([], []) | def get_code(self, obj):
'Returns initial and final code for non-toplevel objects/classes.\n final is mainly used for sizers to call SetSizer(sizer_1) at the end'
return ([], [])<|docstring|>Returns initial and final code for non-toplevel objects/classes.
final is mainly used for sizers to call SetSizer(... |
cce944dcea5f8b78386c069d851a0087347dc9c7dbb80d30f803b721762681b1 | def get_properties_code(self, obj):
'Returns a list of strings with the code to set properties etc.\n Called on its own only for toplevel classes.'
return [] | Returns a list of strings with the code to set properties etc.
Called on its own only for toplevel classes. | wcodegen/__init__.py | get_properties_code | Jalkhov/wxGlade | 225 | python | def get_properties_code(self, obj):
'Returns a list of strings with the code to set properties etc.\n Called on its own only for toplevel classes.'
return [] | def get_properties_code(self, obj):
'Returns a list of strings with the code to set properties etc.\n Called on its own only for toplevel classes.'
return []<|docstring|>Returns a list of strings with the code to set properties etc.
Called on its own only for toplevel classes.<|endoftext|> |
77c7c9963e561a176a410e19cdd518526a621da2dbddccc68a6fa44417e4e737 | def get_init_code(self, obj):
'Called on its own only for toplevel objects/classes.'
return [] | Called on its own only for toplevel objects/classes. | wcodegen/__init__.py | get_init_code | Jalkhov/wxGlade | 225 | python | def get_init_code(self, obj):
return [] | def get_init_code(self, obj):
return []<|docstring|>Called on its own only for toplevel objects/classes.<|endoftext|> |
6cbe1ebcc99e0357cf984e30fc4c0e94104fb95773ffcce3ddbdfe53710bd134 | def get_layout_code(self, obj):
'Returns code for the final code of toplevel objects (classes).'
return [] | Returns code for the final code of toplevel objects (classes). | wcodegen/__init__.py | get_layout_code | Jalkhov/wxGlade | 225 | python | def get_layout_code(self, obj):
return [] | def get_layout_code(self, obj):
return []<|docstring|>Returns code for the final code of toplevel objects (classes).<|endoftext|> |
0e5b6606b3a55edee52449984ecf22233039e3cb8dd18dadb416c89ef58c4f72 | def get_code_per_child(self, obj, child):
"Returns code that will be inserted after the child code; e.g. for adding element to a sizer.\n It's placed before the final code returned from get_code()."
return [] | Returns code that will be inserted after the child code; e.g. for adding element to a sizer.
It's placed before the final code returned from get_code(). | wcodegen/__init__.py | get_code_per_child | Jalkhov/wxGlade | 225 | python | def get_code_per_child(self, obj, child):
"Returns code that will be inserted after the child code; e.g. for adding element to a sizer.\n It's placed before the final code returned from get_code()."
return [] | def get_code_per_child(self, obj, child):
"Returns code that will be inserted after the child code; e.g. for adding element to a sizer.\n It's placed before the final code returned from get_code()."
return []<|docstring|>Returns code that will be inserted after the child code; e.g. for adding element to ... |
c6100661055965024f373c6870bd272483ed4242f10bb0fe3601d17094be0b30 | def cn(self, name):
'Return the properly formatted name; see: cn_f(), cn_class()'
return name | Return the properly formatted name; see: cn_f(), cn_class() | wcodegen/__init__.py | cn | Jalkhov/wxGlade | 225 | python | def cn(self, name):
return name | def cn(self, name):
return name<|docstring|>Return the properly formatted name; see: cn_f(), cn_class()<|endoftext|> |
db74ecccd8f931eec99e0207e5ae5cd6bb059f5ac38a10d6f98852b07b252a28 | def cn_class(self, klass):
'Return the properly formatted class name; see cn()'
return klass | Return the properly formatted class name; see cn() | wcodegen/__init__.py | cn_class | Jalkhov/wxGlade | 225 | python | def cn_class(self, klass):
return klass | def cn_class(self, klass):
return klass<|docstring|>Return the properly formatted class name; see cn()<|endoftext|> |
cf1d8b7a3379f86f38f248fdc40e8681c386094289ec5406aaf01ff5c26dcd55 | def get_class(self, scope):
"Return the last element of the given scope; see: get_scope(), scope_sep\n\n Example::\n >>> self.get_class('ui.AboutDialog')\n 'ui.AboutDialog'\n "
if self.scope_sep:
scope_list = scope.rsplit(self.scope_sep, 1)
if (len(scope_list... | Return the last element of the given scope; see: get_scope(), scope_sep
Example::
>>> self.get_class('ui.AboutDialog')
'ui.AboutDialog' | wcodegen/__init__.py | get_class | Jalkhov/wxGlade | 225 | python | def get_class(self, scope):
"Return the last element of the given scope; see: get_scope(), scope_sep\n\n Example::\n >>> self.get_class('ui.AboutDialog')\n 'ui.AboutDialog'\n "
if self.scope_sep:
scope_list = scope.rsplit(self.scope_sep, 1)
if (len(scope_list... | def get_class(self, scope):
"Return the last element of the given scope; see: get_scope(), scope_sep\n\n Example::\n >>> self.get_class('ui.AboutDialog')\n 'ui.AboutDialog'\n "
if self.scope_sep:
scope_list = scope.rsplit(self.scope_sep, 1)
if (len(scope_list... |
91b9e167c0f7de9bce28ea9de452548c73b771c3aa060eca84d80d0f474e4ccf | def get_scope(self, scope):
"Return the scope without the last element; see: get_class(), scope_sep\n\n Example::\n >>> self.get_scope('ui.AboutDialog')\n 'ui'\n >>> self.get_scope('uiAboutDialog')\n ''\n "
if self.scope_sep:
scope_list = scope.... | Return the scope without the last element; see: get_class(), scope_sep
Example::
>>> self.get_scope('ui.AboutDialog')
'ui'
>>> self.get_scope('uiAboutDialog')
'' | wcodegen/__init__.py | get_scope | Jalkhov/wxGlade | 225 | python | def get_scope(self, scope):
"Return the scope without the last element; see: get_class(), scope_sep\n\n Example::\n >>> self.get_scope('ui.AboutDialog')\n 'ui'\n >>> self.get_scope('uiAboutDialog')\n \n "
if self.scope_sep:
scope_list = scope.rs... | def get_scope(self, scope):
"Return the scope without the last element; see: get_class(), scope_sep\n\n Example::\n >>> self.get_scope('ui.AboutDialog')\n 'ui'\n >>> self.get_scope('uiAboutDialog')\n \n "
if self.scope_sep:
scope_list = scope.rs... |
71f5f6f350c1c558e46df8af4e3a51220f0d5cb7e1438d364b83944adefc7357 | def _get_style_list(self):
'Return a list of all styles supported by this widget'
try:
groups = self.config['style_list']
except (AttributeError, KeyError):
groups = []
return groups | Return a list of all styles supported by this widget | wcodegen/__init__.py | _get_style_list | Jalkhov/wxGlade | 225 | python | def _get_style_list(self):
try:
groups = self.config['style_list']
except (AttributeError, KeyError):
groups = []
return groups | def _get_style_list(self):
try:
groups = self.config['style_list']
except (AttributeError, KeyError):
groups = []
return groups<|docstring|>Return a list of all styles supported by this widget<|endoftext|> |
43ee552dca6649b0c566c1f152e6b06ff5ffe7ae77fd49649d5ec2e794634ec2 | def cn(self, name):
'Return the name properly formatted; see: self._perl_constant_list'
if (name.startswith('wxBITMAP_TYPE_') or name.startswith('wxDefault') or name.startswith('wxSYS_COLOUR_')):
return name
if ('_' in name):
start = name.split('_', 1)[0]
if (start in {'wxART', 'wxBO... | Return the name properly formatted; see: self._perl_constant_list | wcodegen/__init__.py | cn | Jalkhov/wxGlade | 225 | python | def cn(self, name):
if (name.startswith('wxBITMAP_TYPE_') or name.startswith('wxDefault') or name.startswith('wxSYS_COLOUR_')):
return name
if ('_' in name):
start = name.split('_', 1)[0]
if (start in {'wxART', 'wxBORDER', 'wxBRUSHSTYLE', 'wxBU', 'wxCB', 'wxCC', 'wxCHB', 'wxCHK', 'w... | def cn(self, name):
if (name.startswith('wxBITMAP_TYPE_') or name.startswith('wxDefault') or name.startswith('wxSYS_COLOUR_')):
return name
if ('_' in name):
start = name.split('_', 1)[0]
if (start in {'wxART', 'wxBORDER', 'wxBRUSHSTYLE', 'wxBU', 'wxCB', 'wxCC', 'wxCHB', 'wxCHK', 'w... |
c8f5536c85fdfc9c71c0a460ac304dd801e000d92cdb58b52c1f476d45d69ff9 | def stmt2list(self, stmt):
"Split a code statement into a list by conserving tailing newlines\n e.g. tmpl2list('line 1\\nline 2\\nline 3\\n') -> ['line 1\\n', 'line 2\\n', 'line 3\\n', '\\n']"
temp = [('%s\n' % line) for line in stmt.split('\n')]
return temp | Split a code statement into a list by conserving tailing newlines
e.g. tmpl2list('line 1\nline 2\nline 3\n') -> ['line 1\n', 'line 2\n', 'line 3\n', '\n'] | wcodegen/__init__.py | stmt2list | Jalkhov/wxGlade | 225 | python | def stmt2list(self, stmt):
"Split a code statement into a list by conserving tailing newlines\n e.g. tmpl2list('line 1\\nline 2\\nline 3\\n') -> ['line 1\\n', 'line 2\\n', 'line 3\\n', '\\n']"
temp = [('%s\n' % line) for line in stmt.split('\n')]
return temp | def stmt2list(self, stmt):
"Split a code statement into a list by conserving tailing newlines\n e.g. tmpl2list('line 1\\nline 2\\nline 3\\n') -> ['line 1\\n', 'line 2\\n', 'line 3\\n', '\\n']"
temp = [('%s\n' % line) for line in stmt.split('\n')]
return temp<|docstring|>Split a code statement into a ... |
2b256b1dfe638059e462a4d132b2f8f8230ff8b362f0122b88251173d848bf00 | def _reset_vars(self):
'Reset instance variables back to defaults'
self.import_modules = self.__import_modules[:]
self.has_selection = False
self.has_setdefault = False
self.has_setvalue = False
self.has_setvalue1 = False
self.tmpl_before = []
self.tmpl_after = []
self.tmpl_layout = ... | Reset instance variables back to defaults | wcodegen/__init__.py | _reset_vars | Jalkhov/wxGlade | 225 | python | def _reset_vars(self):
self.import_modules = self.__import_modules[:]
self.has_selection = False
self.has_setdefault = False
self.has_setvalue = False
self.has_setvalue1 = False
self.tmpl_before = []
self.tmpl_after = []
self.tmpl_layout = []
self.tmpl_props = []
self.tmpl_d... | def _reset_vars(self):
self.import_modules = self.__import_modules[:]
self.has_selection = False
self.has_setdefault = False
self.has_setvalue = False
self.has_setvalue1 = False
self.tmpl_before = []
self.tmpl_after = []
self.tmpl_layout = []
self.tmpl_props = []
self.tmpl_d... |
8015aed80ff43b0e6164de7610c1e74aa6dd0f6562efc25b3ef21ca1091193e5 | def _prepare_style(self, style):
'Process and format style string with cn_f(); returns string; see _prepare_tmpl_content(), tmpl_flags'
style_s = style.get_string_value()
fmt_style = self.cn_f(style_s)
fmt_default_style = self.cn_f(self.default_style)
if (fmt_style and (fmt_style != fmt_default_styl... | Process and format style string with cn_f(); returns string; see _prepare_tmpl_content(), tmpl_flags | wcodegen/__init__.py | _prepare_style | Jalkhov/wxGlade | 225 | python | def _prepare_style(self, style):
style_s = style.get_string_value()
fmt_style = self.cn_f(style_s)
fmt_default_style = self.cn_f(self.default_style)
if (fmt_style and (fmt_style != fmt_default_style)):
style = (self.tmpl_flags % fmt_style)
elif ((not style_s) and fmt_default_style):
... | def _prepare_style(self, style):
style_s = style.get_string_value()
fmt_style = self.cn_f(style_s)
fmt_default_style = self.cn_f(self.default_style)
if (fmt_style and (fmt_style != fmt_default_style)):
style = (self.tmpl_flags % fmt_style)
elif ((not style_s) and fmt_default_style):
... |
f31b00e6f84ab070712b18571c0655d4ed16ac4e9c0bb043a69adb83705fc3e7 | def _prepare_tmpl_content(self, obj):
'Prepare and set template variables; obj is instance of xml_parse.CodeObject; returns dict'
self.tmpl_dict['comment'] = self.codegen.comment_sign
self.tmpl_dict['tab'] = self.codegen.tabs(1)
self.tmpl_dict['store_as_attr'] = self.codegen.store_as_attr(obj)
(self... | Prepare and set template variables; obj is instance of xml_parse.CodeObject; returns dict | wcodegen/__init__.py | _prepare_tmpl_content | Jalkhov/wxGlade | 225 | python | def _prepare_tmpl_content(self, obj):
self.tmpl_dict['comment'] = self.codegen.comment_sign
self.tmpl_dict['tab'] = self.codegen.tabs(1)
self.tmpl_dict['store_as_attr'] = self.codegen.store_as_attr(obj)
(self.tmpl_dict['id_name'], self.tmpl_dict['id_number']) = self.codegen.generate_code_id(obj)
... | def _prepare_tmpl_content(self, obj):
self.tmpl_dict['comment'] = self.codegen.comment_sign
self.tmpl_dict['tab'] = self.codegen.tabs(1)
self.tmpl_dict['store_as_attr'] = self.codegen.store_as_attr(obj)
(self.tmpl_dict['id_name'], self.tmpl_dict['id_number']) = self.codegen.generate_code_id(obj)
... |
ce92effca3a3cbac70f6525f8318bf2f0908b6397fd66004d93fed6ba5c1859f | def _get_default_style(self):
'Default widget style in wxWidget notation; see set_default_style, prefix_style'
try:
name = self.config['default_style']
except (AttributeError, KeyError):
name = ''
return name | Default widget style in wxWidget notation; see set_default_style, prefix_style | wcodegen/__init__.py | _get_default_style | Jalkhov/wxGlade | 225 | python | def _get_default_style(self):
try:
name = self.config['default_style']
except (AttributeError, KeyError):
name =
return name | def _get_default_style(self):
try:
name = self.config['default_style']
except (AttributeError, KeyError):
name =
return name<|docstring|>Default widget style in wxWidget notation; see set_default_style, prefix_style<|endoftext|> |
b874fc941ed64db9e3d420fad5b8b017566c08f2d89a8e352d746ba0d8c93d53 | def _prepare_bitmaps(self, obj):
'Prepare content for widgets with bitmaps'
need_artprovider = have_constructor_argument = False
for p_name in obj.property_names:
p = obj.properties[p_name]
if (not isinstance(p, np.BitmapProperty)):
continue
value = p.get_value()
... | Prepare content for widgets with bitmaps | wcodegen/__init__.py | _prepare_bitmaps | Jalkhov/wxGlade | 225 | python | def _prepare_bitmaps(self, obj):
need_artprovider = have_constructor_argument = False
for p_name in obj.property_names:
p = obj.properties[p_name]
if (not isinstance(p, np.BitmapProperty)):
continue
value = p.get_value()
if value.startswith('art:'):
n... | def _prepare_bitmaps(self, obj):
need_artprovider = have_constructor_argument = False
for p_name in obj.property_names:
p = obj.properties[p_name]
if (not isinstance(p, np.BitmapProperty)):
continue
value = p.get_value()
if value.startswith('art:'):
n... |
94247dd452541d22c1e7549100284000db48defb9ab67659c6073c1b24220fb2 | def _prepare_choice(self, obj):
"Prepare content for widgets with choices; see: get_code(), tmpl_concatenate_choices\n\n The content of choices will be generated automatically if the\n template in self.tmpl contains '%(choices)s' or '%(choices_len)s'\n\n obj: Instance of xml_parse.CodeObject"
... | Prepare content for widgets with choices; see: get_code(), tmpl_concatenate_choices
The content of choices will be generated automatically if the
template in self.tmpl contains '%(choices)s' or '%(choices_len)s'
obj: Instance of xml_parse.CodeObject | wcodegen/__init__.py | _prepare_choice | Jalkhov/wxGlade | 225 | python | def _prepare_choice(self, obj):
"Prepare content for widgets with choices; see: get_code(), tmpl_concatenate_choices\n\n The content of choices will be generated automatically if the\n template in self.tmpl contains '%(choices)s' or '%(choices_len)s'\n\n obj: Instance of xml_parse.CodeObject"
... | def _prepare_choice(self, obj):
"Prepare content for widgets with choices; see: get_code(), tmpl_concatenate_choices\n\n The content of choices will be generated automatically if the\n template in self.tmpl contains '%(choices)s' or '%(choices_len)s'\n\n obj: Instance of xml_parse.CodeObject"
... |
d1b336954fbaac66049bf6b656c56d176bca1d40f6bfa6c342d0770cbf299b87 | def generate_code_bitmap(self, bitmap, required=False):
'Returns a code fragment that generates an wxBitmap object\n\n bitmap: Bitmap definition string\n\n see: tmpl_inline_bitmap, get_inline_stmt_emptybitmap(), get_inline_stmt_artprovider()'
assert self.tmpl_inline_bitmap
if ((not bitmap) and... | Returns a code fragment that generates an wxBitmap object
bitmap: Bitmap definition string
see: tmpl_inline_bitmap, get_inline_stmt_emptybitmap(), get_inline_stmt_artprovider() | wcodegen/__init__.py | generate_code_bitmap | Jalkhov/wxGlade | 225 | python | def generate_code_bitmap(self, bitmap, required=False):
'Returns a code fragment that generates an wxBitmap object\n\n bitmap: Bitmap definition string\n\n see: tmpl_inline_bitmap, get_inline_stmt_emptybitmap(), get_inline_stmt_artprovider()'
assert self.tmpl_inline_bitmap
if ((not bitmap) and... | def generate_code_bitmap(self, bitmap, required=False):
'Returns a code fragment that generates an wxBitmap object\n\n bitmap: Bitmap definition string\n\n see: tmpl_inline_bitmap, get_inline_stmt_emptybitmap(), get_inline_stmt_artprovider()'
assert self.tmpl_inline_bitmap
if ((not bitmap) and... |
96cdcd490c560355ad45be9c71a288c064d5792d2be6b9518f04a8cda5e15e6c | def get_code(self, obj):
'Generates language specific code for the wxWidget object from a template by filling variables\n generated by _prepare_tmpl_content().'
assert (self.tmpl or (obj.klass in ('spacer', 'sizerslot')))
lines = []
self._reset_vars()
self._prepare_tmpl_content(obj)
if ((... | Generates language specific code for the wxWidget object from a template by filling variables
generated by _prepare_tmpl_content(). | wcodegen/__init__.py | get_code | Jalkhov/wxGlade | 225 | python | def get_code(self, obj):
'Generates language specific code for the wxWidget object from a template by filling variables\n generated by _prepare_tmpl_content().'
assert (self.tmpl or (obj.klass in ('spacer', 'sizerslot')))
lines = []
self._reset_vars()
self._prepare_tmpl_content(obj)
if ((... | def get_code(self, obj):
'Generates language specific code for the wxWidget object from a template by filling variables\n generated by _prepare_tmpl_content().'
assert (self.tmpl or (obj.klass in ('spacer', 'sizerslot')))
lines = []
self._reset_vars()
self._prepare_tmpl_content(obj)
if ((... |
31bcb25a60bff4dfc87b0735e79bf74500a665267d5480b5b77f8791c5d451bb | def get_event_handlers(self, obj):
"Returns a list of event handlers defined for the given object (CodeObject instance).\n\n Each list entry has following items: (ID, Event, Handler, Event prototype)\n\n B{Example}::\n >>> self.get_event_handlers(obj)\n [('wxID_OPEN', 'EVT_MENU',... | Returns a list of event handlers defined for the given object (CodeObject instance).
Each list entry has following items: (ID, Event, Handler, Event prototype)
B{Example}::
>>> self.get_event_handlers(obj)
[('wxID_OPEN', 'EVT_MENU', 'OnOpen', 'wxCommandEvent'),
('wxID_EXIT', 'EVT_MENU', 'OnClose', 'wxCom... | wcodegen/__init__.py | get_event_handlers | Jalkhov/wxGlade | 225 | python | def get_event_handlers(self, obj):
"Returns a list of event handlers defined for the given object (CodeObject instance).\n\n Each list entry has following items: (ID, Event, Handler, Event prototype)\n\n B{Example}::\n >>> self.get_event_handlers(obj)\n [('wxID_OPEN', 'EVT_MENU',... | def get_event_handlers(self, obj):
"Returns a list of event handlers defined for the given object (CodeObject instance).\n\n Each list entry has following items: (ID, Event, Handler, Event prototype)\n\n B{Example}::\n >>> self.get_event_handlers(obj)\n [('wxID_OPEN', 'EVT_MENU',... |
257492792ee0214529c4b7e0b43e63201ecd073d8bb0e864074999a788406146 | def get_properties_code(self, obj):
'Generates language specific code to set properties for the wxWidget object from a template\n by filling variables generated by _prepare_tmpl_content(); returns list of strings; see tmpl_props'
prop_lines = []
self._reset_vars()
self._prepare_tmpl_content(obj)
... | Generates language specific code to set properties for the wxWidget object from a template
by filling variables generated by _prepare_tmpl_content(); returns list of strings; see tmpl_props | wcodegen/__init__.py | get_properties_code | Jalkhov/wxGlade | 225 | python | def get_properties_code(self, obj):
'Generates language specific code to set properties for the wxWidget object from a template\n by filling variables generated by _prepare_tmpl_content(); returns list of strings; see tmpl_props'
prop_lines = []
self._reset_vars()
self._prepare_tmpl_content(obj)
... | def get_properties_code(self, obj):
'Generates language specific code to set properties for the wxWidget object from a template\n by filling variables generated by _prepare_tmpl_content(); returns list of strings; see tmpl_props'
prop_lines = []
self._reset_vars()
self._prepare_tmpl_content(obj)
... |
c13707ea3bb1832c93865848632b2348702e7629f4327fc7d5132134bd28084c | def get_layout_code(self, obj):
'Generates language specific code to create the layout for the wxWidget object from a template\n by filling variables generated by _prepare_tmpl_content(); returns list of strings; see tmpl_props'
layout_lines = []
self._reset_vars()
self._prepare_tmpl_content(obj)... | Generates language specific code to create the layout for the wxWidget object from a template
by filling variables generated by _prepare_tmpl_content(); returns list of strings; see tmpl_props | wcodegen/__init__.py | get_layout_code | Jalkhov/wxGlade | 225 | python | def get_layout_code(self, obj):
'Generates language specific code to create the layout for the wxWidget object from a template\n by filling variables generated by _prepare_tmpl_content(); returns list of strings; see tmpl_props'
layout_lines = []
self._reset_vars()
self._prepare_tmpl_content(obj)... | def get_layout_code(self, obj):
'Generates language specific code to create the layout for the wxWidget object from a template\n by filling variables generated by _prepare_tmpl_content(); returns list of strings; see tmpl_props'
layout_lines = []
self._reset_vars()
self._prepare_tmpl_content(obj)... |
ef38ae4f07e13d02e22bb57aa414b11f3e31e5714598c03788ecfc8c861c2de1 | def get_inline_stmt_artprovider(self, bitmap):
"Return a inline statement of a bitmap from the given statement using wxArtProvider.\n See generate_code_bitmap().\n\n bitmap: Bitmap definition (string)\n\n B{Syntax}::\n art:<ArtID>,<ArtClient>\n art:<ArtID>,<ArtClient>,<wid... | Return a inline statement of a bitmap from the given statement using wxArtProvider.
See generate_code_bitmap().
bitmap: Bitmap definition (string)
B{Syntax}::
art:<ArtID>,<ArtClient>
art:<ArtID>,<ArtClient>,<width>,<height>
B{Example}::
>>> get_inline_stmt_artprovider('art:wxART_HELP,wxART_OTHER,32,32')
... | wcodegen/__init__.py | get_inline_stmt_artprovider | Jalkhov/wxGlade | 225 | python | def get_inline_stmt_artprovider(self, bitmap):
"Return a inline statement of a bitmap from the given statement using wxArtProvider.\n See generate_code_bitmap().\n\n bitmap: Bitmap definition (string)\n\n B{Syntax}::\n art:<ArtID>,<ArtClient>\n art:<ArtID>,<ArtClient>,<wid... | def get_inline_stmt_artprovider(self, bitmap):
"Return a inline statement of a bitmap from the given statement using wxArtProvider.\n See generate_code_bitmap().\n\n bitmap: Bitmap definition (string)\n\n B{Syntax}::\n art:<ArtID>,<ArtClient>\n art:<ArtID>,<ArtClient>,<wid... |
a60a5599a9bcf64b1bc2696f05f3b78638c24f1f0149d6568e848b39d0babdf0 | def get_inline_stmt_emptybitmap(self, bitmap):
"Return a inline statement to create an empty wxBitmap. See generate_code_bitmap().\n\n bitmap: Bitmap definition (string)\n\n B{Syntax}::\n empty:<width>,<height>\n\n B{Example}::\n >>> get_inline_stmt_emptybitmap('empty:32,3... | Return a inline statement to create an empty wxBitmap. See generate_code_bitmap().
bitmap: Bitmap definition (string)
B{Syntax}::
empty:<width>,<height>
B{Example}::
>>> get_inline_stmt_emptybitmap('empty:32,32')
'wx.EmptyBitmap(32, 32)' | wcodegen/__init__.py | get_inline_stmt_emptybitmap | Jalkhov/wxGlade | 225 | python | def get_inline_stmt_emptybitmap(self, bitmap):
"Return a inline statement to create an empty wxBitmap. See generate_code_bitmap().\n\n bitmap: Bitmap definition (string)\n\n B{Syntax}::\n empty:<width>,<height>\n\n B{Example}::\n >>> get_inline_stmt_emptybitmap('empty:32,3... | def get_inline_stmt_emptybitmap(self, bitmap):
"Return a inline statement to create an empty wxBitmap. See generate_code_bitmap().\n\n bitmap: Bitmap definition (string)\n\n B{Syntax}::\n empty:<width>,<height>\n\n B{Example}::\n >>> get_inline_stmt_emptybitmap('empty:32,3... |
d5683902f02b1dd5f42a195eb365ffafe5f86a817402224b4757a20681cfdf94 | def get_inline_stmt_wxSize(self, width, heigh):
"Returns a inline statement to specific the widget size with wxSize()\n\n B{Example}::\n >>> get_inline_stmt_wxSize(16, 16)\n '(16, 16)' # Python\n\n >>> get_inline_stmt_wxSize(16, 16)\n 'wxSize(16, 1... | Returns a inline statement to specific the widget size with wxSize()
B{Example}::
>>> get_inline_stmt_wxSize(16, 16)
'(16, 16)' # Python
>>> get_inline_stmt_wxSize(16, 16)
'wxSize(16, 16)' # C++ | wcodegen/__init__.py | get_inline_stmt_wxSize | Jalkhov/wxGlade | 225 | python | def get_inline_stmt_wxSize(self, width, heigh):
"Returns a inline statement to specific the widget size with wxSize()\n\n B{Example}::\n >>> get_inline_stmt_wxSize(16, 16)\n '(16, 16)' # Python\n\n >>> get_inline_stmt_wxSize(16, 16)\n 'wxSize(16, 1... | def get_inline_stmt_wxSize(self, width, heigh):
"Returns a inline statement to specific the widget size with wxSize()\n\n B{Example}::\n >>> get_inline_stmt_wxSize(16, 16)\n '(16, 16)' # Python\n\n >>> get_inline_stmt_wxSize(16, 16)\n 'wxSize(16, 1... |
a1c9ec94148e8ce7cf6fd2bedba50fcca1a8fafb6bbbb874cd85ba5a43a563a4 | def is_widget_supported(self, major, minor=None):
'Check if the widget is supported for the given version; see config.widget_config\n major, minor: Major and minor version number (int)'
assert isinstance(major, int)
assert (isinstance(minor, int) or (minor is None))
if ('supported_by' not in self... | Check if the widget is supported for the given version; see config.widget_config
major, minor: Major and minor version number (int) | wcodegen/__init__.py | is_widget_supported | Jalkhov/wxGlade | 225 | python | def is_widget_supported(self, major, minor=None):
'Check if the widget is supported for the given version; see config.widget_config\n major, minor: Major and minor version number (int)'
assert isinstance(major, int)
assert (isinstance(minor, int) or (minor is None))
if ('supported_by' not in self... | def is_widget_supported(self, major, minor=None):
'Check if the widget is supported for the given version; see config.widget_config\n major, minor: Major and minor version number (int)'
assert isinstance(major, int)
assert (isinstance(minor, int) or (minor is None))
if ('supported_by' not in self... |
bcb0cd98eaae4a8fcf4c44e6a35278b68aea257af0d78e557226161452bdbee5 | def __init__(self, file_path):
'Initialize a new instance of raspy.io.file_info.FileInfo.\n\n Initializes a new instance of the FileInfo class with the\n fully-qualified or relative name of the file.\n\n :param str file_path: The fully-qualified name of the of the file,\n or the relative... | Initialize a new instance of raspy.io.file_info.FileInfo.
Initializes a new instance of the FileInfo class with the
fully-qualified or relative name of the file.
:param str file_path: The fully-qualified name of the of the file,
or the relative file name.
:raises: raspy.argument_null_exception.ArgumentNullException i... | raspy/io/file_info.py | __init__ | cyrusbuilt/RasPy | 0 | python | def __init__(self, file_path):
'Initialize a new instance of raspy.io.file_info.FileInfo.\n\n Initializes a new instance of the FileInfo class with the\n fully-qualified or relative name of the file.\n\n :param str file_path: The fully-qualified name of the of the file,\n or the relative... | def __init__(self, file_path):
'Initialize a new instance of raspy.io.file_info.FileInfo.\n\n Initializes a new instance of the FileInfo class with the\n fully-qualified or relative name of the file.\n\n :param str file_path: The fully-qualified name of the of the file,\n or the relative... |
110d8c20b2d0425e30ea9d20eb20fcaff925339a62ea2a75d072d4085cd016e2 | def __str__(self):
'Return the path as a string.\n\n :returns: A string representing the path.\n :rtype: str\n '
return self.__originalPath | Return the path as a string.
:returns: A string representing the path.
:rtype: str | raspy/io/file_info.py | __str__ | cyrusbuilt/RasPy | 0 | python | def __str__(self):
'Return the path as a string.\n\n :returns: A string representing the path.\n :rtype: str\n '
return self.__originalPath | def __str__(self):
'Return the path as a string.\n\n :returns: A string representing the path.\n :rtype: str\n '
return self.__originalPath<|docstring|>Return the path as a string.
:returns: A string representing the path.
:rtype: str<|endoftext|> |
4dc140bdce1e3b5eaadeed104fab3a2820401a6ca56507fa856885b7cd410b29 | def exists(self):
'Check to see if this file exists.\n\n :returns: True if exists; Otherwise, false.\n :rtype: bool\n '
return os.path.exists(self.__fullPath) | Check to see if this file exists.
:returns: True if exists; Otherwise, false.
:rtype: bool | raspy/io/file_info.py | exists | cyrusbuilt/RasPy | 0 | python | def exists(self):
'Check to see if this file exists.\n\n :returns: True if exists; Otherwise, false.\n :rtype: bool\n '
return os.path.exists(self.__fullPath) | def exists(self):
'Check to see if this file exists.\n\n :returns: True if exists; Otherwise, false.\n :rtype: bool\n '
return os.path.exists(self.__fullPath)<|docstring|>Check to see if this file exists.
:returns: True if exists; Otherwise, false.
:rtype: bool<|endoftext|> |
f3cd56fe975714b93095cc1140544e24112f7bad56b7225559ee3a146a0e5eb7 | def get_directory_name(self):
'Get the directory name (path) the file is in.\n\n :returns: The directory component of the full file path.\n :rtype: str\n '
(head, tail) = os.path.split(self.__fullPath)
return head | Get the directory name (path) the file is in.
:returns: The directory component of the full file path.
:rtype: str | raspy/io/file_info.py | get_directory_name | cyrusbuilt/RasPy | 0 | python | def get_directory_name(self):
'Get the directory name (path) the file is in.\n\n :returns: The directory component of the full file path.\n :rtype: str\n '
(head, tail) = os.path.split(self.__fullPath)
return head | def get_directory_name(self):
'Get the directory name (path) the file is in.\n\n :returns: The directory component of the full file path.\n :rtype: str\n '
(head, tail) = os.path.split(self.__fullPath)
return head<|docstring|>Get the directory name (path) the file is in.
:returns: The ... |
9e0f7d3b9aabe4590c078195d3006d415880cd27fd25425f4908c2a7069c79cd | def get_file_name(self):
'Get the file name.\n\n :returns: The file name component of the full file path.\n :rtype: str\n '
(head, tail) = os.path.split(self.__fullPath)
return tail | Get the file name.
:returns: The file name component of the full file path.
:rtype: str | raspy/io/file_info.py | get_file_name | cyrusbuilt/RasPy | 0 | python | def get_file_name(self):
'Get the file name.\n\n :returns: The file name component of the full file path.\n :rtype: str\n '
(head, tail) = os.path.split(self.__fullPath)
return tail | def get_file_name(self):
'Get the file name.\n\n :returns: The file name component of the full file path.\n :rtype: str\n '
(head, tail) = os.path.split(self.__fullPath)
return tail<|docstring|>Get the file name.
:returns: The file name component of the full file path.
:rtype: str<|end... |
2f29b5b8317e1f90152dc6df9f1ae456681186f2d770400203113076718731e6 | def get_file_extension(self):
'Get the file extension name.\n\n :returns: The file extension (ie. "txt" or "pdf")\n :rtype: str\n '
(root, ext) = os.path.splitext(self.__name)
return ext | Get the file extension name.
:returns: The file extension (ie. "txt" or "pdf")
:rtype: str | raspy/io/file_info.py | get_file_extension | cyrusbuilt/RasPy | 0 | python | def get_file_extension(self):
'Get the file extension name.\n\n :returns: The file extension (ie. "txt" or "pdf")\n :rtype: str\n '
(root, ext) = os.path.splitext(self.__name)
return ext | def get_file_extension(self):
'Get the file extension name.\n\n :returns: The file extension (ie. "txt" or "pdf")\n :rtype: str\n '
(root, ext) = os.path.splitext(self.__name)
return ext<|docstring|>Get the file extension name.
:returns: The file extension (ie. "txt" or "pdf")
:rtype: ... |
92a1752ac567253c8226b9395387647f5e959c241b09dbebeb0be75f825535d1 | def delete(self):
'Delete this file.\n\n :raises: raspy.io.io_exception.IOException if an error occurred while\n trying to delete the file (such as if the file does not exist).\n '
try:
if self.exists():
os.remove(self.__fullPath)
except OSError as ex:
raise ... | Delete this file.
:raises: raspy.io.io_exception.IOException if an error occurred while
trying to delete the file (such as if the file does not exist). | raspy/io/file_info.py | delete | cyrusbuilt/RasPy | 0 | python | def delete(self):
'Delete this file.\n\n :raises: raspy.io.io_exception.IOException if an error occurred while\n trying to delete the file (such as if the file does not exist).\n '
try:
if self.exists():
os.remove(self.__fullPath)
except OSError as ex:
raise ... | def delete(self):
'Delete this file.\n\n :raises: raspy.io.io_exception.IOException if an error occurred while\n trying to delete the file (such as if the file does not exist).\n '
try:
if self.exists():
os.remove(self.__fullPath)
except OSError as ex:
raise ... |
66e85f7e3db35dfc56b28843dc89f8b60f3b85a4dc1e1c9ac8436733a736526b | def get_length(self):
'Get the file size in bytes.\n\n :returns: The file size in bytes if it exists; Otherwise, zero. May\n also return zero if this is a zero byte file.\n :rtype: int\n '
if (not self.exists()):
return 0
return os.path.getsize(self.__fullPath) | Get the file size in bytes.
:returns: The file size in bytes if it exists; Otherwise, zero. May
also return zero if this is a zero byte file.
:rtype: int | raspy/io/file_info.py | get_length | cyrusbuilt/RasPy | 0 | python | def get_length(self):
'Get the file size in bytes.\n\n :returns: The file size in bytes if it exists; Otherwise, zero. May\n also return zero if this is a zero byte file.\n :rtype: int\n '
if (not self.exists()):
return 0
return os.path.getsize(self.__fullPath) | def get_length(self):
'Get the file size in bytes.\n\n :returns: The file size in bytes if it exists; Otherwise, zero. May\n also return zero if this is a zero byte file.\n :rtype: int\n '
if (not self.exists()):
return 0
return os.path.getsize(self.__fullPath)<|docstring... |
9d89ad95d58eefda753f5dacf52a87fdd1c45e1f86fbd90f4d298de0266b1840 | def get_filename_without_extension(self):
'Get the file name, without the file extension.\n\n :returns: The file name without file extension.\n :rtype: str\n '
ext_len = len(self.get_file_extension())
return self.__name[0:(len(self.__name) - ext_len)] | Get the file name, without the file extension.
:returns: The file name without file extension.
:rtype: str | raspy/io/file_info.py | get_filename_without_extension | cyrusbuilt/RasPy | 0 | python | def get_filename_without_extension(self):
'Get the file name, without the file extension.\n\n :returns: The file name without file extension.\n :rtype: str\n '
ext_len = len(self.get_file_extension())
return self.__name[0:(len(self.__name) - ext_len)] | def get_filename_without_extension(self):
'Get the file name, without the file extension.\n\n :returns: The file name without file extension.\n :rtype: str\n '
ext_len = len(self.get_file_extension())
return self.__name[0:(len(self.__name) - ext_len)]<|docstring|>Get the file name, with... |
7b959b5d5c68179bb6a5721d343fa7f69fe0c10db2d2a956388c062321037392 | def get_fullname(self):
'Get the full file name path (dir + name + extension).\n\n :returns: The full file path.\n :rtype: str\n '
return self.__fullPath | Get the full file name path (dir + name + extension).
:returns: The full file path.
:rtype: str | raspy/io/file_info.py | get_fullname | cyrusbuilt/RasPy | 0 | python | def get_fullname(self):
'Get the full file name path (dir + name + extension).\n\n :returns: The full file path.\n :rtype: str\n '
return self.__fullPath | def get_fullname(self):
'Get the full file name path (dir + name + extension).\n\n :returns: The full file path.\n :rtype: str\n '
return self.__fullPath<|docstring|>Get the full file name path (dir + name + extension).
:returns: The full file path.
:rtype: str<|endoftext|> |
a9668e18054a0060b36562b8bc074d8f48e4fed8382634a427915a41c1a81e6e | def write_to_file(contours, file_path):
'\n :param contours: [[x1, y1], [x2, y2]... [xn, yn]]\n :param file_path: target file path\n '
with open(file_path, 'w') as f:
for cont in contours:
cont = np.stack([cont[(:, 0)], cont[(:, 1)]], 1)
cont = cont.flatten().astype(str)... | :param contours: [[x1, y1], [x2, y2]... [xn, yn]]
:param file_path: target file path | train_textBPN.py | write_to_file | DerekRay/TextBPN | 0 | python | def write_to_file(contours, file_path):
'\n :param contours: [[x1, y1], [x2, y2]... [xn, yn]]\n :param file_path: target file path\n '
with open(file_path, 'w') as f:
for cont in contours:
cont = np.stack([cont[(:, 0)], cont[(:, 1)]], 1)
cont = cont.flatten().astype(str)... | def write_to_file(contours, file_path):
'\n :param contours: [[x1, y1], [x2, y2]... [xn, yn]]\n :param file_path: target file path\n '
with open(file_path, 'w') as f:
for cont in contours:
cont = np.stack([cont[(:, 0)], cont[(:, 1)]], 1)
cont = cont.flatten().astype(str)... |
dbfc60f4a29ee31edba54f682122b227e6a5db01337301089c821c2c11159f7d | def GetKeywords(self):
'Returns Specified Keywords List '
keywords = list()
keyw_str = [COMM_KEYWORDS]
if (self.LangId == synglob.ID_LANG_CSH):
keyw_str.append(CSH_KEYWORDS)
else:
if (self.LangId != synglob.ID_LANG_BOURNE):
keyw_str.append(EXT_KEYWORDS)
if (self.L... | Returns Specified Keywords List | Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_sh.py | GetKeywords | William22FM/RobotTest | 27 | python | def GetKeywords(self):
' '
keywords = list()
keyw_str = [COMM_KEYWORDS]
if (self.LangId == synglob.ID_LANG_CSH):
keyw_str.append(CSH_KEYWORDS)
else:
if (self.LangId != synglob.ID_LANG_BOURNE):
keyw_str.append(EXT_KEYWORDS)
if (self.LangId == synglob.ID_LANG_BASH):... | def GetKeywords(self):
' '
keywords = list()
keyw_str = [COMM_KEYWORDS]
if (self.LangId == synglob.ID_LANG_CSH):
keyw_str.append(CSH_KEYWORDS)
else:
if (self.LangId != synglob.ID_LANG_BOURNE):
keyw_str.append(EXT_KEYWORDS)
if (self.LangId == synglob.ID_LANG_BASH):... |
1a3cb7d35b088b1357cef257e5426e96a89efddc30e773eba16f0196133d2ac1 | def GetSyntaxSpec(self):
'Syntax Specifications '
return SYNTAX_ITEMS | Syntax Specifications | Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_sh.py | GetSyntaxSpec | William22FM/RobotTest | 27 | python | def GetSyntaxSpec(self):
' '
return SYNTAX_ITEMS | def GetSyntaxSpec(self):
' '
return SYNTAX_ITEMS<|docstring|>Syntax Specifications<|endoftext|> |
92d388cd998d188679571efc2d5c00ddea0de78a7e635188ffc56e64e835c348 | def GetProperties(self):
'Returns a list of Extra Properties to set '
return [FOLD, FLD_COMMENT, FLD_COMPACT] | Returns a list of Extra Properties to set | Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_sh.py | GetProperties | William22FM/RobotTest | 27 | python | def GetProperties(self):
' '
return [FOLD, FLD_COMMENT, FLD_COMPACT] | def GetProperties(self):
' '
return [FOLD, FLD_COMMENT, FLD_COMPACT]<|docstring|>Returns a list of Extra Properties to set<|endoftext|> |
c47405eea7357d80190fc83bf9160fecd167310b0e0a0198d212517e69af01c1 | def GetCommentPattern(self):
'Returns a list of characters used to comment a block of code '
return [u'#'] | Returns a list of characters used to comment a block of code | Lib/site-packages/wx-2.8-msw-unicode/wx/tools/Editra/src/syntax/_sh.py | GetCommentPattern | William22FM/RobotTest | 27 | python | def GetCommentPattern(self):
' '
return [u'#'] | def GetCommentPattern(self):
' '
return [u'#']<|docstring|>Returns a list of characters used to comment a block of code<|endoftext|> |
e62b3e9e50e7a272130a4120c2459e53a37835003118339c19d86d53226a7707 | def get_queryset(self):
"\n Filter results based on user permissions.\n\n 1. returns ``Projects`` where the user is admin if ``/projects/`` is hit\n 2. filters by parent ``project_slug`` (NestedViewSetMixin)\n 2. returns ``detail_objects`` results if it's a detail view\n 3. return... | Filter results based on user permissions.
1. returns ``Projects`` where the user is admin if ``/projects/`` is hit
2. filters by parent ``project_slug`` (NestedViewSetMixin)
2. returns ``detail_objects`` results if it's a detail view
3. returns ``listing_objects`` results if it's a listing view
4. raise a ``NotFound``... | readthedocs/api/v3/mixins.py | get_queryset | darrowco/readthedocs.org | 19 | python | def get_queryset(self):
"\n Filter results based on user permissions.\n\n 1. returns ``Projects`` where the user is admin if ``/projects/`` is hit\n 2. filters by parent ``project_slug`` (NestedViewSetMixin)\n 2. returns ``detail_objects`` results if it's a detail view\n 3. return... | def get_queryset(self):
"\n Filter results based on user permissions.\n\n 1. returns ``Projects`` where the user is admin if ``/projects/`` is hit\n 2. filters by parent ``project_slug`` (NestedViewSetMixin)\n 2. returns ``detail_objects`` results if it's a detail view\n 3. return... |
e508cce9e186cc5d3488352935a6de479850362504d5d35206c7d0b1fa1e4f75 | async def create_soup(self, url, params=None):
"Run a GET request to Tidal's JSON API for album data."
params = (params or {})
album_id = self.parse_release_id(url)
for cc in get_tidal_regions_to_fetch():
try:
self.country_code = cc
params['countrycode'] = cc
... | Run a GET request to Tidal's JSON API for album data. | salmon/sources/tidal.py | create_soup | Junkbite/smoked-salmon | 42 | python | async def create_soup(self, url, params=None):
params = (params or {})
album_id = self.parse_release_id(url)
for cc in get_tidal_regions_to_fetch():
try:
self.country_code = cc
params['countrycode'] = cc
data = (await self.get_json(f'/albums/{album_id}', para... | async def create_soup(self, url, params=None):
params = (params or {})
album_id = self.parse_release_id(url)
for cc in get_tidal_regions_to_fetch():
try:
self.country_code = cc
params['countrycode'] = cc
data = (await self.get_json(f'/albums/{album_id}', para... |
1041a3c2a1e4603f5001862c67aeac588e28d5a7de5357a5c719aefebf57bc02 | def init_coeff2epi_wf(omp_nthreads, debug=False, write_coeff=False, name='coeff2epi_wf'):
'\n Move the field coefficients on to the target (distorted) EPI space.\n\n Workflow Graph\n .. workflow::\n :graph2use: orig\n :simple_form: yes\n\n from sdcflows.workflows.apply.... | Move the field coefficients on to the target (distorted) EPI space.
Workflow Graph
.. workflow::
:graph2use: orig
:simple_form: yes
from sdcflows.workflows.apply.registration import init_coeff2epi_wf
wf = init_coeff2epi_wf(omp_nthreads=2)
Parameters
----------
omp_nthreads : :obj:... | sdcflows/workflows/apply/registration.py | init_coeff2epi_wf | madisoth/sdcflows | 16 | python | def init_coeff2epi_wf(omp_nthreads, debug=False, write_coeff=False, name='coeff2epi_wf'):
'\n Move the field coefficients on to the target (distorted) EPI space.\n\n Workflow Graph\n .. workflow::\n :graph2use: orig\n :simple_form: yes\n\n from sdcflows.workflows.apply.... | def init_coeff2epi_wf(omp_nthreads, debug=False, write_coeff=False, name='coeff2epi_wf'):
'\n Move the field coefficients on to the target (distorted) EPI space.\n\n Workflow Graph\n .. workflow::\n :graph2use: orig\n :simple_form: yes\n\n from sdcflows.workflows.apply.... |
c802444c6b21aa96ab4cd7605e7a4a40f7adb836b066b8a439dacd6b001dd741 | def predict(reversed_dictionary, dictionary):
"\n\t\tThis is only for a single word prediction, not for text generation.\n\t\tInput 3 word => ['which', 'way','she']\n\t\tprediction => ['knew']\n\n\t"
opt = keras.optimizers.Adam(lr=0.001, decay=1e-06)
loaded_model = load_model(model_name)
loaded_model.co... | This is only for a single word prediction, not for text generation.
Input 3 word => ['which', 'way','she']
prediction => ['knew'] | Text_LSTM.py | predict | ManishGotame/Keras-LSTM-TextGenerator | 0 | python | def predict(reversed_dictionary, dictionary):
"\n\t\tThis is only for a single word prediction, not for text generation.\n\t\tInput 3 word => ['which', 'way','she']\n\t\tprediction => ['knew']\n\n\t"
opt = keras.optimizers.Adam(lr=0.001, decay=1e-06)
loaded_model = load_model(model_name)
loaded_model.co... | def predict(reversed_dictionary, dictionary):
"\n\t\tThis is only for a single word prediction, not for text generation.\n\t\tInput 3 word => ['which', 'way','she']\n\t\tprediction => ['knew']\n\n\t"
opt = keras.optimizers.Adam(lr=0.001, decay=1e-06)
loaded_model = load_model(model_name)
loaded_model.co... |
b069c67293bdf94f52879a9915c4fac692e8d8e747fc841b2669ea363b428b1f | def Text_Generator(reversed_dictionary, dictionary):
"\n\t\tThis is the text Generator. \n\t\tinput => ['as','she','coudn't]\n\t\ttext => ['words','words','words']\n\t"
opt = keras.optimizers.Adam(lr=0.001)
loaded_model = load_model(model_name)
loaded_model.compile(loss='categorical_crossentropy', optim... | This is the text Generator.
input => ['as','she','coudn't]
text => ['words','words','words'] | Text_LSTM.py | Text_Generator | ManishGotame/Keras-LSTM-TextGenerator | 0 | python | def Text_Generator(reversed_dictionary, dictionary):
"\n\t\tThis is the text Generator. \n\t\tinput => ['as','she','coudn't]\n\t\ttext => ['words','words','words']\n\t"
opt = keras.optimizers.Adam(lr=0.001)
loaded_model = load_model(model_name)
loaded_model.compile(loss='categorical_crossentropy', optim... | def Text_Generator(reversed_dictionary, dictionary):
"\n\t\tThis is the text Generator. \n\t\tinput => ['as','she','coudn't]\n\t\ttext => ['words','words','words']\n\t"
opt = keras.optimizers.Adam(lr=0.001)
loaded_model = load_model(model_name)
loaded_model.compile(loss='categorical_crossentropy', optim... |
8475d63c002a10c367c670addfdd2039ecbd49473b8650df17671b8e834bfcff | @json
@args(Body, Query, Query, Query, Query, Query)
@post('predict/')
def request_cloud_prediction(self, payload, environment, version, order, limit, threshold):
'Get all public teachables' | Get all public teachables | teachablehub/clients/prediction_api.py | request_cloud_prediction | teachablehub/python-sdk | 4 | python | @json
@args(Body, Query, Query, Query, Query, Query)
@post('predict/')
def request_cloud_prediction(self, payload, environment, version, order, limit, threshold):
| @json
@args(Body, Query, Query, Query, Query, Query)
@post('predict/')
def request_cloud_prediction(self, payload, environment, version, order, limit, threshold):
<|docstring|>Get all public teachables<|endoftext|> |
ad927d19c53613438163df9b71691bcefc8b2b7fccc8aa52dc26a1d4bd620edf | def load_classifier(classifier_name):
"Function to load trained classifier\n\n Parameters\n ----------\n classifier_name: str\n name of classifier to be loaded from the data folder\n options are: ['complete.pkl', 'partial.pkl']\n\n Returns\n -------\n clf: sklearn.ensemble.RandomFore... | Function to load trained classifier
Parameters
----------
classifier_name: str
name of classifier to be loaded from the data folder
options are: ['complete.pkl', 'partial.pkl']
Returns
-------
clf: sklearn.ensemble.RandomForestClassifier
trained classifier that is loaded from the data folder | kndetect/predict.py | load_classifier | b-biswas/kn_ztf_detection | 0 | python | def load_classifier(classifier_name):
"Function to load trained classifier\n\n Parameters\n ----------\n classifier_name: str\n name of classifier to be loaded from the data folder\n options are: ['complete.pkl', 'partial.pkl']\n\n Returns\n -------\n clf: sklearn.ensemble.RandomFore... | def load_classifier(classifier_name):
"Function to load trained classifier\n\n Parameters\n ----------\n classifier_name: str\n name of classifier to be loaded from the data folder\n options are: ['complete.pkl', 'partial.pkl']\n\n Returns\n -------\n clf: sklearn.ensemble.RandomFore... |
a2b5ebedbda12287f04825fda62a720385bd74aec75ad03d89c14b9a84642db6 | def filter_no_coeff_events(features_df):
'Function to filter out events that have no predictions in both `g` and `r` bands\n\n Parameters\n ----------\n features_df: pd.DataFrame\n dataframe with the optimised set of coefficients and features.\n this dataframe must contain "coeff1_g" and "coe... | Function to filter out events that have no predictions in both `g` and `r` bands
Parameters
----------
features_df: pd.DataFrame
dataframe with the optimised set of coefficients and features.
this dataframe must contain "coeff1_g" and "coeff1_r" columns
Returns
_______
filtered_indices: list
list with boo... | kndetect/predict.py | filter_no_coeff_events | b-biswas/kn_ztf_detection | 0 | python | def filter_no_coeff_events(features_df):
'Function to filter out events that have no predictions in both `g` and `r` bands\n\n Parameters\n ----------\n features_df: pd.DataFrame\n dataframe with the optimised set of coefficients and features.\n this dataframe must contain "coeff1_g" and "coe... | def filter_no_coeff_events(features_df):
'Function to filter out events that have no predictions in both `g` and `r` bands\n\n Parameters\n ----------\n features_df: pd.DataFrame\n dataframe with the optimised set of coefficients and features.\n this dataframe must contain "coeff1_g" and "coe... |
39dbe70d775ddb37bac4cdaa5e181dec9fc6fa2faf5692ce616fd55d47f28ba8 | def predict_kn_score(clf, features_df):
'Function to predict kn_scores\n\n Parameters\n ----------\n clf: sklearn.ensemble.RandomForestClassifier\n trained classifier to be used for classifying events\n features_df: pd.DataFrame\n A dataframe containing at least the columns mentioned\n ... | Function to predict kn_scores
Parameters
----------
clf: sklearn.ensemble.RandomForestClassifier
trained classifier to be used for classifying events
features_df: pd.DataFrame
A dataframe containing at least the columns mentioned
in kndetect.predict_features.get_feature_names.
Etra columns are ignored ... | kndetect/predict.py | predict_kn_score | b-biswas/kn_ztf_detection | 0 | python | def predict_kn_score(clf, features_df):
'Function to predict kn_scores\n\n Parameters\n ----------\n clf: sklearn.ensemble.RandomForestClassifier\n trained classifier to be used for classifying events\n features_df: pd.DataFrame\n A dataframe containing at least the columns mentioned\n ... | def predict_kn_score(clf, features_df):
'Function to predict kn_scores\n\n Parameters\n ----------\n clf: sklearn.ensemble.RandomForestClassifier\n trained classifier to be used for classifying events\n features_df: pd.DataFrame\n A dataframe containing at least the columns mentioned\n ... |
6e0c002813b81fc966e265968691e5e3b05bdb7ab3320d44c462194f54dd0346 | def base_score(text: str, index: int) -> float:
'Find a place to split string in two and in about two equal halves. Preference order:\n 1. Newlines (score 16 / distance to the midpoint)\n 2. "!.?" that is immediately followed by whitespace (score 16/ distance to the midpoint)\n 3. Other punctuation immedia... | Find a place to split string in two and in about two equal halves. Preference order:
1. Newlines (score 16 / distance to the midpoint)
2. "!.?" that is immediately followed by whitespace (score 16/ distance to the midpoint)
3. Other punctuation immediately followed by whitespace (score 8/ distance to the midpoint)
3. O... | textreader/textreader/textsplitter.py | base_score | timokoola/textreaderserverless | 2 | python | def base_score(text: str, index: int) -> float:
'Find a place to split string in two and in about two equal halves. Preference order:\n 1. Newlines (score 16 / distance to the midpoint)\n 2. "!.?" that is immediately followed by whitespace (score 16/ distance to the midpoint)\n 3. Other punctuation immedia... | def base_score(text: str, index: int) -> float:
'Find a place to split string in two and in about two equal halves. Preference order:\n 1. Newlines (score 16 / distance to the midpoint)\n 2. "!.?" that is immediately followed by whitespace (score 16/ distance to the midpoint)\n 3. Other punctuation immedia... |
c1e2e6ec6354990e756cb94f49a2e30244404fae7ac64f591217ef9aeb900fe6 | def pivot_point(text: str) -> PivotPoint:
'Find the breaking point for the string around the middle'
scores = [base_score(text, x[0]) for x in enumerate(text)]
break_at = max([x for x in enumerate(scores)], key=(lambda x: x[1]))[0]
return PivotPoint(break_at, len(text[:(break_at + 1)]), len(text[(break_... | Find the breaking point for the string around the middle | textreader/textreader/textsplitter.py | pivot_point | timokoola/textreaderserverless | 2 | python | def pivot_point(text: str) -> PivotPoint:
scores = [base_score(text, x[0]) for x in enumerate(text)]
break_at = max([x for x in enumerate(scores)], key=(lambda x: x[1]))[0]
return PivotPoint(break_at, len(text[:(break_at + 1)]), len(text[(break_at + 1):])) | def pivot_point(text: str) -> PivotPoint:
scores = [base_score(text, x[0]) for x in enumerate(text)]
break_at = max([x for x in enumerate(scores)], key=(lambda x: x[1]))[0]
return PivotPoint(break_at, len(text[:(break_at + 1)]), len(text[(break_at + 1):]))<|docstring|>Find the breaking point for the st... |
f581544d22669a803bfce6e6448dba37f0f4d6689e8756987dd83b6230ca1798 | @classmethod
def split(cls, node: 'TextNode') -> Tuple[('TextNode', 'TextNode')]:
'Return left and right half of this tuple'
left_start = node.start_index
left_end = (left_start + node.split_point.split_at)
left = TextNode(left_start, left_end, pivot_point(node.full_text[left_start:(left_end + 1)]), nod... | Return left and right half of this tuple | textreader/textreader/textsplitter.py | split | timokoola/textreaderserverless | 2 | python | @classmethod
def split(cls, node: 'TextNode') -> Tuple[('TextNode', 'TextNode')]:
left_start = node.start_index
left_end = (left_start + node.split_point.split_at)
left = TextNode(left_start, left_end, pivot_point(node.full_text[left_start:(left_end + 1)]), node.max_length, node.full_text)
right = ... | @classmethod
def split(cls, node: 'TextNode') -> Tuple[('TextNode', 'TextNode')]:
left_start = node.start_index
left_end = (left_start + node.split_point.split_at)
left = TextNode(left_start, left_end, pivot_point(node.full_text[left_start:(left_end + 1)]), node.max_length, node.full_text)
right = ... |
daaef2ae49ff2b1575899de06bda8aa571cdbcf1f019c4b49d392d5cb65cffbb | def prime_cache(args):
'If data needs to be denormalized for lookup, do that here.\n This procedure should be separate from the db initialization, because\n it will have to be run periodically whenever data has been updated.\n '
entries = {e.name.lower(): e for e in DBSession.query(models.Entry)}
(... | If data needs to be denormalized for lookup, do that here.
This procedure should be separate from the db initialization, because
it will have to be run periodically whenever data has been updated. | csd/scripts/initializedb.py | prime_cache | clld/csd | 0 | python | def prime_cache(args):
'If data needs to be denormalized for lookup, do that here.\n This procedure should be separate from the db initialization, because\n it will have to be run periodically whenever data has been updated.\n '
entries = {e.name.lower(): e for e in DBSession.query(models.Entry)}
(... | def prime_cache(args):
'If data needs to be denormalized for lookup, do that here.\n This procedure should be separate from the db initialization, because\n it will have to be run periodically whenever data has been updated.\n '
entries = {e.name.lower(): e for e in DBSession.query(models.Entry)}
(... |
242dc30d9f94e48f4077af9b4d003e6d4f3dbc2de37cc050daca35dc1f8f648f | def language_chunks(self):
"\n\n :return: yields dictionaries where the value of 'forms' are the phonetic siouan forms for a particular language.\n "
data = defaultdict(list)
for (k, v) in self:
if (k in LANGUAGES):
if (data.get('forms') or data.get('oo')):
... | :return: yields dictionaries where the value of 'forms' are the phonetic siouan forms for a particular language. | csd/scripts/initializedb.py | language_chunks | clld/csd | 0 | python | def language_chunks(self):
"\n\n \n "
data = defaultdict(list)
for (k, v) in self:
if (k in LANGUAGES):
if (data.get('forms') or data.get('oo')):
(yield data)
data = defaultdict(list)
data.update(language=k, forms=(v or None))
... | def language_chunks(self):
"\n\n \n "
data = defaultdict(list)
for (k, v) in self:
if (k in LANGUAGES):
if (data.get('forms') or data.get('oo')):
(yield data)
data = defaultdict(list)
data.update(language=k, forms=(v or None))
... |
dbf2c90aec18e007bcf2a2c0c885070a2c0a0b57a1e29b921a31426387e89ac0 | def generate_config(context):
'Creates private PyPi.'
resources = [{'name': 'pypi-run', 'type': 'run-template.py', 'properties': {'region': context.properties['region']}}, {'name': 'pypi-secret', 'type': 'secret-template.py'}, {'name': 'pypi-service-account', 'type': 'service-account-template.py'}, {'name': 'py... | Creates private PyPi. | install/pypi-template.py | generate_config | Backupni/pypi-google-cloud | 7 | python | def generate_config(context):
resources = [{'name': 'pypi-run', 'type': 'run-template.py', 'properties': {'region': context.properties['region']}}, {'name': 'pypi-secret', 'type': 'secret-template.py'}, {'name': 'pypi-service-account', 'type': 'service-account-template.py'}, {'name': 'pypi-services', 'type': '... | def generate_config(context):
resources = [{'name': 'pypi-run', 'type': 'run-template.py', 'properties': {'region': context.properties['region']}}, {'name': 'pypi-secret', 'type': 'secret-template.py'}, {'name': 'pypi-service-account', 'type': 'service-account-template.py'}, {'name': 'pypi-services', 'type': '... |
4ca17383c7fa6bdd9d0998c43291edc961e34ce86e81314537e4bad1645d0c20 | def teardown_method(self, method):
' Tear down function '
FileList = ['addedmass2D.xmf', 'addedmass2D.h5', 'addedmass3D.xmf', 'addedmass3D.h5', 'record_rectangle1.csv', 'record_rectangle1_Aij.csv', 'record_cuboid1.csv', 'record_cuboid1_Aij.csv', 'mesh.ele', 'mesh.edge', 'mesh.node', 'mesh.neigh', 'mesh.face', '... | Tear down function | proteus/tests/AddedMass/test_addedmass2D.py | teardown_method | zhang-alvin/cleanProteus | 0 | python | def teardown_method(self, method):
' '
FileList = ['addedmass2D.xmf', 'addedmass2D.h5', 'addedmass3D.xmf', 'addedmass3D.h5', 'record_rectangle1.csv', 'record_rectangle1_Aij.csv', 'record_cuboid1.csv', 'record_cuboid1_Aij.csv', 'mesh.ele', 'mesh.edge', 'mesh.node', 'mesh.neigh', 'mesh.face', 'mesh.poly', 'force... | def teardown_method(self, method):
' '
FileList = ['addedmass2D.xmf', 'addedmass2D.h5', 'addedmass3D.xmf', 'addedmass3D.h5', 'record_rectangle1.csv', 'record_rectangle1_Aij.csv', 'record_cuboid1.csv', 'record_cuboid1_Aij.csv', 'mesh.ele', 'mesh.edge', 'mesh.node', 'mesh.neigh', 'mesh.face', 'mesh.poly', 'force... |
0433ca2004a89c5694d62b41eaeed9567f982f8ce61390849b80fd1938934dc1 | def serveCurveEdit(port, hoverTimeResponse, curveset):
'\n /hoverTime requests actually are handled by the curvecalc gui\n '
curveEdit = CurveEdit(curveset)
class HoverTime(PrettyErrorHandler, cyclone.web.RequestHandler):
def get(self):
hoverTimeResponse(self)
class LiveInpu... | /hoverTime requests actually are handled by the curvecalc gui | light9/curvecalc/curveedit.py | serveCurveEdit | drewp/light9 | 2 | python | def serveCurveEdit(port, hoverTimeResponse, curveset):
'\n \n '
curveEdit = CurveEdit(curveset)
class HoverTime(PrettyErrorHandler, cyclone.web.RequestHandler):
def get(self):
hoverTimeResponse(self)
class LiveInputPoint(PrettyErrorHandler, cyclone.web.RequestHandler):
... | def serveCurveEdit(port, hoverTimeResponse, curveset):
'\n \n '
curveEdit = CurveEdit(curveset)
class HoverTime(PrettyErrorHandler, cyclone.web.RequestHandler):
def get(self):
hoverTimeResponse(self)
class LiveInputPoint(PrettyErrorHandler, cyclone.web.RequestHandler):
... |
be0ac8718ffcca120d6f0aa4771759e004790265624cf44834567f11ceab256d | def start(filename):
'Start transcript, appending print output to given filename'
sys.stdout = Transcript(filename) | Start transcript, appending print output to given filename | codes/tools/transcript.py | start | wustl-cig/2022-MRM-LEARN | 6 | python | def start(filename):
sys.stdout = Transcript(filename) | def start(filename):
sys.stdout = Transcript(filename)<|docstring|>Start transcript, appending print output to given filename<|endoftext|> |
09a5e8bd411d3a8811c935a1f8d17d6448e3f4b391afa0c9314c611b4d8fb24b | def stop():
'Stop transcript and return print functionality to normal'
sys.stdout.logfile.close()
sys.stdout = sys.stdout.terminal | Stop transcript and return print functionality to normal | codes/tools/transcript.py | stop | wustl-cig/2022-MRM-LEARN | 6 | python | def stop():
sys.stdout.logfile.close()
sys.stdout = sys.stdout.terminal | def stop():
sys.stdout.logfile.close()
sys.stdout = sys.stdout.terminal<|docstring|>Stop transcript and return print functionality to normal<|endoftext|> |
dc1261659b65adb4806fbf2383ddf2f1149d6392621576541bc9260ec1781486 | @pytest.mark.parametrize('search_type,json_data', TEST_VALID_DATA)
def test_search_valid(session, client, jwt, search_type, json_data):
'Assert that valid search criteria returns a 201 status.'
current_app.config.update(PAYMENT_SVC_URL=MOCK_PAY_URL)
rv = client.post('/api/v1/searches', json=json_data, heade... | Assert that valid search criteria returns a 201 status. | ppr-api/tests/unit/api/test_searches.py | test_search_valid | thorwolpert/ppr | 0 | python | @pytest.mark.parametrize('search_type,json_data', TEST_VALID_DATA)
def test_search_valid(session, client, jwt, search_type, json_data):
current_app.config.update(PAYMENT_SVC_URL=MOCK_PAY_URL)
rv = client.post('/api/v1/searches', json=json_data, headers=create_header_account(jwt, [PPR_ROLE]), content_type='... | @pytest.mark.parametrize('search_type,json_data', TEST_VALID_DATA)
def test_search_valid(session, client, jwt, search_type, json_data):
current_app.config.update(PAYMENT_SVC_URL=MOCK_PAY_URL)
rv = client.post('/api/v1/searches', json=json_data, headers=create_header_account(jwt, [PPR_ROLE]), content_type='... |
d3a64e011470a7e9cf7c900a002b812a060aede5a1c06cfa9388b8b241c5eda8 | @pytest.mark.parametrize('search_type,json_data', TEST_VALID_DATA)
def test_staff_search_certified(session, client, jwt, search_type, json_data):
'Assert that valid staff certified search criteria returns a 201 status.'
current_app.config.update(PAYMENT_SVC_URL=MOCK_PAY_URL)
rv = client.post('/api/v1/search... | Assert that valid staff certified search criteria returns a 201 status. | ppr-api/tests/unit/api/test_searches.py | test_staff_search_certified | thorwolpert/ppr | 0 | python | @pytest.mark.parametrize('search_type,json_data', TEST_VALID_DATA)
def test_staff_search_certified(session, client, jwt, search_type, json_data):
current_app.config.update(PAYMENT_SVC_URL=MOCK_PAY_URL)
rv = client.post('/api/v1/searches?certified=true', json=json_data, headers=create_header_account(jwt, [P... | @pytest.mark.parametrize('search_type,json_data', TEST_VALID_DATA)
def test_staff_search_certified(session, client, jwt, search_type, json_data):
current_app.config.update(PAYMENT_SVC_URL=MOCK_PAY_URL)
rv = client.post('/api/v1/searches?certified=true', json=json_data, headers=create_header_account(jwt, [P... |
812d36a3211fda753c52273dcfec190c9f55d3ea7e47526da89bf6c7e18bb76a | @pytest.mark.parametrize('role,routing_slip,bcol_number,dat_number,certified,status', TEST_STAFF_SEARCH_DATA)
def test_staff_search(session, client, jwt, role, routing_slip, bcol_number, dat_number, certified, status):
'Assert that staff search requests returns the correct status.'
current_app.config.update(PAY... | Assert that staff search requests returns the correct status. | ppr-api/tests/unit/api/test_searches.py | test_staff_search | thorwolpert/ppr | 0 | python | @pytest.mark.parametrize('role,routing_slip,bcol_number,dat_number,certified,status', TEST_STAFF_SEARCH_DATA)
def test_staff_search(session, client, jwt, role, routing_slip, bcol_number, dat_number, certified, status):
current_app.config.update(PAYMENT_SVC_URL=MOCK_PAY_URL)
params =
if certified:
... | @pytest.mark.parametrize('role,routing_slip,bcol_number,dat_number,certified,status', TEST_STAFF_SEARCH_DATA)
def test_staff_search(session, client, jwt, role, routing_slip, bcol_number, dat_number, certified, status):
current_app.config.update(PAYMENT_SVC_URL=MOCK_PAY_URL)
params =
if certified:
... |
3cf1010e3cfd74f8c53030381ea71f7ab92205e9b0c611147fd2cc674f69724c | def test_search_query_invalid_type_400(session, client, jwt):
'Assert that search criteria with an invalid type returns a 400 error.'
json_data = copy.deepcopy(SAMPLE_JSON_DATA)
json_data['type'] = 'INVALID_TYPE'
rv = client.post('/api/v1/searches', json=json_data, headers=create_header_account(jwt, [PP... | Assert that search criteria with an invalid type returns a 400 error. | ppr-api/tests/unit/api/test_searches.py | test_search_query_invalid_type_400 | thorwolpert/ppr | 0 | python | def test_search_query_invalid_type_400(session, client, jwt):
json_data = copy.deepcopy(SAMPLE_JSON_DATA)
json_data['type'] = 'INVALID_TYPE'
rv = client.post('/api/v1/searches', json=json_data, headers=create_header_account(jwt, [PPR_ROLE]), content_type='application/json')
assert (rv.status_code =... | def test_search_query_invalid_type_400(session, client, jwt):
json_data = copy.deepcopy(SAMPLE_JSON_DATA)
json_data['type'] = 'INVALID_TYPE'
rv = client.post('/api/v1/searches', json=json_data, headers=create_header_account(jwt, [PPR_ROLE]), content_type='application/json')
assert (rv.status_code =... |
5ce1d5b3abf94b1e323c94db1a01838c6c2de83bf5b3b5237de5ba1aa00274b1 | def test_search_query_nonstaff_missing_account_400(session, client, jwt):
'Assert that a search request with a non-staff jwt and no account ID returns a 400 status.'
json_data = copy.deepcopy(SAMPLE_JSON_DATA)
del json_data['criteria']['debtorName']['business']
del json_data['criteria']['value']
rv ... | Assert that a search request with a non-staff jwt and no account ID returns a 400 status. | ppr-api/tests/unit/api/test_searches.py | test_search_query_nonstaff_missing_account_400 | thorwolpert/ppr | 0 | python | def test_search_query_nonstaff_missing_account_400(session, client, jwt):
json_data = copy.deepcopy(SAMPLE_JSON_DATA)
del json_data['criteria']['debtorName']['business']
del json_data['criteria']['value']
rv = client.post('/api/v1/searches', json=json_data, headers=create_header(jwt, [PPR_ROLE]), c... | def test_search_query_nonstaff_missing_account_400(session, client, jwt):
json_data = copy.deepcopy(SAMPLE_JSON_DATA)
del json_data['criteria']['debtorName']['business']
del json_data['criteria']['value']
rv = client.post('/api/v1/searches', json=json_data, headers=create_header(jwt, [PPR_ROLE]), c... |
4b3897275afc1f1e4245eda29b8665078bcada22202567f08035b3f373df7835 | def test_search_query_staff_missing_account_400(session, client, jwt):
'Assert that a search request with a staff jwt and no account ID returns a 201 status.'
json_data = {'type': 'REGISTRATION_NUMBER', 'criteria': {'value': 'TEST0001'}, 'clientReferenceId': 'T-API-SQ-RN-1'}
rv = client.post('/api/v1/search... | Assert that a search request with a staff jwt and no account ID returns a 201 status. | ppr-api/tests/unit/api/test_searches.py | test_search_query_staff_missing_account_400 | thorwolpert/ppr | 0 | python | def test_search_query_staff_missing_account_400(session, client, jwt):
json_data = {'type': 'REGISTRATION_NUMBER', 'criteria': {'value': 'TEST0001'}, 'clientReferenceId': 'T-API-SQ-RN-1'}
rv = client.post('/api/v1/searches', json=json_data, headers=create_header(jwt, [PPR_ROLE, STAFF_ROLE]), content_type='... | def test_search_query_staff_missing_account_400(session, client, jwt):
json_data = {'type': 'REGISTRATION_NUMBER', 'criteria': {'value': 'TEST0001'}, 'clientReferenceId': 'T-API-SQ-RN-1'}
rv = client.post('/api/v1/searches', json=json_data, headers=create_header(jwt, [PPR_ROLE, STAFF_ROLE]), content_type='... |
b15fe894b9b0c52562bd303ebd43a9a56a004f567d2e9b9a2d47e1a8f89e6d62 | def test_search_query_no_result_200(session, client, jwt):
'Assert that a valid search request with no results returns a 201 status.'
current_app.config.update(PAYMENT_SVC_URL=MOCK_PAY_URL)
json_data = {'type': 'REGISTRATION_NUMBER', 'criteria': {'value': 'TESTXXXX'}, 'clientReferenceId': 'T-API-SQ-RN-5'}
... | Assert that a valid search request with no results returns a 201 status. | ppr-api/tests/unit/api/test_searches.py | test_search_query_no_result_200 | thorwolpert/ppr | 0 | python | def test_search_query_no_result_200(session, client, jwt):
current_app.config.update(PAYMENT_SVC_URL=MOCK_PAY_URL)
json_data = {'type': 'REGISTRATION_NUMBER', 'criteria': {'value': 'TESTXXXX'}, 'clientReferenceId': 'T-API-SQ-RN-5'}
rv = client.post('/api/v1/searches', json=json_data, headers=create_hea... | def test_search_query_no_result_200(session, client, jwt):
current_app.config.update(PAYMENT_SVC_URL=MOCK_PAY_URL)
json_data = {'type': 'REGISTRATION_NUMBER', 'criteria': {'value': 'TESTXXXX'}, 'clientReferenceId': 'T-API-SQ-RN-5'}
rv = client.post('/api/v1/searches', json=json_data, headers=create_hea... |
6817894abdc3e0847b3013ecc2674604153c865100ab631e6f5a3ab6fd03d943 | def test_search_query_nonstaff_unauthorized_404(session, client, jwt):
'Assert that a search request with a non-ppr role and an account ID returns a 404 status.'
json_data = copy.deepcopy(SAMPLE_JSON_DATA)
del json_data['criteria']['debtorName']['business']
del json_data['criteria']['value']
rv = cl... | Assert that a search request with a non-ppr role and an account ID returns a 404 status. | ppr-api/tests/unit/api/test_searches.py | test_search_query_nonstaff_unauthorized_404 | thorwolpert/ppr | 0 | python | def test_search_query_nonstaff_unauthorized_404(session, client, jwt):
json_data = copy.deepcopy(SAMPLE_JSON_DATA)
del json_data['criteria']['debtorName']['business']
del json_data['criteria']['value']
rv = client.post('/api/v1/searches', json=json_data, headers=create_header_account(jwt, [COLIN_RO... | def test_search_query_nonstaff_unauthorized_404(session, client, jwt):
json_data = copy.deepcopy(SAMPLE_JSON_DATA)
del json_data['criteria']['debtorName']['business']
del json_data['criteria']['value']
rv = client.post('/api/v1/searches', json=json_data, headers=create_header_account(jwt, [COLIN_RO... |
a1d2597474bdc43b030e6f9f6fc91abcf1c5afffca7de63ab8fca45298c0cded | def test_search_query_invalid_start_datetime_400(session, client, jwt):
'Assert that a valid search request with an invalid startDateTime returns a 400 status.'
json_data = {'type': 'REGISTRATION_NUMBER', 'criteria': {'value': 'TEST0001'}, 'clientReferenceId': 'T-API-SQ-RN-6', 'endDateTime': '2021-01-20T19:38:4... | Assert that a valid search request with an invalid startDateTime returns a 400 status. | ppr-api/tests/unit/api/test_searches.py | test_search_query_invalid_start_datetime_400 | thorwolpert/ppr | 0 | python | def test_search_query_invalid_start_datetime_400(session, client, jwt):
json_data = {'type': 'REGISTRATION_NUMBER', 'criteria': {'value': 'TEST0001'}, 'clientReferenceId': 'T-API-SQ-RN-6', 'endDateTime': '2021-01-20T19:38:43+00:00'}
ts_start = now_ts_offset(1, True)
json_data['startDateTime'] = format_... | def test_search_query_invalid_start_datetime_400(session, client, jwt):
json_data = {'type': 'REGISTRATION_NUMBER', 'criteria': {'value': 'TEST0001'}, 'clientReferenceId': 'T-API-SQ-RN-6', 'endDateTime': '2021-01-20T19:38:43+00:00'}
ts_start = now_ts_offset(1, True)
json_data['startDateTime'] = format_... |
59515f9ca2a89dcdd21f557acd51edab062971e0f4aa31f70f258075e31a5d53 | def test_search_selection_update_valid(session, client, jwt):
'Assert that a valid search selection update returns a 200 status.'
current_app.config.update(PAYMENT_SVC_URL=MOCK_PAY_URL)
json_data = [{'baseRegistrationNumber': 'TEST0001', 'matchType': 'EXACT', 'createDateTime': '2021-03-02T22:46:43+00:00', '... | Assert that a valid search selection update returns a 200 status. | ppr-api/tests/unit/api/test_searches.py | test_search_selection_update_valid | thorwolpert/ppr | 0 | python | def test_search_selection_update_valid(session, client, jwt):
current_app.config.update(PAYMENT_SVC_URL=MOCK_PAY_URL)
json_data = [{'baseRegistrationNumber': 'TEST0001', 'matchType': 'EXACT', 'createDateTime': '2021-03-02T22:46:43+00:00', 'registrationType': 'SA', 'debtor': {'businessName': 'TEST BUS 2 DEB... | def test_search_selection_update_valid(session, client, jwt):
current_app.config.update(PAYMENT_SVC_URL=MOCK_PAY_URL)
json_data = [{'baseRegistrationNumber': 'TEST0001', 'matchType': 'EXACT', 'createDateTime': '2021-03-02T22:46:43+00:00', 'registrationType': 'SA', 'debtor': {'businessName': 'TEST BUS 2 DEB... |
dd07686ddd0d588b84cfb3ceb586b57291e870652122329104a4bca9721cf6f5 | def test_search_selection_update_invalid_400(session, client, jwt):
'Assert that an invalid search selection update returns a 400 status.'
json_data = [{'baseRegistrationNumber': 'TEST0001', 'createDateTime': '2021-03-02T22:46:43+00:00', 'registrationType': 'SA', 'debtor': {'businessName': 'TEST BUS 2 DEBTOR', ... | Assert that an invalid search selection update returns a 400 status. | ppr-api/tests/unit/api/test_searches.py | test_search_selection_update_invalid_400 | thorwolpert/ppr | 0 | python | def test_search_selection_update_invalid_400(session, client, jwt):
json_data = [{'baseRegistrationNumber': 'TEST0001', 'createDateTime': '2021-03-02T22:46:43+00:00', 'registrationType': 'SA', 'debtor': {'businessName': 'TEST BUS 2 DEBTOR', 'partyId': 200000002}}]
rv = client.put('/api/v1/searches/20000000... | def test_search_selection_update_invalid_400(session, client, jwt):
json_data = [{'baseRegistrationNumber': 'TEST0001', 'createDateTime': '2021-03-02T22:46:43+00:00', 'registrationType': 'SA', 'debtor': {'businessName': 'TEST BUS 2 DEBTOR', 'partyId': 200000002}}]
rv = client.put('/api/v1/searches/20000000... |
311a28d270be8acbf4d0d25a9cec27b24ebaf6695d95c0de221bfd8012fd069e | def test_search_selection_update_unauthorized_404(session, client, jwt):
'Assert that a valid search selection update with an invalid role returns a 404 status.'
json_data = [{'baseRegistrationNumber': 'TEST0001', 'matchType': 'EXACT', 'createDateTime': '2021-03-02T22:46:43+00:00', 'registrationType': 'SA', 'de... | Assert that a valid search selection update with an invalid role returns a 404 status. | ppr-api/tests/unit/api/test_searches.py | test_search_selection_update_unauthorized_404 | thorwolpert/ppr | 0 | python | def test_search_selection_update_unauthorized_404(session, client, jwt):
json_data = [{'baseRegistrationNumber': 'TEST0001', 'matchType': 'EXACT', 'createDateTime': '2021-03-02T22:46:43+00:00', 'registrationType': 'SA', 'debtor': {'businessName': 'TEST BUS 2 DEBTOR', 'partyId': 200000002}}]
rv = client.put... | def test_search_selection_update_unauthorized_404(session, client, jwt):
json_data = [{'baseRegistrationNumber': 'TEST0001', 'matchType': 'EXACT', 'createDateTime': '2021-03-02T22:46:43+00:00', 'registrationType': 'SA', 'debtor': {'businessName': 'TEST BUS 2 DEBTOR', 'partyId': 200000002}}]
rv = client.put... |
5f323079c51fb34afc75d15e19c4be1e38781bfd5a342c1576410ede53320294 | def test_search_selection_update_nonstaff_no_account_400(session, client, jwt):
'Assert that a valid search selection update with non-staff role, no account ID returns a 400 status.'
json_data = [{'baseRegistrationNumber': 'TEST0001', 'matchType': 'EXACT', 'createDateTime': '2021-03-02T22:46:43+00:00', 'registr... | Assert that a valid search selection update with non-staff role, no account ID returns a 400 status. | ppr-api/tests/unit/api/test_searches.py | test_search_selection_update_nonstaff_no_account_400 | thorwolpert/ppr | 0 | python | def test_search_selection_update_nonstaff_no_account_400(session, client, jwt):
json_data = [{'baseRegistrationNumber': 'TEST0001', 'matchType': 'EXACT', 'createDateTime': '2021-03-02T22:46:43+00:00', 'registrationType': 'SA', 'debtor': {'businessName': 'TEST BUS 2 DEBTOR', 'partyId': 200000002}}]
rv = cli... | def test_search_selection_update_nonstaff_no_account_400(session, client, jwt):
json_data = [{'baseRegistrationNumber': 'TEST0001', 'matchType': 'EXACT', 'createDateTime': '2021-03-02T22:46:43+00:00', 'registrationType': 'SA', 'debtor': {'businessName': 'TEST BUS 2 DEBTOR', 'partyId': 200000002}}]
rv = cli... |
c6034736c04faa2ec26651c42471553ade780576fee230683fccafad080941a6 | def test_get_payment_details(session, client, jwt):
'Assert that a valid search request payment details setup works as expected.'
json_data = copy.deepcopy(SERIAL_NUMBER_JSON)
query = SearchRequest.create_from_json(json_data)
details = get_payment_details(query, json_data['type'])
assert details
... | Assert that a valid search request payment details setup works as expected. | ppr-api/tests/unit/api/test_searches.py | test_get_payment_details | thorwolpert/ppr | 0 | python | def test_get_payment_details(session, client, jwt):
json_data = copy.deepcopy(SERIAL_NUMBER_JSON)
query = SearchRequest.create_from_json(json_data)
details = get_payment_details(query, json_data['type'])
assert details
assert (details['label'] == 'Serial/VIN Number:')
assert (details['value... | def test_get_payment_details(session, client, jwt):
json_data = copy.deepcopy(SERIAL_NUMBER_JSON)
query = SearchRequest.create_from_json(json_data)
details = get_payment_details(query, json_data['type'])
assert details
assert (details['label'] == 'Serial/VIN Number:')
assert (details['value... |
977486a8cbccf0d07ebb5a1a9d92817f77d79cc8ab45f28f812745e0480a4881 | def get_users(recipe):
'Get all users and times for comments'
all_comments = recipe.comments
users = []
times = []
for comment in all_comments:
user = User.query.get(comment.user_id)
users.append(user)
times.append(comment.created_at)
return (users, times) | Get all users and times for comments | utilities/user_utility.py | get_users | nikgun1984/ketolife_backend | 1 | python | def get_users(recipe):
all_comments = recipe.comments
users = []
times = []
for comment in all_comments:
user = User.query.get(comment.user_id)
users.append(user)
times.append(comment.created_at)
return (users, times) | def get_users(recipe):
all_comments = recipe.comments
users = []
times = []
for comment in all_comments:
user = User.query.get(comment.user_id)
users.append(user)
times.append(comment.created_at)
return (users, times)<|docstring|>Get all users and times for comments<|end... |
424dad83a19f6f24546ff1a396f69f0dd419f37077edab4193e4c3aef5b646dd | def get_best_rated_recipes():
'Get best rated recipes by the user'
user = User.query.get(g.user.id)
rated_recipes = user.rating
best_rated = []
user_ratings = []
net_carbs = []
for rated in rated_recipes:
if (rated.rating >= 4):
recipe = Recipe.query.get(rated.recipe_id)
... | Get best rated recipes by the user | utilities/user_utility.py | get_best_rated_recipes | nikgun1984/ketolife_backend | 1 | python | def get_best_rated_recipes():
user = User.query.get(g.user.id)
rated_recipes = user.rating
best_rated = []
user_ratings = []
net_carbs = []
for rated in rated_recipes:
if (rated.rating >= 4):
recipe = Recipe.query.get(rated.recipe_id)
res = util.calculate_all... | def get_best_rated_recipes():
user = User.query.get(g.user.id)
rated_recipes = user.rating
best_rated = []
user_ratings = []
net_carbs = []
for rated in rated_recipes:
if (rated.rating >= 4):
recipe = Recipe.query.get(rated.recipe_id)
res = util.calculate_all... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.