code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
def trace(paths, destination):
"""
Traces path from destination to origin.
Input:
paths; dictionary
Return:
List containing tuples of x-, y-, z-coordinates.
"""
coordinates = destination
... | code/helpers/helpers.py | from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
def trace(paths, destination):
"""
Traces path from destination to origin.
Input:
paths; dictionary
Return:
List containing tuples of x-, y-, z-coordinates.
"""
coordinates = destination
... | 0.859531 | 0.77223 |
import torch
import os
import sys
import torch.nn as nn
from MWCNN import WCNN,IWCNN
import torch.nn.functional as F
def init_weights(m):
if type(m) == nn.Conv2d:
nn.init.xavier_uniform_(m.weight)
m.bias.data.fill_(0.01)
class SimpleCNN(torch.nn.Module):
#Our batch shape for input x is (... | project/models/MWU_CNN.py | import torch
import os
import sys
import torch.nn as nn
from MWCNN import WCNN,IWCNN
import torch.nn.functional as F
def init_weights(m):
if type(m) == nn.Conv2d:
nn.init.xavier_uniform_(m.weight)
m.bias.data.fill_(0.01)
class SimpleCNN(torch.nn.Module):
#Our batch shape for input x is (... | 0.803521 | 0.499756 |
"""Setup dot py."""
from __future__ import absolute_import, print_function
import zipfile
from glob import glob
from pathlib import Path
from os.path import basename, dirname, join, splitext
from setuptools import find_packages, setup
def read(*names, **kwargs):
"""Read description files."""
path = join(dirna... | setup.py | """Setup dot py."""
from __future__ import absolute_import, print_function
import zipfile
from glob import glob
from pathlib import Path
from os.path import basename, dirname, join, splitext
from setuptools import find_packages, setup
def read(*names, **kwargs):
"""Read description files."""
path = join(dirna... | 0.745954 | 0.183301 |
import torch
import warnings
import time
from dataset.fake_human.melanoma_fake_human_dataset import MelanomaFakeHumanDataset
from support import cprint, Color
from neural_network.convolutional_melanoma_neural_network import ConvolutionalMelanomaNeuralNetwork
warnings.filterwarnings("ignore", category=UserWarning)
#... | src/train.py | import torch
import warnings
import time
from dataset.fake_human.melanoma_fake_human_dataset import MelanomaFakeHumanDataset
from support import cprint, Color
from neural_network.convolutional_melanoma_neural_network import ConvolutionalMelanomaNeuralNetwork
warnings.filterwarnings("ignore", category=UserWarning)
#... | 0.331769 | 0.244138 |
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_cond... | bot.py | from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import logging
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_cond... | 0.17989 | 0.050098 |
import pandas as pd
import config
def generate_quality_df():
"""
generate dataframe for training and evaluating image quality model : only deepdr dataset
(use original train for train-valid spilit, use original valid as test --> so that can evaluate with test)
save : ./output/q_traindf.csv and ./output... | data_wrangling/wrangling.py | import pandas as pd
import config
def generate_quality_df():
"""
generate dataframe for training and evaluating image quality model : only deepdr dataset
(use original train for train-valid spilit, use original valid as test --> so that can evaluate with test)
save : ./output/q_traindf.csv and ./output... | 0.295738 | 0.424352 |
from collections import namedtuple
from typing import List
from django.views.generic import TemplateView, View
from django.http import HttpResponse
from braces.views import LoginRequiredMixin, GroupRequiredMixin
from poetry.apps.corpus.models import Poem, MarkupVersion
from rupo.main.markup import Markup
def get_ac... | poetry/apps/corpus/views/comparison_view.py | from collections import namedtuple
from typing import List
from django.views.generic import TemplateView, View
from django.http import HttpResponse
from braces.views import LoginRequiredMixin, GroupRequiredMixin
from poetry.apps.corpus.models import Poem, MarkupVersion
from rupo.main.markup import Markup
def get_ac... | 0.755997 | 0.430447 |
import logging
import math
from typing import Tuple, Dict
import numpy as np
from jgtextrank.utility import MultiprocPool
_logger = logging.getLogger("jgtextrank.metrics")
__author__ = '<NAME> <<EMAIL>>'
__all__ = ["_get_max_score", "_get_average_score", "_get_sum_score", "_term_size_normalize",
"_log_... | jgtextrank/metrics.py |
import logging
import math
from typing import Tuple, Dict
import numpy as np
from jgtextrank.utility import MultiprocPool
_logger = logging.getLogger("jgtextrank.metrics")
__author__ = '<NAME> <<EMAIL>>'
__all__ = ["_get_max_score", "_get_average_score", "_get_sum_score", "_term_size_normalize",
"_log_... | 0.745028 | 0.460471 |
from unittest import TestCase
from ghia.github import GitHub
from betamax import Betamax
from betamax.cassette import cassette
import os
import pathlib
from ghia.common import GHIA, get_rules
import importlib
import pkg_resources
import click
from ghia.Helpers import Parser
TOKEN_PLACEHOLDER = '<AUTH_TOKEN>'
TOKEN = ... | my_tests/test.py | from unittest import TestCase
from ghia.github import GitHub
from betamax import Betamax
from betamax.cassette import cassette
import os
import pathlib
from ghia.common import GHIA, get_rules
import importlib
import pkg_resources
import click
from ghia.Helpers import Parser
TOKEN_PLACEHOLDER = '<AUTH_TOKEN>'
TOKEN = ... | 0.384334 | 0.233106 |
import logging
import pprint
import werkzeug
import json
from odoo import http
from odoo.http import request
from odoo.http import Response
from odoo.addons.payment.models.payment_acquirer import ValidationError
_logger = logging.getLogger(__name__)
class WompiColController(http.Controller):
@http.route(['/pay... | controllers/main.py | import logging
import pprint
import werkzeug
import json
from odoo import http
from odoo.http import request
from odoo.http import Response
from odoo.addons.payment.models.payment_acquirer import ValidationError
_logger = logging.getLogger(__name__)
class WompiColController(http.Controller):
@http.route(['/pay... | 0.321034 | 0.08617 |
from . import db
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
from . import login_manager
@login_manager.user_loader
def load_user(user_id):
"""
@login_manager.user_loader Passes in a user_id to this function and in r... | app/models.py | from . import db
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import datetime
from . import login_manager
@login_manager.user_loader
def load_user(user_id):
"""
@login_manager.user_loader Passes in a user_id to this function and in r... | 0.618896 | 0.118666 |
import json, datetime
from tests.factories import (NOWSubmissionFactory, NOWApplicationIdentityFactory)
class TestGetApplicationResource:
"""GET /now-submissions/applications/{now_number}/status"""
def test_get_now_application_status_by_now_number_success(self, test_client, db_session,
... | services/core-api/tests/now_submissions/resources/test_application_status_resource.py | import json, datetime
from tests.factories import (NOWSubmissionFactory, NOWApplicationIdentityFactory)
class TestGetApplicationResource:
"""GET /now-submissions/applications/{now_number}/status"""
def test_get_now_application_status_by_now_number_success(self, test_client, db_session,
... | 0.438545 | 0.144934 |
import random
import globals
# Create two concurrent lists representing a split row
# - row is the front end of the row with sec_estimate faredecode_dict
# - row1 is the back end of the row
def simulate_row(epsilon, taxi_id, spd, cp, fr):
row = {}
row1 = {}
# Create row = epsilon, taxi_id, shift, co... | src/simulate_row.py | import random
import globals
# Create two concurrent lists representing a split row
# - row is the front end of the row with sec_estimate faredecode_dict
# - row1 is the back end of the row
def simulate_row(epsilon, taxi_id, spd, cp, fr):
row = {}
row1 = {}
# Create row = epsilon, taxi_id, shift, co... | 0.322526 | 0.572962 |
from kv1_811 import *
from inserter import insert,version_imported,versions_imported,getConnection
from settings.const import *
import urllib2
from lxml import etree
import logging
logger = logging.getLogger("importer")
url_gvb = 'http://pol.gvb.nl/gvbpublicatieinternet/KV1/'
kv1index_gvb = url_gvb+'KV1index.xml'
de... | importers/gvb.py | from kv1_811 import *
from inserter import insert,version_imported,versions_imported,getConnection
from settings.const import *
import urllib2
from lxml import etree
import logging
logger = logging.getLogger("importer")
url_gvb = 'http://pol.gvb.nl/gvbpublicatieinternet/KV1/'
kv1index_gvb = url_gvb+'KV1index.xml'
de... | 0.26923 | 0.107766 |
import xarray as xr
import numpy as np
import quaternion
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from itertools import product
from typing import Optional
from pathlib import Path
class Plotter:
def __init__(self):
pass
def plot(self, result: xr.Dataset, s... | cw/simulation/plotter.py | import xarray as xr
import numpy as np
import quaternion
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from itertools import product
from typing import Optional
from pathlib import Path
class Plotter:
def __init__(self):
pass
def plot(self, result: xr.Dataset, s... | 0.792544 | 0.594845 |
from nmt_adaptation.util import arr2txt, rm_dupl_from_list, text2arr
import re
from os.path import join
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def get_length_sentences_from_file(path_data: dir) -> list:
length_sentences = []
with open(join(path_data, "test.de")) as text:
... | nmt_adaptation/split_testset.py | from nmt_adaptation.util import arr2txt, rm_dupl_from_list, text2arr
import re
from os.path import join
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
def get_length_sentences_from_file(path_data: dir) -> list:
length_sentences = []
with open(join(path_data, "test.de")) as text:
... | 0.318061 | 0.587825 |
from __future__ import division
import ast
class Expression_Parser(ast.NodeVisitor):
"""
Transformer that safely parses an expression, disallowing any complicated
functions or control structures (inline if..else is allowed though).
"""
# Boolean operators
# The AST nodes may have multiple ops ... | expression/parser.py | from __future__ import division
import ast
class Expression_Parser(ast.NodeVisitor):
"""
Transformer that safely parses an expression, disallowing any complicated
functions or control structures (inline if..else is allowed though).
"""
# Boolean operators
# The AST nodes may have multiple ops ... | 0.858511 | 0.843444 |
__authors__ = ['<EMAIL> (<NAME>)',
'<EMAIL> (<NAME>)']
import time
from viewfinder.backend.base import util
from viewfinder.backend.base.testing import async_test
from viewfinder.backend.db.notification import Notification
from viewfinder.backend.db.operation import Operation
from viewfinder.backend.op... | backend/db/test/notification_test.py | __authors__ = ['<EMAIL> (<NAME>)',
'<EMAIL> (<NAME>)']
import time
from viewfinder.backend.base import util
from viewfinder.backend.base.testing import async_test
from viewfinder.backend.db.notification import Notification
from viewfinder.backend.db.operation import Operation
from viewfinder.backend.op... | 0.568176 | 0.156523 |
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import argparse
parser = argparse.ArgumentParser(description='Runs a flight simulation.')
parser.add_argument('--final_mass', type=float, default=0.9, help='The rockets total dry weight without the motor. This value is in kg.')
parser.add_argument(... | sim/falcon1_sim.py | import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import argparse
parser = argparse.ArgumentParser(description='Runs a flight simulation.')
parser.add_argument('--final_mass', type=float, default=0.9, help='The rockets total dry weight without the motor. This value is in kg.')
parser.add_argument(... | 0.740268 | 0.4575 |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'SponsorshipType.display_heading'
db.add_column('sponsors_sponsorshiptype', 'display_heading', self.gf('djang... | sponsors/migrations/0002_auto__add_field_sponsorshiptype_display_heading.py | import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'SponsorshipType.display_heading'
db.add_column('sponsors_sponsorshiptype', 'display_heading', self.gf('djang... | 0.327346 | 0.109277 |
#Date Last Modified: 02-13-2014
#Module: delete.py
#Object: delete requested organization, platform, or sensor from database
#Return:
# Copyright (c) 2015, Gulf of Mexico Coastal and Ocean Observing System
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# mo... | adminForm/delete.py |
#Date Last Modified: 02-13-2014
#Module: delete.py
#Object: delete requested organization, platform, or sensor from database
#Return:
# Copyright (c) 2015, Gulf of Mexico Coastal and Ocean Observing System
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# mo... | 0.403802 | 0.043043 |
import re
from uuid import uuid4
from graphql import graphql
from ..id_type import BaseGlobalIDType, SimpleGlobalIDType, UUIDGlobalIDType
from ..node import Node
from ...types import Int, ObjectType, Schema, String
class TestUUIDGlobalID:
def setup(self):
self.user_list = [
{"id": uuid4(), "... | graphene/relay/tests/test_custom_global_id.py | import re
from uuid import uuid4
from graphql import graphql
from ..id_type import BaseGlobalIDType, SimpleGlobalIDType, UUIDGlobalIDType
from ..node import Node
from ...types import Int, ObjectType, Schema, String
class TestUUIDGlobalID:
def setup(self):
self.user_list = [
{"id": uuid4(), "... | 0.633183 | 0.352536 |
import argparse
import json
import os
import requests
import sys
from subprocess import call
from uuid import uuid4
URL_BASE = "https://api.gdc.cancer.gov/legacy/"
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--platform",
choices=["Illumina Human Methy... | transform/tcga/download_methylation.py | import argparse
import json
import os
import requests
import sys
from subprocess import call
from uuid import uuid4
URL_BASE = "https://api.gdc.cancer.gov/legacy/"
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--platform",
choices=["Illumina Human Methy... | 0.144209 | 0.150684 |
import pytest
import json
import os
from contextlib import contextmanager
from newrelic.api.application import (application_instance as
current_application)
from newrelic.api.background_task import BackgroundTask
from newrelic.core.rules_engine import SegmentCollapseEngine
from newrelic.core.agent import age... | tests/cross_agent/test_transaction_segment_terms.py |
import pytest
import json
import os
from contextlib import contextmanager
from newrelic.api.application import (application_instance as
current_application)
from newrelic.api.background_task import BackgroundTask
from newrelic.core.rules_engine import SegmentCollapseEngine
from newrelic.core.agent import age... | 0.49585 | 0.315393 |
from __future__ import print_function
import torch
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.datasets.utils import download_url
import os
import errno
import numpy as np
import pandas as pd
class CCLE_Dataset(torch.utils.data.Dataset):
"""`CCLE` dataset from paper... | datasets/ccle_dataset.py | from __future__ import print_function
import torch
from torch.utils.data import DataLoader
from torchvision import transforms
from torchvision.datasets.utils import download_url
import os
import errno
import numpy as np
import pandas as pd
class CCLE_Dataset(torch.utils.data.Dataset):
"""`CCLE` dataset from paper... | 0.773045 | 0.641366 |
from __future__ import unicode_literals
import sys
import json
import csv
if sys.version_info[0] < 3:
from backports import csv
from io import open
from io import StringIO
import ads
MANUAL_ADDITION = [
'2019JCAP...10..035H',
'2019arXiv190805276D',
'2019arXiv190104454S',
'2018JCAP...11..009D',
... | docs/_data/_generate_publications_csv.py | from __future__ import unicode_literals
import sys
import json
import csv
if sys.version_info[0] < 3:
from backports import csv
from io import open
from io import StringIO
import ads
MANUAL_ADDITION = [
'2019JCAP...10..035H',
'2019arXiv190805276D',
'2019arXiv190104454S',
'2018JCAP...11..009D',
... | 0.242026 | 0.080755 |
import os
import argparse
import warnings
from itertools import chain
import glob
from collections import defaultdict
import numpy as np
import h5py
def _check_pathes(pathes, strict=True):
filtered = []
for path in pathes:
if h5py.is_hdf5(path):
filtered.append(path)
else:
... | macro/merge-hdf5.py | import os
import argparse
import warnings
from itertools import chain
import glob
from collections import defaultdict
import numpy as np
import h5py
def _check_pathes(pathes, strict=True):
filtered = []
for path in pathes:
if h5py.is_hdf5(path):
filtered.append(path)
else:
... | 0.427994 | 0.14069 |
import time
# bin packing problem
class Shelf(object):
"""
Single shelf object for items that keeps a running sum.
"""
def __init__(self, W):
self.items = []
self.sum = 0
self.width = W
def append(self, item):
self.items.append(item)
self.sum += item
... | flask_citibike/bin_packing.py | import time
# bin packing problem
class Shelf(object):
"""
Single shelf object for items that keeps a running sum.
"""
def __init__(self, W):
self.items = []
self.sum = 0
self.width = W
def append(self, item):
self.items.append(item)
self.sum += item
... | 0.610337 | 0.353875 |
import sys
if(len(sys.argv)!=2):
print("usage: python "+sys.argv[0]+" <integer greater than 0 and less than 10^52>")
sys.exit()
num=int(sys.argv[1])
if(num<=0 or num>=(10**52)):
print("usage: python "+sys.argv[0]+" <integer greater than 0 and less than 10^52>")
sys.exit()
out=""
def il(numb... | sino-koreanNums.py | import sys
if(len(sys.argv)!=2):
print("usage: python "+sys.argv[0]+" <integer greater than 0 and less than 10^52>")
sys.exit()
num=int(sys.argv[1])
if(num<=0 or num>=(10**52)):
print("usage: python "+sys.argv[0]+" <integer greater than 0 and less than 10^52>")
sys.exit()
out=""
def il(numb... | 0.025945 | 0.149128 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | clients/PyLagoon/PyLagoon/postgresql.py |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under th... | 0.874305 | 0.25972 |
class GeometryData:
""" Class which holds the geometry data of a ObjId
"""
def __init__(self, subdetid = 0, discriminator = ()):
self.subdetid = subdetid
self.discriminator = discriminator
# ObjId names from Alignment/CommonAlignment/interface/StructureType.h
data = {-1: GeometryData(),... | Alignment/MillePedeAlignmentAlgorithm/python/mpsvalidate/geometrydata.py |
class GeometryData:
""" Class which holds the geometry data of a ObjId
"""
def __init__(self, subdetid = 0, discriminator = ()):
self.subdetid = subdetid
self.discriminator = discriminator
# ObjId names from Alignment/CommonAlignment/interface/StructureType.h
data = {-1: GeometryData(),... | 0.781205 | 0.47859 |
from django.http import HttpResponse, JsonResponse
from polls.models import Recommendation
from django.template import loader
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
import json
from django.db import connection
from django.conf import settings
from django.views.generic i... | webapp/polls/views.py | from django.http import HttpResponse, JsonResponse
from polls.models import Recommendation
from django.template import loader
from django.views.decorators.csrf import csrf_exempt
from django.core import serializers
import json
from django.db import connection
from django.conf import settings
from django.views.generic i... | 0.462959 | 0.086131 |
import tensorflow as tf
class ShuffleNetV2:
def __init__(self, complexity=2, num_classes=10):
self.output_classes = num_classes
self.complexity = complexity
if self.complexity == 0.5:
self.out_filters = [48, 96, 192]
elif self.complexity == 1:
self.out_filt... | models/shufflenet_v2.py | import tensorflow as tf
class ShuffleNetV2:
def __init__(self, complexity=2, num_classes=10):
self.output_classes = num_classes
self.complexity = complexity
if self.complexity == 0.5:
self.out_filters = [48, 96, 192]
elif self.complexity == 1:
self.out_filt... | 0.915498 | 0.472744 |
import io
import pytest
import sys
import sudoku.grid as grid
class TestGrid:
def test_grid(self):
g = grid.Grid()
assert g.grid_type == "grid"
def test_grid_add_row(self):
g = grid.Grid()
row = [7, 0, 9, 4, 0, 2, 3, 8, 0]
g.add_row(row)
g.add_row(row)
... | tests/test_grid.py | import io
import pytest
import sys
import sudoku.grid as grid
class TestGrid:
def test_grid(self):
g = grid.Grid()
assert g.grid_type == "grid"
def test_grid_add_row(self):
g = grid.Grid()
row = [7, 0, 9, 4, 0, 2, 3, 8, 0]
g.add_row(row)
g.add_row(row)
... | 0.422147 | 0.786131 |
from __future__ import print_function
import argparse
import math
import os
import struct
import sys
from csiphash import siphash24
from cskipdict import SkipDict
class Element(object):
__slots__ = ('value', 'count')
def __init__(self, value):
self.value = value
self.count = 1
class Reco... | recordinality.py |
from __future__ import print_function
import argparse
import math
import os
import struct
import sys
from csiphash import siphash24
from cskipdict import SkipDict
class Element(object):
__slots__ = ('value', 'count')
def __init__(self, value):
self.value = value
self.count = 1
class Reco... | 0.564339 | 0.176672 |
import numpy as np
import soundfile as sf
from metprint import LogType, Logger, FHFormatter
from stegstash.lsb import LSB
exts = ["wav"]
def extNotLossless(fileName):
""" Output the file extension not lossless error """
Logger(FHFormatter()).logPrint(
"File extension is not lossless: " + fileName + "! Must be " +... | stegstash/soundlsb.py | import numpy as np
import soundfile as sf
from metprint import LogType, Logger, FHFormatter
from stegstash.lsb import LSB
exts = ["wav"]
def extNotLossless(fileName):
""" Output the file extension not lossless error """
Logger(FHFormatter()).logPrint(
"File extension is not lossless: " + fileName + "! Must be " +... | 0.817101 | 0.42173 |
import logging
import crochet
import requests
import fido
from yelp_bytes import to_bytes
from bravado_core.response import IncomingResponse
from bravado.http_client import HttpClient
from bravado.http_future import FutureAdapter
from bravado.http_future import HttpFuture
log = logging.getLogger(__name__)
class Fi... | bravado/fido_client.py | import logging
import crochet
import requests
import fido
from yelp_bytes import to_bytes
from bravado_core.response import IncomingResponse
from bravado.http_client import HttpClient
from bravado.http_future import FutureAdapter
from bravado.http_future import HttpFuture
log = logging.getLogger(__name__)
class Fi... | 0.560974 | 0.120103 |
from scipy.stats import shapiro
import scipy.stats as stats
import numpy as np
import pandas as pd
import yaml
from utils import *
# A/B Testing Function - Quick Solution
def perform_ab_test(dataframe, group, target, group_a, group_b):
# Split A/B
groupA = dataframe[dataframe[group] == group_a][target]
... | src/perform_abtest.py | from scipy.stats import shapiro
import scipy.stats as stats
import numpy as np
import pandas as pd
import yaml
from utils import *
# A/B Testing Function - Quick Solution
def perform_ab_test(dataframe, group, target, group_a, group_b):
# Split A/B
groupA = dataframe[dataframe[group] == group_a][target]
... | 0.408041 | 0.407805 |
import argparse
import os
import sys
import requests
# constants
API_URL = 'https://api.github.com'
class PullRequest:
"""Pull Request class"""
def __init__(self,
head_owner, head, head_token,
base_owner, repo, base, base_token):
self.head_owner = head_owner
... | .github/workflows/action-helper/python/utils.py | {r.json()}
# Assume upstream is {self.base_owner}/{self.base_repo} remote
git fetch upstream {self.head} {self.base}
git checkout -b fix-auto-merge-conflict-{number} upstream/{self.base}
git merge upstream/{self.head}
# Fix any merge conflicts caused by this merge
git commit -am "Merge {self.head} into {self.base}"
gi... | 0.488771 | 0.17441 |
from datetime import datetime
import unittest
import mox
from stacktach.models import RawData, GlanceRawData, GenericRawData
from stacktach.models import ImageDeletes, InstanceExists, ImageExists
from tests.unit.utils import IMAGE_UUID_1
from stacktach import datetime_to_decimal as dt
from tests.unit import StacktachB... | tests/unit/test_models.py | from datetime import datetime
import unittest
import mox
from stacktach.models import RawData, GlanceRawData, GenericRawData
from stacktach.models import ImageDeletes, InstanceExists, ImageExists
from tests.unit.utils import IMAGE_UUID_1
from stacktach import datetime_to_decimal as dt
from tests.unit import StacktachB... | 0.658418 | 0.207777 |
# Things that won't be done
# - Statics won't be name mangled
# - __LINE__ and __FILE__ won't work well
import sys
import pathlib
import shutil
# note: all files have to be in same directory
def add_file(imports, file_name, out_file, header_guard):
if file_name in imports: return
if not file_name.endswith(".inc... | ssc.py |
# Things that won't be done
# - Statics won't be name mangled
# - __LINE__ and __FILE__ won't work well
import sys
import pathlib
import shutil
# note: all files have to be in same directory
def add_file(imports, file_name, out_file, header_guard):
if file_name in imports: return
if not file_name.endswith(".inc... | 0.141845 | 0.05634 |
import csv
import logging
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Tuple, Union
import pandas as pd
from pulp import LpMaximize, LpProblem, LpVariable, lpSum, PULP_CBC_CMD
from dfs import constraints
from dfs import data_frame_utils, pulp_utils
from dfs import file_utils
from dfs.except... | dfs/optimize.py | import csv
import logging
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Tuple, Union
import pandas as pd
from pulp import LpMaximize, LpProblem, LpVariable, lpSum, PULP_CBC_CMD
from dfs import constraints
from dfs import data_frame_utils, pulp_utils
from dfs import file_utils
from dfs.except... | 0.875348 | 0.198996 |
import os
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from ..conftest import CONFIG
from ..conftest import read_json
from ..conftest import TESTING_CONFIG_DIR
from ..conftest import U... | src/dvtests/testing/default/system/test_datasets.py | import os
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from ..conftest import CONFIG
from ..conftest import read_json
from ..conftest import TESTING_CONFIG_DIR
from ..conftest import U... | 0.42919 | 0.272076 |
from contextlib import contextmanager
from typing import Dict, List
from docker.models.containers import Container
from loguru import logger
from pydantic import BaseModel as Base
from .circuit import OnionCircuit
from .client import ContainerBase, ContainerOptions
from .mount import MountFile, MountPoint
HAPROXY_I... | requests_whaor/balancer.py |
from contextlib import contextmanager
from typing import Dict, List
from docker.models.containers import Container
from loguru import logger
from pydantic import BaseModel as Base
from .circuit import OnionCircuit
from .client import ContainerBase, ContainerOptions
from .mount import MountFile, MountPoint
HAPROXY_I... | 0.922124 | 0.241389 |
import enum
class SubmitStatus(object):
# TODO(actics): make this abstract (now it timus only support)
_processing_verdicts = ['Compiling', 'Running', 'Waiting']
_running_verdict = 'Running'
_accepted_verdict = 'Accepted'
_failed_verdict = 'Failed'
_compilation_error_info = 'Compilation error'... | acm_cli/acm_api/structs.py | import enum
class SubmitStatus(object):
# TODO(actics): make this abstract (now it timus only support)
_processing_verdicts = ['Compiling', 'Running', 'Waiting']
_running_verdict = 'Running'
_accepted_verdict = 'Accepted'
_failed_verdict = 'Failed'
_compilation_error_info = 'Compilation error'... | 0.339828 | 0.130979 |
from pathlib import Path
import requests
import json
import csv
class Elasticsearch:
def __init__(self, index):
self.cluster_health_url = "http://elasticsearch:9200/_cluster/health"
self.index_template_url = "http://elasticsearch:9200/_index_template/template_1"
self.index_url = f"http://el... | backend/utils/elasticsearch.py | from pathlib import Path
import requests
import json
import csv
class Elasticsearch:
def __init__(self, index):
self.cluster_health_url = "http://elasticsearch:9200/_cluster/health"
self.index_template_url = "http://elasticsearch:9200/_index_template/template_1"
self.index_url = f"http://el... | 0.308711 | 0.232272 |
import os
import numpy as np
from math import sqrt
from scipy import stats
from torch_geometric.data import InMemoryDataset, DataLoader
from torch_geometric.data import Dataset
from torch_geometric import data as DATA
import torch
import pdb
class TrainDataset(Dataset):
def __init__(self, root='./', train_x1_index... | apps/drug_target_interaction/hybriddta/pairwise/GraphDTA/utils.py | import os
import numpy as np
from math import sqrt
from scipy import stats
from torch_geometric.data import InMemoryDataset, DataLoader
from torch_geometric.data import Dataset
from torch_geometric import data as DATA
import torch
import pdb
class TrainDataset(Dataset):
def __init__(self, root='./', train_x1_index... | 0.602179 | 0.559711 |
import unittest
import inventoryanalytics.lotsizing.deterministic.constant.eoq as eoq
import numpy as np
class TestEOQ(unittest.TestCase):
def setUp(self):
instance = {"K": 3.2, "h": 0.24, "d": 2400, "v": 0.4}
self.eoq = eoq.eoq(**instance)
def tearDown(self):
pass
def test_eoq(s... | inventoryanalytics/lotsizing/deterministic/constant/test/eoq_test.py | import unittest
import inventoryanalytics.lotsizing.deterministic.constant.eoq as eoq
import numpy as np
class TestEOQ(unittest.TestCase):
def setUp(self):
instance = {"K": 3.2, "h": 0.24, "d": 2400, "v": 0.4}
self.eoq = eoq.eoq(**instance)
def tearDown(self):
pass
def test_eoq(s... | 0.457137 | 0.760951 |
from matchmaker.losses.lambdarank import *
from matchmaker.losses.listnet import *
from matchmaker.losses.ranknet import *
from matchmaker.losses.msmargin import *
from matchmaker.losses.teacher_kldiv_list import *
from matchmaker.losses.teacher_kldiv_pointwise import *
from matchmaker.losses.teacher_mse_pointwise impo... | matchmaker/losses/all.py | from matchmaker.losses.lambdarank import *
from matchmaker.losses.listnet import *
from matchmaker.losses.ranknet import *
from matchmaker.losses.msmargin import *
from matchmaker.losses.teacher_kldiv_list import *
from matchmaker.losses.teacher_kldiv_pointwise import *
from matchmaker.losses.teacher_mse_pointwise impo... | 0.564098 | 0.181934 |
import os
import tempfile
from copy import copy
import numpy as np
import rasterio as rio
from elapid import utils
# set the test raster data paths
directory_path, script_path = os.path.split(os.path.abspath(__file__))
data_path = os.path.join(directory_path, "data")
raster_1b = os.path.join(data_path, "test-raster... | tests/test_utils.py |
import os
import tempfile
from copy import copy
import numpy as np
import rasterio as rio
from elapid import utils
# set the test raster data paths
directory_path, script_path = os.path.split(os.path.abspath(__file__))
data_path = os.path.join(directory_path, "data")
raster_1b = os.path.join(data_path, "test-raster... | 0.530236 | 0.607285 |
import logging
import sys
from copy import deepcopy
if sys.version_info < (3, 3):
from collections import Mapping
else:
from collections.abc import Mapping
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__all__ = ["get_data_lines"]
def copy(obj):
def copy(self):
"""
Copy self to a new obj... | attmap/helpers.py |
import logging
import sys
from copy import deepcopy
if sys.version_info < (3, 3):
from collections import Mapping
else:
from collections.abc import Mapping
__author__ = "<NAME>"
__email__ = "<EMAIL>"
__all__ = ["get_data_lines"]
def copy(obj):
def copy(self):
"""
Copy self to a new obj... | 0.514888 | 0.263173 |
from pg2avro import get_avro_schema, ColumnMapping, get_avro_row_dict
from sqlalchemy import (
Column,
BIGINT,
BOOLEAN,
CHAR,
DATE,
INTEGER,
NUMERIC,
SMALLINT,
TEXT,
VARCHAR,
TIME,
)
from sqlalchemy.dialects.postgresql import (
ARRAY,
INTERVAL,
TIMESTAMP,
ENUM... | tests/test_schema_types.py | from pg2avro import get_avro_schema, ColumnMapping, get_avro_row_dict
from sqlalchemy import (
Column,
BIGINT,
BOOLEAN,
CHAR,
DATE,
INTEGER,
NUMERIC,
SMALLINT,
TEXT,
VARCHAR,
TIME,
)
from sqlalchemy.dialects.postgresql import (
ARRAY,
INTERVAL,
TIMESTAMP,
ENUM... | 0.606615 | 0.319259 |
import sys, os, shutil, subprocess, pathlib
import json, re
IDENTIFIER_PAT = '[a-zA-Z]\\w*'
gconf = None
pconf = None
printe = lambda *args : print(*args, file=sys.stderr)
def loadgconf() :
global gconf
gconf = load_meta(getroot() + "/config.json")
pgconf:dict = load_meta(getroot() + "/private/config.jso... | bin/common.py | import sys, os, shutil, subprocess, pathlib
import json, re
IDENTIFIER_PAT = '[a-zA-Z]\\w*'
gconf = None
pconf = None
printe = lambda *args : print(*args, file=sys.stderr)
def loadgconf() :
global gconf
gconf = load_meta(getroot() + "/config.json")
pgconf:dict = load_meta(getroot() + "/private/config.jso... | 0.105879 | 0.076546 |
import numpy as np
from scipy import signal
from nn.module import Module
class Linear(Module):
"""
A module which applies a linear transformation
A common name is fully-connected layer, InnerProductLayer in caffe.
The module should work with 2D input of shape (n_samples, n_feature).
"""
de... | nn/layers.py | import numpy as np
from scipy import signal
from nn.module import Module
class Linear(Module):
"""
A module which applies a linear transformation
A common name is fully-connected layer, InnerProductLayer in caffe.
The module should work with 2D input of shape (n_samples, n_feature).
"""
de... | 0.916433 | 0.448185 |
import time
import pandas as pd
from pandas.testing import assert_frame_equal
from simplepipeline.pipeline import Pipeline
from simplepipeline.map.parallel import par_map, par_map_unpack
from simplepipeline.map.sequential import seq_map, seq_map_unpack
from simplepipeline.task import task, filter_task, set_pipeline, ... | tests/test_all.py | import time
import pandas as pd
from pandas.testing import assert_frame_equal
from simplepipeline.pipeline import Pipeline
from simplepipeline.map.parallel import par_map, par_map_unpack
from simplepipeline.map.sequential import seq_map, seq_map_unpack
from simplepipeline.task import task, filter_task, set_pipeline, ... | 0.445047 | 0.632843 |
import copy
import functools
import getpass
import os
from json import JSONDecodeError
from multiprocessing.pool import ThreadPool
from random import shuffle
from typing import Dict, List
import uuid
from requests import Response
from tqdm import tqdm
from vortexasdk.abstract_client import AbstractVortexaClient
from ... | vortexasdk/client.py | import copy
import functools
import getpass
import os
from json import JSONDecodeError
from multiprocessing.pool import ThreadPool
from random import shuffle
from typing import Dict, List
import uuid
from requests import Response
from tqdm import tqdm
from vortexasdk.abstract_client import AbstractVortexaClient
from ... | 0.804252 | 0.12166 |
from flask_jwt_extended import jwt_required, get_jwt_identity
from flask_restful import Resource
from flask import request, jsonify
from database.db import mongo
from resources.students.student_proposal import curr_user_is_student
class EditProposal(Resource):
@jwt_required
def post(self):
current_us... | app/resources/students/edit_proposal.py | from flask_jwt_extended import jwt_required, get_jwt_identity
from flask_restful import Resource
from flask import request, jsonify
from database.db import mongo
from resources.students.student_proposal import curr_user_is_student
class EditProposal(Resource):
@jwt_required
def post(self):
current_us... | 0.402157 | 0.05301 |
from otree.api import Currency as c, currency_range
from ._builtin import Page, WaitPage
from .models import Constants
class Offer(Page):
form_model = 'group'
form_fields = ['offer']
def is_displayed(self):
if self.participant.vars['is_finished']:
return False
else:
... | example_apps/rubinstein/pages.py | from otree.api import Currency as c, currency_range
from ._builtin import Page, WaitPage
from .models import Constants
class Offer(Page):
form_model = 'group'
form_fields = ['offer']
def is_displayed(self):
if self.participant.vars['is_finished']:
return False
else:
... | 0.249173 | 0.13084 |
from flask import Flask, flash, redirect, render_template, request, session, abort, url_for, escape, jsonify
import models as dbHandler
import os
import qrcode
import base64
import io
import random
app = Flask(__name__)
@app.route('/', methods =['GET','POST'])
def index():
return render_template('index.html')
@a... | main.py | from flask import Flask, flash, redirect, render_template, request, session, abort, url_for, escape, jsonify
import models as dbHandler
import os
import qrcode
import base64
import io
import random
app = Flask(__name__)
@app.route('/', methods =['GET','POST'])
def index():
return render_template('index.html')
@a... | 0.105596 | 0.058804 |
from __future__ import absolute_import
from __future__ import print_function
from .offset_manager import OffsetWriter
from kafka_utils.util.client import KafkaToolClient
from kafka_utils.util.offsets import nullify_offsets
from kafka_utils.util.offsets import set_consumer_offsets
from kafka_utils.util.zookeeper import... | kafka_utils/kafka_consumer_manager/commands/delete_group.py | from __future__ import absolute_import
from __future__ import print_function
from .offset_manager import OffsetWriter
from kafka_utils.util.client import KafkaToolClient
from kafka_utils.util.offsets import nullify_offsets
from kafka_utils.util.offsets import set_consumer_offsets
from kafka_utils.util.zookeeper import... | 0.701815 | 0.073297 |
from gcsfs.utils import ChecksumError
from gcsfs.checkers import Crc32cChecker, MD5Checker, SizeChecker, crcmod
from hashlib import md5
import base64
import pytest
def google_response_from_data(expected_data: bytes, actual_data=None):
actual_data = actual_data or expected_data
checksum = md5(actual_data)
... | gcsfs/tests/test_checkers.py | from gcsfs.utils import ChecksumError
from gcsfs.checkers import Crc32cChecker, MD5Checker, SizeChecker, crcmod
from hashlib import md5
import base64
import pytest
def google_response_from_data(expected_data: bytes, actual_data=None):
actual_data = actual_data or expected_data
checksum = md5(actual_data)
... | 0.557123 | 0.320968 |
from Level.Region import Region
import json
import os
class Data:
def __init__(self, level, number = 0):
self.regions = []
self.regionsGrid = []
self.level = level
self.number = number
self.deleteCount = 0
files = os.listdir(level.folder + "/region" + str(number))
... | Level/Data.py | from Level.Region import Region
import json
import os
class Data:
def __init__(self, level, number = 0):
self.regions = []
self.regionsGrid = []
self.level = level
self.number = number
self.deleteCount = 0
files = os.listdir(level.folder + "/region" + str(number))
... | 0.376279 | 0.215021 |
from placeholder import *
from loss import *
from optimizer import *
from layer import *
from tensor import *
from util import *
import numpy as np
from copy import copy
class Model(object):
"""
Grahp model class
"""
def __init__(self, input_placeholder, output_placeholder):
"""
初始化模型参数... | model.py | from placeholder import *
from loss import *
from optimizer import *
from layer import *
from tensor import *
from util import *
import numpy as np
from copy import copy
class Model(object):
"""
Grahp model class
"""
def __init__(self, input_placeholder, output_placeholder):
"""
初始化模型参数... | 0.360377 | 0.257967 |
import argparse
import json
import logging
import os
import sys
from conda_recipe_tools.git import FeedStock, NotFeedstockRepo
from conda_recipe_tools.util import get_feedstock_dirs
LOG_FORMAT = '%(asctime)s - %(levelname)s : %(message)s'
def read_last_commits(checkfile):
""" Read in the latest commits from a ... | conda_recipe_tools/cli/find_changed_feedstocks.py |
import argparse
import json
import logging
import os
import sys
from conda_recipe_tools.git import FeedStock, NotFeedstockRepo
from conda_recipe_tools.util import get_feedstock_dirs
LOG_FORMAT = '%(asctime)s - %(levelname)s : %(message)s'
def read_last_commits(checkfile):
""" Read in the latest commits from a ... | 0.319227 | 0.07989 |
import json
import jieba
from django.db.models import Q
from algo.model.model import CustomModel
from algo.model.model_config import BertBilstmCrfConfig
from keras.models import Model
from keras.layers import Bidirectional, LSTM, Dense, Dropout
from keras.optimizers import Adam
from keras_contrib.layers import CRF
im... | backend/algo/model/bert_bilstm_crf.py | import json
import jieba
from django.db.models import Q
from algo.model.model import CustomModel
from algo.model.model_config import BertBilstmCrfConfig
from keras.models import Model
from keras.layers import Bidirectional, LSTM, Dense, Dropout
from keras.optimizers import Adam
from keras_contrib.layers import CRF
im... | 0.398758 | 0.187374 |
import click
import plistlib
import subprocess
import os
"""
MIT License
Copyright (c) 2019 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, includ... | cider.py | import click
import plistlib
import subprocess
import os
"""
MIT License
Copyright (c) 2019 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, includ... | 0.464659 | 0.116814 |
from .base import API
from .utils import lambda_method, make_data
class NotificationAPI(API):
@lambda_method
def create_email_provider(self, name, description, url, port, email, password):
import cloud.notification.create_email_provider as method
params = {
'name': name,
... | aws_interface/core/api/notification.py | from .base import API
from .utils import lambda_method, make_data
class NotificationAPI(API):
@lambda_method
def create_email_provider(self, name, description, url, port, email, password):
import cloud.notification.create_email_provider as method
params = {
'name': name,
... | 0.476336 | 0.063279 |
from shellish import autocommand
import unittest
class PositionalTests(unittest.TestCase):
def test_one_pos(self):
@autocommand
def f(one):
self.assertEqual(one, 'ONE')
f(argv='ONE')
with self.assertRaises(SystemExit):
f(argv='')
def test_2_and_3_pos(s... | test/autocommand.py | from shellish import autocommand
import unittest
class PositionalTests(unittest.TestCase):
def test_one_pos(self):
@autocommand
def f(one):
self.assertEqual(one, 'ONE')
f(argv='ONE')
with self.assertRaises(SystemExit):
f(argv='')
def test_2_and_3_pos(s... | 0.520984 | 0.495911 |
import os
import pickle
from typing import Callable, Optional, TypeVar
import gym
from imitation.util import networks, util
from stable_baselines.common import vec_env
import tensorflow as tf
from evaluating_rewards import serialize
from evaluating_rewards.rewards import base
T = TypeVar("T")
V = TypeVar("V")
EnvRe... | src/evaluating_rewards/scripts/regress_utils.py | import os
import pickle
from typing import Callable, Optional, TypeVar
import gym
from imitation.util import networks, util
from stable_baselines.common import vec_env
import tensorflow as tf
from evaluating_rewards import serialize
from evaluating_rewards.rewards import base
T = TypeVar("T")
V = TypeVar("V")
EnvRe... | 0.863305 | 0.175962 |
from azure.cli.testsdk import ScenarioTest, ResourceGroupPreparer, StorageAccountPreparer
from msrestazure.tools import resource_id
class AmsAccountIdentityTests(ScenarioTest):
@ResourceGroupPreparer()
@StorageAccountPreparer(parameter_name='storage_account_for_create')
def test_ams_create_system_identity... | src/azure-cli/azure/cli/command_modules/ams/tests/latest/test_ams_account_identity_scenarios.py |
from azure.cli.testsdk import ScenarioTest, ResourceGroupPreparer, StorageAccountPreparer
from msrestazure.tools import resource_id
class AmsAccountIdentityTests(ScenarioTest):
@ResourceGroupPreparer()
@StorageAccountPreparer(parameter_name='storage_account_for_create')
def test_ams_create_system_identity... | 0.550124 | 0.142053 |
import pytest
import responses
import renamedia.tmdb.client as testee
from renamedia.common.model import MediaType
from renamedia.tmdb.model import TmdbItem
_FIND_URL = ('https://api.themoviedb.org/3/search/multi?api_key=12345'
'&language=en-US&page=1&include_adult=false&query=Title')
_GET_URL = ('https:... | tests/renamedia/tmdb/test_client.py | import pytest
import responses
import renamedia.tmdb.client as testee
from renamedia.common.model import MediaType
from renamedia.tmdb.model import TmdbItem
_FIND_URL = ('https://api.themoviedb.org/3/search/multi?api_key=12345'
'&language=en-US&page=1&include_adult=false&query=Title')
_GET_URL = ('https:... | 0.452052 | 0.258835 |
from __future__ import absolute_import, division, print_function, unicode_literals
import math
from numbers import Integral
import numpy as np
import pickle
import spectral as spy
from ..io.spyfile import SpyFile, TransformedImage
from ..utilities.errors import has_nan, NaNValueError
from .spymath import matrix_sqrt
... | spectral/algorithms/algorithms.py | from __future__ import absolute_import, division, print_function, unicode_literals
import math
from numbers import Integral
import numpy as np
import pickle
import spectral as spy
from ..io.spyfile import SpyFile, TransformedImage
from ..utilities.errors import has_nan, NaNValueError
from .spymath import matrix_sqrt
... | 0.869382 | 0.450359 |
import boto3
from botocore.exceptions import ClientError
import pytest
from websocket_chat import ApiGatewayWebsocket
@pytest.mark.parametrize('error_code', [None, 'TestException'])
def test_create_api(make_stubber, error_code):
apigatewayv2_client = boto3.client('apigatewayv2')
apigatewayv2_stubber = make_s... | python/cross_service/apigateway_websocket_chat/test/test_websocket_chat.py | import boto3
from botocore.exceptions import ClientError
import pytest
from websocket_chat import ApiGatewayWebsocket
@pytest.mark.parametrize('error_code', [None, 'TestException'])
def test_create_api(make_stubber, error_code):
apigatewayv2_client = boto3.client('apigatewayv2')
apigatewayv2_stubber = make_s... | 0.324771 | 0.216146 |
from urllib import request, parse
import time
import random
import hashlib
import json
import requests
def get_ts(): #时间戳 乘以1000 取整
ts = str(int(1000 * time.time()))
return ts
def get_salt(ts):
salt = ts + str(random.randint(0, 10)) # 上面的方法返回值 加上1-10之间的随机数
return salt
def get_sign(words, salt):... | translate2.py | from urllib import request, parse
import time
import random
import hashlib
import json
import requests
def get_ts(): #时间戳 乘以1000 取整
ts = str(int(1000 * time.time()))
return ts
def get_salt(ts):
salt = ts + str(random.randint(0, 10)) # 上面的方法返回值 加上1-10之间的随机数
return salt
def get_sign(words, salt):... | 0.268845 | 0.11158 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='Cohort',
fields... | stucon/migrations/0001_initial.py |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='Cohort',
fields... | 0.557123 | 0.144722 |
import sys
sys.path.append('lib/tweepy')
import boto3
import json
import io
import urllib.request
import tweepy
import datetime
#自作関数
import functions
#Twitterの認証
twitter = json.loads(functions.get_secret())
CK = twitter["TWITTER_CK"]
CS = twitter["TWITTER_CS"]
AT = twitter["TWITTER_AT"]
AS = twitter["TWITTER_AS"]
... | index.py | import sys
sys.path.append('lib/tweepy')
import boto3
import json
import io
import urllib.request
import tweepy
import datetime
#自作関数
import functions
#Twitterの認証
twitter = json.loads(functions.get_secret())
CK = twitter["TWITTER_CK"]
CS = twitter["TWITTER_CS"]
AT = twitter["TWITTER_AT"]
AS = twitter["TWITTER_AS"]
... | 0.16529 | 0.15633 |
import unittest
import spydrnet as sdn
from spydrnet.parsers.edif.parser import EdifParser
from spydrnet import base_dir
import os
import tempfile
import glob
import shutil
class TestEdifTokenizer(unittest.TestCase):
def test_multi_bit_add_out_of_order(self):
definition = sdn.Definition()
cable0 ... | spydrnet/parsers/edif/tests/test_edif_parser.py | import unittest
import spydrnet as sdn
from spydrnet.parsers.edif.parser import EdifParser
from spydrnet import base_dir
import os
import tempfile
import glob
import shutil
class TestEdifTokenizer(unittest.TestCase):
def test_multi_bit_add_out_of_order(self):
definition = sdn.Definition()
cable0 ... | 0.40392 | 0.280789 |
import logging
import argparse
import random
import math
import matplotlib.pyplot as plt
import ast
parser = argparse.ArgumentParser()
parser.add_argument('--number_of_inliers', help="The number of inliers. Default: 200", type=int, default=200)
parser.add_argument('--inliers_noise', help="The noise for the inliers. De... | utilities/create_noisy_circles.py | import logging
import argparse
import random
import math
import matplotlib.pyplot as plt
import ast
parser = argparse.ArgumentParser()
parser.add_argument('--number_of_inliers', help="The number of inliers. Default: 200", type=int, default=200)
parser.add_argument('--inliers_noise', help="The noise for the inliers. De... | 0.481454 | 0.304145 |
import numpy
import scipy.special
import matplotlib.pyplot
import imageio
import glob
# 神经网络类定义
class neuralNetwork:
# 初始化神经网络
def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate):
# 设置每个输入、隐藏、输出层的节点数
self.inodes = inputnodes
self.hnodes = hiddennodes
... | Handwritten_digit_recognition/Handwritten.py | import numpy
import scipy.special
import matplotlib.pyplot
import imageio
import glob
# 神经网络类定义
class neuralNetwork:
# 初始化神经网络
def __init__(self, inputnodes, hiddennodes, outputnodes, learningrate):
# 设置每个输入、隐藏、输出层的节点数
self.inodes = inputnodes
self.hnodes = hiddennodes
... | 0.153137 | 0.40645 |
import os
from setuptools import setup
from subprocess import Popen, PIPE
def git_tag():
try:
cmd = ['git', 'describe', '--tags', '--abbrev=0']
proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
proc.stderr.close()
return proc.stdout.readlines()[0].strip().decode()
except:
ret... | setup.py | import os
from setuptools import setup
from subprocess import Popen, PIPE
def git_tag():
try:
cmd = ['git', 'describe', '--tags', '--abbrev=0']
proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
proc.stderr.close()
return proc.stdout.readlines()[0].strip().decode()
except:
ret... | 0.20466 | 0.08163 |
from model.backbone.mobilenetv2 import MobileNetV2_3feature
import torch
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
class conv_bn_relu(torch.nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, bias=False):
super(conv_bn_relu... | src/model/net.py | from model.backbone.mobilenetv2 import MobileNetV2_3feature
import torch
import numpy as np
import torch.nn.functional as F
import torch.nn as nn
class conv_bn_relu(torch.nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, bias=False):
super(conv_bn_relu... | 0.956166 | 0.416915 |
"""Tests for parsing module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
import textwrap
from absl.testing import absltest as test
import gast
from pyctr.core import parsing
class ParsingTest(test.TestCase):
def test_parse_entity... | core/parsing_test.py | """Tests for parsing module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
import textwrap
from absl.testing import absltest as test
import gast
from pyctr.core import parsing
class ParsingTest(test.TestCase):
def test_parse_entity... | 0.822011 | 0.486636 |
from pathlib import Path
from typing import Dict, List, Union
import einops
import torch
import torch.nn.functional as F
import torchaudio
from torch import Tensor
from torch.utils.data import Dataset, DataLoader
from peach.utils import TokenConverter
class SpeechCommandsDataset(Dataset):
def __init__(
... | kespo/datamodules/speech_commands_datamodule.py | from pathlib import Path
from typing import Dict, List, Union
import einops
import torch
import torch.nn.functional as F
import torchaudio
from torch import Tensor
from torch.utils.data import Dataset, DataLoader
from peach.utils import TokenConverter
class SpeechCommandsDataset(Dataset):
def __init__(
... | 0.745954 | 0.372591 |
import argparse
import csv
from typing import Dict
EXPECTED_RESOLUTIONS = 6
WANTED_RESOLUTIONS = {144, 240, 360, 480, 720, 1080}
WANTED_RESOLUTION_IDS = {160, 133, 134, 135, 136, 137}
OUTPUT_FILE = 'yt8m_data.csv'
HEADER = ['', 'creator', 'duration', 'id', 'labels', 'ladder', 'title', 'views']
parser = argparse.Argu... | YT8M_downloader/cleaner.py |
import argparse
import csv
from typing import Dict
EXPECTED_RESOLUTIONS = 6
WANTED_RESOLUTIONS = {144, 240, 360, 480, 720, 1080}
WANTED_RESOLUTION_IDS = {160, 133, 134, 135, 136, 137}
OUTPUT_FILE = 'yt8m_data.csv'
HEADER = ['', 'creator', 'duration', 'id', 'labels', 'ladder', 'title', 'views']
parser = argparse.Argu... | 0.477311 | 0.174481 |
from nfv_vim.database._database_block_storage_module import database_volume_add # noqa: F401
from nfv_vim.database._database_block_storage_module import database_volume_delete # noqa: F401
from nfv_vim.database._database_block_storage_module import database_volume_get_list # noqa: F401
from nfv_vim.database._databas... | nfv/nfv-vim/nfv_vim/database/__init__.py | from nfv_vim.database._database_block_storage_module import database_volume_add # noqa: F401
from nfv_vim.database._database_block_storage_module import database_volume_delete # noqa: F401
from nfv_vim.database._database_block_storage_module import database_volume_get_list # noqa: F401
from nfv_vim.database._databas... | 0.232484 | 0.030705 |
import gc
import math
import multiprocessing
import tempfile
from importlib.util import find_spec
from os.path import join
from typing import Optional
import lightgbm
import numpy
from lightgbm import Booster, record_evaluation
from aydin.regression.base import RegressorBase
from aydin.regression.gbm_utils.callbacks ... | aydin/regression/lgbm.py | import gc
import math
import multiprocessing
import tempfile
from importlib.util import find_spec
from os.path import join
from typing import Optional
import lightgbm
import numpy
from lightgbm import Booster, record_evaluation
from aydin.regression.base import RegressorBase
from aydin.regression.gbm_utils.callbacks ... | 0.887137 | 0.472197 |
name = "seed"
shortDesc = ""
longDesc = """
"""
autoGenerated=True
entry(
index = 0,
label = "H + H <=> H2",
degeneracy = 0.5,
duplicate = True,
kinetics = Arrhenius(A=(5.45e+10,'cm^3/(mol*s)'), n=0, Ea=(6.276,'kJ/mol'), T0=(1,'K'), Tmin=(278,'K'), Tmax=(372,'K'), comment="""Matched reaction 56 H ... | rmgpy/rmg/test_data/restartTest/seed_no_filters/seed/reactions.py |
name = "seed"
shortDesc = ""
longDesc = """
"""
autoGenerated=True
entry(
index = 0,
label = "H + H <=> H2",
degeneracy = 0.5,
duplicate = True,
kinetics = Arrhenius(A=(5.45e+10,'cm^3/(mol*s)'), n=0, Ea=(6.276,'kJ/mol'), T0=(1,'K'), Tmin=(278,'K'), Tmax=(372,'K'), comment="""Matched reaction 56 H ... | 0.390476 | 0.318267 |
class MinIntHeap(object):
def __init__(self):
self.__capacity = 10
self.__size = 0
self.__items = [0] * self.__capacity
def __get_left_child_index(self, parent_index):
return 2 * parent_index + 1
def __get_right_child_index(self, parent_index):
return 2 * parent_ind... | src/min_int_heap/min_int_heap.py | class MinIntHeap(object):
def __init__(self):
self.__capacity = 10
self.__size = 0
self.__items = [0] * self.__capacity
def __get_left_child_index(self, parent_index):
return 2 * parent_index + 1
def __get_right_child_index(self, parent_index):
return 2 * parent_ind... | 0.727298 | 0.330417 |
from solid import *
from solid.utils import * # Not required, but the utils module is useful
import math as M
from lib.item import Item
class ShellBase(Item):
def __init__(self, dim):
super().__init__(dim)
self.color = (87, 117, 144)
self.door_w = 30
self.door_off = 6
self.vnose_h = 42
self... | lib/shell.py | from solid import *
from solid.utils import * # Not required, but the utils module is useful
import math as M
from lib.item import Item
class ShellBase(Item):
def __init__(self, dim):
super().__init__(dim)
self.color = (87, 117, 144)
self.door_w = 30
self.door_off = 6
self.vnose_h = 42
self... | 0.714329 | 0.116312 |
from __future__ import unicode_literals
from . import views
from django.shortcuts import redirect
from django.contrib import admin
from . models import Event,Profile
import datetime
import calendar
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
from . utils import EventCalend... | app/admin.py | from __future__ import unicode_literals
from . import views
from django.shortcuts import redirect
from django.contrib import admin
from . models import Event,Profile
import datetime
import calendar
from django.core.urlresolvers import reverse
from django.utils.safestring import mark_safe
from . utils import EventCalend... | 0.409103 | 0.089058 |
import threading
import time
import RPi.GPIO as GPIO
from tkinter import messagebox
class StepperMotor:
def __init__(self, pin_step, pin_direction, pin_calibration_microswitch, pin_safety_microswitch,
step_frequency, microswitch_bouncetime=300, calibration_timeout=20, name=""):
"""Interfa... | steppermotor.py | import threading
import time
import RPi.GPIO as GPIO
from tkinter import messagebox
class StepperMotor:
def __init__(self, pin_step, pin_direction, pin_calibration_microswitch, pin_safety_microswitch,
step_frequency, microswitch_bouncetime=300, calibration_timeout=20, name=""):
"""Interfa... | 0.810891 | 0.290874 |
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
def from_env(env_options, default=None):
value = None
if isinstance(env_options, str):
value = os.environ.get(env_options, None)
else:
for option in env_options:
if option in os.environ:
value = os.... | ore/settings/base.py | import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
def from_env(env_options, default=None):
value = None
if isinstance(env_options, str):
value = os.environ.get(env_options, None)
else:
for option in env_options:
if option in os.environ:
value = os.... | 0.371821 | 0.069415 |
from __future__ import division
from collections import defaultdict
import itertools
import numpy as np
from bbox_tools import IOU
def calc_detection_voc_prec_rec(
pred_bboxes, pred_labels, pred_scores, gt_bboxes, gt_labels, gt_difcs=None,
iou_thresh=0.5
):
pred_bboxes = iter(pred_bboxes)
... | Faster RCNN/eval_tools.py | from __future__ import division
from collections import defaultdict
import itertools
import numpy as np
from bbox_tools import IOU
def calc_detection_voc_prec_rec(
pred_bboxes, pred_labels, pred_scores, gt_bboxes, gt_labels, gt_difcs=None,
iou_thresh=0.5
):
pred_bboxes = iter(pred_bboxes)
... | 0.280715 | 0.266259 |
import struct
import copy
from test_framework.mininode import ser_vector, deser_vector, COutPoint, deser_uint256, deser_compact_size, CTxOut
class msg_getutxos(object):
command = b"getutxos"
def __init__(self, checkmempool = False, outpoints = []):
self.checkmempool = checkmempool
self.outpoin... | qa/rpc-tests/test_framework/bip64.py | import struct
import copy
from test_framework.mininode import ser_vector, deser_vector, COutPoint, deser_uint256, deser_compact_size, CTxOut
class msg_getutxos(object):
command = b"getutxos"
def __init__(self, checkmempool = False, outpoints = []):
self.checkmempool = checkmempool
self.outpoin... | 0.445288 | 0.10235 |
import threading
import time
from pathlib import Path
from typing import List
from daipecore.container.WatcherLogger import WatcherLogger
class ConfigsWatcherThread(threading.Thread):
def __init__(self, configs_dir: str, watcher_logger: WatcherLogger, callback, polling_interval=1):
threading.Thread.__init... | src/daipecore/container/ConfigsWatcherThread.py | import threading
import time
from pathlib import Path
from typing import List
from daipecore.container.WatcherLogger import WatcherLogger
class ConfigsWatcherThread(threading.Thread):
def __init__(self, configs_dir: str, watcher_logger: WatcherLogger, callback, polling_interval=1):
threading.Thread.__init... | 0.66072 | 0.104798 |
import unittest
from mock import MagicMock
from state import BaseState, CorridorState
class BaseStateTests(unittest.TestCase):
"""Unit tests for the BaseState class."""
def setUp(self):
self.mock_robot = MagicMock()
self.state = BaseState(self.mock_robot)
def test_init(self):
self.assertEqual(self.state... | src/tests/state_test.py |
import unittest
from mock import MagicMock
from state import BaseState, CorridorState
class BaseStateTests(unittest.TestCase):
"""Unit tests for the BaseState class."""
def setUp(self):
self.mock_robot = MagicMock()
self.state = BaseState(self.mock_robot)
def test_init(self):
self.assertEqual(self.state... | 0.70028 | 0.686933 |
import argparse
import os
import numpy as np
import torch
import torch.nn.functional as F
import tqdm
from pytorch_pretrained_bert import GPT2Tokenizer
def main():
parser = argparse.ArgumentParser(description='PyTorch Transformer Language Model')
parser.add_argument('--work_dir', type=str, required=True,
... | transformer_xl/generate.py | import argparse
import os
import numpy as np
import torch
import torch.nn.functional as F
import tqdm
from pytorch_pretrained_bert import GPT2Tokenizer
def main():
parser = argparse.ArgumentParser(description='PyTorch Transformer Language Model')
parser.add_argument('--work_dir', type=str, required=True,
... | 0.674801 | 0.232299 |
import mock
import six
from senlin.api.middleware import fault
from senlin.api.openstack.v1 import policy_types
from senlin.common import exception as senlin_exc
from senlin.common import policy
from senlin.rpc import client as rpc_client
from senlin.tests.apiv1 import shared
from senlin.tests.common import base
@m... | senlin/tests/apiv1/test_policy_types.py |
import mock
import six
from senlin.api.middleware import fault
from senlin.api.openstack.v1 import policy_types
from senlin.common import exception as senlin_exc
from senlin.common import policy
from senlin.rpc import client as rpc_client
from senlin.tests.apiv1 import shared
from senlin.tests.common import base
@m... | 0.482429 | 0.11689 |
import logging, pickle, threading, urllib2
from multiprocessing.dummy import Pool
from flask import Flask, jsonify
from json import dumps
from flasgger import Swagger
from port_retrieval import get_nsi_topology, parse_ports
app = Flask(__name__)
Swagger(app)
topology_lock = threading.Lock()
#~ import logging_tree
#... | src/rest_api.py | import logging, pickle, threading, urllib2
from multiprocessing.dummy import Pool
from flask import Flask, jsonify
from json import dumps
from flasgger import Swagger
from port_retrieval import get_nsi_topology, parse_ports
app = Flask(__name__)
Swagger(app)
topology_lock = threading.Lock()
#~ import logging_tree
#... | 0.380989 | 0.081228 |
__author__ = "<NAME> (<EMAIL>)"
import json
import time
import urllib
import urllib2
#HTTP Method code
GET = 0
POST = 1
UPLOAD = 2
#Keyword for GET method
GET_KEYWORDS = ["get", "list", "batch"]
class APIError(StandardError):
"""API exception class."""
def __init__(self, code, message):
self.code... | renren.py |
__author__ = "<NAME> (<EMAIL>)"
import json
import time
import urllib
import urllib2
#HTTP Method code
GET = 0
POST = 1
UPLOAD = 2
#Keyword for GET method
GET_KEYWORDS = ["get", "list", "batch"]
class APIError(StandardError):
"""API exception class."""
def __init__(self, code, message):
self.code... | 0.644113 | 0.072047 |