repo stringlengths 2 99 | file stringlengths 13 225 | code stringlengths 0 18.3M | file_length int64 0 18.3M | avg_line_length float64 0 1.36M | max_line_length int64 0 4.26M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
PuncturedFEM | PuncturedFEM-main/puncturedfem/plot/traceplot.py | import numpy as np
import matplotlib.pyplot as plt
# from .. import quad
from ..mesh.cell import cell
def plot_trace(f_trace_list, fmt, legend, title, K: cell, quad_list):
t = _get_trace_param_cell_boundary(K, quad_list)
plt.figure()
for k in range(len(f_trace_list)):
plt.plot(t, f_trace_list[k], fmt[k])
plt.... | 1,576 | 20.310811 | 73 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/plot/edges.py | import numpy as np
import matplotlib.pyplot as plt
from .. import mesh
def plot_edges(edge_list,
orientation=False,
axis_arg='equal',
grid_arg='minor'):
plt.figure()
plt.axis(axis_arg)
plt.grid(grid_arg)
for e in edge_list:
if orientation:
_plot_oriented_edge(e)
else:
_plot_edge(e)
plt.show()
... | 1,057 | 15.53125 | 63 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/plot/__init__.py | 0 | 0 | 0 | py | |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/intval.py | import numpy as np
from ..mesh.cell import cell
from .locfun import locfun
def interior_values(v: locfun, K: cell):
"""
Returns (y1, y2, vals) where y1,y2 form a meshgrid covering the cell K
and vals is an array of the same size of the interior values of v.
At points that are not in the interior, vals is nan.
"""... | 3,232 | 29.5 | 71 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/int_poly.py | from .poly.poly import polynomial
from ..mesh.cell import cell
def integrate_poly_over_cell(p: polynomial, K: cell):
""""
Returns the value of
\int_K (self) dx
by reducing this volumetric integral to one on the boundary via
the Divergence Theorem
"""
x1, x2 = K.get_boundary_points()
xn = K.dot_with_no... | 479 | 27.235294 | 65 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/locfun.py | from . import d2n
from . import antilap
from .int_poly import integrate_poly_over_cell
from ..mesh.cell import cell
from .poly.poly import polynomial
class locfun:
"""
Local function object (defined over single cell), consisting of:
* Dirichlet trace values (given as array)
* Laplacian (given as polynomial object)... | 6,822 | 31.961353 | 77 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/__init__.py | 0 | 0 | 0 | py | |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/poly/monomial.py | import numpy as np
from .multi_index import multi_index_2
class monomial:
"""
Monomials of the form
c (x, y) ^ (alpha_1, alpha_2) = c (x ^ alpha_1) * (y ^ alpha_2)
"""
def __init__(self, alpha: multi_index_2=None, coef: float=0.0) -> None:
if alpha is None:
alpha = multi_index_2()
self.set_coef(coef)
s... | 3,818 | 23.798701 | 72 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/poly/multi_index.py | from math import sqrt, floor
class multi_index_2:
"""
Integer multi-index with two components
"""
def __init__(self, alpha: list[int]=None) -> None:
if alpha is None:
alpha = [0, 0]
self.set(alpha)
def validate(self, alpha: list[int]):
if not isinstance(alpha, list):
raise TypeError('Multi-index mus... | 1,519 | 27.148148 | 68 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/poly/__init__.py | 0 | 0 | 0 | py | |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/poly/poly.py | import numpy as np
from .monomial import monomial
from .multi_index import multi_index_2
class polynomial:
"""
Treated as a list of monomial objects
"""
def __init__(self, coef_multidx_pairs=None):
self.set(coef_multidx_pairs)
def set(self, coef_multidx_pairs=None):
self.monos = []
if coef_multidx_pairs i... | 7,240 | 23.629252 | 68 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/nystrom/double_layer.py | import numpy as np
# from ...mesh.quad import quad
from ...mesh.cell import cell
from ...mesh.edge import edge
def double_layer_mat(K: cell):
"""
Double layer potential operator matrix
"""
N = K.num_pts
A = np.zeros((N,N))
for i in range(K.num_edges):
for j in range(K.num_edges):
A[K.vert_idx[i] : K.vert... | 1,081 | 19.415094 | 58 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/nystrom/neumann.py | import numpy as np
from scipy.sparse.linalg import gmres, LinearOperator
from ...mesh.cell import cell
from . import single_layer, double_layer, apply_double_layer
def solve_neumann_zero_average(K: cell, u_wnd):
# single and double layer operators
T1 = single_layer.single_layer_mat(K)
T2 = double_layer.double_lay... | 926 | 21.071429 | 68 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/nystrom/single_layer.py | import numpy as np
from ...mesh.quad.quad import quad
from ...mesh.cell import cell
from ...mesh.edge import edge
def single_layer_mat(K: cell):
"""
Single layer potential operator matrix
"""
N = K.num_pts
A = np.zeros((N,N))
for j in range(K.num_edges):
# Martensen quadrature
nm = (K.edge_list[j].num_pt... | 1,616 | 21.150685 | 60 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/nystrom/apply_double_layer.py | def apply_T2(u, T2, T2_sum, closest_vert_idx):
corner_values = u[closest_vert_idx]
return 0.5 * (u - corner_values) + T2 @ u - corner_values * T2_sum | 151 | 49.666667 | 67 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/nystrom/__init__.py | from . import single_layer
from . import double_layer
from . import neumann
from . import apply_double_layer | 108 | 26.25 | 32 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/antilap/antilap.py | import numpy as np
from ...mesh.cell import cell
from ..d2n.fft_deriv import fft_antiderivative
from ..d2n.log_terms import get_log_grad
from . import log_antilap
from .. import nystrom
def get_anti_laplacian_harmonic(K: cell, psi, psi_hat, a):
"""
Returns the trace and weighted normal derivative of an anti-Laplacia... | 3,989 | 30.666667 | 75 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/antilap/__init__.py | from . import antilap
from . import log_antilap | 47 | 23 | 25 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/antilap/log_antilap.py | import numpy as np
from ...mesh.cell import cell
from .. import d2n
def get_log_antilap(K: cell):
"""
Returns traces of an anti-Laplacian of logarithmic terms on the boundary
\Lambda(x) = \frac14 |x|^2 (\ln|x|-1)
"""
LAM_trace = np.zeros((K.num_pts, K.num_holes))
for j in range(K.num_holes):
xi = K.hole_int... | 1,359 | 27.333333 | 74 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/d2n/trace2tangential.py | import numpy as np
from ...mesh.cell import cell
from ...mesh.contour import contour
from . import fft_deriv
def get_weighted_tangential_derivative_from_trace(K: cell, f):
"""
Returns df / ds = \nabla f(x(t)) \cdot x'(t) by computing the derivative
of f(x(t)) with respect to the scalar parameter t, where x(t)
is ... | 1,107 | 28.157895 | 73 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/d2n/log_terms.py | import numpy as np
from ...mesh.cell import cell
def shifted_coordinates(x, xi):
x_xi = np.array([x[0] - xi[0], x[1] - xi[1]])
x_xi_norm_sq = x_xi[0]**2 + x_xi[1]**2
return x_xi, x_xi_norm_sq
def get_log_trace(K: cell):
"""
Returns traces of logarithmic terms on the boundary
"""
lam_trace = np.zeros((K.num_pt... | 1,935 | 26.267606 | 63 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/d2n/fft_deriv.py | import numpy as np
def fft_derivative(f, interval_length):
N = len(f)
omega = np.fft.fft(f)
omega *= 1j * N * np.fft.fftfreq(N)
omega *= 2 * np.pi / interval_length
return np.real(np.fft.ifft(omega))
def fft_antiderivative(df, interval_length):
N = len(df)
omega = np.fft.fft(df)
fft_idx = np.fft.fftfreq(len(d... | 460 | 23.263158 | 44 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/d2n/harmconj.py | import numpy as np
from scipy.sparse.linalg import gmres, LinearOperator
from ...mesh.cell import cell
from .. import nystrom
from . import log_terms
from . import trace2tangential
def get_harmonic_conjugate(K: cell, phi, debug=False):
phi_wtd = \
trace2tangential.get_weighted_tangential_derivative_from_trace(K,... | 3,557 | 21.377358 | 74 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/locfun/d2n/__init__.py | from . import harmconj
from . import log_terms
from . import trace2tangential
from . import fft_deriv | 101 | 24.5 | 30 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/mesh/edge.py | import copy
import numpy as np
from .quad.quad import quad
class edge:
__slots__ = (
'id',
'etype',
'qtype',
'num_pts',
'x',
'unit_tangent',
'unit_normal',
'dx_norm',
'curvature',
)
def __init__(self, etype: str, q: quad, id: any = ... | 6,426 | 27.95045 | 77 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/mesh/contour.py | import numpy as np
from matplotlib import path
from . import edge
class contour:
__slots__ = (
'id',
'edge_list',
'num_edges',
'num_pts',
'vert_idx',
)
def __init__(self, edge_list: list[edge.edge], id='') -> None:
# optional identifier
self.id = id
# save edge list
self.edge_list = edge_list... | 6,424 | 25.549587 | 70 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/mesh/__init__.py | 0 | 0 | 0 | py | |
PuncturedFEM | PuncturedFEM-main/puncturedfem/mesh/cell.py | import numpy as np
from .edge import edge
from .contour import contour
class cell(contour):
__slots__ = (
'num_holes',
'closest_vert_idx',
'contour_idx',
'hole_int_pts',
)
def __init__(self, edge_list: list[edge], id=''):
# call initialization of contour object
super().__init__(edge_list, id)
# i... | 6,911 | 30.561644 | 71 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/mesh/edgelib/bean.py | """
Bean shape
x(t) = (cos t + 0.65 cos(2t), 1.5 sin t)
"""
import numpy as np
def _x(t, **kwargs):
x = np.zeros((2,len(t)))
x[0,:] = np.cos(t) + 0.65 * np.cos(2 * t)
x[1,:] = 1.5 * np.sin(t)
return x
def _dx(t, **kwargs):
dx = np.zeros((2,len(t)))
dx[0,:] = - np.sin(t) - 2 * 0.65 * np.sin(2 * t)
dx[1,:] = 1.... | 489 | 19.416667 | 50 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/mesh/edgelib/circle.py | """
Parameterization of the unit circle centered at the origin
"""
import numpy as np
def _x(t, **kwargs):
x = np.zeros((2,len(t)))
x[0,:] = np.cos(t)
x[1,:] = np.sin(t)
return x
def _dx(t, **kwargs):
dx = np.zeros((2,len(t)))
dx[0,:] = - np.sin(t)
dx[1,:] = np.cos(t)
return dx
def _... | 437 | 18.043478 | 58 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/mesh/edgelib/sine_wave.py | """
Parameterization of sine wave joining the origin to (1,0) of the form
x = t / (2*pi)
y = a * sin( omega/2 * t ) , 0 < t < 2*pi
Include arguments for the amplitude ('amp') and the frequency ('freq').
The frequency argument must be an integer.
"""
import numpy as np
def _x(t, **kwargs):
a = kwargs['a... | 943 | 23.205128 | 71 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/mesh/edgelib/circular_arc_deg.py | """
Parameterization of a circular arc from (1,0) to (cos(theta0), sin(theta0))
"""
import numpy as np
def unpack(kwargs):
theta0 = kwargs['theta0']
if theta0 <= 0 or theta0 > 360:
raise ValueError('theta0 must be a nontrivial angle between '
+ '0 and 360 degrees')
omega = theta0 / 360.0
return omega
def ... | 795 | 22.411765 | 75 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/mesh/edgelib/teardrop.py | """
Teardrop shape
x(t) = (2 sin(t/2), −β sin t), β = tan(π/(2α)), α = 3/2
"""
import numpy as np
def _x(t, **kwargs):
alpha = 3/2
beta = np.tan(0.5 * np.pi / alpha)
x = np.zeros((2,len(t)))
x[0,:] = 2 * np.sin(t / 2)
x[1,:] = -beta * np.sin(t)
return x
def _dx(t, **kwargs):
alpha = 3/2
beta = np.tan(0.5 * n... | 600 | 19.033333 | 55 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/mesh/edgelib/ellipse.py | """
Parameterization of an ellipse centered at the origin
"""
import numpy as np
def _x(t, **kwargs):
x = np.zeros((2,len(t)))
x[0,:] = kwargs['a'] * np.cos(t)
x[1,:] = kwargs['b'] * np.sin(t)
return x
def _dx(t, **kwargs):
dx = np.zeros((2,len(t)))
dx[0,:] = - kwargs['a'] * np.sin(t)
dx[... | 516 | 21.478261 | 53 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/mesh/edgelib/cartioid.py | """
Generalized Teardrop / Cartioid
x(t) = r(t) [cos(t), sin(t)] where
r(t) = 1 + a (1 - t / pi) ^ 8, a > -1 is a fixed parameter
Note:
a = 0 gives the unit circle
-1 < a < 0 is "generalized cartioid" with a reentrant corner
a > 0 is a "generalized teardrop"
"""
import numpy as np
def _x(t, **kwargs):
a = kwargs[... | 1,016 | 23.804878 | 61 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/mesh/edgelib/line.py | """
Parameterization of a line joining the origin to (1,0).
"""
import numpy as np
def _x(t, **kwargs):
x = np.zeros((2,len(t)))
x[0,:] = t / (2*np.pi)
return x
def _dx(t, **kwargs):
dx = np.zeros((2,len(t)))
dx[0,:] = np.ones((len(t),)) / (2*np.pi)
return dx
def _ddx(t, **kwargs):
ddx =... | 356 | 17.789474 | 55 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/mesh/edgelib/circular_arc.py | """
Parameterization of a circular arc joining the origin to (1,0).
The center of the circle lies at (1/2, H). The points on the circle below
the x2 axis are discarded.
"""
import numpy as np
def unpack(kwargs):
H = kwargs['H']
R = np.sqrt(0.25 + H ** 2)
t0 = np.arcsin(H / R)
omega = -0.5 - t0 / np.pi
return H, ... | 951 | 24.052632 | 73 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/mesh/quad/quad.py | import numpy as np
class quad:
"""
quad: 1-dimensional quadrature object
Attributes:
type: str = label for quadrature variant
n: int = interval sampled at 2*n points, excluding the last endpoint
h: float = pi / n sample spacing in tau
t: array (len=2*n) of sampled parameter... | 2,844 | 25.100917 | 77 | py |
PuncturedFEM | PuncturedFEM-main/puncturedfem/mesh/quad/__init__.py | 0 | 0 | 0 | py | |
cypress | cypress-master/scripts/plot_synfire.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Cypress -- C++ Spiking Neural Network Simulation Framework
# Copyright (C) 2016 Andreas Stöckel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Found... | 2,907 | 34.463415 | 124 | py |
cypress | cypress-master/scripts/plot_tuning_curves.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Cypress -- C++ Spiking Neural Network Simulation Framework
# Copyright (C) 2016 Andreas Stöckel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Found... | 1,606 | 31.795918 | 81 | py |
cypress | cypress-master/scripts/decode_function.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Cypress -- C++ Spiking Neural Network Simulation Framework
# Copyright (C) 2016 Andreas Stöckel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Found... | 2,111 | 28.333333 | 72 | py |
cypress | cypress-master/scripts/plot_winner_take_all.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Cypress -- C++ Spiking Neural Network Simulation Framework
# Copyright (C) 2016 Andreas Stöckel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Found... | 1,837 | 29.131148 | 74 | py |
cypress | cypress-master/scripts/plot_epsp.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Cypress -- C++ Spiking Neural Network Simulation Framework
# Copyright (C) 2016 Andreas Stöckel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Found... | 2,112 | 31.015152 | 76 | py |
cypress | cypress-master/resource/hexdump.py | #!/usr/bin/env python
import sys
while True:
b = sys.stdin.read(1)
if b != "":
sys.stdout.write("0x%02x,"%ord(b))
else:
break
| 133 | 13.888889 | 36 | py |
cypress | cypress-master/resource/backend/nmpi/broker.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Cypress -- A C++ interface to PyNN
# Copyright (C) 2016 Andreas Stöckel
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either versio... | 11,406 | 31.873199 | 148 | py |
GenomicsDB | GenomicsDB-master/tests/run.py | #!/usr/bin/env python
#The MIT License (MIT)
#Copyright (c) 2016-2017 Intel Corporation
#Permission is hereby granted, free of charge, to any person obtaining a copy of
#this software and associated documentation files (the "Software"), to deal in
#the Software without restriction, including without limitation the ... | 54,278 | 52.266928 | 250 | py |
GenomicsDB | GenomicsDB-master/tests/run_spark_hdfs.py | #!/usr/bin/env python
#The MIT License (MIT)
#Copyright (c) 2018 University of California, Los Angeles and Intel Corporation
#Permission is hereby granted, free of charge, to any person obtaining a copy of
#this software and associated documentation files (the "Software"), to deal in
#the Software without restricti... | 23,088 | 56.15099 | 564 | py |
GenomicsDB | GenomicsDB-master/docker/vcf_combiner/usr/bin/combine_vcf.py | #! /usr/bin/python3
# pylint: disable=missing-docstring, invalid-name, broad-except, too-many-branches, too-many-locals, line-too-long
"""
The MIT License (MIT)
Copyright (c) 2016-2017 Intel Corporation
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associate... | 11,402 | 41.077491 | 122 | py |
imagefusion-rfn-nest | imagefusion-rfn-nest-main/args_fusion.py |
class args():
# training args
epochs = 2 #"number of training epochs, default is 2"
batch_size = 4 #"batch size for training, default is 4"
dataset_ir = "path of KAIST infrared images"
dataset_vi = "path of KAIST visible images"
HEIGHT = 256
WIDTH = 256
save_fusion_model = "models/train/fusionnet/"
save_lo... | 1,363 | 33.974359 | 118 | py |
imagefusion-rfn-nest | imagefusion-rfn-nest-main/utils.py | import os
import random
import numpy as np
import torch
from args_fusion import args
from scipy.misc import imread, imsave, imresize
import matplotlib as mpl
from os import listdir
from os.path import join
EPSILON = 1e-5
def list_images(directory):
images = []
names = []
dir = listdir(directory)
dir.... | 6,275 | 33.108696 | 104 | py |
imagefusion-rfn-nest | imagefusion-rfn-nest-main/test_21pairs.py | # test phase
import os
import torch
from torch.autograd import Variable
from net import NestFuse_light2_nodense, Fusion_network, Fusion_strategy
import utils
from args_fusion import args
import numpy as np
def load_model(path_auto, path_fusion, fs_type, flag_img):
if flag_img is True:
nc = 3
else:
nc =1
input_... | 4,860 | 31.406667 | 152 | py |
imagefusion-rfn-nest | imagefusion-rfn-nest-main/net.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
EPSILON = 1e-10
def var(x, dim=0):
x_zero_meaned = x - x.mean(dim).expand_as(x)
return x_zero_meaned.pow(2).mean(dim)
class MultConst(nn.Module):
def forward(self, input):
return 255*input
class UpsampleRes... | 12,480 | 34.157746 | 96 | py |
imagefusion-rfn-nest | imagefusion-rfn-nest-main/test_40pairs.py | # -*- coding:utf-8 -*-
# @Author: Li Hui, Jiangnan University
# @Email: [email protected]
# @File : test_40pairs.py
# @Time : 2020/8/14 17:11
# test phase
import os
import torch
from torch.autograd import Variable
from net import NestFuse_light2_nodense, Fusion_network, Fusion_strategy
import utils
from args_fusion i... | 4,952 | 30.75 | 152 | py |
imagefusion-rfn-nest | imagefusion-rfn-nest-main/train_fusionnet.py | # Training a NestFuse network
# auto-encoder
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
import sys
import time
from tqdm import tqdm, trange
import scipy.io as scio
import random
import torch
from torch.optim import Adam
from torch.autograd import Variable
import utils
from net import NestFuse_light2_nodense,... | 8,542 | 33.447581 | 181 | py |
imagefusion-rfn-nest | imagefusion-rfn-nest-main/pytorch_msssim/__init__.py | import torch
import torch.nn.functional as F
from math import exp
import numpy as np
def gaussian(window_size, sigma):
gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)])
return gauss/gauss.sum()
def create_window(window_size, channel=1):
_1D_window = gaus... | 4,380 | 31.69403 | 118 | py |
tasksource | tasksource-main/.github/scripts/release.py | #!/usr/bin/env python3
import json
import subprocess
def get_last_version() -> str:
"""Return the version number of the last release."""
json_string = (
subprocess.run(
["gh", "release", "view", "--json", "tagName"],
check=True,
stdout=subprocess.PIPE,
s... | 1,328 | 26.122449 | 78 | py |
tasksource | tasksource-main/src/tasksource/mtasks.py | from .preprocess import cat, get,name, regen, constant, Classification, TokenClassification, MultipleChoice
from .metadata import udep_labels
from datasets import get_dataset_config_names, ClassLabel, Dataset, DatasetDict, concatenate_datasets, Sequence
def all(dataset_name):
try:
config_name=get_dataset_c... | 6,676 | 48.828358 | 174 | py |
tasksource | tasksource-main/src/tasksource/access.py | from .preprocess import Preprocessing
import re
import pandas as pd
from . import tasks, recast
from .metadata import dataset_rank
from datasets import load_dataset
import funcy as fc
import os
import copy
from sorcery import dict_of
from functools import cache
import random
class lazy_mtasks:
def __getattr__(sel... | 4,268 | 38.527778 | 114 | py |
tasksource | tasksource-main/src/tasksource/recast.py | import random
from datasets import DatasetDict, Dataset
from sorcery import dict_of
import string
improper_labels = ['recast/recast_kg_relations','linguisticprobing',"lexglue/scotus","pragmeval/squinky","pragmeval/emobank",'pragmeval/persuasiveness']
improper_labels += ['glue/stsb', 'sick/relatedness', 'joci', 'utilit... | 5,086 | 44.419643 | 696 | py |
tasksource | tasksource-main/src/tasksource/__init__.py | from .tasks import *
from .preprocess import *
from .access import *
| 69 | 16.5 | 25 | py |
tasksource | tasksource-main/src/tasksource/tasks.py | from .preprocess import cat, get, regen, name, constant, Classification, TokenClassification, MultipleChoice
from .metadata import bigbench_discriminative_english, blimp_hard, imppres_presupposition, imppres_implicature, udep_en_configs, udep_en_labels
from datasets import get_dataset_config_names, Sequence, ClassLabel... | 49,569 | 46.89372 | 230 | py |
tasksource | tasksource-main/src/tasksource/preprocess.py | from collections.abc import Iterable
from dotwiz import DotWiz
from dataclasses import dataclass
from typing import Union
import itertools
import funcy as fc
import exrex
import magicattr
import numpy as np
import copy
import datasets
import time
def get_column_names(dataset):
cn = dataset.column_names
if ty... | 8,816 | 32.022472 | 136 | py |
tasksource | tasksource-main/src/tasksource/metadata/popularity.py | dataset_rank = {'glue': 0,
'super_glue': 12,
'tweet_eval': 23,
'blimp': 34,
'imdb': 101,
'wikitext': 102,
'squad': 106,
'trec': 107,
'openwebtext': 108,
'rotten_tomatoes': 109,
'anli': 110,
'adversarial_qa': 111,
'ai2_arc': 115,
'xsum': 117,
'amazon_reviews_multi': 118,
'ag_news': 125,
'yelp_review_full... | 24,310 | 28.290361 | 69 | py |
tasksource | tasksource-main/src/tasksource/metadata/blimp_groups.py | import pandas as pd
dfh=pd.read_csv('https://raw.githubusercontent.com/alexwarstadt/blimp/master/raw_results/summary/human_validation_summary.csv')
dfh['linguistic_term']=dfh['Condition']
dfm=pd.read_json('https://raw.githubusercontent.com/alexwarstadt/blimp/master/raw_results/summary/models_summary.jsonl',lines=True)... | 2,721 | 29.244444 | 131 | py |
tasksource | tasksource-main/src/tasksource/metadata/__init__.py | from .bigbench_groups import *
from .blimp_groups import *
from .popularity import *
imppres_presupposition=['presupposition_all_n_presupposition',
'presupposition_both_presupposition',
'presupposition_change_of_state',
'presupposition_cleft_existence',
'presupposition_cleft_uniqueness',
'presupposition_only_pres... | 6,152 | 71.388235 | 4,014 | py |
tasksource | tasksource-main/src/tasksource/metadata/bigbench_groups.py | bigbench_discriminative = set("""abstract_narrative_understanding
anachronisms
analogical_similarity
analytic_entailment
arithmetic
authorship_verification
bbq_lite_json
causal_judgment
cause_and_effect
checkmate_in_one
cifar10_classification
code_line_description
color
common_morpheme
conceptual_combinations
contextua... | 3,450 | 20.171779 | 147 | py |
afqsfenicsutil | afqsfenicsutil-master/with_scipy.py | """
These are utilities for interfacing FEniCS with Scipy.
This is how I look at sparsities or interface with LIS (see pylis by afq).
"""
from fenics import PETScMatrix, assemble
def assemble_as_scipy(form):
K = PETScMatrix()
assemble(form, tensor=K)
ki,kj,kv = K.mat().getValuesCSR()
import scipy
... | 663 | 25.56 | 74 | py |
afqsfenicsutil | afqsfenicsutil-master/my_restriction_map.py | # Copyright (C) 2010-2014 Simula Research Laboratory
#
# This file is part of CBCPOST.
#
# CBCPOST is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) ... | 7,493 | 35.916256 | 105 | py |
afqsfenicsutil | afqsfenicsutil-master/various.py | """
by B. E. Abali and A. Queiruga
"""
from fenics import *
import numpy as np
#
# Helper methods for extracting submeshes
# and making mappings between them
#
def SubMesh2(mesh,marker,inds):
mask = MeshFunction("size_t",mesh,marker.dim())
o = marker.array()
m = mask.array()
for i in xrange(len(m)): m... | 3,608 | 32.110092 | 191 | py |
afqsfenicsutil | afqsfenicsutil-master/write_vtk.py | from six import iteritems
from dolfin import FunctionSpace,VectorFunctionSpace,TensorFunctionSpace,project,cells
def write_vtk_f(fname, mesh=None, nodefunctions=None,cellfunctions=None):
"""
Write a whole bunch of FEniCS functions to the same vtk file.
"""
if mesh==None:
if nodefunctions != Non... | 4,331 | 34.508197 | 122 | py |
afqsfenicsutil | afqsfenicsutil-master/mesh_morph.py | """
A super-simple mesh-morpher designed for EMSI
Alejandro F Queiruga
UC Berkeley, 2014
"""
import numpy as np
from scipy.spatial import Delaunay
def do_tri_map(fix_ind,nodes,nodes_orig):
global dela,dela_orig,points,points_orig
gdim = nodes.shape[1]
fix_ind = list(set(fix_ind))
points = nodes[fix_in... | 1,850 | 30.913793 | 86 | py |
afqsfenicsutil | afqsfenicsutil-master/__init__.py | """
This is a little library of helper functions for use with FEniCS
by Alejandro F. Queiruga, with major contributions by B. Emek Abali.
"""
from .various import *
#from my_restriction_map import restriction_map
from .write_vtk import write_vtk_f
from .with_scipy import assemble_as_scipy, look_at_a_form
from .mes... | 337 | 23.142857 | 68 | py |
sm-vit | sm-vit-main/train.py | # coding=utf-8
from __future__ import absolute_import, division, print_function
wnb = False
if wnb:
import wandb
wandb.init(project="sm-vit", entity="xxx")
import logging
import argparse
import os
import random
import numpy as np
from datetime import timedelta
import time
import torch
import torch.distribut... | 17,894 | 39.763098 | 247 | py |
sm-vit | sm-vit-main/models/modeling.py | # coding=utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import logging
import math
from os.path import join as pjoin
from re import X
from matplotlib.cbook import flatten
import torch
import torch.nn as nn
import numpy as np
from torch.... | 19,835 | 38.12426 | 176 | py |
sm-vit | sm-vit-main/models/configs.py | # Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | 3,453 | 31.895238 | 74 | py |
sm-vit | sm-vit-main/utils/data_utils.py | import logging
import torch
from torchvision import transforms, datasets
from .dataset import *
from torch.utils.data import DataLoader, RandomSampler, DistributedSampler, SequentialSampler
from PIL import Image
from .autoaugment import AutoAugImageNetPolicy
import os
logger = logging.getLogger(__name__)
def get_l... | 12,747 | 46.924812 | 124 | py |
sm-vit | sm-vit-main/utils/dataset.py | import os
import json
from os.path import join
import numpy as np
import scipy
from scipy import io
import scipy.misc
from PIL import Image
import pandas as pd
import matplotlib.pyplot as plt
import torch
from torch.utils.data import Dataset
from torchvision.datasets import VisionDataset
from torchvision.datasets.fol... | 67,209 | 39.659407 | 180 | py |
sm-vit | sm-vit-main/utils/scheduler.py | import logging
import math
from torch.optim.lr_scheduler import LambdaLR
logger = logging.getLogger(__name__)
class ConstantLRSchedule(LambdaLR):
""" Constant learning rate schedule.
"""
def __init__(self, optimizer, last_epoch=-1):
super(ConstantLRSchedule, self).__init__(optimizer, lambda _: 1.... | 2,799 | 42.75 | 117 | py |
sm-vit | sm-vit-main/utils/autoaugment.py | """
Copy from https://github.com/DeepVoltaire/AutoAugment/blob/master/autoaugment.py
"""
from PIL import Image, ImageEnhance, ImageOps
import numpy as np
import random
__all__ = ['AutoAugImageNetPolicy', 'AutoAugCIFAR10Policy', 'AutoAugSVHNPolicy']
class AutoAugImageNetPolicy(object):
def __init__(self, fillcol... | 10,387 | 49.673171 | 116 | py |
sm-vit | sm-vit-main/utils/dist_util.py | import torch.distributed as dist
def get_rank():
if not dist.is_available():
return 0
if not dist.is_initialized():
return 0
return dist.get_rank()
def get_world_size():
if not dist.is_available():
return 1
if not dist.is_initialized():
return 1
return dist.get_... | 711 | 21.967742 | 56 | py |
sm-vit | sm-vit-main/U2Net/data_loader.py | # data loader
from __future__ import print_function, division
import glob
import torch
from skimage import io, transform, color
import numpy as np
import random
import math
import matplotlib.pyplot as plt
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms, utils
from PIL import Image
... | 9,327 | 32.797101 | 159 | py |
sm-vit | sm-vit-main/U2Net/u2net_test.py | import os
from re import X
from skimage import io, transform
import torch
import torchvision
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms#, utils
# import torch.optim as optim
import numpy a... | 13,512 | 37.719198 | 139 | py |
sm-vit | sm-vit-main/U2Net/model/u2net.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class REBNCONV(nn.Module):
def __init__(self,in_ch=3,out_ch=3,dirate=1):
super(REBNCONV,self).__init__()
self.conv_s1 = nn.Conv2d(in_ch,out_ch,3,padding=1*dirate,dilation=1*dirate)
self.bn_s1 = nn.BatchNorm2d(out_ch)
... | 14,719 | 26.984791 | 118 | py |
sm-vit | sm-vit-main/U2Net/model/u2net_refactor.py | import torch
import torch.nn as nn
import math
__all__ = ['U2NET_full', 'U2NET_lite']
def _upsample_like(x, size):
return nn.Upsample(size=size, mode='bilinear', align_corners=False)(x)
def _size_map(x, height):
# {height: size} for Upsample
size = list(x.shape[-2:])
sizes = {}
for h in range(... | 6,097 | 35.08284 | 101 | py |
sm-vit | sm-vit-main/U2Net/model/__init__.py | from .u2net import U2NET
from .u2net import U2NETP
| 51 | 16.333333 | 25 | py |
sm-vit | sm-vit-main/U2Net/model/setup_model_weights.py | import os
import gdown
os.makedirs('./saved_models/u2net', exist_ok=True)
os.makedirs('./saved_models/u2net_portrait', exist_ok=True)
gdown.download('https://drive.google.com/uc?id=1ao1ovG1Qtx4b7EoskHXmi2E9rp5CHLcZ',
'./saved_models/u2net/u2net.pth',
quiet=False)
gdown.download('https://drive.google.com/uc?i... | 431 | 29.857143 | 82 | py |
HighOrderAtten | HighOrderAtten-master/image_model/download_model.py | """
Download the VGG and deep residual model to extract image features.
Version: 1.0
Contributor: Jiasen Lu
"""
import os
import argparse
import json
def download_VGG():
print('Downloading VGG model from http://www.robots.ox.ac.uk/~vgg/software/very_deep/caffe/VGG_ILSVRC_19_layers.caffemodel')
os.system('wget... | 1,337 | 35.162162 | 169 | py |
HighOrderAtten | HighOrderAtten-master/data/vqa_preprocess.py | """
Download the vqa data and preprocessing.
Version: 1.0
Contributor: Jiasen Lu
"""
# Download the VQA Questions from http://www.visualqa.org/download.html
import json
import os
import argparse
def download_vqa():
os.system('wget http://visualqa.org/data/mscoco/vqa/Questions_Train_mscoco.zip -P zip/')
os.s... | 8,123 | 43.393443 | 137 | py |
HighOrderAtten | HighOrderAtten-master/data/prepro_vqa.py | '''
Preoricess a raw json dataset into hdf5/json files.
Caption: Use NLTK or split function to get tokens.
'''
from random import shuffle, seed
import sys
import os.path
import argparse
import numpy as np
import scipy.io
import pdb
import h5py
from nltk.tokenize import word_tokenize
import json
import re
import math
... | 11,897 | 37.882353 | 153 | py |
MCEdit-Unified | MCEdit-Unified-master/setuptest.py | try:
from pymclevel import _nbt
print "Succesfully imported _nbt"
except ImportError as err:
print "An error occurred while importing _nbt.c ({0})".format(err)
| 172 | 27.833333 | 70 | py |
MCEdit-Unified | MCEdit-Unified-master/renderer.py | """Copyright (c) 2010-2012 David Rio Vierra
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WA... | 146,617 | 35.572213 | 153 | py |
MCEdit-Unified | MCEdit-Unified-master/glbackground.py | """Copyright (c) 2010-2012 David Rio Vierra
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WA... | 2,034 | 36 | 119 | py |
MCEdit-Unified | MCEdit-Unified-master/player_cache.py | import json
import urllib2
from directories import userCachePath
import os
import time
from PIL import Image
import atexit
import threading
import logging
from uuid import UUID
import httplib
import base64
import datetime
import traceback
log = logging.getLogger(__name__)
class ThreadRS(threading.Thread):
# This... | 20,783 | 38.739962 | 137 | py |
MCEdit-Unified | MCEdit-Unified-master/bresenham.py | def bresenham(p1, p2):
"""Bresenham line algorithm
adapted for 3d. slooooow."""
coords = []
x, y, z = p1
x2, y2, z2 = p2
dx = abs(x2 - x)
if (x2 - x) > 0:
sx = 1
else:
sx = -1
dy = abs(y2 - y)
if (y2 - y) > 0:
sy = 1
else:
sy = -1
dz = ab... | 1,005 | 19.958333 | 46 | py |
MCEdit-Unified | MCEdit-Unified-master/fileEdits.py | from editortools.operation import Operation
import itertools
from albow import alert
class fileEdit:
def __init__(self, filename, timeChanged, box, editor, level):
self.filename = filename
self.timeChanged = timeChanged
self.box = box
self.editor = editor
self.level = level
... | 4,986 | 37.068702 | 118 | py |
MCEdit-Unified | MCEdit-Unified-master/keys.py | # -*- coding: utf_8 -*-
#.# Marks the layout modifications. -- D.C.-G.
from config import config
import albow
from albow.dialogs import Dialog
from albow.translate import _
from glbackground import Panel
from albow import Button, Column
ESCAPE = '\033'
def remapMouseButton(button):
buttons = [0, 1, 3, 2, 4, 5, 6... | 30,426 | 35.395933 | 238 | py |
MCEdit-Unified | MCEdit-Unified-master/hook-updater4pyi.py | # hook for pyinstaller
import updater4pyi
import updater4pyi.util
import os.path
def locpath(x):
return os.path.realpath(os.path.join(os.path.dirname(updater4pyi.__file__), x))
datas = [
(locpath('cacert.pem'), 'updater4pyi'),
]
if updater4pyi.util.is_linux() or updater4pyi.util.is_macosx():
datas += ... | 668 | 22.892857 | 85 | py |
MCEdit-Unified | MCEdit-Unified-master/setup.py | import sys
import os
import platform
import distutils.file_util
from setuptools import setup
from Cython.Build import cythonize
# Output annotated .html
import Cython.Compiler.Options
Cython.Compiler.Options.annotate = True
modules_map = {
"png": {"source": "cpngfilters.pyx",
"description": "Build the... | 2,709 | 30.511628 | 91 | py |
MCEdit-Unified | MCEdit-Unified-master/pyperclip.py | """
Pyperclip
A cross-platform clipboard module for Python. (only handles plain text for now)
By Al Sweigart [email protected]
BSD License
Usage:
import pyperclip
pyperclip.copy('The text to be copied to the clipboard.')
spam = pyperclip.paste()
On Windows, no additional modules are needed.
On Mac, this ... | 5,760 | 27.805 | 167 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.