body stringlengths 26 98.2k | body_hash int64 -9,222,864,604,528,158,000 9,221,803,474B | docstring stringlengths 1 16.8k | path stringlengths 5 230 | name stringlengths 1 96 | repository_name stringlengths 7 89 | lang stringclasses 1
value | body_without_docstring stringlengths 20 98.2k |
|---|---|---|---|---|---|---|---|
def forward(self, x, timesteps, y=None):
'\n Apply the model to an input batch.\n\n :param x: an [N x C x ...] Tensor of inputs.\n :param timesteps: a 1-D batch of timesteps.\n :param y: an [N, L] Tensor of texts, if conditional.\n :return: an [N x C x ...] Tensor of outputs.\n ... | 3,838,222,474,808,738,000 | Apply the model to an input batch.
:param x: an [N x C x ...] Tensor of inputs.
:param timesteps: a 1-D batch of timesteps.
:param y: an [N, L] Tensor of texts, if conditional.
:return: an [N x C x ...] Tensor of outputs. | diff_dalle/unet.py | forward | AranKomat/Diff-DALLE | python | def forward(self, x, timesteps, y=None):
'\n Apply the model to an input batch.\n\n :param x: an [N x C x ...] Tensor of inputs.\n :param timesteps: a 1-D batch of timesteps.\n :param y: an [N, L] Tensor of texts, if conditional.\n :return: an [N x C x ...] Tensor of outputs.\n ... |
def forward(self, x, timesteps):
'\n Apply the model to an input batch.\n\n :param x: an [N x C x ...] Tensor of inputs.\n :param timesteps: a 1-D batch of timesteps.\n :return: an [N x K] Tensor of outputs.\n '
emb = self.time_embed(timestep_embedding(timesteps, self.model_ch... | 4,133,264,892,193,183,000 | Apply the model to an input batch.
:param x: an [N x C x ...] Tensor of inputs.
:param timesteps: a 1-D batch of timesteps.
:return: an [N x K] Tensor of outputs. | diff_dalle/unet.py | forward | AranKomat/Diff-DALLE | python | def forward(self, x, timesteps):
'\n Apply the model to an input batch.\n\n :param x: an [N x C x ...] Tensor of inputs.\n :param timesteps: a 1-D batch of timesteps.\n :return: an [N x K] Tensor of outputs.\n '
emb = self.time_embed(timestep_embedding(timesteps, self.model_ch... |
def findTimeColumn(row):
'Dynamically determine which column of a log file contains dates.\n\n Parameters:\n row: A row of a logfile\n Returns:\n iterator: An integer defining the row that contains a valid date\n string.\n '
import dateparser
iterator = 0
for item in ro... | 1,817,709,913,675,201,000 | Dynamically determine which column of a log file contains dates.
Parameters:
row: A row of a logfile
Returns:
iterator: An integer defining the row that contains a valid date
string. | cfltools/depreciated/getuniqueip.py | findTimeColumn | bradley-evans/cfltools | python | def findTimeColumn(row):
'Dynamically determine which column of a log file contains dates.\n\n Parameters:\n row: A row of a logfile\n Returns:\n iterator: An integer defining the row that contains a valid date\n string.\n '
import dateparser
iterator = 0
for item in ro... |
def scrapeIPs(filename):
'Scrapes all IP addresses from a logfile.\n '
file = open(filename, encoding='utf-8')
logfile_reader = csv.reader(file)
print('Getting the size of the logfile....\n')
logsize = sum((1 for row in logfile_reader))
file.seek(0)
next(logfile_reader)
row = next(log... | 7,910,495,692,019,230,000 | Scrapes all IP addresses from a logfile. | cfltools/depreciated/getuniqueip.py | scrapeIPs | bradley-evans/cfltools | python | def scrapeIPs(filename):
'\n '
file = open(filename, encoding='utf-8')
logfile_reader = csv.reader(file)
print('Getting the size of the logfile....\n')
logsize = sum((1 for row in logfile_reader))
file.seek(0)
next(logfile_reader)
row = next(logfile_reader)
ip_column = findIpColum... |
def getTimerange(filename, unique_ip_address):
"Naive method to determine the time range during which an IP\n address appears in a logfile.\n\n This is sort of hacky. I'm using timestring to process fairly arbitrary\n text input strings for dates from logs, converting those into POSIX\n dates and times,... | -1,948,701,142,690,386,200 | Naive method to determine the time range during which an IP
address appears in a logfile.
This is sort of hacky. I'm using timestring to process fairly arbitrary
text input strings for dates from logs, converting those into POSIX
dates and times, and then comparing that to a simple integer stored
in the object to esta... | cfltools/depreciated/getuniqueip.py | getTimerange | bradley-evans/cfltools | python | def getTimerange(filename, unique_ip_address):
"Naive method to determine the time range during which an IP\n address appears in a logfile.\n\n This is sort of hacky. I'm using timestring to process fairly arbitrary\n text input strings for dates from logs, converting those into POSIX\n dates and times,... |
def get_bigram_pair_string(self, text):
'\n Return a string of text containing part-of-speech, lemma pairs.\n '
bigram_pairs = []
if (len(text) <= 2):
text_without_punctuation = text.translate(self.punctuation_table)
if (len(text_without_punctuation) >= 1):
text = t... | -4,480,019,657,429,147,000 | Return a string of text containing part-of-speech, lemma pairs. | tagging.py | get_bigram_pair_string | sciutrux/cbotami | python | def get_bigram_pair_string(self, text):
'\n \n '
bigram_pairs = []
if (len(text) <= 2):
text_without_punctuation = text.translate(self.punctuation_table)
if (len(text_without_punctuation) >= 1):
text = text_without_punctuation
document = self.nlp(text)
if (l... |
def _get_handler(self, scheme):
'Lazy-load the downloadhandler for a scheme\n only on the first request for that scheme.\n 仅在对该协议的第一个请求时才延迟加载该协议的下载处理程序。\n '
if (scheme in self._handlers):
return self._handlers[scheme]
if (scheme in self._notconfigured):
return None
i... | 126,885,426,239,589,500 | Lazy-load the downloadhandler for a scheme
only on the first request for that scheme.
仅在对该协议的第一个请求时才延迟加载该协议的下载处理程序。 | scrapy/core/downloader/handlers/__init__.py | _get_handler | Hugking/scrapy | python | def _get_handler(self, scheme):
'Lazy-load the downloadhandler for a scheme\n only on the first request for that scheme.\n 仅在对该协议的第一个请求时才延迟加载该协议的下载处理程序。\n '
if (scheme in self._handlers):
return self._handlers[scheme]
if (scheme in self._notconfigured):
return None
i... |
def _part_ind_KDTree(self, ptype):
'Find the particles in cells using a KDTree approach.'
parent = getattr(self, 'parent', self.base_object)
units = 'code_length'
pos = np.stack([self[('index', 'x')].to(units), self[('index', 'y')].to(units), self[('index', 'z')].to(units)], axis=1).value
dx = np.st... | 1,242,186,821,144,728,600 | Find the particles in cells using a KDTree approach. | yt/data_objects/selection_objects/cut_region.py | _part_ind_KDTree | chummels/yt | python | def _part_ind_KDTree(self, ptype):
parent = getattr(self, 'parent', self.base_object)
units = 'code_length'
pos = np.stack([self[('index', 'x')].to(units), self[('index', 'y')].to(units), self[('index', 'z')].to(units)], axis=1).value
dx = np.stack([self[('index', 'dx')].to(units), self[('index', '... |
def _get_bbox(self):
'\n Get the bounding box for the cut region. Here we just use\n the bounding box for the source region.\n '
return self.base_object._get_bbox() | -3,642,009,883,120,007,000 | Get the bounding box for the cut region. Here we just use
the bounding box for the source region. | yt/data_objects/selection_objects/cut_region.py | _get_bbox | chummels/yt | python | def _get_bbox(self):
'\n Get the bounding box for the cut region. Here we just use\n the bounding box for the source region.\n '
return self.base_object._get_bbox() |
def first(seq, key=(lambda x: bool(x)), default=None, apply=(lambda x: x)):
"Give the first value that satisfies the key test.\n\n Args:\n seq (iterable):\n key (callable): test for each element of iterable\n default: returned when all elements fail test\n apply (callable): applied to... | -1,724,293,131,468,870,000 | Give the first value that satisfies the key test.
Args:
seq (iterable):
key (callable): test for each element of iterable
default: returned when all elements fail test
apply (callable): applied to element before return, but not to default value
Returns: first element in seq that passes key, mutated wi... | lib/python3.7/site-packages/conda/_vendor/auxlib/collection.py | first | AXGKl/be_black | python | def first(seq, key=(lambda x: bool(x)), default=None, apply=(lambda x: x)):
"Give the first value that satisfies the key test.\n\n Args:\n seq (iterable):\n key (callable): test for each element of iterable\n default: returned when all elements fail test\n apply (callable): applied to... |
def call_each(seq):
'Calls each element of sequence to invoke the side effect.\n\n Args:\n seq:\n\n Returns: None\n\n '
try:
reduce((lambda _, y: y()), seq)
except TypeError as e:
if (text_type(e) != 'reduce() of empty sequence with no initial value'):
raise | 8,482,218,526,092,047,000 | Calls each element of sequence to invoke the side effect.
Args:
seq:
Returns: None | lib/python3.7/site-packages/conda/_vendor/auxlib/collection.py | call_each | AXGKl/be_black | python | def call_each(seq):
'Calls each element of sequence to invoke the side effect.\n\n Args:\n seq:\n\n Returns: None\n\n '
try:
reduce((lambda _, y: y()), seq)
except TypeError as e:
if (text_type(e) != 'reduce() of empty sequence with no initial value'):
raise |
@click.command()
@environment.pass_env
def cli(env):
'List options for creating a placement group.'
manager = PlacementManager(env.client)
routers = manager.get_routers()
env.fout(get_router_table(routers))
rules = manager.get_all_rules()
env.fout(get_rule_table(rules)) | -4,255,090,912,820,993,500 | List options for creating a placement group. | SoftLayer/CLI/virt/placementgroup/create_options.py | cli | ATGE/softlayer-python | python | @click.command()
@environment.pass_env
def cli(env):
manager = PlacementManager(env.client)
routers = manager.get_routers()
env.fout(get_router_table(routers))
rules = manager.get_all_rules()
env.fout(get_rule_table(rules)) |
def get_router_table(routers):
'Formats output from _get_routers and returns a table. '
table = formatting.Table(['Datacenter', 'Hostname', 'Backend Router Id'], 'Available Routers')
for router in routers:
datacenter = router['topLevelLocation']['longName']
table.add_row([datacenter, router[... | -8,719,616,408,360,183,000 | Formats output from _get_routers and returns a table. | SoftLayer/CLI/virt/placementgroup/create_options.py | get_router_table | ATGE/softlayer-python | python | def get_router_table(routers):
' '
table = formatting.Table(['Datacenter', 'Hostname', 'Backend Router Id'], 'Available Routers')
for router in routers:
datacenter = router['topLevelLocation']['longName']
table.add_row([datacenter, router['hostname'], router['id']])
return table |
def get_rule_table(rules):
'Formats output from get_all_rules and returns a table. '
table = formatting.Table(['Id', 'KeyName'], 'Rules')
for rule in rules:
table.add_row([rule['id'], rule['keyName']])
return table | -5,018,079,132,225,288,000 | Formats output from get_all_rules and returns a table. | SoftLayer/CLI/virt/placementgroup/create_options.py | get_rule_table | ATGE/softlayer-python | python | def get_rule_table(rules):
' '
table = formatting.Table(['Id', 'KeyName'], 'Rules')
for rule in rules:
table.add_row([rule['id'], rule['keyName']])
return table |
def reconstruct(ri, li, rs, v, x, y, phix, phiy):
'\n Takes x, y gradients to the solution to screen mapping potential problem and\n reconstructs the perpendicular deflection fields wBx and wBy.\n\n Args:\n ri (float): Distance from source to plasma (cm).\n li (float): Distance across plasma ... | 2,081,807,718,555,341,300 | Takes x, y gradients to the solution to screen mapping potential problem and
reconstructs the perpendicular deflection fields wBx and wBy.
Args:
ri (float): Distance from source to plasma (cm).
li (float): Distance across plasma (cm).
rs (float): Distance from plasma to screen (cm).
v (float): Velocity... | problem/deflect.py | reconstruct | flash-center/PROBLEM | python | def reconstruct(ri, li, rs, v, x, y, phix, phiy):
'\n Takes x, y gradients to the solution to screen mapping potential problem and\n reconstructs the perpendicular deflection fields wBx and wBy.\n\n Args:\n ri (float): Distance from source to plasma (cm).\n li (float): Distance across plasma ... |
def magpath(wBx, wBy):
'\n Takes the perpendicular deflection field and reconstructs the path\n integrated magnetic field.\n\n Args:\n wBx (array): x-component perpendicular deflection field.\n wBy (array): y-component perpendicular deflection field.\n\n Returns:\n Bxpath (array): P... | -5,663,707,700,662,836,000 | Takes the perpendicular deflection field and reconstructs the path
integrated magnetic field.
Args:
wBx (array): x-component perpendicular deflection field.
wBy (array): y-component perpendicular deflection field.
Returns:
Bxpath (array): Path integrated magnetic field x-component.
Bypath (array): Pa... | problem/deflect.py | magpath | flash-center/PROBLEM | python | def magpath(wBx, wBy):
'\n Takes the perpendicular deflection field and reconstructs the path\n integrated magnetic field.\n\n Args:\n wBx (array): x-component perpendicular deflection field.\n wBy (array): y-component perpendicular deflection field.\n\n Returns:\n Bxpath (array): P... |
def fluximage(ri, li, rs, v, x, y, N, wBx, wBy):
'\n Creates a flux image out of a perpendicular deflection field. \n\n Args:\n ri:\n li:\n rs:\n v:\n x (array): Perpendicular deflection field x-coordinates.\n y (array): Perpendicular deflection field y-coordinates.\n... | 9,105,284,645,734,496,000 | Creates a flux image out of a perpendicular deflection field.
Args:
ri:
li:
rs:
v:
x (array): Perpendicular deflection field x-coordinates.
y (array): Perpendicular deflection field y-coordinates.
wBx (array): Perpendicular deflection field x-component.
wBy (array): Perpendicular defle... | problem/deflect.py | fluximage | flash-center/PROBLEM | python | def fluximage(ri, li, rs, v, x, y, N, wBx, wBy):
'\n Creates a flux image out of a perpendicular deflection field. \n\n Args:\n ri:\n li:\n rs:\n v:\n x (array): Perpendicular deflection field x-coordinates.\n y (array): Perpendicular deflection field y-coordinates.\n... |
def fluximage2(x, y, phix, phiy, flux0, scale_fact=1, scale_order=3):
'\n An alternative approach to creating a flux image out of a perpendicular deflection field. \n \n Args:\n x (array): Plasma x-coordinates (cm). \n y (array): Plasma x-coordinates (cm).\n phix (array): Gradient of s... | 2,417,979,036,212,821,500 | An alternative approach to creating a flux image out of a perpendicular deflection field.
Args:
x (array): Plasma x-coordinates (cm).
y (array): Plasma x-coordinates (cm).
phix (array): Gradient of screen mapping potential in x-direction.
phiy (array): Gradient of screen mapping potential in y-direct... | problem/deflect.py | fluximage2 | flash-center/PROBLEM | python | def fluximage2(x, y, phix, phiy, flux0, scale_fact=1, scale_order=3):
'\n An alternative approach to creating a flux image out of a perpendicular deflection field. \n \n Args:\n x (array): Plasma x-coordinates (cm). \n y (array): Plasma x-coordinates (cm).\n phix (array): Gradient of s... |
def fluximage3(ri, li, rs, v, x, y, N, wBx, wBy, Ntest):
'\n A Monte Carlo approach to creating a flux image out of a perpendicular deflection field. \n \n Args:\n ri:\n li:\n rs:\n v:\n N: Number of protons in reality\n x (array): Perpendicular deflection field x-... | 4,024,405,721,791,568,400 | A Monte Carlo approach to creating a flux image out of a perpendicular deflection field.
Args:
ri:
li:
rs:
v:
N: Number of protons in reality
x (array): Perpendicular deflection field x-coordinates.
y (array): Perpendicular deflection field y-coordinates.
wBx (array): Perpendicular def... | problem/deflect.py | fluximage3 | flash-center/PROBLEM | python | def fluximage3(ri, li, rs, v, x, y, N, wBx, wBy, Ntest):
'\n A Monte Carlo approach to creating a flux image out of a perpendicular deflection field. \n \n Args:\n ri:\n li:\n rs:\n v:\n N: Number of protons in reality\n x (array): Perpendicular deflection field x-... |
def __init__(self, quantizable_layer_type=['Conv2D', 'Linear', 'Conv2DTranspose'], weight_quantize_type='abs_max', activation_quantize_type='moving_average_abs_max', weight_bits=8, activation_bits=8, moving_rate=0.9, weight_preprocess_layer=None, act_preprocess_layer=None, weight_quantize_layer=None, act_quantize_layer... | -3,078,167,706,314,112,500 | The constructor for ImperativeQuantAware.
Args:
quantizable_layer_type(list[str | layer]): List the type of
layers that will be quantized. Default is ['Conv2D', 'Linear'].
weight_quantize_type(str): quantization type for weights,
which supports 'abs_max' and 'channel_wise_abs_max'.
activati... | python/paddle/fluid/contrib/slim/quantization/imperative/qat.py | __init__ | MissPenguin/Paddle | python | def __init__(self, quantizable_layer_type=['Conv2D', 'Linear', 'Conv2DTranspose'], weight_quantize_type='abs_max', activation_quantize_type='moving_average_abs_max', weight_bits=8, activation_bits=8, moving_rate=0.9, weight_preprocess_layer=None, act_preprocess_layer=None, weight_quantize_layer=None, act_quantize_layer... |
def quantize(self, model):
"\n According to weights' and activations' quantization types,\n the model will be added some fake quant ops, such as\n fake_quantize_dequantize_moving_average_abs_max,\n fake_quantize_dequantize_abs_max and so on. At the same time,\n the out_scale value... | 4,487,817,234,187,552,000 | According to weights' and activations' quantization types,
the model will be added some fake quant ops, such as
fake_quantize_dequantize_moving_average_abs_max,
fake_quantize_dequantize_abs_max and so on. At the same time,
the out_scale value of outputs would be calculated.
Args:
model(paddle.nn.Layer): the model ... | python/paddle/fluid/contrib/slim/quantization/imperative/qat.py | quantize | MissPenguin/Paddle | python | def quantize(self, model):
"\n According to weights' and activations' quantization types,\n the model will be added some fake quant ops, such as\n fake_quantize_dequantize_moving_average_abs_max,\n fake_quantize_dequantize_abs_max and so on. At the same time,\n the out_scale value... |
def __init__(self, quantizable_layer_type=['Conv2D', 'Linear', 'Conv2DTranspose'], weight_quantize_type='abs_max', activation_quantize_type='moving_average_abs_max', weight_bits=8, activation_bits=8, moving_rate=0.9, weight_preprocess_layer=None, act_preprocess_layer=None, weight_quantize_layer=None, act_quantize_layer... | -7,740,397,867,562,542,000 | The constructor for ImperativeQuantizeInputs.
Please refer to the args of ImperativeQuantAware. | python/paddle/fluid/contrib/slim/quantization/imperative/qat.py | __init__ | MissPenguin/Paddle | python | def __init__(self, quantizable_layer_type=['Conv2D', 'Linear', 'Conv2DTranspose'], weight_quantize_type='abs_max', activation_quantize_type='moving_average_abs_max', weight_bits=8, activation_bits=8, moving_rate=0.9, weight_preprocess_layer=None, act_preprocess_layer=None, weight_quantize_layer=None, act_quantize_layer... |
def apply(self, model):
'\n Quantize the weights and activations to calculate for specific \n layers.\n\n Args:\n model(paddle.nn.Layer): The target model which would\n calculate the input quantization scale.\n\n Returns:\n None\n '
assert ... | 958,465,973,222,111,000 | Quantize the weights and activations to calculate for specific
layers.
Args:
model(paddle.nn.Layer): The target model which would
calculate the input quantization scale.
Returns:
None | python/paddle/fluid/contrib/slim/quantization/imperative/qat.py | apply | MissPenguin/Paddle | python | def apply(self, model):
'\n Quantize the weights and activations to calculate for specific \n layers.\n\n Args:\n model(paddle.nn.Layer): The target model which would\n calculate the input quantization scale.\n\n Returns:\n None\n '
assert ... |
def __init__(self, moving_rate=0.9):
'\n The constructor for ImperativeQuantizeOutputs.\n\n Args:\n moving_rate(float): The decay coefficient of moving average.\n The default value is 0.9.\n '
super(ImperativeQuantizeOutputs, self).__init__()
se... | 7,053,021,617,716,009,000 | The constructor for ImperativeQuantizeOutputs.
Args:
moving_rate(float): The decay coefficient of moving average.
The default value is 0.9. | python/paddle/fluid/contrib/slim/quantization/imperative/qat.py | __init__ | MissPenguin/Paddle | python | def __init__(self, moving_rate=0.9):
'\n The constructor for ImperativeQuantizeOutputs.\n\n Args:\n moving_rate(float): The decay coefficient of moving average.\n The default value is 0.9.\n '
super(ImperativeQuantizeOutputs, self).__init__()
se... |
def apply(self, model):
'\n Insert the `moving_average_abs_max_scale` layers to calculate the\n output scales for specific layers in the dygraph model.\n\n Args:\n model(paddle.nn.Layer): The target model which would be\n calculate the output quantization scale.\n\n ... | -2,443,531,186,074,505,700 | Insert the `moving_average_abs_max_scale` layers to calculate the
output scales for specific layers in the dygraph model.
Args:
model(paddle.nn.Layer): The target model which would be
calculate the output quantization scale.
Returns:
None | python/paddle/fluid/contrib/slim/quantization/imperative/qat.py | apply | MissPenguin/Paddle | python | def apply(self, model):
'\n Insert the `moving_average_abs_max_scale` layers to calculate the\n output scales for specific layers in the dygraph model.\n\n Args:\n model(paddle.nn.Layer): The target model which would be\n calculate the output quantization scale.\n\n ... |
def save_quantized_model(self, model, path, input_spec=None, **config):
"\n Save the quantized model for the inference.\n\n Args:\n model (Layer): The model to be saved.\n path (str): The path prefix to save model. The format is \n ``dirname/file_prefix`` or ``file... | -5,138,356,119,441,218,000 | Save the quantized model for the inference.
Args:
model (Layer): The model to be saved.
path (str): The path prefix to save model. The format is
``dirname/file_prefix`` or ``file_prefix``.
input_spec (list[InputSpec|Tensor], optional): Describes the input
of the saved model's forward metho... | python/paddle/fluid/contrib/slim/quantization/imperative/qat.py | save_quantized_model | MissPenguin/Paddle | python | def save_quantized_model(self, model, path, input_spec=None, **config):
"\n Save the quantized model for the inference.\n\n Args:\n model (Layer): The model to be saved.\n path (str): The path prefix to save model. The format is \n ``dirname/file_prefix`` or ``file... |
def _is_target_layer(self, layer):
'\n Whether the layer needs to calculate output scales.\n '
flag = False
if isinstance(layer, dygraph.Layer):
if (utils.is_leaf_layer(layer) and (not isinstance(layer, tuple(utils.fake_quant_leaf_layers)))):
flag = True
if isinstan... | 8,147,025,312,163,031,000 | Whether the layer needs to calculate output scales. | python/paddle/fluid/contrib/slim/quantization/imperative/qat.py | _is_target_layer | MissPenguin/Paddle | python | def _is_target_layer(self, layer):
'\n \n '
flag = False
if isinstance(layer, dygraph.Layer):
if (utils.is_leaf_layer(layer) and (not isinstance(layer, tuple(utils.fake_quant_leaf_layers)))):
flag = True
if isinstance(layer, tuple(utils.fake_quant_wrap_layers)):
... |
def _gather_scales(self, program, scope):
'\n Get all scales from fake ops, save them into the corresponding ops\n and delete all moving_average_abs_max_scale ops. \n '
def _gather_input_scale():
target_ops = []
skip_ops = (utils.fake_quantize_dequantize_op_types + ['moving... | 4,573,290,824,300,222,000 | Get all scales from fake ops, save them into the corresponding ops
and delete all moving_average_abs_max_scale ops. | python/paddle/fluid/contrib/slim/quantization/imperative/qat.py | _gather_scales | MissPenguin/Paddle | python | def _gather_scales(self, program, scope):
'\n Get all scales from fake ops, save them into the corresponding ops\n and delete all moving_average_abs_max_scale ops. \n '
def _gather_input_scale():
target_ops = []
skip_ops = (utils.fake_quantize_dequantize_op_types + ['moving... |
def _set_skip_quant_attr(self, program):
'\n Label the skip quantized ops.\n '
for block in program.blocks:
for op in block.ops:
if self._is_skip_quant_op(block, op):
op._set_attr('skip_quant', True) | 1,421,227,798,379,409,000 | Label the skip quantized ops. | python/paddle/fluid/contrib/slim/quantization/imperative/qat.py | _set_skip_quant_attr | MissPenguin/Paddle | python | def _set_skip_quant_attr(self, program):
'\n \n '
for block in program.blocks:
for op in block.ops:
if self._is_skip_quant_op(block, op):
op._set_attr('skip_quant', True) |
def _is_skip_quant_op(self, block, in_op):
'\n The input op should be skipped quantization.\n 1. the type of input op should be conv2d, depthwise_conv2d or matmul\n 2. the previous ops of the input op are not fake_quantize_dequantize ops\n '
target_op_types = ['conv2d', 'depthwise_co... | -4,782,836,982,770,918,000 | The input op should be skipped quantization.
1. the type of input op should be conv2d, depthwise_conv2d or matmul
2. the previous ops of the input op are not fake_quantize_dequantize ops | python/paddle/fluid/contrib/slim/quantization/imperative/qat.py | _is_skip_quant_op | MissPenguin/Paddle | python | def _is_skip_quant_op(self, block, in_op):
'\n The input op should be skipped quantization.\n 1. the type of input op should be conv2d, depthwise_conv2d or matmul\n 2. the previous ops of the input op are not fake_quantize_dequantize ops\n '
target_op_types = ['conv2d', 'depthwise_co... |
def pascal_row(self, n):
" Returns n-th row of Pascal's triangle\n "
result = [1]
(x, numerator) = (1, n)
for denominator in range(1, ((n // 2) + 1)):
x *= numerator
x /= denominator
result.append(x)
numerator -= 1
if ((n & 1) == 0):
result.extend(rever... | -7,095,657,236,191,123,000 | Returns n-th row of Pascal's triangle | info/utils/captcha/captcha.py | pascal_row | rymmx/My_information | python | def pascal_row(self, n):
" \n "
result = [1]
(x, numerator) = (1, n)
for denominator in range(1, ((n // 2) + 1)):
x *= numerator
x /= denominator
result.append(x)
numerator -= 1
if ((n & 1) == 0):
result.extend(reversed(result[:(- 1)]))
else:
... |
def make_bezier(self, n):
' Bezier curves:\n http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Generalization\n '
try:
return self.beziers[n]
except KeyError:
combinations = self.pascal_row((n - 1))
result = []
for t in self.tsequence:
tpowers = ((t... | 7,316,862,772,145,992,000 | Bezier curves:
http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Generalization | info/utils/captcha/captcha.py | make_bezier | rymmx/My_information | python | def make_bezier(self, n):
' Bezier curves:\n http://en.wikipedia.org/wiki/B%C3%A9zier_curve#Generalization\n '
try:
return self.beziers[n]
except KeyError:
combinations = self.pascal_row((n - 1))
result = []
for t in self.tsequence:
tpowers = ((t... |
def captcha(self, path=None, fmt='JPEG'):
"Create a captcha.\n\n Args:\n path: save path, default None.\n fmt: image format, PNG / JPEG.\n Returns:\n A tuple, (name, text, StringIO.value).\n For example:\n ('EXAMPLE_KEY', 'JGW9', '\x89PNG\r\n\... | 5,946,452,396,114,644,000 | Create a captcha.
Args:
path: save path, default None.
fmt: image format, PNG / JPEG.
Returns:
A tuple, (name, text, StringIO.value).
For example:
('EXAMPLE_KEY', 'JGW9', 'PNG
...') | info/utils/captcha/captcha.py | captcha | rymmx/My_information | python | def captcha(self, path=None, fmt='JPEG'):
"Create a captcha.\n\n Args:\n path: save path, default None.\n fmt: image format, PNG / JPEG.\n Returns:\n A tuple, (name, text, StringIO.value).\n For example:\n ('EXAMPLE_KEY', 'JGW9', '\x89PNG\r\n\... |
def parse_requirements(file_):
"Parse a requirements formatted file.\n\n Traverse a string until a delimiter is detected, then split at said\n delimiter, get module name by element index, create a dict consisting of\n module:version, and add dict to list of parsed modules.\n\n Args:\n file_: File... | 8,203,025,767,294,502,000 | Parse a requirements formatted file.
Traverse a string until a delimiter is detected, then split at said
delimiter, get module name by element index, create a dict consisting of
module:version, and add dict to list of parsed modules.
Args:
file_: File to parse.
Raises:
OSerror: If there's any issues accessin... | pipenv/vendor/pipreqs/pipreqs.py | parse_requirements | 0mp/pipenv | python | def parse_requirements(file_):
"Parse a requirements formatted file.\n\n Traverse a string until a delimiter is detected, then split at said\n delimiter, get module name by element index, create a dict consisting of\n module:version, and add dict to list of parsed modules.\n\n Args:\n file_: File... |
def compare_modules(file_, imports):
'Compare modules in a file to imported modules in a project.\n\n Args:\n file_ (str): File to parse for modules to be compared.\n imports (tuple): Modules being imported in the project.\n\n Returns:\n tuple: The modules not imported in the project, but... | 6,199,117,424,864,670,000 | Compare modules in a file to imported modules in a project.
Args:
file_ (str): File to parse for modules to be compared.
imports (tuple): Modules being imported in the project.
Returns:
tuple: The modules not imported in the project, but do exist in the
specified file. | pipenv/vendor/pipreqs/pipreqs.py | compare_modules | 0mp/pipenv | python | def compare_modules(file_, imports):
'Compare modules in a file to imported modules in a project.\n\n Args:\n file_ (str): File to parse for modules to be compared.\n imports (tuple): Modules being imported in the project.\n\n Returns:\n tuple: The modules not imported in the project, but... |
def diff(file_, imports):
'Display the difference between modules in a file and imported modules.'
modules_not_imported = compare_modules(file_, imports)
logging.info('The following modules are in {} but do not seem to be imported: {}'.format(file_, ', '.join((x for x in modules_not_imported)))) | -1,095,672,304,813,857,800 | Display the difference between modules in a file and imported modules. | pipenv/vendor/pipreqs/pipreqs.py | diff | 0mp/pipenv | python | def diff(file_, imports):
modules_not_imported = compare_modules(file_, imports)
logging.info('The following modules are in {} but do not seem to be imported: {}'.format(file_, ', '.join((x for x in modules_not_imported)))) |
def clean(file_, imports):
"Remove modules that aren't imported in project from file."
modules_not_imported = compare_modules(file_, imports)
re_remove = re.compile('|'.join(modules_not_imported))
to_write = []
try:
f = open_func(file_, 'r+')
except OSError:
logging.error('Failed... | -143,540,156,866,477,780 | Remove modules that aren't imported in project from file. | pipenv/vendor/pipreqs/pipreqs.py | clean | 0mp/pipenv | python | def clean(file_, imports):
modules_not_imported = compare_modules(file_, imports)
re_remove = re.compile('|'.join(modules_not_imported))
to_write = []
try:
f = open_func(file_, 'r+')
except OSError:
logging.error('Failed on file: {}'.format(file_))
raise
else:
... |
def dataloader(name):
'\n decorator for registering dataloader functions\n\n Args:\n name: data set name\n\n '
def loader(func):
_dataloaders[name] = func
return func
return loader | 4,858,664,684,579,101,000 | decorator for registering dataloader functions
Args:
name: data set name | local2global_embedding/run.py | dataloader | LJeub/Local2Global_embedding | python | def dataloader(name):
'\n decorator for registering dataloader functions\n\n Args:\n name: data set name\n\n '
def loader(func):
_dataloaders[name] = func
return func
return loader |
def load_data(name):
'\n load data set\n\n Args:\n name: name of data set (one of {names})\n\n Returns:\n largest connected component of data set\n\n '
data = _dataloaders[name]()
data = largest_connected_component(data=data)
data.num_nodes = data.x.shape[0]
return data | 1,143,256,952,060,514,800 | load data set
Args:
name: name of data set (one of {names})
Returns:
largest connected component of data set | local2global_embedding/run.py | load_data | LJeub/Local2Global_embedding | python | def load_data(name):
'\n load data set\n\n Args:\n name: name of data set (one of {names})\n\n Returns:\n largest connected component of data set\n\n '
data = _dataloaders[name]()
data = largest_connected_component(data=data)
data.num_nodes = data.x.shape[0]
return data |
def prepare_patches(output_folder, **kwargs):
'\n initialise patch data if ``output_folder`` does not exist, else load existing patch data\n\n Args:\n output_folder: folder for storing patch data\n **kwargs: arguments passed to :py:func:`~local2global_embedding.patches.create_patch_data`\n\n ... | -6,062,185,444,986,822,000 | initialise patch data if ``output_folder`` does not exist, else load existing patch data
Args:
output_folder: folder for storing patch data
**kwargs: arguments passed to :py:func:`~local2global_embedding.patches.create_patch_data`
Returns:
patch_data, patch_graph | local2global_embedding/run.py | prepare_patches | LJeub/Local2Global_embedding | python | def prepare_patches(output_folder, **kwargs):
'\n initialise patch data if ``output_folder`` does not exist, else load existing patch data\n\n Args:\n output_folder: folder for storing patch data\n **kwargs: arguments passed to :py:func:`~local2global_embedding.patches.create_patch_data`\n\n ... |
def csvlist(input_type=str):
'\n Create an argparse type that parses comma separated lists of type ``input_type``\n\n Args:\n input_type: type of list elements\n\n Returns:\n list parser\n\n '
def make_list(input_str):
return [input_type(s) for s in input_str.split(',')]
m... | -347,569,928,596,149,250 | Create an argparse type that parses comma separated lists of type ``input_type``
Args:
input_type: type of list elements
Returns:
list parser | local2global_embedding/run.py | csvlist | LJeub/Local2Global_embedding | python | def csvlist(input_type=str):
'\n Create an argparse type that parses comma separated lists of type ``input_type``\n\n Args:\n input_type: type of list elements\n\n Returns:\n list parser\n\n '
def make_list(input_str):
return [input_type(s) for s in input_str.split(',')]
m... |
def run(**kwargs):
"\n Run training example.\n\n By default this function writes results to the current working directory. To override this use the ``output``\n keyword argument.\n\n This function reproduces figure 1(a) of [#l2g]_ if called as ``run(dims=[2**i for i in range(1, 8)], plot=True)``.\n\n\n ... | -867,494,552,452,990,000 | Run training example.
By default this function writes results to the current working directory. To override this use the ``output``
keyword argument.
This function reproduces figure 1(a) of [#l2g]_ if called as ``run(dims=[2**i for i in range(1, 8)], plot=True)``.
Keyword Args:
data: Name of data set to load (o... | local2global_embedding/run.py | run | LJeub/Local2Global_embedding | python | def run(**kwargs):
"\n Run training example.\n\n By default this function writes results to the current working directory. To override this use the ``output``\n keyword argument.\n\n This function reproduces figure 1(a) of [#l2g]_ if called as ``run(dims=[2**i for i in range(1, 8)], plot=True)``.\n\n\n ... |
@classmethod
def load(cls, filename, replace=False):
'\n restore results from file\n\n Args:\n filename: input json file\n replace: set the replace attribute\n\n Returns:\n populated ResultsDict\n\n '
self = cls(replace=replace)
with open(filename... | -141,132,625,160,646,660 | restore results from file
Args:
filename: input json file
replace: set the replace attribute
Returns:
populated ResultsDict | local2global_embedding/run.py | load | LJeub/Local2Global_embedding | python | @classmethod
def load(cls, filename, replace=False):
'\n restore results from file\n\n Args:\n filename: input json file\n replace: set the replace attribute\n\n Returns:\n populated ResultsDict\n\n '
self = cls(replace=replace)
with open(filename... |
def save(self, filename):
'\n dump contents to json file\n\n Args:\n filename: output file path\n\n '
with open(filename, 'w') as f:
json.dump(self._data, f) | -7,717,427,815,994,800,000 | dump contents to json file
Args:
filename: output file path | local2global_embedding/run.py | save | LJeub/Local2Global_embedding | python | def save(self, filename):
'\n dump contents to json file\n\n Args:\n filename: output file path\n\n '
with open(filename, 'w') as f:
json.dump(self._data, f) |
def __init__(self, replace=False):
'\n initialise empty ResultsDict\n Args:\n replace: set the replace attribute (default: ``False``)\n '
self._data = {'dims': [], 'auc': [], 'args': []}
self.replace = replace | 7,425,415,623,795,663,000 | initialise empty ResultsDict
Args:
replace: set the replace attribute (default: ``False``) | local2global_embedding/run.py | __init__ | LJeub/Local2Global_embedding | python | def __init__(self, replace=False):
'\n initialise empty ResultsDict\n Args:\n replace: set the replace attribute (default: ``False``)\n '
self._data = {'dims': [], 'auc': [], 'args': []}
self.replace = replace |
def _update_index(self, index, aucs: list, args=None):
'\n update data for a given index\n\n Args:\n index: integer index into data lists\n aucs: new auc values (should be a list)\n args: new args data (optional)\n\n '
if self.replace:
self['auc'][in... | 2,771,856,164,189,648,400 | update data for a given index
Args:
index: integer index into data lists
aucs: new auc values (should be a list)
args: new args data (optional) | local2global_embedding/run.py | _update_index | LJeub/Local2Global_embedding | python | def _update_index(self, index, aucs: list, args=None):
'\n update data for a given index\n\n Args:\n index: integer index into data lists\n aucs: new auc values (should be a list)\n args: new args data (optional)\n\n '
if self.replace:
self['auc'][in... |
def _insert_index(self, index: int, dim: int, aucs: list, args=None):
'\n insert new data at index\n\n Args:\n index: integer index into data lists\n dim: data dimension for index\n aucs: new auc values\n args: new args data (optional)\n '
self['a... | -2,603,589,553,267,202,000 | insert new data at index
Args:
index: integer index into data lists
dim: data dimension for index
aucs: new auc values
args: new args data (optional) | local2global_embedding/run.py | _insert_index | LJeub/Local2Global_embedding | python | def _insert_index(self, index: int, dim: int, aucs: list, args=None):
'\n insert new data at index\n\n Args:\n index: integer index into data lists\n dim: data dimension for index\n aucs: new auc values\n args: new args data (optional)\n '
self['a... |
def update_dim(self, dim, aucs, args=None):
'\n update data for given dimension\n\n Args:\n dim: dimension to update\n aucs: new auc values\n args: new args data (optional)\n\n if ``self.contains_dim(dim) == True``, behaviour depends on the value of\n ``s... | 4,456,085,917,307,313,700 | update data for given dimension
Args:
dim: dimension to update
aucs: new auc values
args: new args data (optional)
if ``self.contains_dim(dim) == True``, behaviour depends on the value of
``self.replace`` | local2global_embedding/run.py | update_dim | LJeub/Local2Global_embedding | python | def update_dim(self, dim, aucs, args=None):
'\n update data for given dimension\n\n Args:\n dim: dimension to update\n aucs: new auc values\n args: new args data (optional)\n\n if ``self.contains_dim(dim) == True``, behaviour depends on the value of\n ``s... |
def max_auc(self, dim=None):
'\n return maximum auc values\n\n Args:\n dim: if ``dim=None``, return list of values for all dimension, else only return maximum value for ``dim``.\n\n '
if (dim is None):
return [max(aucs) for aucs in self['auc']]
else:
index = b... | -4,541,015,127,444,244,500 | return maximum auc values
Args:
dim: if ``dim=None``, return list of values for all dimension, else only return maximum value for ``dim``. | local2global_embedding/run.py | max_auc | LJeub/Local2Global_embedding | python | def max_auc(self, dim=None):
'\n return maximum auc values\n\n Args:\n dim: if ``dim=None``, return list of values for all dimension, else only return maximum value for ``dim``.\n\n '
if (dim is None):
return [max(aucs) for aucs in self['auc']]
else:
index = b... |
def contains_dim(self, dim):
"\n equivalent to ``dim in self['dims']``\n\n "
index = bisect_left(self['dims'], dim)
return ((index < len(self['dims'])) and (self['dims'][index] == dim)) | 4,224,711,043,312,171,000 | equivalent to ``dim in self['dims']`` | local2global_embedding/run.py | contains_dim | LJeub/Local2Global_embedding | python | def contains_dim(self, dim):
"\n \n\n "
index = bisect_left(self['dims'], dim)
return ((index < len(self['dims'])) and (self['dims'][index] == dim)) |
def reduce_to_dims(self, dims):
'\n remove all data for dimensions not in ``dims``\n Args:\n dims: list of dimensions to keep\n\n '
index = [i for (i, d) in enumerate(dims) if self.contains_dim(d)]
for key1 in self._data:
if isinstance(self._data[key1], list):
... | 7,847,196,897,316,981,000 | remove all data for dimensions not in ``dims``
Args:
dims: list of dimensions to keep | local2global_embedding/run.py | reduce_to_dims | LJeub/Local2Global_embedding | python | def reduce_to_dims(self, dims):
'\n remove all data for dimensions not in ``dims``\n Args:\n dims: list of dimensions to keep\n\n '
index = [i for (i, d) in enumerate(dims) if self.contains_dim(d)]
for key1 in self._data:
if isinstance(self._data[key1], list):
... |
def runs(self, dim=None):
'\n return the number of runs\n\n Args:\n dim: if ``dim is None``, return list of number of runs for all dimension, else return number of\n runs for dimension ``dim``.\n\n '
if (dim is None):
return [len(x) for x in self['auc']]
... | 9,131,347,349,148,236,000 | return the number of runs
Args:
dim: if ``dim is None``, return list of number of runs for all dimension, else return number of
runs for dimension ``dim``. | local2global_embedding/run.py | runs | LJeub/Local2Global_embedding | python | def runs(self, dim=None):
'\n return the number of runs\n\n Args:\n dim: if ``dim is None``, return list of number of runs for all dimension, else return number of\n runs for dimension ``dim``.\n\n '
if (dim is None):
return [len(x) for x in self['auc']]
... |
def merge_func(op1, op2):
'Artificial example where a CZ will absorb any merge-able operation.'
for op in [op1, op2]:
if (op.gate == cirq.CZ):
return op
return None | -3,623,384,611,022,538,000 | Artificial example where a CZ will absorb any merge-able operation. | cirq-core/cirq/transformers/transformer_primitives_test.py | merge_func | TripleRD/Cirq | python | def merge_func(op1, op2):
for op in [op1, op2]:
if (op.gate == cirq.CZ):
return op
return None |
@abstractmethod
def positioned(self, aEvent: 'EventObject_a3d70b03') -> None:
'\n is invoked when the database form has been positioned on a data record.\n ' | 3,457,554,679,496,431,000 | is invoked when the database form has been positioned on a data record. | ooobuild/lo/form/x_positioning_listener.py | positioned | Amourspirit/ooo_uno_tmpl | python | @abstractmethod
def positioned(self, aEvent: 'EventObject_a3d70b03') -> None:
'\n \n ' |
def plot_cross_section(self):
' Plot the raw imported nist data '
plt.plot(self.cross_section_x, self.cross_section_y)
plt.title('Cross Section')
plt.xlabel('Angle')
plt.show() | 742,893,952,309,889,700 | Plot the raw imported nist data | model/algorithms/legacy/angular_spread_lorentzian.py | plot_cross_section | surfaceanalytics/inelasticscattering | python | def plot_cross_section(self):
' '
plt.plot(self.cross_section_x, self.cross_section_y)
plt.title('Cross Section')
plt.xlabel('Angle')
plt.show() |
def load_nist_cross_section(self, filename):
' Load nist data file of differential elastic scattering profile.\n Input:\n filename: filename of csv data from nist database\n Returns:\n cross_section_y: given cross section in range -90 to 90 deg '
filepath = ((os.path.dirname(... | -3,489,505,185,187,247,000 | Load nist data file of differential elastic scattering profile.
Input:
filename: filename of csv data from nist database
Returns:
cross_section_y: given cross section in range -90 to 90 deg | model/algorithms/legacy/angular_spread_lorentzian.py | load_nist_cross_section | surfaceanalytics/inelasticscattering | python | def load_nist_cross_section(self, filename):
' Load nist data file of differential elastic scattering profile.\n Input:\n filename: filename of csv data from nist database\n Returns:\n cross_section_y: given cross section in range -90 to 90 deg '
filepath = ((os.path.dirname(... |
def plot_nist(self):
' Plot the raw imported nist data '
plt.plot(self.cross_section_x, self.cross_section_y)
plt.title('NIST Data')
plt.xlabel('Angle')
plt.show() | -2,960,817,490,565,703,700 | Plot the raw imported nist data | model/algorithms/legacy/angular_spread_lorentzian.py | plot_nist | surfaceanalytics/inelasticscattering | python | def plot_nist(self):
' '
plt.plot(self.cross_section_x, self.cross_section_y)
plt.title('NIST Data')
plt.xlabel('Angle')
plt.show() |
def run_convolution(self):
' Run convolution between the nist cross section and a sine curve\n representing initial scattering distribution.\n Returns:\n centered_data: angular distribution spread after each scattering\n event\n '
self.cross_section_y_norm = (self... | 3,539,386,310,495,746,000 | Run convolution between the nist cross section and a sine curve
representing initial scattering distribution.
Returns:
centered_data: angular distribution spread after each scattering
event | model/algorithms/legacy/angular_spread_lorentzian.py | run_convolution | surfaceanalytics/inelasticscattering | python | def run_convolution(self):
' Run convolution between the nist cross section and a sine curve\n representing initial scattering distribution.\n Returns:\n centered_data: angular distribution spread after each scattering\n event\n '
self.cross_section_y_norm = (self... |
def plot_convolution_results(self):
' Plot convolution result to show angular distribution spread after\n each scattering event.'
for n in [0, 1, 2, 5, 10, 20, 50]:
plt.plot(self.emitted_elctn_x, self.centered_data[n], label=str(n))
plt.xticks([(- 90), (- 60), (- 30), 0, 30, 60, 90])
... | 820,424,270,423,335,800 | Plot convolution result to show angular distribution spread after
each scattering event. | model/algorithms/legacy/angular_spread_lorentzian.py | plot_convolution_results | surfaceanalytics/inelasticscattering | python | def plot_convolution_results(self):
' Plot convolution result to show angular distribution spread after\n each scattering event.'
for n in [0, 1, 2, 5, 10, 20, 50]:
plt.plot(self.emitted_elctn_x, self.centered_data[n], label=str(n))
plt.xticks([(- 90), (- 60), (- 30), 0, 30, 60, 90])
... |
def limit_by_acceptance_angle(self):
' Limit the data to the acceptance angle of the analyser '
self.angle_limited = self._limit_by_constant_angle(self.centered_data, self.acceptance_angle) | -5,836,222,258,590,825,000 | Limit the data to the acceptance angle of the analyser | model/algorithms/legacy/angular_spread_lorentzian.py | limit_by_acceptance_angle | surfaceanalytics/inelasticscattering | python | def limit_by_acceptance_angle(self):
' '
self.angle_limited = self._limit_by_constant_angle(self.centered_data, self.acceptance_angle) |
def plot_angle_limited(self):
' Plot the convolution results only in the accepted angle range'
for n in [0, 1, 2, 5, 10, 20, 50]:
plt.plot(self.emitted_elctn_x, self.angle_limited[n], label=str(n))
plt.xticks([(- 90), (- 60), (- 30), 0, 30, 60, 90])
plt.xlabel('theta (degrees)')
... | 5,782,635,014,783,489,000 | Plot the convolution results only in the accepted angle range | model/algorithms/legacy/angular_spread_lorentzian.py | plot_angle_limited | surfaceanalytics/inelasticscattering | python | def plot_angle_limited(self):
' '
for n in [0, 1, 2, 5, 10, 20, 50]:
plt.plot(self.emitted_elctn_x, self.angle_limited[n], label=str(n))
plt.xticks([(- 90), (- 60), (- 30), 0, 30, 60, 90])
plt.xlabel('theta (degrees)')
plt.ylabel('Intensity (a.u.)')
plt.title('Intensity d... |
def calc_area_under_curve(self):
' Calculate area under each curve within acceptance angle,\n represents intensity that the detector sees'
sin = np.absolute(np.sin(((np.arange((- 90), 90, 1) * np.pi) / 180)))
angle_integrated = ((self.angle_limited * sin) * np.pi)
self.area_sum = np.sum(angle_int... | -5,156,297,809,877,121,000 | Calculate area under each curve within acceptance angle,
represents intensity that the detector sees | model/algorithms/legacy/angular_spread_lorentzian.py | calc_area_under_curve | surfaceanalytics/inelasticscattering | python | def calc_area_under_curve(self):
' Calculate area under each curve within acceptance angle,\n represents intensity that the detector sees'
sin = np.absolute(np.sin(((np.arange((- 90), 90, 1) * np.pi) / 180)))
angle_integrated = ((self.angle_limited * sin) * np.pi)
self.area_sum = np.sum(angle_int... |
def plot_area_under_curve(self):
' Plot area under curve per scattering event / iteration '
plt.plot(self.area_sum)
plt.title((((('area under curve \n (Energy: ' + str(self.energy)) + ', Acceptance Angle: ') + str(self.acceptance_angle)) + ')'))
plt.xlabel('No. of iterations')
plt.ylabel('Intensity ... | -2,997,363,733,917,999,000 | Plot area under curve per scattering event / iteration | model/algorithms/legacy/angular_spread_lorentzian.py | plot_area_under_curve | surfaceanalytics/inelasticscattering | python | def plot_area_under_curve(self):
' '
plt.plot(self.area_sum)
plt.title((((('area under curve \n (Energy: ' + str(self.energy)) + ', Acceptance Angle: ') + str(self.acceptance_angle)) + ')'))
plt.xlabel('No. of iterations')
plt.ylabel('Intensity a.u.')
plt.show() |
def calc_area_ratio(self):
' Calculate the change in area ratio between iteration n and n-1'
self.area_ratio_list = self._area_ratio_change(self.area_sum)
return self.area_ratio_list | -6,407,582,401,457,896,000 | Calculate the change in area ratio between iteration n and n-1 | model/algorithms/legacy/angular_spread_lorentzian.py | calc_area_ratio | surfaceanalytics/inelasticscattering | python | def calc_area_ratio(self):
' '
self.area_ratio_list = self._area_ratio_change(self.area_sum)
return self.area_ratio_list |
def plot_area_ratio(self):
' Plot the change in area ratio per iteration '
plt.plot(self.area_ratio_list)
plt.title((((('Intensity ratio change per iteration \n (Energy: ' + str(self.energy)) + ' eV, Acceptance Angle: ') + str(self.acceptance_angle)) + ')'))
plt.xlabel('Iterations')
plt.ylabel('Area... | -7,336,764,495,966,653,000 | Plot the change in area ratio per iteration | model/algorithms/legacy/angular_spread_lorentzian.py | plot_area_ratio | surfaceanalytics/inelasticscattering | python | def plot_area_ratio(self):
' '
plt.plot(self.area_ratio_list)
plt.title((((('Intensity ratio change per iteration \n (Energy: ' + str(self.energy)) + ' eV, Acceptance Angle: ') + str(self.acceptance_angle)) + ')'))
plt.xlabel('Iterations')
plt.ylabel('Area Ratio between iterations')
plt.show() |
def __eq__(self, *args):
' x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y '
pass | 2,144,965,521,805,394,200 | x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y | release/stubs.min/Autodesk/Revit/DB/__init___parts/Domain.py | __eq__ | BCSharp/ironpython-stubs | python | def __eq__(self, *args):
' '
pass |
def __format__(self, *args):
' __format__(formattable: IFormattable,format: str) -> str '
pass | -4,894,195,495,142,889,000 | __format__(formattable: IFormattable,format: str) -> str | release/stubs.min/Autodesk/Revit/DB/__init___parts/Domain.py | __format__ | BCSharp/ironpython-stubs | python | def __format__(self, *args):
' '
pass |
def __init__(self, *args):
' x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature '
pass | -90,002,593,062,007,400 | x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature | release/stubs.min/Autodesk/Revit/DB/__init___parts/Domain.py | __init__ | BCSharp/ironpython-stubs | python | def __init__(self, *args):
' '
pass |
def run(process, *args, **inputs):
'\n Run the process with the supplied inputs in a local runner that will block until the process is completed.\n The return value will be the results of the completed process\n\n :param process: the process class or workfunction to run\n :param inputs: the inputs to be... | -9,197,858,556,187,132,000 | Run the process with the supplied inputs in a local runner that will block until the process is completed.
The return value will be the results of the completed process
:param process: the process class or workfunction to run
:param inputs: the inputs to be passed to the process
:return: the outputs of the process | aiida/work/launch.py | run | JuDFTteam/aiida_core | python | def run(process, *args, **inputs):
'\n Run the process with the supplied inputs in a local runner that will block until the process is completed.\n The return value will be the results of the completed process\n\n :param process: the process class or workfunction to run\n :param inputs: the inputs to be... |
def run_get_node(process, *args, **inputs):
'\n Run the process with the supplied inputs in a local runner that will block until the process is completed.\n The return value will be the results of the completed process\n\n :param process: the process class or workfunction to run\n :param inputs: the inp... | 282,945,995,080,449,020 | Run the process with the supplied inputs in a local runner that will block until the process is completed.
The return value will be the results of the completed process
:param process: the process class or workfunction to run
:param inputs: the inputs to be passed to the process
:return: tuple of the outputs of the pr... | aiida/work/launch.py | run_get_node | JuDFTteam/aiida_core | python | def run_get_node(process, *args, **inputs):
'\n Run the process with the supplied inputs in a local runner that will block until the process is completed.\n The return value will be the results of the completed process\n\n :param process: the process class or workfunction to run\n :param inputs: the inp... |
def run_get_pid(process, *args, **inputs):
'\n Run the process with the supplied inputs in a local runner that will block until the process is completed.\n The return value will be the results of the completed process\n\n :param process: the process class or workfunction to run\n :param inputs: the inpu... | -3,261,614,733,050,708,500 | Run the process with the supplied inputs in a local runner that will block until the process is completed.
The return value will be the results of the completed process
:param process: the process class or workfunction to run
:param inputs: the inputs to be passed to the process
:return: tuple of the outputs of the pr... | aiida/work/launch.py | run_get_pid | JuDFTteam/aiida_core | python | def run_get_pid(process, *args, **inputs):
'\n Run the process with the supplied inputs in a local runner that will block until the process is completed.\n The return value will be the results of the completed process\n\n :param process: the process class or workfunction to run\n :param inputs: the inpu... |
def submit(process, **inputs):
'\n Submit the process with the supplied inputs to the daemon runners immediately returning control to\n the interpreter. The return value will be the calculation node of the submitted process.\n\n :param process: the process class to submit\n :param inputs: the inputs to ... | 5,516,377,438,263,609,000 | Submit the process with the supplied inputs to the daemon runners immediately returning control to
the interpreter. The return value will be the calculation node of the submitted process.
:param process: the process class to submit
:param inputs: the inputs to be passed to the process
:return: the calculation node of ... | aiida/work/launch.py | submit | JuDFTteam/aiida_core | python | def submit(process, **inputs):
'\n Submit the process with the supplied inputs to the daemon runners immediately returning control to\n the interpreter. The return value will be the calculation node of the submitted process.\n\n :param process: the process class to submit\n :param inputs: the inputs to ... |
def __init__(self, env: gym.Env, combined_observation_space: Tuple[(Tuple[(int, int, int)], int)], lr: float, gamma: float, epsilon: float, epsilon_decay: float, target_update_interval: int=100, log_wandb: bool=False, replay_buffer: Optional[ReplayBuffer]=None, fc_layers: Optional[List[int]]=None, conv_layers: Optional... | -1,705,906,103,581,523,700 | Construct a new 'Deep Q-Network' object.
:param env: The environment of the game
:param lr: The learning rate of the agent
:param gamma: The amount of weight it gives to future rewards in the value function
:param epsilon: The probability where we do not go with the “greedy” action with the highest Q-value but rather ... | RL/Snake-DQN/model/dqn_engineered.py | __init__ | kiritowu/Deep-Learning | python | def __init__(self, env: gym.Env, combined_observation_space: Tuple[(Tuple[(int, int, int)], int)], lr: float, gamma: float, epsilon: float, epsilon_decay: float, target_update_interval: int=100, log_wandb: bool=False, replay_buffer: Optional[ReplayBuffer]=None, fc_layers: Optional[List[int]]=None, conv_layers: Optional... |
def build_wrapper(img_size: types_of_loco.input_img_size=28, channels: int=3, model_name: str='model1', optimizer: Optimizer=SGD()) -> Union[(ModelBuilder, pytorch_builder.PytorchModelBuilder)]:
'\n モデル生成をする関数を返す\n 交差検証をかける際のラッパーとして使う\n :param img_size:\n :param channels:\n :param model_name:\n :p... | -802,269,240,548,085,500 | モデル生成をする関数を返す
交差検証をかける際のラッパーとして使う
:param img_size:
:param channels:
:param model_name:
:param optimizer:
:return: | network_model/model_builder.py | build_wrapper | Tetuwo181/ModelLearner | python | def build_wrapper(img_size: types_of_loco.input_img_size=28, channels: int=3, model_name: str='model1', optimizer: Optimizer=SGD()) -> Union[(ModelBuilder, pytorch_builder.PytorchModelBuilder)]:
'\n モデル生成をする関数を返す\n 交差検証をかける際のラッパーとして使う\n :param img_size:\n :param channels:\n :param model_name:\n :p... |
def builder_of_generator(class_num: int, channels: int=1, optimizer: Optimizer=SGD()):
'\n Ganのgenerator部を作成する\n :param class_num\n :param channels:色の出力変数(白黒画像なら1)\n :param optimizer: 2次元の畳み込みウィンドウの幅と高さ 整数なら縦横比同じに\n :return: discriminator部のモデル\n '
return builder(class_n... | -6,910,396,911,601,175,000 | Ganのgenerator部を作成する
:param class_num
:param channels:色の出力変数(白黒画像なら1)
:param optimizer: 2次元の畳み込みウィンドウの幅と高さ 整数なら縦横比同じに
:return: discriminator部のモデル | network_model/model_builder.py | builder_of_generator | Tetuwo181/ModelLearner | python | def builder_of_generator(class_num: int, channels: int=1, optimizer: Optimizer=SGD()):
'\n Ganのgenerator部を作成する\n :param class_num\n :param channels:色の出力変数(白黒画像なら1)\n :param optimizer: 2次元の畳み込みウィンドウの幅と高さ 整数なら縦横比同じに\n :return: discriminator部のモデル\n '
return builder(class_n... |
def connection_made(self, transport):
'asyncio callback when a connection is opened.'
assert (not self._transport)
logger.debug(('Connected & Listening: %s:%d' % (self.dstaddr, self.dstport)))
self._transport = transport
if self.on_connection_send_msg:
self.send_message(self.on_connection_se... | 7,884,721,591,143,972,000 | asyncio callback when a connection is opened. | test/functional/test_framework/mininode.py | connection_made | BitcoinSN/BitcoinSN | python | def connection_made(self, transport):
assert (not self._transport)
logger.debug(('Connected & Listening: %s:%d' % (self.dstaddr, self.dstport)))
self._transport = transport
if self.on_connection_send_msg:
self.send_message(self.on_connection_send_msg)
self.on_connection_send_msg = N... |
def connection_lost(self, exc):
'asyncio callback when a connection is closed.'
if exc:
logger.warning('Connection lost to {}:{} due to {}'.format(self.dstaddr, self.dstport, exc))
else:
logger.debug(('Closed connection to: %s:%d' % (self.dstaddr, self.dstport)))
self._transport = None
... | -3,005,130,395,724,729 | asyncio callback when a connection is closed. | test/functional/test_framework/mininode.py | connection_lost | BitcoinSN/BitcoinSN | python | def connection_lost(self, exc):
if exc:
logger.warning('Connection lost to {}:{} due to {}'.format(self.dstaddr, self.dstport, exc))
else:
logger.debug(('Closed connection to: %s:%d' % (self.dstaddr, self.dstport)))
self._transport = None
self.recvbuf = b
self.on_close() |
def data_received(self, t):
'asyncio callback when data is read from the socket.'
if (len(t) > 0):
self.recvbuf += t
self._on_data() | 993,073,361,923,927,400 | asyncio callback when data is read from the socket. | test/functional/test_framework/mininode.py | data_received | BitcoinSN/BitcoinSN | python | def data_received(self, t):
if (len(t) > 0):
self.recvbuf += t
self._on_data() |
def _on_data(self):
'Try to read P2P messages from the recv buffer.\n\n This method reads data from the buffer in a loop. It deserializes,\n parses and verifies the P2P header, then passes the P2P payload to\n the on_message callback for processing.'
try:
while True:
if ... | -8,964,093,991,799,058,000 | Try to read P2P messages from the recv buffer.
This method reads data from the buffer in a loop. It deserializes,
parses and verifies the P2P header, then passes the P2P payload to
the on_message callback for processing. | test/functional/test_framework/mininode.py | _on_data | BitcoinSN/BitcoinSN | python | def _on_data(self):
'Try to read P2P messages from the recv buffer.\n\n This method reads data from the buffer in a loop. It deserializes,\n parses and verifies the P2P header, then passes the P2P payload to\n the on_message callback for processing.'
try:
while True:
if ... |
def on_message(self, message):
'Callback for processing a P2P payload. Must be overridden by derived class.'
raise NotImplementedError | -7,141,849,742,548,494,000 | Callback for processing a P2P payload. Must be overridden by derived class. | test/functional/test_framework/mininode.py | on_message | BitcoinSN/BitcoinSN | python | def on_message(self, message):
raise NotImplementedError |
def send_message(self, message):
'Send a P2P message over the socket.\n\n This method takes a P2P payload, builds the P2P header and adds\n the message to the send buffer to be sent over the socket.'
if (not self.is_connected):
raise IOError('Not connected')
self._log_message('send', m... | -2,728,624,306,352,936,000 | Send a P2P message over the socket.
This method takes a P2P payload, builds the P2P header and adds
the message to the send buffer to be sent over the socket. | test/functional/test_framework/mininode.py | send_message | BitcoinSN/BitcoinSN | python | def send_message(self, message):
'Send a P2P message over the socket.\n\n This method takes a P2P payload, builds the P2P header and adds\n the message to the send buffer to be sent over the socket.'
if (not self.is_connected):
raise IOError('Not connected')
self._log_message('send', m... |
def _build_message(self, message):
'Build a serialized P2P message'
command = message.command
data = message.serialize()
tmsg = MAGIC_BYTES[self.network]
tmsg += command
tmsg += (b'\x00' * (12 - len(command)))
tmsg += struct.pack('<I', len(data))
th = sha256(data)
h = sha256(th)
... | -7,292,992,019,461,254,000 | Build a serialized P2P message | test/functional/test_framework/mininode.py | _build_message | BitcoinSN/BitcoinSN | python | def _build_message(self, message):
command = message.command
data = message.serialize()
tmsg = MAGIC_BYTES[self.network]
tmsg += command
tmsg += (b'\x00' * (12 - len(command)))
tmsg += struct.pack('<I', len(data))
th = sha256(data)
h = sha256(th)
tmsg += h[:4]
tmsg += data
... |
def _log_message(self, direction, msg):
'Logs a message being sent or received over the connection.'
if (direction == 'send'):
log_message = 'Send message to '
elif (direction == 'receive'):
log_message = 'Received message from '
log_message += ('%s:%d: %s' % (self.dstaddr, self.dstport,... | 7,418,905,072,498,204,000 | Logs a message being sent or received over the connection. | test/functional/test_framework/mininode.py | _log_message | BitcoinSN/BitcoinSN | python | def _log_message(self, direction, msg):
if (direction == 'send'):
log_message = 'Send message to '
elif (direction == 'receive'):
log_message = 'Received message from '
log_message += ('%s:%d: %s' % (self.dstaddr, self.dstport, repr(msg)[:500]))
if (len(log_message) > 500):
... |
def on_message(self, message):
'Receive message and dispatch message to appropriate callback.\n\n We keep a count of how many of each message type has been received\n and the most recent message of each type.'
with mininode_lock:
try:
command = message.command.decode('ascii')
... | -6,178,374,556,390,762,000 | Receive message and dispatch message to appropriate callback.
We keep a count of how many of each message type has been received
and the most recent message of each type. | test/functional/test_framework/mininode.py | on_message | BitcoinSN/BitcoinSN | python | def on_message(self, message):
'Receive message and dispatch message to appropriate callback.\n\n We keep a count of how many of each message type has been received\n and the most recent message of each type.'
with mininode_lock:
try:
command = message.command.decode('ascii')
... |
def wait_for_getdata(self, timeout=60):
'Waits for a getdata message.\n\n Receiving any getdata message will satisfy the predicate. the last_message["getdata"]\n value must be explicitly cleared before calling this method, or this will return\n immediately with success. TODO: change this method... | -9,031,565,317,313,411,000 | Waits for a getdata message.
Receiving any getdata message will satisfy the predicate. the last_message["getdata"]
value must be explicitly cleared before calling this method, or this will return
immediately with success. TODO: change this method to take a hash value and only
return true if the correct block/tx has be... | test/functional/test_framework/mininode.py | wait_for_getdata | BitcoinSN/BitcoinSN | python | def wait_for_getdata(self, timeout=60):
'Waits for a getdata message.\n\n Receiving any getdata message will satisfy the predicate. the last_message["getdata"]\n value must be explicitly cleared before calling this method, or this will return\n immediately with success. TODO: change this method... |
def wait_for_getheaders(self, timeout=60):
'Waits for a getheaders message.\n\n Receiving any getheaders message will satisfy the predicate. the last_message["getheaders"]\n value must be explicitly cleared before calling this method, or this will return\n immediately with success. TODO: change... | -8,589,494,662,717,943,000 | Waits for a getheaders message.
Receiving any getheaders message will satisfy the predicate. the last_message["getheaders"]
value must be explicitly cleared before calling this method, or this will return
immediately with success. TODO: change this method to take a hash value and only
return true if the correct block ... | test/functional/test_framework/mininode.py | wait_for_getheaders | BitcoinSN/BitcoinSN | python | def wait_for_getheaders(self, timeout=60):
'Waits for a getheaders message.\n\n Receiving any getheaders message will satisfy the predicate. the last_message["getheaders"]\n value must be explicitly cleared before calling this method, or this will return\n immediately with success. TODO: change... |
def wait_for_inv(self, expected_inv, timeout=60):
'Waits for an INV message and checks that the first inv object in the message was as expected.'
if (len(expected_inv) > 1):
raise NotImplementedError('wait_for_inv() will only verify the first inv object')
test_function = (lambda : (self.last_message... | -3,942,258,822,374,831,600 | Waits for an INV message and checks that the first inv object in the message was as expected. | test/functional/test_framework/mininode.py | wait_for_inv | BitcoinSN/BitcoinSN | python | def wait_for_inv(self, expected_inv, timeout=60):
if (len(expected_inv) > 1):
raise NotImplementedError('wait_for_inv() will only verify the first inv object')
test_function = (lambda : (self.last_message.get('inv') and (self.last_message['inv'].inv[0].type == expected_inv[0].type) and (self.last_m... |
def run(self):
'Start the network thread.'
self.network_event_loop.run_forever() | 9,011,189,419,497,338,000 | Start the network thread. | test/functional/test_framework/mininode.py | run | BitcoinSN/BitcoinSN | python | def run(self):
self.network_event_loop.run_forever() |
def close(self, timeout=10):
'Close the connections and network event loop.'
self.network_event_loop.call_soon_threadsafe(self.network_event_loop.stop)
wait_until((lambda : (not self.network_event_loop.is_running())), timeout=timeout)
self.network_event_loop.close()
self.join(timeout) | -5,017,505,405,062,556,000 | Close the connections and network event loop. | test/functional/test_framework/mininode.py | close | BitcoinSN/BitcoinSN | python | def close(self, timeout=10):
self.network_event_loop.call_soon_threadsafe(self.network_event_loop.stop)
wait_until((lambda : (not self.network_event_loop.is_running())), timeout=timeout)
self.network_event_loop.close()
self.join(timeout) |
def on_getdata(self, message):
'Check for the tx/block in our stores and if found, reply with an inv message.'
for inv in message.inv:
self.getdata_requests.append(inv.hash)
if (((inv.type & MSG_TYPE_MASK) == MSG_TX) and (inv.hash in self.tx_store.keys())):
self.send_message(msg_tx(s... | -3,934,145,937,144,671,000 | Check for the tx/block in our stores and if found, reply with an inv message. | test/functional/test_framework/mininode.py | on_getdata | BitcoinSN/BitcoinSN | python | def on_getdata(self, message):
for inv in message.inv:
self.getdata_requests.append(inv.hash)
if (((inv.type & MSG_TYPE_MASK) == MSG_TX) and (inv.hash in self.tx_store.keys())):
self.send_message(msg_tx(self.tx_store[inv.hash]))
elif (((inv.type & MSG_TYPE_MASK) == MSG_BLOCK... |
def on_getheaders(self, message):
'Search back through our block store for the locator, and reply with a headers message if found.'
(locator, hash_stop) = (message.locator, message.hashstop)
if (not self.block_store):
return
headers_list = [self.block_store[self.last_block_hash]]
maxheaders ... | 6,135,390,170,369,099,000 | Search back through our block store for the locator, and reply with a headers message if found. | test/functional/test_framework/mininode.py | on_getheaders | BitcoinSN/BitcoinSN | python | def on_getheaders(self, message):
(locator, hash_stop) = (message.locator, message.hashstop)
if (not self.block_store):
return
headers_list = [self.block_store[self.last_block_hash]]
maxheaders = 2000
while (headers_list[(- 1)].sha256 not in locator.vHave):
prev_block_hash = hea... |
def on_reject(self, message):
'Store reject reason and code for testing.'
self.reject_code_received = message.code
self.reject_reason_received = message.reason | 2,698,813,715,860,074,500 | Store reject reason and code for testing. | test/functional/test_framework/mininode.py | on_reject | BitcoinSN/BitcoinSN | python | def on_reject(self, message):
self.reject_code_received = message.code
self.reject_reason_received = message.reason |
def send_blocks_and_test(self, blocks, rpc, success=True, request_block=True, reject_code=None, reject_reason=None, timeout=60):
"Send blocks to test node and test whether the tip advances.\n\n - add all blocks to our block_store\n - send a headers message for the final block\n - the on_geth... | -2,911,765,054,968,182,000 | Send blocks to test node and test whether the tip advances.
- add all blocks to our block_store
- send a headers message for the final block
- the on_getheaders handler will ensure that any getheaders are responded to
- if request_block is True: wait for getdata for each of the blocks. The on_getdata handler will
en... | test/functional/test_framework/mininode.py | send_blocks_and_test | BitcoinSN/BitcoinSN | python | def send_blocks_and_test(self, blocks, rpc, success=True, request_block=True, reject_code=None, reject_reason=None, timeout=60):
"Send blocks to test node and test whether the tip advances.\n\n - add all blocks to our block_store\n - send a headers message for the final block\n - the on_geth... |
def send_txs_and_test(self, txs, rpc, success=True, expect_disconnect=False, reject_code=None, reject_reason=None):
"Send txs to test node and test whether they're accepted to the mempool.\n\n - add all txs to our tx_store\n - send tx messages for all txs\n - if success is True/False: assert... | -4,979,453,914,077,187,000 | Send txs to test node and test whether they're accepted to the mempool.
- add all txs to our tx_store
- send tx messages for all txs
- if success is True/False: assert that the txs are/are not accepted to the mempool
- if expect_disconnect is True: Skip the sync with ping
- if reject_code and reject_reason are set: as... | test/functional/test_framework/mininode.py | send_txs_and_test | BitcoinSN/BitcoinSN | python | def send_txs_and_test(self, txs, rpc, success=True, expect_disconnect=False, reject_code=None, reject_reason=None):
"Send txs to test node and test whether they're accepted to the mempool.\n\n - add all txs to our tx_store\n - send tx messages for all txs\n - if success is True/False: assert... |
def run(self, s):
'\n :param s: input in string format\n :return: solution flag\n '
(_, buses) = s.split('\n')
buses = [((k % int(n)), int(n)) for (k, n) in enumerate(buses.split(',')) if (n != 'x')]
(_, base) = buses[0]
multiplier = base
for (rest, b) in buses[1:]:
... | 33,742,449,778,658,504 | :param s: input in string format
:return: solution flag | day-13/part-2/coco.py | run | david-ds/adventofcode-2020 | python | def run(self, s):
'\n :param s: input in string format\n :return: solution flag\n '
(_, buses) = s.split('\n')
buses = [((k % int(n)), int(n)) for (k, n) in enumerate(buses.split(',')) if (n != 'x')]
(_, base) = buses[0]
multiplier = base
for (rest, b) in buses[1:]:
... |
def assertDtypesMatch(self, x, y, *, canonicalize_dtypes=True):
'Compares dtypes across JAX and TF dtypes. Overrides super method.'
def to_numpy_dtype(dt):
return (dt if isinstance(dt, np.dtype) else dt.as_numpy_dtype)
if ((not config.FLAGS.jax_enable_x64) and canonicalize_dtypes):
self.ass... | 7,438,900,400,489,860,000 | Compares dtypes across JAX and TF dtypes. Overrides super method. | jax/experimental/jax2tf/tests/tf_test_util.py | assertDtypesMatch | BuddenD/jax | python | def assertDtypesMatch(self, x, y, *, canonicalize_dtypes=True):
def to_numpy_dtype(dt):
return (dt if isinstance(dt, np.dtype) else dt.as_numpy_dtype)
if ((not config.FLAGS.jax_enable_x64) and canonicalize_dtypes):
self.assertEqual(dtypes.canonicalize_dtype(to_numpy_dtype(jtu._dtype(x))), ... |
def ConvertAndCompare(self, func_jax: Callable, *args, with_function: bool=False, atol=None, rtol=None) -> Tuple[(Any, Any)]:
'Compares jax_func(*args) with convert(jax_func)(*args).'
func_tf = jax2tf.convert(func_jax)
if with_function:
func_tf = tf.function(func_tf)
res_jax = func_jax(*args)
... | 6,940,974,501,894,013,000 | Compares jax_func(*args) with convert(jax_func)(*args). | jax/experimental/jax2tf/tests/tf_test_util.py | ConvertAndCompare | BuddenD/jax | python | def ConvertAndCompare(self, func_jax: Callable, *args, with_function: bool=False, atol=None, rtol=None) -> Tuple[(Any, Any)]:
func_tf = jax2tf.convert(func_jax)
if with_function:
func_tf = tf.function(func_tf)
res_jax = func_jax(*args)
res_tf = func_tf(*args)
self.assertAllClose(res_jax... |
def _run_one_off_job(self):
'Runs the one-off MapReduce job.'
job_id = activity_jobs_one_off.ActivityContributorsSummaryOneOffJob.create_new()
activity_jobs_one_off.ActivityContributorsSummaryOneOffJob.enqueue(job_id)
self.assertEqual(self.count_jobs_in_mapreduce_taskqueue(taskqueue_services.QUEUE_NAME_... | -6,288,681,077,837,944,000 | Runs the one-off MapReduce job. | core/domain/activity_jobs_one_off_test.py | _run_one_off_job | AnanyaNegi/oppia | python | def _run_one_off_job(self):
job_id = activity_jobs_one_off.ActivityContributorsSummaryOneOffJob.create_new()
activity_jobs_one_off.ActivityContributorsSummaryOneOffJob.enqueue(job_id)
self.assertEqual(self.count_jobs_in_mapreduce_taskqueue(taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 1)
self.proces... |
def _run_one_off_job(self):
'Runs the one-off MapReduce job.'
job_id = activity_jobs_one_off.AuditContributorsOneOffJob.create_new()
activity_jobs_one_off.AuditContributorsOneOffJob.enqueue(job_id)
self.assertEqual(self.count_jobs_in_mapreduce_taskqueue(taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 1)
... | 5,256,973,170,232,315,000 | Runs the one-off MapReduce job. | core/domain/activity_jobs_one_off_test.py | _run_one_off_job | AnanyaNegi/oppia | python | def _run_one_off_job(self):
job_id = activity_jobs_one_off.AuditContributorsOneOffJob.create_new()
activity_jobs_one_off.AuditContributorsOneOffJob.enqueue(job_id)
self.assertEqual(self.count_jobs_in_mapreduce_taskqueue(taskqueue_services.QUEUE_NAME_ONE_OFF_JOBS), 1)
self.process_and_flush_pending_... |
def _trusted_commit(self, committer_id, commit_type, commit_message, commit_cmds):
'Record the event to the commit log after the model commit.\n\n Note that this overrides the superclass method.\n\n Args:\n committer_id: str. The user_id of the user who committed the\n change... | -3,582,706,145,878,410 | Record the event to the commit log after the model commit.
Note that this overrides the superclass method.
Args:
committer_id: str. The user_id of the user who committed the
change.
commit_type: str. The type of commit. Possible values are in
core.storage.base_models.COMMIT_TYPE_CHOICES.
c... | core/domain/activity_jobs_one_off_test.py | _trusted_commit | AnanyaNegi/oppia | python | def _trusted_commit(self, committer_id, commit_type, commit_message, commit_cmds):
'Record the event to the commit log after the model commit.\n\n Note that this overrides the superclass method.\n\n Args:\n committer_id: str. The user_id of the user who committed the\n change... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.