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 |
|---|---|---|---|---|---|---|
plotnine | plotnine-main/plotnine/mapping/evaluation.py | from __future__ import annotations
import numbers
import typing
import numpy as np
import pandas as pd
import pandas.api.types as pdtypes
from ..exceptions import PlotnineError
if typing.TYPE_CHECKING:
from typing import Any
from plotnine.typing import EvalEnvironment
from . import aes
__all__ = ("a... | 8,023 | 28.5 | 79 | py |
plotnine | plotnine-main/doc/conf.py | #
# plotnine documentation build configuration file, created by
# sphinx-quickstart on Wed Dec 23 22:32:29 2015.
#
# 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
# autogenerated file.
#
# All configuration values... | 15,504 | 29.581854 | 79 | py |
plotnine | plotnine-main/doc/sphinxext/examples_and_gallery.py | """
sphinxext.examples_and_gallery
Provides, two directives `include_example` and `gallery`.
How to use the extension
------------------------
1. Create a galley.rst page with a `gallery` directive.
2. Define the path to the notebooks and the notebook filenames
as `EXAMPLES_PATH`. These are the notebooks that wil... | 12,740 | 27.956818 | 78 | py |
plotnine | plotnine-main/doc/sphinxext/inline_code_highlight.py | from docutils.parsers.rst.roles import code_role
def python_role(role, rawtext, text, lineno, inliner, options={}, content=[]):
options = {"language": "python"}
return code_role(
role, rawtext, text, lineno, inliner, options=options, content=content
)
def setup(app):
app.add_role("python", p... | 368 | 25.357143 | 78 | py |
plotnine | plotnine-main/doc/sphinxext/__init__.py | 0 | 0 | 0 | py | |
plotnine | plotnine-main/doc/images/readme_images.py | from plotnine import (
aes,
facet_wrap,
geom_point,
ggplot,
stat_smooth,
theme,
theme_tufte,
theme_xkcd,
)
from plotnine.data import mtcars
p1 = (
ggplot(mtcars, aes("wt", "mpg"))
+ geom_point()
+ theme(figure_size=(6, 4), dpi=300)
)
p1.save("readme-image-1.png")
p2 = p1 + ... | 621 | 17.294118 | 40 | py |
plotnine | plotnine-main/doc/images/logo.py | import numpy as np
import pandas as pd
from plotnine import (
aes,
annotate,
geom_bar,
geom_line,
geom_point,
ggplot,
scale_color_gradientn,
scale_fill_gradientn,
theme,
theme_void,
)
n = 99
x = np.linspace(0, 1, n)
y = np.exp(-7 * (x - 0.5) ** 2)
df = pd.DataFrame({"x": x, "... | 1,424 | 19.357143 | 77 | py |
getdist | getdist-master/GetDist.py | #!/usr/bin/env python
# Once installed this is not used, same as getdist script
import sys
import os
sys.path.append(os.path.realpath(os.path.dirname(__file__)))
from getdist.command_line import getdist_command
getdist_command()
| 234 | 17.076923 | 60 | py |
getdist | getdist-master/setup.py | #!/usr/bin/env python
import re
import os
import sys
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
def find_version():
version_file = open(os.path.join(os.path.dirname(__file__), 'getdist/__init__.py')).read()
version_match = re.search(r"^__version__ = ['\"]([... | 5,569 | 33.596273 | 94 | py |
getdist | getdist-master/GetDistGUI.py | #!/usr/bin/env python
# Once installed this is not used, same as getdist-gui script
import sys
import os
sys.path.append(os.path.realpath(os.path.dirname(__file__)))
from getdist.command_line import getdist_gui
getdist_gui()
| 230 | 16.769231 | 61 | py |
getdist | getdist-master/getdist/parampriors.py | import os
import numpy as np
class ParamBounds:
"""
Class for holding list of parameter bounds (e.g. for plotting, or hard priors).
A limit is None if not specified, denoted by 'N' if read from a string or file
:ivar names: list of parameter names
:ivar lower: dict of lower limits, indexed by par... | 4,158 | 32.540323 | 102 | py |
getdist | getdist-master/getdist/covscale.py | import sys
import fnmatch
import os
from getdist import covmat
if len(sys.argv) < 4:
print('covscale rescales parameter(s) in all .covmat files in a directory and outputs to another directory')
print('Usage: python covscale.py in_dir out_dir param1:param2:.. fac1:fac2:..')
sys.exit()
indir = os.path.abspa... | 778 | 28.961538 | 112 | py |
getdist | getdist-master/getdist/matplotlib_ext.py | from matplotlib import ticker
from matplotlib.axis import YAxis
import math
import numpy as np
from bisect import bisect_left
class SciFuncFormatter(ticker.Formatter):
# To put full sci notation into each axis label rather than split offsetText
def __call__(self, x, pos=None):
return "${}$".format(se... | 16,654 | 45.263889 | 119 | py |
getdist | getdist-master/getdist/chains.py | import os
import numpy as np
import re
from packaging import version
from getdist.paramnames import ParamNames, ParamInfo, escapeLatex
from getdist.convolve import autoConvolve
from getdist import cobaya_interface
import pickle
import logging
from copy import deepcopy
from collections import namedtuple
from typing impo... | 63,549 | 40.454664 | 119 | py |
getdist | getdist-master/getdist/yaml_tools.py | # JT 2017-19
import re
try:
# noinspection PyPackageRequirements
import yaml
except ModuleNotFoundError:
raise ModuleNotFoundError(
"You need to install 'PyYAML' in order to load Cobaya samples.")
# Exceptions
class InputSyntaxError(Exception):
"""Syntax error in YAML input."""
# Better lo... | 2,748 | 36.148649 | 97 | py |
getdist | getdist-master/getdist/covcomb.py | # usage:
# python covcmb.py out.covmat in1.covmat in2.covmat
# Nb. in1 values take priority over in2
import sys
from getdist import covmat
if len(sys.argv) < 3:
print('Usage: python covcmb.py out.covmat in1.covmat in2.covmat [in3.covmat...]')
sys.exit()
foutname = sys.argv[1]
cov = covmat.CovMat(sys.argv[2]... | 463 | 21.095238 | 85 | py |
getdist | getdist-master/getdist/chain_grid.py | import os
import glob
from getdist.inifile import IniFile
def file_root_to_root(root):
return (os.path.basename(root) if not root.endswith((os.sep, "/"))
else os.path.basename(root[:-1]) + os.sep)
def get_chain_root_files(rootdir):
"""
Gets the root names of all chain files in a directory.
... | 5,391 | 39.238806 | 116 | py |
getdist | getdist-master/getdist/inifile.py | import os
import numpy as np
class IniError(Exception):
pass
class IniFile:
"""
Class for storing option parameter values and reading/saving to file
Unlike standard .ini files, IniFile allows inheritance, in that a .ini file can use
INCLUDE(..) and DEFAULT(...) to include or override settings i... | 13,684 | 32.135593 | 119 | py |
getdist | getdist-master/getdist/types.py | import decimal
import os
from io import BytesIO
import numpy as np
import tempfile
from getdist.paramnames import ParamInfo, ParamList
from types import MappingProxyType
empty_dict = MappingProxyType({})
_sci_tolerance = 4
class TextFile:
def __init__(self, lines=None):
if isinstance(lines, str):
... | 36,688 | 39.053493 | 120 | py |
getdist | getdist-master/getdist/plots.py | import os
import copy
import matplotlib
import sys
import warnings
import logging
from typing import Mapping, Sequence, Union, Optional, Iterable, Tuple, Any, Dict
import numpy as np
if 'ipykern' not in matplotlib.rcParams['backend'] and \
'linux' in sys.platform and os.environ.get('DISPLAY', '') == '':
# ... | 169,853 | 49.208099 | 124 | py |
getdist | getdist-master/getdist/_base.py | # This provides base classes for handling backwards compatibility with renamed or removed attributes
import re
import logging
def _convert_camel(name):
s = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s).lower()
def _map_name(obj, name):
try:
return ob... | 1,947 | 30.419355 | 101 | py |
getdist | getdist-master/getdist/densities.py | import numpy as np
from scipy.interpolate import splrep, splev, RectBivariateSpline, LinearNDInterpolator
from typing import Sequence
class DensitiesError(Exception):
pass
defaultContours = (0.68, 0.95)
class InterpGridCache:
__slots__ = "factor", "grid", "sortgrid", "bign", "norm", "softgrid", "cumsum"
... | 12,245 | 31.482759 | 118 | py |
getdist | getdist-master/getdist/paramnames.py | import os
import fnmatch
from itertools import chain
def makeList(roots):
"""
Checks if the given parameter is a list.
If not, Creates a list with the parameter as an item in it.
:param roots: The parameter to check
:return: A list containing the parameter.
"""
if isinstance(roots, (list,... | 16,211 | 34.015119 | 117 | py |
getdist | getdist-master/getdist/gaussian_mixtures.py | import numpy as np
from getdist.densities import Density1D, Density2D
from getdist.paramnames import ParamNames
from getdist.mcsamples import MCSamples
import copy
def make_2D_Cov(sigmax, sigmay, corr):
return np.array([[sigmax ** 2, sigmax * sigmay * corr], [sigmax * sigmay * corr, sigmay ** 2]])
class Mixture... | 22,060 | 41.836893 | 117 | py |
getdist | getdist-master/getdist/__init__.py | __author__ = 'Antony Lewis'
__version__ = "1.4.3"
__url__ = "https://getdist.readthedocs.io"
import os
import sys
from getdist.inifile import IniFile
from getdist.paramnames import ParamInfo, ParamNames
from getdist.chains import WeightedSamples
from getdist.mcsamples import MCSamples, loadMCSamples
if sys.version_in... | 2,161 | 29.885714 | 105 | py |
getdist | getdist-master/getdist/convolve.py | import numpy as np
from scipy import fftpack
# numbers of the form 2^n3^m5^r, even only and r<=1
fastFFT = np.array(
[2, 4, 6, 8, 10, 12, 16, 20, 24, 32, 40, 48, 64, 80, 96, 128, 144, 160, 192, 256, 288, 320, 384, 432, 480,
512, 576, 640, 720, 768, 864, 960, 1024, 1152, 1280, 1440, 1536, 1728, 1920, 2048, 230... | 9,222 | 38.080508 | 116 | py |
getdist | getdist-master/getdist/covmat.py | import numpy as np
class CovMat:
"""
Class holding a covariance matrix for some named parameters
:ivar matrix: the covariance matrix (square numpy array)
:ivar paramNames: list of parameter name strings
"""
def __init__(self, filename='', matrix=None, paramNames=None):
"""
:... | 3,901 | 31.516667 | 98 | py |
getdist | getdist-master/getdist/cobaya_interface.py | # JT 2017-19
from importlib import import_module
from copy import deepcopy
import logging
from numbers import Number
import numpy as np
import os
from typing import Mapping, Sequence
# Conventions
_label = "label"
_prior = "prior"
_theory = "theory"
_params = "params"
_likelihood = "likelihood"
_sampler = "sampler"
_... | 11,204 | 37.90625 | 95 | py |
getdist | getdist-master/getdist/command_line.py | import os
import subprocess
import getdist
import sys
import logging
from getdist import MCSamples, chains, IniFile
def runScript(fname):
subprocess.Popen(['python', fname])
# noinspection PyUnboundLocalVariable,PyProtectedMember
def getdist_script(args, exit_on_error=True):
def do_error(msg):
if ex... | 12,863 | 35.134831 | 116 | py |
getdist | getdist-master/getdist/kde_bandwidth.py | import numpy as np
from scipy import fftpack
from scipy.optimize import fsolve, brentq, minimize
from getdist.convolve import dct2d
import logging
import warnings
"""
Code to find optimal bandwidths for basic kernel density estimators in 1 and 2D
Adapted from Matlab code by Zdravko Botev
Extended to include correlatio... | 11,880 | 39.968966 | 119 | py |
getdist | getdist-master/getdist/mcsamples.py | import os
import glob
import logging
import copy
import pickle
import math
import time
from typing import Mapping, Any, Optional, Union, Iterable
import numpy as np
from scipy.stats import norm
import getdist
from getdist import types as types
from getdist import chains, covmat, ParamInfo, IniFile, ParamNames, cobaya_i... | 118,236 | 43.922872 | 145 | py |
getdist | getdist-master/getdist/styles/planck.py | import os
from getdist import plots
# Style that roughly follows the Planck parameter papers; uses latex formatting and sans-serif font.
class PlanckPlotter(plots.GetDistPlotter):
# common setup for matplotlib
_style_rc = {'axes.labelsize': 9,
'font.size': 8,
'legend.fontsiz... | 2,450 | 39.85 | 115 | py |
getdist | getdist-master/getdist/styles/tab10.py | from getdist import plots
from matplotlib import cm
# Simple style that uses matplotlib's default color table for contours and lines
class DefaultColorsPlotter(plots.GetDistPlotter):
# noinspection PyUnresolvedReferences
def set_default_settings(self):
s = plots.GetDistPlotSettings()
s.solid_... | 517 | 26.263158 | 80 | py |
getdist | getdist-master/getdist/styles/__init__.py | __author__ = 'Antony Lewis'
| 28 | 13.5 | 27 | py |
getdist | getdist-master/getdist/gui/SyntaxHighlight.py | try:
from PySide6.QtCore import QRegularExpression
from PySide6.QtGui import QColor, QTextCharFormat, QFont, QSyntaxHighlighter
except ImportError:
# noinspection PyUnresolvedReferences
from PySide2.QtCore import QRegularExpression
# noinspection PyUnresolvedReferences
from PySide2.QtGui import... | 6,643 | 34.913514 | 88 | py |
getdist | getdist-master/getdist/gui/mainwindow.py | #!/usr/bin/env python
# !/usr/bin/env python
import os
import copy
import logging
import matplotlib
import matplotlib.colors
import numpy as np
import scipy
import sys
import signal
import warnings
from io import BytesIO
from typing import Optional
if os.name == "nt" and sys.getwindowsversion().major >= 10: # noqa
... | 96,733 | 39.678722 | 120 | py |
getdist | getdist-master/getdist/gui/__init__.py | __author__ = 'Antony Lewis'
| 28 | 13.5 | 27 | py |
getdist | getdist-master/getdist/tests/test_distributions.py | import os
try:
from getdist.plots import get_subplot_plotter
except ImportError:
import sys
sys.path.insert(0, os.path.realpath(os.path.join(os.path.dirname(__file__), '..', '..')))
from getdist.plots import get_subplot_plotter
import matplotlib.pyplot as plt
import numpy as np
from getdist.gaussian_m... | 16,705 | 44.644809 | 120 | py |
getdist | getdist-master/getdist/tests/getdist_test.py | import tempfile
import os
import numpy as np
import unittest
import subprocess
import shutil
from getdist import loadMCSamples, plots, IniFile
from getdist.tests.test_distributions import Test2DDistributions, Gaussian1D, Gaussian2D
from getdist.mcsamples import MCSamples
from getdist.styles.tab10 import style_name as t... | 19,412 | 45.00237 | 116 | py |
getdist | getdist-master/getdist/tests/__init__.py | 0 | 0 | 0 | py | |
getdist | getdist-master/docs/source/conf.py | # -*- coding: utf-8 -*-
#
# MyProj documentation build configuration file, created by
# sphinx-quickstart on Thu Jun 18 20:57:49 2015.
#
# 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
# autogenerated file.
#
# Al... | 9,201 | 31.174825 | 100 | py |
VQA_LSTM_CNN | VQA_LSTM_CNN-master/prepro.py | """
Preoricess a raw json dataset into hdf5/json files.
Caption: Use spaCy or NLTK or split function to get tokens.
"""
import copy
from random import shuffle, seed
import sys
import os.path
import argparse
import glob
import numpy as np
from scipy.misc import imread, imresize
import scipy.io
import pdb
import string... | 9,689 | 35.156716 | 153 | py |
VQA_LSTM_CNN | VQA_LSTM_CNN-master/evaluate.py | import sys
import os
sys.path.insert(0, 'Path_to_PythonEvaluationTools/')
import pdb
from vqaEvalDemo import evaluate
path = os.getcwd()
result_path = 'Path_to_result'
filePath = path + result_path + '.json'
print 'Loading ' +filePath
vqaEval = evaluate(filePath)
# saving to txt
f = open(path+result_path+'_accuracy.... | 741 | 28.68 | 81 | py |
VQA_LSTM_CNN | VQA_LSTM_CNN-master/create_spacy_paraphraser.py | """Prepare a spaCy vocabulary file that performs nearest-neighbor paraphrasing"""
from __future__ import unicode_literals, print_function
import io
import os
import argparse
from collections import Counter
import json
import numpy
import random
import spacy.en
import sputnik.util
import sense2vec.vectors
def build_v... | 3,768 | 40.877778 | 114 | py |
VQA_LSTM_CNN | VQA_LSTM_CNN-master/data/vqa_preprocessing.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... | 5,862 | 40.288732 | 137 | py |
golo-jmh-benchmarks | golo-jmh-benchmarks-master/src/test/resources/snippets/jython/check.py | def truth():
return 42
def incr(n):
return n + 1
def foo(o):
return o.foo()
| 90 | 9.111111 | 18 | py |
golo-jmh-benchmarks | golo-jmh-benchmarks-master/src/main/resources/snippets/jython/filter-map-reduce.py | def run(data):
return reduce(lambda acc, next: acc + next,
map(lambda x: x * 2,
filter(lambda x: x % 2 == 0, data)), 0)
| 144 | 28 | 51 | py |
golo-jmh-benchmarks | golo-jmh-benchmarks-master/src/main/resources/snippets/jython/fibonacci.py | def fib(n):
if n < 2:
return 1
else:
return fib(n - 1) + fib(n - 2)
| 92 | 14.5 | 38 | py |
golo-jmh-benchmarks | golo-jmh-benchmarks-master/src/main/resources/snippets/jython/dispatch.py | def dispatch(data):
result = ""
for item in data:
result = result + item.__str__()
return result
| 117 | 18.666667 | 40 | py |
golo-jmh-benchmarks | golo-jmh-benchmarks-master/src/main/resources/snippets/jython/arithmetic.py | def gcd(x, y):
a = x
b = y
while a != b:
if a > b:
a = a - b
else:
b = b - a
return a
| 142 | 13.3 | 21 | py |
DGGAN | DGGAN-main/code/discriminator.py | import tensorflow as tf
class Discriminator():
def __init__(self, n_node, node_emd_init, config):
self.n_node = n_node
self.emd_dim = config.n_emb
self.node_emd_init = node_emd_init
#with tf.variable_scope('disciminator'):
if node_emd_init:
self.node_embedding_... | 3,360 | 59.017857 | 145 | py |
DGGAN | DGGAN-main/code/utils.py | import numpy as np
def read_graph(train_filename):
nodes = set()
nodes_s = set()
egs = []
graph = [{}, {}]
with open(train_filename) as infile:
for line in infile.readlines():
source_node, target_node = line.strip().split(' ')
source_node = int(source_node)
... | 1,315 | 29.604651 | 73 | py |
DGGAN | DGGAN-main/code/config.py | g_batch_size = 128
d_batch_size = 128
lambda_gen = 1e-5
lambda_dis = 1e-5
lr_gen = 1e-4
lr_dis = 1e-4
n_epoch = 5
sig = 1.0
label_smooth = 0.0
d_epoch = 15
g_epoch = 5
n_emb = 128
pre_d_epoch = 0
pre_g_epoch = 0
neg_weight = [1, 1, 1, 1]
dataset = 'cora'
experiment = 'link_prediction'
train_file = '../data/%s/train_0.... | 558 | 18.275862 | 55 | py |
DGGAN | DGGAN-main/code/evaluation.py | import numpy as np
from sklearn.metrics import roc_auc_score
def sigmoid(x):
return 1 / (1 + np.exp(-x))
class LinkPrediction():
def __init__(self, config):
self.links = [[], [], []]
sufs = ['_0', '_50', '_100']
for i, suf in enumerate(sufs):
with open(config.test_file + s... | 1,154 | 32 | 84 | py |
DGGAN | DGGAN-main/code/generator.py | import tensorflow as tf
class Generator():
def __init__(self, n_node, node_emd_init, config):
self.n_node = n_node
self.emd_dim = config.n_emb
self.node_emd_init = node_emd_init
#with tf.variable_scope('generator'):
if node_emd_init:
self.node_embedding_matrix ... | 4,919 | 51.903226 | 123 | py |
DGGAN | DGGAN-main/code/dggan.py | import os
import tensorflow as tf
import time
import numpy as np
import random
import math
import utils
import config
import evaluation
from generator import Generator
from discriminator import Discriminator
import warnings
warnings.filterwarnings('ignore')
class Model():
def __init__(self):
t = time.time... | 10,584 | 45.836283 | 135 | py |
JOELIN | JOELIN-master/train_shared.py | #!/usr/bin/env python3
import os
import csv
import time
import copy
import argparse
import numpy as np
import pandas as pd
from tqdm import tqdm
from sklearn import metrics
from prediction import new_data_predict
from transformers import (
AutoTokenizer, AutoConfig,
AdamW, get_linear_schedule_with_warmup)
impo... | 32,010 | 41.511288 | 174 | py |
JOELIN | JOELIN-master/submit_prediction_reformat.py | #
import os
import jsonlines
import sys
def parseBinaryValue(value):
if len(value) == 1 and value[0] == 'Not Specified':
return False
else:
return True
def formatData(data):
pred_anno = data['predicted_annotation']
data['predicted_annotation'] = {
f'part2-{key}.Response': val... | 3,252 | 33.606383 | 97 | py |
JOELIN | JOELIN-master/final_reformat.py |
import os
import jsonlines
import spacy
nlp = spacy.load("en_core_web_sm")
event_list = ['positive', 'negative', 'can_not_test', 'death', 'cure']
for event in event_list:
filename = f"./Test_Positive/Test_Positive-{event}.jsonl"
count = 0
person_count = 0
loc_count = 0
with jsonlines.open(filen... | 3,524 | 42.518519 | 102 | py |
JOELIN | JOELIN-master/extract_data.py | #!/usr/bin/env python3
import os
import csv
import time
import copy
import argparse
import numpy as np
import pandas as pd
from tqdm import tqdm
from sklearn import metrics
from pprint import pprint
from transformers import (
BertTokenizerFast, BertPreTrainedModel, BertModel, BertConfig,
AutoTokenizer, AutoMod... | 8,815 | 41.796117 | 142 | py |
JOELIN | JOELIN-master/model.py | from transformers import BertTokenizer, BertTokenizerFast, BertPreTrainedModel, BertModel, BertConfig, AdamW, get_linear_schedule_with_warmup
from transformers import AutoTokenizer, AutoModel, AutoConfig
from torch import nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import torch
... | 13,239 | 42.267974 | 141 | py |
JOELIN | JOELIN-master/load_data.py |
### load data.py
from mod.utils import *
downloaded_ones = read_json_line('./data/downloaded_tweets-tagging.jsonl')
downloaded_ones_dict = {}
for each_line in downloaded_ones:
downloaded_ones_dict[each_line['id_str']] = each_line
file_names = ['positive', 'negative', 'can_not_test', 'death', 'cure_and_preventio... | 904 | 38.347826 | 85 | py |
JOELIN | JOELIN-master/prediction_shared.py | #!/usr/bin/env python3
import os
import csv
import time
import copy
import argparse
import numpy as np
import pandas as pd
from tqdm import tqdm
from sklearn import metrics
# from prediction import new_data_predict
from transformers import (
AutoTokenizer, AutoConfig,
AdamW, get_linear_schedule_with_warmup)
im... | 24,679 | 40.689189 | 146 | py |
JOELIN | JOELIN-master/preprocessing/const.py |
Q_TOKEN = "<Q_TARGET>"
URL_TOKEN = "<URL>"
COVID_TOKEN = "<COVID_TAG>"
AUTHOR_OF_THE_TWEET = "AUTHOR OF THE TWEET"
NEAR_AUTHOR_OF_THE_TWEET = "NEAR AUTHOR OF THE TWEET"
NOT_SPECIFIED = "Not Specified"
DATA_FOLDER = './data'
NEW_DATA_FOLDER = './test-data'
OUTPUT_DATA_FOLDER = '.'
MIN_POS_SAMPLES_THRESHOLD = 1... | 409 | 23.117647 | 85 | py |
JOELIN | JOELIN-master/preprocessing/getQuestionTagAndKey.py |
def getQuestionTagAndKeyList(subtask):
if subtask == 'positive':
question_tag_and_key_list = [
("age" , "part2-age.Response" ),
("close_contact" , "part2-close_contact.Response" ),
("employer" , "part2-employer.Response" ),
("g... | 2,516 | 46.490566 | 67 | py |
JOELIN | JOELIN-master/preprocessing/utils.py |
import os
import json
import pickle
import datetime
import matplotlib.pyplot as plt
import numpy as np
import logging
def saveToPickleFile(save_object, save_file):
with open(save_file, "wb") as pickle_out:
pickle.dump(save_object, pickle_out)
def loadFromPickleFile(pickle_file):
with open(pickle... | 2,230 | 27.974026 | 176 | py |
JOELIN | JOELIN-master/preprocessing/processText.py |
import re
import emoji
import unidecode
import unicodedata
from html import unescape
import logging
def asciifyEmojis(text):
"""
Converts emojis into text aliases. E.g. 👍 becomes :thumbs_up:
For a full list of text aliases see: https://www.webfx.com/tools/emoji-cheat-sheet/
"""
text = emoji.demo... | 2,857 | 25.71028 | 87 | py |
JOELIN | JOELIN-master/preprocessing/loadData.py |
from transformers import BertTokenizer, BertTokenizerFast
import torch
from torch.utils.data import Dataset, DataLoader
import logging
import os
from preprocessing.preprocessData import splitDatasetIntoTrainDevTest, preprocessDataAndSave
from preprocessing.utils import loadFromPickleFile
from preprocessing import con... | 8,848 | 36.655319 | 110 | py |
JOELIN | JOELIN-master/preprocessing/preprocessData.py |
import os
import sys
import json
import copy
from itertools import compress as itertools_compress
from preprocessing.getQuestionTagAndKey import getQuestionTagAndKeyList
from preprocessing.utils import (saveToPickleFile, loadFromPickleFile)
from preprocessing import const
# NOTE 1) Separate statistics and preproces... | 22,585 | 38.555166 | 112 | py |
bayesmix | bayesmix-master/src/proto/__init__.py | 0 | 0 | 0 | py | |
bayesmix | bayesmix-master/src/proto/py/__init__.py | 0 | 0 | 0 | py | |
bayesmix | bayesmix-master/python/setup.py | import os
import setuptools
import site
import sys
site.ENABLE_USER_SITE = '--user' in sys.argv[1:]
__version__ = "0.0.1"
folder = os.path.dirname(__file__)
path = os.path.join(folder, 'requirements.txt')
install_requires = []
if os.path.exists(path):
with open(path) as fp:
install_requires = [line.strip() for l... | 423 | 22.555556 | 52 | py |
bayesmix | bayesmix-master/python/__init__.py | 0 | 0 | 0 | py | |
bayesmix | bayesmix-master/python/scripts/populate_benchmark_datasets.py | import numpy as np
import os
multivariate_dims = [2, 4, 8]
N_BY_CLUS = 10
BASE_PATH = os.path.join("resources", "benchmarks", "datasets")
BASE_CHAIN_PATH = os.path.join("resources", "benchmarks", "chains")
if __name__ == '__main__':
os.makedirs(BASE_PATH, exist_ok=True)
os.makedirs(BASE_CHAIN_PATH, exist_ok=T... | 920 | 29.7 | 67 | py |
bayesmix | bayesmix-master/python/scripts/__init__.py | 0 | 0 | 0 | py | |
bayesmix | bayesmix-master/python/scripts/generate_asciipb.py | from google.protobuf.text_format import PrintMessage
from math import sqrt
from proto.py import distribution_pb2
from proto.py import mixing_prior_pb2
from proto.py import hierarchy_prior_pb2
# Run this from root with python -m python.generate_asciipb
def identity_list(dim):
"""Returns the list of entries of a dim-... | 5,278 | 35.157534 | 73 | py |
bayesmix | bayesmix-master/python/tests/test_build.py | from bayesmixpy import build_bayesmix
def test_build():
success = build_bayesmix()
assert success == True
| 115 | 18.333333 | 37 | py |
bayesmix | bayesmix-master/python/tests/__init__.py | 0 | 0 | 0 | py | |
bayesmix | bayesmix-master/python/tests/test_run.py | import numpy as np
from bayesmixpy import run_mcmc
DP_PARAMS = """
fixed_value {
totalmass: 1.0
}
"""
GO_PARAMS = """
fixed_values {
mean: 0.0
var_scaling: 0.1
shape: 2.0
scale: 2.0
}
"""
ALGO_PARAMS = """
algo_id: "Neal2"
rng_seed: 20201124
iterations: 10
burnin: 5
init_num_c... | 2,051 | 23.428571 | 62 | py |
bayesmix | bayesmix-master/python/bayesmixpy/build_bayesmix.py | import os
import pathlib
import subprocess
from dotenv import set_key
from .shell_utils import get_env_file, run_shell
HERE = os.path.dirname(os.path.realpath(__file__))
path = pathlib.Path(HERE)
BAYESMIX_HOME = os.environ.get("BAYESMIX_HOME", path.resolve().parents[1])
def set_bayesmix_env(run_path):
env_file... | 1,794 | 28.42623 | 84 | py |
bayesmix | bayesmix-master/python/bayesmixpy/run.py | import os
import shutil
import subprocess
import numpy as np
from dotenv import load_dotenv
from tempfile import TemporaryDirectory
from pathlib import Path
from .shell_utils import get_env_file, run_shell
def _is_file(a: str):
out = False
try:
p = Path(a)
out = p.exists() and p.is_file()
... | 7,154 | 33.071429 | 79 | py |
bayesmix | bayesmix-master/python/bayesmixpy/shell_utils.py | import os
import subprocess
HERE = os.path.dirname(os.path.realpath(__file__))
def run_shell(cmd, flush_startswith=None, cwd=None):
proc = subprocess.Popen(
cmd.split(),
bufsize=1,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE,
stderr=subprocess.STDO... | 830 | 25.806452 | 64 | py |
bayesmix | bayesmix-master/python/bayesmixpy/__init__.py | __all__ = ['build_bayesmix', 'run_mcmc']
from .build_bayesmix import build_bayesmix
from .run import run_mcmc
| 111 | 21.4 | 42 | py |
bayesmix | bayesmix-master/docs/conf.py | import os
import sys
import subprocess
sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath('..'))
sys.path.insert(0, os.path.abspath('../python'))
sys.path.insert(0, os.path.abspath('../python/bayesmixpy'))
def configureDoxyfile(input_dir, output_dir):
with open('Doxyfile.in', 'r') as file... | 1,563 | 23.825397 | 68 | py |
bayesmix | bayesmix-master/resources/benchmarks/chains/__init__.py | 0 | 0 | 0 | py | |
rcnn | rcnn-master/code/__init__.py | 0 | 0 | 0 | py | |
rcnn | rcnn-master/code/nn/optimization.py | '''
This file implements various optimization methods, including
-- SGD with gradient norm clipping
-- AdaGrad
-- AdaDelta
-- Adam
Transparent to switch between CPU / GPU.
@author: Tao Lei (taolei@csail.mit.edu)
'''
import random
from collections import OrderedDict
import... | 9,054 | 36.887029 | 93 | py |
rcnn | rcnn-master/code/nn/advanced.py | '''
This file contains implementations of advanced NN components, including
-- Attention layer (two versions)
-- StrCNN: non-consecutive & non-linear CNN
-- RCNN: recurrent convolutional network
Sequential layers (recurrent/convolutional) has two forward methods implemented:
-- forwar... | 20,215 | 33.380952 | 97 | py |
rcnn | rcnn-master/code/nn/initialization.py | '''
This file implements various methods for initializing NN parameters
@author: Tao Lei (taolei@csail.mit.edu)
'''
import random
import numpy as np
import theano
import theano.tensor as T
from theano.sandbox.rng_mrg import MRG_RandomStreams
'''
whether to use Xavier initialization, as described in
... | 2,779 | 25.990291 | 92 | py |
rcnn | rcnn-master/code/nn/__init__.py |
'''
Import classes and methods from other .py files
'''
from utils import say
#from .initialization import default_srng, default_rng, USE_XAVIER_INIT
#from .initialization import set_default_rng_seed, random_init, create_shared
#from .initialization import ReLU, sigmoid, tanh, softmax, linear, get_activation_by_n... | 525 | 29.941176 | 89 | py |
rcnn | rcnn-master/code/nn/evaluation.py |
def evaluate_average(predictions, masks = None):
if masks is None:
sum_all = sum(sum(x.ravel()) for x in predictions)
cnt_all = sum(len(x.ravel()) for x in predictions)
else:
#masked = predictions * masks
masked = [ x*m for x,m in zip(predictions, masks) ]
sum_all = sum(... | 434 | 35.25 | 59 | py |
rcnn | rcnn-master/code/nn/basic.py | '''
This file contains implementations of various NN components, including
-- Dropout
-- Feedforward layer (with custom activations)
-- RNN (with customizable activations)
-- LSTM
-- GRU
-- CNN
Each instance has a forward() method which takes x as input and return the
po... | 19,077 | 31.445578 | 97 | py |
rcnn | rcnn-master/code/rationale/rationale.py |
import os, sys, gzip
import time
import math
import json
import cPickle as pickle
import numpy as np
import theano
import theano.tensor as T
from theano.sandbox.rng_mrg import MRG_RandomStreams
from nn import create_optimization_updates, get_activation_by_name, sigmoid, linear
from nn import EmbeddingLayer, Layer, L... | 24,504 | 35.90512 | 98 | py |
rcnn | rcnn-master/code/rationale/extended_layers.py | import numpy as np
import theano
import theano.tensor as T
from theano.sandbox.rng_mrg import MRG_RandomStreams
from nn import create_optimization_updates, get_activation_by_name, sigmoid, linear
from nn import EmbeddingLayer, Layer, RecurrentLayer, LSTM, RCNN, apply_dropout, default_rng
from nn import create_shared, ... | 5,594 | 32.704819 | 99 | py |
rcnn | rcnn-master/code/rationale/myio.py |
import gzip
import random
import json
import theano
import numpy as np
from nn import EmbeddingLayer
from utils import say, load_embedding_iterator
def read_rationales(path):
data = [ ]
fopen = gzip.open if path.endswith(".gz") else open
with fopen(path) as fin:
for line in fin:
item... | 2,483 | 28.571429 | 81 | py |
rcnn | rcnn-master/code/rationale/rationale_dependent.py |
import os, sys, gzip
import time
import math
import json
import cPickle as pickle
import numpy as np
import theano
import theano.tensor as T
from nn import create_optimization_updates, get_activation_by_name, sigmoid, linear
from nn import EmbeddingLayer, Layer, LSTM, RCNN, apply_dropout, default_rng
from utils impo... | 25,347 | 35.843023 | 96 | py |
rcnn | rcnn-master/code/rationale/options.py |
import sys
import argparse
def load_arguments():
argparser = argparse.ArgumentParser(sys.argv[0])
argparser.add_argument("--load_rationale",
type = str,
default = "",
help = "path to annotated rationale data"
)
argparser.add_argument("--embedding",
t... | 4,426 | 27.197452 | 66 | py |
rcnn | rcnn-master/code/rationale/ubuntu/rationale.py | import sys
import time
import argparse
import gzip
import cPickle as pickle
from prettytable import PrettyTable
import numpy as np
import theano
import theano.tensor as T
from utils import load_embedding_iterator
from nn import get_activation_by_name, create_optimization_updates
from nn import EmbeddingLayer, LSTM, G... | 27,404 | 34.683594 | 96 | py |
rcnn | rcnn-master/code/rationale/ubuntu/extended_layers.py | import numpy as np
import theano
import theano.tensor as T
from theano.sandbox.rng_mrg import MRG_RandomStreams
from nn import create_optimization_updates, get_activation_by_name, sigmoid, linear
from nn import EmbeddingLayer, Layer, RecurrentLayer, LSTM, RCNN, apply_dropout, default_rng
from nn import create_shared, ... | 5,759 | 32.882353 | 99 | py |
rcnn | rcnn-master/code/rationale/ubuntu/myio.py | import sys
import gzip
import random
from collections import Counter
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
import theano
from nn import EmbeddingLayer
def say(s, stream=sys.stdout):
stream.write(s)
stream.flush()
def read_corpus(path):
empty_cnt = 0
raw_corpu... | 7,773 | 34.336364 | 92 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.