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 __future__ import absolute_import
from . import internals
from . import utils
class DataType:
"""Contains the possible data types which can be represented in an Element.
Class attributes:
BOOL Boolean
CHAR Char
BYTE Unsigned 8 bit value
I... | Mayank/blpapi_python3.5.5/build/lib.linux-i686-2.7/blpapi/datatype.py | from __future__ import absolute_import
from . import internals
from . import utils
class DataType:
"""Contains the possible data types which can be represented in an Element.
Class attributes:
BOOL Boolean
CHAR Char
BYTE Unsigned 8 bit value
I... | 0.78968 | 0.21211 |
import json
import os
import shutil
import tempfile
import traceback
from io import BytesIO
from typing import List
from zipfile import ZipFile
import nvflare.fuel.hci.file_transfer_defs as ftd
from nvflare.apis.job_def import JobMetaKey
from nvflare.apis.job_def_manager_spec import JobDefManagerSpec
from nvflare.fuel... | nvflare/fuel/hci/server/file_transfer.py | import json
import os
import shutil
import tempfile
import traceback
from io import BytesIO
from typing import List
from zipfile import ZipFile
import nvflare.fuel.hci.file_transfer_defs as ftd
from nvflare.apis.job_def import JobMetaKey
from nvflare.apis.job_def_manager_spec import JobDefManagerSpec
from nvflare.fuel... | 0.477554 | 0.118436 |
from kiali_qe.entities import EntityBase
from kiali_qe.components.enums import MeshWideTLSType
class Overview(EntityBase):
def __init__(self, overview_type, namespace, items,
config_status=None,
healthy=0, unhealthy=0, degraded=0, na=0, idle=0,
tls_type=MeshWide... | kiali_qe/entities/overview.py | from kiali_qe.entities import EntityBase
from kiali_qe.components.enums import MeshWideTLSType
class Overview(EntityBase):
def __init__(self, overview_type, namespace, items,
config_status=None,
healthy=0, unhealthy=0, degraded=0, na=0, idle=0,
tls_type=MeshWide... | 0.64232 | 0.124612 |
from typing import Optional, Tuple
import SimpleITK
import numpy as np
import pytest
import sys
from pathlib import Path
import nnunet.inference.predict_simple
from nnunet.inference.predict_simple import main
RESOURCES_DIR = Path(__file__).parent / "resources"
TASK004_HIPPOCAMPUS_PRETRAINED_DIR = RESOURCES_DIR / "pr... | tests/test_prediction.py | from typing import Optional, Tuple
import SimpleITK
import numpy as np
import pytest
import sys
from pathlib import Path
import nnunet.inference.predict_simple
from nnunet.inference.predict_simple import main
RESOURCES_DIR = Path(__file__).parent / "resources"
TASK004_HIPPOCAMPUS_PRETRAINED_DIR = RESOURCES_DIR / "pr... | 0.627837 | 0.25097 |
from functools import wraps
from flask import render_template
from flask_babelex import gettext
import pgadmin.browser.server_groups.servers.databases as database
from config import PG_DEFAULT_DRIVER
from pgadmin.browser.server_groups.servers.databases.schemas.utils \
import SchemaChildModule
from pgadmin.browser... | pgAdmin/browser/server_groups/servers/databases/schemas/catalog_objects/__init__.py | from functools import wraps
from flask import render_template
from flask_babelex import gettext
import pgadmin.browser.server_groups.servers.databases as database
from config import PG_DEFAULT_DRIVER
from pgadmin.browser.server_groups.servers.databases.schemas.utils \
import SchemaChildModule
from pgadmin.browser... | 0.693888 | 0.129513 |
import datetime
import random
from datetime import datetime
from textwrap import wrap
from typing import Union
import discord
from discord.ext import commands
from lib.emotes import basic_emoji
class Miscellaneous(commands.Cog):
"""Other interesting commands"""
def __init__(self, bot):
self.bot = b... | bot/cogs/miscellaneous_cog.py | import datetime
import random
from datetime import datetime
from textwrap import wrap
from typing import Union
import discord
from discord.ext import commands
from lib.emotes import basic_emoji
class Miscellaneous(commands.Cog):
"""Other interesting commands"""
def __init__(self, bot):
self.bot = b... | 0.644673 | 0.107437 |
from __future__ import annotations
import abc
from typing import NamedTuple, Union, Dict
from conflowgen.domain_models.data_types.mode_of_transport import ModeOfTransport
class ContainersAndTEUContainerFlowPair(NamedTuple):
"""
This is a pair of two container flows, i.e. the number of containers moving from... | conflowgen/posthoc_analysis/abstract_posthoc_analysis.py | from __future__ import annotations
import abc
from typing import NamedTuple, Union, Dict
from conflowgen.domain_models.data_types.mode_of_transport import ModeOfTransport
class ContainersAndTEUContainerFlowPair(NamedTuple):
"""
This is a pair of two container flows, i.e. the number of containers moving from... | 0.918745 | 0.4206 |
import json
import xml.etree.ElementTree as ET
from cafe.engine.models.base import AutoMarshallingModel
from cafe.engine.models.base import AutoMarshallingListModel
from cloudcafe.compute.common.constants import Constants
from cloudcafe.compute.common.equality_tools import EqualityTools
class FlavorAccess(AutoMarsha... | cloudcafe/compute/flavors_api/models/flavor_access.py | import json
import xml.etree.ElementTree as ET
from cafe.engine.models.base import AutoMarshallingModel
from cafe.engine.models.base import AutoMarshallingListModel
from cloudcafe.compute.common.constants import Constants
from cloudcafe.compute.common.equality_tools import EqualityTools
class FlavorAccess(AutoMarsha... | 0.490236 | 0.052255 |
import logging
import types
from etcd import EtcdResult
from mock import Mock
from calico.etcdutils import PathDispatcher
from calico.felix.test.base import BaseTestCase
_log = logging.getLogger(__name__)
SAME_AS_KEY = object()
class _TestPathDispatcherBase(BaseTestCase):
"""
Abstract base class for Dispa... | calico/test/test_etcdutils.py | import logging
import types
from etcd import EtcdResult
from mock import Mock
from calico.etcdutils import PathDispatcher
from calico.felix.test.base import BaseTestCase
_log = logging.getLogger(__name__)
SAME_AS_KEY = object()
class _TestPathDispatcherBase(BaseTestCase):
"""
Abstract base class for Dispa... | 0.570092 | 0.179818 |
from PlaystationHandler import PlayStationHandler
from geometry_msgs.msg import Twist,TwistStamped
import rospy
class PlayStationDiffDrive(PlayStationHandler):
def __init__(self,message_type):
PlayStationHandler.__init__(self)
self.rate=rospy.Rate(rospy.get_param("~rate",10))
self.active_ro... | src/Match_Mobile_Robotics/general_hardware_helper/ps4_controller/src/ps4_controller/PlayStationDiffDrive.py | from PlaystationHandler import PlayStationHandler
from geometry_msgs.msg import Twist,TwistStamped
import rospy
class PlayStationDiffDrive(PlayStationHandler):
def __init__(self,message_type):
PlayStationHandler.__init__(self)
self.rate=rospy.Rate(rospy.get_param("~rate",10))
self.active_ro... | 0.344774 | 0.117193 |
import librosa
import argparse
import numpy as np
import warnings
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import scale as mscale
from matplotlib import transforms as mtransforms
from separator import AudioSeparator
import librosa.display
import os
class MelScale(mscale... | separation_examples_and_compute_metrics.py | import librosa
import argparse
import numpy as np
import warnings
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import scale as mscale
from matplotlib import transforms as mtransforms
from separator import AudioSeparator
import librosa.display
import os
class MelScale(mscale... | 0.778902 | 0.527499 |
from robot.utils import normalize, normalize_whitespace, RecommendationFinder
from .tokens import Token
class Settings:
names = ()
aliases = {}
multi_use = (
'Metadata',
'Library',
'Resource',
'Variables'
)
single_value = (
'Resource',
'Test Timeou... | src/robot/parsing/lexer/settings.py |
from robot.utils import normalize, normalize_whitespace, RecommendationFinder
from .tokens import Token
class Settings:
names = ()
aliases = {}
multi_use = (
'Metadata',
'Library',
'Resource',
'Variables'
)
single_value = (
'Resource',
'Test Timeou... | 0.664758 | 0.240412 |
import os
import sys
import boto3
import time
import acme
from botocore.exceptions import ClientError, WaiterError
LOGGER = acme.get_logger(__name__)
# AWS SSM Client
SSM_CLIENT = boto3.client('ssm')
def generate_csr(common_name, instance_id, platform, subject_alternative_names, path):
"""
Use AWS SSM Run... | platforms/linux-aws-ssm/src/app.py |
import os
import sys
import boto3
import time
import acme
from botocore.exceptions import ClientError, WaiterError
LOGGER = acme.get_logger(__name__)
# AWS SSM Client
SSM_CLIENT = boto3.client('ssm')
def generate_csr(common_name, instance_id, platform, subject_alternative_names, path):
"""
Use AWS SSM Run... | 0.412885 | 0.123471 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from torch.nn import init
__all__ = ["MobileNetV3", "mobilenet_v3_large", "mo... | src/lib/models/networks/mobilenetv3.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from torch.nn import init
__all__ = ["MobileNetV3", "mobilenet_v3_large", "mo... | 0.934328 | 0.311034 |
from __future__ import print_function
import argparse
import json
import time
from apollo import accessible_organisms
from apollo.util import CnOrGuess, GuessCn
from arrow.apollo import get_apollo_instance
from webapollo import UserObj, handle_credentials
if __name__ == '__main__':
parser = argparse.ArgumentPa... | tools/apollo/export.py | from __future__ import print_function
import argparse
import json
import time
from apollo import accessible_organisms
from apollo.util import CnOrGuess, GuessCn
from arrow.apollo import get_apollo_instance
from webapollo import UserObj, handle_credentials
if __name__ == '__main__':
parser = argparse.ArgumentPa... | 0.317215 | 0.091018 |
import sympy as sy
from .testfunction import TestMinFunction
from .meta import symbolize, substitute
def Rosenbrock(a=1, b=100):
"""
Creates the Rosenbrock function object.
f(x,y) = (a-x)**2 + b*(y-x**2)**2
a,b are constants, tipically a is set to 1 and b is set to 100.
The global minimum
... | src/dewloosh/math/function/functions.py | import sympy as sy
from .testfunction import TestMinFunction
from .meta import symbolize, substitute
def Rosenbrock(a=1, b=100):
"""
Creates the Rosenbrock function object.
f(x,y) = (a-x)**2 + b*(y-x**2)**2
a,b are constants, tipically a is set to 1 and b is set to 100.
The global minimum
... | 0.532668 | 0.597461 |
from pkg_resources import parse_version
import kaitaistruct
from kaitaistruct import KaitaiStruct, KaitaiStream, BytesIO
import collections
if parse_version(kaitaistruct.__version__) < parse_version('0.9'):
raise Exception("Incompatible Kaitai Struct Python API: 0.9 or later is required, but you have %s" % (kait... | polyfile/kaitai/parsers/lzh.py |
from pkg_resources import parse_version
import kaitaistruct
from kaitaistruct import KaitaiStruct, KaitaiStream, BytesIO
import collections
if parse_version(kaitaistruct.__version__) < parse_version('0.9'):
raise Exception("Incompatible Kaitai Struct Python API: 0.9 or later is required, but you have %s" % (kait... | 0.303835 | 0.13201 |
from datetime import datetime
from uuid import UUID
from byceps.services.shop.order import service as order_service
from byceps.services.shop.order.transfer.number import OrderNumber
from byceps.services.shop.order.transfer.order import (
Order,
Orderer,
PaymentState,
)
from byceps.services.shop.shop.trans... | tests/unit/services/shop/order/test_order_payment_state.py | from datetime import datetime
from uuid import UUID
from byceps.services.shop.order import service as order_service
from byceps.services.shop.order.transfer.number import OrderNumber
from byceps.services.shop.order.transfer.order import (
Order,
Orderer,
PaymentState,
)
from byceps.services.shop.shop.trans... | 0.731346 | 0.397558 |
import re
from calendar import day_abbr, day_name, month_abbr, month_name
from datetime import datetime as datetime_
from datetime import timedelta, timezone
from time import localtime
tokens = r"H{1,2}|h{1,2}|m{1,2}|s{1,2}|S{1,6}|YYYY|YY|M{1,4}|D{1,4}|Z{1,2}|zz|A|X|x|E|Q|dddd|ddd|d"
pattern = re.compile(r"(?:{0})|\[... | loguru/_datetime.py | import re
from calendar import day_abbr, day_name, month_abbr, month_name
from datetime import datetime as datetime_
from datetime import timedelta, timezone
from time import localtime
tokens = r"H{1,2}|h{1,2}|m{1,2}|s{1,2}|S{1,6}|YYYY|YY|M{1,4}|D{1,4}|Z{1,2}|zz|A|X|x|E|Q|dddd|ddd|d"
pattern = re.compile(r"(?:{0})|\[... | 0.395718 | 0.329109 |
class Product:
def __init__(self, product_id, product_price):
self.product_id = product_id # which product
self.product_price = product_price # product_price
self.stock = 0 # temporary stock will be zero
def add_stock(self, quantity):
self.stock = self.stock + quantity
d... | Shop/shop.py | class Product:
def __init__(self, product_id, product_price):
self.product_id = product_id # which product
self.product_price = product_price # product_price
self.stock = 0 # temporary stock will be zero
def add_stock(self, quantity):
self.stock = self.stock + quantity
d... | 0.343782 | 0.233684 |
from __future__ import absolute_import, print_function, unicode_literals
from pyfaup.faup import Faup
from modules import AbstractBolt, load_whitelist, text2urls_whitelisted
from modules.attachments import MailAttachments
class Urls(AbstractBolt):
outputs = ['sha256_random', 'results']
def initialize(self,... | src/bolts/urls.py | from __future__ import absolute_import, print_function, unicode_literals
from pyfaup.faup import Faup
from modules import AbstractBolt, load_whitelist, text2urls_whitelisted
from modules.attachments import MailAttachments
class Urls(AbstractBolt):
outputs = ['sha256_random', 'results']
def initialize(self,... | 0.61173 | 0.1844 |
import argparse, os, pathlib, logging, json, copy, pickle
import pandas as pd
from datetime import datetime, timezone
from typing import Optional
from distutils.util import strtobool
from importlib.metadata import version
from emhass.retrieve_hass import retrieve_hass
from emhass.forecast import forecast
from emhass.... | src/emhass/command_line.py |
import argparse, os, pathlib, logging, json, copy, pickle
import pandas as pd
from datetime import datetime, timezone
from typing import Optional
from distutils.util import strtobool
from importlib.metadata import version
from emhass.retrieve_hass import retrieve_hass
from emhass.forecast import forecast
from emhass.... | 0.728169 | 0.171408 |
import fire
from pyhappn.happn import Relations
from pyhappn.happn import User
from pyhappn.settings import TOKEN
class HappnCli(object):
"""Cli Happn."""
def like_all(self):
"""Like all"""
user_inst = User(TOKEN)
device_list = user_inst.get_device_list()
user_inst.set_devic... | cli.py | import fire
from pyhappn.happn import Relations
from pyhappn.happn import User
from pyhappn.settings import TOKEN
class HappnCli(object):
"""Cli Happn."""
def like_all(self):
"""Like all"""
user_inst = User(TOKEN)
device_list = user_inst.get_device_list()
user_inst.set_devic... | 0.29088 | 0.072834 |
import pytest
from ..manager import ZuulManager
from ..exceptions import ZuulManagerConfig
@pytest.mark.unit
@pytest.mark.zuul_manager
class TestZuulConnector:
def test_raise_when_no_user_key_file(self, path_to_test_file):
with pytest.raises(ZuulManagerConfig):
ZuulManager(host="host",
... | acid/features/zuul_manager/tests/test_manager.py | import pytest
from ..manager import ZuulManager
from ..exceptions import ZuulManagerConfig
@pytest.mark.unit
@pytest.mark.zuul_manager
class TestZuulConnector:
def test_raise_when_no_user_key_file(self, path_to_test_file):
with pytest.raises(ZuulManagerConfig):
ZuulManager(host="host",
... | 0.309545 | 0.265321 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
def ParserArgs():
"""Args Parser."""
parser = argparse.ArgumentParser()
parser.add_argument("--debug", default=False, action="store_true",
help="set debug mode")
... | experimental/args.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
def ParserArgs():
"""Args Parser."""
parser = argparse.ArgumentParser()
parser.add_argument("--debug", default=False, action="store_true",
help="set debug mode")
... | 0.800224 | 0.05455 |
import os
from datetime import date
import shutil
import pandas as pd
import urllib.request
import glob
# Name of the dataset
ds_name = 'WQP'
# Download directory
proj_dir = '/gpfs/space/home/holgerv/gis_holgerv/river_quality'
dl_dir = os.path.join(proj_dir, 'data', ds_name, 'raw', f'download_{date.today(... | preprocessing/WQP/wqp_download.py | import os
from datetime import date
import shutil
import pandas as pd
import urllib.request
import glob
# Name of the dataset
ds_name = 'WQP'
# Download directory
proj_dir = '/gpfs/space/home/holgerv/gis_holgerv/river_quality'
dl_dir = os.path.join(proj_dir, 'data', ds_name, 'raw', f'download_{date.today(... | 0.273283 | 0.110856 |
from msrest.serialization import Model
class NotificationSubscriptionUpdateParameters(Model):
"""NotificationSubscriptionUpdateParameters.
:param admin_settings: Admin-managed settings for the subscription. Only applies to subscriptions where the subscriber is a group.
:type admin_settings: :cla... | venv/lib/python3.8/site-packages/vsts/notification/v4_0/models/notification_subscription_update_parameters.py |
from msrest.serialization import Model
class NotificationSubscriptionUpdateParameters(Model):
"""NotificationSubscriptionUpdateParameters.
:param admin_settings: Admin-managed settings for the subscription. Only applies to subscriptions where the subscriber is a group.
:type admin_settings: :cla... | 0.877562 | 0.17901 |
try:
from html.parser import HTMLParser
except ImportError:
from HTMLParser import HTMLParser
import re
class AngularGettextHTMLParser(HTMLParser):
"""Parse HTML to find translate directives.
Note: This will not cope with nested tags (which I don't think make any
sense)
"""
def __init_... | horizon/utils/babel_extract_angular.py |
try:
from html.parser import HTMLParser
except ImportError:
from HTMLParser import HTMLParser
import re
class AngularGettextHTMLParser(HTMLParser):
"""Parse HTML to find translate directives.
Note: This will not cope with nested tags (which I don't think make any
sense)
"""
def __init_... | 0.713032 | 0.175998 |
import discord, sqlite3, asyncio
from discord.ext import commands
from discord_slash import cog_ext, ButtonStyle
from discord_slash.utils.manage_commands import create_option
from discord_slash.utils.manage_components import *
class Slash(commands.Cog):
def __init__(self, bot):
self.bot = bot
@cog_ext... | cogs/card.py | import discord, sqlite3, asyncio
from discord.ext import commands
from discord_slash import cog_ext, ButtonStyle
from discord_slash.utils.manage_commands import create_option
from discord_slash.utils.manage_components import *
class Slash(commands.Cog):
def __init__(self, bot):
self.bot = bot
@cog_ext... | 0.304042 | 0.150746 |
import pygame
import random
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
class Block(pygame.sprite.Sprite):
"""
This class represents the ball
It derives from the "Sprite" class in Pygame
"""
def __init__(self, color, width, height):
... | pygame/hungry lion/hungry.py | import pygame
import random
# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
class Block(pygame.sprite.Sprite):
"""
This class represents the ball
It derives from the "Sprite" class in Pygame
"""
def __init__(self, color, width, height):
... | 0.453988 | 0.356755 |
from builtins import hasattr
import logging
import re
from urllib.parse import urljoin, urlencode
import requests
from django.conf import settings
from django.contrib.auth.models import User
from django.utils import timezone
from applications.constants import INTEGRATION_PREFIX
from applications.models import Bootcam... | hubspot/api.py | from builtins import hasattr
import logging
import re
from urllib.parse import urljoin, urlencode
import requests
from django.conf import settings
from django.contrib.auth.models import User
from django.utils import timezone
from applications.constants import INTEGRATION_PREFIX
from applications.models import Bootcam... | 0.776792 | 0.211946 |
import shutil
from pathlib import Path
from typing import Dict, List, Union
import lmdb
from docarray import Document, DocumentArray
LMDB_MAP_SIZE = 100 * 1024 * 1024 * 1024
class DocStorage:
"""The backend storage engine of Documents"""
def __init__(
self, path: Union[str, Path], serialize_config:... | annlite/storage/kv.py | import shutil
from pathlib import Path
from typing import Dict, List, Union
import lmdb
from docarray import Document, DocumentArray
LMDB_MAP_SIZE = 100 * 1024 * 1024 * 1024
class DocStorage:
"""The backend storage engine of Documents"""
def __init__(
self, path: Union[str, Path], serialize_config:... | 0.75985 | 0.214897 |
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from app.router import KaKao, Record, Images, Profile, Objective, Apple
from app.database import Tables
from app.da... | main.py | from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from starlette.exceptions import HTTPException as StarletteHTTPException
from app.router import KaKao, Record, Images, Profile, Objective, Apple
from app.database import Tables
from app.da... | 0.464173 | 0.09782 |
import os
import unittest
from lime.lime_text import LimeTextExplainer as OriginalLimeTextExplainer
from xai.explainer.explainer_exceptions import ExplainerUninitializedError
from xai.explainer.text.lime_text_explainer import LimeTextExplainer
class TestLimeTextExplainer(unittest.TestCase):
def setUp(self) ->... | tests/explainer/test_lime_text_explainer.py |
import os
import unittest
from lime.lime_text import LimeTextExplainer as OriginalLimeTextExplainer
from xai.explainer.explainer_exceptions import ExplainerUninitializedError
from xai.explainer.text.lime_text_explainer import LimeTextExplainer
class TestLimeTextExplainer(unittest.TestCase):
def setUp(self) ->... | 0.502197 | 0.304869 |
import json
from aiozk import ZKClient
from aiozk.exc import NoNode, NodeExists
from aiozk.protocol import AuthRequest
from vmshepherd.runtime import AbstractRuntimeData
class ZookeeperDriver(AbstractRuntimeData):
def __init__(self, instance_id, config):
super().__init__(instance_id)
self.reconfi... | src/vmshepherd_zookeeper_driver/__init__.py | import json
from aiozk import ZKClient
from aiozk.exc import NoNode, NodeExists
from aiozk.protocol import AuthRequest
from vmshepherd.runtime import AbstractRuntimeData
class ZookeeperDriver(AbstractRuntimeData):
def __init__(self, instance_id, config):
super().__init__(instance_id)
self.reconfi... | 0.403802 | 0.048971 |
from nate.svonet.graph_svo import generate_ticks, find_max_burst
import networkx as nx
import stop_words as sw
import copy
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.ticker import MaxNLocator
import numpy as np
from multiprocessing impo... | nate/svonet/svo_degree_over_time.py | from nate.svonet.graph_svo import generate_ticks, find_max_burst
import networkx as nx
import stop_words as sw
import copy
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.ticker import MaxNLocator
import numpy as np
from multiprocessing impo... | 0.456894 | 0.368974 |
import requests
from bs4 import BeautifulSoup, Tag
class LinkPreview:
"""
A teaser of a website, containing a title, description, and a preview image.
The website is fetched from 'url' and the preview is generated from html.
Uses the algorithm described here:
https://andrejgajdos.com/how-to-create... | backend/service/linkpreview.py | import requests
from bs4 import BeautifulSoup, Tag
class LinkPreview:
"""
A teaser of a website, containing a title, description, and a preview image.
The website is fetched from 'url' and the preview is generated from html.
Uses the algorithm described here:
https://andrejgajdos.com/how-to-create... | 0.502686 | 0.155174 |
import pigpio
class Servo:
def __init__(self, gpio, min_value=0, max_value=180, min_pulse=0.5, max_pulse=2.4, frequency=50):
if min_pulse < 0:
raise ValueError("The value of the argument min_pulse is out of range.")
if max_pulse < 0:
raise ValueError("The value of the argume... | src/piservo/servo.py | import pigpio
class Servo:
def __init__(self, gpio, min_value=0, max_value=180, min_pulse=0.5, max_pulse=2.4, frequency=50):
if min_pulse < 0:
raise ValueError("The value of the argument min_pulse is out of range.")
if max_pulse < 0:
raise ValueError("The value of the argume... | 0.639961 | 0.189184 |
import pytest
from sanic.blueprints import Blueprint
from sanic.exceptions import HeaderExpectationFailed
from sanic.request import StreamBuffer
from sanic.response import stream, text
from sanic.views import CompositionView, HTTPMethodView
from sanic.views import stream as stream_decorator
data = "abc" * 10000000
... | tests/test_request_stream.py | import pytest
from sanic.blueprints import Blueprint
from sanic.exceptions import HeaderExpectationFailed
from sanic.request import StreamBuffer
from sanic.response import stream, text
from sanic.views import CompositionView, HTTPMethodView
from sanic.views import stream as stream_decorator
data = "abc" * 10000000
... | 0.574753 | 0.330525 |
from papermill.iorw import load_notebook_node
import papermill as pm
import yaml
import os
import shutil
import copy
import numpy as np
import json
import plotly
import IPython
from IPython.display import display as idisplay, Video, Image
from base64 import b64decode, b64encode
from .input_types import parse
class DB(... | hublib/tool/rw.py | from papermill.iorw import load_notebook_node
import papermill as pm
import yaml
import os
import shutil
import copy
import numpy as np
import json
import plotly
import IPython
from IPython.display import display as idisplay, Video, Image
from base64 import b64decode, b64encode
from .input_types import parse
class DB(... | 0.368974 | 0.186428 |
import os
import re
from time import time
import numpy as np
import pypinyin
import tensorflow as tf
from pypinyin import lazy_pinyin
from datasets import audio
from hparams import hparams
from tacotron.synthesizerp import Synthesizer
def pinyin_sentence(sentences):
pinyin = lazy_pinyin(sentences, style=pypinyi... | test.py | import os
import re
from time import time
import numpy as np
import pypinyin
import tensorflow as tf
from pypinyin import lazy_pinyin
from datasets import audio
from hparams import hparams
from tacotron.synthesizerp import Synthesizer
def pinyin_sentence(sentences):
pinyin = lazy_pinyin(sentences, style=pypinyi... | 0.146148 | 0.211743 |
from django.test import TestCase
from mockldap import MockLdap
from ..ldap.actions import LDAPAccountAdder
from ..ldap.actions import LDAPAccountUpdater
from ..ldap import utils
from ..models import PendingUser
class LDAPFunctionsTestCase(TestCase):
"""
Warning : you must update your project settings in orde... | accounts/tests/test_ldap_functions.py | from django.test import TestCase
from mockldap import MockLdap
from ..ldap.actions import LDAPAccountAdder
from ..ldap.actions import LDAPAccountUpdater
from ..ldap import utils
from ..models import PendingUser
class LDAPFunctionsTestCase(TestCase):
"""
Warning : you must update your project settings in orde... | 0.571886 | 0.330931 |
import maya.cmds
import maya.OpenMaya
import pymel.core as pm
import imath
import math
import IECore
import IECoreScene
import IECoreMaya
class FromMayaInstancerConverter( IECoreMaya.TestCase ) :
def setUp( self ) :
super( FromMayaInstancerConverter, self ).setUp()
def makeScene( self ):
maya.cmds.poly... | test/IECoreMaya/FromMayaInstancerConverterTest.py |
import maya.cmds
import maya.OpenMaya
import pymel.core as pm
import imath
import math
import IECore
import IECoreScene
import IECoreMaya
class FromMayaInstancerConverter( IECoreMaya.TestCase ) :
def setUp( self ) :
super( FromMayaInstancerConverter, self ).setUp()
def makeScene( self ):
maya.cmds.poly... | 0.529993 | 0.395368 |
import logging
import voluptuous as vol
from bluepy.btle import BTLEDisconnectError
from bluepy.btle import BTLEManagementError
from homeassistant import config_entries
from homeassistant.const import CONF_MAC
from homeassistant.const import CONF_NAME
from homeassistant.helpers import device_registry
from radiacode.tr... | custom_components/radiacode_bt/config_flow.py | import logging
import voluptuous as vol
from bluepy.btle import BTLEDisconnectError
from bluepy.btle import BTLEManagementError
from homeassistant import config_entries
from homeassistant.const import CONF_MAC
from homeassistant.const import CONF_NAME
from homeassistant.helpers import device_registry
from radiacode.tr... | 0.689724 | 0.112065 |
from binascii import hexlify
from typing import TYPE_CHECKING
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.backends import default_backend
import six
from .._internal.client_credential_base import ClientCredentialBase
if TYPE_CHECKING:
fr... | sdk/identity/azure-identity/azure/identity/_credentials/certificate.py | from binascii import hexlify
from typing import TYPE_CHECKING
from cryptography import x509
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.backends import default_backend
import six
from .._internal.client_credential_base import ClientCredentialBase
if TYPE_CHECKING:
fr... | 0.800848 | 0.229654 |
import abc
import re
import six
@six.add_metaclass(abc.ABCMeta)
class retry_base(object):
"""Abstract base class for retry strategies."""
@abc.abstractmethod
def __call__(self, retry_state):
pass
def __and__(self, other):
return retry_all(self, other)
def __or__(self, other):
... | tenacity/retry.py |
import abc
import re
import six
@six.add_metaclass(abc.ABCMeta)
class retry_base(object):
"""Abstract base class for retry strategies."""
@abc.abstractmethod
def __call__(self, retry_state):
pass
def __and__(self, other):
return retry_all(self, other)
def __or__(self, other):
... | 0.829388 | 0.086671 |
from os.path import join, dirname
from jig.tools import NumberedDirectoriesToGit, slugify, indent
from jig.tests.testcase import JigTestCase
class TestSlugify(JigTestCase):
"""
Converting strings into slugs.
"""
def test_nothing(self):
"""
An empty string is given.
"""
... | src/jig/tests/test_tools.py | from os.path import join, dirname
from jig.tools import NumberedDirectoriesToGit, slugify, indent
from jig.tests.testcase import JigTestCase
class TestSlugify(JigTestCase):
"""
Converting strings into slugs.
"""
def test_nothing(self):
"""
An empty string is given.
"""
... | 0.644225 | 0.512327 |
from application.models import STATUS_CHOICES
from django import forms
from django.forms import widgets
from .models import Step1Rating, Step2Rating
from .models import RATING_METADATA_1_CHOICES, RATING_METADATA_2_CHOICES
import ast
class Step1RateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
... | web/src/rating/forms.py | from application.models import STATUS_CHOICES
from django import forms
from django.forms import widgets
from .models import Step1Rating, Step2Rating
from .models import RATING_METADATA_1_CHOICES, RATING_METADATA_2_CHOICES
import ast
class Step1RateForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
... | 0.705582 | 0.087994 |
import urllib2
from config import SHOW_AVATARS
try:
from PIL import Image
except ImportError:
SHOW_AVATARS = False
class Payload(object):
def __init__(self, data):
self.data = data
def user_link(self):
name = self.data['sender']['login']
url = self.data['sender']['html_url']... | payload.py | import urllib2
from config import SHOW_AVATARS
try:
from PIL import Image
except ImportError:
SHOW_AVATARS = False
class Payload(object):
def __init__(self, data):
self.data = data
def user_link(self):
name = self.data['sender']['login']
url = self.data['sender']['html_url']... | 0.474631 | 0.141252 |
import torch
import torch.nn as nn
from src.utils.custom_typing import EncoderOutput
class BaseEncoder(nn.Module):
def __init__(
self,
img_size: int,
in_channels: int,
num_filters: int,
kernel_size: int,
repr_dim: int,
):
"""Encoder to extract the repres... | src/neural_networks/encoder.py | import torch
import torch.nn as nn
from src.utils.custom_typing import EncoderOutput
class BaseEncoder(nn.Module):
def __init__(
self,
img_size: int,
in_channels: int,
num_filters: int,
kernel_size: int,
repr_dim: int,
):
"""Encoder to extract the repres... | 0.960231 | 0.504944 |
from dataclasses import dataclass, field
from .components import OpenApiComponents
from .info import OpenApiInfo
from .path import OpenApiPath
from .server import OpenApiServer
from .tag import OpenApiTag
@dataclass
class OpenApiSpec:
"""
This is the root document object of the OpenAPI document.
"""
... | src/openapi_dataclasses/types/openapi/spec.py | from dataclasses import dataclass, field
from .components import OpenApiComponents
from .info import OpenApiInfo
from .path import OpenApiPath
from .server import OpenApiServer
from .tag import OpenApiTag
@dataclass
class OpenApiSpec:
"""
This is the root document object of the OpenAPI document.
"""
... | 0.755997 | 0.208199 |
"""Base functions for checkpointing."""
import functools
import itertools
import multiprocessing.pool
import os
import re
from typing import Any, Callable, Iterable, Iterator, Sequence, Mapping, Optional
from tensorflow.io import gfile
from vmoe.checkpoints import serialization
AsyncResult = multiprocessing.pool.Asy... | vmoe/checkpoints/base.py |
"""Base functions for checkpointing."""
import functools
import itertools
import multiprocessing.pool
import os
import re
from typing import Any, Callable, Iterable, Iterator, Sequence, Mapping, Optional
from tensorflow.io import gfile
from vmoe.checkpoints import serialization
AsyncResult = multiprocessing.pool.Asy... | 0.877674 | 0.302597 |
from math import ceil
def eta_hms(seconds, always_show_hours=False, always_show_minutes=False, hours_leading_zero=False):
"""Converts seconds remaining into a human readable timestamp (e.g. hh:mm:ss, h:mm:ss, mm:ss, or ss).
Positional arguments:
seconds -- integer/float indicating seconds remaining.
... | etaprogress/components/eta_conversions.py |
from math import ceil
def eta_hms(seconds, always_show_hours=False, always_show_minutes=False, hours_leading_zero=False):
"""Converts seconds remaining into a human readable timestamp (e.g. hh:mm:ss, h:mm:ss, mm:ss, or ss).
Positional arguments:
seconds -- integer/float indicating seconds remaining.
... | 0.896423 | 0.555073 |
import albumentations as A
from torch.utils.data import Dataset
import cv2
import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedKFold
from .commons import config, target_cols
def get_train_data():
train = pd.read_csv('/workspace/train.csv')
train_annotated = pd.read_csv('/wo... | src/dataset.py | import albumentations as A
from torch.utils.data import Dataset
import cv2
import numpy as np
import pandas as pd
from sklearn.model_selection import StratifiedKFold
from .commons import config, target_cols
def get_train_data():
train = pd.read_csv('/workspace/train.csv')
train_annotated = pd.read_csv('/wo... | 0.564699 | 0.341775 |
import datetime
import logging
import logging.handlers
import os
import socket
import sys
from typing import List
__all__ = [
'get_logger',
'get_log_file_handler',
'get_log_file_path',
'get_output_loggers',
'get_screen_handler',
'launch_config',
'reset',
]
def with_per_logger_formattin... | launch/launch/logging.py | import datetime
import logging
import logging.handlers
import os
import socket
import sys
from typing import List
__all__ = [
'get_logger',
'get_log_file_handler',
'get_log_file_path',
'get_output_loggers',
'get_screen_handler',
'launch_config',
'reset',
]
def with_per_logger_formattin... | 0.692226 | 0.121869 |
__author__ = 'kensuke-mi'
import sys
import unittest
from JapaneseTokenizer.mecab_wrapper.mecab_wrapper import MecabWrapper
from JapaneseTokenizer.datamodels import TokenizedSenetence
from six import string_types
import os
python_version = sys.version_info
class TestMecabWrapperPython2(unittest.TestCase):
def se... | test/test_mecab_wrapper_python2.py | __author__ = 'kensuke-mi'
import sys
import unittest
from JapaneseTokenizer.mecab_wrapper.mecab_wrapper import MecabWrapper
from JapaneseTokenizer.datamodels import TokenizedSenetence
from six import string_types
import os
python_version = sys.version_info
class TestMecabWrapperPython2(unittest.TestCase):
def se... | 0.237311 | 0.32611 |
import copy
from importlib import import_module
from autumn.tools.project import get_project, Project
class Opti:
"""
This class is used to define and solve an optimisation problem based on one of the existing AuTuMN apps.
"""
project: Project
def __init__(
self,
app_name, # e.... | autumn/tools/optimisation/opti.py | import copy
from importlib import import_module
from autumn.tools.project import get_project, Project
class Opti:
"""
This class is used to define and solve an optimisation problem based on one of the existing AuTuMN apps.
"""
project: Project
def __init__(
self,
app_name, # e.... | 0.721743 | 0.351422 |
from openpeerpower.components.cover import ATTR_CURRENT_POSITION
from openpeerpower.components.ozw.cover import VALUE_SELECTED_ID
from .common import setup_ozw
VALUE_ID = "Value"
async def test_cover(opp, cover_data, sent_messages, cover_msg):
"""Test setting up config entry."""
receive_message = await setu... | tests/components/ozw/test_cover.py | from openpeerpower.components.cover import ATTR_CURRENT_POSITION
from openpeerpower.components.ozw.cover import VALUE_SELECTED_ID
from .common import setup_ozw
VALUE_ID = "Value"
async def test_cover(opp, cover_data, sent_messages, cover_msg):
"""Test setting up config entry."""
receive_message = await setu... | 0.616474 | 0.396594 |
from flask import Response,current_app,request,session
from sqlalchemy import text
from decimal import Decimal
import json,time,datetime
# 自定义跨域 接口 返回 class
class ApiCorsResponse():
@staticmethod
def response(data ,success = True,status_code= 200):
if success :
re_data = {'msg':'ok','data... | webServer/customer.py | from flask import Response,current_app,request,session
from sqlalchemy import text
from decimal import Decimal
import json,time,datetime
# 自定义跨域 接口 返回 class
class ApiCorsResponse():
@staticmethod
def response(data ,success = True,status_code= 200):
if success :
re_data = {'msg':'ok','data... | 0.252845 | 0.072243 |
import asyncio
import logging
import time
import typing
import ydb
from ydb import issues, settings, table
from ydb.table import (
BaseSession,
BaseTableClient,
_scan_query_request_factory,
_wrap_scan_query_response,
BaseTxContext,
)
from . import _utilities
from ydb import _apis, _session_impl
... | ydb/aio/table.py | import asyncio
import logging
import time
import typing
import ydb
from ydb import issues, settings, table
from ydb.table import (
BaseSession,
BaseTableClient,
_scan_query_request_factory,
_wrap_scan_query_response,
BaseTxContext,
)
from . import _utilities
from ydb import _apis, _session_impl
... | 0.581778 | 0.095645 |
from __future__ import annotations
from typing import Callable
from xknx import XKNX
from xknx.devices import DateTime, ExposeSensor
from xknx.dpt import DPTNumeric
from xknx.remote_value import RemoteValueSensor
from homeassistant.const import (
CONF_ENTITY_ID,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE... | homeassistant/components/knx/expose.py | from __future__ import annotations
from typing import Callable
from xknx import XKNX
from xknx.devices import DateTime, ExposeSensor
from xknx.dpt import DPTNumeric
from xknx.remote_value import RemoteValueSensor
from homeassistant.const import (
CONF_ENTITY_ID,
STATE_OFF,
STATE_ON,
STATE_UNAVAILABLE... | 0.880861 | 0.221424 |
import logging
import os
from anykeystore import create_store_from_settings
from pyramid.config import Configurator
from pyramid.exceptions import ConfigurationError
from pyramid.response import Response
from velruse.app.utils import generate_token
from velruse.app.utils import redirect_form
log = logging.getLogge... | velruse/app/__init__.py | import logging
import os
from anykeystore import create_store_from_settings
from pyramid.config import Configurator
from pyramid.exceptions import ConfigurationError
from pyramid.response import Response
from velruse.app.utils import generate_token
from velruse.app.utils import redirect_form
log = logging.getLogge... | 0.332961 | 0.057388 |
import logging
import uuid
from diskimage_builder.block_device.exception \
import BlockDeviceSetupException
from diskimage_builder.block_device.plugin import NodeBase
from diskimage_builder.block_device.plugin import PluginBase
from diskimage_builder.block_device.utils import exec_sudo
logger = logging.getLogge... | diskimage_builder/block_device/level2/mkfs.py |
import logging
import uuid
from diskimage_builder.block_device.exception \
import BlockDeviceSetupException
from diskimage_builder.block_device.plugin import NodeBase
from diskimage_builder.block_device.plugin import PluginBase
from diskimage_builder.block_device.utils import exec_sudo
logger = logging.getLogge... | 0.497803 | 0.164852 |
import unittest
from ctci.structs.stack import Stack
class TestStackPush(unittest.TestCase):
def setUp(self):
self.a = Stack()
def test_one(self):
self.a.push(1)
self.assertEqual(self.a.peek(), 1)
def test_two(self):
self.a.push(1)
self.a.push(2)
self... | tests/test_stack.py | import unittest
from ctci.structs.stack import Stack
class TestStackPush(unittest.TestCase):
def setUp(self):
self.a = Stack()
def test_one(self):
self.a.push(1)
self.assertEqual(self.a.peek(), 1)
def test_two(self):
self.a.push(1)
self.a.push(2)
self... | 0.442877 | 0.578984 |
import inspect
from collections import OrderedDict
from typing import Callable, Any, Union, Iterable, Dict, Tuple
from typish._types import Empty
from typish.classes._cls_dict import ClsDict
class ClsFunction:
"""
ClsDict is a callable that takes a ClsDict or a dict. When called, it uses
the first argume... | typish/classes/_cls_function.py | import inspect
from collections import OrderedDict
from typing import Callable, Any, Union, Iterable, Dict, Tuple
from typish._types import Empty
from typish.classes._cls_dict import ClsDict
class ClsFunction:
"""
ClsDict is a callable that takes a ClsDict or a dict. When called, it uses
the first argume... | 0.718792 | 0.305361 |
def get_config():
return {
'aws': {
'profile_name': 'mgap'
},
'clarifai': {
'api_key': ''
},
'elucidate': {
'host': 'http://localhost',
'port': 8080,
'base_path': '/annotation',
'annotation_model': 'w3c',... | mgap/util.py | def get_config():
return {
'aws': {
'profile_name': 'mgap'
},
'clarifai': {
'api_key': ''
},
'elucidate': {
'host': 'http://localhost',
'port': 8080,
'base_path': '/annotation',
'annotation_model': 'w3c',... | 0.561936 | 0.131507 |
from multiprocessing.dummy import Pool
from source.request import Request
import datetime
class Batch:
"""
Concurrently retrieves a set of reviews
"""
_DEFAULT_THREADS = 8
_REVIEWS_PER_BATCH = 20
_TIME_FORMAT = "[%Y-%m-%d_%H:%M:%S]"
def __init__(self, app_id: int, start: int, concurren... | source/batch.py | from multiprocessing.dummy import Pool
from source.request import Request
import datetime
class Batch:
"""
Concurrently retrieves a set of reviews
"""
_DEFAULT_THREADS = 8
_REVIEWS_PER_BATCH = 20
_TIME_FORMAT = "[%Y-%m-%d_%H:%M:%S]"
def __init__(self, app_id: int, start: int, concurren... | 0.788502 | 0.318644 |
"""Binary class head for Estimator that allow integration with TF Privacy."""
import tensorflow as tf
from tensorflow import estimator as tf_estimator
from tensorflow.python.keras.utils import losses_utils # pylint: disable=g-direct-tensorflow-import
from tensorflow_estimator.python.estimator import model_fn
from ten... | tensorflow_privacy/privacy/estimators/binary_class_head.py | """Binary class head for Estimator that allow integration with TF Privacy."""
import tensorflow as tf
from tensorflow import estimator as tf_estimator
from tensorflow.python.keras.utils import losses_utils # pylint: disable=g-direct-tensorflow-import
from tensorflow_estimator.python.estimator import model_fn
from ten... | 0.951605 | 0.296521 |
import json
import copy
class TreeNode(object):
'二叉树节点类'
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
class BinTree(object):
'二叉树类'
# 二叉树初始化
def __init__(self, data = None):
self.queue = []
if data is None:
... | optimizer/generate_stmt.py | import json
import copy
class TreeNode(object):
'二叉树节点类'
def __init__(self, data=None):
self.data = data
self.left = None
self.right = None
class BinTree(object):
'二叉树类'
# 二叉树初始化
def __init__(self, data = None):
self.queue = []
if data is None:
... | 0.182936 | 0.193604 |
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
class Analytics:
def __init__(self, states):
self.states = states
def show_heatmap(self):
'Plot a heatmap of the state values obtained via the Monte Carlo policy evaluation'
# convert to n... | 2_reinforcement_learning/Analytics.py | import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd
class Analytics:
def __init__(self, states):
self.states = states
def show_heatmap(self):
'Plot a heatmap of the state values obtained via the Monte Carlo policy evaluation'
# convert to n... | 0.395718 | 0.730626 |
import numpy as np
from sklearn.utils.validation import check_is_fitted
class PrefitVotingClassifier(object):
"""Stripped-down version of VotingClassifier that uses prefit estimators"""
def __init__(self, estimators, feats_per_estimator, voting='hard', weights=None):
self.estimators = [e[1] for e in e... | code/prefit_voting_classifier.py | import numpy as np
from sklearn.utils.validation import check_is_fitted
class PrefitVotingClassifier(object):
"""Stripped-down version of VotingClassifier that uses prefit estimators"""
def __init__(self, estimators, feats_per_estimator, voting='hard', weights=None):
self.estimators = [e[1] for e in e... | 0.947805 | 0.602734 |
from functools import wraps
from typing import Any, Callable, Optional, Union, no_type_check
from pydantic import errors
from pydantic_yaml.compat.types import YamlStr
from semver import VersionInfo
__all__ = ["SemVer"]
Comparator = Callable[["SemVer", Any], bool]
def _comparator(operator: Comparator) -> Comparat... | pydantic_yaml/ext/semver.py | from functools import wraps
from typing import Any, Callable, Optional, Union, no_type_check
from pydantic import errors
from pydantic_yaml.compat.types import YamlStr
from semver import VersionInfo
__all__ = ["SemVer"]
Comparator = Callable[["SemVer", Any], bool]
def _comparator(operator: Comparator) -> Comparat... | 0.930466 | 0.205077 |
from .code_generator_info import CodeGeneratorInfoMutable
from .composition_parts import Identifier
from .composition_parts import WithCodeGeneratorInfo
from .composition_parts import WithComponent
from .composition_parts import WithDebugInfo
from .composition_parts import WithIdentifier
class Union(WithIdentifier, ... | third_party/blink/renderer/bindings/scripts/web_idl/union.py |
from .code_generator_info import CodeGeneratorInfoMutable
from .composition_parts import Identifier
from .composition_parts import WithCodeGeneratorInfo
from .composition_parts import WithComponent
from .composition_parts import WithDebugInfo
from .composition_parts import WithIdentifier
class Union(WithIdentifier, ... | 0.890306 | 0.349838 |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import o... | sdk/storage/azure-storage-blob/tests/test_blob_samples_common.py |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import o... | 0.669205 | 0.188063 |
import sys
sys.path.append("./lambda/helper/python")
import boto3
import unittest
from moto import mock_s3
from moto import mock_dynamodb2
import datastore
DOCUMENTS_TABLE_NAME="DocumentsTestTable"
OUTPUT_TABLE_NAME="OutputTestTable"
current_session = boto3.session.Session()
REGION = current_session.region_name
print... | source/test/test_datastore.py | import sys
sys.path.append("./lambda/helper/python")
import boto3
import unittest
from moto import mock_s3
from moto import mock_dynamodb2
import datastore
DOCUMENTS_TABLE_NAME="DocumentsTestTable"
OUTPUT_TABLE_NAME="OutputTestTable"
current_session = boto3.session.Session()
REGION = current_session.region_name
print... | 0.207455 | 0.169715 |
from numba.core import registry, serialize, dispatcher
from numba import types
from numba.core.errors import UnsupportedError
import dpctl
from numba.core.compiler_lock import global_compiler_lock
class TargetDispatcher(serialize.ReduceMixin, metaclass=dispatcher.DispatcherMeta):
__numba__ = 'py_func'
target... | numba-dppy/numba_dppy/target_dispatcher.py | from numba.core import registry, serialize, dispatcher
from numba import types
from numba.core.errors import UnsupportedError
import dpctl
from numba.core.compiler_lock import global_compiler_lock
class TargetDispatcher(serialize.ReduceMixin, metaclass=dispatcher.DispatcherMeta):
__numba__ = 'py_func'
target... | 0.72662 | 0.087759 |
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
from utils import utils
from models.BaseModel import GeneralModel
from helpers.KGReader import KGReader
class CFKG(GeneralModel):
reader = 'KGReader'
@staticmethod
def parse_model_args(parser):
parser.add_argument('--emb_... | src/models/general/CFKG.py |
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
from utils import utils
from models.BaseModel import GeneralModel
from helpers.KGReader import KGReader
class CFKG(GeneralModel):
reader = 'KGReader'
@staticmethod
def parse_model_args(parser):
parser.add_argument('--emb_... | 0.801315 | 0.183155 |
from __future__ import print_function
import json
import traceback
import pandas as pd
import flask
from six import reraise
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import MALFORMED_REQUEST, BAD_REQUEST
from mlflow.utils.rest_utils import NumpyEncoder
from mlflow.utils.logging_... | mlflow/pyfunc/scoring_server.py | from __future__ import print_function
import json
import traceback
import pandas as pd
import flask
from six import reraise
from mlflow.exceptions import MlflowException
from mlflow.protos.databricks_pb2 import MALFORMED_REQUEST, BAD_REQUEST
from mlflow.utils.rest_utils import NumpyEncoder
from mlflow.utils.logging_... | 0.783988 | 0.204223 |
import pprint
import re # noqa: F401
import six
from ory_hydra_client.configuration import Configuration
class WellKnown(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
opena... | clients/hydra/python/ory_hydra_client/models/well_known.py | import pprint
import re # noqa: F401
import six
from ory_hydra_client.configuration import Configuration
class WellKnown(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
opena... | 0.604983 | 0.067948 |
import models
from aiogram.types import Message, ChatType, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
from auth import dp
from utils.general import save_message_to_storage_channel
from utils import logger
@dp.message_handler(commands=['add', 'addr'], chat_type=[ChatType.PRIVATE,
... | handlers/command_handlers/commands.py | import models
from aiogram.types import Message, ChatType, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
from auth import dp
from utils.general import save_message_to_storage_channel
from utils import logger
@dp.message_handler(commands=['add', 'addr'], chat_type=[ChatType.PRIVATE,
... | 0.130175 | 0.12075 |
from torch import nn
from pytorch_widedeep.wdtypes import * # noqa: F403
from pytorch_widedeep.models.tab_mlp import MLP
from pytorch_widedeep.models.transformers._encoders import SaintEncoder
from pytorch_widedeep.models.transformers._embeddings_layers import (
CatAndContEmbeddings,
)
class SAINT(nn.Module):
... | pytorch_widedeep/models/transformers/saint.py | from torch import nn
from pytorch_widedeep.wdtypes import * # noqa: F403
from pytorch_widedeep.models.tab_mlp import MLP
from pytorch_widedeep.models.transformers._encoders import SaintEncoder
from pytorch_widedeep.models.transformers._embeddings_layers import (
CatAndContEmbeddings,
)
class SAINT(nn.Module):
... | 0.967763 | 0.761317 |
import indigo
import json
from Shelly_Addon import Shelly_Addon
class Shelly_Addon_DHT22(Shelly_Addon):
"""
The Shelly Temperature Add-on is a sensor tht attaches to a host device.
The host devices can be a Shelly 1 or Shelly 1PM.
"""
def __init__(self, device):
Shelly_Addon.__init__(self... | ShellyMQTT.indigoPlugin/Contents/Server Plugin/Devices/Addons/Shelly_Addon_DHT22.py | import indigo
import json
from Shelly_Addon import Shelly_Addon
class Shelly_Addon_DHT22(Shelly_Addon):
"""
The Shelly Temperature Add-on is a sensor tht attaches to a host device.
The host devices can be a Shelly 1 or Shelly 1PM.
"""
def __init__(self, device):
Shelly_Addon.__init__(self... | 0.747155 | 0.364664 |
import unreal
BL_ColorRamp3 = unreal.AssetToolsHelpers.get_asset_tools().create_asset('BL_ColorRamp3', '/Engine/Functions/BLUI/', unreal.MaterialFunction, unreal.MaterialFunctionFactoryNew())
BL_ColorRamp3.set_editor_property("expose_to_library", True)
BL_ColorRamp3.set_editor_property("library_categories_text", (... | BL_ColorRamp3_MF.py | import unreal
BL_ColorRamp3 = unreal.AssetToolsHelpers.get_asset_tools().create_asset('BL_ColorRamp3', '/Engine/Functions/BLUI/', unreal.MaterialFunction, unreal.MaterialFunctionFactoryNew())
BL_ColorRamp3.set_editor_property("expose_to_library", True)
BL_ColorRamp3.set_editor_property("library_categories_text", (... | 0.332635 | 0.126353 |
import pmdarima
import pandas as pd
import numpy as np
import sklearn
import copy
from training import TrainHelper, ModelsBaseClass
from preparation import PreparationHelper
class ARIMA(ModelsBaseClass.BaseModel):
"""
Class containing (S)ARIMA(X) model and methods
"""
def __init__(self, target_colum... | training/ModelsARIMA.py | import pmdarima
import pandas as pd
import numpy as np
import sklearn
import copy
from training import TrainHelper, ModelsBaseClass
from preparation import PreparationHelper
class ARIMA(ModelsBaseClass.BaseModel):
"""
Class containing (S)ARIMA(X) model and methods
"""
def __init__(self, target_colum... | 0.747524 | 0.417212 |
import numpy as np
import matplotlib.pyplot as plt
plt.rc("font", family="serif")
plt.rc("text", usetex=True)
from astropy.table import Table
from astropy.cosmology import Planck15
DIST = Planck15.luminosity_distance(z=0.0137).cgs.value
def optical():
# PTF12gzk
dat = Table.read("table1.dat", format='ascii... | code/extra_plots/compare_12gzk.py |
import numpy as np
import matplotlib.pyplot as plt
plt.rc("font", family="serif")
plt.rc("text", usetex=True)
from astropy.table import Table
from astropy.cosmology import Planck15
DIST = Planck15.luminosity_distance(z=0.0137).cgs.value
def optical():
# PTF12gzk
dat = Table.read("table1.dat", format='ascii... | 0.549157 | 0.656658 |
import numpy as np
import cv2, re, os, keras, warnings, time
from keras.models import Model
import keras.layers as L
from keras.optimizers import RMSprop
from keras import models
from keras import optimizers
from keras.applications import VGG16
from mylib.Mailer import Mailer
from mylib import Config
warnings.filterwar... | Run.py | import numpy as np
import cv2, re, os, keras, warnings, time
from keras.models import Model
import keras.layers as L
from keras.optimizers import RMSprop
from keras import models
from keras import optimizers
from keras.applications import VGG16
from mylib.Mailer import Mailer
from mylib import Config
warnings.filterwar... | 0.780328 | 0.248483 |
from lockstep.lockstep_response import LockstepResponse
class CodeDefinitionsClient:
def __init__(self, client):
self.client = client
def retrieve_codedefinition(self, id: str, include: str) -> LockstepResponse:
"""
Retrieves the CodeDefinition specified by this unique
identi... | src/lockstep/clients/codedefinitions_client.py |
from lockstep.lockstep_response import LockstepResponse
class CodeDefinitionsClient:
def __init__(self, client):
self.client = client
def retrieve_codedefinition(self, id: str, include: str) -> LockstepResponse:
"""
Retrieves the CodeDefinition specified by this unique
identi... | 0.862872 | 0.260778 |
import sys
import os
import uuid
import re
DEFAULT_VCPROJ = r'''<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9.00"
Name="%{PROJNAME}%"
ProjectGUID="%{PROJGUID}%"
RootNamespace="%{PROJNAME}%"
TargetFrameworkVersion="196613"
>
<Platforms>
<Platform
Na... | src/newvc8.py |
import sys
import os
import uuid
import re
DEFAULT_VCPROJ = r'''<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
ProjectType="Visual C++"
Version="9.00"
Name="%{PROJNAME}%"
ProjectGUID="%{PROJGUID}%"
RootNamespace="%{PROJNAME}%"
TargetFrameworkVersion="196613"
>
<Platforms>
<Platform
Na... | 0.22627 | 0.055695 |
from http import HTTPStatus
from flask import Response, json, request
from flask_apispec import doc, marshal_with, use_kwargs
from flask_apispec.views import MethodResource
from flask_restful import Resource, reqparse
from smart_queue.apps import InvalidResponseModel
from smart_queue.apps.conditions.models import (
... | smart_queue/apps/conditions/views.py | from http import HTTPStatus
from flask import Response, json, request
from flask_apispec import doc, marshal_with, use_kwargs
from flask_apispec.views import MethodResource
from flask_restful import Resource, reqparse
from smart_queue.apps import InvalidResponseModel
from smart_queue.apps.conditions.models import (
... | 0.609059 | 0.056966 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['IndustrialPidLoopArgs', 'IndustrialPidLoop']
@pulumi.input_type
class IndustrialPidLoopArgs:
def __init__(__self__, *,
pid_loop_configura... | sdk/python/pulumi_alicloud/brain/industrial_pid_loop.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = ['IndustrialPidLoopArgs', 'IndustrialPidLoop']
@pulumi.input_type
class IndustrialPidLoopArgs:
def __init__(__self__, *,
pid_loop_configura... | 0.756268 | 0.069226 |
import os
import uuid
import pytest
import swapper
from django.conf import settings
from django.template.response import TemplateResponse
from django.test import TestCase
from django.urls import reverse, reverse_lazy
from django_fsm import can_proceed
from getpaid.registry import registry
from getpaid.types import Ba... | tests/dummy/test_dummy_integration.py | import os
import uuid
import pytest
import swapper
from django.conf import settings
from django.template.response import TemplateResponse
from django.test import TestCase
from django.urls import reverse, reverse_lazy
from django_fsm import can_proceed
from getpaid.registry import registry
from getpaid.types import Ba... | 0.42668 | 0.164181 |
from __future__ import annotations
import asyncio
import logging
import pprint
from asyncio import tasks
from dataclasses import dataclass
from typing import Any, Callable, cast
import aiohttp
import async_timeout
from aiohttp import ClientWebSocketResponse, WSMsgType, client_exceptions
from .const import NOTIFY_WS_... | aioshelly/wsrpc.py | from __future__ import annotations
import asyncio
import logging
import pprint
from asyncio import tasks
from dataclasses import dataclass
from typing import Any, Callable, cast
import aiohttp
import async_timeout
from aiohttp import ClientWebSocketResponse, WSMsgType, client_exceptions
from .const import NOTIFY_WS_... | 0.850298 | 0.097562 |
import sys
from PyQt5.QtWidgets import QApplication, QDialog, QPushButton,QComboBox,QLabel, QMainWindow, QWidget, QVBoxLayout
from PyQt5.QtGui import QPixmap,QIcon
from datetime import datetime
import time
from utils import covid_info,covid_table
import matplotlib.pyplot as plt
#information
covid_result=cov... | covidui.py |
import sys
from PyQt5.QtWidgets import QApplication, QDialog, QPushButton,QComboBox,QLabel, QMainWindow, QWidget, QVBoxLayout
from PyQt5.QtGui import QPixmap,QIcon
from datetime import datetime
import time
from utils import covid_info,covid_table
import matplotlib.pyplot as plt
#information
covid_result=cov... | 0.092048 | 0.077239 |
import os
import m5
from m5.util import addToPath
from m5.objects import *
from m5.options import *
import argparse
m5.util.addToPath('../..')
from common import SysPaths
from common import ObjectList
from common import MemConfig
from common.cores.arm import HPI
import devices
default_kernel = 'vmlinux.arm64'
defa... | configs/example/arm/starter_fs.py | import os
import m5
from m5.util import addToPath
from m5.objects import *
from m5.options import *
import argparse
m5.util.addToPath('../..')
from common import SysPaths
from common import ObjectList
from common import MemConfig
from common.cores.arm import HPI
import devices
default_kernel = 'vmlinux.arm64'
defa... | 0.36557 | 0.191158 |
import time
from collections import OrderedDict
from random import Random
from typing import Dict
class SimRandom:
"""Simulator random object that will keep a module level random.Random object to keep its internal random sequence,
it will not be affected by outside, and outside can set seed with seed functio... | maro/simulator/utils/sim_random.py |
import time
from collections import OrderedDict
from random import Random
from typing import Dict
class SimRandom:
"""Simulator random object that will keep a module level random.Random object to keep its internal random sequence,
it will not be affected by outside, and outside can set seed with seed functio... | 0.850701 | 0.485966 |
import torch as th
import torch.nn as nn
import torch.nn.functional as F
from modules.attention import Attention
class ATTRNNAgent(nn.Module):
def __init__(self, input_scheme, args):
super(ATTRNNAgent, self).__init__()
self.args = args
fixed_inputs = []
var_inputs = []
idx... | src/modules/agents/att_rnn_agent.py | import torch as th
import torch.nn as nn
import torch.nn.functional as F
from modules.attention import Attention
class ATTRNNAgent(nn.Module):
def __init__(self, input_scheme, args):
super(ATTRNNAgent, self).__init__()
self.args = args
fixed_inputs = []
var_inputs = []
idx... | 0.642993 | 0.242626 |
from typing import Callable, List, Optional
from rp2.abstract_transaction import AbstractTransaction
from rp2.configuration import Configuration
from rp2.entry_types import TransactionType
from rp2.logger import LOGGER
from rp2.rp2_decimal import FIAT_DECIMAL_MASK, ZERO, RP2Decimal
from rp2.rp2_error import RP2TypeEr... | src/rp2/out_transaction.py |
from typing import Callable, List, Optional
from rp2.abstract_transaction import AbstractTransaction
from rp2.configuration import Configuration
from rp2.entry_types import TransactionType
from rp2.logger import LOGGER
from rp2.rp2_decimal import FIAT_DECIMAL_MASK, ZERO, RP2Decimal
from rp2.rp2_error import RP2TypeEr... | 0.887485 | 0.201538 |
from typing import Dict, List, Union
import unittest
from rating.manager.bisect import get_closest_configs_bisect
import yaml
def generate_test_from_timestamp(timestamp: int) -> Union[int, Dict, Dict]:
"""Generate multiple configurations procedurally, to be tested afterward."""
rules = """
rules... | tests/test_timestamps.py | from typing import Dict, List, Union
import unittest
from rating.manager.bisect import get_closest_configs_bisect
import yaml
def generate_test_from_timestamp(timestamp: int) -> Union[int, Dict, Dict]:
"""Generate multiple configurations procedurally, to be tested afterward."""
rules = """
rules... | 0.899844 | 0.423041 |
from __future__ import absolute_import, unicode_literals, print_function, division
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth.decorators import login_required
from django.conf.urls import include
from django.contrib import admin
from django.contrib.auth.views i... | biosys/urls.py | from __future__ import absolute_import, unicode_literals, print_function, division
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth.decorators import login_required
from django.conf.urls import include
from django.contrib import admin
from django.contrib.auth.views i... | 0.444324 | 0.05962 |
from gevent import monkey
monkey.patch_all()
import unittest
import coverage
cov = coverage.coverage()
cov.start()
from flask import Flask, session
from flask.ext.socketio import SocketIO, send, emit, join_room, leave_room
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
socketio = SocketIO(app)
disconnect... | test_socketio.py | from gevent import monkey
monkey.patch_all()
import unittest
import coverage
cov = coverage.coverage()
cov.start()
from flask import Flask, session
from flask.ext.socketio import SocketIO, send, emit, join_room, leave_room
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret'
socketio = SocketIO(app)
disconnect... | 0.399929 | 0.239199 |