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 |
|---|---|---|---|---|---|---|
csshar_tfa | csshar_tfa-main/utils/experiment_utils.py | import datetime
import json
import os
import random
import numpy as np
import torch
import yaml
def generate_experiment_id():
""" A function for generating unique experiment id based on the current time"""
return str(datetime.datetime.now()).replace(' ', '_').replace(':', '_').replace('.', '_')
def generat... | 1,704 | 25.640625 | 93 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/SUT 2.py | import matplotlib.pyplot as plt
from typing import List
import pandas as pd
import numpy as np
import random
def sum(a,b):
return a + b
def sub(a,b):
return a - b
if __name__ == '__main__':
import click
@click.command()
@click.option('-i', '--file', 'file_in', help='Path for getting the dat... | 4,608 | 38.059322 | 111 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/inputGenerator.py | from typing import List
import random
#A string of up to `max_length` characters'''
#in the range [`char_start`, `char_start` + `char_range`)'''
def fuzzer(max_length: int = 100, char_start: int = 32, char_range: int = 32) -> str:
string_length = random.randrange(0, max_length + 1)
out = ""
for i in rang... | 1,235 | 24.75 | 85 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/MRs_Checker.py | import pandas as pd
## 0 means violated
## 1 means not-violated
def MRsChecker(df):
for index, row in df.iterrows():
## MR_1 ##
if row['output'] == row['MR1_output']:
finalLog.at[index, 'MR1_checker'] = 'No-violated'
if row['output'] != row['MR1_output']:
... | 1,614 | 22.75 | 98 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/SUT_onlySub_sameConstant.py | import matplotlib.pyplot as plt
from typing import List
import pandas as pd
import numpy as np
import random
def sum(a,b):
return a + b
def sub(a,b):
return a - b
if __name__ == '__main__':
import click
@click.command()
@click.option('-i', '--file', 'file_in', help='Path for getting the dat... | 5,094 | 36.740741 | 98 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/MT.py | import pandas as pd
import shortuuid
import sys
from SUT import calculator
def SutExecution(input_a, input_b, op):
if op == 'sum':
return calculator(input_b, input_a).add()
if op == 'sub':
return calculator(input_b, input_a).subtraction()
if op == 'mul':
return calculator(inp... | 9,176 | 41.09633 | 137 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/inputGenerator_v2.py | 0 | 0 | 0 | py | |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/plot.py | import pandas as pd
import numpy as np
import glob as gl
import pickle
from efficient_apriori import apriori
import matplotlib.pyplot as plt
import warnings
import os
import pathlib
import seaborn as sns
import statsmodels.api as sm
import scipy.stats as stats
warnings.filterwarnings('ignore')
from matplotlib import ... | 1,178 | 23.5625 | 86 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/SUT_onlySum_sameConstant.py | import matplotlib.pyplot as plt
from typing import List
import pandas as pd
import numpy as np
import random
def sum(a,b):
return a + b
def sub(a,b):
return a - b
if __name__ == '__main__':
import click
@click.command()
@click.option('-i', '--file', 'file_in', help='Path for getting the dat... | 4,791 | 36.4375 | 98 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/SUT_onlySum.py | import matplotlib.pyplot as plt
from typing import List
import pandas as pd
import numpy as np
import random
def sum(a,b):
return a + b
def sub(a,b):
return a - b
if __name__ == '__main__':
import click
@click.command()
@click.option('-i', '--file', 'file_in', help='Path for getting the dat... | 4,791 | 36.4375 | 98 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/SUT_op.py | import matplotlib.pyplot as plt
from typing import List
import pandas as pd
import numpy as np
import random
def sum(a,b):
return a + b
def sub(a,b):
return a - b
if __name__ == '__main__':
import click
@click.command()
@click.option('-i', '--file', 'file_in', help='Path for getting the dat... | 4,586 | 37.546218 | 111 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/SUT_onlySub.py | import matplotlib.pyplot as plt
from typing import List
import pandas as pd
import numpy as np
import random
def sum(a,b):
return a + b
def sub(a,b):
return a - b
if __name__ == '__main__':
import click
@click.command()
@click.option('-i', '--file', 'file_in', help='Path for getting the dat... | 5,094 | 36.740741 | 98 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/SUT.py | class calculator():
def __init__( self, x, y ):
self.x = x
self.y = y
def add(self):
return self.x + self.y
def subtraction(self):
return self.x - self.y
def multiplication(self):
return self.x * self.y
# def division(self):
# try:
# return self.x / self.y
# ... | 346 | 14.772727 | 32 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/firstResults_ConsCero/AuxScripts/csv-joiner.py | import os
import glob as gl
import pathlib
import pandas as pd
# set working directory
# os.chdir("/mydir")
# find all csv files in the folder
# use glob pattern matching -> extension = 'csv'
# save result in list -> all_filenames
def joiner(path, save_path, file_out):
extension = 'csv'
all_filenames = [i fo... | 1,036 | 26.289474 | 79 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/Atheris/firstPhase/src_tests_fuzzer.py | import atheris
import pandas as pd
import shortuuid
import sys
with atheris.instrument_imports():
from toy_example import calculator
# @atheris.instrument_func
def test_add(data):
constant = 3
fdp = atheris.FuzzedDataProvider(data)
# input = fdp.ConsumeIntList(2,1)
inputs = fdp.ConsumeIntListI... | 3,493 | 30.196429 | 95 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/Atheris/firstPhase/fuzzing_toy_example.py | from pathlib import Path
import subprocess
import pandas as pd
import os
import sys
import atheris
# if __name__ == '__main__':
# args = sys.argv
# import click
# @click.command()
# @click.option('-o', '--out', 'file_out', help = 'name for savig the logs')
# def main(file_out):
# subp =... | 1,968 | 26.347222 | 115 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/Atheris/firstPhase/MRs_checker.py | import pandas as pd
## 0 means violated
## 1 means not-violated
# ,id,input_a,input_b,output_add,output_sub,output_add_MR1,output_sub_MR1,output_add_MR2,output_sub_MR2,output_add_MR3,output_sub_MR3,output_add_MR4,output_sub_MR4
def MRsChecker(df):
for index, row in df.iterrows():
#### ADD
## MR_... | 2,970 | 28.415842 | 163 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/Atheris/firstPhase/toy_example.py | class calculator():
def __init__( self, x, y ):
self.x = x
self.y = y
def add(self):
return self.x + self.y
def subtraction(self):
return self.x - self.y
def multiplication(self):
return self.x * self.y
# def division(self):
# try:
# return self.x / self.y
... | 349 | 14.909091 | 32 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/Atheris/firstPhase/followUp-tests.py | import pandas as pd
| 21 | 6.333333 | 19 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/Atheris/AtherisExp/prueba.py | import struct
import atheris
from calculator import *
import sys
with atheris.instrument_imports():
import calculator
# def TestOneInput(data1):
# print('data:', data1)
# # print('data1:', data1[1])
# # print('data2:', data1[0])
# def TestOneInput2( data):
# print('data:', data)
# # print('data1:', d... | 1,237 | 24.791667 | 80 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/Atheris/AtherisExp/calculator_v2.py | class calculator():
def __init__(self,x,y):
self.x=x
self.y=y
def add(self):
print("Sum :",self.x+self.y)
def subtraction(self):
print("Subtraction :",self.x-self.y)
def multiplication(self):
print("Multiplication :",self.x*self.y)
def division(self):
print("Division :",self.x/se... | 370 | 18.526316 | 43 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/Atheris/AtherisExp/prueba_v2.py | import struct
import atheris
import sys
with atheris.instrument_imports():
from calculator_v2 import calculator
# def TestOneInput(data1):
# print('data:', data1)
# # print('data1:', data1[1])
# # print('data2:', data1[0])
# def TestOneInput2( data):
# print('data:', data)
# # print('data1:', data1[1... | 1,265 | 25.375 | 80 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/Atheris/AtherisExp/calculator.py | class Calculator:
def add(self, a, b):
return a + b
def sub(self, a, b):
return a - b
def mul(self, a, b):
return a * b
def div(self, a, b):
return a / b
| 222 | 14.928571 | 24 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/Atheris/thirdPhase-regressionTesting/mutation/test_toy_example.py | from toy_example import calculator
# import pandas as pd
def test_add():
# inputs = pd.read_csv('log_1000.csv', index_col= 0)
assert calculator(2,4).add == 6
| 169 | 17.888889 | 56 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/Atheris/thirdPhase-regressionTesting/mutation/toy_example.py | class calculator():
def __init__( self, x, y ):
self.x = x
self.y = y
def add(self):
return self.x + self.y
def subtraction(self):
return self.x - self.y
def multiplication(self):
return self.x * self.y
# def division(self):
# try:
# return self.x / self.y
... | 349 | 14.909091 | 32 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/Atheris/ToyExample_AtherisExample/fuzzing_toy_example.py | import sys
import zlib
import atheris
import coverage
import ast
from pathlib import Path
from mutatest import run
from mutatest import transformers
from mutatest.api import Genome, GenomeGroup, MutationException
from mutatest.filters import CoverageFilter, CategoryCodeFilter
with atheris.instrument_imports():
... | 1,338 | 19.921875 | 109 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/Atheris/ToyExample_AtherisExample/toy_example.py | class calculator():
def __init__( self, x, y ):
self.x = x
self.y = y
def add(self):
return self.x + self.y
def subtraction(self):
return self.x - self.y
def multiplication(self):
return self.x * self.y
# def division(self):
# try:
# return self.x / self.y
... | 349 | 14.909091 | 32 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/Atheris/mutation/SUT/test_toy_example.py | import sys
import zlib
import atheris
import coverage
import ast
from pathlib import Path
from mutatest import run
from mutatest import transformers
from mutatest.api import Genome, GenomeGroup, MutationException
from mutatest.filters import CoverageFilter, CategoryCodeFilter
with atheris.instrument_imports():
... | 1,338 | 19.921875 | 109 | py |
VST2023-BugORNOTbug | VST2023-BugORNOTbug-main/Atheris/mutation/SUT/toy_example.py | class calculator():
def __init__( self, x, y ):
self.x = x
self.y = y
def add(self):
return self.x + self.y
def subtraction(self):
return self.x - self.y
def multiplication(self):
return self.x * self.y
# def division(self):
# try:
# return self.x / self.y
... | 349 | 14.909091 | 32 | py |
bluest | bluest-main/setup.py | from setuptools import setup
from pybind11.setup_helpers import intree_extensions
ext_modules = intree_extensions(["bluest/cmisc.cpp"])
ext_modules[0].extra_compile_args[:0] = ["-O3", "-m64", "-ftree-vectorize", "-ffast-math", "-march=native"]
ext_modules[0].name = "_cmisc_bluest"
setup(
name="bluest",
packa... | 492 | 26.388889 | 107 | py |
bluest | bluest-main/tutorials/01_tutorial.py | from bluest import BLUEProblem
import numpy as np
from scipy.special import gamma
# approximate E[e^Z] for Z being a std Gaussian random variable
# model i defined by truncating the exponential series after n_models - i terms
# high-fidelity model defined exactly as exp(Z).
# lowest fidelity model defined as log(|Z|) ... | 15,693 | 43.208451 | 183 | py |
bluest | bluest-main/examples/multi_output_example.py | from dolfin import *
from bluest import *
from numpy.random import RandomState
import numpy as np
import math
import sys
set_log_level(30)
mpiRank = MPI.rank(MPI.comm_world)
mpiSize = MPI.size(MPI.comm_world)
verbose = mpiRank == 0
RNG = RandomState(mpiRank)
No = 3
dim = 2 # spatial dimension
buf = 1
n_levels = ... | 7,651 | 35.438095 | 157 | py |
bluest | bluest-main/examples/single_output_example.py | from dolfin import *
from bluest import *
from numpy.random import RandomState
import numpy as np
import math
import sys
set_log_level(30)
mpiRank = MPI.rank(MPI.comm_world)
mpiSize = MPI.size(MPI.comm_world)
verbose = mpiRank == 0
RNG = RandomState(mpiRank)
dim = 2 # spatial dimension
buf = 1
n_levels = 6
meshe... | 6,675 | 33.235897 | 143 | py |
bluest | bluest-main/examples/paper_examples/restrictions_matern/plot_results.py | from numpy import array
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from matplotlib.legend_handler import HandlerTuple
from matplotlib.ticker import MaxNLocator
import subprocess
import os
import sys
################################################# PYPLOT SETUP ############... | 6,779 | 35.648649 | 188 | py |
bluest | bluest-main/examples/paper_examples/restrictions_matern/restrictions_matern.py | from dolfin import *
from bluest import *
from numpy.random import RandomState
import numpy as np
import math
import sys
import os
from io import StringIO
from single_matern_field import MaternField,make_nested_mapping
from cvxpy.error import SolverError
from mpi4py.MPI import PROD as MPIPROD
set_log_level(30)
comm =... | 16,880 | 38.813679 | 246 | py |
bluest | bluest-main/examples/paper_examples/restrictions_matern/single_matern_field.py | from dolfin import *
from petsc4py import PETSc
import numpy as np
from scipy.sparse import csr_matrix
from scipy.special import gammaln
from scipy.spatial import cKDTree
def gammaratio(x,y): # computes the ratio between \Gamma(x) and \Gamma(y)
return np.exp(gammaln(x) - gammaln(y))
def make_nested_mapping(outer... | 6,800 | 37.862857 | 179 | py |
bluest | bluest-main/examples/paper_examples/restrictions_matern/plot_histograms.py | from numpy import array
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from matplotlib.legend_handler import HandlerTuple
import subprocess
import os
import sys
################################################# PYPLOT SETUP ###############################################
# cha... | 4,087 | 35.176991 | 188 | py |
bluest | bluest-main/examples/paper_examples/hodgkin-huxley/blue_hodgkin-huxley.py | from dolfin import *
from bluest import *
import numpy as np
from numpy.random import RandomState
from mpi4py import MPI
import sys
import os
import logging
logging.getLogger('FFC').setLevel(logging.WARNING)
set_log_level(LogLevel.ERROR)
worldcomm = MPI.COMM_WORLD
mpiRank = worldcomm.Get_rank()
mpiSize = worldcomm.G... | 14,715 | 31.414097 | 267 | py |
bluest | bluest-main/examples/paper_examples/hodgkin-huxley/hodgkin-huxley.py | import numpy as np
import matplotlib.pyplot as plt
T = 50 # ms
dt = 0.001
N = int(np.ceil(T/dt))
t = np.linspace(0,T,N+1)
dt = T/N
gna = 120
gk = 36
gl = 0.3
vna = 56
vk = -77
vl = -60
Cm = 1
I = 0.005*gna*vna
def alphan(v):
y = np.exp(1-v/10)
return 0.1*np.log(y)/(y-1)
def alpham(v):
y = np.exp(2.5-v/... | 2,053 | 25 | 107 | py |
bluest | bluest-main/examples/paper_examples/hodgkin-huxley/another_hodgkin-huxley.py | import numpy as np
import matplotlib.pyplot as plt
T = 25 # ms
dt = 0.01
N = int(np.ceil(T/dt))
dt = T/float(N)
gna = 1.2
gk = 0.36
gl = 0.003
vna = 55.17
vk = -72.14
vl = -49.42
Cm = 0.01
I = 0.1 #0.005*gna*vna
print(I)
alphan = lambda v : 0.01*(v+50)/(1-np.exp(-5-v/10))
alpham = lambda v : 0.1*(35+v)/(1-np.exp(-... | 1,477 | 24.050847 | 107 | py |
bluest | bluest-main/examples/paper_examples/hodgkin-huxley/pde_hodgkin-huxley.py | from dolfin import *
import numpy as np
import matplotlib.pyplot as plt
import logging
logging.getLogger('FFC').setLevel(logging.WARNING)
set_log_level(LogLevel.ERROR)
mpi_comm = MPI.comm_world
T = 200 # ms
T0 = 2.0
dt = 0.025
N = int(np.ceil(T/dt))
t = np.linspace(0,T,N+1)
dt = T/N
gna = 120
gk = 36
gl = 0.3
vna... | 6,725 | 26.341463 | 113 | py |
bluest | bluest-main/examples/paper_examples/hodgkin-huxley/plot_histograms.py | from numpy import array
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from matplotlib.legend_handler import HandlerTuple
import subprocess
import os
import sys
################################################# PYPLOT SETUP ###############################################
# cha... | 8,238 | 48.041667 | 417 | py |
bluest | bluest-main/examples/paper_examples/navier_stokes/bluest_NS.py | from bluest import *
import numpy as np
from dolfin import set_log_level, MPI, LogLevel, File
from NS import build_space, solve_stokes, solve_navier_stokes, postprocess
import sys
set_log_level(30)
set_log_level(LogLevel.ERROR)
mpiRank = MPI.rank(MPI.comm_world)
mpiSize = MPI.size(MPI.comm_world)
verbose = mpiRank =... | 5,564 | 35.611842 | 192 | py |
bluest | bluest-main/examples/paper_examples/navier_stokes/NS.py | # as in https://fenics-handson.readthedocs.io/en/latest/navierstokes/doc.html#steady-navier-stokes-flow
from dolfin import *
import matplotlib.pyplot as plt
from mesh_generator import MPI_generate_NS_mesh
from mpi4py import MPI
import logging
logging.getLogger('FFC').setLevel(logging.WARNING)
set_log_level(LogLevel.... | 8,539 | 29.609319 | 146 | py |
bluest | bluest-main/examples/paper_examples/navier_stokes/mesh_generator.py | import pygmsh
import meshio
import sys
import os
def create_mesh(mesh, cell_type, prune_z=False):
cells = mesh.get_cells_type(cell_type)
cell_data = mesh.get_cell_data("gmsh:physical", cell_type)
points = mesh.points[:,:2] if prune_z else mesh.points
out_mesh = meshio.Mesh(points=points, cells={cell_ty... | 5,319 | 35.689655 | 129 | py |
bluest | bluest-main/examples/paper_examples/navier_stokes/plot_histograms.py | from numpy import array
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Patch
from matplotlib.legend_handler import HandlerTuple
import subprocess
import os
import sys
################################################# PYPLOT SETUP ###############################################
# cha... | 7,486 | 50.993056 | 560 | py |
bluest | bluest-main/bluest/blue_models.py | import numpy as np
import networkx as nx
from itertools import combinations
from mpi4py.MPI import COMM_WORLD
from .blue_fn import blue_fn
from .mosap import MOSAP,BLUESTError
from .misc import attempt_mlmc_setup,attempt_mfmc_setup,compute_mfmc_data
from .spg import spg
spg_default_params = {"maxit" : 10000,
... | 43,930 | 43.736253 | 347 | py |
bluest | bluest-main/bluest/mosap.py | import numpy as np
from itertools import combinations, product
from .sap import SAP,mosek_params,cvxpy_default_params,cvxopt_default_params
from .misc import best_closest_integer_solution_BLUE_multi
import cvxpy as cp
from scipy.sparse import csr_matrix, bmat, find
from cvxopt import matrix,spmatrix,solvers
def csr_t... | 31,774 | 46.71021 | 434 | py |
bluest | bluest-main/bluest/misc.py | import numpy as np
from itertools import combinations, product
try: from numba import njit
except ImportError:
def njit(*args, **kwargs):
def decorator(func):
return func
return decorator
from _cmisc_bluest import assemble_psi_c,objectiveK_c,gradK_c,hessKQ_c,cleanupK_c
##############... | 21,921 | 33.796825 | 180 | py |
bluest | bluest-main/bluest/blue_fn.py | # blue function for coupled levels
from numpy import zeros, array, isfinite, ndarray, savez_compressed, load
from numpy.random import RandomState
from numpy import sum as npsum
from time import time
from inspect import signature
from shutil import get_terminal_size
from mpi4py.MPI import COMM_WORLD, SUM
import os
col... | 9,102 | 39.101322 | 169 | py |
bluest | bluest-main/bluest/__init__.py | __author__ = 'Matteo Croci'
__credits__ = ['Matteo Croci']
__license__ = 'MIT'
__maintainer__ = 'Matteo Croci'
__email__ = 'matteo.croci@austin.utexas.edu'
from .blue_fn import blue_fn
from .sap import SAP
from .mosap import MOSAP,BLUESTError
from .blue_models import BLUEProblem
| 296 | 26 | 49 | py |
bluest | bluest-main/bluest/spg.py | import numpy as np
def linesearch(feval, x, f, g, d, Hlength, last_fval, max_fevals, count):
sigma_min = 0.1
sigma_max = 0.9
gamma = 10**-4
fmax = max(last_fval)
gdotd = g@d
alpha = 1.0
xnew = x + alpha*d
fnew = feval(xnew)
count += 1
while fnew > fmax + gamma*alpha*gdotd an... | 4,360 | 25.271084 | 137 | py |
bluest | bluest-main/bluest/sap.py | import numpy as np
from itertools import combinations
import cvxpy as cp
from scipy.sparse import csr_matrix, bmat, find
from cvxopt import matrix,spmatrix,solvers
from .misc import assemble_psi,get_phi_full,variance_full,variance_GH_full,PHIinvY0,best_closest_integer_solution_BLUE,assemble_cleanup_matrix
##########... | 21,261 | 42.839175 | 391 | py |
LYNX-BeyondDuplicates | LYNX-BeyondDuplicates-main/data/data_extract.py | from export import data_access
import logging
import pandas as pd
import itertools
import collections
from collections import Counter, defaultdict
import statistics
import itertools
import re
import math
from pprint import pprint
from bs4 import BeautifulSoup as Soup
import datetime
logging.basicConfig(level=logging.I... | 9,737 | 29.526646 | 81 | py |
LYNX-BeyondDuplicates | LYNX-BeyondDuplicates-main/data/data_access.py | """
created at: 2018-12-11
author: anonymous
"""
import configparser
import logging
from export import util
from pymongo import MongoClient
from pymongo.errors import ServerSelectionTimeoutError, ConnectionFailure, NetworkTimeout, OperationFailure, \
ConfigurationError
from pymongo.auth import MECHANISMS
logging.... | 3,681 | 38.170213 | 112 | py |
code-docstring-corpus | code-docstring-corpus-master/scripts/extract_funcdefs_and_docstrings.py | #! /usr/bin/python
import sys
import ast
import re
import astunparse
def prettify_docstring(docstr):
docstr = docstr.replace("DCQT", "DCQTDCQT").replace("DCNL", "DCQTDCNL")
docstr = docstr.replace("'", "\\'")
rv_list = []
for line in docstr.split('\n'):
line = line.strip() # Remove whitespa... | 3,912 | 36.625 | 162 | py |
code-docstring-corpus | code-docstring-corpus-master/scripts/filter_additional_parallel_by_repos.py | #! /usr/bin/python
import sys
def main():
if len(sys.argv) != 10:
usage()
decl_fs = open(sys.argv[1])
desc_fs = open(sys.argv[2])
bodies_fs = open(sys.argv[3])
meta_fs = open(sys.argv[4])
repos_fs = open(sys.argv[5])
out_decl_fs = open(sys.argv[6], "w")
out_desc_fs = open(sys.... | 1,296 | 27.195652 | 185 | py |
code-docstring-corpus | code-docstring-corpus-master/scripts/filter_mono_by_repos.py | #! /usr/bin/python
import sys
def main():
if len(sys.argv) != 8:
usage()
decl_fs = open(sys.argv[1])
bodies_fs = open(sys.argv[2])
meta_fs = open(sys.argv[3])
repos_fs = open(sys.argv[4])
out_decl_fs = open(sys.argv[5], "w")
out_bodies_fs = open(sys.argv[6], "w")
out_meta_fs =... | 1,105 | 25.333333 | 145 | py |
code-docstring-corpus | code-docstring-corpus-master/scripts/get_lines_by_num.py | #! /usr/bin/python
import sys
def main():
if len(sys.argv) != 2:
usage()
line_ids_fd = open(sys.argv[1])
lines = sys.stdin.readlines()
for line_id_str in line_ids_fd:
line_id = int(line_id_str.strip()) - 1
print lines[line_id].strip()
def usage():
print >> sys.stderr, "Usa... | 443 | 18.304348 | 60 | py |
code-docstring-corpus | code-docstring-corpus-master/scripts/extract_modules_and_classes.py | #! /usr/bin/python
import sys
import ast
import re
import astunparse
def prettify_docstring(docstr):
docstr = docstr.replace("DCQT", "DCQTDCQT").replace("DCNL", "DCQTDCNL").replace("DCNA", "DCQTDCNA")
docstr = docstr.replace("'", "\\'")
rv_list = []
for line in docstr.split('\n'):
line = line... | 4,004 | 40.28866 | 189 | py |
code-docstring-corpus | code-docstring-corpus-master/scripts/extract_funcdefs_and_meta_without_docstrings_properspacing.py | #! /usr/bin/python
import sys
import ast
import re
import astunparse
# reduce identation to one space (or custom separator) per level
# assumes that the original code uses 4 spaces per level
def reduce_ident(line, ident_separator=" "):
line = line.rstrip()
line_all_stripped = line.lstrip()
n_spaces = len... | 3,286 | 34.728261 | 162 | py |
code-docstring-corpus | code-docstring-corpus-master/scripts/PyRepo.py | import os
from git import Repo
class PyRepo:
def __init__(self, name, full_name, description, clone_url, timestamp, num_stars, num_forks, created_at, pushed_at):
self._name = name
self._full_name = full_name
self._description = description
self._clone_url = clone_url
self._... | 2,075 | 25.961039 | 133 | py |
code-docstring-corpus | code-docstring-corpus-master/scripts/extract_commit_data.py | #! /usr/bin/python
import sys
import cPickle
def main():
if len(sys.argv) != 2:
usage()
database = cPickle.load(open(sys.argv[1]))
for e in database:
print e.name, e.last_commit_sha
def usage():
print >> sys.stderr, 'Usage:'
print >> sys.stderr, sys.argv[0], 'pickle-file-name'
... | 376 | 15.391304 | 56 | py |
code-docstring-corpus | code-docstring-corpus-master/scripts/repo_train_valid_test_split.py | #! /usr/bin/python
import sys
import numpy as np
from collections import defaultdict
def pick_repos(repos, repos_count_dict, repos_mean_size, target_size):
rv = []
cur_size = 0
while cur_size < target_size - 0.5 * repos_mean_size:
repo = repos.pop()
cur_size += repos_count_dict[repo]
... | 2,839 | 34.5 | 143 | py |
code-docstring-corpus | code-docstring-corpus-master/scripts/rename_data_dirs_with_commits.py | #! /usr/bin/python
import sys
import cPickle
import os
def main():
if len(sys.argv) != 3:
usage()
database = cPickle.load(open(sys.argv[1]))
commit_dict = {}
for e in database:
commit_dict[e.full_name] = e.last_commit_sha
data_dir = sys.argv[2]
for user_dir in os.listdir(... | 766 | 22.96875 | 92 | py |
code-docstring-corpus | code-docstring-corpus-master/scripts/extract_funcdefs_without_docstrings.py | #! /usr/bin/python
import sys
import ast
import re
import astunparse
# reduce identation to one space (or custom separator) per level
# assumes that the original code uses 4 spaces per level
def reduce_ident(line, ident_separator=" "):
line = line.rstrip()
line_all_stripped = line.lstrip()
n_spaces = len... | 2,995 | 33.045455 | 162 | py |
code-docstring-corpus | code-docstring-corpus-master/scripts/find_shuffled_line_nums.py | #! /usr/bin/python
import sys
def main():
if len(sys.argv) != 2:
usage()
line_dict = {}
unshuf_fd = open(sys.argv[1])
for i, line in enumerate(unshuf_fd):
line = line.strip()
line_dict[line] = i
for i, line in enumerate(sys.stdin):
line = line.strip()
if li... | 661 | 20.354839 | 71 | py |
code-docstring-corpus | code-docstring-corpus-master/scripts/extract_methoddefs_and_meta_without_docstrings_properspacing.py | #! /usr/bin/python
import sys
import ast
import re
import astunparse
# reduce identation to one space (or custom separator) per level
# assumes that the original code uses 4 spaces per level
def reduce_ident(line, ident_separator=" "):
line = line.rstrip()
line_all_stripped = line.lstrip()
n_spaces = len... | 3,803 | 37.424242 | 162 | py |
code-docstring-corpus | code-docstring-corpus-master/scripts/extract_methoddefs_and_docstrings_and_meta_properspacing.py | #! /usr/bin/python
import sys
import ast
import re
import astunparse
def prettify_docstring(docstr):
docstr = docstr.replace("DCQT", "DCQTDCQT").replace("DCNL", "DCQTDCNL")
docstr = docstr.replace("'", "\\'")
rv_list = []
for line in docstr.split('\n'):
line = line.strip() # Remove whitespa... | 4,756 | 40.008621 | 162 | py |
code-docstring-corpus | code-docstring-corpus-master/scripts/extract_funcdefs_and_docstrings_and_meta_properspacing.py | #! /usr/bin/python
import sys
import ast
import re
import astunparse
def prettify_docstring(docstr):
docstr = docstr.replace("DCQT", "DCQTDCQT").replace("DCNL", "DCQTDCNL")
docstr = docstr.replace("'", "\\'")
rv_list = []
for line in docstr.split('\n'):
line = line.strip() # Remove whitespa... | 4,203 | 37.925926 | 162 | py |
API-Editor | API-Editor-main/data/client/titanic.py | import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder
data = pd.read_csv("data/train.csv", index_col="PassengerId")
data = data.dro... | 1,671 | 29.962963 | 81 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/test_dir.py | import sys
import os
import os.path as osp
import pdb
import json
import tqdm
import numpy as np
import torch
import torch.nn.functional as F
from dirtorch.utils.convenient import mkdir
from dirtorch.utils import common
from dirtorch.utils.common import tonumpy, matmul, pool
from dirtorch.utils.pytorch_loader import ... | 9,805 | 36.715385 | 131 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/extract_features.py | import sys
import os
import os.path as osp
import pdb
import json
import tqdm
import numpy as np
import torch
import torch.nn.functional as F
from dirtorch.utils.convenient import mkdir
from dirtorch.utils import common
from dirtorch.utils.common import tonumpy, matmul, pool
from dirtorch.utils.pytorch_loader import ... | 4,874 | 37.385827 | 131 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/loss.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class APLoss (nn.Module):
""" Differentiable AP loss, through quantization. From the paper:
Learning with Average Precision: Training Image Retrieval with a Listwise Loss
Jerome Revaud, Jon Almazan, Rafael Sampa... | 8,245 | 35.8125 | 120 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/extract_kapture.py | import os
import tqdm
import torch.nn.functional as F
from typing import Optional
os.environ['DB_ROOT'] = ''
from dirtorch.utils import common # noqa: E402
from dirtorch.utils.common import tonumpy, pool # noqa: E402
from dirtorch.datasets.generic import ImageList # noqa: E402
from dirtorch.test_dir import extract... | 7,658 | 49.388158 | 119 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/nets/__main__.py | from . import model_names
# python -m nets
print("Listing available architectures:")
print("\t" + "\n\t".join(model_names))
| 125 | 20 | 41 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/nets/rmac_resnet_fpn.py | import pdb
from .backbones.resnet import *
from .layers.pooling import GeneralizedMeanPooling, GeneralizedMeanPoolingP
def l2_normalize(x, axis=-1):
x = F.normalize(x, p=2, dim=axis)
return x
class ResNet_RMAC_FPN(ResNet):
""" ResNet for RMAC (without ROI pooling)
"""
def __init__(self, block, l... | 3,816 | 25.692308 | 96 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/nets/rmac_resnext.py | from .backbones.resnext101_features import *
from .layers.pooling import GeneralizedMeanPooling, GeneralizedMeanPoolingP
def l2_normalize(x, axis=-1):
x = F.normalize(x, p=2, dim=axis)
return x
class ResNext_RMAC(nn.Module):
""" ResNet for RMAC (without ROI pooling)
"""
def __init__(self, backbo... | 2,731 | 23.176991 | 112 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/nets/rmac_resnet.py | import pdb
import torch
from .backbones.resnet import *
from .layers.pooling import GeneralizedMeanPooling, GeneralizedMeanPoolingP
def l2_normalize(x, axis=-1):
x = F.normalize(x, p=2, dim=axis)
return x
class ResNet_RMAC(ResNet):
""" ResNet for RMAC (without ROI pooling)
"""
def __init__(self,... | 2,838 | 23.059322 | 112 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/nets/__init__.py | ''' List all architectures at the bottom of this file.
To list all available architectures, use:
python -m nets
'''
import os
import pdb
import torch
from collections import OrderedDict
internal_funcs = set(globals().keys())
from .backbones.resnet import resnet101, resnet50, resnet18, resnet152
from .rmac_resnet... | 3,084 | 23.484127 | 142 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/nets/layers/pooling.py | import pdb
import numpy as np
import torch
from torch.autograd import Variable
import torch.nn as nn
from torch.nn.modules import Module
from torch.nn.parameter import Parameter
import torch.nn.functional as F
import math
class GeneralizedMeanPooling(Module):
r"""Applies a 2D power-average adaptive pooling over a... | 1,815 | 30.859649 | 106 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/nets/backbones/resnet.py | import torch.nn as nn
import torch
import math
import numpy as np
from torch.autograd import Variable
import torch.nn.functional as F
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padd... | 7,827 | 33.333333 | 167 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/nets/backbones/resnext101_features.py | from __future__ import print_function, division, absolute_import
import torch
import torch.nn as nn
from torch.autograd import Variable
from functools import reduce
class LambdaBase(nn.Sequential):
def __init__(self, fn, *args):
super(LambdaBase, self).__init__(*args)
self.lambda_func = fn
def... | 57,499 | 41.942494 | 91 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/nets/backbones/__init__.py | from collections import OrderedDict
def load_pretrained_weights(net, state_dict):
""" Load the pretrained weights.
If layers are missing or of wrong shape, will not load them.
"""
new_dict = OrderedDict()
for k,v in list(state_dict.items()):
if k.startswith('module.'): k = k.replace('... | 876 | 34.08 | 102 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/datasets/__main__.py | import os
import sys
import pdb
from nltools.gutils.pyplot import *
def viz_dataset(db, nr=6, nc=6):
''' a convenient way to vizualize the content of a dataset.
If there are queries, it will show the ground-truth for each query.
'''
pyplot(globals())
try:
query_db = db.get_query_... | 2,123 | 24.285714 | 75 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/datasets/downloader.py | import os
import os.path as osp
DB_ROOT = os.environ['DB_ROOT']
def download_dataset(dataset):
if not os.path.isdir(DB_ROOT):
os.makedirs(DB_ROOT)
dataset = dataset.lower()
if dataset in ('oxford5k', 'roxford5k'):
src_dir = 'http://www.robots.ox.ac.uk/~vgg/data/oxbuildings'
dl_fil... | 2,439 | 45.037736 | 97 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/datasets/landmarks.py | import os
from .generic import ImageListLabels
DB_ROOT = os.environ['DB_ROOT']
class Landmarks_clean(ImageListLabels):
def __init__(self):
ImageListLabels.__init__(self, os.path.join(DB_ROOT, 'landmarks/annotations/annotation_clean_train.txt'),
os.path.join(DB_ROOT, 'landm... | 827 | 40.4 | 113 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/datasets/dataset.py | import os
import json
import pdb
import numpy as np
from collections import defaultdict
class Dataset(object):
''' Base class for a dataset. To be overloaded.
Contains:
- images --> get_image(i) --> image
- image labels --> get_label(i)
- list o... | 20,116 | 33.212585 | 150 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/datasets/create.py | from .dataset import split, deploy, deploy_and_split
from .generic import *
class DatasetCreator:
''' Create a dataset from a string.
dataset_cmd (str):
Command to execute.
ex: "ImageList('path/to/list.txt')"
Returns:
instanciated dataset.
'''
def __init__(self, globs):
... | 922 | 28.774194 | 148 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/datasets/generic.py | import os
import json
import pdb
import numpy as np
import pickle
import os.path as osp
import json
from .dataset import Dataset
from .generic_func import *
class ImageList(Dataset):
''' Just a list of images (no labels, no query).
Input: text file, 1 image path per row
'''
def __init__(self, img_l... | 9,990 | 32.303333 | 118 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/datasets/oxford.py | import os
from .generic import ImageListRelevants
DB_ROOT = os.environ['DB_ROOT']
class Oxford5K(ImageListRelevants):
def __init__(self):
ImageListRelevants.__init__(self, os.path.join(DB_ROOT, 'oxford5k/gnd_oxford5k.pkl'),
root=os.path.join(DB_ROOT, 'oxford5k'))
class RO... | 541 | 35.133333 | 94 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/datasets/paris.py | from .generic import ImageListRelevants
import os
DB_ROOT = os.environ['DB_ROOT']
class Paris6K(ImageListRelevants):
def __init__(self):
ImageListRelevants.__init__(self, os.path.join(DB_ROOT, 'paris6k/gnd_paris6k.pkl'),
root=os.path.join(DB_ROOT, 'paris6k'))
class RParis... | 533 | 34.6 | 92 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/datasets/generic_func.py | ''' Generic functions for Dataset() class
'''
import pdb
import numpy as np
from collections import defaultdict
def find_and_list_classes(labels, cls_idx=None ):
''' Given a list of image labels, deduce the list of classes.
Parameters:
-----------
labels : list
per-image labels (can be str, i... | 1,829 | 28.047619 | 107 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/datasets/landmarks18.py | import os
from .generic import ImageListLabels, ImageList
DB_ROOT = os.environ['DB_ROOT']
class Landmarks18_train(ImageListLabels):
def __init__(self):
ImageListLabels.__init__(self, os.path.join(DB_ROOT, 'landmarks18/lists/train.txt'),
os.path.join(DB_ROOT, 'landmarks18/'... | 2,853 | 41.597015 | 102 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/datasets/__init__.py | try: from .oxford import *
except ImportError: pass
try: from .paris import *
except ImportError: pass
try: from .distractors import *
except ImportError: pass
try: from .landmarks import Landmarks_clean, Landmarks_clean_val, Landmarks_lite
except ImportError: pass
try: from .landmarks18 import *
except ImportError: pa... | 491 | 26.333333 | 80 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/utils/funcs.py | """ generic functions
"""
import pdb
import numpy as np
def sigmoid(x, a=1, b=0):
return 1 / (1 + np.exp(a * (b - x)))
def sigmoid_range(x, at5, at95):
""" create sigmoid function like that:
sigmoid(at5) = 0.05
sigmoid(at95) = 0.95
and returns sigmoid(x)
"""
a = 6 ... | 383 | 18.2 | 43 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/utils/convenient.py | import os
################################################
# file stuff
def mkdir(d):
try: os.makedirs(d)
except OSError: pass
def mkdir( fname, isfile='auto' ):
''' Make a directory given a file path
If the path is already a directory, make sure it ends with '/' !
'''
if isfile == 'auto... | 4,220 | 21.333333 | 104 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/utils/pytorch_loader.py | import pdb
from PIL import Image
import numpy as np
import random
import torch
import torch.utils.data as data
def get_loader( dataset, trf_chain, iscuda,
preprocess = {}, # variables for preprocessing (input_size, mean, std, ...)
output = ('img','label'),
batch_size ... | 9,903 | 31.686469 | 119 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/utils/common.py | import os
import sys
import pdb
import shutil
from collections import OrderedDict
import numpy as np
import sklearn.decomposition
import torch
import torch.nn.functional as F
try:
import torch
import torch.nn as nn
except ImportError:
pass
def typename(x):
return type(x).__module__
def tonumpy(x):... | 7,499 | 30.120332 | 104 | py |
deep-image-retrieval | deep-image-retrieval-master/dirtorch/utils/transforms_tools.py | import pdb
import numpy as np
from PIL import Image, ImageOps, ImageEnhance
def is_pil_image(img):
return isinstance(img, Image.Image)
class DummyImg:
''' This class is a dummy image only defined by its size.
'''
def __init__(self, size):
self.size = size
def resize(self, size, *... | 7,792 | 29.924603 | 80 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.