uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
6eba68285911acc5a84505f2
train
function
def should_skip_newer_k8s(k8s_version, kops_version): if kops_version is None: return False if k8s_version is None: return True return float(k8s_version) > float(kops_version)
def should_skip_newer_k8s(k8s_version, kops_version):
if kops_version is None: return False if k8s_version is None: return True return float(k8s_version) > float(kops_version)
.split('\n'): if pattern in line: if new_str: line = line.replace(pattern, new_str) keep.append(line) else: keep.append(line) return '\n'.join(keep) def should_skip_newer_k8s(k8s_version, kops_version):
64
64
56
17
47
yvettep321/test-infra
config/jobs/kubernetes/kops/helpers.py
Python
should_skip_newer_k8s
should_skip_newer_k8s
75
80
75
75
95615b3cc432bdf30c9dc568dce9b25a8aa2a155
bigcode/the-stack
train
9fc002c5cedba2a526b669eb
train
function
def replace_or_remove_line(s, pattern, new_str): keep = [] for line in s.split('\n'): if pattern in line: if new_str: line = line.replace(pattern, new_str) keep.append(line) else: keep.append(line) return '\n'.join(keep)
def replace_or_remove_line(s, pattern, new_str):
keep = [] for line in s.split('\n'): if pattern in line: if new_str: line = line.replace(pattern, new_str) keep.append(line) else: keep.append(line) return '\n'.join(keep)
return "%d %d * * *" % (minute, hour), runs_per_week runs_per_week += 1 return "%d %d * * %d" % (minute, hour, day_of_week), runs_per_week def replace_or_remove_line(s, pattern, new_str):
64
64
68
12
51
yvettep321/test-infra
config/jobs/kubernetes/kops/helpers.py
Python
replace_or_remove_line
replace_or_remove_line
64
73
64
64
f99cc02c3beb9d35e43b6cdb8ce26ce4d2a6ca60
bigcode/the-stack
train
a14ddfce4f1d475bbb5f682e
train
function
def k8s_version_info(k8s_version): test_package_bucket = '' test_package_dir = '' if k8s_version == 'latest': marker = 'latest.txt' k8s_deploy_url = "https://storage.googleapis.com/kubernetes-release/release/latest.txt" elif k8s_version == 'ci': marker = 'latest.txt' k8s_...
def k8s_version_info(k8s_version):
test_package_bucket = '' test_package_dir = '' if k8s_version == 'latest': marker = 'latest.txt' k8s_deploy_url = "https://storage.googleapis.com/kubernetes-release/release/latest.txt" elif k8s_version == 'ci': marker = 'latest.txt' k8s_deploy_url = "https://storage.googl...
return '\n'.join(keep) def should_skip_newer_k8s(k8s_version, kops_version): if kops_version is None: return False if k8s_version is None: return True return float(k8s_version) > float(kops_version) def k8s_version_info(k8s_version):
76
76
254
11
65
yvettep321/test-infra
config/jobs/kubernetes/kops/helpers.py
Python
k8s_version_info
k8s_version_info
82
101
82
82
04aea760c62f745e1b480a1ae81ab3ec7b55d684
bigcode/the-stack
train
62c3c0c201f03fce3c3890b9
train
function
def build_cron(key, runs_per_day): runs_per_week = 0 minute = simple_hash("minutes:" + key) % 60 hour = simple_hash("hours:" + key) % 24 day_of_week = simple_hash("day_of_week:" + key) % 7 if runs_per_day > 0: hour_denominator = 24 / runs_per_day hour_offset = simple_hash("hours:" +...
def build_cron(key, runs_per_day):
runs_per_week = 0 minute = simple_hash("minutes:" + key) % 60 hour = simple_hash("hours:" + key) % 24 day_of_week = simple_hash("day_of_week:" + key) % 7 if runs_per_day > 0: hour_denominator = 24 / runs_per_day hour_offset = simple_hash("hours:" + key) % hour_denominator re...
[ 'kops-grid-scenario-service-account-iam', 'kops-grid-scenario-arm64', 'kops-grid-scenario-serial-test-for-timeout', 'kops-grid-scenario-terraform', ] def simple_hash(s): # & 0xffffffff avoids python2/python3 compatibility return zlib.crc32(s.encode()) & 0xffffffff def build_cron(key, runs_pe...
91
91
305
10
80
yvettep321/test-infra
config/jobs/kubernetes/kops/helpers.py
Python
build_cron
build_cron
36
62
36
36
bade1b3c8c386202679596d820aa324059e0eb88
bigcode/the-stack
train
1bbe32f67d44b4fae1b2f024
train
function
def create_args(kops_channel, networking, container_runtime, extra_flags, kops_image): args = f"--channel={kops_channel} --networking=" + networking if container_runtime: args += f" --container-runtime={container_runtime}" image_overridden = False if extra_flags: for arg in extra_flags:...
def create_args(kops_channel, networking, container_runtime, extra_flags, kops_image):
args = f"--channel={kops_channel} --networking=" + networking if container_runtime: args += f" --container-runtime={container_runtime}" image_overridden = False if extra_flags: for arg in extra_flags: if "--image=" in arg: image_overridden = True ...
_version}.txt" # pylint: disable=line-too-long else: raise Exception('missing required k8s_version') return marker, k8s_deploy_url, test_package_bucket, test_package_dir def create_args(kops_channel, networking, container_runtime, extra_flags, kops_image):
64
64
128
19
44
yvettep321/test-infra
config/jobs/kubernetes/kops/helpers.py
Python
create_args
create_args
103
116
103
103
35ee3c4120b3e1f6e64b4f62be98620cb9e1f77d
bigcode/the-stack
train
aa3d406b7925273d1ed822d9
train
function
@view_config(route_name="user_view", renderer="user.mako") def response(request): username = unquote(request.matchdict.get("username")) cursor = db.con.cursor() cursor.execute( "SELECT username, to_char(date, 'Mon FMDD, YYYY HH:MM AM'), karma, title, \ name, city, state, country, biogra...
@view_config(route_name="user_view", renderer="user.mako") def response(request):
username = unquote(request.matchdict.get("username")) cursor = db.con.cursor() cursor.execute( "SELECT username, to_char(date, 'Mon FMDD, YYYY HH:MM AM'), karma, title, \ name, city, state, country, biography, avatar \ FROM bulbs_User WHERE username = %s", (username, )) data...
from pyramid.view import view_config from urllib.parse import unquote from bulbs.components import db @view_config(route_name="user_view", renderer="user.mako") def response(request):
39
68
228
19
19
CrystallineEntity/bulbs
bulbs/views/user.py
Python
response
response
6
33
6
7
21f387a01d7f90c7c267611b53afd1109fe7b68f
bigcode/the-stack
train
0e803d6d659038d88ab2486e
train
function
@app.route("/") @app.route("/home") def home(): return render_template("base.html")
@app.route("/") @app.route("/home") def home():
return render_template("base.html")
, request, make_response from webapp import app, db, bcrypt, login_manager from flask_login import login_user, current_user, logout_user, login_required from webapp.modules import User from webapp.forms import RegistrationForm, LoginForm @app.route("/") @app.route("/home") def home():
64
64
18
11
52
SimonSkade/ShoppingListPredictor
webapp/.ipynb_checkpoints/routes-checkpoint.py
Python
home
home
8
11
8
10
bb5c9603d17734950d4b852e10af512bb1abfbac
bigcode/the-stack
train
f84948f31f0920bbb11186a7
train
function
@app.route("/logout") def logout(): logout_user() return redirect(url_for("home"))
@app.route("/logout") def logout():
logout_user() return redirect(url_for("home"))
) next_page = request.args.get("next") return redirect(next_page) if next_page else redirect(url_for("home")) else: flash("Login unsuccessful. Please check username and password", "danger") return render_template("login.html", form=form) @app.route("/logout") def logout():
64
64
19
8
56
SimonSkade/ShoppingListPredictor
webapp/.ipynb_checkpoints/routes-checkpoint.py
Python
logout
logout
51
54
51
52
58a445e4a9fbb8524159a6d63132c06899a7e033
bigcode/the-stack
train
3e81fa8be80a3207b5e7156f
train
function
@app.route("/about") def about(): return render_template("about.html")
@app.route("/about") def about():
return render_template("about.html")
, login_manager from flask_login import login_user, current_user, logout_user, login_required from webapp.modules import User from webapp.forms import RegistrationForm, LoginForm @app.route("/") @app.route("/home") def home(): return render_template("base.html") @app.route("/about") def about():
64
64
15
8
56
SimonSkade/ShoppingListPredictor
webapp/.ipynb_checkpoints/routes-checkpoint.py
Python
about
about
14
16
14
15
2825b812b62152cd9981f9b0878359bd4d121c31
bigcode/the-stack
train
d70c5d22237ecd439b0da1fd
train
function
@app.route("/register", methods=["GET","POST"]) def register(): if current_user.is_authenticated: return redirect(url_for("home")) form = RegistrationForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash(form.password.data).decode("utf-8") user = User(username=form.username.data,...
@app.route("/register", methods=["GET","POST"]) def register():
if current_user.is_authenticated: return redirect(url_for("home")) form = RegistrationForm() if form.validate_on_submit(): hashed_password = bcrypt.generate_password_hash(form.password.data).decode("utf-8") user = User(username=form.username.data, email=form.email.data, password=hashed_password) db.session.a...
webapp.modules import User from webapp.forms import RegistrationForm, LoginForm @app.route("/") @app.route("/home") def home(): return render_template("base.html") @app.route("/about") def about(): return render_template("about.html") @app.route("/register", methods=["GET","POST"]) def register():
64
64
150
14
50
SimonSkade/ShoppingListPredictor
webapp/.ipynb_checkpoints/routes-checkpoint.py
Python
register
register
19
33
19
20
a5bcbd5aee0b533d68a69fbb3f7c620392e7c6b0
bigcode/the-stack
train
ed32de52b3734931541cf88b
train
function
@app.route("/login", methods=["GET","POST"]) def login(): if current_user.is_authenticated: return redirect(url_for("home")) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user and bcrypt.check_password_hash(user.password, form.password.data): ...
@app.route("/login", methods=["GET","POST"]) def login():
if current_user.is_authenticated: return redirect(url_for("home")) form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user and bcrypt.check_password_hash(user.password, form.password.data): login_user(user) next_page = request.args.get("next") ...
}! You were logged in!", "success") login_user(user) next_page = request.args.get("next") return redirect(next_page) if next_page else redirect(url_for("home")) return render_template("register.html", form=form) @app.route("/login", methods=["GET","POST"]) def login():
64
64
128
14
50
SimonSkade/ShoppingListPredictor
webapp/.ipynb_checkpoints/routes-checkpoint.py
Python
login
login
36
49
36
37
e7682b37a8923941a986adf82c9b175b63d5adbd
bigcode/the-stack
train
d7e22b743ebb1ce44c4d4672
train
function
def plot_step_function(v, vertical_lines=True, **kwds): r""" Return the line graphics object that gives the plot of the step function `f` defined by the list `v` of pairs `(a,b)`. Here if `(a,b)` is in `v`, then `f(a) = b`. The user does not have to worry about sorting the input list `v`. INP...
def plot_step_function(v, vertical_lines=True, **kwds):
r""" Return the line graphics object that gives the plot of the step function `f` defined by the list `v` of pairs `(a,b)`. Here if `(a,b)` is in `v`, then `f(a) = b`. The user does not have to worry about sorting the input list `v`. INPUT: - ``v`` -- list of pairs (a,b) - ``vertica...
#***************************************************************************** # Copyright (C) 2009 William Stein <wstein@gmail.com>, # # Distributed under the terms of the GNU General Public License (GPL) # # This code is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; withou...
136
136
456
14
121
bopopescu/sage
src/sage/plot/step.py
Python
plot_step_function
plot_step_function
23
68
23
23
3aab5e45a1b103a6d536ed10623a3b1708c7dede
bigcode/the-stack
train
fea467e0fc99b78e4901e397
train
class
class SingleSentenceDataset(Dataset): def __init__(self, config): self.source_language = config['source_language'].lower() self.strategy = config['split_strategy'] assert self.strategy is not None self.split_ratio = config['split_ratio'] super().__init__(config) def _get...
class SingleSentenceDataset(Dataset):
def __init__(self, config): self.source_language = config['source_language'].lower() self.strategy = config['split_strategy'] assert self.strategy is not None self.split_ratio = config['split_ratio'] super().__init__(config) def _get_preset(self): self.token2idx ...
# @Time : 2020/11/5 # @Author : Junyi Li, Gaole He # @Email : lijunyi@ruc.edu.cn """ textbox.data.dataset.single_sent_dataset ######################################## """ import os import pickle import nltk import collections import random from textbox.data.dataset import Dataset class SingleSentenceDataset(Datas...
80
256
1,577
7
72
JBoRu/TextBox-1
textbox/data/dataset/single_sent_dataset.py
Python
SingleSentenceDataset
SingleSentenceDataset
19
196
19
19
7dc637e6a5252d3d174ca0cafd93c0ff60ac88c2
bigcode/the-stack
train
6c5107fb790664ac482cb90e
train
class
class Migration(migrations.Migration): dependencies = [ ('ideabox', '0001_initial'), ] operations = [ migrations.AlterField( model_name='idea', name='date_added', field=models.DateTimeField(default=datetime.datetime.now, verbose_name='date added'), ...
class Migration(migrations.Migration):
dependencies = [ ('ideabox', '0001_initial'), ] operations = [ migrations.AlterField( model_name='idea', name='date_added', field=models.DateTimeField(default=datetime.datetime.now, verbose_name='date added'), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import datetime class Migration(migrations.Migration):
34
64
65
7
26
cantorek/codeweekend
ideabox/migrations/0002_auto_20151006_2111.py
Python
Migration
Migration
8
20
8
9
4140d24f22f1f46a50b905a61b06482904db2f53
bigcode/the-stack
train
5e168890c56ae9c2f6b09f70
train
function
def get_keyring(): try: from ..signatures import keys import keyring except ImportError: raise WheelError("Install wheel[signatures] (requires keyring, dirspec) for signatures.") return keys.WheelKeys, keyring
def get_keyring():
try: from ..signatures import keys import keyring except ImportError: raise WheelError("Install wheel[signatures] (requires keyring, dirspec) for signatures.") return keys.WheelKeys, keyring
install import WheelFile def require_pkgresources(name): try: import pkg_resources except ImportError: raise RuntimeError("'{0}' needs pkg_resources (part of setuptools).".format(name)) import argparse class WheelError(Exception): pass # For testability def get_keyring():
64
64
58
5
58
BlueMoon3000/election-2016
venv/lib/python2.7/site-packages/wheel/tool/__init__.py
Python
get_keyring
get_keyring
28
34
28
28
632538d6f20c9582cf95609bd64d3068bebe13c6
bigcode/the-stack
train
fa2572eb75fe9478a014abc0
train
class
class WheelError(Exception): pass
class WheelError(Exception):
pass
native, binary, matches_requirement) from ..install import WheelFile def require_pkgresources(name): try: import pkg_resources except ImportError: raise RuntimeError("'{0}' needs pkg_resources (part of setuptools).".format(name)) import argparse class WheelError(Exception...
64
64
7
6
57
BlueMoon3000/election-2016
venv/lib/python2.7/site-packages/wheel/tool/__init__.py
Python
WheelError
WheelError
25
25
25
25
63547dcd213e2af618c4f7d2850a2d7b868941f8
bigcode/the-stack
train
597a9352b856848f27490526
train
function
def keygen(get_keyring=get_keyring): """Generate a public/private key pair.""" WheelKeys, keyring = get_keyring() ed25519ll = signatures.get_ed25519ll() wk = WheelKeys().load() keypair = ed25519ll.crypto_sign_keypair() vk = native(urlsafe_b64encode(keypair.vk)) sk = native(urlsafe_b64enco...
def keygen(get_keyring=get_keyring):
"""Generate a public/private key pair.""" WheelKeys, keyring = get_keyring() ed25519ll = signatures.get_ed25519ll() wk = WheelKeys().load() keypair = ed25519ll.crypto_sign_keypair() vk = native(urlsafe_b64encode(keypair.vk)) sk = native(urlsafe_b64encode(keypair.sk)) kr = keyring.get_...
Error(Exception): pass # For testability def get_keyring(): try: from ..signatures import keys import keyring except ImportError: raise WheelError("Install wheel[signatures] (requires keyring, dirspec) for signatures.") return keys.WheelKeys, keyring def keygen(get_keyring=get_keyri...
78
78
261
10
67
BlueMoon3000/election-2016
venv/lib/python2.7/site-packages/wheel/tool/__init__.py
Python
keygen
keygen
36
62
36
36
3dc725a0da518375220053d1919a55ec98f17520
bigcode/the-stack
train
8c9691f1711deb71ca43b1fd
train
function
def unsign(wheelfile): """ Remove RECORD.jws from a wheel by truncating the zip file. RECORD.jws must be at the end of the archive. The zip file must be an ordinary archive, with the compressed files and the directory in the same order, and without any non-zip content after the truncation poi...
def unsign(wheelfile):
""" Remove RECORD.jws from a wheel by truncating the zip file. RECORD.jws must be at the end of the archive. The zip file must be an ordinary archive, with the compressed files and the directory in the same order, and without any non-zip content after the truncation point. """ import ...
hash":"sha256=" + native(urlsafe_b64encode(hashlib.sha256(record_data).digest()))} sig = signatures.sign(payload, keypair) wf.zipfile.writestr(sig_name, json.dumps(sig, sort_keys=True)) wf.zipfile.close() def unsign(wheelfile):
64
64
157
8
56
BlueMoon3000/election-2016
venv/lib/python2.7/site-packages/wheel/tool/__init__.py
Python
unsign
unsign
94
108
94
94
057ae3bfe4f7c12a672931113277316f95210377
bigcode/the-stack
train
1491da4f21f104d18097b551
train
function
def parser(): p = argparse.ArgumentParser() s = p.add_subparsers(help="commands") def keygen_f(args): keygen() keygen_parser = s.add_parser('keygen', help='Generate signing key') keygen_parser.set_defaults(func=keygen_f) def sign_f(args): sign(args.wheelfile) sign_parser = ...
def parser():
p = argparse.ArgumentParser() s = p.add_subparsers(help="commands") def keygen_f(args): keygen() keygen_parser = s.add_parser('keygen', help='Generate signing key') keygen_parser.set_defaults(func=keygen_f) def sign_f(args): sign(args.wheelfile) sign_parser = s.add_parser('...
import pkg_resources except ImportError: raise RuntimeError("'wheel install_scripts' needs setuptools.") for dist in distributions: pkg_resources_dist = pkg_resources.get_distribution(dist) install = wheel.paths.get_install_command(dist) command = easy_install.easy_install(inst...
239
239
799
3
236
BlueMoon3000/election-2016
venv/lib/python2.7/site-packages/wheel/tool/__init__.py
Python
parser
parser
264
348
264
264
863b302e404e9a2d64b368d03d3b2409ce919263
bigcode/the-stack
train
a9bfa301d08af5c616a67ed2
train
function
def install_scripts(distributions): """ Regenerate the entry_points console_scripts for the named distribution. """ try: from setuptools.command import easy_install import pkg_resources except ImportError: raise RuntimeError("'wheel install_scripts' needs setuptools.") f...
def install_scripts(distributions):
""" Regenerate the entry_points console_scripts for the named distribution. """ try: from setuptools.command import easy_install import pkg_resources except ImportError: raise RuntimeError("'wheel install_scripts' needs setuptools.") for dist in distributions: pk...
.write("Installing:\n") if dry_run: return for wf in to_install: if list_files: sys.stdout.write(" {0}\n".format(wf.filename)) continue wf.install(force=force) wf.zipfile.close() def install_scripts(distributions):
64
64
122
6
58
BlueMoon3000/election-2016
venv/lib/python2.7/site-packages/wheel/tool/__init__.py
Python
install_scripts
install_scripts
226
242
226
226
4a5c997446d8c52cd1856be594fc8a7d3dffcc64
bigcode/the-stack
train
ae391fd7bf226e509af38165
train
function
def sign(wheelfile, replace=False, get_keyring=get_keyring): """Sign a wheel""" WheelKeys, keyring = get_keyring() ed25519ll = signatures.get_ed25519ll() wf = WheelFile(wheelfile, append=True) wk = WheelKeys().load() name = wf.parsed_filename.group('name') sign_with = wk.signers(name)[0] ...
def sign(wheelfile, replace=False, get_keyring=get_keyring):
"""Sign a wheel""" WheelKeys, keyring = get_keyring() ed25519ll = signatures.get_ed25519ll() wf = WheelFile(wheelfile, append=True) wk = WheelKeys().load() name = wf.parsed_filename.group('name') sign_with = wk.signers(name)[0] sys.stdout.write("Signing {0} with {1}\n".format(name, si...
', vk) if sk2 != sk: raise WheelError("Keyring is broken. Could not retrieve secret key.") sys.stdout.write("Trusting {0} to sign and verify all packages.\n".format(vk)) wk.add_signer('+', vk) wk.trust('+', vk) wk.save() def sign(wheelfile, replace=False, get_keyring=get_keyring):
87
87
291
17
70
BlueMoon3000/election-2016
venv/lib/python2.7/site-packages/wheel/tool/__init__.py
Python
sign
sign
64
92
64
64
415a1cff9385ba0e25e31c1bae943e39efdab80f
bigcode/the-stack
train
421daa6ca5fd345ed6ff0875
train
function
def verify(wheelfile): """Verify a wheel. The signature will be verified for internal consistency ONLY and printed. Wheel's own unpack/install commands verify the manifest against the signature and file contents. """ wf = WheelFile(wheelfile) sig_name = wf.distinfo_name + '/RECORD.jws'...
def verify(wheelfile):
"""Verify a wheel. The signature will be verified for internal consistency ONLY and printed. Wheel's own unpack/install commands verify the manifest against the signature and file contents. """ wf = WheelFile(wheelfile) sig_name = wf.distinfo_name + '/RECORD.jws' sig = json.loads(n...
a") info = vzf.infolist() if not (len(info) and info[-1].filename.endswith('/RECORD.jws')): raise WheelError("RECORD.jws not found at end of archive.") vzf.pop() vzf.close() def verify(wheelfile):
64
64
130
7
57
BlueMoon3000/election-2016
venv/lib/python2.7/site-packages/wheel/tool/__init__.py
Python
verify
verify
110
123
110
110
45e725c9b8c7e13279e2e1fb5fcc8fcdc50b9acd
bigcode/the-stack
train
e3749fa76415ab323505fd0d
train
function
def unpack(wheelfile, dest='.'): """Unpack a wheel. Wheel content will be unpacked to {dest}/{name}-{ver}, where {name} is the package name and {ver} its version. :param wheelfile: The path to the wheel. :param dest: Destination directory (default to current directory). """ wf = WheelFile(...
def unpack(wheelfile, dest='.'):
"""Unpack a wheel. Wheel content will be unpacked to {dest}/{name}-{ver}, where {name} is the package name and {ver} its version. :param wheelfile: The path to the wheel. :param dest: Destination directory (default to current directory). """ wf = WheelFile(wheelfile) namever = wf.parse...
= json.loads(native(wf.zipfile.open(sig_name).read())) verified = signatures.verify(sig) sys.stderr.write("Signatures are internally consistent.\n") sys.stdout.write(json.dumps(verified, indent=2)) sys.stdout.write('\n') def unpack(wheelfile, dest='.'):
64
64
141
10
54
BlueMoon3000/election-2016
venv/lib/python2.7/site-packages/wheel/tool/__init__.py
Python
unpack
unpack
125
139
125
125
485220e3bb2cd70cf36fbf31dae56a3913d420c0
bigcode/the-stack
train
3e9381bcba020065d6db1ed9
train
function
def install(requirements, requirements_file=None, wheel_dirs=None, force=False, list_files=False, dry_run=False): """Install wheels. :param requirements: A list of requirements or wheel files to install. :param requirements_file: A file containing requirements to install. :p...
def install(requirements, requirements_file=None, wheel_dirs=None, force=False, list_files=False, dry_run=False):
"""Install wheels. :param requirements: A list of requirements or wheel files to install. :param requirements_file: A file containing requirements to install. :param wheel_dirs: A list of directories to search for wheels. :param force: Install a wheel file even if it is not compatible. :par...
Signatures are internally consistent.\n") sys.stdout.write(json.dumps(verified, indent=2)) sys.stdout.write('\n') def unpack(wheelfile, dest='.'): """Unpack a wheel. Wheel content will be unpacked to {dest}/{name}-{ver}, where {name} is the package name and {ver} its version. :param wheelfile...
195
195
651
26
169
BlueMoon3000/election-2016
venv/lib/python2.7/site-packages/wheel/tool/__init__.py
Python
install
install
141
224
141
143
9447491c0c169b6dbc6fdb6e2e4c8abd853b92ee
bigcode/the-stack
train
02294974de2d5e6a919975e6
train
function
def main(): p = parser() args = p.parse_args() if not hasattr(args, 'func'): p.print_help() else: # XXX on Python 3.3 we get 'args has no func' rather than short help. try: args.func(args) return 0 except WheelError as e: sys.stderr.wri...
def main():
p = parser() args = p.parse_args() if not hasattr(args, 'func'): p.print_help() else: # XXX on Python 3.3 we get 'args has no func' rather than short help. try: args.func(args) return 0 except WheelError as e: sys.stderr.write(e.message...
('version', help='Print version and exit') version_parser.set_defaults(func=version_f) def help_f(args): p.print_help() help_parser = s.add_parser('help', help='Show this help') help_parser.set_defaults(func=help_f) return p def main():
64
64
89
3
60
BlueMoon3000/election-2016
venv/lib/python2.7/site-packages/wheel/tool/__init__.py
Python
main
main
350
362
350
350
325cb81978eb798cbb53df6b700e6fb8f4f3e702
bigcode/the-stack
train
4e7d5794f1ea6bb64fe36d6d
train
function
def convert(installers, dest_dir, verbose): require_pkgresources('wheel convert') # Only support wheel convert if pkg_resources is present from ..wininst2wheel import bdist_wininst2wheel from ..egg2wheel import egg2wheel for pat in installers: for installer in iglob(pat): i...
def convert(installers, dest_dir, verbose):
require_pkgresources('wheel convert') # Only support wheel convert if pkg_resources is present from ..wininst2wheel import bdist_wininst2wheel from ..egg2wheel import egg2wheel for pat in installers: for installer in iglob(pat): if os.path.splitext(installer)[1] == '.egg': ...
.get_distribution(dist) install = wheel.paths.get_install_command(dist) command = easy_install.easy_install(install.distribution) command.args = ['wheel'] # dummy argument command.finalize_options() command.install_egg_scripts(pkg_resources_dist) def convert(installers, dest_dir,...
64
64
149
11
53
BlueMoon3000/election-2016
venv/lib/python2.7/site-packages/wheel/tool/__init__.py
Python
convert
convert
244
262
244
244
ed540409dcc09505f420c5b9367d7ba7d2164217
bigcode/the-stack
train
972e2ed88792ba57cf1d154f
train
function
def require_pkgresources(name): try: import pkg_resources except ImportError: raise RuntimeError("'{0}' needs pkg_resources (part of setuptools).".format(name))
def require_pkgresources(name):
try: import pkg_resources except ImportError: raise RuntimeError("'{0}' needs pkg_resources (part of setuptools).".format(name))
import hashlib import sys import json import wheel.paths from glob import iglob from .. import signatures from ..util import (urlsafe_b64decode, urlsafe_b64encode, native, binary, matches_requirement) from ..install import WheelFile def require_pkgresources(name):
64
64
39
6
57
BlueMoon3000/election-2016
venv/lib/python2.7/site-packages/wheel/tool/__init__.py
Python
require_pkgresources
require_pkgresources
17
21
17
17
ca071aa1d216293fac00f95c216e59870925d3f2
bigcode/the-stack
train
e05ef96828addc514aff6bf7
train
class
class MarkdownView(QFrame): def __init__(self, parent): super(TestProtocolView, self).__init__() self.parent = parent self.setFrameStyle(QFrame.StyledPanel) self.htmlView = QWebView() self.htmlView.setStyle(QStyleFactory.create("windows")) layou...
class MarkdownView(QFrame):
def __init__(self, parent): super(TestProtocolView, self).__init__() self.parent = parent self.setFrameStyle(QFrame.StyledPanel) self.htmlView = QWebView() self.htmlView.setStyle(QStyleFactory.create("windows")) layout = QVBoxLayout() layout....
* from PyQt5.QtWidgets import * from PyQt5.QtWebKitWidgets import QWebView from PyQt5.QtWebKit import QWebSettings from PyQt5.QtNetwork import QNetworkRequest Signal = pyqtSignal Slot = pyqtSlot # import matplotlib # matplotlib.use('Agg') from scilab.tools.project import * from pathlib import * # from fn import _ a...
162
162
543
7
154
elcritch/CuteMark
CuteMark/RendererPanel.py
Python
MarkdownView
MarkdownView
33
100
33
34
06d953ab7a5afe087eee19d609d9581972dad617
bigcode/the-stack
train
6f91c979b99de4d66d55ca46
train
class
class MajorMinorEncoderDecoder(SingleChordEncoderDecoder): """Encodes chords as root + major/minor, with zero index for "no chord". Encodes chords as follows: 0: "no chord" 1-12: chords with a major triad, where 1 is C major, 2 is C# major, etc. 13-24: chords with a minor triad, where 13 is C mino...
class MajorMinorEncoderDecoder(SingleChordEncoderDecoder):
"""Encodes chords as root + major/minor, with zero index for "no chord". Encodes chords as follows: 0: "no chord" 1-12: chords with a major triad, where 1 is C major, 2 is C# major, etc. 13-24: chords with a minor triad, where 13 is C minor, 14 is C# minor, etc. """ # Mapping from pitch class...
abc.abstractmethod def encode_chord(self, figure): """Convert from a chord symbol string to a chord encoding integer. Args: figure: A chord symbol string representing the chord. Returns: An integer representing the encoded chord, in range [0, self.num_classes). """ pass @abc.abstr...
146
146
489
11
134
Sprog-gle/Magenta
magenta/music/chords_lib.py
Python
MajorMinorEncoderDecoder
MajorMinorEncoderDecoder
416
467
416
416
79827a329acf10d6c8790e21769ce00fe068e4d3
bigcode/the-stack
train
4894c015aa53eed23f2b6dea
train
class
class ChordEncodingException(Exception): pass
class ChordEncodingException(Exception):
pass
_OCTAVE NO_CHORD = constants.NO_CHORD # Shortcut to CHORD_SYMBOL annotation type. CHORD_SYMBOL = music_pb2.NoteSequence.TextAnnotation.CHORD_SYMBOL class CoincidentChordsException(Exception): pass class BadChordException(Exception): pass class ChordEncodingException(Exception):
64
64
10
7
56
Sprog-gle/Magenta
magenta/music/chords_lib.py
Python
ChordEncodingException
ChordEncodingException
51
52
51
51
bc5f01c61a8dc663e295fb059a71b27f183e8a80
bigcode/the-stack
train
3aafb9eb5351b8533daac8c8
train
class
class ChordProgression(events_lib.SimpleEventSequence): """Stores a quantized stream of chord events. ChordProgression is an intermediate representation that all chord or lead sheet models can use. Chords are represented here by a chord symbol string; model-specific code is responsible for converting this repr...
class ChordProgression(events_lib.SimpleEventSequence):
"""Stores a quantized stream of chord events. ChordProgression is an intermediate representation that all chord or lead sheet models can use. Chords are represented here by a chord symbol string; model-specific code is responsible for converting this representation to SequenceExample protos for TensorFlow. ...
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Utility functions for working with chord progressions. Use extract_chords_for_melodies to extract chord progressions from a QuantizedSequence objec...
256
256
1,755
11
244
Sprog-gle/Magenta
magenta/music/chords_lib.py
Python
ChordProgression
ChordProgression
55
255
55
55
b29d85ba25dc3d14b6346b420e1561c1e83b236a
bigcode/the-stack
train
405ce61d769cb8d6cc6847a6
train
class
class SingleChordEncoderDecoder(object): """An abstract class for encoding and decoding individual chords. """ __metaclass__ = abc.ABCMeta @abc.abstractproperty def num_classes(self): """The number of distinct chord encodings. Returns: An int, the range of ints that can be returned by self.enc...
class SingleChordEncoderDecoder(object):
"""An abstract class for encoding and decoding individual chords. """ __metaclass__ = abc.ABCMeta @abc.abstractproperty def num_classes(self): """The number of distinct chord encodings. Returns: An int, the range of ints that can be returned by self.encode_chord. """ pass @abc.abstr...
# Render the last chord. pitches = self._chord_symbol_functions.chord_symbol_midi_pitches( prev_figure) self._render_notes(sequence=sequence, pitches=pitches, start_time=prev_time, end_time=sequence.total_time) class ...
65
65
217
7
58
Sprog-gle/Magenta
magenta/music/chords_lib.py
Python
SingleChordEncoderDecoder
SingleChordEncoderDecoder
377
413
377
377
12d1e426022a18deadd29c82b954c0ed34d33417
bigcode/the-stack
train
4ee85b211487e070b05c7689
train
class
class BadChordException(Exception): pass
class BadChordException(Exception):
pass
ES_PER_OCTAVE = constants.NOTES_PER_OCTAVE NO_CHORD = constants.NO_CHORD # Shortcut to CHORD_SYMBOL annotation type. CHORD_SYMBOL = music_pb2.NoteSequence.TextAnnotation.CHORD_SYMBOL class CoincidentChordsException(Exception): pass class BadChordException(Exception):
64
64
9
6
57
Sprog-gle/Magenta
magenta/music/chords_lib.py
Python
BadChordException
BadChordException
47
48
47
47
9a60958e35dc2f1e408b9d051f0efb985aa11641
bigcode/the-stack
train
f4e286815e991a28108d60cd
train
class
class ChordsEncoderDecoder(events_lib.EventsEncoderDecoder): """An abstract class for translating between chords and model data. When building your dataset, the `encode` method takes in a chord progression and returns a SequenceExample of inputs and labels. These SequenceExamples are fed into the model during ...
class ChordsEncoderDecoder(events_lib.EventsEncoderDecoder):
"""An abstract class for translating between chords and model data. When building your dataset, the `encode` method takes in a chord progression and returns a SequenceExample of inputs and labels. These SequenceExamples are fed into the model during training and evaluation. During generation, the `get_input...
_symbol_quality(figure) if quality == chord_symbols_lib.CHORD_QUALITY_MAJOR: return root + 1 elif quality == chord_symbols_lib.CHORD_QUALITY_MINOR: return root + NOTES_PER_OCTAVE + 1 else: raise ChordEncodingException('chord is neither major nor minor: %s' ...
166
166
554
11
155
Sprog-gle/Magenta
magenta/music/chords_lib.py
Python
ChordsEncoderDecoder
ChordsEncoderDecoder
470
541
470
470
d0090421fbfc598588b3290d078d9857ee8b2827
bigcode/the-stack
train
c292061b051231c66c2a143f
train
class
class ChordRenderer(object): """An abstract class for rendering NoteSequence chord symbols as notes.""" __metaclass__ = abc.ABCMeta @abc.abstractmethod def render(self, sequence): """Renders the chord symbols of a NoteSequence. This function renders chord symbol annotations in a NoteSequence as actual...
class ChordRenderer(object):
"""An abstract class for rendering NoteSequence chord symbols as notes.""" __metaclass__ = abc.ABCMeta @abc.abstractmethod def render(self, sequence): """Renders the chord symbols of a NoteSequence. This function renders chord symbol annotations in a NoteSequence as actual notes. Notes are added t...
.from_quantized_sequence( quantized_sequence, melody.start_step, melody.end_step) except CoincidentChordsException: stats['coincident_chords'].increment() chords = None chord_progressions.append(chords) return chord_progressions, stats.values() class ChordRenderer(object):
64
64
112
6
58
Sprog-gle/Magenta
magenta/music/chords_lib.py
Python
ChordRenderer
ChordRenderer
290
305
290
290
c9501cf2c9d8abacc26c57aacb66648fbf2e8900
bigcode/the-stack
train
346a126b7796b41583e66717
train
function
def extract_chords_for_melodies(quantized_sequence, melodies): """Extracts from the QuantizedSequence a chord progression for each melody. This function will extract the underlying chord progression (encoded as text annotations) from `quantized_sequence` for each monophonic melody in `melodies`. Each chord pr...
def extract_chords_for_melodies(quantized_sequence, melodies):
"""Extracts from the QuantizedSequence a chord progression for each melody. This function will extract the underlying chord progression (encoded as text annotations) from `quantized_sequence` for each monophonic melody in `melodies`. Each chord progression will be the same length as its corresponding melody...
by the ChordSymbolFunctions object. """ for i in xrange(len(self._events)): if self._events[i] != NO_CHORD: self._events[i] = chord_symbol_functions.transpose_chord_symbol( self._events[i], transpose_amount % NOTES_PER_OCTAVE) def extract_chords_for_melodies(quantized_sequence, melodi...
77
77
259
15
62
Sprog-gle/Magenta
magenta/music/chords_lib.py
Python
extract_chords_for_melodies
extract_chords_for_melodies
258
287
258
258
14f6b3b75208bd77be4805315a96b2b951b8d70a
bigcode/the-stack
train
3e7b5fa4fb64719037de7a6d
train
class
class BasicChordRenderer(ChordRenderer): """A chord renderer that holds each note for the duration of the chord.""" def __init__(self, velocity=100, instrument=1, program=88, chord_symbol_functions= chord_symbols_lib.ChordSymbolFunctions.ge...
class BasicChordRenderer(ChordRenderer):
"""A chord renderer that holds each note for the duration of the chord.""" def __init__(self, velocity=100, instrument=1, program=88, chord_symbol_functions= chord_symbols_lib.ChordSymbolFunctions.get()): """Initialize a BasicChordRende...
() chords = None chord_progressions.append(chords) return chord_progressions, stats.values() class ChordRenderer(object): """An abstract class for rendering NoteSequence chord symbols as notes.""" __metaclass__ = abc.ABCMeta @abc.abstractmethod def render(self, sequence): """Renders the chor...
143
143
479
8
134
Sprog-gle/Magenta
magenta/music/chords_lib.py
Python
BasicChordRenderer
BasicChordRenderer
308
374
308
308
4364b27cb8566172767417174d6bd79aa3b62543
bigcode/the-stack
train
5d820189c0e9a648e59b2765
train
class
class CoincidentChordsException(Exception): pass
class CoincidentChordsException(Exception):
pass
Q = constants.STANDARD_PPQ NOTES_PER_OCTAVE = constants.NOTES_PER_OCTAVE NO_CHORD = constants.NO_CHORD # Shortcut to CHORD_SYMBOL annotation type. CHORD_SYMBOL = music_pb2.NoteSequence.TextAnnotation.CHORD_SYMBOL class CoincidentChordsException(Exception):
64
64
11
8
55
Sprog-gle/Magenta
magenta/music/chords_lib.py
Python
CoincidentChordsException
CoincidentChordsException
43
44
43
43
c9bc685f77da3eeeb720e82cd8f5c44c2e6907a7
bigcode/the-stack
train
e4f8e83dda073e128e9aa0a3
train
class
class ClassificationMetricReporter(MetricReporter): __EXPANSIBLE__ = True class Config(MetricReporter.Config): model_select_metric: ComparableClassificationMetric = ( ComparableClassificationMetric.ACCURACY ) target_label: Optional[str] = None #: These column names c...
class ClassificationMetricReporter(MetricReporter):
__EXPANSIBLE__ = True class Config(MetricReporter.Config): model_select_metric: ComparableClassificationMetric = ( ComparableClassificationMetric.ACCURACY ) target_label: Optional[str] = None #: These column names correspond to raw input data columns. Text in these ...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved from enum import Enum from typing import List, Optional from pytext.common.constants import Stage from pytext.data import CommonMetadata from pytext.metrics import ( RECALL_AT_PRECISION_THRESHOLDS, LabelListPredictio...
231
256
1,169
8
223
sdwivedi/pytext
pytext/metric_reporters/classification_metric_reporter.py
Python
ClassificationMetricReporter
ClassificationMetricReporter
36
177
36
36
07d02ee533fa6e5fb0105d6688220b7a5d4741c0
bigcode/the-stack
train
2f6ac9760364b5db0cecf19c
train
class
class ComparableClassificationMetric(Enum): ACCURACY = "accuracy" ROC_AUC = "roc_auc" MCC = "mcc" MACRO_F1 = "macro_f1" LABEL_F1 = "label_f1" LABEL_AVG_PRECISION = "label_avg_precision" LABEL_ROC_AUC = "label_roc_auc" # use negative because the reporter's lower_is_better value is False ...
class ComparableClassificationMetric(Enum):
ACCURACY = "accuracy" ROC_AUC = "roc_auc" MCC = "mcc" MACRO_F1 = "macro_f1" LABEL_F1 = "label_f1" LABEL_AVG_PRECISION = "label_avg_precision" LABEL_ROC_AUC = "label_roc_auc" # use negative because the reporter's lower_is_better value is False NEGATIVE_LOSS = "negative_loss"
ISION_THRESHOLDS, LabelListPrediction, LabelPrediction, compute_classification_metrics, compute_multi_label_classification_metrics, ) from .channel import Channel, ConsoleChannel, FileChannel from .metric_reporter import MetricReporter META_LABEL_NAMES = "label_names" class ComparableClassificationMe...
64
64
102
6
58
sdwivedi/pytext
pytext/metric_reporters/classification_metric_reporter.py
Python
ComparableClassificationMetric
ComparableClassificationMetric
24
33
24
24
2662e44489953143afa0fa2d65f58520ddbbe063
bigcode/the-stack
train
188357c5e128eee8003d20bb
train
class
class MultiLabelClassificationMetricReporter(ClassificationMetricReporter): def calculate_metric(self): return compute_multi_label_classification_metrics( [ LabelListPrediction(scores, pred, expect) for scores, pred, expect in zip( self.all_sco...
class MultiLabelClassificationMetricReporter(ClassificationMetricReporter):
def calculate_metric(self): return compute_multi_label_classification_metrics( [ LabelListPrediction(scores, pred, expect) for scores, pred, expect in zip( self.all_scores, self.all_preds, self.all_targets ) ], ...
elif self.model_select_metric == ComparableClassificationMetric.NEGATIVE_LOSS: metric = -metrics.loss else: raise ValueError(f"unknown metric: {self.model_select_metric}") assert metric is not None return metric class MultiLabelClassificationMetricReporter(Class...
64
64
176
11
52
sdwivedi/pytext
pytext/metric_reporters/classification_metric_reporter.py
Python
MultiLabelClassificationMetricReporter
MultiLabelClassificationMetricReporter
180
210
180
180
f0c87c3e4f9d0ed331c9e6d6ce44f5a18b8ca407
bigcode/the-stack
train
c3e07b610e99b11367b7a517
train
class
class Migration(migrations.Migration): dependencies = [ ('visualizer', '0004_auto_20171220_1610'), ] operations = [ migrations.AlterField( model_name='visualization', name='icon', field=models.ImageField(default='visualizer/static/visualizer/img/default-...
class Migration(migrations.Migration):
dependencies = [ ('visualizer', '0004_auto_20171220_1610'), ] operations = [ migrations.AlterField( model_name='visualization', name='icon', field=models.ImageField(default='visualizer/static/visualizer/img/default-img.jpg', upload_to='visualizer/static/v...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-03-12 07:52 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration):
52
64
85
7
44
dipapaspyros/bdo_platform
visualizer/migrations/0005_auto_20180312_0952.py
Python
Migration
Migration
8
20
8
9
fa8f76693f07af70032413428d0279713fcc5f66
bigcode/the-stack
train
85282697e95fdc8038d199bc
train
class
class CategoryAdmin(BaseOwnerAdmin): list_display = [ 'name', 'status', 'is_nav', 'created_time' ] fields = ( 'name', 'status', 'is_nav' )
class CategoryAdmin(BaseOwnerAdmin):
list_display = [ 'name', 'status', 'is_nav', 'created_time' ] fields = ( 'name', 'status', 'is_nav' )
:blog_post_change', args=(obj.id,)) ) # 添加描述,这句代码不加,管理界面会显示operator operator.short_description = '操作' xadmin.site.register(Post, PostAdmin) # @admin.register(Category, site=custom_site) class CategoryAdmin(BaseOwnerAdmin):
64
64
48
7
57
Family-TreeSY/WeBlog
weblog/blog/adminx.py
Python
CategoryAdmin
CategoryAdmin
66
74
66
66
4a0c388263eef2e14f2b171de2197ea681c0d4a4
bigcode/the-stack
train
aa50e2b930a91fcce7617136
train
class
class PostAdmin(BaseOwnerAdmin): ''' list_display: 展示页面要展示的功能 search_fields: 搜索栏 actions_on_top: 动作栏 fields: 编辑页面要展示的功能 ''' form = PostAdminForm list_display = [ 'title', 'user', 'status', 'category', 'pv', 'uv', 'created_time', 'operator' ] search_fields = ['title'] ...
class PostAdmin(BaseOwnerAdmin):
''' list_display: 展示页面要展示的功能 search_fields: 搜索栏 actions_on_top: 动作栏 fields: 编辑页面要展示的功能 ''' form = PostAdminForm list_display = [ 'title', 'user', 'status', 'category', 'pv', 'uv', 'created_time', 'operator' ] search_fields = ['title'] list_filter = ('user',) acti...
import xadmin from xadmin.layout import Fieldset, Row # from django.contrib import admin from django.urls import reverse from django.utils.html import format_html from .models import Post, Category, Tag # from weblog.custom_site import custom_site from .adminforms import PostAdminForm from weblog.adminx import BaseOwn...
90
90
303
7
83
Family-TreeSY/WeBlog
weblog/blog/adminx.py
Python
PostAdmin
PostAdmin
15
62
15
15
bb6c7d16f4cac830c9b4cdf6d5e3eba96e005c0f
bigcode/the-stack
train
575cea9875992fe6495067d5
train
class
class TagAdmin(BaseOwnerAdmin): list_display = [ 'name', 'status', 'created_time', ] fields = ( 'name', 'status', )
class TagAdmin(BaseOwnerAdmin):
list_display = [ 'name', 'status', 'created_time', ] fields = ( 'name', 'status', )
[ 'name', 'status', 'is_nav', 'created_time' ] fields = ( 'name', 'status', 'is_nav' ) xadmin.site.register(Category, CategoryAdmin) # @admin.register(Tag, site=custom_site) class TagAdmin(BaseOwnerAdmin):
64
64
39
7
57
Family-TreeSY/WeBlog
weblog/blog/adminx.py
Python
TagAdmin
TagAdmin
78
85
78
78
b5f28c510686a892b2d1eb963698f2adef0125f2
bigcode/the-stack
train
af537aaa4825ca85d8ff1bde
train
function
def get_all_notification_sites(user_id, chat_site, room_id): sites = [] for notification in GlobalVars.notifications: if notification[0] == int(user_id) and notification[1] == chat_site and notification[2] == int(room_id): sites.append(notification[3]) return sorted(sites)
def get_all_notification_sites(user_id, chat_site, room_id):
sites = [] for notification in GlobalVars.notifications: if notification[0] == int(user_id) and notification[1] == chat_site and notification[2] == int(room_id): sites.append(notification[3]) return sorted(sites)
int(user_id) my_notifications = [] for notification in GlobalVars.notifications: if notification[0] == user_id: my_notifications.append(notification[:4]) for notification in my_notifications: remove_from_notification_list(*notification) def get_all_notification_sites(user_id, ...
64
64
68
14
50
mehrdad-shokri/SmokeDetector
datahandling.py
Python
get_all_notification_sites
get_all_notification_sites
485
490
485
485
91d939146b09305c5837df719f3c922377c1ff2f
bigcode/the-stack
train
d790c70b29bf8d08a17d14dc
train
function
def get_blacklisted_user_data(user): try: return (user,) + tuple(GlobalVars.blacklisted_users[user]) except KeyError: return ()
def get_blacklisted_user_data(user):
try: return (user,) + tuple(GlobalVars.blacklisted_users[user]) except KeyError: return ()
Vars.false_positives # noinspection PyMissingTypeHints def is_whitelisted_user(user): return user in GlobalVars.whitelisted_users # noinspection PyMissingTypeHints def is_blacklisted_user(user): return user in GlobalVars.blacklisted_users def get_blacklisted_user_data(user):
64
64
33
8
55
mehrdad-shokri/SmokeDetector
datahandling.py
Python
get_blacklisted_user_data
get_blacklisted_user_data
160
164
160
160
823a9783b65ee54df1b10a61f49b4f7520ac1e30
bigcode/the-stack
train
b6bd33d87db195b59cf11bc4
train
function
def add_false_positive(site_post_id_tuple): if site_post_id_tuple is None or site_post_id_tuple in GlobalVars.false_positives: return GlobalVars.false_positives.append(site_post_id_tuple) _dump_pickle("falsePositives.p", GlobalVars.false_positives) global last_feedbacked last_feedbacked = (...
def add_false_positive(site_post_id_tuple):
if site_post_id_tuple is None or site_post_id_tuple in GlobalVars.false_positives: return GlobalVars.false_positives.append(site_post_id_tuple) _dump_pickle("falsePositives.p", GlobalVars.false_positives) global last_feedbacked last_feedbacked = (site_post_id_tuple, time.time() + 60)
_site_tuple): if postid_site_tuple is None or is_auto_ignored_post(postid_site_tuple): return GlobalVars.auto_ignored_posts.append(postid_site_tuple) _dump_pickle("autoIgnoredPosts.p", GlobalVars.auto_ignored_posts) def add_false_positive(site_post_id_tuple):
64
64
87
9
55
mehrdad-shokri/SmokeDetector
datahandling.py
Python
add_false_positive
add_false_positive
256
263
256
256
7ec797cb362f0f70904caaec5c0e2f96b8874693
bigcode/the-stack
train
53cffe54f4ba108d0b8dad4a
train
function
def add_blacklisted_user(user, message_url, post_url): if is_blacklisted_user(user) or user is None: return GlobalVars.blacklisted_users[user] = (message_url, post_url) _dump_pickle("blacklistedUsers.p", GlobalVars.blacklisted_users)
def add_blacklisted_user(user, message_url, post_url):
if is_blacklisted_user(user) or user is None: return GlobalVars.blacklisted_users[user] = (message_url, post_url) _dump_pickle("blacklistedUsers.p", GlobalVars.blacklisted_users)
Hints def add_whitelisted_user(user): if user in GlobalVars.whitelisted_users or user is None: return GlobalVars.whitelisted_users.add(user) _dump_pickle("whitelistedUsers.p", GlobalVars.whitelisted_users) def add_blacklisted_user(user, message_url, post_url):
64
64
61
13
51
mehrdad-shokri/SmokeDetector
datahandling.py
Python
add_blacklisted_user
add_blacklisted_user
242
246
242
242
9a3d603b13ba43ae2f79b68a29a464ca2cb2ae89
bigcode/the-stack
train
e5aff5a91470c93c446de5dd
train
function
def remove_whitelisted_user(user): if user not in GlobalVars.whitelisted_users: return False GlobalVars.whitelisted_users.remove(user) _dump_pickle("whitelistedUsers.p", GlobalVars.whitelisted_users) return True
def remove_whitelisted_user(user):
if user not in GlobalVars.whitelisted_users: return False GlobalVars.whitelisted_users.remove(user) _dump_pickle("whitelistedUsers.p", GlobalVars.whitelisted_users) return True
(user) if not blacklisted_user_data: return False GlobalVars.blacklisted_users.pop(blacklisted_user_data[0]) _dump_pickle("blacklistedUsers.p", GlobalVars.blacklisted_users) return True # noinspection PyMissingTypeHints def remove_whitelisted_user(user):
64
64
51
7
56
mehrdad-shokri/SmokeDetector
datahandling.py
Python
remove_whitelisted_user
remove_whitelisted_user
287
292
287
287
5a570beaec7a903f38630f39e3a20897013a2455
bigcode/the-stack
train
76cde575bf1401ba6aed637b
train
function
def load_files(): if _has_pickle("falsePositives.p"): GlobalVars.false_positives = _load_pickle("falsePositives.p", encoding='utf-8') if _has_pickle("whitelistedUsers.p"): GlobalVars.whitelisted_users = _load_pickle("whitelistedUsers.p", encoding='utf-8') if not isinstance(GlobalVars.whi...
def load_files():
if _has_pickle("falsePositives.p"): GlobalVars.false_positives = _load_pickle("falsePositives.p", encoding='utf-8') if _has_pickle("whitelistedUsers.p"): GlobalVars.whitelisted_users = _load_pickle("whitelistedUsers.p", encoding='utf-8') if not isinstance(GlobalVars.whitelisted_users, se...
if os.path.isfile(path): # Remove old one os.remove(path) newpath = os.path.join(PICKLE_STORAGE, path) with open(newpath, "wb") as f: pickle.dump(item, f, protocol=protocol) def _remove_pickle(path): try: os.remove(path) except OSError: pass path = os.path.join...
172
172
574
4
167
mehrdad-shokri/SmokeDetector
datahandling.py
Python
load_files
load_files
92
127
92
92
6255ae7489b7a6d445c30b9d53b0109ffda75579
bigcode/the-stack
train
1bf697b7dca6370113aa5cb5
train
function
def is_false_positive(postid_site_tuple): return postid_site_tuple in GlobalVars.false_positives
def is_false_positive(postid_site_tuple):
return postid_site_tuple in GlobalVars.false_positives
in to_remove: GlobalVars.auto_ignored_posts.remove(tr) _dump_pickle("autoIgnoredPosts.p", GlobalVars.auto_ignored_posts) # methods to check whether a post/user is whitelisted/blacklisted/... # noinspection PyMissingTypeHints def is_false_positive(postid_site_tuple):
64
64
23
9
54
mehrdad-shokri/SmokeDetector
datahandling.py
Python
is_false_positive
is_false_positive
146
147
146
146
2f697cb54dbd14ae6b686088959b7fd5abbaf3aa
bigcode/the-stack
train
c9a0a8bfb326d4db3701e913
train
function
def store_bodyfetcher_queue(): _dump_pickle("bodyfetcherQueue.p", GlobalVars.bodyfetcher.queue)
def store_bodyfetcher_queue():
_dump_pickle("bodyfetcherQueue.p", GlobalVars.bodyfetcher.queue)
_per_site[site] = 1 _dump_pickle("apiCalls.pickle", GlobalVars.api_calls_per_site) def clear_api_data(): GlobalVars.api_calls_per_site = {} _dump_pickle("apiCalls.pickle", GlobalVars.api_calls_per_site) def store_bodyfetcher_queue():
64
64
25
7
57
mehrdad-shokri/SmokeDetector
datahandling.py
Python
store_bodyfetcher_queue
store_bodyfetcher_queue
338
339
338
338
9b96c4df07a1dd1cdb6a2d823e7656e9ce1595b2
bigcode/the-stack
train
08557cf86cdd8a51c691a0e1
train
function
def _dump_pickle(path, item, protocol=pickle.HIGHEST_PROTOCOL): if not os.path.isdir(PICKLE_STORAGE): os.mkdir(PICKLE_STORAGE) if os.path.isfile(path): # Remove old one os.remove(path) newpath = os.path.join(PICKLE_STORAGE, path) with open(newpath, "wb") as f: pickle.dump(item, ...
def _dump_pickle(path, item, protocol=pickle.HIGHEST_PROTOCOL):
if not os.path.isdir(PICKLE_STORAGE): os.mkdir(PICKLE_STORAGE) if os.path.isfile(path): # Remove old one os.remove(path) newpath = os.path.join(PICKLE_STORAGE, path) with open(newpath, "wb") as f: pickle.dump(item, f, protocol=protocol)
except EOFError: _save_problem_pickle(path) raise except pickle.UnpicklingError as err: if 'pickle data was truncated' in str(err).lower(): _save_problem_pickle(path) raise def _dump_pickle(path, item, protocol=pickle.HIGHEST_PROTOCOL):
64
64
90
16
47
mehrdad-shokri/SmokeDetector
datahandling.py
Python
_dump_pickle
_dump_pickle
63
70
63
63
c696e435647b60f11a4aa1a659a400c945d904c3
bigcode/the-stack
train
f8c98708c1b46d012e6522d1
train
function
def add_why(site, post_id, why): key = site + "/" + str(post_id) why_data_tuple = (key, why) GlobalVars.why_data.append(why_data_tuple) filter_why() _dump_pickle("whyData.p", GlobalVars.why_data)
def add_why(site, post_id, why):
key = site + "/" + str(post_id) why_data_tuple = (key, why) GlobalVars.why_data.append(why_data_tuple) filter_why() _dump_pickle("whyData.p", GlobalVars.why_data)
Hints def remove_whitelisted_user(user): if user not in GlobalVars.whitelisted_users: return False GlobalVars.whitelisted_users.remove(user) _dump_pickle("whitelistedUsers.p", GlobalVars.whitelisted_users) return True def add_why(site, post_id, why):
64
64
64
11
52
mehrdad-shokri/SmokeDetector
datahandling.py
Python
add_why
add_why
295
300
295
295
6e6d396a29b23f79f5d7bbb3b09c0e4c22efea68
bigcode/the-stack
train
b883913440e3b382f9f897c6
train
function
def _has_pickle(path): newpath = os.path.join(PICKLE_STORAGE, path) return os.path.isfile(newpath) or os.path.isfile(path)
def _has_pickle(path):
newpath = os.path.join(PICKLE_STORAGE, path) return os.path.isfile(newpath) or os.path.isfile(path)
, f, protocol=protocol) def _remove_pickle(path): try: os.remove(path) except OSError: pass path = os.path.join(PICKLE_STORAGE, path) try: os.remove(path) except OSError: pass def _has_pickle(path):
64
64
34
6
57
mehrdad-shokri/SmokeDetector
datahandling.py
Python
_has_pickle
_has_pickle
85
87
85
85
7a2754173656c9d444c4c976dad34664a78129db
bigcode/the-stack
train
67747ee2a7857cb457779494
train
function
def add_to_notification_list(user_id, chat_site, room_id, se_site, always_ping=True): if se_site[0] != "/": exists, se_site = check_site_and_get_full_name(se_site) if not exists: return -2, None notification_tuple = (int(user_id), chat_site, int(room_id), se_site, Any()) if notif...
def add_to_notification_list(user_id, chat_site, room_id, se_site, always_ping=True):
if se_site[0] != "/": exists, se_site = check_site_and_get_full_name(se_site) if not exists: return -2, None notification_tuple = (int(user_id), chat_site, int(room_id), se_site, Any()) if notification_tuple in GlobalVars.notifications: return -1, None GlobalVars.noti...
given site." # methods to add/remove/check users on the "notification" list # (that is, being pinged when Smokey reports something on a specific site) # noinspection PyMissingTypeHints def add_to_notification_list(user_id, chat_site, room_id, se_site, always_ping=True):
64
64
138
21
42
mehrdad-shokri/SmokeDetector
datahandling.py
Python
add_to_notification_list
add_to_notification_list
436
446
436
436
991700703e326814f20801fdd33135c32145eeaf
bigcode/the-stack
train
28d4ff6e86b567ff647bba0e
train
function
def is_blacklisted_user(user): return user in GlobalVars.blacklisted_users
def is_blacklisted_user(user):
return user in GlobalVars.blacklisted_users
def is_false_positive(postid_site_tuple): return postid_site_tuple in GlobalVars.false_positives # noinspection PyMissingTypeHints def is_whitelisted_user(user): return user in GlobalVars.whitelisted_users # noinspection PyMissingTypeHints def is_blacklisted_user(user):
64
64
17
7
56
mehrdad-shokri/SmokeDetector
datahandling.py
Python
is_blacklisted_user
is_blacklisted_user
156
157
156
156
a3c0daafca8604be436f00420f9e912021b86f12
bigcode/the-stack
train
1d4d127084f985618a1b10bb
train
function
def filter_why(max_size=50): GlobalVars.why_data = GlobalVars.why_data[-max_size:]
def filter_why(max_size=50):
GlobalVars.why_data = GlobalVars.why_data[-max_size:]
GlobalVars.why_data) def get_why(site, post_id): key = site + "/" + str(post_id) for post in GlobalVars.why_data: if post[0] == key: return post[1] return None def filter_why(max_size=50):
64
64
25
9
54
mehrdad-shokri/SmokeDetector
datahandling.py
Python
filter_why
filter_why
311
312
311
311
003cbeb92a87a58043bdb1e8a3e0fd17ed2192ba
bigcode/the-stack
train
9a301425d880d267ee906361
train
function
def remove_all_from_notification_list(user_id): user_id = int(user_id) my_notifications = [] for notification in GlobalVars.notifications: if notification[0] == user_id: my_notifications.append(notification[:4]) for notification in my_notifications: remove_from_notification...
def remove_all_from_notification_list(user_id):
user_id = int(user_id) my_notifications = [] for notification in GlobalVars.notifications: if notification[0] == user_id: my_notifications.append(notification[:4]) for notification in my_notifications: remove_from_notification_list(*notification)
check_site_and_get_full_name(se_site) if not exists: return False notification_tuple = (int(user_id), chat_site, int(room_id), site, Any()) return notification_tuple in GlobalVars.notifications # noinspection PyMissingTypeHints def remove_all_from_notification_list(user_id):
64
64
63
9
54
mehrdad-shokri/SmokeDetector
datahandling.py
Python
remove_all_from_notification_list
remove_all_from_notification_list
473
482
473
473
0f03579dcf9eb71424f5f8bc1c4d819451242e3b
bigcode/the-stack
train
e0076cf287bb47a03e5cbbaa
train
function
def remove_from_notification_list(user_id, chat_site, room_id, se_site): if se_site[0] != "/": exists, se_site = check_site_and_get_full_name(se_site) if not exists: return False notification_tuple = (int(user_id), chat_site, int(room_id), se_site, Any()) if notification_tuple no...
def remove_from_notification_list(user_id, chat_site, room_id, se_site):
if se_site[0] != "/": exists, se_site = check_site_and_get_full_name(se_site) if not exists: return False notification_tuple = (int(user_id), chat_site, int(room_id), se_site, Any()) if notification_tuple not in GlobalVars.notifications: return False GlobalVars.notifi...
.append((int(user_id), chat_site, int(room_id), se_site, always_ping)) _dump_pickle("notifications.p", GlobalVars.notifications) return 0, se_site # noinspection PyMissingTypeHints def remove_from_notification_list(user_id, chat_site, room_id, se_site):
64
64
110
17
46
mehrdad-shokri/SmokeDetector
datahandling.py
Python
remove_from_notification_list
remove_from_notification_list
450
460
450
450
2bf8879da4cdba686ae89a37a10acde11ed2fc31
bigcode/the-stack
train
66f1ff0a2f925a6889893a86
train
function
def get_post_site_id_link(post_site_id): if post_site_id in GlobalVars.post_site_id_to_question: return GlobalVars.post_site_id_to_question[post_site_id] return None
def get_post_site_id_link(post_site_id):
if post_site_id in GlobalVars.post_site_id_to_question: return GlobalVars.post_site_id_to_question[post_site_id] return None
_why(max_size=50): GlobalVars.why_data = GlobalVars.why_data[-max_size:] def add_post_site_id_link(post_site_id, question_id): GlobalVars.post_site_id_to_question[post_site_id] = question_id def get_post_site_id_link(post_site_id):
64
64
42
10
53
mehrdad-shokri/SmokeDetector
datahandling.py
Python
get_post_site_id_link
get_post_site_id_link
319
322
319
319
54e1582a4c2dcca7cf06d28be2e01d8f273bb7dd
bigcode/the-stack
train
f18b93552f9c69f2f234fe15
train
function
def is_whitelisted_user(user): return user in GlobalVars.whitelisted_users
def is_whitelisted_user(user):
return user in GlobalVars.whitelisted_users
_posts) # methods to check whether a post/user is whitelisted/blacklisted/... # noinspection PyMissingTypeHints def is_false_positive(postid_site_tuple): return postid_site_tuple in GlobalVars.false_positives # noinspection PyMissingTypeHints def is_whitelisted_user(user):
64
64
17
7
56
mehrdad-shokri/SmokeDetector
datahandling.py
Python
is_whitelisted_user
is_whitelisted_user
151
152
151
151
fa052a5d4e9aeefed95c99bf0bc729ae6e65baa7
bigcode/the-stack
train
1cd1f6b5051bf4ede942c754
train
function
def remove_blacklisted_user(user): blacklisted_user_data = get_blacklisted_user_data(user) if not blacklisted_user_data: return False GlobalVars.blacklisted_users.pop(blacklisted_user_data[0]) _dump_pickle("blacklistedUsers.p", GlobalVars.blacklisted_users) return True
def remove_blacklisted_user(user):
blacklisted_user_data = get_blacklisted_user_data(user) if not blacklisted_user_data: return False GlobalVars.blacklisted_users.pop(blacklisted_user_data[0]) _dump_pickle("blacklistedUsers.p", GlobalVars.blacklisted_users) return True
ignored_posts: return GlobalVars.ignored_posts.append(postid_site_tuple) _dump_pickle("ignoredPosts.p", GlobalVars.ignored_posts) global last_feedbacked last_feedbacked = (postid_site_tuple, time.time() + 60) def remove_blacklisted_user(user):
64
64
67
7
57
mehrdad-shokri/SmokeDetector
datahandling.py
Python
remove_blacklisted_user
remove_blacklisted_user
277
283
277
277
c3586a546af2910e153dbd7cd2b96f4cf6f0eb00
bigcode/the-stack
train
56e3b083d1a8d212dd8d9657
train
function
def clear_api_data(): GlobalVars.api_calls_per_site = {} _dump_pickle("apiCalls.pickle", GlobalVars.api_calls_per_site)
def clear_api_data():
GlobalVars.api_calls_per_site = {} _dump_pickle("apiCalls.pickle", GlobalVars.api_calls_per_site)
if site in GlobalVars.api_calls_per_site: GlobalVars.api_calls_per_site[site] += 1 else: GlobalVars.api_calls_per_site[site] = 1 _dump_pickle("apiCalls.pickle", GlobalVars.api_calls_per_site) def clear_api_data():
64
64
31
5
59
mehrdad-shokri/SmokeDetector
datahandling.py
Python
clear_api_data
clear_api_data
333
335
333
333
3da8b0ea4b446884f75802a8956a2f5c27d7bc03
bigcode/the-stack
train
05f7be79ed647d6143d25d25
train
function
def is_ignored_post(postid_site_tuple): return postid_site_tuple in GlobalVars.ignored_posts
def is_ignored_post(postid_site_tuple):
return postid_site_tuple in GlobalVars.ignored_posts
(user): return user in GlobalVars.blacklisted_users def get_blacklisted_user_data(user): try: return (user,) + tuple(GlobalVars.blacklisted_users[user]) except KeyError: return () # noinspection PyMissingTypeHints def is_ignored_post(postid_site_tuple):
64
64
23
10
53
mehrdad-shokri/SmokeDetector
datahandling.py
Python
is_ignored_post
is_ignored_post
168
169
168
168
6e539b02094e0c542de282e69fcb328b813f3dcf
bigcode/the-stack
train
62ae9a511f8cb82eaf3248e5
train
function
def append_pings(original_message, names): if len(names) != 0: new_message = u"{0} ({1})".format(original_message, " ".join("@" + x.replace(" ", "") for x in names)) if len(new_message) <= 500: return new_message return original_message
def append_pings(original_message, names):
if len(names) != 0: new_message = u"{0} ({1})".format(original_message, " ".join("@" + x.replace(" ", "") for x in names)) if len(new_message) <= 500: return new_message return original_message
.get_user(i).name) else: try: names.append(current_users[current_users.index((i, Any()))][1]) except ValueError: # user not in room pass return names # noinspection PyMissingTypeHints def append_pings(original_message, names):
64
64
70
9
54
mehrdad-shokri/SmokeDetector
datahandling.py
Python
append_pings
append_pings
528
533
528
528
1ecb782cbef57bf3ef7b04203817dd69bd31d204
bigcode/the-stack
train
d1c9d0e23ef2646c08758b03
train
function
def refresh_sites(): has_more = True page = 1 url = "https://api.stackexchange.com/2.2/sites" while has_more: params = { 'filter': '!)Qpa1bTB_jCkeaZsqiQ8pDwI', 'key': 'IAkbitmze4B8KpacUfLqkw((', 'page': page, 'pagesize': 500 } respo...
def refresh_sites():
has_more = True page = 1 url = "https://api.stackexchange.com/2.2/sites" while has_more: params = { 'filter': '!)Qpa1bTB_jCkeaZsqiQ8pDwI', 'key': 'IAkbitmze4B8KpacUfLqkw((', 'page': page, 'pagesize': 500 } response = requests.get(ur...
name, message, tb) for time, name, message, tb in logs]) if s: return redact_passwords(s) else: return "The fetched log is empty." # method to check whether a SE site exists: # noinspection PyMissingTypeHints def refresh_sites():
64
64
211
4
59
mehrdad-shokri/SmokeDetector
datahandling.py
Python
refresh_sites
refresh_sites
392
415
392
392
abdc96e9e3883446a990ca826b560fb6e7371bef
bigcode/the-stack
train
5f329fdbcb5621a695d58f42
train
class
class SmokeyTransfer: HEADER = "-----BEGIN SMOKEY DATA BLOCK-----" ENDING = "-----END SMOKEY DATA BLOCK-----" ITEMS = [ # (dict_key, object, attr, type, post_processing) ('blacklisted_users', GlobalVars, 'blacklisted_users', None, None), ('whitelisted_users', GlobalVars, 'whiteliste...
class SmokeyTransfer:
HEADER = "-----BEGIN SMOKEY DATA BLOCK-----" ENDING = "-----END SMOKEY DATA BLOCK-----" ITEMS = [ # (dict_key, object, attr, type, post_processing) ('blacklisted_users', GlobalVars, 'blacklisted_users', None, None), ('whitelisted_users', GlobalVars, 'whitelisted_users', None, None),...
_integer): user_id = str(user_id) for i in range(len(GlobalVars.multiple_reporters)): if GlobalVars.multiple_reporters[i][0] == user_id and GlobalVars.multiple_reporters[i][1] == chat_host: GlobalVars.multiple_reporters[i] = (GlobalVars.multiple_reporters[i][0], ...
237
237
792
5
232
mehrdad-shokri/SmokeDetector
datahandling.py
Python
SmokeyTransfer
SmokeyTransfer
581
662
581
581
434fd156e2f034b30f65a2a8e932c0b9c755d700
bigcode/the-stack
train
b452b55c949efd19493309c3
train
function
def _save_problem_pickle(path): # Keep the most recent copy of a pickle file which had an error. errorpath = path + '-error' if os.path.isfile(errorpath): os.remove(errorpath) if os.path.isfile(path): os.rename(path, errorpath)
def _save_problem_pickle(path): # Keep the most recent copy of a pickle file which had an error.
errorpath = path + '-error' if os.path.isfile(errorpath): os.remove(errorpath) if os.path.isfile(path): os.rename(path, errorpath)
log, log_exception, redact_passwords last_feedbacked = None PICKLE_STORAGE = "pickles/" class Any: def __eq__(self, _): return True def _save_problem_pickle(path): # Keep the most recent copy of a pickle file which had an error.
64
64
61
23
40
mehrdad-shokri/SmokeDetector
datahandling.py
Python
_save_problem_pickle
_save_problem_pickle
30
36
30
31
1f1b79d9eb1dc5e6299d32a465df55674d0ee287
bigcode/the-stack
train
a2a1e5165d220baf5fa017c9
train
function
def is_auto_ignored_post(postid_site_tuple): for p in GlobalVars.auto_ignored_posts: if p[0] == postid_site_tuple[0] and p[1] == postid_site_tuple[1]: return True return False
def is_auto_ignored_post(postid_site_tuple):
for p in GlobalVars.auto_ignored_posts: if p[0] == postid_site_tuple[0] and p[1] == postid_site_tuple[1]: return True return False
.blacklisted_users[user]) except KeyError: return () # noinspection PyMissingTypeHints def is_ignored_post(postid_site_tuple): return postid_site_tuple in GlobalVars.ignored_posts # noinspection PyMissingTypeHints def is_auto_ignored_post(postid_site_tuple):
64
64
57
11
52
mehrdad-shokri/SmokeDetector
datahandling.py
Python
is_auto_ignored_post
is_auto_ignored_post
173
177
173
173
a71250bf2e018af7e43e79ec0849b44560e66a4c
bigcode/the-stack
train
62b2d7b28f49b5d3525d9707
train
function
def has_community_bumped_post(post_url, post_content): if GlobalVars.metasmoke_key is not None and GlobalVars.metasmoke_host is not None: try: ms_posts = metasmoke.Metasmoke.get_post_bodies_from_ms(post_url) if not ms_posts: return False return any(post['...
def has_community_bumped_post(post_url, post_content):
if GlobalVars.metasmoke_key is not None and GlobalVars.metasmoke_host is not None: try: ms_posts = metasmoke.Metasmoke.get_post_bodies_from_ms(post_url) if not ms_posts: return False return any(post['body'] == post_content for post in ms_posts) ex...
_message, " ".join("@" + x.replace(" ", "") for x in names)) if len(new_message) <= 500: return new_message return original_message # method to check if a post has been bumped by Community def has_community_bumped_post(post_url, post_content):
64
64
115
13
50
mehrdad-shokri/SmokeDetector
datahandling.py
Python
has_community_bumped_post
has_community_bumped_post
538
548
538
538
6251c37218c2a46da89924658916dc30fe71f1ec
bigcode/the-stack
train
48c98e264912ef60fc7c686f
train
function
def add_ignored_post(postid_site_tuple): if postid_site_tuple is None or postid_site_tuple in GlobalVars.ignored_posts: return GlobalVars.ignored_posts.append(postid_site_tuple) _dump_pickle("ignoredPosts.p", GlobalVars.ignored_posts) global last_feedbacked last_feedbacked = (postid_site_tu...
def add_ignored_post(postid_site_tuple):
if postid_site_tuple is None or postid_site_tuple in GlobalVars.ignored_posts: return GlobalVars.ignored_posts.append(postid_site_tuple) _dump_pickle("ignoredPosts.p", GlobalVars.ignored_posts) global last_feedbacked last_feedbacked = (postid_site_tuple, time.time() + 60)
(site_post_id_tuple) _dump_pickle("falsePositives.p", GlobalVars.false_positives) global last_feedbacked last_feedbacked = (site_post_id_tuple, time.time() + 60) # noinspection PyMissingTypeHints def add_ignored_post(postid_site_tuple):
64
64
84
10
53
mehrdad-shokri/SmokeDetector
datahandling.py
Python
add_ignored_post
add_ignored_post
267
274
267
267
144095d1b6986d752a6363cb0e6f88b72d82a250
bigcode/the-stack
train
68bd283966ec6924bd9de36c
train
function
def get_user_ids_on_notification_list(chat_site, room_id, se_site): uids = [] for notification in GlobalVars.notifications: if notification[1] == chat_site and notification[2] == int(room_id) and notification[3] == se_site: uids.append((notification[0], notification[4])) return uids
def get_user_ids_on_notification_list(chat_site, room_id, se_site):
uids = [] for notification in GlobalVars.notifications: if notification[1] == chat_site and notification[2] == int(room_id) and notification[3] == se_site: uids.append((notification[0], notification[4])) return uids
notification in GlobalVars.notifications: if notification[0] == int(user_id) and notification[1] == chat_site and notification[2] == int(room_id): sites.append(notification[3]) return sorted(sites) def get_user_ids_on_notification_list(chat_site, room_id, se_site):
64
64
75
16
48
mehrdad-shokri/SmokeDetector
datahandling.py
Python
get_user_ids_on_notification_list
get_user_ids_on_notification_list
493
498
493
493
be23dacb6edbf3f62c0427e444e77104870cf0a0
bigcode/the-stack
train
679486b2f448484b844b8f88
train
function
def fetch_lines_from_error_log(count): if not os.path.isfile("errorLogs.db"): return "The error log database does not exist." if count <= 0: return "Please request an exception count greater than zero." logs = ErrorLogs.fetch_last(count) s = '\n'.join([ "### {2} on {0} at {1}Z: {...
def fetch_lines_from_error_log(count):
if not os.path.isfile("errorLogs.db"): return "The error log database does not exist." if count <= 0: return "Please request an exception count greater than zero." logs = ErrorLogs.fetch_last(count) s = '\n'.join([ "### {2} on {0} at {1}Z: {3}\n{4}".format( GlobalVars...
_id, title): for post in GlobalVars.latest_questions: if post[0] == host and post[1] == str(post_id): return True return False # method to get data from the error log: # noinspection PyUnusedLocal def fetch_lines_from_error_log(count):
64
64
150
8
55
mehrdad-shokri/SmokeDetector
datahandling.py
Python
fetch_lines_from_error_log
fetch_lines_from_error_log
371
385
371
371
4c2da0b79c9f76cbb4df448f3a4057fec0096f74
bigcode/the-stack
train
d12706a52924b2d91cdb6e2a
train
function
def add_whitelisted_user(user): if user in GlobalVars.whitelisted_users or user is None: return GlobalVars.whitelisted_users.add(user) _dump_pickle("whitelistedUsers.p", GlobalVars.whitelisted_users)
def add_whitelisted_user(user):
if user in GlobalVars.whitelisted_users or user is None: return GlobalVars.whitelisted_users.add(user) _dump_pickle("whitelistedUsers.p", GlobalVars.whitelisted_users)
numeric IDs, strings are hard to handle _dump_pickle("metasmokePostIds.p", GlobalVars.metasmoke_ids) return ms_url # methods to add/remove whitelisted/blacklisted users, ignored posts, ... # noinspection PyMissingTypeHints def add_whitelisted_user(user):
64
64
49
7
56
mehrdad-shokri/SmokeDetector
datahandling.py
Python
add_whitelisted_user
add_whitelisted_user
235
239
235
235
bebcd41a17fb3c4ff8bcc89c8afdf0c8cebcee89
bigcode/the-stack
train
be835ae9ffa596f43568bff0
train
function
def get_why(site, post_id): key = site + "/" + str(post_id) for post in GlobalVars.why_data: if post[0] == key: return post[1] return None
def get_why(site, post_id):
key = site + "/" + str(post_id) for post in GlobalVars.why_data: if post[0] == key: return post[1] return None
why): key = site + "/" + str(post_id) why_data_tuple = (key, why) GlobalVars.why_data.append(why_data_tuple) filter_why() _dump_pickle("whyData.p", GlobalVars.why_data) def get_why(site, post_id):
64
64
49
9
55
mehrdad-shokri/SmokeDetector
datahandling.py
Python
get_why
get_why
303
308
303
303
af89b19e54aa64d51306238b8cd2b8314906df6f
bigcode/the-stack
train
c14453577b45799a40a77b6a
train
function
def _load_pickle(path, encoding='utf-8'): newpath = os.path.join(PICKLE_STORAGE, path) if os.path.isfile(newpath): path = newpath try: with open(path, mode="rb") as f: return pickle.load(f, encoding=encoding) except UnicodeDecodeError: _save_problem_pickle(path) ...
def _load_pickle(path, encoding='utf-8'):
newpath = os.path.join(PICKLE_STORAGE, path) if os.path.isfile(newpath): path = newpath try: with open(path, mode="rb") as f: return pickle.load(f, encoding=encoding) except UnicodeDecodeError: _save_problem_pickle(path) if "apicalls" in path.lower(): ...
Keep the most recent copy of a pickle file which had an error. errorpath = path + '-error' if os.path.isfile(errorpath): os.remove(errorpath) if os.path.isfile(path): os.rename(path, errorpath) def _load_pickle(path, encoding='utf-8'):
64
64
155
12
52
mehrdad-shokri/SmokeDetector
datahandling.py
Python
_load_pickle
_load_pickle
39
60
39
39
7df4b36e0a3b7e21cc0a4a41d3f7e6493b9bfce7
bigcode/the-stack
train
6ada7c11d92e1105f7ed5559
train
function
def can_report_now(user_id, chat_host): user_id = str(user_id) for reporter in GlobalVars.multiple_reporters: if reporter[0] == user_id and reporter[1] == chat_host: now = time.time() latest_report = reporter[2] can_report_again = latest_report + 30 if now...
def can_report_now(user_id, chat_host):
user_id = str(user_id) for reporter in GlobalVars.multiple_reporters: if reporter[0] == user_id and reporter[1] == chat_host: now = time.time() latest_report = reporter[2] can_report_again = latest_report + 30 if now > can_report_again: ret...
iple_reporters[i] = (GlobalVars.multiple_reporters[i][0], GlobalVars.multiple_reporters[i][1], time_integer) return 1 GlobalVars.multiple_reporters.append((user_id, chat_host, time_integer)) def can_report_now(user_id, chat_host):
64
64
104
10
54
mehrdad-shokri/SmokeDetector
datahandling.py
Python
can_report_now
can_report_now
564
574
564
564
81d7a9317a2a44db978be2396e3bf03e39b90a2b
bigcode/the-stack
train
1b568edbf9dec22c92c41d87
train
function
def get_user_names_on_notification_list(chat_site, room_id, se_site, client): names = [] try: current_users = client._br.get_current_users_in_room(room_id) except Exception: # ChatExchange had a problem getting the current users. This shouldn't be allowed to # cause us to crash, as i...
def get_user_names_on_notification_list(chat_site, room_id, se_site, client):
names = [] try: current_users = client._br.get_current_users_in_room(room_id) except Exception: # ChatExchange had a problem getting the current users. This shouldn't be allowed to # cause us to crash, as it's on the path we take for going into standby. # It should be noted t...
[] for notification in GlobalVars.notifications: if notification[1] == chat_site and notification[2] == int(room_id) and notification[3] == se_site: uids.append((notification[0], notification[4])) return uids def get_user_names_on_notification_list(chat_site, room_id, se_site, client):
73
73
245
18
54
mehrdad-shokri/SmokeDetector
datahandling.py
Python
get_user_names_on_notification_list
get_user_names_on_notification_list
501
524
501
501
669e996a1c1db30e6d82bb6c93caeeafb61bc97e
bigcode/the-stack
train
00e483141006e07cfdc5fbe9
train
function
def add_auto_ignored_post(postid_site_tuple): if postid_site_tuple is None or is_auto_ignored_post(postid_site_tuple): return GlobalVars.auto_ignored_posts.append(postid_site_tuple) _dump_pickle("autoIgnoredPosts.p", GlobalVars.auto_ignored_posts)
def add_auto_ignored_post(postid_site_tuple):
if postid_site_tuple is None or is_auto_ignored_post(postid_site_tuple): return GlobalVars.auto_ignored_posts.append(postid_site_tuple) _dump_pickle("autoIgnoredPosts.p", GlobalVars.auto_ignored_posts)
_url, post_url): if is_blacklisted_user(user) or user is None: return GlobalVars.blacklisted_users[user] = (message_url, post_url) _dump_pickle("blacklistedUsers.p", GlobalVars.blacklisted_users) def add_auto_ignored_post(postid_site_tuple):
64
64
63
11
53
mehrdad-shokri/SmokeDetector
datahandling.py
Python
add_auto_ignored_post
add_auto_ignored_post
249
253
249
249
2cd42abd90afe36f772cb09c1aae30fc5ebc1ca7
bigcode/the-stack
train
ffd2109896d873e671886f4f
train
function
def add_or_update_multiple_reporter(user_id, chat_host, time_integer): user_id = str(user_id) for i in range(len(GlobalVars.multiple_reporters)): if GlobalVars.multiple_reporters[i][0] == user_id and GlobalVars.multiple_reporters[i][1] == chat_host: GlobalVars.multiple_reporters[i] = (Global...
def add_or_update_multiple_reporter(user_id, chat_host, time_integer):
user_id = str(user_id) for i in range(len(GlobalVars.multiple_reporters)): if GlobalVars.multiple_reporters[i][0] == user_id and GlobalVars.multiple_reporters[i][1] == chat_host: GlobalVars.multiple_reporters[i] = (GlobalVars.multiple_reporters[i][0], ...
, so assume it is not bumped return False # methods to check if someone waited long enough to use another !!/report with multiple URLs # (to avoid SmokeDetector's chat messages to be rate-limited too much) def add_or_update_multiple_reporter(user_id, chat_host, time_integer):
64
64
125
16
48
mehrdad-shokri/SmokeDetector
datahandling.py
Python
add_or_update_multiple_reporter
add_or_update_multiple_reporter
554
561
554
554
19f7310a2d5e77850a85b8fb6a419cb600e690ec
bigcode/the-stack
train
c8a840241e5bed729f874c76
train
class
class Any: def __eq__(self, _): return True
class Any:
def __eq__(self, _): return True
PyCompatibility import regex from parsing import api_parameter_from_link, post_id_from_link from globalvars import GlobalVars import blacklists from helpers import ErrorLogs, log, log_exception, redact_passwords last_feedbacked = None PICKLE_STORAGE = "pickles/" class Any:
63
64
16
3
60
mehrdad-shokri/SmokeDetector
datahandling.py
Python
Any
Any
25
27
25
25
6fa6a1794eb5c27d4a9bffe5ad30c284ef603ca5
bigcode/the-stack
train
4ef7b8474ae2769fd9e007cb
train
function
def store_queue_timings(): _dump_pickle("bodyfetcherQueueTimings.p", GlobalVars.bodyfetcher.queue_timings)
def store_queue_timings():
_dump_pickle("bodyfetcherQueueTimings.p", GlobalVars.bodyfetcher.queue_timings)
_calls_per_site) def store_bodyfetcher_queue(): _dump_pickle("bodyfetcherQueue.p", GlobalVars.bodyfetcher.queue) def store_bodyfetcher_max_ids(): _dump_pickle("bodyfetcherMaxIds.p", GlobalVars.bodyfetcher.previous_max_ids) def store_queue_timings():
64
64
28
6
58
mehrdad-shokri/SmokeDetector
datahandling.py
Python
store_queue_timings
store_queue_timings
346
347
346
346
b44012dfd89f90723bd9afb3614a13b58fbde51a
bigcode/the-stack
train
4da6388ba192284d4f007060
train
function
def will_i_be_notified(user_id, chat_site, room_id, se_site): exists, site = check_site_and_get_full_name(se_site) if not exists: return False notification_tuple = (int(user_id), chat_site, int(room_id), site, Any()) return notification_tuple in GlobalVars.notifications
def will_i_be_notified(user_id, chat_site, room_id, se_site):
exists, site = check_site_and_get_full_name(se_site) if not exists: return False notification_tuple = (int(user_id), chat_site, int(room_id), site, Any()) return notification_tuple in GlobalVars.notifications
if notification_tuple not in GlobalVars.notifications: return False GlobalVars.notifications.remove(notification_tuple) _dump_pickle("notifications.p", GlobalVars.notifications) return True # noinspection PyMissingTypeHints def will_i_be_notified(user_id, chat_site, room_id, se_site):
64
64
70
18
45
mehrdad-shokri/SmokeDetector
datahandling.py
Python
will_i_be_notified
will_i_be_notified
464
469
464
464
99cb67c27d481cf0d3ff9aead0cb4df95eec5e61
bigcode/the-stack
train
30fbef73b22c5b8eaac7caa7
train
function
def update_reason_weights(): d = {'last_updated': datetime.utcnow().date()} items = metasmoke.Metasmoke.get_reason_weights() if not items: return # No update for item in items: d[item['reason_name'].lower()] = item['weight'] GlobalVars.reason_weights = d _dump_pickle("reasonWeig...
def update_reason_weights():
d = {'last_updated': datetime.utcnow().date()} items = metasmoke.Metasmoke.get_reason_weights() if not items: return # No update for item in items: d[item['reason_name'].lower()] = item['weight'] GlobalVars.reason_weights = d _dump_pickle("reasonWeights.p", GlobalVars.reason_wei...
.code_privileged_users is None: update_code_privileged_users_list() try: # For now, disable the moderator override on code/blacklist changes return (site, user_id) in GlobalVars.code_privileged_users except TypeError: return False def update_reason_weights():
64
64
85
5
58
mehrdad-shokri/SmokeDetector
datahandling.py
Python
update_reason_weights
update_reason_weights
196
204
196
196
3a64d0e360a288917ae0ab04a33ca79c592a4a8d
bigcode/the-stack
train
34a10926c3c26c3b056f1eec
train
function
def resolve_ms_link(post_url): identifier = (api_parameter_from_link(post_url), post_id_from_link(post_url)) if identifier in GlobalVars.metasmoke_ids: if isinstance(GlobalVars.metasmoke_ids[identifier], int): ms_url = (GlobalVars.metasmoke_host.rstrip("/") + "/post/{}").format( ...
def resolve_ms_link(post_url):
identifier = (api_parameter_from_link(post_url), post_id_from_link(post_url)) if identifier in GlobalVars.metasmoke_ids: if isinstance(GlobalVars.metasmoke_ids[identifier], int): ms_url = (GlobalVars.metasmoke_host.rstrip("/") + "/post/{}").format( GlobalVars.metasmoke_ids[id...
()} items = metasmoke.Metasmoke.get_reason_weights() if not items: return # No update for item in items: d[item['reason_name'].lower()] = item['weight'] GlobalVars.reason_weights = d _dump_pickle("reasonWeights.p", GlobalVars.reason_weights) def resolve_ms_link(post_url):
76
76
255
7
69
mehrdad-shokri/SmokeDetector
datahandling.py
Python
resolve_ms_link
resolve_ms_link
207
228
207
207
2f65cee0ceaa978123aef0c3aae27977a7e30f16
bigcode/the-stack
train
c79becf8ec53fb541a4d3ab2
train
function
def append_to_latest_questions(host, post_id, title): GlobalVars.latest_questions.insert(0, (host, str(post_id), title)) if len(GlobalVars.latest_questions) > 50: GlobalVars.latest_questions.pop()
def append_to_latest_questions(host, post_id, title):
GlobalVars.latest_questions.insert(0, (host, str(post_id), title)) if len(GlobalVars.latest_questions) > 50: GlobalVars.latest_questions.pop()
fetcherMaxIds.p", GlobalVars.bodyfetcher.previous_max_ids) def store_queue_timings(): _dump_pickle("bodyfetcherQueueTimings.p", GlobalVars.bodyfetcher.queue_timings) # methods that help avoiding reposting alerts: def append_to_latest_questions(host, post_id, title):
64
64
49
12
52
mehrdad-shokri/SmokeDetector
datahandling.py
Python
append_to_latest_questions
append_to_latest_questions
353
356
353
353
3be38cd5eb4f03c360f3cb5a961cd4e50e4d6996
bigcode/the-stack
train
2dd55a32995fb82eb9a9203f
train
function
def has_already_been_posted(host, post_id, title): for post in GlobalVars.latest_questions: if post[0] == host and post[1] == str(post_id): return True return False
def has_already_been_posted(host, post_id, title):
for post in GlobalVars.latest_questions: if post[0] == host and post[1] == str(post_id): return True return False
_id, title): GlobalVars.latest_questions.insert(0, (host, str(post_id), title)) if len(GlobalVars.latest_questions) > 50: GlobalVars.latest_questions.pop() # noinspection PyMissingTypeHints def has_already_been_posted(host, post_id, title):
64
64
50
15
48
mehrdad-shokri/SmokeDetector
datahandling.py
Python
has_already_been_posted
has_already_been_posted
360
364
360
360
085569340778de455c24a1d60509692b4bb0bd4d
bigcode/the-stack
train
825ce574c584a15f76768480
train
function
def store_bodyfetcher_max_ids(): _dump_pickle("bodyfetcherMaxIds.p", GlobalVars.bodyfetcher.previous_max_ids)
def store_bodyfetcher_max_ids():
_dump_pickle("bodyfetcherMaxIds.p", GlobalVars.bodyfetcher.previous_max_ids)
def clear_api_data(): GlobalVars.api_calls_per_site = {} _dump_pickle("apiCalls.pickle", GlobalVars.api_calls_per_site) def store_bodyfetcher_queue(): _dump_pickle("bodyfetcherQueue.p", GlobalVars.bodyfetcher.queue) def store_bodyfetcher_max_ids():
64
64
29
8
56
mehrdad-shokri/SmokeDetector
datahandling.py
Python
store_bodyfetcher_max_ids
store_bodyfetcher_max_ids
342
343
342
342
32a3d0baefb09da2aa6f32a25faa695c69db2a4e
bigcode/the-stack
train
1813e56ddf27fc5175a9b2b3
train
function
def add_post_site_id_link(post_site_id, question_id): GlobalVars.post_site_id_to_question[post_site_id] = question_id
def add_post_site_id_link(post_site_id, question_id):
GlobalVars.post_site_id_to_question[post_site_id] = question_id
GlobalVars.why_data: if post[0] == key: return post[1] return None def filter_why(max_size=50): GlobalVars.why_data = GlobalVars.why_data[-max_size:] def add_post_site_id_link(post_site_id, question_id):
63
64
30
13
50
mehrdad-shokri/SmokeDetector
datahandling.py
Python
add_post_site_id_link
add_post_site_id_link
315
316
315
315
3d37f4b210919c5b2a5c11d5608a01c0e4abf533
bigcode/the-stack
train
7fdd623aa8c649cd11ab1bec
train
function
def update_code_privileged_users_list(): metasmoke.Metasmoke.update_code_privileged_users_list() _dump_pickle("codePrivileges.p", GlobalVars.code_privileged_users)
def update_code_privileged_users_list():
metasmoke.Metasmoke.update_code_privileged_users_list() _dump_pickle("codePrivileges.p", GlobalVars.code_privileged_users)
is_auto_ignored_post(postid_site_tuple): for p in GlobalVars.auto_ignored_posts: if p[0] == postid_site_tuple[0] and p[1] == postid_site_tuple[1]: return True return False def update_code_privileged_users_list():
64
64
39
8
55
mehrdad-shokri/SmokeDetector
datahandling.py
Python
update_code_privileged_users_list
update_code_privileged_users_list
180
182
180
180
02fcd96721e667a74798435211eb4c63bbf4f841
bigcode/the-stack
train
864f945b2a2c9334d8b5b198
train
function
def filter_auto_ignored_posts(): today_date = datetime.today() to_remove = [] for aip in GlobalVars.auto_ignored_posts: day_ignored = aip[2] day_diff = (today_date - day_ignored).days if day_diff > 7: to_remove.append(aip) for tr in to_remove: GlobalVars.auto_...
def filter_auto_ignored_posts():
today_date = datetime.today() to_remove = [] for aip in GlobalVars.auto_ignored_posts: day_ignored = aip[2] day_diff = (today_date - day_ignored).days if day_diff > 7: to_remove.append(aip) for tr in to_remove: GlobalVars.auto_ignored_posts.remove(tr) _dum...
load_pickle("cookies.p", encoding='utf-8') if _has_pickle("metasmokePostIds.p"): GlobalVars.metasmoke_ids = _load_pickle("metasmokePostIds.p", encoding='utf-8') blacklists.load_blacklists() def filter_auto_ignored_posts():
64
64
102
7
57
mehrdad-shokri/SmokeDetector
datahandling.py
Python
filter_auto_ignored_posts
filter_auto_ignored_posts
130
140
130
130
2598331b458018a4f542165c615a0bcae28e4f8f
bigcode/the-stack
train
f8e0097b6b1e0014e308e350
train
function
def _remove_pickle(path): try: os.remove(path) except OSError: pass path = os.path.join(PICKLE_STORAGE, path) try: os.remove(path) except OSError: pass
def _remove_pickle(path):
try: os.remove(path) except OSError: pass path = os.path.join(PICKLE_STORAGE, path) try: os.remove(path) except OSError: pass
LE_STORAGE) if os.path.isfile(path): # Remove old one os.remove(path) newpath = os.path.join(PICKLE_STORAGE, path) with open(newpath, "wb") as f: pickle.dump(item, f, protocol=protocol) def _remove_pickle(path):
64
64
51
6
58
mehrdad-shokri/SmokeDetector
datahandling.py
Python
_remove_pickle
_remove_pickle
73
82
73
73
90ed841a5c4f23ca61f4657cf9080cacb4411d05
bigcode/the-stack
train
47aa7697ab15de41314c8c4d
train
function
def dump_cookies(): _dump_pickle("cookies.p", GlobalVars.cookies)
def dump_cookies():
_dump_pickle("cookies.p", GlobalVars.cookies)
_host: now = time.time() latest_report = reporter[2] can_report_again = latest_report + 30 if now > can_report_again: return True, True return False, math.ceil(can_report_again - now) return True, True def dump_cookies():
64
64
17
5
58
mehrdad-shokri/SmokeDetector
datahandling.py
Python
dump_cookies
dump_cookies
577
578
577
577
44be891f6a48403519262307b379dda594f6074f
bigcode/the-stack
train
14330c37f70f6ef0c1808deb
train
function
def is_code_privileged(site, user_id): if GlobalVars.code_privileged_users is None: update_code_privileged_users_list() try: # For now, disable the moderator override on code/blacklist changes return (site, user_id) in GlobalVars.code_privileged_users except TypeError: retur...
def is_code_privileged(site, user_id):
if GlobalVars.code_privileged_users is None: update_code_privileged_users_list() try: # For now, disable the moderator override on code/blacklist changes return (site, user_id) in GlobalVars.code_privileged_users except TypeError: return False
postid_site_tuple[1]: return True return False def update_code_privileged_users_list(): metasmoke.Metasmoke.update_code_privileged_users_list() _dump_pickle("codePrivileges.p", GlobalVars.code_privileged_users) def is_code_privileged(site, user_id):
64
64
73
10
54
mehrdad-shokri/SmokeDetector
datahandling.py
Python
is_code_privileged
is_code_privileged
185
193
185
185
202fced43052cfe571ccc46b1edefd763ab22389
bigcode/the-stack
train
d115751e417ee17de3d4eb52
train
function
def add_or_update_api_data(site): if site in GlobalVars.api_calls_per_site: GlobalVars.api_calls_per_site[site] += 1 else: GlobalVars.api_calls_per_site[site] = 1 _dump_pickle("apiCalls.pickle", GlobalVars.api_calls_per_site)
def add_or_update_api_data(site):
if site in GlobalVars.api_calls_per_site: GlobalVars.api_calls_per_site[site] += 1 else: GlobalVars.api_calls_per_site[site] = 1 _dump_pickle("apiCalls.pickle", GlobalVars.api_calls_per_site)
.post_site_id_to_question[post_site_id] = question_id def get_post_site_id_link(post_site_id): if post_site_id in GlobalVars.post_site_id_to_question: return GlobalVars.post_site_id_to_question[post_site_id] return None def add_or_update_api_data(site):
64
64
67
8
55
mehrdad-shokri/SmokeDetector
datahandling.py
Python
add_or_update_api_data
add_or_update_api_data
325
330
325
325
d705178fa3dac413c2490653bbbc65c5401557b3
bigcode/the-stack
train
c390778dff01120e3d2d4528
train
function
def check_site_and_get_full_name(site): if len(GlobalVars.se_sites) == 0: refreshed, msg = refresh_sites() if not refreshed: return False, "Could not fetch sites: " + msg for item in GlobalVars.se_sites: full_name = regex.sub(r'https?://', '', item['site_url']) short_...
def check_site_and_get_full_name(site):
if len(GlobalVars.se_sites) == 0: refreshed, msg = refresh_sites() if not refreshed: return False, "Could not fetch sites: " + msg for item in GlobalVars.se_sites: full_name = regex.sub(r'https?://', '', item['site_url']) short_name = item["api_site_parameter"] ...
data: return False, "`has_more` not in JSON data" GlobalVars.se_sites.extend(data["items"]) has_more = data["has_more"] page += 1 return True, "OK" # noinspection PyMissingTypeHints def check_site_and_get_full_name(site):
64
64
115
9
54
mehrdad-shokri/SmokeDetector
datahandling.py
Python
check_site_and_get_full_name
check_site_and_get_full_name
419
429
419
419
d0afbf53c10b2634c0e66ba5f786843dc409d6fe
bigcode/the-stack
train
2e128807881a5b9537e65630
train
class
@ENCODERS.register_module() class SAREncoder(BaseEncoder): """Implementation of encoder module in `SAR. <https://arxiv.org/abs/1811.00751>`_ Args: enc_bi_rnn (bool): If True, use bidirectional RNN in encoder. enc_do_rnn (float): Dropout probability of RNN layer in encoder. enc_gru ...
@ENCODERS.register_module() class SAREncoder(BaseEncoder):
"""Implementation of encoder module in `SAR. <https://arxiv.org/abs/1811.00751>`_ Args: enc_bi_rnn (bool): If True, use bidirectional RNN in encoder. enc_do_rnn (float): Dropout probability of RNN layer in encoder. enc_gru (bool): If True, use GRU, else LSTM in encoder. d_m...
# Copyright (c) OpenMMLab. All rights reserved. import math import torch import torch.nn as nn import torch.nn.functional as F import mmocr.utils as utils from mmocr.models.builder import ENCODERS from .base_encoder import BaseEncoder @ENCODERS.register_module() class SAREncoder(BaseEncoder):
73
243
810
15
57
constanreedjohn/mmocr
mmocr/models/textrecog/encoders/sar_encoder.py
Python
SAREncoder
SAREncoder
13
101
13
14
86676049197451f27ca6ea4afc8f7e2ce939834f
bigcode/the-stack
train
9b3a188a4c870c3f5c39d684
train
class
class BenchmarkAssessment(ABC): """Base class describing what an assessment can do. Parameters ---------- task_num : int Number of experiment the assessment ask to run the corresponding task kwargs : dict Configurable parameters of the assessment, a particular assessment implem...
class BenchmarkAssessment(ABC):
"""Base class describing what an assessment can do. Parameters ---------- task_num : int Number of experiment the assessment ask to run the corresponding task kwargs : dict Configurable parameters of the assessment, a particular assessment implementation can have its own parame...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Base definition of Assessment ============================== """ from abc import ABC, abstractmethod from orion.core.utils import GenericFactory class BenchmarkAssessment(ABC):
46
114
383
6
39
satyaog/orion
src/orion/benchmark/assessment/base.py
Python
BenchmarkAssessment
BenchmarkAssessment
13
67
13
13
380e3aef9f162526dc60276e496ca3d1e755258d
bigcode/the-stack
train