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 |
|---|---|---|---|---|---|---|
LOSTIN | LOSTIN-main/GNN-LSTM/make_master_file.py | ### script for writing meta information of datasets into master.csv
### for graph property prediction datasets.
import pandas as pd
dataset_list = []
dataset_dict = {}
### add cdfg_lut
name = 'vgraph'
dataset_dict[name] = {'eval metric': 'rmse'}
dataset_dict[name]['download_name'] = 'vgraph'
dataset_dict[name]['vers... | 852 | 29.464286 | 67 | py |
LOSTIN | LOSTIN-main/GNN-LSTM/read_graph_pyg.py | import pandas as pd
import torch
from torch_geometric.data import Data
import os.path as osp
import numpy as np
from read_graph_raw import read_csv_graph_raw
from tqdm import tqdm
def read_graph_pyg(raw_dir, add_inverse_edge = False, additional_node_files = [], additional_edge_files = [], binary = False):
graph_l... | 1,387 | 27.916667 | 156 | py |
LOSTIN | LOSTIN-main/GNN-LSTM/read_graph_raw.py | import pandas as pd
import os.path as osp
import os
import numpy as np
from tqdm import tqdm
### reading raw files from a directory.
### for homogeneous graph
def read_csv_graph_raw(raw_dir, add_inverse_edge = False, additional_node_files = [], additional_edge_files = []):
'''
raw_dir: path to the raw director... | 5,396 | 36.741259 | 170 | py |
LOSTIN | LOSTIN-main/GNN-LSTM/main_gnn_customized_inference.py | ### Libraries
# torchtext 0.6.0
import numpy as np
import argparse
from tqdm import tqdm
# Libraries
import matplotlib.pyplot as plts
import pandas as pd
import torch
# Preliminaries
from torchtext.data import Field, TabularDataset, BucketIterator
# Models
import torch.nn as nn
from torch.nn.utils.rnn import pack_pad... | 6,775 | 37.942529 | 169 | py |
LOSTIN | LOSTIN-main/GNN-LSTM/gnn.py | import torch
from torch_geometric.nn import MessagePassing,BatchNorm
from torch_geometric.nn import global_add_pool, global_mean_pool, global_max_pool, GlobalAttention, Set2Set
import torch.nn.functional as F
from torch_geometric.nn.inits import uniform
from torch.nn import Sequential, ReLU, Linear, ModuleList
from co... | 2,744 | 36.60274 | 188 | py |
LOSTIN | LOSTIN-main/GNN-LSTM/conv.py | import torch
from torch_geometric.nn import MessagePassing
import torch.nn.functional as F
from torch_geometric.nn import global_mean_pool, global_add_pool
from node_encoder import NodeEncoder,EdgeEncoder
from torch_geometric.utils import degree
import math
### GIN convolution along the graph structure
class GINConv(... | 8,791 | 35.481328 | 182 | py |
LOSTIN | LOSTIN-main/GNN-LSTM/main_gnn_customized_area.py | ### Libraries
import numpy as np
import argparse
from tqdm import tqdm
import matplotlib.pyplot as plts
import pandas as pd
import torch
# Preliminaries
# torchtext 0.6.0
from torchtext.data import Field, TabularDataset, BucketIterator
# Models
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence... | 9,153 | 36.670782 | 148 | py |
LOSTIN | LOSTIN-main/GNN-LSTM/dataset_pyg.py | from torch_geometric.data import InMemoryDataset
import pandas as pd
import shutil, os
import os.path as osp
import torch
import numpy as np
from read_graph_pyg import read_graph_pyg
class PygGraphPropPredDataset(InMemoryDataset):
def __init__(self, name, root = 'dataset', transform=None, pre_transform = None, me... | 6,691 | 38.364706 | 199 | py |
LOSTIN | LOSTIN-main/LSTM/LSTM_inference.py | ### Libraries
# torchtext 0.6.0
import numpy as np
import argparse
from tqdm import tqdm
# Libraries
import matplotlib.pyplot as plts
import pandas as pd
import torch
# Preliminaries
from torchtext.data import Field, TabularDataset, BucketIterator
# Models
import torch.nn as nn
from torch.nn.utils.rnn import pack_pad... | 6,857 | 33.29 | 149 | py |
LOSTIN | LOSTIN-main/LSTM/LSTM_area.py | ### Libraries
# torchtext 0.6.0
import numpy as np
import argparse
from tqdm import tqdm
# Libraries
import matplotlib.pyplot as plts
import pandas as pd
import torch
# Preliminaries
from torchtext.data import Field, TabularDataset, BucketIterator
# Models
import torch.nn as nn
from torch.nn.utils.rnn import pack_pad... | 9,043 | 34.328125 | 148 | py |
LOSTIN | LOSTIN-main/LSTM/LSTM_delay.py | ### Libraries
# torchtext 0.6.0
import numpy as np
import argparse
from tqdm import tqdm
# Libraries
import matplotlib.pyplot as plts
import pandas as pd
import torch
# Preliminaries
from torchtext.data import Field, TabularDataset, BucketIterator
# Models
import torch.nn as nn
from torch.nn.utils.rnn import pack_pad... | 9,049 | 34.490196 | 148 | py |
LOSTIN | LOSTIN-main/verilog2graph/verilog_cleanser.py | ### remove / and [] in verilog files, so as to be compatible with the parser
path='epfl/'
new_path='epfl_new/'
filename=['adder.v', 'arbiter.v', 'bar.v', 'div.v', 'log2.v', 'max.v', 'multiplier.v', 'sin.v', 'sqrt.v', 'square.v', 'voter.v']
for fname in filename:
# read verilog file
f = open(path + fname, "r")... | 663 | 30.619048 | 128 | py |
LOSTIN | LOSTIN-main/verilog2graph/parser.py | from lark import Lark, Transformer, v_args
from typing import Dict, List, Tuple, Optional, Union
verilog_netlist_grammar = r"""
start: description*
?description: module
?module: "module" identifier list_of_ports? ";" module_item* "endmodule"
list_of_ports: "(" port ("," port)* ")"
?... | 15,344 | 26.450805 | 114 | py |
LOSTIN | LOSTIN-main/verilog2graph/verilog2graph.py | import networkx as nx
import json
from parser import parse_verilog
from graph import Graph
### convert to networkx graphs
def network_to_networkx(network):
"""method to export a pathpy Network to a networkx compatible graph
Parameters
----------
network: Network
Returns
-------
networkx G... | 2,965 | 25.247788 | 130 | py |
LOSTIN | LOSTIN-main/verilog2graph/graph.py | import pathpy as pp
import igraph
import lark
from collections import deque
# Graph class
class Graph:
def __init__(self):
self._graph = pp.Network(directed=True)
self._num_ANDs = 0
self._num_ORs = 0
self._num_NOTs = 0
def create_node(self, node_name, node_type):
node... | 6,086 | 35.668675 | 90 | py |
LOSTIN | LOSTIN-main/CNN/utils.py | import os
import re
import datetime
import numpy as np
from subprocess import check_output
#abc_binary='./abc'
#abc_command='read adder.v; strash;rw; rw; rf; rfz; b; rf; b; rw; rfz; read OCL.lib;map -v;ps;'
#proc = check_output([abc_binary, '-c', abc_command])
def run_abc(input_file, command):
abc_binary='./abc... | 1,941 | 28.876923 | 96 | py |
LOSTIN | LOSTIN-main/CNN/cnn_data_gen.py | import utils
import pandas as pd
import numpy as np
import argparse
import pprint as pp
from os import listdir
from os.path import isfile, join
import torch
from torch.utils.data import TensorDataset, DataLoader
def main(args):
ff_10 = pd.read_csv('flow_10.csv',header=None)
ff_15 = pd.read_csv('flow_15.csv... | 7,046 | 33.208738 | 116 | py |
LOSTIN | LOSTIN-main/CNN/train_cnn.py | import torch
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
import torch.utils.data as Data
from torch.utils.data import TensorDataset, DataLoader
import numpy as np
import argparse
# Keras -> PyTorch Implementation
# Modification: Classification -> Regression
class CNN_Reg... | 5,484 | 31.264706 | 110 | py |
LOSTIN | LOSTIN-main/dataset-generation/utils.py | import os
import re
import datetime
import numpy as np
from subprocess import check_output
#abc_binary='./abc'
#abc_command='read adder.v; strash;rw; rw; rf; rfz; b; rf; b; rw; rfz; read OCL.lib;map -v;ps;'
#proc = check_output([abc_binary, '-c', abc_command])
def run_abc(input_file, command):
abc_binary='./abc... | 1,941 | 28.876923 | 96 | py |
LOSTIN | LOSTIN-main/dataset-generation/run_abc_syn.py | import utils
import pandas as pd
import numpy as np
import argparse
import pprint as pp
def main(args):
if int(args['flow_length'])==10:
ff=pd.read_csv('flow_10.csv',header=None)
elif int(args['flow_length'])==15:
ff=pd.read_csv('flow_15.csv',header=None)
elif int(args['flow_length'])==20... | 2,333 | 35.46875 | 156 | py |
cbm-project | cbm-project-master/driver.py | from igraph import summary
from src.data_read import load, build_graphs
from src.data_synthetic import generate_temporal_graph
from src.transitions import egonet_transitions
def synthetic_data(n=500, p=0.25, anomalies=0.05, anomaly_type='clique', num_graphs=10):
graphs = generate_temporal_graph(n, p, anomalies=an... | 1,881 | 30.898305 | 146 | py |
cbm-project | cbm-project-master/src/data_synthetic.py | import igraph as ig
from random import random, seed
# n:
# number of nodes in the shared nodeset
# this will include both genuine and anomalous nodes
# p:
# probability of randomly connecting any two nodes
# this does not apply to anomalous nodes
# anomalies:
# percentage of the total nodes that should be an... | 2,321 | 30.808219 | 130 | py |
cbm-project | cbm-project-master/src/data_read.py | from os.path import join
import datetime
import graph_tool.all as gt
# renames the vertices so they are integers in the range [0, ... n-1]
def reindex(edgelist):
vertices = list({u for u, v, t in edgelist} | {v for u, v, t in edgelist})
f = {v: i for (v, i) in zip(vertices, range(len(vertices)))}
edgelist ... | 4,101 | 36.981481 | 134 | py |
cbm-project | cbm-project-master/src/transitions.py | import numpy as np
import igraph as ig
import graph_tool.all as gt
from graph_tool.topology import isomorphism, subgraph_isomorphism
from tqdm import tqdm
from pqdm.processes import pqdm
from multiprocessing import Pool
from itertools import chain, combinations
from src.data_read import load_graph_pairs
def powerse... | 6,352 | 35.302857 | 162 | py |
cbm-project | cbm-project-master/embeddings/dbscan.py | import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import matplotlib.patches as mpatches
from kneed import KneeLocator
from sklearn.neighbors import NearestNeighbors
from sklearn.manifold import SpectralEmbedding
from sklearn.metrics import davies_bouldi... | 4,970 | 38.452381 | 133 | py |
pynamical | pynamical-main/setup.py | """Install pynamical."""
import os
from setuptools import setup
# provide a long description using reStructuredText
LONG_DESCRIPTION = r"""
**pynamical** is a Python package for modeling, simulating, visualizing, and animating discrete
nonlinear dynamical systems and chaos. pynamical uses pandas, numpy, and numba fo... | 2,454 | 37.968254 | 188 | py |
pynamical | pynamical-main/tests/test_pynamical.py | """
pynamical tests
"""
import matplotlib as mpl
mpl.use("Agg") # use agg backend so you don't need a display on travis
import matplotlib.cm as cm
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from mpl_toolkits.mplot3d import Axes3D
from numba import jit... | 3,335 | 19.981132 | 97 | py |
pynamical | pynamical-main/docs/source/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Configure pynamical docs."""
# pynamical documentation build configuration file, created by
# sphinx-quickstart on Tue Jan 31 13:34:32 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration... | 5,062 | 29.871951 | 87 | py |
pynamical | pynamical-main/pynamical/pynamical.py | """pynamical core."""
import os
import matplotlib.cm as cm
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from numba import jit
def get_title_font(family="Helvetica", style="normal", size=20, weight="normal", stretch="normal"):
"""
Define fonts to... | 35,585 | 27.537289 | 99 | py |
pynamical | pynamical-main/pynamical/__init__.py | """Expose the pynamical API."""
from .pynamical import *
__version__ = "0.3.2"
| 81 | 12.666667 | 31 | py |
clipspy | clipspy-master/setup.py | # Copyright (c) 2016-2023, Matteo Cafasso
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and ... | 2,819 | 39.285714 | 80 | py |
clipspy | clipspy-master/test/environment_test.py | import os
import unittest
from tempfile import mkstemp
from clips import CLIPSError
from clips import Environment, Symbol, LoggingRouter, ImpliedFact, InstanceName
DEFRULE_FACT = """
(defrule fact-rule
?fact <- (test-fact)
=>
(python_method ?fact))
"""
DEFRULE_INSTANCE = """
(defrule instance-rule
?insta... | 5,415 | 27.505263 | 79 | py |
clipspy | clipspy-master/test/functions_test.py | import unittest
from clips import Environment, Symbol, CLIPSError
DEFFUNCTION1 = """(deffunction function-sum (?a ?b) (+ ?a ?b))"""
DEFFUNCTION2 = """(deffunction function-sub (?a ?b) (- ?a ?b))"""
DEFGENERIC1 = """(defgeneric generic-sum)"""
DEFGENERIC2 = """(defgeneric generic-sub)"""
DEFMETHOD = """
(defmethod ge... | 3,363 | 30.148148 | 70 | py |
clipspy | clipspy-master/test/agenda_test.py | import unittest
from clips import Environment, CLIPSError, Strategy, SalienceEvaluation
DEFTEMPLATE = """(deftemplate template-fact
(slot template-slot))
"""
DEFRULE = """(defrule MAIN::rule-name
(declare (salience 10))
(implied-fact implied-value)
=>
(assert (rule-fired)))
"""
DEFTEMPLATERULE = """(... | 5,094 | 29.147929 | 77 | py |
clipspy | clipspy-master/test/classes_test.py | import os
import unittest
from tempfile import mkstemp
from clips import Environment, Symbol, InstanceName
from clips import CLIPSError, ClassDefaultMode, LoggingRouter
DEFCLASSES = [
"""
(defclass AbstractClass (is-a USER)
(role abstract))
""",
"""(defclass InheritClass (is-a AbstractClass))""... | 9,513 | 33.722628 | 89 | py |
clipspy | clipspy-master/test/facts_test.py | import os
import unittest
from tempfile import mkstemp
from clips import Environment, Symbol, CLIPSError, TemplateSlotDefaultType
DEFTEMPLATE = """(deftemplate MAIN::template-fact
(slot int (type INTEGER) (allowed-values 0 1 2 3 4 5 6 7 8 9))
(slot float (type FLOAT))
(slot str (type STRING))
(slot symbo... | 7,966 | 34.887387 | 86 | py |
clipspy | clipspy-master/test/modules_test.py | import unittest
from clips import Environment, Symbol, CLIPSError
DEFGLOBAL = """
(defglobal
?*a* = 1
?*b* = 2)
"""
DEFMODULE = """(defmodule TEST)"""
class TestModules(unittest.TestCase):
def setUp(self):
self.env = Environment()
self.env.build(DEFGLOBAL)
def tearDown(self):
... | 2,026 | 24.658228 | 57 | py |
clipspy | clipspy-master/clips/classes.py | # Copyright (c) 2016-2023, Matteo Cafasso
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and ... | 28,087 | 30.418345 | 80 | py |
clipspy | clipspy-master/clips/environment.py | # Copyright (c) 2016-2023, Matteo Cafasso
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and ... | 6,501 | 33.956989 | 80 | py |
clipspy | clipspy-master/clips/modules.py | # Copyright (c) 2016-2023, Matteo Cafasso
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and ... | 8,139 | 29.0369 | 80 | py |
clipspy | clipspy-master/clips/routers.py | # Copyright (c) 2016-2023, Matteo Cafasso
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and ... | 8,877 | 29.613793 | 80 | py |
clipspy | clipspy-master/clips/functions.py | # Copyright (c) 2016-2023, Matteo Cafasso
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and ... | 15,175 | 30.290722 | 80 | py |
clipspy | clipspy-master/clips/agenda.py | # Copyright (c) 2016-2023, Matteo Cafasso
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and ... | 12,531 | 29.417476 | 80 | py |
clipspy | clipspy-master/clips/common.py | # Copyright (c) 2016-2023, Matteo Cafasso
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and ... | 7,437 | 34.084906 | 80 | py |
clipspy | clipspy-master/clips/__init__.py | # Copyright (c) 2016-2023, Matteo Cafasso
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and ... | 2,474 | 38.285714 | 80 | py |
clipspy | clipspy-master/clips/facts.py | # Copyright (c) 2016-2023, Matteo Cafasso
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and ... | 20,258 | 29.464662 | 80 | py |
clipspy | clipspy-master/clips/values.py | # Copyright (c) 2016-2023, Matteo Cafasso
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and ... | 6,285 | 37.09697 | 80 | py |
clipspy | clipspy-master/clips/clips_build.py | # Copyright (c) 2016-2023, Matteo Cafasso
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and ... | 2,364 | 32.309859 | 80 | py |
clipspy | clipspy-master/doc/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# clipspy documentation build configuration file, created by
# sphinx-quickstart on Sat Oct 7 00:14:23 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# au... | 10,419 | 27.547945 | 80 | py |
ScatterPlot | ScatterPlot-master/Scatter plot.py | # -*- coding: utf-8 -*-
"""
Created on Tue Nov 3 14:37:55 2020
@author: dongdong
"""
import numpy as np
import matplotlib.pyplot as plt
library_lng = 120.425947
library_lat = 36.078474
longitude=[]
latitude=[]
for i in range(1,7):#The initial value is 6, every iteration, the number is increased by 6
longitude=[]... | 1,269 | 36.352941 | 93 | py |
TAM | TAM-main/tam.py | import numpy as np
from entropy import *
def est_entropy(x, A = None):
'''helper function for estimating (conditional) entropy H(x|A).
Parameters
----------
x : np.array
Data of the R.V. to be estimate
A : 2d np.array
Data matrix of conditioning set
Can b... | 5,134 | 31.5 | 96 | py |
TAM | TAM-main/utils.py | import numpy as np
import igraph as ig
import networkx as nx
def compute_caus_order(G):
d = G.shape[0]
remain = list(range(d))
caus_order = np.empty(d, dtype = int)
for i in range(d-1):
root = min(np.where(G.sum(axis=0) == 0)[0])
caus_order[i] = remain[root]
del remain[root]
... | 5,659 | 33.512195 | 90 | py |
TAM | TAM-main/entropy.py | #!/usr/bin/env python3
"""
Main libraray for entropy estimation
"""
import linecache
from math import log, floor
import numpy as np
class Entropy():
"""
Entropy estimator
"""
def __init__(self, k, L=None, M=None, N=None):
"""
Args:
k: int, required
alphabet size
... | 4,355 | 25.888889 | 93 | py |
scalene | scalene-master/setup.py | from setuptools import setup, find_packages
from setuptools.extension import Extension
from scalene.scalene_version import scalene_version
from os import path, environ
import platform
import sys
if sys.platform == 'darwin':
import sysconfig
mdt = 'MACOSX_DEPLOYMENT_TARGET'
target = environ[mdt] if mdt in e... | 6,575 | 37.45614 | 103 | py |
scalene | scalene-master/benchmarks/julia1_nopil.py | import sys
# Disable the @profile decorator if none has been declared.
try:
# Python 2
import __builtin__ as builtins
except ImportError:
# Python 3
import builtins
try:
builtins.profile
except AttributeError:
# No line profiler, provide a pass-through version
def profile(func): return fu... | 2,797 | 29.086022 | 80 | py |
scalene | scalene-master/benchmarks/benchmark.py | import os
import sys
import re
import subprocess
import traceback
import statistics
python = "python3"
progname = os.path.join(os.path.dirname(__file__), "julia1_nopil.py")
number_of_runs = 1 # We take the average of this many runs.
# Output timing string from the benchmark.
result_regexp = re.compile("calculate_z_se... | 8,083 | 43.417582 | 643 | py |
scalene | scalene-master/benchmarks/pystone.py | #! /usr/bin/env python3
"""
"PYSTONE" Benchmark Program
Version: Python/1.1 (corresponds to C/1.1 plus 2 Pystone fixes)
Author: Reinhold P. Weicker, CACM Vol 27, No 10, 10/84 pg. 1013.
Translated from ADA to C by Rick Richardson.
Every method to preserve ADA-likeness ... | 7,444 | 26.472325 | 75 | py |
scalene | scalene-master/test/testpyt.py | # -*- coding: utf-8 -*-
import random
import torch
class DynamicNet(torch.nn.Module):
def __init__(self, D_in, H, D_out):
"""
In the constructor we construct three nn.Linear instances that we will use
in the forward pass.
"""
super(DynamicNet, self).__init__()
self.... | 2,339 | 34.454545 | 85 | py |
scalene | scalene-master/test/test-pprofile.py | import time
import argparse
def do_work_fn(x, i):
return (x >> 2) | (i & x)
def inline_loop(x, its):
for i in range(its): # 9500000
x = x | (x >> 2) | (i & x)
return x
def fn_call_loop(x, its):
for i in range(its): # 500000):
x = x | do_work_fn(x, i)
return x
def main():
pars... | 1,418 | 30.533333 | 111 | py |
scalene | scalene-master/test/test-size.py | from __future__ import print_function
from sys import getsizeof, stderr
from itertools import chain
from collections import deque
try:
from reprlib import repr
except ImportError:
pass
def total_size(o, handlers={}, verbose=False):
""" Returns the approximate memory footprint an object and all of its conte... | 2,145 | 29.225352 | 86 | py |
scalene | scalene-master/test/testflask-driver.py | import os
import time
from random import random
from requests import get
iter = 1
while True:
print(iter)
iter += 1
get(f"http://localhost:5000/{random()}")
| 171 | 13.333333 | 44 | py |
scalene | scalene-master/test/test-martinheinz.py | from decimal import *
def exp(x):
getcontext().prec += 2
i, lasts, s, fact, num = 0, 0, 1, 1, 1
while s != lasts:
lasts = s
i += 1
fact *= i
num *= x
s += num / fact
getcontext().prec -= 2
print(+s)
return +s
import time
start = time.time()
print("Orig... | 1,355 | 19.861538 | 88 | py |
scalene | scalene-master/test/multiprocessing_test.py | import logging
import multiprocessing
from time import sleep, perf_counter
# import faulthandler
# faulthandler.enable()
# import signal
# import os
# multiprocessing.log_to_stderr(logging.DEBUG)
# from multiprocessing.spawn import spawn_main
# import scalene.replacement_pjoin
# Stolen from https://stackoverflow.com/qu... | 1,539 | 28.615385 | 98 | py |
scalene | scalene-master/test/torchtest.py | import torch
import math
def torchtest():
dtype = torch.float
#device = torch.device("cpu")
device = torch.device("cuda:0") # Uncomment this to run on GPU
# device = torch.device("cuda") # Uncomment this to run on GPU
# Create Tensors to hold input and outputs.
# By default, requires_grad=Fa... | 2,736 | 41.765625 | 85 | py |
scalene | scalene-master/test/new_mp_test.py | import multiprocessing
from time import sleep, perf_counter
# from multiprocessing.spawn import spawn_main
# import scalene.replacement_pjoin
# Stolen from https://stackoverflow.com/questions/15347174/python-finding-prime-factors
class Integer(object):
def __init__(self, x):
self.x = x
def largest_prime_fac... | 1,181 | 35.9375 | 98 | py |
scalene | scalene-master/test/test-memory.py | import numpy as np
import sys
x = np.ones((1,1))
print(sys.getsizeof(x) / 1048576)
x = np.ones((1000,1000))
print(sys.getsizeof(x) / 1048576)
x = np.ones((1000,2000))
print(sys.getsizeof(x) / 1048576)
x = np.ones((1000,20000))
print(sys.getsizeof(x) / 1048576)
@profile
def allocate():
for i in range(100):
... | 650 | 17.6 | 33 | py |
scalene | scalene-master/test/pool-test.py | import multiprocessing
pool = multiprocessing.Pool(processes=1)
pool.terminate()
| 81 | 19.5 | 40 | py |
scalene | scalene-master/test/threads-test.py | import threading
import sys
import numpy as np
# Disable the @profile decorator if none has been declared.
try:
# Python 2
import __builtin__ as builtins
except ImportError:
# Python 3
import builtins
try:
builtins.profile
except AttributeError:
# No line profiler, provide a pass-through vers... | 972 | 16.690909 | 59 | py |
scalene | scalene-master/test/testflask.py | from flask import Flask
app = Flask(__name__)
cache = {}
@app.route("/<page>")
def index(page):
if page not in cache:
cache[page] = f"<h1>Welcome to {page}</h1>"
return cache[page]
if __name__ == "__main__":
app.run()
| 248 | 13.647059 | 51 | py |
scalene | scalene-master/test/test_sparkline.py | import pytest
from scalene.sparkline import SparkLine
@pytest.fixture(name="sl")
def sparkline() -> SparkLine:
return SparkLine()
def test_get_bars(sl):
bar = sl._get_bars()
assert bar == "▁▂▃▄▅▆▇█"
def test_get_bars___in_wsl(sl, monkeypatch):
monkeypatch.setenv("WSL_DISTRO_NAME", "Some WSL dist... | 1,784 | 19.755814 | 67 | py |
scalene | scalene-master/test/testtf.py | import tensorflow as tf
from time import perf_counter
def config():
num_threads = 16
tf.config.threading.set_inter_op_parallelism_threads(
num_threads
)
tf.config.threading.set_intra_op_parallelism_threads(
num_threads
)
def run_benchmark():
mnist = tf.keras.datasets.mnist
... | 1,116 | 26.925 | 77 | py |
scalene | scalene-master/test/small_mp_test.py | import multiprocessing
import faulthandler
import os
import signal
from time import sleep
import threading
def do_very_little():
sleep(1)
print("In subprocess")
print(threading.enumerate())
if __name__ == "__main__":
print("Starting")
p = multiprocessing.Process(target=do_very_little)
p.start(... | 400 | 18.095238 | 54 | py |
scalene | scalene-master/test/testme.py | import numpy as np
#import math
from numpy import linalg as LA
arr = [i for i in range(1,1000)]
def doit1(x):
# x = [i*i for i in range(1,1000)][0]
y = 1
# w, v = LA.eig(np.diag(arr)) # (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)))
x = [i*i for i in range(0,100000)][99999]
y1 = [i*i for i in range(0,200000)][1... | 1,207 | 18.483871 | 68 | py |
scalene | scalene-master/test/test_timers.py | import signal
import time
start = -1
loop = 10
def callback(*args):
global loop
global start
print(time.perf_counter() - start)
start = time.perf_counter()
loop -= 1
signal.signal(signal.SIGALRM, callback)
start = time.perf_counter()
signal.setitimer(signal.ITIMER_REAL, 5, 1)
i = 0
while loop >... | 354 | 15.136364 | 42 | py |
scalene | scalene-master/test/issues/test-issue74.py | import gevent
def calc(a):
x = 0
for i in range(1000000):
x += 1
gevent.sleep(a)
g1 = gevent.spawn(calc, 1)
g2 = gevent.spawn(calc, 2)
g3 = gevent.spawn(calc, 3)
g1.start()
g2.start()
g3.start()
g1.join()
g2.join()
g3.join()
| 247 | 12.777778 | 28 | py |
scalene | scalene-master/test/issues/test-issue130.py | from pyproj import Proj
import time
time.sleep(1)
time.sleep(0.1)
| 67 | 10.333333 | 23 | py |
scalene | scalene-master/test/issues/test-issue156.py | import numpy as np
class A:
def __init__(self, n):
self.arr = np.random.rand(n)
self.lst = [1] * n
print(n)
if __name__ == '__main__':
a = A(50_000_000)
| 188 | 14.75 | 36 | py |
scalene | scalene-master/test/issues/test-issue256.py | ret_value = dict()
for k in range(10**7):
temp = k*2
ret_value[k] = temp
| 82 | 12.833333 | 23 | py |
scalene | scalene-master/test/issues/test-issue193.py | import time
def test_cls_in_locals():
cls = "This value is not a class"
time.sleep(0.5)
if __name__ == "__main__":
test_cls_in_locals()
| 151 | 14.2 | 37 | py |
scalene | scalene-master/test/issues/test-issue124.py | #!/usr/bin/env python3
import time
time.sleep(5)
x = 0
for i in range(10000000):
x += 1
print("done")
| 111 | 7.615385 | 25 | py |
scalene | scalene-master/test/issues/test-issue31.py | import numpy as np
def main1():
# Before optimization
x = np.array(range(10**7))
y = np.array(np.random.uniform(0, 100, size=10**8))
def main2():
# After optimization, spurious `np.array` removed.
x = np.array(range(10**7))
y = np.random.uniform(0, 100, size=10**8)
main1()
main2()
| 311 | 17.352941 | 55 | py |
scalene | scalene-master/test/issues/test-issue266.py | import pandas as pd
import numpy as np
import gc
def f():
print('called f')
#Uses around 4GB of memory when looped once
df = np.ones(500000000)
#Uses around 20GB of memory when looped 5 times
for i in range(0,5):
f()
| 239 | 17.461538 | 47 | py |
scalene | scalene-master/test/issues/test-issue167.py | import time
import numpy as np
import pandas as pd
# this assumes you have memory_profiler installed
# if you want to use "@profile" on a function
# if not, we can ignore it with a pass-through decorator
if 'profile' not in dir():
def profile(fn):
return fn
SIZE = 10_000_000
@profile
def get_mean_for_i... | 1,804 | 31.818182 | 131 | py |
scalene | scalene-master/test/original/bm_spectral_norm.py | """
MathWorld: "Hundred-Dollar, Hundred-Digit Challenge Problems", Challenge #3.
http://mathworld.wolfram.com/Hundred-DollarHundred-DigitChallengeProblems.html
The Computer Language Benchmarks Game
http://benchmarksgame.alioth.debian.org/u64q/spectralnorm-description.html#spectralnorm
Contributed by Sebastien Loisel
... | 1,773 | 22.653333 | 87 | py |
scalene | scalene-master/test/original/bm_raytrace.py | """
This file contains definitions for a simple raytracer.
Copyright Callum and Tony Garnock-Jones, 2008.
This file may be freely redistributed under the MIT license,
http://www.opensource.org/licenses/mit-license.php
From http://www.lshift.net/blog/2008/10/29/toy-raytracer-in-python
"""
import array
import math
im... | 12,142 | 28.473301 | 90 | py |
scalene | scalene-master/test/original/bm_scimark.py | from array import array
import math
import pyperf
from six.moves import xrange
class Array2D(object):
def __init__(self, w, h, data=None):
self.width = w
self.height = h
self.data = array('d', [0]) * (w * h)
if data is not None:
self.setup(data)
def _idx(self, x,... | 10,284 | 23.546539 | 82 | py |
scalene | scalene-master/test/original/bm_sympy.py | import pyperf
from sympy import expand, symbols, integrate, tan, summation
from sympy.core.cache import clear_cache
def bench_expand():
x, y, z = symbols('x y z')
expand((1 + x + y + z) ** 20)
def bench_integrate():
x, y = symbols('x y')
f = (1 / tan(x)) ** 10
return integrate(f, x)
def bench... | 1,512 | 20.309859 | 68 | py |
scalene | scalene-master/test/original/bm_richards.py | """
based on a Java version:
Based on original version written in BCPL by Dr Martin Richards
in 1981 at Cambridge University Computer Laboratory, England
and a C++ version derived from a Smalltalk version written by
L Peter Deutsch.
Java version: Copyright (C) 1995 Sun Microsystems, Inc.
Translation from C++, Ma... | 9,629 | 21.5 | 83 | py |
scalene | scalene-master/test/original/bm_mdp.py | import collections
from collections import defaultdict
from fractions import Fraction
import pyperf
# Disable @profile if not defined.
try:
# Python 2
import __builtin__ as builtins
except ImportError:
# Python 3
import builtins
try:
builtins.profile
except AttributeError:
# No line profiler,... | 9,396 | 29.911184 | 79 | py |
scalene | scalene-master/test/original/bm_pyflate.py | #!/usr/bin/env python
"""
Copyright 2006--2007-01-21 Paul Sladen
http://www.paul.sladen.org/projects/compression/
You may use and distribute this code under any DFSG-compatible
license (eg. BSD, GNU GPLv2).
Stand-alone pure-Python DEFLATE (gzip) and bzip2 decoder/decompressor.
This is probably most useful for researc... | 20,272 | 29.213115 | 98 | py |
scalene | scalene-master/test/optimized/bm_spectral_norm.py | """
MathWorld: "Hundred-Dollar, Hundred-Digit Challenge Problems", Challenge #3.
http://mathworld.wolfram.com/Hundred-DollarHundred-DigitChallengeProblems.html
The Computer Language Benchmarks Game
http://benchmarksgame.alioth.debian.org/u64q/spectralnorm-description.html#spectralnorm
Contributed by Sebastien Loisel
... | 1,997 | 23.666667 | 87 | py |
scalene | scalene-master/test/optimized/bm_raytrace.py | """
This file contains definitions for a simple raytracer.
Copyright Callum and Tony Garnock-Jones, 2008.
This file may be freely redistributed under the MIT license,
http://www.opensource.org/licenses/mit-license.php
From http://www.lshift.net/blog/2008/10/29/toy-raytracer-in-python
"""
import array
import math
im... | 12,330 | 28.713253 | 104 | py |
scalene | scalene-master/test/optimized/bm_scimark.py | from array import array
import math
import pyperf
from six.moves import xrange
class Array2D(object):
def __init__(self, w, h, data=None):
self.width = w
self.height = h
self.data = array('d', [0]) * (w * h)
if data is not None:
self.setup(data)
def _idx(self, x,... | 10,363 | 23.617577 | 82 | py |
scalene | scalene-master/test/optimized/bm_richards.py | """
based on a Java version:
Based on original version written in BCPL by Dr Martin Richards
in 1981 at Cambridge University Computer Laboratory, England
and a C++ version derived from a Smalltalk version written by
L Peter Deutsch.
Java version: Copyright (C) 1995 Sun Microsystems, Inc.
Translation from C++, Ma... | 9,721 | 21.609302 | 83 | py |
scalene | scalene-master/test/optimized/bm_pyflate.py | #!/usr/bin/env python
"""
Copyright 2006--2007-01-21 Paul Sladen
http://www.paul.sladen.org/projects/compression/
You may use and distribute this code under any DFSG-compatible
license (eg. BSD, GNU GPLv2).
Stand-alone pure-Python DEFLATE (gzip) and bzip2 decoder/decompressor.
This is probably most useful for researc... | 20,545 | 29.303835 | 98 | py |
scalene | scalene-master/scalene/scalene_version.py | """Current version of Scalene; reported by --version."""
scalene_version = "1.5.5"
| 84 | 20.25 | 56 | py |
scalene | scalene-master/scalene/__main__.py | import sys
import traceback
from scalene import scalene_profiler
def should_trace(s) -> bool:
if scalene_profiler.Scalene.is_done():
return False
return scalene_profiler.Scalene.should_trace(s)
def main():
try:
from scalene import scalene_profiler
scalene_profiler.Scalene.main()
... | 523 | 20.833333 | 83 | py |
scalene | scalene-master/scalene/scalene_arguments.py | import argparse
class ScaleneArguments(argparse.Namespace):
"""Encapsulates all arguments and default values for Scalene."""
def __init__(self) -> None:
super().__init__()
self.cpu_only = False
self.cpu_percent_threshold = 1
# mean seconds between interrupts for CPU sampling.
... | 1,695 | 38.44186 | 97 | py |
scalene | scalene-master/scalene/replacement_signal_fns.py | import os
import signal
import sys
import traceback
from scalene.scalene_profiler import Scalene
@Scalene.shim
def replacement_signal_fns(scalene: Scalene) -> None:
old_signal = signal.signal
if sys.version_info < (3, 8):
old_raise_signal = lambda s: os.kill(os.getpid(), s)
else:
old_rai... | 3,805 | 38.645833 | 146 | py |
scalene | scalene-master/scalene/replacement_lock.py | import sys
import threading
import time
from typing import Any
from scalene.scalene_profiler import Scalene
@Scalene.shim
def replacement_lock(scalene: Scalene) -> None:
class ReplacementLock(object):
"""Replace lock with a version that periodically yields and updates sleeping status."""
def __i... | 2,126 | 32.234375 | 95 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.