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 django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AccountEmailaddress',
fields=[
('id', models.BigAutoField(primary_key=True, serialize=False... | whatshouldido/migrations/0001_initial.py |
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AccountEmailaddress',
fields=[
('id', models.BigAutoField(primary_key=True, serialize=False... | 0.503418 | 0.187486 |
import graphene
from graphene_django.types import DjangoObjectType
from rx import Observable
from graphene_subscriptions.events import CREATED, UPDATED, DELETED
from tests.models import SomeModel
CUSTOM_EVENT = "custom_event"
class SomeModelType(DjangoObjectType):
class Meta:
model = SomeModel
class... | tests/schema.py | import graphene
from graphene_django.types import DjangoObjectType
from rx import Observable
from graphene_subscriptions.events import CREATED, UPDATED, DELETED
from tests.models import SomeModel
CUSTOM_EVENT = "custom_event"
class SomeModelType(DjangoObjectType):
class Meta:
model = SomeModel
class... | 0.620047 | 0.203529 |
from polygon.rest.models import (
MarketHoliday,
MarketStatus,
MarketCurrencies,
MarketExchanges,
)
from base import BaseTest
class MarketsTest(BaseTest):
def test_get_market_holidays(self):
holidays = self.c.get_market_holidays()
expected = [
MarketHoliday(
... | test_rest/test_markets.py | from polygon.rest.models import (
MarketHoliday,
MarketStatus,
MarketCurrencies,
MarketExchanges,
)
from base import BaseTest
class MarketsTest(BaseTest):
def test_get_market_holidays(self):
holidays = self.c.get_market_holidays()
expected = [
MarketHoliday(
... | 0.691706 | 0.305795 |
from unittest import TestCase, main
from project.student import Student
class TestStudent(TestCase):
def setUp(self):
self.student = Student("Ivan")
self.student_with_course = Student("Ivan", {"math": ["some notes"]})
def test_initializing(self):
self.assertEqual("Ivan", self.student... | Testing - Exercise/test/test_student.py | from unittest import TestCase, main
from project.student import Student
class TestStudent(TestCase):
def setUp(self):
self.student = Student("Ivan")
self.student_with_course = Student("Ivan", {"math": ["some notes"]})
def test_initializing(self):
self.assertEqual("Ivan", self.student... | 0.695028 | 0.627152 |
__author__ = "TetrisFinalBoss"
__version__ = "0.4.3"
import sys
import cv2
import numpy
import pafy
import re
import os.path
import getopt
AGS_DS2_PLAYLIST = 'PL_ftpUY_ldBTtHOUQLt5irghX1XfIzoy-'
def getFile(media):
for stream in media.streams:
if stream.dimensions[1] == 360 and stream.extension=... | ags-ds2.py | __author__ = "TetrisFinalBoss"
__version__ = "0.4.3"
import sys
import cv2
import numpy
import pafy
import re
import os.path
import getopt
AGS_DS2_PLAYLIST = 'PL_ftpUY_ldBTtHOUQLt5irghX1XfIzoy-'
def getFile(media):
for stream in media.streams:
if stream.dimensions[1] == 360 and stream.extension=... | 0.278944 | 0.109372 |
import logging
import jwt
import requests
from jwt import PyJWKClient
from users_microservice.cfg import config
from users_microservice.constants import (
DEFAULT_AUDIENCE,
DEFAULT_GOOGLE_OPENID_CFG_JWKS_KEY,
DEFAULT_GOOGLE_OPENID_CFG_URI,
)
from users_microservice.exceptions import EmailAlreadyRegistered... | users_microservice/controllers/oauth.py | import logging
import jwt
import requests
from jwt import PyJWKClient
from users_microservice.cfg import config
from users_microservice.constants import (
DEFAULT_AUDIENCE,
DEFAULT_GOOGLE_OPENID_CFG_JWKS_KEY,
DEFAULT_GOOGLE_OPENID_CFG_URI,
)
from users_microservice.exceptions import EmailAlreadyRegistered... | 0.563858 | 0.152347 |
import base64
import traceback
from Crypto.Cipher import AES
from .type_tool import TypeTool
from .b64 import Base64
def pkcs7padding(data):
bs = AES.block_size
padding = bs - len(data) % bs
padding_text = chr(padding) * padding
return data + padding_text.encode()
def pkcs7unpadding(data):
leng... | zdppy_password/aes.py | import base64
import traceback
from Crypto.Cipher import AES
from .type_tool import TypeTool
from .b64 import Base64
def pkcs7padding(data):
bs = AES.block_size
padding = bs - len(data) % bs
padding_text = chr(padding) * padding
return data + padding_text.encode()
def pkcs7unpadding(data):
leng... | 0.491944 | 0.403684 |
import unittest
import numpy as np
from .. import qxrf
from ...utils import units
from ...patch import jsonpickle
class test_qxrf(unittest.TestCase):
def geometryinstance(self):
energy = 10
geometryinstance = qxrf.factory("sxm1", simplecalibration=False)
info = {
"I0_counts":... | spectrocrunch/geometries/tests/test_qxrf.py |
import unittest
import numpy as np
from .. import qxrf
from ...utils import units
from ...patch import jsonpickle
class test_qxrf(unittest.TestCase):
def geometryinstance(self):
energy = 10
geometryinstance = qxrf.factory("sxm1", simplecalibration=False)
info = {
"I0_counts":... | 0.674158 | 0.55266 |
import os
import cv2
import glob
import tqdm
import argparse
from lh_tool.Iterator import SingleProcess, MultiProcess
import lh_tool.imageio as iio
def images2video(image_path, video_file, postfix, fourcc, fps, frameSize=None):
image_file_list = glob.glob(os.path.join(image_path, f'*.{postfix}'))
if len(image... | src/lh_tool/image2video.py | import os
import cv2
import glob
import tqdm
import argparse
from lh_tool.Iterator import SingleProcess, MultiProcess
import lh_tool.imageio as iio
def images2video(image_path, video_file, postfix, fourcc, fps, frameSize=None):
image_file_list = glob.glob(os.path.join(image_path, f'*.{postfix}'))
if len(image... | 0.283285 | 0.136349 |
import numpy as np
import scipy.constants
def signal_delay(st1, st2, ecef):
'''Signal delay due to speed of light between station-1 to ecef position to station-2
'''
r1 = np.linalg.norm(ecef - st1.ecef[:,None], axis=0)
r2 = np.linalg.norm(ecef - st1.ecef[:,None], axis=0)
dt = (r1 + r2)/scipy.const... | sorts/functions.py | import numpy as np
import scipy.constants
def signal_delay(st1, st2, ecef):
'''Signal delay due to speed of light between station-1 to ecef position to station-2
'''
r1 = np.linalg.norm(ecef - st1.ecef[:,None], axis=0)
r2 = np.linalg.norm(ecef - st1.ecef[:,None], axis=0)
dt = (r1 + r2)/scipy.const... | 0.763572 | 0.550607 |
import os
import subprocess
from clams import arg, Command
from unb_cli.project import is_project_root
pip = Command(
name='pip',
title='pip interface and tools',
description='pip interface and tools',
)
@pip.register('install')
@arg('package', nargs='?', default='requirements.txt')
@arg('--nocache', action... | unb_cli/unb/pip.py | import os
import subprocess
from clams import arg, Command
from unb_cli.project import is_project_root
pip = Command(
name='pip',
title='pip interface and tools',
description='pip interface and tools',
)
@pip.register('install')
@arg('package', nargs='?', default='requirements.txt')
@arg('--nocache', action... | 0.474144 | 0.110807 |
import torch
from torch.utils.data import SubsetRandomSampler
import numpy as np
from Precipitation_Forecasting.precipitation_dataset import precipitation_maps_oversampled_h5
from Precipitation_Forecasting.precipitation_lightning import AA_TransUnet_base
class Precip_regression_base(TransUnet_base):
def __init__(... | Precipitation Forecasting/precipitation_lightning_base.py | import torch
from torch.utils.data import SubsetRandomSampler
import numpy as np
from Precipitation_Forecasting.precipitation_dataset import precipitation_maps_oversampled_h5
from Precipitation_Forecasting.precipitation_lightning import AA_TransUnet_base
class Precip_regression_base(TransUnet_base):
def __init__(... | 0.776284 | 0.394726 |
import serial, glob
import copy
import json
import time
from time import localtime, strftime
#initialization and open the port
#possible timeout values:
# 1. None: wait forever, block call
# 2. 0: non-blocking mode, return immediately
# 3. x, x is bigger than 0, float allowed, timeout block call
temp_list =... | test_uart/uart1.py |
import serial, glob
import copy
import json
import time
from time import localtime, strftime
#initialization and open the port
#possible timeout values:
# 1. None: wait forever, block call
# 2. 0: non-blocking mode, return immediately
# 3. x, x is bigger than 0, float allowed, timeout block call
temp_list =... | 0.156169 | 0.098209 |
import contribution.utils
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('accounts', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Contribution',
... | contribution/migrations/0001_initial.py |
import contribution.utils
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('accounts', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Contribution',
... | 0.521959 | 0.136522 |
import math
import operator
from functools import reduce
def cached_pure_function(fn):
cache = {}
def wrapper(*args):
if args in cache:
return cache[args]
x = fn(*args)
cache[args] = x
return x
return wrapper
def cached_pure_generator(fn):
caches = {}
... | intseq/utility.py | import math
import operator
from functools import reduce
def cached_pure_function(fn):
cache = {}
def wrapper(*args):
if args in cache:
return cache[args]
x = fn(*args)
cache[args] = x
return x
return wrapper
def cached_pure_generator(fn):
caches = {}
... | 0.35768 | 0.306598 |
from __future__ import unicode_literals, print_function
import logging
from os import path
import os
import subprocess as sp
import sys
from chalmers import errors
import tempfile
python_exe = sys.executable
chalmers_script = sys.argv[0]
def read_data(filename):
filename = path.join(path.dirname(__file__), 'd... | chalmers/service/darwin_service.py | from __future__ import unicode_literals, print_function
import logging
from os import path
import os
import subprocess as sp
import sys
from chalmers import errors
import tempfile
python_exe = sys.executable
chalmers_script = sys.argv[0]
def read_data(filename):
filename = path.join(path.dirname(__file__), 'd... | 0.286968 | 0.085939 |
import time, json
from collections import OrderedDict as od
class kormerDict:
def __init__(self):
self._1mer_ = {}
self._2mer_ = {}
self._3mer_ = {}
def getData(self,fname):
self.fname = fname
with open(self.fname, "r") as rf :
self._udict_ = jso... | kormerDict.py | import time, json
from collections import OrderedDict as od
class kormerDict:
def __init__(self):
self._1mer_ = {}
self._2mer_ = {}
self._3mer_ = {}
def getData(self,fname):
self.fname = fname
with open(self.fname, "r") as rf :
self._udict_ = jso... | 0.054588 | 0.154217 |
from profileapi.models import Profile
from profileapi.serializers import ProfileSerializer
from rest_framework import generics, status
from rest_framework.response import Response
from django.core.exceptions import ObjectDoesNotExist
from django.views.decorators.csrf import csrf_exempt
class Profiles(generics.ListCrea... | taskit_backend/profileapi/views.py | from profileapi.models import Profile
from profileapi.serializers import ProfileSerializer
from rest_framework import generics, status
from rest_framework.response import Response
from django.core.exceptions import ObjectDoesNotExist
from django.views.decorators.csrf import csrf_exempt
class Profiles(generics.ListCrea... | 0.689096 | 0.117521 |
class FileLoader(object):
def __init__(self, fname, coltypes = {}, separator = None):
self.types = coltypes
if type(fname) == str:
ofile = open(fname)
else:
ofile = fname
self.rows = [x.split(separator) for x in ofile]
def __getitem__(self, *args):
... | sandbox/src2/src/fileloader.py | class FileLoader(object):
def __init__(self, fname, coltypes = {}, separator = None):
self.types = coltypes
if type(fname) == str:
ofile = open(fname)
else:
ofile = fname
self.rows = [x.split(separator) for x in ofile]
def __getitem__(self, *args):
... | 0.45423 | 0.167695 |
from typing import Type, Optional, Dict, Any, Iterator
from marshy.errors import MarshallError
from marshy.factory import marshaller_factory_abc
from marshy.factory.marshaller_factory_abc import MarshallerFactoryABC
from marshy.marshaller import marshaller_abc
from marshy.types import ExternalType
from marshy.utils im... | marshy/marshaller_context.py | from typing import Type, Optional, Dict, Any, Iterator
from marshy.errors import MarshallError
from marshy.factory import marshaller_factory_abc
from marshy.factory.marshaller_factory_abc import MarshallerFactoryABC
from marshy.marshaller import marshaller_abc
from marshy.types import ExternalType
from marshy.utils im... | 0.883022 | 0.07579 |
from timo.database_manager.databases.mysql import MySQL
import HtmlTestRunner
import xmlrunner
import unittest
import json
import os
import yaml
class TestMySQL(unittest.TestCase):
def setUp(self):
self.db = MySQL()
self.db.open_DB_session()
def tearDown(self):
self.db.close_DB_sessi... | tests/test_mysql.py |
from timo.database_manager.databases.mysql import MySQL
import HtmlTestRunner
import xmlrunner
import unittest
import json
import os
import yaml
class TestMySQL(unittest.TestCase):
def setUp(self):
self.db = MySQL()
self.db.open_DB_session()
def tearDown(self):
self.db.close_DB_sessi... | 0.298185 | 0.17434 |
import os
import numpy as np
import pandas as pd
from datashader.utils import lnglat_to_meters as webm
from src.utils import write_log
def engineer_brazilian_zip_code() -> None:
"""
Engineers the brazilian zip code (CEP) in the geolocation dataset by Olist.
"""
write_log("Reading geolocation dataset ... | src/features/Engineer_Brazilian_ZIP_Code.py | import os
import numpy as np
import pandas as pd
from datashader.utils import lnglat_to_meters as webm
from src.utils import write_log
def engineer_brazilian_zip_code() -> None:
"""
Engineers the brazilian zip code (CEP) in the geolocation dataset by Olist.
"""
write_log("Reading geolocation dataset ... | 0.655115 | 0.534673 |
from .preprocessor import FortranPreprocessor
import re
from .smartopen import smart_open
UNIT_REGEX = re.compile(r"^\s*(?P<unit_type>module(?!\s+procedure)|program)\s*(?P<modname>\w*)",
re.IGNORECASE)
END_REGEX = re.compile(r"^\s*end\s*(?P<unit_type>module|program)\s*(?P<modname>\w*)?",
... | fortdepend/units.py | from .preprocessor import FortranPreprocessor
import re
from .smartopen import smart_open
UNIT_REGEX = re.compile(r"^\s*(?P<unit_type>module(?!\s+procedure)|program)\s*(?P<modname>\w*)",
re.IGNORECASE)
END_REGEX = re.compile(r"^\s*end\s*(?P<unit_type>module|program)\s*(?P<modname>\w*)?",
... | 0.539954 | 0.182316 |
import random
from django.conf import settings
from django.utils.text import slugify
import factory
from cms.api import add_plugin, create_page, create_title
def create_i18n_page(title=None, languages=None, is_homepage=False, **kwargs):
"""
Creating a multilingual page is not straightforward so we should ha... | src/richie/apps/core/helpers.py | import random
from django.conf import settings
from django.utils.text import slugify
import factory
from cms.api import add_plugin, create_page, create_title
def create_i18n_page(title=None, languages=None, is_homepage=False, **kwargs):
"""
Creating a multilingual page is not straightforward so we should ha... | 0.694303 | 0.33497 |
import MySQLdb
import time
import re
import os
import urllib
from datetime import datetime
from xml.sax.saxutils import unescape
f = open('workfile.tex', 'w')
def db(hst, usr, pw, dba):
db = MySQLdb.connect(host=hst, user=usr, passwd=pw, db=dba)
# you must create a Cursor object. It will let
# you execute ... | db.py | import MySQLdb
import time
import re
import os
import urllib
from datetime import datetime
from xml.sax.saxutils import unescape
f = open('workfile.tex', 'w')
def db(hst, usr, pw, dba):
db = MySQLdb.connect(host=hst, user=usr, passwd=pw, db=dba)
# you must create a Cursor object. It will let
# you execute ... | 0.164315 | 0.088939 |
import uuid
from dashboards.models import Dashboard, DashboardWidget, DashboardRow
from exceptions import InvalidDashboardParametersException
class DashboardFactory(object):
@staticmethod
def create_dashboard_from_query_params(query_params):
dashboard = Dashboard()
dashboard.name = query_para... | dashboards/factories.py | import uuid
from dashboards.models import Dashboard, DashboardWidget, DashboardRow
from exceptions import InvalidDashboardParametersException
class DashboardFactory(object):
@staticmethod
def create_dashboard_from_query_params(query_params):
dashboard = Dashboard()
dashboard.name = query_para... | 0.667364 | 0.110615 |
see: http://www.astroml.org/book_figures/chapter3/fig_bivariate_gaussian.html
'''
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.patches import Ellipse
from astroML.stats.random import bivariate_normal
from astroML.plotting import setup_text_plots
from IPython.display import SVG,display
impor... | second-round-intreview/parcoord-brushing/backend/src/paper2declutter/preprocessing/ForestPreprocesing.py | see: http://www.astroml.org/book_figures/chapter3/fig_bivariate_gaussian.html
'''
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.patches import Ellipse
from astroML.stats.random import bivariate_normal
from astroML.plotting import setup_text_plots
from IPython.display import SVG,display
impor... | 0.424173 | 0.45042 |
import re
from lib.nlp import helper
OFFSET_OF_NEXT_WORD = 2
BRACKET_MAP_OPEN = {'[': ']', '(': ')', '{': '}'}
BRACKET_MAP_CLOSE = {']': '[', ')': '(', '}': '{'}
TAILING_CHARS = [':', ';', '?', '!', ',']
def sent_tokenize(text):
'''
Sentence segmentation with user specific algorithm.
NOTE: It's might be... | lib/nlp/tokenizer.py | import re
from lib.nlp import helper
OFFSET_OF_NEXT_WORD = 2
BRACKET_MAP_OPEN = {'[': ']', '(': ')', '{': '}'}
BRACKET_MAP_CLOSE = {']': '[', ')': '(', '}': '{'}
TAILING_CHARS = [':', ';', '?', '!', ',']
def sent_tokenize(text):
'''
Sentence segmentation with user specific algorithm.
NOTE: It's might be... | 0.253491 | 0.155335 |
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA,TruncatedSVD,NMF
from sklearn.preprocessing import Normalizer
import argparse
import time
import numba
@numba.jit(nopython=True)
def year_binner(year,val=10):
return year - year%val
parser = argparse.ArgumentParser(description='Perform... | src/dimensionality_reduction.py | import pandas as pd
import numpy as np
from sklearn.decomposition import PCA,TruncatedSVD,NMF
from sklearn.preprocessing import Normalizer
import argparse
import time
import numba
@numba.jit(nopython=True)
def year_binner(year,val=10):
return year - year%val
parser = argparse.ArgumentParser(description='Perform... | 0.479747 | 0.208209 |
from __future__ import division
import numpy as np
import random
import pygame
from shapely.geometry import LineString
# pyGame initialization
FPS = 60
QFPS = 240
SCREEN_WIDTH, SCREEN_HEIGHT = 640, 480
pygame.init()
FPS_CLOCK = pygame.time.Clock()
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.... | king_pong.py | from __future__ import division
import numpy as np
import random
import pygame
from shapely.geometry import LineString
# pyGame initialization
FPS = 60
QFPS = 240
SCREEN_WIDTH, SCREEN_HEIGHT = 640, 480
pygame.init()
FPS_CLOCK = pygame.time.Clock()
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.... | 0.744378 | 0.178526 |
import django.core.validators
import django.db.models.deletion
import django.utils.timezone
import django_fsm
import model_utils.fields
from django.db import migrations, models
import waldur_core.core.fields
import waldur_core.core.models
import waldur_core.logging.loggers
class Migration(migrations.Migration):
... | src/waldur_paypal/migrations/0001_initial.py | import django.core.validators
import django.db.models.deletion
import django.utils.timezone
import django_fsm
import model_utils.fields
from django.db import migrations, models
import waldur_core.core.fields
import waldur_core.core.models
import waldur_core.logging.loggers
class Migration(migrations.Migration):
... | 0.442396 | 0.146789 |
import abc
import torch
import torch.nn as nn
import torch.nn.functional as F
from .cfg import Config
from .SphereProjection import SphereProjection
class RowBilinear(nn.Module):
def __init__(self, n_in, kernel_shapes, pad=0):
super(RowBilinear, self).__init__()
n_transform = kernel_shapes.siz... | model/KernelTransformer/KTN.py |
import abc
import torch
import torch.nn as nn
import torch.nn.functional as F
from .cfg import Config
from .SphereProjection import SphereProjection
class RowBilinear(nn.Module):
def __init__(self, n_in, kernel_shapes, pad=0):
super(RowBilinear, self).__init__()
n_transform = kernel_shapes.siz... | 0.905259 | 0.304752 |
import typing
from pylark.lark_request import Response
from pylark.api_service_drive_file_search import (
SearchDriveFileReq,
SearchDriveFileResp,
_gen_search_drive_file_req,
)
from pylark.api_service_drive_file_meta_get import (
GetDriveFileMetaReq,
GetDriveFileMetaResp,
_gen_get_drive_file_m... | pylark/api_service_drive.py |
import typing
from pylark.lark_request import Response
from pylark.api_service_drive_file_search import (
SearchDriveFileReq,
SearchDriveFileResp,
_gen_search_drive_file_req,
)
from pylark.api_service_drive_file_meta_get import (
GetDriveFileMetaReq,
GetDriveFileMetaResp,
_gen_get_drive_file_m... | 0.227469 | 0.030416 |
from itertools import zip_longest
import json
from plmbr.pipe import pipe
from plmbr.pipes import *
class validate(Pipe):
def __init__(self, *vals):
self.vals = vals
def pipe(self, items: Iterator) -> Iterator:
for expected, actual in zip_longest(self.vals, items):
print(f'expecti... | test/test_pipes.py | from itertools import zip_longest
import json
from plmbr.pipe import pipe
from plmbr.pipes import *
class validate(Pipe):
def __init__(self, *vals):
self.vals = vals
def pipe(self, items: Iterator) -> Iterator:
for expected, actual in zip_longest(self.vals, items):
print(f'expecti... | 0.518059 | 0.557424 |
import os
import tkinter as tk
import webbrowser
from tkinter import messagebox
from tkinter import ttk
from thonnycontrib.codelive.views.session_status.user_list import UserList, UserListItem
SESSION_DIA_MIN_SIZE = {"width": 378, "height": 400}
BUG_ICON_PATH = os.path.join(os.path.dirname(__file__), "res", "bug-16.... | thonnycontrib/codelive/views/session_status/dialog.py | import os
import tkinter as tk
import webbrowser
from tkinter import messagebox
from tkinter import ttk
from thonnycontrib.codelive.views.session_status.user_list import UserList, UserListItem
SESSION_DIA_MIN_SIZE = {"width": 378, "height": 400}
BUG_ICON_PATH = os.path.join(os.path.dirname(__file__), "res", "bug-16.... | 0.405213 | 0.101411 |
import optparse
import re
from pyang import plugin
from pyang import util
from pyang import grammar
def pyang_plugin_init():
plugin.register_plugin(StripPlugin())
class StripPlugin(plugin.PyangPlugin):
def add_output_format(self, fmts):
fmts['strip'] = self
self.handle_comments = True
d... | plugins/strip.py |
import optparse
import re
from pyang import plugin
from pyang import util
from pyang import grammar
def pyang_plugin_init():
plugin.register_plugin(StripPlugin())
class StripPlugin(plugin.PyangPlugin):
def add_output_format(self, fmts):
fmts['strip'] = self
self.handle_comments = True
d... | 0.284477 | 0.090695 |
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.MerchantBaseEnterOpenModel import MerchantBaseEnterOpenModel
from alipay.aop.api.domain.SubMerchantCommonEnterOpenModel import SubMerchantCommonEnterOpenModel
from alipay.aop.api.domain.SubMerchantEnterOpenModel import SubMerch... | alipay/aop/api/domain/AlipayEbppInvoiceMerchantlistEnterApplyModel.py | import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.MerchantBaseEnterOpenModel import MerchantBaseEnterOpenModel
from alipay.aop.api.domain.SubMerchantCommonEnterOpenModel import SubMerchantCommonEnterOpenModel
from alipay.aop.api.domain.SubMerchantEnterOpenModel import SubMerch... | 0.378115 | 0.040922 |
import os
import sys
import time
from argparse import ArgumentParser
import math
import numpy as np
import time
import torch
from torch.optim.lr_scheduler import MultiStepLR
import torch.utils.data.distributed
from src.model import model, Loss
from src.utils import dboxes300_coco, Encoder
from src.evaluate import ev... | docs/examples/use_cases/pytorch/single_stage_detector/main.py | import os
import sys
import time
from argparse import ArgumentParser
import math
import numpy as np
import time
import torch
from torch.optim.lr_scheduler import MultiStepLR
import torch.utils.data.distributed
from src.model import model, Loss
from src.utils import dboxes300_coco, Encoder
from src.evaluate import ev... | 0.542621 | 0.164282 |
from db import db
class PortfolioModel(db.Model):
"""SQLAlchemy Portfolio Model"""
# We assign the correct table
__tablename__ = 'portfolios'
# Table columns
portfolioId = db.Column(db.Integer, primary_key=True, nullable=False)
name = db.Column(db.String(300), nullable=False)
# ... | models/portfolio.py |
from db import db
class PortfolioModel(db.Model):
"""SQLAlchemy Portfolio Model"""
# We assign the correct table
__tablename__ = 'portfolios'
# Table columns
portfolioId = db.Column(db.Integer, primary_key=True, nullable=False)
name = db.Column(db.String(300), nullable=False)
# ... | 0.688364 | 0.176264 |
from face_lib import my_api, inference
import csv
import multiprocessing
import tensorflow as tf
class LFW_TEST:
def __init__(self,sia,se):
self.sia = sia
self.se = se
def csv_write(self,path, data):
out_test = open(path, 'w', newline='')
csv_test_writer = csv.writer(out_test,... | lfw_test.py | from face_lib import my_api, inference
import csv
import multiprocessing
import tensorflow as tf
class LFW_TEST:
def __init__(self,sia,se):
self.sia = sia
self.se = se
def csv_write(self,path, data):
out_test = open(path, 'w', newline='')
csv_test_writer = csv.writer(out_test,... | 0.406273 | 0.333449 |
import json
from sqlalchemy import text
from profiler.domain.aggregation import Aggregation, AggregationBatch
from profiler.domain.errors import EntityWasNotStoredError
from profiler.ports.aggregations_repository import AggregationsRepository
from profiler.db.pg_engine import engine
from profiler.utils.json_dumper impo... | profiler/profiler/adapters/aggregations_repository/pg_aggregations_repository.py | import json
from sqlalchemy import text
from profiler.domain.aggregation import Aggregation, AggregationBatch
from profiler.domain.errors import EntityWasNotStoredError
from profiler.ports.aggregations_repository import AggregationsRepository
from profiler.db.pg_engine import engine
from profiler.utils.json_dumper impo... | 0.432183 | 0.090735 |
from doit.action import CmdAction
from doit.task import clean_targets
import sys
def gui_open_action(pth):
action = None
if sys.platform.startswith('linux'):
action = ["xdg-open", str(pth)]
elif sys.platform.startswith('darwin'):
action = ["open", str(pth)]
elif sys.platform.startswit... | dodo.py | from doit.action import CmdAction
from doit.task import clean_targets
import sys
def gui_open_action(pth):
action = None
if sys.platform.startswith('linux'):
action = ["xdg-open", str(pth)]
elif sys.platform.startswith('darwin'):
action = ["open", str(pth)]
elif sys.platform.startswit... | 0.333829 | 0.079246 |
# Standard imports
from dataclasses import dataclass
from typing import List
# Third party imports
from github.GithubException import UnknownObjectException
from requests.exceptions import ReadTimeout
# Application imports
from app.logger import console
from app.techniques.abstract_handl... | email2github/app/techniques/fake_commits.py |
# Standard imports
from dataclasses import dataclass
from typing import List
# Third party imports
from github.GithubException import UnknownObjectException
from requests.exceptions import ReadTimeout
# Application imports
from app.logger import console
from app.techniques.abstract_handl... | 0.420005 | 0.108048 |
from __future__ import unicode_literals
import logging
from peewee import fn
import time
import datetime
from fetch.api import make_request, default_requests_session
from lock import lock_method
from models import SearchResult, WebPageVersion
logger = logging.getLogger('data')
ARCHIVE_URL = 'http://web.archive.org/... | fetch/histories.py |
from __future__ import unicode_literals
import logging
from peewee import fn
import time
import datetime
from fetch.api import make_request, default_requests_session
from lock import lock_method
from models import SearchResult, WebPageVersion
logger = logging.getLogger('data')
ARCHIVE_URL = 'http://web.archive.org/... | 0.483892 | 0.10217 |
from unittest.mock import MagicMock, call, mock_open, patch
from pytest import raises
from vang.pio.rsr import _in
from vang.pio.rsr import _replace_in_file
from vang.pio.rsr import _replace_file
from vang.pio.rsr import _rsr
from vang.pio.rsr import get_replace_function
from vang.pio.rsr import rsr
from vang.pio.rsr... | vang/pio/tests/test_rsr.py | from unittest.mock import MagicMock, call, mock_open, patch
from pytest import raises
from vang.pio.rsr import _in
from vang.pio.rsr import _replace_in_file
from vang.pio.rsr import _replace_file
from vang.pio.rsr import _rsr
from vang.pio.rsr import get_replace_function
from vang.pio.rsr import rsr
from vang.pio.rsr... | 0.452052 | 0.366533 |
import logging
import os
import re
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
import pandas as pd
from .util import print_log, read_fasta_and_generate_seq
def create_bed_from_fa(fa_path, dest_dir_path, bgzip='bgzip',
human_autosome=False, target... | tmber/bed.py |
import logging
import os
import re
from concurrent.futures import ProcessPoolExecutor, as_completed
from pathlib import Path
import pandas as pd
from .util import print_log, read_fasta_and_generate_seq
def create_bed_from_fa(fa_path, dest_dir_path, bgzip='bgzip',
human_autosome=False, target... | 0.284377 | 0.263368 |
import logging
import os
import re
import subprocess
import sys
import time
from webkitpy.benchmark_runner.http_server_driver.http_server_driver import HTTPServerDriver
_log = logging.getLogger(__name__)
class SimpleHTTPServerDriver(HTTPServerDriver):
"""This class depends on unix environment, need to be mod... | Tools/Scripts/webkitpy/benchmark_runner/http_server_driver/simple_http_server_driver.py |
import logging
import os
import re
import subprocess
import sys
import time
from webkitpy.benchmark_runner.http_server_driver.http_server_driver import HTTPServerDriver
_log = logging.getLogger(__name__)
class SimpleHTTPServerDriver(HTTPServerDriver):
"""This class depends on unix environment, need to be mod... | 0.257578 | 0.04904 |
import pickle
import sqlite3
import logging
from collections import namedtuple
from sanskrit_parser.base.sanskrit_base import SanskritImmutableString, SCHEMES
from sanskrit_parser.util.lexical_lookup import LexicalLookup
from sanskrit_parser.util.inriatagmapper import inriaTagMapper
from sanskrit_parser.util.data_mana... | sanskrit_parser/util/inriaxmlwrapper.py | import pickle
import sqlite3
import logging
from collections import namedtuple
from sanskrit_parser.base.sanskrit_base import SanskritImmutableString, SCHEMES
from sanskrit_parser.util.lexical_lookup import LexicalLookup
from sanskrit_parser.util.inriatagmapper import inriaTagMapper
from sanskrit_parser.util.data_mana... | 0.552781 | 0.339171 |
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
class MainApp(App):
def build(self):
self.operators = ["/", "*", "+","%","^","Mod"]
self.last_was_operator = None
se... | Calvy/main.py | from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
class MainApp(App):
def build(self):
self.operators = ["/", "*", "+","%","^","Mod"]
self.last_was_operator = None
se... | 0.421552 | 0.204878 |
import os
import sys
import requests
import time
from datetime import date, datetime, timedelta
import json
import pickle
import logging
from collections import deque
from configparser import ConfigParser
from optparse import OptionParser
from ifobfuscate import decode
import warnings
warnings.filterwarnings('ignore... | insightFinderToServiceNow/GeneratePredictedIncidentServiceNowTicket.py |
import os
import sys
import requests
import time
from datetime import date, datetime, timedelta
import json
import pickle
import logging
from collections import deque
from configparser import ConfigParser
from optparse import OptionParser
from ifobfuscate import decode
import warnings
warnings.filterwarnings('ignore... | 0.305594 | 0.070528 |
from app.database.models import SalesVolumes
from app.database import db
from app.log import logger
def create_new_record(record):
with db.auto_commit_db():
new_sales = SalesVolumes(pid=record['pid'], sid=record['sid'], pname=record['pname'], date=record['date'], sales=record['sales'])
db.session.a... | SA-be/app/database/salesVolumes.py | from app.database.models import SalesVolumes
from app.database import db
from app.log import logger
def create_new_record(record):
with db.auto_commit_db():
new_sales = SalesVolumes(pid=record['pid'], sid=record['sid'], pname=record['pname'], date=record['date'], sales=record['sales'])
db.session.a... | 0.376165 | 0.125842 |
import logging
import logging.config
import os
import torch
import pickle
import numpy as np
logger=logging.getLogger(__name__)
def init_logging(exp_dir, config_path='config/logging_config.yaml'):
"""
initial logging module with config
:param config_path:
:return:
"""
import ... | utils.py | import logging
import logging.config
import os
import torch
import pickle
import numpy as np
logger=logging.getLogger(__name__)
def init_logging(exp_dir, config_path='config/logging_config.yaml'):
"""
initial logging module with config
:param config_path:
:return:
"""
import ... | 0.252937 | 0.059674 |
import os
import random
import traceback
import discord
from discord.ext import commands, tasks
GUILD = 384811165949231104
IMG_DIR = './data/server-icons'
PLAN_Z = 507429352720433152
def find_file(i):
images = os.listdir(IMG_DIR)
for img_name in images:
if img_name.startswith(str(i)):
r... | archive/server_icon.py | import os
import random
import traceback
import discord
from discord.ext import commands, tasks
GUILD = 384811165949231104
IMG_DIR = './data/server-icons'
PLAN_Z = 507429352720433152
def find_file(i):
images = os.listdir(IMG_DIR)
for img_name in images:
if img_name.startswith(str(i)):
r... | 0.386069 | 0.2296 |
import numpy as np
import histo_funcs as hf
from scipy.interpolate import interp1d
def get_shifts(ref, N, max_shift=150, global_shift_fun=None):
"""
This computes the optimal shift between a 1d reference array and the
columns of a 2d data array using an fft based cross correlation. The
optimal shift ... | SiO2/SEDcorr/sed_corr.py | import numpy as np
import histo_funcs as hf
from scipy.interpolate import interp1d
def get_shifts(ref, N, max_shift=150, global_shift_fun=None):
"""
This computes the optimal shift between a 1d reference array and the
columns of a 2d data array using an fft based cross correlation. The
optimal shift ... | 0.897852 | 0.75665 |
from textwrap import dedent
import unittest
from graphql import parse
from ...schema_transformation.utils import InvalidTypeNameError, SchemaStructureError, check_ast_schema_is_valid
class TestCheckSchemaValid(unittest.TestCase):
def test_missing_type_schema(self):
schema_string = dedent(
"""\
schema ... | graphql_compiler/tests/schema_transformation_tests/test_check_schema_valid.py | from textwrap import dedent
import unittest
from graphql import parse
from ...schema_transformation.utils import InvalidTypeNameError, SchemaStructureError, check_ast_schema_is_valid
class TestCheckSchemaValid(unittest.TestCase):
def test_missing_type_schema(self):
schema_string = dedent(
"""\
schema ... | 0.525612 | 0.597579 |
import sys
from itertools import product
import iris
import iris.quickplot as qplt
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from remake import Task, TaskControl, remake_task_control
from cosmic import util
from cosmic.config import CONSTRAINT_ASIA, PATHS
from orog_precip_paths import (la... | ctrl/WP2_analysis/orog_precip/diagnose_orog_mask.py | import sys
from itertools import product
import iris
import iris.quickplot as qplt
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from remake import Task, TaskControl, remake_task_control
from cosmic import util
from cosmic.config import CONSTRAINT_ASIA, PATHS
from orog_precip_paths import (la... | 0.209712 | 0.340924 |
from __future__ import print_function
import os
import math
import tensorflow as tf
import horovod.tensorflow as hvd
from model import efficientnet_model
from utils import dataset_factory, hvd_utils, callbacks, preprocessing
__all__ = ['get_optimizer_params', 'get_metrics', 'get_learning_rate_params', 'build_mode... | DeepLearningExamples/TensorFlow2/Classification/ConvNets/efficientnet/runtime/runner_utils.py |
from __future__ import print_function
import os
import math
import tensorflow as tf
import horovod.tensorflow as hvd
from model import efficientnet_model
from utils import dataset_factory, hvd_utils, callbacks, preprocessing
__all__ = ['get_optimizer_params', 'get_metrics', 'get_learning_rate_params', 'build_mode... | 0.874507 | 0.171824 |
from flask import Flask, render_template, request
import RPi.GPIO as GPIO
app = Flask(__name__)
GPIO.setmode(GPIO.BOARD)
pin_list = [12, 16]
for pin in pin_list:
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, GPIO.LOW)
pin_dict = {
12: {
'led_colour': 'Green LED',
'led_state': GPIO.LOW
... | LED/FLASK/flask_red_green_LED.py | from flask import Flask, render_template, request
import RPi.GPIO as GPIO
app = Flask(__name__)
GPIO.setmode(GPIO.BOARD)
pin_list = [12, 16]
for pin in pin_list:
GPIO.setup(pin, GPIO.OUT)
GPIO.output(pin, GPIO.LOW)
pin_dict = {
12: {
'led_colour': 'Green LED',
'led_state': GPIO.LOW
... | 0.433262 | 0.088702 |
from collections import namedtuple
from datetime import date, datetime, time
from decimal import Context, Decimal, ROUND_HALF_UP
from html.parser import HTMLParser
from itertools import zip_longest
from re import compile, finditer, sub
from secrets import choice
from string import ascii_letters, digits
LOAD_VARIABLE_... | metadata/util.py | from collections import namedtuple
from datetime import date, datetime, time
from decimal import Context, Decimal, ROUND_HALF_UP
from html.parser import HTMLParser
from itertools import zip_longest
from re import compile, finditer, sub
from secrets import choice
from string import ascii_letters, digits
LOAD_VARIABLE_... | 0.643329 | 0.190686 |
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_datasets as tfds
dataset, info = tfds.load('oxford_iiit_pet:3.*.*', with_info=True)
def normalize(input_image, input_mask):
input_image = tf.cast(input_image, tf.float32) / 255.0
input_mask -= 1
return input_image, input_mask
@tf... | unet.py | import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_datasets as tfds
dataset, info = tfds.load('oxford_iiit_pet:3.*.*', with_info=True)
def normalize(input_image, input_mask):
input_image = tf.cast(input_image, tf.float32) / 255.0
input_mask -= 1
return input_image, input_mask
@tf... | 0.858526 | 0.693022 |
import requests
import os
from people_detection import PeopleDetection
from PIL import Image
from io import BytesIO
from time import time, sleep
class Scam(object):
base_url = "http://scam.42.fr"
cam_endpoints = {
# region: [camera, camera, camera]
"e0": [
"cam-e1-sm-rue",
... | scam.py | import requests
import os
from people_detection import PeopleDetection
from PIL import Image
from io import BytesIO
from time import time, sleep
class Scam(object):
base_url = "http://scam.42.fr"
cam_endpoints = {
# region: [camera, camera, camera]
"e0": [
"cam-e1-sm-rue",
... | 0.583915 | 0.230259 |
import unittest
from envdiff.diff import Diff
class TestDiff(unittest.TestCase):
def test_loads_files_on_construction(self):
expected_contents = ['URL=https://www.test.com/', 'FOO=BAR']
self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple')
self.assertEqual(self.dif... | test/test_diff.py | import unittest
from envdiff.diff import Diff
class TestDiff(unittest.TestCase):
def test_loads_files_on_construction(self):
expected_contents = ['URL=https://www.test.com/', 'FOO=BAR']
self.differ = Diff('test/fixtures/.env-simple', 'test/fixtures/.env-simple')
self.assertEqual(self.dif... | 0.608478 | 0.661718 |
from datetime import (
date,
datetime,
time,
timedelta
)
from babel.dates import (
format_date,
format_datetime,
format_time,
format_timedelta,
get_timezone
)
from pyramid.compat import text_type
def date_formatter(request, value, format='medium', locale_name=None):
"""Date for... | djed/formatter/datetime.py | from datetime import (
date,
datetime,
time,
timedelta
)
from babel.dates import (
format_date,
format_datetime,
format_time,
format_timedelta,
get_timezone
)
from pyramid.compat import text_type
def date_formatter(request, value, format='medium', locale_name=None):
"""Date for... | 0.605449 | 0.127979 |
import socket
import sys
import signal
import time
BUFFER_SIZE = 1024
def recv(sock):
buffer = sock.recv(BUFFER_SIZE)
out = buffer.decode('utf-8')
if out != "ok":
raise "Failed to receive a message"
print("receiving: " + out)
def sendto(sock, remote, cmd):
print("cmd: " + cmd)
sock.s... | command_drone.py | import socket
import sys
import signal
import time
BUFFER_SIZE = 1024
def recv(sock):
buffer = sock.recv(BUFFER_SIZE)
out = buffer.decode('utf-8')
if out != "ok":
raise "Failed to receive a message"
print("receiving: " + out)
def sendto(sock, remote, cmd):
print("cmd: " + cmd)
sock.s... | 0.123617 | 0.064506 |
import os
import time
import fnmatch
def match(paths, atimeout=None, ctimeout=None, mtimeout=None, seed=None, patterns=None, verbose=False):
'''
:param paths: path for clean
:param atimeout: file will be deleted after access timeout
:param ctimeout: file will be deleted after creation timeout
:pa... | pyplus/tools/file_cleaner.py | import os
import time
import fnmatch
def match(paths, atimeout=None, ctimeout=None, mtimeout=None, seed=None, patterns=None, verbose=False):
'''
:param paths: path for clean
:param atimeout: file will be deleted after access timeout
:param ctimeout: file will be deleted after creation timeout
:pa... | 0.205894 | 0.160496 |
from assets.variables import *
import assets.tools as tools
from scenes import editor, helper, options
class MainMenu(tools.SceneBase):
"""Class that creates the main menu screen
Attributes
----------
counter: int
keeps track of the user's selection
selection: dict
uses the counte... | scripts/scenes/menu.py | from assets.variables import *
import assets.tools as tools
from scenes import editor, helper, options
class MainMenu(tools.SceneBase):
"""Class that creates the main menu screen
Attributes
----------
counter: int
keeps track of the user's selection
selection: dict
uses the counte... | 0.758779 | 0.348146 |
r"""
Copyright (c) 2015 <NAME>
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
"""
__author__ = 'mori.yuichiro'
import time
import pprint
import logging
import json
import argparse
import tempfile
import boto
from boto.s3.key import Key
from crypt import Encrypto... | s4backup.py |
r"""
Copyright (c) 2015 <NAME>
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
"""
__author__ = 'mori.yuichiro'
import time
import pprint
import logging
import json
import argparse
import tempfile
import boto
from boto.s3.key import Key
from crypt import Encrypto... | 0.414306 | 0.070848 |
import geopandas as gpd
import scipy.optimize
import scipy.sparse
def match_footprints(grnd_df, prop_df,
threshold=0.25, base_reward=100.):
"""
Optimal matching of ground truth footprints with proposal footprints
(for a single timestep).
Input dataframes should have "id" & "geometr... | solaris/eval/scot.py | import geopandas as gpd
import scipy.optimize
import scipy.sparse
def match_footprints(grnd_df, prop_df,
threshold=0.25, base_reward=100.):
"""
Optimal matching of ground truth footprints with proposal footprints
(for a single timestep).
Input dataframes should have "id" & "geometr... | 0.559049 | 0.560794 |
from pathlib import Path
import re
import json
from collections import defaultdict
section_tex_dir = Path("tacling_climate_change_source/sections")
bbl_file = Path("tacling_climate_change_source/main.bbl")
sections_out = Path("section_information.json")
citations_out = Path("section_citations.json")
authors_out = Path... | parse_tex.py | from pathlib import Path
import re
import json
from collections import defaultdict
section_tex_dir = Path("tacling_climate_change_source/sections")
bbl_file = Path("tacling_climate_change_source/main.bbl")
sections_out = Path("section_information.json")
citations_out = Path("section_citations.json")
authors_out = Path... | 0.150778 | 0.124372 |
from __future__ import unicode_literals
from django.db import migrations
current_montage = [
"SC-2078",
"SC-2197",
"SC-2190",
"SC-2189",
"SC-2298",
"SC-2059",
"SC-2058",
"SC-2299",
"SC-2163",
"SC-2162",
"SC-2284",
"SC-2043",
"SC-1196",
"SC-2161",
"SC-2160",
"SC-2149",
"SC-2148",
"SC-1188",
"SC-2035",
"SC-2034",
"SC-2... | sisyphus/migrations/0003_auto_20190809_1123.py | from __future__ import unicode_literals
from django.db import migrations
current_montage = [
"SC-2078",
"SC-2197",
"SC-2190",
"SC-2189",
"SC-2298",
"SC-2059",
"SC-2058",
"SC-2299",
"SC-2163",
"SC-2162",
"SC-2284",
"SC-2043",
"SC-1196",
"SC-2161",
"SC-2160",
"SC-2149",
"SC-2148",
"SC-1188",
"SC-2035",
"SC-2034",
"SC-2... | 0.400984 | 0.29015 |
# IMPORT
from abc import ABCMeta
from abc import abstractmethod
from concurrent.futures import ThreadPoolExecutor
from bluepy.btle import BTLEException
from blue_st_sdk.utils.ble_node_definitions import Debug
from blue_st_sdk.utils.python_utils import lock
# CLASSES
class DebugConsole():
"""Class... | blue_st_sdk/debug_console.py | # IMPORT
from abc import ABCMeta
from abc import abstractmethod
from concurrent.futures import ThreadPoolExecutor
from bluepy.btle import BTLEException
from blue_st_sdk.utils.ble_node_definitions import Debug
from blue_st_sdk.utils.python_utils import lock
# CLASSES
class DebugConsole():
"""Class... | 0.769946 | 0.191725 |
__author__ = "<NAME>"
__copyright__ = "Copyright (c) 2021 <NAME> All Rights Reserved."
__email__ = "<EMAIL>"
__license__ = "Apache 2"
import copy
import json
from pprint import pprint
import requests
DATASETS_URL = "https://phenotypes.healthdatagateway.org/api/v1/data-sources/?format=json"
PHENOTYPES_URL = "https://p... | scripts/generate_crossrefs.py | __author__ = "<NAME>"
__copyright__ = "Copyright (c) 2021 <NAME> All Rights Reserved."
__email__ = "<EMAIL>"
__license__ = "Apache 2"
import copy
import json
from pprint import pprint
import requests
DATASETS_URL = "https://phenotypes.healthdatagateway.org/api/v1/data-sources/?format=json"
PHENOTYPES_URL = "https://p... | 0.311532 | 0.201322 |
import weakref
from nfv_common import debug
from nfv_common.strategy._strategy_result import STRATEGY_STEP_RESULT
DLOG = debug.debug_get_logger('nfv_common.strategy.step')
class StrategyStep(object):
"""
Strategy Step
"""
def __init__(self, name, force_pass=False, timeout_in_secs=0, max_retries=1):... | nfv/nfv-common/nfv_common/strategy/_strategy_step.py | import weakref
from nfv_common import debug
from nfv_common.strategy._strategy_result import STRATEGY_STEP_RESULT
DLOG = debug.debug_get_logger('nfv_common.strategy.step')
class StrategyStep(object):
"""
Strategy Step
"""
def __init__(self, name, force_pass=False, timeout_in_secs=0, max_retries=1):... | 0.79999 | 0.198646 |
import warnings
import pandas as pd
import numpy as np
def simFireplace(
temperature,
occ_act,
n_ovens=1,
T_oven_on=5,
t_cool=5.0,
fullloadSteps=450,
seed=None,
):
"""
Creates the profile of the heating of wood ovens based on the outside
temperature and the activity of the occ... | tsib/renewables/fireplace.py | import warnings
import pandas as pd
import numpy as np
def simFireplace(
temperature,
occ_act,
n_ovens=1,
T_oven_on=5,
t_cool=5.0,
fullloadSteps=450,
seed=None,
):
"""
Creates the profile of the heating of wood ovens based on the outside
temperature and the activity of the occ... | 0.789761 | 0.543348 |
import re
import simple_history
from django import forms
from django.contrib import admin, messages
from django.contrib.admin import TabularInline
from django.db.models import Count, Exists, OuterRef
from django.utils import timezone
from django.utils.safestring import mark_safe
from clubs.management.commands.merge_d... | backend/clubs/admin.py | import re
import simple_history
from django import forms
from django.contrib import admin, messages
from django.contrib.admin import TabularInline
from django.db.models import Count, Exists, OuterRef
from django.utils import timezone
from django.utils.safestring import mark_safe
from clubs.management.commands.merge_d... | 0.380183 | 0.132824 |
from pytest import raises # type: ignore
from pygritia import * # pylint: disable=wildcard-import,unused-wildcard-import
def test_if():
"""Test for If"""
cond = symbol('cond')
sym = symbol('sym')
arr = [1, 2, 3]
expr = If(cond, sym[0])
assert str(expr) == 'If(cond, sym[0])'
assert evalua... | tests/test_cases.py | from pytest import raises # type: ignore
from pygritia import * # pylint: disable=wildcard-import,unused-wildcard-import
def test_if():
"""Test for If"""
cond = symbol('cond')
sym = symbol('sym')
arr = [1, 2, 3]
expr = If(cond, sym[0])
assert str(expr) == 'If(cond, sym[0])'
assert evalua... | 0.498291 | 0.757638 |
import ast
import os.path
from typing import List
from typing import Tuple
from all_repos_depends.errors import DependsError
from all_repos_depends.lang import python
from all_repos_depends.types import Depends
class FindsInstallRequires(ast.NodeVisitor):
def __init__(self) -> None:
self.requires: List[D... | all_repos_depends/depends.py | import ast
import os.path
from typing import List
from typing import Tuple
from all_repos_depends.errors import DependsError
from all_repos_depends.lang import python
from all_repos_depends.types import Depends
class FindsInstallRequires(ast.NodeVisitor):
def __init__(self) -> None:
self.requires: List[D... | 0.496582 | 0.150903 |
import os
import sys
import yaml
import desiutil
import fitsio
import desisim
import argparse
import os.path as path
import numpy as np
import astropy.io.fits as fits
import matplotlib.pyplot as plt
from desiutil ... | py/desispec/scripts/compute_tsnr_ensemble.py | import os
import sys
import yaml
import desiutil
import fitsio
import desisim
import argparse
import os.path as path
import numpy as np
import astropy.io.fits as fits
import matplotlib.pyplot as plt
from desiutil ... | 0.229449 | 0.168275 |
from Estoque import Estoque_Menu
list_estoque = list() # Contém todas as produtos registrados e seu disponibilidade
list_verifica_id = list() # Contém todos os ids já registrados para tratamento de erro
list_entrada_de_produto = list() # Registra toda a entrada de produto
list_saída_de_produto = list() # Registra tod... | !Loja (Canceled Version)!/Estoque/Backup.py | from Estoque import Estoque_Menu
list_estoque = list() # Contém todas as produtos registrados e seu disponibilidade
list_verifica_id = list() # Contém todos os ids já registrados para tratamento de erro
list_entrada_de_produto = list() # Registra toda a entrada de produto
list_saída_de_produto = list() # Registra tod... | 0.169784 | 0.451085 |
try:
from pyspark import SparkContext, SparkConf,SQLContext
from pyspark.sql.functions import to_date,lit,desc,col
from pyspark.sql import Row
from operator import add
from server.main.utils import get_requireddataframe_fromcsv
import sys
except:
print('error')
def create_task(words):
... | services/web/project/server/main/tasks.py |
try:
from pyspark import SparkContext, SparkConf,SQLContext
from pyspark.sql.functions import to_date,lit,desc,col
from pyspark.sql import Row
from operator import add
from server.main.utils import get_requireddataframe_fromcsv
import sys
except:
print('error')
def create_task(words):
... | 0.36557 | 0.282118 |
from entrenamiento.app.app import db
from entrenamiento.models.base import BaseModel
class Torneo(BaseModel):
''' Tiene toda la informacion sobre el tipo de resultado.
Es importante tener en cuenta que esto se lo usa tanto para
los torneos reales como para las practicas de torneos.
:param int id: un ... | entrenamiento/models/torneo.py |
from entrenamiento.app.app import db
from entrenamiento.models.base import BaseModel
class Torneo(BaseModel):
''' Tiene toda la informacion sobre el tipo de resultado.
Es importante tener en cuenta que esto se lo usa tanto para
los torneos reales como para las practicas de torneos.
:param int id: un ... | 0.520984 | 0.440409 |
from fastapi import APIRouter, HTTPException, Depends
from pymongo.client_session import ClientSession
from autologging import logged
from app.api.deps import get_session
from app.db.operations import insert_one, update_one
from app.schemas.response import InsertOneResponse, UpdateOneResponse
from app.schemas.usage im... | backend/app/api/endpoints/usage.py | from fastapi import APIRouter, HTTPException, Depends
from pymongo.client_session import ClientSession
from autologging import logged
from app.api.deps import get_session
from app.db.operations import insert_one, update_one
from app.schemas.response import InsertOneResponse, UpdateOneResponse
from app.schemas.usage im... | 0.731346 | 0.098555 |
import logging
import os
import shutil
import subprocess # nosec
import uuid
from tempfile import mkdtemp
from textwrap import fill
from typing import Iterable, Generator, Optional, Sequence
from pkg_resources import resource_string
import markdown
from jinja2 import Template
from publish import __version__ as packa... | publish/output.py | import logging
import os
import shutil
import subprocess # nosec
import uuid
from tempfile import mkdtemp
from textwrap import fill
from typing import Iterable, Generator, Optional, Sequence
from pkg_resources import resource_string
import markdown
from jinja2 import Template
from publish import __version__ as packa... | 0.718397 | 0.207496 |
import pytest
from clean.entities.token import UserToken
from clean.auth.abs import DecodeToken
from clean.auth.decorator import DecoratorBuilder
from clean.exceptions import AuthException
class VerifyTokenAuth(DecodeToken):
def get_token(self):
raw = self.raw_token.get('token', None)
if raw is ... | tests/clean/auth/test_decorator_builder.py | import pytest
from clean.entities.token import UserToken
from clean.auth.abs import DecodeToken
from clean.auth.decorator import DecoratorBuilder
from clean.exceptions import AuthException
class VerifyTokenAuth(DecodeToken):
def get_token(self):
raw = self.raw_token.get('token', None)
if raw is ... | 0.577853 | 0.224682 |
from flask import Flask, json, render_template
from threading import Thread
from flask_socketio import SocketIO
from graphqlclient import GraphQLClient
import serial, time, serial.tools.list_ports, datetime, socket
app = Flask(__name__)
app.config['SECRET_KEY'] = 'SECRET!'
socketio = SocketIO(app)
uuid_last = ''
data... | app.py | from flask import Flask, json, render_template
from threading import Thread
from flask_socketio import SocketIO
from graphqlclient import GraphQLClient
import serial, time, serial.tools.list_ports, datetime, socket
app = Flask(__name__)
app.config['SECRET_KEY'] = 'SECRET!'
socketio = SocketIO(app)
uuid_last = ''
data... | 0.254602 | 0.086632 |
from pero.properties import *
from pero import Legend, LegendBox
from .. enums import *
from . graphics import InGraphics, OutGraphics
class OutLegend(OutGraphics):
"""
OutLegend provides a wrapper for the pero.LegendBox glyph to draw the chart
legend outside the main data frame.
Properties:
... | perrot/chart/legends.py |
from pero.properties import *
from pero import Legend, LegendBox
from .. enums import *
from . graphics import InGraphics, OutGraphics
class OutLegend(OutGraphics):
"""
OutLegend provides a wrapper for the pero.LegendBox glyph to draw the chart
legend outside the main data frame.
Properties:
... | 0.910376 | 0.572006 |
from typing import Optional
from pydantic import BaseModel, EmailStr, Field
from enum import Enum
from typing import List
class Gender(str, Enum): # Gender에 들어갈수있는 종류 4개 미리 선언
male = 'male'
female = 'female'
other = 'other'
not_given = 'not_given'
class UserSchema(BaseModel):
# 앱으로부터 받은 유저데이터가 Mo... | app/server/models/user.py | from typing import Optional
from pydantic import BaseModel, EmailStr, Field
from enum import Enum
from typing import List
class Gender(str, Enum): # Gender에 들어갈수있는 종류 4개 미리 선언
male = 'male'
female = 'female'
other = 'other'
not_given = 'not_given'
class UserSchema(BaseModel):
# 앱으로부터 받은 유저데이터가 Mo... | 0.549882 | 0.517998 |
import boto3
import click
import json
from operator import itemgetter
from sys import exit
@click.command()
@click.option('-r', '--region', help='AWS region to use')
@click.option('-z', '--availability-zone', multiple=True,
help="Availability Zones to use, use 'all' for all zones, multiple invocations s... | spottpreis.py | import boto3
import click
import json
from operator import itemgetter
from sys import exit
@click.command()
@click.option('-r', '--region', help='AWS region to use')
@click.option('-z', '--availability-zone', multiple=True,
help="Availability Zones to use, use 'all' for all zones, multiple invocations s... | 0.131898 | 0.094845 |
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form... | src/scripting/parser/parser.py |
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
# 2. Redistributions in binary form... | 0.680666 | 0.055643 |
from ..DB.Repositorio_Grado_De_Ocupacion_Por_Plazas_INE import RepositoryGradoOcupacionPlazasINE as DBRepository
from ..Utilidades.Conversores import Conversores as Conversor
def obtener_grado_de_ocupacion_por_tanto_por_cien_por_plazas_en_ciudad_en_anio(Ciudad, Anio):
"""
Dado una ciudad y un año obtiene el g... | controllers/grado de ocupacion por plazas ine_controller.py | from ..DB.Repositorio_Grado_De_Ocupacion_Por_Plazas_INE import RepositoryGradoOcupacionPlazasINE as DBRepository
from ..Utilidades.Conversores import Conversores as Conversor
def obtener_grado_de_ocupacion_por_tanto_por_cien_por_plazas_en_ciudad_en_anio(Ciudad, Anio):
"""
Dado una ciudad y un año obtiene el g... | 0.398992 | 0.577495 |
from __future__ import unicode_literals
from django.http import Http404
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from rolepermissions.exceptions import RoleDo... | rolepermissions/shortcuts.py | from __future__ import unicode_literals
from django.http import Http404
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from rolepermissions.exceptions import RoleDo... | 0.444565 | 0.092237 |
from __future__ import absolute_import, division, print_function
import operator
import bisect
from . import DDesc, Capabilities
def cat_descriptor_iter(ddlist):
for i, dd in enumerate(ddlist):
for el in dd:
yield el
class Cat_DDesc(DDesc):
"""
A Blaze data descriptor which concate... | blaze/datadescriptor/cat_data_descriptor.py | from __future__ import absolute_import, division, print_function
import operator
import bisect
from . import DDesc, Capabilities
def cat_descriptor_iter(ddlist):
for i, dd in enumerate(ddlist):
for el in dd:
yield el
class Cat_DDesc(DDesc):
"""
A Blaze data descriptor which concate... | 0.637031 | 0.313433 |
from typing import List, Optional, Union
import numpy as np
import pandas as pd
import pytest
import scipy.sparse as sps
import tabmat as tm
from tabmat import from_pandas
from tabmat.constructor import _split_sparse_and_dense_parts
from tabmat.dense_matrix import DenseMatrix
from tabmat.ext.sparse import csr_dense_s... | tests/test_split_matrix.py | from typing import List, Optional, Union
import numpy as np
import pandas as pd
import pytest
import scipy.sparse as sps
import tabmat as tm
from tabmat import from_pandas
from tabmat.constructor import _split_sparse_and_dense_parts
from tabmat.dense_matrix import DenseMatrix
from tabmat.ext.sparse import csr_dense_s... | 0.777215 | 0.729086 |
from utils.env import EnvStore
import os
import json
import pymqi
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# function to establish connection to MQ Queue Manager
def connect():
logger.info('Establising Connection with MQ Server')
try:
cd = None
... | Python/basicsubscribe.py | from utils.env import EnvStore
import os
import json
import pymqi
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# function to establish connection to MQ Queue Manager
def connect():
logger.info('Establising Connection with MQ Server')
try:
cd = None
... | 0.373876 | 0.079353 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... | courses/migrations/0001_initial.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... | 0.551574 | 0.150903 |
__author__ = "<NAME>"
__email__ = "schmidt89 at informatik.uni-marburg.de"
from androlyze.log.Log import log
from androlyze.storage.exception import StorageException
class ImportStorageInterface:
'''
Interface for the import storage
'''
def create_entry_for_apk(self, apk, update = False, tag = None)... | androlyze/storage/ImportStorageInterface.py |
__author__ = "<NAME>"
__email__ = "schmidt89 at informatik.uni-marburg.de"
from androlyze.log.Log import log
from androlyze.storage.exception import StorageException
class ImportStorageInterface:
'''
Interface for the import storage
'''
def create_entry_for_apk(self, apk, update = False, tag = None)... | 0.63409 | 0.253185 |
from git import Repo, db
import os.path
import re
import sys
import glob
from parser_java_kotlin import Parser
from pathlib import Path
from tqdm import tqdm
class ChangedMethodsFinder:
file_extension = {'java': '.*.java', 'kotlin':'.*.kt'}
def __init__(self, path='.'):
self.repo = None
self.... | data_aggregation/get_java_methods.py |
from git import Repo, db
import os.path
import re
import sys
import glob
from parser_java_kotlin import Parser
from pathlib import Path
from tqdm import tqdm
class ChangedMethodsFinder:
file_extension = {'java': '.*.java', 'kotlin':'.*.kt'}
def __init__(self, path='.'):
self.repo = None
self.... | 0.233794 | 0.137851 |
from webparser.youtube import api
from django.db import transaction
from django.utils import timezone
from . import models
from core import models as core_models
def video__get(youtube_id):
try:
return models.Video.objects.get(youtube_id = youtube_id)
except models.Video.DoesNotExist:
return ... | httpserver/youtube/api.py | from webparser.youtube import api
from django.db import transaction
from django.utils import timezone
from . import models
from core import models as core_models
def video__get(youtube_id):
try:
return models.Video.objects.get(youtube_id = youtube_id)
except models.Video.DoesNotExist:
return ... | 0.375477 | 0.089415 |
from __future__ import print_function
# ------------------------------------------------------------------------------------------------
# Copyright (c) 2016 Microsoft Corporation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# associated documentation files (the... | Python_Examples/bridging.py | from __future__ import print_function
# ------------------------------------------------------------------------------------------------
# Copyright (c) 2016 Microsoft Corporation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
# associated documentation files (the... | 0.357007 | 0.162546 |
from __future__ import print_function
import sys
import time
import Pyro4
import bench
if sys.version_info < (3, 0):
input = raw_input
uri = input("Uri of benchmark server? ").strip()
object = Pyro4.core.Proxy(uri)
object._pyroBind()
assert "oneway" in object._pyroOneway # make sure this method ... | examples/benchmark/client.py | from __future__ import print_function
import sys
import time
import Pyro4
import bench
if sys.version_info < (3, 0):
input = raw_input
uri = input("Uri of benchmark server? ").strip()
object = Pyro4.core.Proxy(uri)
object._pyroBind()
assert "oneway" in object._pyroOneway # make sure this method ... | 0.286568 | 0.128197 |