code stringlengths 101 5.91M |
|---|
def parse_path_value(next):
token = next()
value = token[0]
if value:
if ((value[:1] == "'") or (value[:1] == '"')):
return value[1:(- 1)]
try:
return int(value)
except ValueError:
pass
elif token[1].isdigit():
return int(token[1])
... |
def start_of_bilou_slot(tags, i):
if (i == 0):
return (tags[i] != OUTSIDE)
if (tags[i] == OUTSIDE):
return False
if tags[i].startswith(BEGINNING_PREFIX):
return True
if tags[i].startswith(UNIT_PREFIX):
return True
if tags[(i - 1)].startswith(UNIT_PREFIX):
retu... |
def gdb_function_value_to_unicode(function):
(function)
def wrapper(self, string, *args, **kwargs):
if isinstance(string, gdb.Value):
string = string.string()
return function(self, string, *args, **kwargs)
return wrapper |
def make_read_B(sdfg, state, vtype):
dtype = vtype.base_type
mem_veclen = (64 // dtype.bytes)
mtype = dace.vector(dtype, mem_veclen)
(entry, exit) = state.add_map('read_B', {'n0': '0:N//TN', 'm0': '0:M//TM', 'k': '0:K', 'm1': f'0:TM//{mem_veclen}'}, schedule=dace.ScheduleType.FPGA_Device)
mem = stat... |
def dot_distance_between_points(unit_vector, point, reference_point):
return np.dot(unit_vector, (np.array(point) - np.array(reference_point))) |
def unfreeze_weights(*models):
for model in models:
for k in model.parameters():
k.requires_grad = True |
def getWeight(shape, name=''):
with tf.variable_scope('weights'):
initializer = tf.contrib.layers.xavier_initializer()
W = tf.get_variable(('weight' + name), shape=shape, initializer=initializer)
return W |
def test_case70():
url = (brokerIp + '/ngsi-ld/v1/entityOperations/upsert')
headers = {'Content-Type': 'application/json', 'Link': '<{{link}}>; rel=" type="application/ld+json"'}
r = requests.post(url, data=json.dumps(ld_data.subdata60), headers=headers)
print(r.content)
url = (brokerIp + '/ngsi-ld/... |
.skip
def test_tensordot_22():
(device=dace.dtypes.DeviceType.GPU)
def tensordot_2a(A: dace.float32[(3, 3, 3, 3, 3, 3)], B: dace.float32[(3, 3, 3, 3, 3, 3)]):
return np.tensordot(A, B, axes=([0, 3], [4, 2]), out_axes=[7, 6, 5, 4, 3, 2, 1, 0])
A = np.arange((3 ** 6), dtype=np.float32).reshape(3, 3, 3... |
def pythran_type(Ty, ptype='ndarray'):
if Ty.is_buffer:
(ndim, dtype) = (Ty.ndim, Ty.dtype)
if isinstance(dtype, CStructOrUnionType):
ctype = dtype.cname
elif isinstance(dtype, CType):
ctype = dtype.sign_and_name()
elif isinstance(dtype, CTypedefType):
... |
def reset_config(cfg, args):
if args.root:
cfg.data.root = args.root
if args.sources:
cfg.data.sources = args.sources
if args.targets:
cfg.data.targets = args.targets
if args.transforms:
cfg.data.transforms = args.transforms |
_module()
class CBDNet(BaseNet):
def __init__(self, io_channels=3, estimate_channels=32, nlevel_denoise=3, nf_base_denoise=64, nf_gr_denoise=2, nl_base_denoise=1, nl_gr_denoise=2, down_denoise='avepool2d', up_denoise='transpose2d', reduce_denoise='add'):
super().__init__()
estimate_list = nn.ModuleL... |
def middle_sqrt(Y: dace.float32[(3, 3)]):
intermediate = dace.define_local([3, 3], dace.float32)
W = dace.define_local([3, 3], dace.float32)
intermediate[:] = dace.elementwise((lambda x: sqrt(x)), Y)
inner_sdfg(intermediate, W)
Z = np.sum(W)
return Z |
.parametrize('disable', [True, False])
def test_multi(disable):
split = InvertibleModuleWrapper(SplitChannels(2), disable=disable)
concat = InvertibleModuleWrapper(ConcatenateChannels(2), disable=disable)
assert is_invertible_module(split, test_input_shape=(1, 3, 32, 32))
assert is_invertible_module(con... |
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial) |
def _Psi_coeff(l1, l2, p1, p2, m1, m2, r1, r2):
return (((((binom(l1, m1) * binom(l2, m2)) * falling_factorial((((- 2) * r1) - (p2 / 2)), m2)) * falling_factorial(((- p1) / 2), m1)) * calB((l1 - m1), r1, 2)) * calB((l2 - m2), r2, (- 2))) |
def load_audio(path: (str or Path), ch_format: str, sample_rate: int=None, downmix_to_mono: bool=False, resample_by: str='ffmpeg', **kwargs) -> Tuple[(np.ndarray, int)]:
if (ch_format not in (STR_CH_FIRST, STR_CH_LAST)):
raise ValueError(f'ch_format is wrong here -> {ch_format}')
if (os.stat(path).st_si... |
def processInputStreamData(obj):
print('receive context entity')
entityId = obj['entityId']
if (entityId['type'] == 'Camera'):
getCameraURL(obj)
elif (entityId['type'] == 'Pushbutton'):
handlePushButton(obj) |
def vit_b_16_c100():
out_base_name = 'ViT_B_16_norm'
out_dir = 'results/figs'
plot_fn = plot.plot_grad_norm
fn_to_contour = {'results/vit/cifar100/fast_dcgn_global_no_nesterov_meanstd05_vit_base_patch16_384_in21k_imagenet_384c384_8p_bw12_gpipe_acyclic_cifar100_384_gpipe_bs_512_se_16_seed_42.json': 'glob... |
('sdv.datasets.demo._get_data_from_bucket')
def test__download(mock_get_data_from_bucket):
mock_get_data_from_bucket.return_value = b''
_download('single_table', 'ring')
mock_get_data_from_bucket.assert_called_once_with('SINGLE_TABLE/ring.zip') |
class QuantEmbedding(nn.Module):
def __init__(self, num_embeddings, embedding_dim, padding_idx=None, max_norm=None, norm_type=2.0, scale_grad_by_freq=False, sparse=False, _weight=None, weight_bit=8, momentum=0.95, quant_mode=False):
super().__init__()
self.num_ = num_embeddings
self.dim = em... |
def setup_parser():
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', default=None, type=str, required=True, help='The input data dir. Should contain the .tsv files (or other data files) for the task.')
parser.add_argument('--bert_model', default=None, type=str, required=True, help='Bert ... |
_level_function()
def validity_error(array, *, exception=False):
(yield (array,))
return _impl(array, exception) |
def fuse_sg(module):
sdfg = module.sdfg
sdfg.apply_transformations_repeated(TrivialMapRangeElimination)
SubgraphFusion.apply_to(sdfg, *sdfg.node(0).nodes()) |
class DBPedia(Task):
def __init__(self):
super().__init__()
self.class_number = 14
self.file_by_split = dict(train='dbpedia_csv/train.train.csv', val='dbpedia_csv/train.dev.csv', test='dbpedia_csv/test.csv')
self.max_length = 400
def read_data(path, max_length):
def label... |
def parse():
parser = argparse.ArgumentParser()
parser.add_argument('--seed', type=int, default=0)
parser.add_argument('--output', type=str, default='results.pt')
parser.add_argument('--acqf', type=str, default='cucb')
parser.add_argument('--device', type=int, default=0)
parser.add_argument('--f... |
def get_graph_matrix(edge2idx, objects, relations):
triples = []
for (cat, ships) in relations.items():
for (i, js) in enumerate(ships):
for j in js:
triples.append((i, edge2idx[cat], j))
rel_count = {}
for i in range(len(triples)):
pair = (triples[i][0], trip... |
_BOX_HEADS.register('roi_xconv1fc_head')
class roi_xconv1fc_head(nn.Module):
def __init__(self, dim_in, spatial_scale):
super().__init__()
self.dim_in = dim_in[(- 1)]
method = cfg.FAST_RCNN.ROI_XFORM_METHOD
resolution = cfg.FAST_RCNN.ROI_XFORM_RESOLUTION
sampling_ratio = cfg.... |
def make_vecAdd_sdfg(sdfg_name: str, dtype=dace.float32):
n = dace.symbol('size')
vecAdd_sdfg = dace.SDFG(sdfg_name)
vecAdd_state = vecAdd_sdfg.add_state('vecAdd_nested')
x_name = 'x'
y_name = 'y'
z_name = 'z'
vecAdd_sdfg.add_array(x_name, [n], dtype=dtype)
vecAdd_sdfg.add_array(y_name, ... |
class TruncateDataset(BaseWrapperDataset):
def __init__(self, dataset, truncation_length):
super().__init__(dataset)
assert (truncation_length is not None)
self.truncation_length = truncation_length
self.dataset = dataset
def __getitem__(self, index):
item = self.dataset[... |
class SegmentationAwareScore(EvaluatorScore):
def __init__(self, weights_path):
super().__init__()
self.segm_network = SegmentationModule(weights_path=weights_path, use_default_normalization=True).eval()
self.target_class_freq_by_image_total = []
self.target_class_freq_by_image_mask ... |
class PeriodicWriter(HookBase):
def __init__(self, writers, period=20):
self._writers = writers
for w in writers:
assert isinstance(w, EventWriter), w
self._period = period
def after_step(self):
if ((((self.trainer.iter + 1) % self._period) == 0) or (self.trainer.iter... |
class YT8MMusicTextClipsJsonifier(DatasetJsonifier):
def load_raw_data(self):
assert (self.split in ('train', 'test', 'all'))
if (self.split == 'all'):
train_df = pd.read_csv(os.path.join(self.input_dir, 'train.csv'))
test_df = pd.read_csv(os.path.join(self.input_dir, 'test.c... |
()
def stopping_condition() -> StoppingCondition:
return MinimumCoveragePlateauStoppingCondition(50, 1) |
_model
def poolformer_m48(pretrained=False, **kwargs):
layers = [8, 8, 24, 8]
embed_dims = [96, 192, 384, 768]
mlp_ratios = [4, 4, 4, 4]
downsamples = [True, True, True, True]
model = PoolFormer(layers, embed_dims=embed_dims, mlp_ratios=mlp_ratios, downsamples=downsamples, layer_scale_init_value=1e-... |
def remove_files_in_dir(dir):
if (not osp.isdir(dir)):
return
for file in os.listdir(dir):
file_path = os.path.join(dir, file)
try:
if os.path.isfile(file_path):
os.unlink(file_path)
except Exception as e:
print(e) |
def ClawGraph():
edge_list = [(0, 1), (0, 2), (0, 3)]
pos_dict = {0: (0, 1), 1: ((- 1), 0), 2: (0, 0), 3: (1, 0)}
return Graph(edge_list, pos=pos_dict, name='Claw graph') |
class LEDTokenizer(BartTokenizer):
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES |
_experiment(snapshot_mode='last')
def her_ddpg_fetchreach(ctxt=None, seed=1):
set_seed(seed)
with LocalTFRunner(snapshot_config=ctxt) as runner:
env = GarageEnv(gym.make('FetchReach-v1'))
policy = ContinuousMLPPolicy(env_spec=env.spec, name='Policy', hidden_sizes=[256, 256, 256], hidden_nonlinea... |
def update_v(critic: Model, value: Model, batch: Batch, alpha: float, alg: str) -> Tuple[(Model, InfoDict)]:
(q1, q2) = critic(batch.observations, batch.actions)
q = jnp.minimum(q1, q2)
def value_loss_fn(value_params: Params) -> Tuple[(jnp.ndarray, InfoDict)]:
v = value.apply({'params': value_params... |
def traverse_depthfirst(finaltree):
if (len(finaltree) == 1):
return (finaltree['id'], '')
strdepthfirst = ''
for child in finaltree['children']:
(child_id, child_shape) = traverse_depthfirst(child)
strdepthfirst += (((finaltree['id'] + '|') + child_id) + ' ')
if (len(child_s... |
def GenerateSM80_TensorOp_884(manifest, cuda_version):
if (not CudaToolkitVersionSatisfies(cuda_version, 11, 0)):
return
layouts = [(LayoutType.ColumnMajor, LayoutType.ColumnMajor, LayoutType.ColumnMajor), (LayoutType.ColumnMajor, LayoutType.RowMajor, LayoutType.ColumnMajor), (LayoutType.RowMajor, Layou... |
class TestStartFixer(unittest.TestCase):
def test_init(self):
contigs_fa = os.path.join(data_dir, 'start_fixer_init_contigs.fa')
dna_da = os.path.join(data_dir, 'start_fixer_init_dnaA.fa')
with self.assertRaises(start_fixer.Error):
sfixer = start_fixer.StartFixer('notafile', 'out... |
def no_duplicates(f):
def wrap_remove_duplicates():
policies = f()
return remove_duplicates(policies)
return wrap_remove_duplicates |
def get_extractor(data_set, system):
if ((system == 'closest') or (system == 'latent')):
return 'cort.coreference.approaches.mention_ranking.extract_substructures'
elif (system == 'tree'):
return 'cort.coreference.approaches.antecedent_trees.extract_substructures'
elif (system == 'pair'):
... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--task_name', default=None, type=str, required=True, help='The name of the task to train.')
parser.add_argument('--cache_dir', default='', type=str, help='Where do you want to store the pre-trained models downloaded from s3')
parser.add... |
def computeDialogue(greedy, answer):
examples = []
for (idx, (g, a)) in enumerate(zip(greedy, answer)):
examples.append((a[0][0], g, a[0][1], idx))
examples.sort()
turn_request_positives = 0
turn_goal_positives = 0
joint_goal_positives = 0
ldt = None
for ex in examples:
i... |
def make_union():
if os.path.exists('../korean_learner/korean_learner_train.txt'):
cd = '../'
elif os.path.exists('extract_data/korean_learner/korean_learner_train.txt'):
cd = 'extract_data/'
for mode in ['train', 'test', 'val']:
os.system(f'echo > {cd}union/union_{mode}.txt')
... |
def test_render():
env = MetaMazeEnv()
with pytest.raises(NotImplementedError):
env.render() |
def init_embedding(hparams):
f = open('data/vocab_20000', 'r', encoding='utf-8')
vocab = []
for line in f:
vocab.append(line.rstrip('\n'))
word_vectors = KeyedVectors.load_word2vec_format('data/roc_vector.txt')
emb = []
num = 0
for i in range(0, len(vocab)):
word = vocab[i]
... |
class SemistandardSkewTableaux_size(SemistandardSkewTableaux):
def __init__(self, n, max_entry):
self.n = n
if (max_entry is None):
self.max_entry = n
else:
self.max_entry = max_entry
SemistandardSkewTableaux.__init__(self, category=FiniteEnumeratedSets())
... |
_tf
class TFDataCollatorIntegrationTest(unittest.TestCase):
def setUp(self):
super().setUp()
self.tmpdirname = tempfile.mkdtemp()
vocab_tokens = ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]']
self.vocab_file = os.path.join(self.tmpdirname, 'vocab.txt')
with open(self.vocab_fi... |
class DistilBertConfig(PretrainedConfig):
model_type = 'distilbert'
def __init__(self, vocab_size=30522, max_position_embeddings=512, sinusoidal_pos_embds=False, n_layers=6, n_heads=12, dim=768, hidden_dim=(4 * 768), dropout=0.1, attention_dropout=0.1, activation='gelu', initializer_range=0.02, qa_dropout=0.1, ... |
def merge_single_set_jsons(set_name: str, ORIGINAL_CATEGORIES: List[str], save_dir: str, jsons_reid_per_category_cropped):
global_json = {}
anno_id = 0
all_annos = []
all_image_ids = []
all_images_info = []
for category_name in ORIGINAL_CATEGORIES:
set_single_category_json = jsons_reid_p... |
def compute_graph_max_cut(memory_graph: MemoryGraph, n_iter: int=50, astar_n_iter: int=500, eps: float=0.01) -> Tuple[(List[BaseNode], float, List[Cut])]:
max_cut_astar = MaxCutAstar(memory_graph=memory_graph)
last_result = (None, 0, None)
l_bound = memory_graph.memory_lbound_single_op
u_bound = ((2 * s... |
def forSecond(frame_number, output_arrays, count_arrays, average_count, returned_frame):
plt.clf()
plt.show()
this_colors = []
labels = []
sizes = []
counter = 0
for eachItem in average_count:
counter += 1
labels.append(((eachItem + ' = ') + str(average_count[eachItem])))
... |
def cityscapes_to_coco_all_random(cityscapes_id):
lookup = {0: (- 1), 1: (- 1), 2: (- 1), 3: (- 1), 4: (- 1), 5: (- 1), 6: (- 1), 7: (- 1), 8: (- 1)}
return lookup[cityscapes_id] |
def read_relational_attribute(ofile, relational_attribute, i):
r_end_relational = re.compile((('^[Ee][Nn][Dd]\\s*' + relational_attribute.name) + '\\s*$'))
while (not r_end_relational.match(i)):
m = r_headerline.match(i)
if m:
isattr = r_attribute.match(i)
if isattr:
... |
def try_index(scalar_or_list, i):
try:
return scalar_or_list[i]
except TypeError:
return scalar_or_list |
class RandomFeatureEnsemble(Ensemble):
def __init__(self, M, N, f):
self.M = M
self.N = N
self.f = ACTIVATIONS[f]
self.repr_init()
def generate(self):
Z = (np.random.randn(self.N, self.N) / np.sqrt(self.N))
W = np.random.randn(self.M, self.N)
X = (self.f((... |
class UAS(Metric):
def __init__(self, eps=1e-08):
super(Metric, self).__init__()
self.eps = eps
self.total = 0.0
self.direct_correct = 0.0
self.undirect_correct = 0.0
self.total_sentence = 0.0
self.correct_root = 0.0
def score(self):
return (self.d... |
def _get_training_devices_dump() -> str:
out = subprocess.check_output(['nvidia-smi', '--query-gpu=gpu_name,gpu_bus_id,vbios_version', '--format=csv'])
return out.decode('utf-8').strip() |
def construct_outletDF(outlet_avg_dict, topics):
outlet_topicsDF = pd.DataFrame.from_dict(outlet_avg_dict, orient='index').transpose()
outlet_topicsDF['sum'] = outlet_topicsDF[outlet_topicsDF.columns].sum(axis=1)
outlet_topicsDF = outlet_topicsDF.sort_values('sum', ascending=False).drop('sum', axis=1)
o... |
def sin_transformer(period):
return FunctionTransformer((lambda x: np.sin((((x / period) * 2) * np.pi)))) |
class HTMLPage(object):
def __init__(self, content, encoding, url, cache_link_parsing=True):
self.content = content
self.encoding = encoding
self.url = url
self.cache_link_parsing = cache_link_parsing
def __str__(self):
return redact_auth_from_url(self.url) |
def save_pickle(pickle_path, data):
with open(pickle_path, 'wb') as f:
pickle.dump(data, f, protocol=pickle.HIGHEST_PROTOCOL) |
class SubGoalObserver(WaypointObserver):
def __init__(self, config, vehicle, traffic_manager):
super().__init__(config, vehicle, traffic_manager)
self._num_wps = self.config.observations.sub_goal_num
sub_goal_dist_max = self.config.observations.sub_goal_dist_max
if ((sub_goal_dist_ma... |
def eval_dist_at_powseries(phi, f):
nmoments = phi.parent().precision_cap()
K = f.parent().base_ring()
if K.is_exact():
K = phi.parent().base_ring()
return sum(((a * K(phi.moment(i))) for (a, i) in zip(f.coefficients(), f.exponents()) if ((i >= 0) and (i < nmoments)))) |
def _get_wrn_spec(num_layers, width_factor):
assert (((num_layers - 4) % 6) == 0)
n = ((num_layers - 4) // 6)
layers = ([n] * 3)
channels = [16, (16 * width_factor), (32 * width_factor), (64 * width_factor)]
return (layers, channels) |
class MessagePassingStateChunked():
inputs: chex.Array
hints: chex.Array
is_first: chex.Array
hint_preds: chex.Array
hiddens: chex.Array
lstm_state: Optional[hk.LSTMState] |
def get_text_video_audio_data(data_path, part='train'):
if (part == 'train'):
x_txt = np.load(((data_path + '/') + 'train_text.npy'))
x_vid = np.load(((data_path + '/') + 'train_video.npy'))
vid_seqN = np.load(((data_path + '/') + 'train_video_seqN.npy'))
x_mfcc = np.load(((data_path... |
class FacadesDataset(Pix2pixDataset):
def modify_commandline_options(parser, is_train):
parser = Pix2pixDataset.modify_commandline_options(parser, is_train)
parser.set_defaults(dataroot='./dataset/facades/')
parser.set_defaults(preprocess_mode='resize_and_crop')
load_size = (286 if i... |
_grad()
def inspect_lora(model):
moved = {}
for (name, _module) in model.named_modules():
if (_module.__class__.__name__ in ['LoraInjectedLinear', 'LoraInjectedConv2d', 'LoraInjectedConv3d']):
ups = _module.lora_up.weight.data.clone()
downs = _module.lora_down.weight.data.clone()... |
def text2():
error_sentence_2 = ',,!'
correct_sent = m.correct(error_sentence_2)
print('original sentence:{} => correct sentence:{}'.format(error_sentence_2, correct_sent)) |
def masked_logit_cross_entropy(preds, labels, mask):
loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=preds, labels=labels)
loss = tf.reduce_sum(loss, axis=1)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.maximum(tf.reduce_sum(mask), tf.constant([1.0]))
loss *= mask
return tf.reduce_mea... |
class Modeler(object):
hashtagSegmentor = None
t = 0
totals = 0
totalh = 0
p = 0
r = 0
n = 0
modelerParams = {}
def __init__(self):
pass
def loadParameters(self, args):
leftoverArgs = []
for arg in args:
if (self.loadParameter(arg) == False):
... |
def get_args_from_command_line():
parser = ArgumentParser(description='Parser of Runner of Network')
parser.add_argument('--gpu', dest='gpu_id', help='GPU device id to use [cuda]', default=cfg.CONST.DEVICE, type=str)
parser.add_argument('--phase', dest='phase', help='phase of CNN', default=cfg.NETWORK.PHASE... |
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, noactivation=False):
super(BasicBlock, self).__init__()
self.basicblock_sub = BasicBlockSub(inplanes, planes, stride, noactivation)
self.downsample = downsample
self.stride ... |
def test_LayerNorm(device):
from speechbrain.nnet.normalization import LayerNorm
input = (torch.randn(4, 101, 256, device=device) + 2.0)
norm = LayerNorm(input_shape=input.shape).to(device)
output = norm(input)
assert (input.shape == output.shape)
current_mean = output.mean(dim=2).mean()
ass... |
class Upsampling(Layer):
def __init__(self, new_size, **kwargs):
self.new_size = new_size
super(Upsampling, self).__init__(**kwargs)
def build(self, input_shape):
super(Upsampling, self).build(input_shape)
def call(self, inputs, **kwargs):
(new_height, new_width) = self.new_s... |
def test_IndexedOptionArray_NumpyArray():
v2a = ak.contents.indexedoptionarray.IndexedOptionArray(ak.index.Index(np.array([2, 2, (- 1), 1, (- 1), 5, 4], np.int64)), ak.contents.numpyarray.NumpyArray(np.array([0.0, 1.1, 2.2, 3.3, 4.4, 5.5])))
def f(out, obj):
out[0] = len(obj)
out[1] = (obj[0] if... |
def get_gptq_trainable_parameters(fxp_model: Model, fw_info: FrameworkInfo, add_bias: bool=False) -> (List[tf.Variable], List[tf.Variable], List[tf.Variable]):
trainable_weights: List[tf.Tensor] = []
trainable_threshold: List[tf.Tensor] = []
bias_weights: List[List[tf.Tensor]] = []
for layer in fxp_mode... |
def test_property_selection_function(mosa_strategy):
selection_function = MagicMock(SelectionFunction())
mosa_strategy.selection_function = selection_function
assert (mosa_strategy.selection_function == selection_function) |
class Retry(object):
DEFAULT_METHOD_WHITELIST = frozenset(['HEAD', 'GET', 'PUT', 'DELETE', 'OPTIONS', 'TRACE'])
RETRY_AFTER_STATUS_CODES = frozenset([413, 429, 503])
DEFAULT_REDIRECT_HEADERS_BLACKLIST = frozenset(['Authorization'])
BACKOFF_MAX = 120
def __init__(self, total=10, connect=None, read=No... |
def run_on_one_sequence(sess, model, batch_img):
with sess.as_default():
prob = sess.run(model.preds, feed_dict={images: batch_img, K.learning_phase(): 0})
print(prob)
(gb_grad_value, target_conv_layer_value, target_conv_layer_grad_value) = sess.run([gb_grad, target_conv_layer, target_conv_l... |
def test_fix_span_text():
test_cases = [('The kilogram-force is not a part', ['the', 'kilogram', '-', 'force', 'is', 'not'], 'the kilogram-force is not'), ('The kilogram-force is not a part', ['kilogram', '-', 'force'], 'kilogram-force'), ('In the 1910s, New Yorkbased filmmakers were attracted to', ['new', 'york', ... |
def has_exact_match(ground_truths, candidates):
for ground_truth in ground_truths:
if (ground_truth in candidates):
return True
return False |
class EntropyRegularisationLoss(nn.Module):
def __init__(self):
super(EntropyRegularisationLoss, self).__init__()
pass
def forward(self, policies, tformat):
(_policies, policies_params, policies_tformat) = _to_batch(policies, tformat)
entropy = th.bmm(th.log(_policies).unsqueeze(... |
class Wrapper():
def get_args(parser):
parser.add('--gan_type', type=str, default='gan', help='gan|rgan|ragan')
def get_net(args):
criterion = Criterion(args.gan_type)
return criterion.to(args.device) |
def resize(image, new_width_height=1920, convert_RGB=True):
image = (Image.open(image) if isinstance(image, (str, BytesIO)) else image)
(w, h) = image.size
fixed_size = (new_width_height if isinstance(new_width_height, int) else False)
if fixed_size:
if (h > w):
fixed_height = fixed_... |
def is_source_code_missing_brackets(source_code, prioritize_missing_open=False):
open_brackets = '[{('
close_brackets = ']})'
last_bracket = [(- 1)]
counters = ([0] * len(open_brackets))
missing_open = False
for (t_type, t_content) in list(parse_py_statements(source_code)):
if (t_type !=... |
class CustomAgentExecutor(AgentExecutor):
def _take_next_step(self, name_to_tool_map: Dict[(str, BaseTool)], color_mapping: Dict[(str, str)], inputs: Dict[(str, str)], intermediate_steps: List[Tuple[(AgentAction, str)]]) -> Union[(AgentFinish, List[Tuple[(AgentAction, str)]])]:
output = self.agent.plan(inte... |
def set_flags(_enabled):
orig_flags = (torch._C._get_mkldnn_enabled(),)
torch._C._set_mkldnn_enabled(_enabled)
return orig_flags |
def test_line_coverage_fully_covered(subject_properties_mock, trace_mock):
subject_properties_mock.existing_lines = {0: LineMetaData(0, 'foo', 0), 1: LineMetaData(0, 'foo', 1)}
trace_mock.covered_line_ids = {0, 1}
assert (ff.compute_line_coverage(trace_mock, subject_properties_mock) == 1.0) |
class MultiResolutionSTFTLoss(torch.nn.Module):
def __init__(self, fft_sizes=[1024, 2048, 512], hop_sizes=[120, 240, 50], win_lengths=[600, 1200, 240], window='hann_window', factor_sc=0.1, factor_mag=0.1):
super(MultiResolutionSTFTLoss, self).__init__()
assert (len(fft_sizes) == len(hop_sizes) == le... |
def deriv_df_coefficient(coeff):
dcoeff = defaultdict(float)
for (key, val) in coeff.items():
if (key[0] == 'indirect'):
pwer = key[1]
dcoeff[('indirect', (pwer + 2))] = (((- 0.5) * pwer) * val)
else:
(p, sjn) = key
(s, j, n) = sjn
if (... |
def load_langpair_dataset(data_path, split, src, src_dict, tgt, tgt_dict, combine, dataset_impl, upsample_primary, left_pad_source, left_pad_target, max_source_positions, max_target_positions, prepend_bos=False, load_alignments=False, truncate_source=False, append_source_id=False, num_buckets=0, shuffle=True, pad_to_mu... |
class ExtensionTable():
baseURL: list = dc.field(default_factory=list)
id: list = dc.field(default_factory=list)
name: list = dc.field(default_factory=list)
length: int = dc.field(default_factory=list) |
def unwrap_model(model: torch.nn.Module) -> torch.nn.Module:
if hasattr(model, 'module'):
return unwrap_model(model.module)
else:
return model |
def pointnet_sa_module_msg(xyz, points, npoint, radius_list, nsample_list, mlp_list, is_training, bn_decay, scope, bn=True, use_xyz=True, use_nchw=False):
data_format = ('NCHW' if use_nchw else 'NHWC')
with tf.variable_scope(scope) as sc:
new_xyz = gather_point(xyz, farthest_point_sample(npoint, xyz))
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.