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 kivy.app import App
from kivy.factory import Factory
from kivy.properties import ObjectProperty
from kivy.lang import Builder
Builder.load_string('''
<FxDialog@Popup>
id: popup
title: 'Fiat Currency'
size_hint: 0.8, 0.8
pos_hint: {'top':0.9}
BoxLayout:
orientation: 'vertical'
... | gui/kivy/uix/dialogs/fx_dialog.py | from kivy.app import App
from kivy.factory import Factory
from kivy.properties import ObjectProperty
from kivy.lang import Builder
Builder.load_string('''
<FxDialog@Popup>
id: popup
title: 'Fiat Currency'
size_hint: 0.8, 0.8
pos_hint: {'top':0.9}
BoxLayout:
orientation: 'vertical'
... | 0.576184 | 0.10942 |
from abc import ABCMeta, abstractmethod
from typing import TYPE_CHECKING
from grouper.entities.permission import PermissionNotFoundException
from grouper.util import matches_glob
if TYPE_CHECKING:
from grouper.usecases.interfaces import (
GroupInterface,
PermissionInterface,
ServiceAccount... | grouper/usecases/grant_permission_to_group.py | from abc import ABCMeta, abstractmethod
from typing import TYPE_CHECKING
from grouper.entities.permission import PermissionNotFoundException
from grouper.util import matches_glob
if TYPE_CHECKING:
from grouper.usecases.interfaces import (
GroupInterface,
PermissionInterface,
ServiceAccount... | 0.738952 | 0.135518 |
from unittest import TestCase
import simplejson as json
from mock import patch, Mock, PropertyMock
from pypurlib.pypurlib import bin2hstr
from pur.core import config
from pur.core.Indexer import Indexer
from pur.core.misc import logger
from pur.core.State import State
from pur.core.StateContainer import StateContaine... | tests/core/txs/test_CoinBase.py | from unittest import TestCase
import simplejson as json
from mock import patch, Mock, PropertyMock
from pypurlib.pypurlib import bin2hstr
from pur.core import config
from pur.core.Indexer import Indexer
from pur.core.misc import logger
from pur.core.State import State
from pur.core.StateContainer import StateContaine... | 0.824956 | 0.238689 |
"""UNIT Test for Cli bin/v0upload.py."""
from typing import List
from v0tools.cli import Cli
import unittest
from io import StringIO
import sys
import contextlib
import pathlib
import threading
import tempfile
from pathlib import Path
from v0tools.lib import util
import requests
import time
BASE = pathlib.Path(__file_... | tests/test_cli_v0upload.py | """UNIT Test for Cli bin/v0upload.py."""
from typing import List
from v0tools.cli import Cli
import unittest
from io import StringIO
import sys
import contextlib
import pathlib
import threading
import tempfile
from pathlib import Path
from v0tools.lib import util
import requests
import time
BASE = pathlib.Path(__file_... | 0.49585 | 0.252734 |
import random
import pytest
import networkx as nx
from networkx.testing.utils import *
class TestFunction(object):
def setup_method(self):
self.G = nx.Graph({0: [1, 2, 3], 1: [1, 2, 0], 4: []}, name='Test')
self.Gdegree = {0: 3, 1: 2, 2: 2, 3: 1, 4: 0}
self.Gnodes = list(range(5))
... | networkx/classes/tests/test_function.py | import random
import pytest
import networkx as nx
from networkx.testing.utils import *
class TestFunction(object):
def setup_method(self):
self.G = nx.Graph({0: [1, 2, 3], 1: [1, 2, 0], 4: []}, name='Test')
self.Gdegree = {0: 3, 1: 2, 2: 2, 3: 1, 4: 0}
self.Gnodes = list(range(5))
... | 0.604399 | 0.773943 |
import copy
import logging
import PIL
import cv2
import numpy as np
import scipy.ndimage
import skimage.morphology
import src.utils as utils
def _get_xy_bounding_box(vertex, padding):
"""Returns the xy bounding box of the environment."""
min_ = np.floor(np.min(vertex[:, :2], axis=0) - padding).astype(np.int)
m... | research/cognitive_mapping_and_planning/src/map_utils.py | import copy
import logging
import PIL
import cv2
import numpy as np
import scipy.ndimage
import skimage.morphology
import src.utils as utils
def _get_xy_bounding_box(vertex, padding):
"""Returns the xy bounding box of the environment."""
min_ = np.floor(np.min(vertex[:, :2], axis=0) - padding).astype(np.int)
m... | 0.809163 | 0.528716 |
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
# all states
N_STATES = 19
# discount
GAMMA = 1
# initial state values
stateValues = np.zeros(N_STATES + 2)
# all states but terminal states
states = np.arange(1, N_STATES + 1)
# start from the middle state
START_STATE = 10
... | chapter07/RandomWalk.py |
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
# all states
N_STATES = 19
# discount
GAMMA = 1
# initial state values
stateValues = np.zeros(N_STATES + 2)
# all states but terminal states
states = np.arange(1, N_STATES + 1)
# start from the middle state
START_STATE = 10
... | 0.704973 | 0.709988 |
from .constants import GRAIN_TYPE_LIST
from .constants import HOP_TYPE_LIST
from .constants import IMPERIAL_UNITS
from .constants import SI_UNITS
from .exceptions import ValidatorException
__all__ = [
u"validate_grain_type",
u"validate_hop_type",
u"validate_percentage",
u"validate_units",
u"validat... | brew/validators.py | from .constants import GRAIN_TYPE_LIST
from .constants import HOP_TYPE_LIST
from .constants import IMPERIAL_UNITS
from .constants import SI_UNITS
from .exceptions import ValidatorException
__all__ = [
u"validate_grain_type",
u"validate_hop_type",
u"validate_percentage",
u"validate_units",
u"validat... | 0.763924 | 0.437763 |
from base.middleware import RequestMiddleware
from base.utils import get_our_models
# django imports
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.conf import settings
@receiver(post_save)
def audit_log(sender, instance, created, raw, update_fields, **kw... | base/signals.py | from base.middleware import RequestMiddleware
from base.utils import get_our_models
# django imports
from django.db.models.signals import post_save, post_delete
from django.dispatch import receiver
from django.conf import settings
@receiver(post_save)
def audit_log(sender, instance, created, raw, update_fields, **kw... | 0.61832 | 0.069668 |
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from instance.models import Host
from dashboard.views import sort_host
from webvirtmgr.server import ConnServer
fr... | webvirtmgr/overview/views.py | from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from instance.models import Host
from dashboard.views import sort_host
from webvirtmgr.server import ConnServer
fr... | 0.377196 | 0.034947 |
import KratosMultiphysics
import run_cpp_unit_tests
# Import Kratos "wrapper" for unittests
import KratosMultiphysics.KratosUnittest as KratosUnittest
# Import from Test Factories (with general analysis flows)
from particle_mechanics_test_factory import AxisSymmetricCircularPlate2DTriTest as TAxisSymmetricCircularPla... | applications/ParticleMechanicsApplication/tests/test_ParticleMechanicsApplication.py | import KratosMultiphysics
import run_cpp_unit_tests
# Import Kratos "wrapper" for unittests
import KratosMultiphysics.KratosUnittest as KratosUnittest
# Import from Test Factories (with general analysis flows)
from particle_mechanics_test_factory import AxisSymmetricCircularPlate2DTriTest as TAxisSymmetricCircularPla... | 0.410284 | 0.571288 |
import copy
import glob
import typing
from deoppet.parser import Parser, Snippet
from deoppet.mapping import Mapping
from deoppet.util import debug
from pynvim import Nvim
class Deoppet():
def __init__(self, vim: Nvim) -> None:
self._vim = vim
if not self._vim.call('has', 'nvim-0.5.0'):
... | rplugin/python3/deoppet/deoppet.py |
import copy
import glob
import typing
from deoppet.parser import Parser, Snippet
from deoppet.mapping import Mapping
from deoppet.util import debug
from pynvim import Nvim
class Deoppet():
def __init__(self, vim: Nvim) -> None:
self._vim = vim
if not self._vim.call('has', 'nvim-0.5.0'):
... | 0.424889 | 0.117902 |
from __future__ import division, print_function, absolute_import
from warnings import warn
from numpy import asarray, asarray_chkfinite
# Local imports
from .misc import _datacopied
from .lapack import get_lapack_funcs
from .flinalg import get_flinalg_funcs
__all__ = ['lu', 'lu_solve', 'lu_factor']
def lu_factor... | scipy/linalg/decomp_lu.py |
from __future__ import division, print_function, absolute_import
from warnings import warn
from numpy import asarray, asarray_chkfinite
# Local imports
from .misc import _datacopied
from .lapack import get_lapack_funcs
from .flinalg import get_flinalg_funcs
__all__ = ['lu', 'lu_solve', 'lu_factor']
def lu_factor... | 0.955194 | 0.710797 |
from collections import namedtuple, Counter
class Colors:
"""
Used as an enum to hold possible color values.
"""
def __init__(self):
pass
red, orange, blue, yellow, green, pink, black, white, none = range(9)
colors_list = ['Red', 'Orange', 'Blue', 'Yellow', 'Green', 'Pink', 'Black', ... | game/classes.py | from collections import namedtuple, Counter
class Colors:
"""
Used as an enum to hold possible color values.
"""
def __init__(self):
pass
red, orange, blue, yellow, green, pink, black, white, none = range(9)
colors_list = ['Red', 'Orange', 'Blue', 'Yellow', 'Green', 'Pink', 'Black', ... | 0.86431 | 0.285142 |
from typing import Optional
from fedot.core.operations.model import Model
from fedot.core.pipelines.node import PrimaryNode
from fedot.core.pipelines.pipeline import Pipeline, nodes_with_operation
from fedot.core.repository.dataset_types import DataTypesEnum
from fedot.core.repository.operation_types_repository import... | fedot/core/pipelines/validation_rules.py | from typing import Optional
from fedot.core.operations.model import Model
from fedot.core.pipelines.node import PrimaryNode
from fedot.core.pipelines.pipeline import Pipeline, nodes_with_operation
from fedot.core.repository.dataset_types import DataTypesEnum
from fedot.core.repository.operation_types_repository import... | 0.717408 | 0.244093 |
import discord
import os
from discord.ext import commands
from discord.utils import get
import youtube_dl
from youtube_search import YoutubeSearch
import validators
class MusicCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True, aliases=["J", "jo"])
asyn... | cogs/musiccog.py | import discord
import os
from discord.ext import commands
from discord.utils import get
import youtube_dl
from youtube_search import YoutubeSearch
import validators
class MusicCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(pass_context=True, aliases=["J", "jo"])
asyn... | 0.345326 | 0.122261 |
class Selector:
price_res = "/html/body/div/div/div[1]/div/div[5]/div[3]/div[2]/div/div[2]/div[1]/div[1]/div/div[{0}]/div/div[3]/div/span[1]/span//text()"
price_res2 = "//*[@id='page-block']/div/div[5]/div[4]/div[2]/div/div[2]/div[1]/div[1]/div/div[{0}]/div/div[3]/div/span/span//text()"
price_res1 = "//*[... | promoprice/prom/moduls/constant.py |
class Selector:
price_res = "/html/body/div/div/div[1]/div/div[5]/div[3]/div[2]/div/div[2]/div[1]/div[1]/div/div[{0}]/div/div[3]/div/span[1]/span//text()"
price_res2 = "//*[@id='page-block']/div/div[5]/div[4]/div[2]/div/div[2]/div[1]/div[1]/div/div[{0}]/div/div[3]/div/span/span//text()"
price_res1 = "//*[... | 0.108981 | 0.124559 |
import json
import logging
import inspect
from .decorators import pipeline_functions, register_pipeline
from indra.statements import get_statement_by_name, Statement
logger = logging.getLogger(__name__)
class AssemblyPipeline():
"""An assembly pipeline that runs the specified steps on a given set of
statem... | indra/pipeline/pipeline.py | import json
import logging
import inspect
from .decorators import pipeline_functions, register_pipeline
from indra.statements import get_statement_by_name, Statement
logger = logging.getLogger(__name__)
class AssemblyPipeline():
"""An assembly pipeline that runs the specified steps on a given set of
statem... | 0.838515 | 0.473779 |
from toontown.toonbase import TTLocalizer
from toontown.coghq.SpecImports import *
GlobalEntities = {1000: {'type': 'levelMgr', 'name': 'LevelMgr', 'comment': '',
'parentEntId': 0,
'cogLevel': 0,
'farPlaneDistance': 1500.0,
'modelFilename': 'phase_9/models/cogHQ/SelbotLegFact... | v2.5.7/toontown/coghq/SellbotSwagFactorySpec.py | from toontown.toonbase import TTLocalizer
from toontown.coghq.SpecImports import *
GlobalEntities = {1000: {'type': 'levelMgr', 'name': 'LevelMgr', 'comment': '',
'parentEntId': 0,
'cogLevel': 0,
'farPlaneDistance': 1500.0,
'modelFilename': 'phase_9/models/cogHQ/SelbotLegFact... | 0.336549 | 0.212048 |
import os
from collections import OrderedDict
from . import _espeak
import threading
import languageHandler
from synthDriverHandler import SynthDriver, VoiceInfo, synthIndexReached, synthDoneSpeaking
import speech
from logHandler import log
from speech.commands import (
IndexCommand,
CharacterModeComman... | source/synthDrivers/espeak.py |
import os
from collections import OrderedDict
from . import _espeak
import threading
import languageHandler
from synthDriverHandler import SynthDriver, VoiceInfo, synthIndexReached, synthDoneSpeaking
import speech
from logHandler import log
from speech.commands import (
IndexCommand,
CharacterModeComman... | 0.336767 | 0.05301 |
from samplebase import SampleBase
from rgbmatrix import graphics
import time
import platform
print(platform.python_version())
import livesports
from livesports import LiveSportsClient
from yahoo_weather.weather import YahooWeather
from yahoo_weather.config.units import Unit
from threading import Timer
class Graphic... | ledmatrix_scripts/display_led_scoreboard.py | from samplebase import SampleBase
from rgbmatrix import graphics
import time
import platform
print(platform.python_version())
import livesports
from livesports import LiveSportsClient
from yahoo_weather.weather import YahooWeather
from yahoo_weather.config.units import Unit
from threading import Timer
class Graphic... | 0.323166 | 0.154823 |
import time, os, glob
import cv2
import numpy as np
from erl.customized_agents.customized_ppo import CustomizedPPO
from stable_baselines3.common.vec_env import DummyVecEnv, VecNormalize
from erl.tools.gym_helper import make_env
from erl.tools.adjust_camera_callback import AdjustCameraCallback
img_path = f"videos/imag... | erl/tests.py | import time, os, glob
import cv2
import numpy as np
from erl.customized_agents.customized_ppo import CustomizedPPO
from stable_baselines3.common.vec_env import DummyVecEnv, VecNormalize
from erl.tools.gym_helper import make_env
from erl.tools.adjust_camera_callback import AdjustCameraCallback
img_path = f"videos/imag... | 0.292393 | 0.219338 |
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class CreateVcnDetails(object):
"""
CreateVcnDetails model.
"""
def __init__(self, **kwargs):
"""
... | src/oci/core/models/create_vcn_details.py |
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class CreateVcnDetails(object):
"""
CreateVcnDetails model.
"""
def __init__(self, **kwargs):
"""
... | 0.761627 | 0.307683 |
import itertools
import pickle
import shutil
import tempfile
from soap import logger
from soap.flopoco.common import cd, template_file, flopoco, xilinx
class _RTLGenerator(object):
def __init__(self, expr, var_env, prec, file_name=None, dir=None):
from soap.expression import Expr
self.expr = Exp... | soap/flopoco/actual.py | import itertools
import pickle
import shutil
import tempfile
from soap import logger
from soap.flopoco.common import cd, template_file, flopoco, xilinx
class _RTLGenerator(object):
def __init__(self, expr, var_env, prec, file_name=None, dir=None):
from soap.expression import Expr
self.expr = Exp... | 0.364551 | 0.166675 |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
"metadata_version": "1.1",
"status": ["preview"],
"supported_by": "community",
}
DOCUMENTATION = """
---
module: oci_remote_peering_connection_facts
short_description: Retrieve facts of Remote Peer... | library/oci_remote_peering_connection_facts.py |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
"metadata_version": "1.1",
"status": ["preview"],
"supported_by": "community",
}
DOCUMENTATION = """
---
module: oci_remote_peering_connection_facts
short_description: Retrieve facts of Remote Peer... | 0.669421 | 0.347509 |
import numpy as np
from openvino.inference_engine import IECore
class Model(object):
"""
The Salt model class contains methods important to fine cube inference.
If you would like to make classes that utilize these
inference tasks, treat the Salt model class as the interface to implement.
"""
... | models/salt/only_model_script/model.py | import numpy as np
from openvino.inference_engine import IECore
class Model(object):
"""
The Salt model class contains methods important to fine cube inference.
If you would like to make classes that utilize these
inference tasks, treat the Salt model class as the interface to implement.
"""
... | 0.887327 | 0.425068 |
import json
import requests
class Touchpoint():
from .employee import Employee
from .location import Location
from .item import Item
def __init__(self, api_key=None):
if api_key is None:
raise ValueError("A valid API_KEY must be provided.")
self.api_key = api_key
@cla... | touchpoint/touchpoint.py | import json
import requests
class Touchpoint():
from .employee import Employee
from .location import Location
from .item import Item
def __init__(self, api_key=None):
if api_key is None:
raise ValueError("A valid API_KEY must be provided.")
self.api_key = api_key
@cla... | 0.426322 | 0.061961 |
import pytest
from petisco import Persistence
from petisco.extra.sqlalchemy import SqliteConnection, SqliteDatabase
from tests.modules.extra.sqlalchemy.mother.model_filename_mother import (
ModelFilenameMother,
)
@pytest.mark.integration
def test_should_create_persistence_with_sqlite_database():
filename = M... | tests/modules/extra/sqlalchemy/integration/test_sqlite_database.py | import pytest
from petisco import Persistence
from petisco.extra.sqlalchemy import SqliteConnection, SqliteDatabase
from tests.modules.extra.sqlalchemy.mother.model_filename_mother import (
ModelFilenameMother,
)
@pytest.mark.integration
def test_should_create_persistence_with_sqlite_database():
filename = M... | 0.544075 | 0.275404 |
"""Tests for initializers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
from scipy import special
from scipy import stats
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions
fro... | tensorflow_probability/python/distributions/chi2_test.py | """Tests for initializers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# Dependency imports
import numpy as np
from scipy import special
from scipy import stats
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions
fro... | 0.880771 | 0.605245 |
import os
import numpy as np
import PIL.Image as Img
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
def extract_image(filename: str):
"""
extract the image from the mask, used for cvat results
for colab using, the input is designed for situation where default path have
both "Segm... | Collage_generator/utils.py | import os
import numpy as np
import PIL.Image as Img
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
def extract_image(filename: str):
"""
extract the image from the mask, used for cvat results
for colab using, the input is designed for situation where default path have
both "Segm... | 0.611498 | 0.579579 |
from __future__ import division, print_function
import os
import re
import sys
import argparse
import cv2
import pickle
import numpy as np
import h5py
import chainer
from chainer.links import caffe
from chainer import cuda
"""
Resize and crop an image to 224x224 (some part of sourcecode from chaine... | code/chainer_extract_vgg.py |
from __future__ import division, print_function
import os
import re
import sys
import argparse
import cv2
import pickle
import numpy as np
import h5py
import chainer
from chainer.links import caffe
from chainer import cuda
"""
Resize and crop an image to 224x224 (some part of sourcecode from chaine... | 0.284477 | 0.170197 |
import json
import os
import requests
import subprocess
import sys
import tempfile
import time
import yaml
from oslo_utils import timeutils
from heat_integrationtests.common import exceptions
from heat_integrationtests.functional import functional_base
class ParallelDeploymentsTest(functional_base.FunctionalTestsB... | heat_integrationtests/functional/test_software_config.py |
import json
import os
import requests
import subprocess
import sys
import tempfile
import time
import yaml
from oslo_utils import timeutils
from heat_integrationtests.common import exceptions
from heat_integrationtests.functional import functional_base
class ParallelDeploymentsTest(functional_base.FunctionalTestsB... | 0.319121 | 0.138841 |
import keyring
import oslo_messaging
from oslo_config import cfg
from oslo_log import log
from sysinv.common import constants
from sysinv.common import utils
from sysinv.db import api as dbapi
LOG = log.getLogger(__name__)
callback_func = None
context = None
class NotificationEndpoint(object):
"""Task which ex... | sysinv/sysinv/sysinv/sysinv/conductor/keystone_listener.py | import keyring
import oslo_messaging
from oslo_config import cfg
from oslo_log import log
from sysinv.common import constants
from sysinv.common import utils
from sysinv.db import api as dbapi
LOG = log.getLogger(__name__)
callback_func = None
context = None
class NotificationEndpoint(object):
"""Task which ex... | 0.407687 | 0.082883 |
import os
from options.test_options import TestOptions
from data import CreateDataLoader
from models import create_model
import numpy as np
from PIL import Image
from shutil import copyfile
def save_final_layer_image(image_numpy, image_path):
# last layer is tanh
image_numpy = (np.transpose(image_numpy, (1, 2, 0)) +... | visualize_intermediate_layers.py | import os
from options.test_options import TestOptions
from data import CreateDataLoader
from models import create_model
import numpy as np
from PIL import Image
from shutil import copyfile
def save_final_layer_image(image_numpy, image_path):
# last layer is tanh
image_numpy = (np.transpose(image_numpy, (1, 2, 0)) +... | 0.246171 | 0.344443 |
import pprint
import re # noqa: F401
import six
class GetCharactersCharacterIdAttributesOk(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | swagger_client/models/get_characters_character_id_attributes_ok.py | import pprint
import re # noqa: F401
import six
class GetCharactersCharacterIdAttributesOk(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | 0.772359 | 0.090173 |
import sys
import typing
import numba as nb
import numpy as np
@nb.njit
def sort_csgraph(
n: int,
g: np.ndarray,
) -> typing.Tuple[np.ndarray, np.ndarray, np.ndarray]:
sort_idx = np.argsort(g[:, 0], kind='mergesort')
g = g[sort_idx]
edge_idx = np.searchsorted(g[:, 0], np.arange(n + 1))
ori... | jp.atcoder/practice2/practice2_g/26020641.py | import sys
import typing
import numba as nb
import numpy as np
@nb.njit
def sort_csgraph(
n: int,
g: np.ndarray,
) -> typing.Tuple[np.ndarray, np.ndarray, np.ndarray]:
sort_idx = np.argsort(g[:, 0], kind='mergesort')
g = g[sort_idx]
edge_idx = np.searchsorted(g[:, 0], np.arange(n + 1))
ori... | 0.165256 | 0.250913 |
import json
from copy import deepcopy
from datetime import datetime, timedelta
from buildkite.schedule_and_publish.get_commits import get_commits
from models.benchmark_group_execution import BenchmarkGroupExecution
from models.machine import Machine
from models.memory_usage import MemoryUsage
from models.run import Ru... | tests/api/test_logs.py | import json
from copy import deepcopy
from datetime import datetime, timedelta
from buildkite.schedule_and_publish.get_commits import get_commits
from models.benchmark_group_execution import BenchmarkGroupExecution
from models.machine import Machine
from models.memory_usage import MemoryUsage
from models.run import Ru... | 0.485356 | 0.25163 |
from __future__ import division
import os
import argparse
from solver import Solver
def main(args):
# Create directory if it doesn't exist.
if not os.path.exists(args.text2pal_dir):
os.makedirs(args.text2pal_dir)
if not os.path.exists(args.pal2color_dir):
os.makedirs(args.pal2... | main.py | from __future__ import division
import os
import argparse
from solver import Solver
def main(args):
# Create directory if it doesn't exist.
if not os.path.exists(args.text2pal_dir):
os.makedirs(args.text2pal_dir)
if not os.path.exists(args.pal2color_dir):
os.makedirs(args.pal2... | 0.448909 | 0.075551 |
from ...Generator import PYTHON_TYPE, TAB, TAB2, TAB3, TAB4, TAB5, TAB6, TAB7
from ...Generator.read_fct import (
is_list_pyleecan_type,
is_dict_pyleecan_type,
is_list_unknow_type,
)
def generate_set_None(gen_dict, class_dict, soft_name="software"):
"""Generate the code for the _set_None method of the... | pyleecan/Generator/ClassGenerator/set_None_method_generator.py | from ...Generator import PYTHON_TYPE, TAB, TAB2, TAB3, TAB4, TAB5, TAB6, TAB7
from ...Generator.read_fct import (
is_list_pyleecan_type,
is_dict_pyleecan_type,
is_list_unknow_type,
)
def generate_set_None(gen_dict, class_dict, soft_name="software"):
"""Generate the code for the _set_None method of the... | 0.48121 | 0.14774 |
import json
import tempfile
from werkzeug.wsgi import wrap_file
from werkzeug.wrappers import Request, Response
from executor import execute
@Request.application
def application(request):
"""
To use this application, the user must send a POST request with
base64 or form encoded encoded HTML content and t... | app.py | import json
import tempfile
from werkzeug.wsgi import wrap_file
from werkzeug.wrappers import Request, Response
from executor import execute
@Request.application
def application(request):
"""
To use this application, the user must send a POST request with
base64 or form encoded encoded HTML content and t... | 0.449151 | 0.110088 |
import gensim
import sys,os
ROOT_PATH = '/'.join(os.path.abspath(__file__).split('/')[:-2])
sys.path.append(ROOT_PATH)
import numpy as np
from itertools import chain
import tensorflow as tf
from utils.preprocess import *
from embedding.embedding_base import Base
from common.layers import get_initializer
import collecti... | embedding/word_embedding.py | import gensim
import sys,os
ROOT_PATH = '/'.join(os.path.abspath(__file__).split('/')[:-2])
sys.path.append(ROOT_PATH)
import numpy as np
from itertools import chain
import tensorflow as tf
from utils.preprocess import *
from embedding.embedding_base import Base
from common.layers import get_initializer
import collecti... | 0.371137 | 0.151153 |
import re
from collections import defaultdict, deque
import regex
from telethon import events
from telethon.tl import functions, types
from audynesia import udy
from ..Config import Config
plugin_category = "tools"
HEADER = "「sed」\n"
KNOWN_RE_BOTS = re.compile(Config.GROUP_REG_SED_EX_BOT_S, flags=re.IGNORECASE)
#... | audynesia/plugins/sed.py | import re
from collections import defaultdict, deque
import regex
from telethon import events
from telethon.tl import functions, types
from audynesia import udy
from ..Config import Config
plugin_category = "tools"
HEADER = "「sed」\n"
KNOWN_RE_BOTS = re.compile(Config.GROUP_REG_SED_EX_BOT_S, flags=re.IGNORECASE)
#... | 0.421552 | 0.153962 |
import os
from optparse import make_option
from django.core.management import call_command
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from hvz.main import models
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
... | hvz/main/management/commands/setup-dev.py | import os
from optparse import make_option
from django.core.management import call_command
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from hvz.main import models
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
... | 0.306112 | 0.06134 |
import unittest
import sys, os
sys.path.append('../../')
from etk.core import Core
import json
import codecs
class TestExtractionsInputPaths(unittest.TestCase):
def setUp(self):
file_path = os.path.join(os.path.dirname(__file__), "ground_truth/1_content_extracted.jl")
self.doc = json.load(codecs.... | etk/unit_tests/test_knowledge_graph.py | import unittest
import sys, os
sys.path.append('../../')
from etk.core import Core
import json
import codecs
class TestExtractionsInputPaths(unittest.TestCase):
def setUp(self):
file_path = os.path.join(os.path.dirname(__file__), "ground_truth/1_content_extracted.jl")
self.doc = json.load(codecs.... | 0.270962 | 0.279472 |
from math import ceil
from pyrogram.types import InlineKeyboardButton
from wbb import MOD_LOAD, MOD_NOLOAD
class EqInlineKeyboardButton(InlineKeyboardButton):
def __eq__(self, other):
return self.text == other.text
def __lt__(self, other):
return self.text < other.text
def __gt__(self,... | wbb/utils/misc.py | from math import ceil
from pyrogram.types import InlineKeyboardButton
from wbb import MOD_LOAD, MOD_NOLOAD
class EqInlineKeyboardButton(InlineKeyboardButton):
def __eq__(self, other):
return self.text == other.text
def __lt__(self, other):
return self.text < other.text
def __gt__(self,... | 0.71103 | 0.155174 |
# Before you know it, you're inside a submarine the Elves keep ready for situations like this. It's covered in Christmas lights (because of course it is), and it even has an experimental antenna that should be able to track the keys if you can boost its signal strength high enough; there's a little meter that indicate... | 2021/solutions/d1-sonar-sweep.py |
# Before you know it, you're inside a submarine the Elves keep ready for situations like this. It's covered in Christmas lights (because of course it is), and it even has an experimental antenna that should be able to track the keys if you can boost its signal strength high enough; there's a little meter that indicate... | 0.752559 | 0.641773 |
from __future__ import print_function
from .anchors import compute_overlap
from .visualization import draw_detections, draw_annotations
import numpy as np
import itertools
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import os
import cv2
import pickle
def _compute_ap(recall, precisi... | keras_retinanet/utils/eval.py | from __future__ import print_function
from .anchors import compute_overlap
from .visualization import draw_detections, draw_annotations
import numpy as np
import itertools
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import os
import cv2
import pickle
def _compute_ap(recall, precisi... | 0.915412 | 0.591546 |
from __future__ import division, print_function, unicode_literals, absolute_import
import imghdr
import struct
import io
import numpy as np
_dtypes_float = [np.float, np.float16, np.float32]
_dtypes_int = [np.int, np.int8, np.int16, np.int32, np.uint8, np.uint16, np.uint32]
def _is_float_type(data):
if type(da... | image_attendant/utility.py | from __future__ import division, print_function, unicode_literals, absolute_import
import imghdr
import struct
import io
import numpy as np
_dtypes_float = [np.float, np.float16, np.float32]
_dtypes_int = [np.int, np.int8, np.int16, np.int32, np.uint8, np.uint16, np.uint32]
def _is_float_type(data):
if type(da... | 0.589244 | 0.603377 |
import mmcv
import torch
from mmtrack.models.track_heads.stark_head import (CornerPredictorHead,
ScoreHead, StarkHead,
StarkTransformer)
def test_corner_predictor_head():
bbox_head = CornerPredictorHead(8, 8, fe... | tests/test_models/test_track_heads/test_stark_head.py | import mmcv
import torch
from mmtrack.models.track_heads.stark_head import (CornerPredictorHead,
ScoreHead, StarkHead,
StarkTransformer)
def test_corner_predictor_head():
bbox_head = CornerPredictorHead(8, 8, fe... | 0.811153 | 0.264212 |
import argparse
import json
import pathlib
from pathlib import Path
import numpy as np
import data_loader.data_loaders as module_data
import model.loss as module_loss
import model.metric as module_metric
import model.model as module_arch # monorec model
from evaluater import Evaluater
from utils.parse_config import ... | eval_test.py | import argparse
import json
import pathlib
from pathlib import Path
import numpy as np
import data_loader.data_loaders as module_data
import model.loss as module_loss
import model.metric as module_metric
import model.model as module_arch # monorec model
from evaluater import Evaluater
from utils.parse_config import ... | 0.348645 | 0.166913 |
from __future__ import absolute_import, print_function
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models import Q
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from sentry.db.models import (
... | src/sentry/models/team.py | from __future__ import absolute_import, print_function
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models import Q
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from sentry.db.models import (
... | 0.474144 | 0.068226 |
from unittest import mock
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from django.contrib.sessions.backends.base import SessionBase
from django.http import HttpRequest, HttpResponse
from utm_tracker.middleware import LeadSourceMiddleware, UtmSessionMiddleware
fr... | tests/test_middleware.py | from unittest import mock
from django.contrib.auth import get_user_model
from django.contrib.auth.models import AnonymousUser
from django.contrib.sessions.backends.base import SessionBase
from django.http import HttpRequest, HttpResponse
from utm_tracker.middleware import LeadSourceMiddleware, UtmSessionMiddleware
fr... | 0.646237 | 0.182936 |
import torch
from PIL import Image
from torchvision import transforms
from .pose_resnet import *
from operator import itemgetter
import copy
import matplotlib.pyplot as plt
import cv2
import numpy as np
import time
get_detached = lambda x: copy.deepcopy(x.cpu().detach().numpy())
get_keypoints = lambda pose_layers: ma... | S5_HumanPoseEstimation/src/inference.py | import torch
from PIL import Image
from torchvision import transforms
from .pose_resnet import *
from operator import itemgetter
import copy
import matplotlib.pyplot as plt
import cv2
import numpy as np
import time
get_detached = lambda x: copy.deepcopy(x.cpu().detach().numpy())
get_keypoints = lambda pose_layers: ma... | 0.490236 | 0.322419 |
from sklearn.tree import DecisionTreeRegressor as SKDecisionTreeRegressor
from skopt.space import Integer
from blocktorch.model_family import ModelFamily
from blocktorch.pipelines.components.estimators import Estimator
from blocktorch.problem_types import ProblemTypes
from .blockwise_voting_regressor import Blockwise... | ml_source/src/blocktorch/blocktorch/pipelines/components/estimators/regressors/decision_tree_regressor.py | from sklearn.tree import DecisionTreeRegressor as SKDecisionTreeRegressor
from skopt.space import Integer
from blocktorch.model_family import ModelFamily
from blocktorch.pipelines.components.estimators import Estimator
from blocktorch.problem_types import ProblemTypes
from .blockwise_voting_regressor import Blockwise... | 0.961633 | 0.773388 |
"""Compute minibatch blobs for training a Fast R-CNN network."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import numpy.random as npr
from scipy.misc import imread
from model.utils.config import cfg
from model.utils.blob import prep... | lib/roi_data_layer/minibatch.py |
"""Compute minibatch blobs for training a Fast R-CNN network."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import numpy.random as npr
from scipy.misc import imread
from model.utils.config import cfg
from model.utils.blob import prep... | 0.877765 | 0.641338 |
# Standard library imports
from collections import OrderedDict
import os
import sys
from typing import Union, Optional, Tuple, List, Dict
import uuid
# Third part imports
from qtpy.QtCore import QEvent, QObject, QSize, Qt
from qtpy.QtWidgets import (
QAction, QProxyStyle, QStyle, QToolBar, QToolButton, QWidget)
#... | spyder/api/widgets/toolbars.py | # Standard library imports
from collections import OrderedDict
import os
import sys
from typing import Union, Optional, Tuple, List, Dict
import uuid
# Third part imports
from qtpy.QtCore import QEvent, QObject, QSize, Qt
from qtpy.QtWidgets import (
QAction, QProxyStyle, QStyle, QToolBar, QToolButton, QWidget)
#... | 0.677901 | 0.084041 |
windows = False
if windows:
directory = '//nas.sala.ubc.ca/ELabs/100_personal/nm/Databases/'
bca_dir = '//nas.sala.ubc.ca/ELabs/50_projects/16_PICS/07_BCA data/'
else:
directory = '/Volumes/Samsung_T5/Databases/'
bca_dir = '/Volumes/ELabs/50_projects/16_PICS/07_BCA data/'
modes = ['transit', 'bike', 'w... | SB0_Variables.py | windows = False
if windows:
directory = '//nas.sala.ubc.ca/ELabs/100_personal/nm/Databases/'
bca_dir = '//nas.sala.ubc.ca/ELabs/50_projects/16_PICS/07_BCA data/'
else:
directory = '/Volumes/Samsung_T5/Databases/'
bca_dir = '/Volumes/ELabs/50_projects/16_PICS/07_BCA data/'
modes = ['transit', 'bike', 'w... | 0.363421 | 0.359336 |
import pprint
import re # noqa: F401
import six
class PaymentRequestLivingAddress(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | cardpay/model/payment_request_living_address.py | import pprint
import re # noqa: F401
import six
class PaymentRequestLivingAddress(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | 0.778355 | 0.150934 |
import json
import random
import datetime
import core
import collections
import re
from core import localization
from core.helpers import Comparisons
''' Config
Config is a simple json object that is loaded into core.CONFIG as a dict
All sections and subsections must be capitalized. All keys must be lower-case.
No sp... | core/config.py | import json
import random
import datetime
import core
import collections
import re
from core import localization
from core.helpers import Comparisons
''' Config
Config is a simple json object that is loaded into core.CONFIG as a dict
All sections and subsections must be capitalized. All keys must be lower-case.
No sp... | 0.447943 | 0.108048 |
import json
import DeepInstinct
import demistomock as demisto
params = {
"apikey": "key",
"base_url": "https://demisto.poc.deepinstinctweb.com",
"after_id": 0
}
mock_device = {
"id": 1,
"os": "WINDOWS",
"osv": "Windows",
"ip_address": "192.168.88.80",
"mac_address": "00:00:00:00:00:00"... | Packs/DeepInstinct/Integrations/DeepInstinct/DeepInstinct_test.py | import json
import DeepInstinct
import demistomock as demisto
params = {
"apikey": "key",
"base_url": "https://demisto.poc.deepinstinctweb.com",
"after_id": 0
}
mock_device = {
"id": 1,
"os": "WINDOWS",
"osv": "Windows",
"ip_address": "192.168.88.80",
"mac_address": "00:00:00:00:00:00"... | 0.345436 | 0.341308 |
import asyncio
from tt_web import postgresql as db
from . import objects
def impact_from_row(row):
return objects.Impact(transaction=row['transaction'],
actor=objects.Object(row['actor_type'], row['actor']),
target=objects.Object(row['target_type'], row['targe... | src/tt_impacts/tt_impacts/operations.py | import asyncio
from tt_web import postgresql as db
from . import objects
def impact_from_row(row):
return objects.Impact(transaction=row['transaction'],
actor=objects.Object(row['actor_type'], row['actor']),
target=objects.Object(row['target_type'], row['targe... | 0.385375 | 0.177063 |
import argparse
import functools
import json
import os
import random
import subprocess
import sys
from multiprocessing import Pool
from pathlib import Path
from typing import Dict, Iterable, List, NamedTuple
import typing
import test_target
from test_target import TestTarget
import testvm
from test_config import CRAT... | tools/impl/test_runner.py |
import argparse
import functools
import json
import os
import random
import subprocess
import sys
from multiprocessing import Pool
from pathlib import Path
from typing import Dict, Iterable, List, NamedTuple
import typing
import test_target
from test_target import TestTarget
import testvm
from test_config import CRAT... | 0.666388 | 0.209844 |
import math
import torch
from catalyst.utils.metrics import average_precision
def test_average_precision_base():
"""
Tests for catalyst.utils.metrics.average_precision metric.
"""
outputs = torch.Tensor([0.1, 0.4, 0.35, 0.8])
targets = torch.Tensor([0, 0, 1, 1])
assert torch.isclose(
... | catalyst/utils/metrics/tests/test_average_precision.py | import math
import torch
from catalyst.utils.metrics import average_precision
def test_average_precision_base():
"""
Tests for catalyst.utils.metrics.average_precision metric.
"""
outputs = torch.Tensor([0.1, 0.4, 0.35, 0.8])
targets = torch.Tensor([0, 0, 1, 1])
assert torch.isclose(
... | 0.844152 | 0.761405 |
from datetime import datetime
from unittest.mock import ANY
from unittest.mock import MagicMock
import bs4
import pytest
from fakeparser import Parser
from reader import Content
from reader import HighlightedString
from reader import InvalidSearchQueryError
from reader import SearchError
from reader import StorageErr... | tests/test_search.py | from datetime import datetime
from unittest.mock import ANY
from unittest.mock import MagicMock
import bs4
import pytest
from fakeparser import Parser
from reader import Content
from reader import HighlightedString
from reader import InvalidSearchQueryError
from reader import SearchError
from reader import StorageErr... | 0.660939 | 0.370453 |
from google.cloud import bigquery
import pandas as pd
from datasources.covid_tracking_project_metadata import CtpMetadata
from datasources.data_source import DataSource
import ingestion.gcs_to_bq_util as gcs_to_bq_util
import ingestion.standardized_columns as col_std
from ingestion.standardized_columns import Race
#... | python/datasources/covid_tracking_project.py | from google.cloud import bigquery
import pandas as pd
from datasources.covid_tracking_project_metadata import CtpMetadata
from datasources.data_source import DataSource
import ingestion.gcs_to_bq_util as gcs_to_bq_util
import ingestion.standardized_columns as col_std
from ingestion.standardized_columns import Race
#... | 0.807802 | 0.371707 |
from functools import partial
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
from config import config
from base_model import resnet50
from seg_opr.seg_oprs import ConvBnRelu
from seg_opr.loss_opr import AntimagnetLoss
class CPNet(nn.Module):
def __init__(... | model/cpn/ablation_study/ade.cpn.R50_v1c.lcm/network.py | from functools import partial
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.functional as F
from config import config
from base_model import resnet50
from seg_opr.seg_oprs import ConvBnRelu
from seg_opr.loss_opr import AntimagnetLoss
class CPNet(nn.Module):
def __init__(... | 0.951006 | 0.274771 |
from typing import Dict, List, Optional, Tuple
from ee.clickhouse.client import sync_execute
from ee.clickhouse.models.cohort import format_cohort_table_name
from ee.clickhouse.sql.cohort import COHORT_DISTINCT_ID_FILTER_SQL
from ee.clickhouse.sql.events import EVENT_PROP_CLAUSE, SELECT_PROP_VALUES_SQL, SELECT_PROP_VA... | ee/clickhouse/models/property.py | from typing import Dict, List, Optional, Tuple
from ee.clickhouse.client import sync_execute
from ee.clickhouse.models.cohort import format_cohort_table_name
from ee.clickhouse.sql.cohort import COHORT_DISTINCT_ID_FILTER_SQL
from ee.clickhouse.sql.events import EVENT_PROP_CLAUSE, SELECT_PROP_VALUES_SQL, SELECT_PROP_VA... | 0.547948 | 0.179153 |
import numpy as nm
from sfepy.discrete.fem import Mesh
def refine_2_3(mesh_in):
"""
Refines mesh out of triangles by cutting cutting each edge in half
and making 4 new finer triangles out of one coarser one.
"""
cmesh = mesh_in.cmesh
# Unique edge centres.
e_centres = cmesh.get_centroids(... | sfepy/discrete/fem/refine.py | import numpy as nm
from sfepy.discrete.fem import Mesh
def refine_2_3(mesh_in):
"""
Refines mesh out of triangles by cutting cutting each edge in half
and making 4 new finer triangles out of one coarser one.
"""
cmesh = mesh_in.cmesh
# Unique edge centres.
e_centres = cmesh.get_centroids(... | 0.795539 | 0.602179 |
import yaml
import sys
import re
class Constants:
KEY_CONFIG_FILES = "config_files"
KEY_BASE_DOCKERFILE_TEMPLATE = "base_dockerfile_template"
KEY_CONFIG_LOADER_SH_TEMPLATE = "config_loader_sh_template"
KEY_OUTPUT_DIR = "output_dir"
KEY_PATH = "path"
KEY_FILENAME = "filename"
CONFIG_LOADER... | src/utils/config_loader_generator/config_loader_generator.py |
import yaml
import sys
import re
class Constants:
KEY_CONFIG_FILES = "config_files"
KEY_BASE_DOCKERFILE_TEMPLATE = "base_dockerfile_template"
KEY_CONFIG_LOADER_SH_TEMPLATE = "config_loader_sh_template"
KEY_OUTPUT_DIR = "output_dir"
KEY_PATH = "path"
KEY_FILENAME = "filename"
CONFIG_LOADER... | 0.269133 | 0.051035 |
import unittest
from adjudicator.state import data_to_state
from adjudicator import order
from adjudicator.territory import CoastalTerritory, InlandTerritory, \
SeaTerritory
class TestDataToState(unittest.TestCase):
def test_sea_territory(self):
data = {
'orders': [],
'pieces... | adjudicator/tests/test_data_to_state.py | import unittest
from adjudicator.state import data_to_state
from adjudicator import order
from adjudicator.territory import CoastalTerritory, InlandTerritory, \
SeaTerritory
class TestDataToState(unittest.TestCase):
def test_sea_territory(self):
data = {
'orders': [],
'pieces... | 0.433862 | 0.57081 |
import re
from resolv.shared import ResolverError, TechnicalError, unescape, Task
class PutlockerTask(Task):
result_type = "video"
name = "PutLocker"
author = "<NAME>"
author_url = "http://cryto.net/~joepie91"
def run(self):
try:
import mechanize
except ImportError:
self.state = "failed"
raise Te... | resolv/resolvers/putlocker.py | import re
from resolv.shared import ResolverError, TechnicalError, unescape, Task
class PutlockerTask(Task):
result_type = "video"
name = "PutLocker"
author = "<NAME>"
author_url = "http://cryto.net/~joepie91"
def run(self):
try:
import mechanize
except ImportError:
self.state = "failed"
raise Te... | 0.134378 | 0.108566 |
import typing as _typing
import apache.thrift.metadata.lite_types as _fbthrift_metadata
import folly.iobuf as _fbthrift_iobuf
from thrift.py3lite.client import (
AsyncClient as _fbthrift_py3lite_AsyncClient,
SyncClient as _fbthrift_py3lite_SyncClient,
Client as _fbthrift_py3lite_Client,
)
import thrift.py... | thrift/compiler/test/fixtures/basic/gen-py3lite/module/lite_clients.py |
import typing as _typing
import apache.thrift.metadata.lite_types as _fbthrift_metadata
import folly.iobuf as _fbthrift_iobuf
from thrift.py3lite.client import (
AsyncClient as _fbthrift_py3lite_AsyncClient,
SyncClient as _fbthrift_py3lite_SyncClient,
Client as _fbthrift_py3lite_Client,
)
import thrift.py... | 0.433622 | 0.051678 |
from a10sdk.common.A10BaseClass import A10BaseClass
class SslModuleStats(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param total_enabled_crypto_engines: {"type": "number", "description": "Number of enabled crypto engines", "format": "number"}
:param requests_han... | a10sdk/core/slb/slb_ssl_stats_oper.py | from a10sdk.common.A10BaseClass import A10BaseClass
class SslModuleStats(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param total_enabled_crypto_engines: {"type": "number", "description": "Number of enabled crypto engines", "format": "number"}
:param requests_han... | 0.822403 | 0.327668 |
import logging
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import workflows
from openstack_dashboard import api
from openstack_dashboard.dashboards.project.networks import workflows \
a... | openstack_dashboard/dashboards/project/networks/subnets/workflows.py |
import logging
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import workflows
from openstack_dashboard import api
from openstack_dashboard.dashboards.project.networks import workflows \
a... | 0.516108 | 0.086323 |
import json
import os
from typing import Any, Dict, List, Optional, Tuple, Union
import structlog
from celery import group
from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.core.cache import cache
from django.db.models import Q
from django.db.models.expressions import F
from... | posthog/tasks/update_cache.py | import json
import os
from typing import Any, Dict, List, Optional, Tuple, Union
import structlog
from celery import group
from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.core.cache import cache
from django.db.models import Q
from django.db.models.expressions import F
from... | 0.645679 | 0.109539 |
import os
from pathlib import Path
import json
import attr
from ..utils.messenger import send_message, make_message, gen_uuid, now, AuditFlag
from .helpers import ensure_list, gather_runtime_info
class Audit:
"""Handle provenance tracking and resource utilization."""
def __init__(self, audit_flags, messenger... | pydra/engine/audit.py | import os
from pathlib import Path
import json
import attr
from ..utils.messenger import send_message, make_message, gen_uuid, now, AuditFlag
from .helpers import ensure_list, gather_runtime_info
class Audit:
"""Handle provenance tracking and resource utilization."""
def __init__(self, audit_flags, messenger... | 0.677367 | 0.170335 |
from argparse import ArgumentParser
import yaml
from pathlib import Path
import dir_search
import yaml_utils
def parser():
# parser information setup
prog='parse_dir'
description = 'Parse directories ' + \
'to create yaml file read on database creation'
usage = 'usage: python3 {} ' .format(__fi... | doc/scripts/parse_dir.py | from argparse import ArgumentParser
import yaml
from pathlib import Path
import dir_search
import yaml_utils
def parser():
# parser information setup
prog='parse_dir'
description = 'Parse directories ' + \
'to create yaml file read on database creation'
usage = 'usage: python3 {} ' .format(__fi... | 0.386995 | 0.077413 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from requests import codes
from time import time
from uber_rides.errors import ClientError
from uber_rides.errors import UberIllegalState
from uber_rides.utils import a... | venv/lib/python2.7/site-packages/uber_rides/session.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from requests import codes
from time import time
from uber_rides.errors import ClientError
from uber_rides.errors import UberIllegalState
from uber_rides.utils import a... | 0.847306 | 0.118131 |
import os
from cStringIO \
import \
StringIO
from bento.core \
import \
PackageDescription, PackageOptions
from bento.core.pkg_objects \
import \
Extension, CompiledLibrary
from bento.core.package \
import \
raw_parse, raw_to_pkg_kw, build_ast_from_raw_dict, PackageDesc... | bento/commands/tests/utils.py | import os
from cStringIO \
import \
StringIO
from bento.core \
import \
PackageDescription, PackageOptions
from bento.core.pkg_objects \
import \
Extension, CompiledLibrary
from bento.core.package \
import \
raw_parse, raw_to_pkg_kw, build_ast_from_raw_dict, PackageDesc... | 0.197987 | 0.105441 |
from enum import Enum, EnumMeta
from six import with_metaclass
class _CaseInsensitiveEnumMeta(EnumMeta):
def __getitem__(self, name):
return super().__getitem__(name.upper())
def __getattr__(cls, name):
"""Return the enum member matching `name`
We use __getattr__ instead of descriptor... | sdk/labservices/azure-mgmt-labservices/azure/mgmt/labservices/models/_managed_labs_client_enums.py |
from enum import Enum, EnumMeta
from six import with_metaclass
class _CaseInsensitiveEnumMeta(EnumMeta):
def __getitem__(self, name):
return super().__getitem__(name.upper())
def __getattr__(cls, name):
"""Return the enum member matching `name`
We use __getattr__ instead of descriptor... | 0.783368 | 0.125467 |
from typing import Callable, Dict, Optional, Sequence, Tuple
from functools import partial
import numpy as np
import torch
from torch import Tensor
from torch.nn import functional as F
# @TODO:
# after full classification metrics re-implementation, make a reference to
# https://github.com/scikit-learn/scikit-learn/b... | catalyst/metrics/functional.py | from typing import Callable, Dict, Optional, Sequence, Tuple
from functools import partial
import numpy as np
import torch
from torch import Tensor
from torch.nn import functional as F
# @TODO:
# after full classification metrics re-implementation, make a reference to
# https://github.com/scikit-learn/scikit-learn/b... | 0.894709 | 0.777553 |
import sys
from jsonschema import ValidationError
from .error import MetadataNotFoundError
from .metadata_app_utils import AppBase, CliOption, Flag, SchemaProperty, MetadataSchemaProperty
from .metadata import Metadata
from .manager import MetadataManager
from .schema import SchemaManager
class NamespaceBase(AppBas... | elyra/metadata/metadata_app.py | import sys
from jsonschema import ValidationError
from .error import MetadataNotFoundError
from .metadata_app_utils import AppBase, CliOption, Flag, SchemaProperty, MetadataSchemaProperty
from .metadata import Metadata
from .manager import MetadataManager
from .schema import SchemaManager
class NamespaceBase(AppBas... | 0.449634 | 0.086942 |
import dgl
import numpy as np
from pathlib import Path
import torch
from deepstochlog.term import Term, List
from deepstochlog.context import ContextualizedTerm, Context
from deepstochlog.dataset import ContextualizedTermDataset
root_path = Path(__file__).parent
dataset = dgl.data.CiteseerGraphDataset()
g = dataset... | examples/citeseer/with_rule_weights/citeseer_data_withrules.py | import dgl
import numpy as np
from pathlib import Path
import torch
from deepstochlog.term import Term, List
from deepstochlog.context import ContextualizedTerm, Context
from deepstochlog.dataset import ContextualizedTermDataset
root_path = Path(__file__).parent
dataset = dgl.data.CiteseerGraphDataset()
g = dataset... | 0.301362 | 0.47171 |
import numpy as np
import matplotlib.pyplot as plt
## Performs LU factorization with partial pivoting
def lup(A):
m = A.shape[0]
U = A.copy()
L, P = np.eye(m), np.eye(m)
for k in range(m-1):
# Selects the index of the max element and swaps the required rows
i = k + np.argmax(abs(U[k:,k]))
U[[k,i],k:] = U[... | A3/Q6.py | import numpy as np
import matplotlib.pyplot as plt
## Performs LU factorization with partial pivoting
def lup(A):
m = A.shape[0]
U = A.copy()
L, P = np.eye(m), np.eye(m)
for k in range(m-1):
# Selects the index of the max element and swaps the required rows
i = k + np.argmax(abs(U[k:,k]))
U[[k,i],k:] = U[... | 0.400046 | 0.513485 |
import dataclasses
from typing import Collection
import structlog
from covidactnow.datapublic.common_fields import CommonFields
from covidactnow.datapublic.common_fields import PdFields
from libs.datasets import timeseries
import pandas as pd
_log = structlog.get_logger()
DROPPING_TIMESERIES_WITH_ONLY_ZEROS = "Dr... | libs/datasets/sources/zeros_filter.py | import dataclasses
from typing import Collection
import structlog
from covidactnow.datapublic.common_fields import CommonFields
from covidactnow.datapublic.common_fields import PdFields
from libs.datasets import timeseries
import pandas as pd
_log = structlog.get_logger()
DROPPING_TIMESERIES_WITH_ONLY_ZEROS = "Dr... | 0.750644 | 0.312213 |
from pprint import pformat
from six import iteritems
import re
class Subnet(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | purity_fb/purity_fb_1dot9/models/subnet.py | from pprint import pformat
from six import iteritems
import re
class Subnet(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | 0.69987 | 0.126677 |
import base64
import logging
import os
import sys
import urllib.parse
import uuid
# Installed packages
import boto3
from boto3.dynamodb.conditions import Key
from flask import Blueprint
from flask import Flask
from flask import request
from flask import Response
from prometheus_flask_exporter import PrometheusMetri... | db/app-tpl.py | import base64
import logging
import os
import sys
import urllib.parse
import uuid
# Installed packages
import boto3
from boto3.dynamodb.conditions import Key
from flask import Blueprint
from flask import Flask
from flask import request
from flask import Response
from prometheus_flask_exporter import PrometheusMetri... | 0.384103 | 0.061848 |
from untils import until, Event
from Addon import Addon, middelware, addon_init
from Template import str_back
L = {'азербайджанский': 'az', 'малаялам': 'ml', 'албанский': 'sq', 'мальтийский': 'mt', 'амхарский': 'am',
'македонский': 'mk', 'английский': 'en', 'маори': 'mi', 'арабский': 'ar', 'мара... | addons/translator/translator.py | from untils import until, Event
from Addon import Addon, middelware, addon_init
from Template import str_back
L = {'азербайджанский': 'az', 'малаялам': 'ml', 'албанский': 'sq', 'мальтийский': 'mt', 'амхарский': 'am',
'македонский': 'mk', 'английский': 'en', 'маори': 'mi', 'арабский': 'ar', 'мара... | 0.169578 | 0.399929 |
import os
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
class TestRule4c:
def __init__(self):
self.g_ba... | resources/test_cases/python/cryptography/TestRule4c.py | import os
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
class TestRule4c:
def __init__(self):
self.g_ba... | 0.712932 | 0.232735 |
from __future__ import division
from __future__ import print_function
from builtins import range
import numpy as np
import os
import gzip
import argparse
try:
import pickle
except ImportError:
import cPickle as pickle
from singa import initializer
from singa import optimizer
from singa import device
from sing... | examples/mnist/train.py | from __future__ import division
from __future__ import print_function
from builtins import range
import numpy as np
import os
import gzip
import argparse
try:
import pickle
except ImportError:
import cPickle as pickle
from singa import initializer
from singa import optimizer
from singa import device
from sing... | 0.581065 | 0.315169 |
import pathlib
import pickle
import time
from flexcache import DiskCacheByHash
# These sleep time is needed when run on GitHub Actions
# If not given or too short, some mtime changes are not visible.
FS_SLEEP = 0.010
def parser(p: pathlib.Path):
return p.read_bytes()
def test_file_changed(tmp_path):
# Gen... | flexcache/testsuite/test_byhash.py | import pathlib
import pickle
import time
from flexcache import DiskCacheByHash
# These sleep time is needed when run on GitHub Actions
# If not given or too short, some mtime changes are not visible.
FS_SLEEP = 0.010
def parser(p: pathlib.Path):
return p.read_bytes()
def test_file_changed(tmp_path):
# Gen... | 0.398758 | 0.36591 |
import py
from pypy.lang.smalltalk import squeakimage
from pypy.lang.smalltalk.squeakimage import chrs2int
from pypy.lang.smalltalk import objspace
space = objspace.ObjSpace()
# ----- helpers ----------------------------------------------
def ints2str(*ints):
import struct
return struct.pack(">" + "i" * len(... | pypy/lang/smalltalk/test/test_squeakimage.py | import py
from pypy.lang.smalltalk import squeakimage
from pypy.lang.smalltalk.squeakimage import chrs2int
from pypy.lang.smalltalk import objspace
space = objspace.ObjSpace()
# ----- helpers ----------------------------------------------
def ints2str(*ints):
import struct
return struct.pack(">" + "i" * len(... | 0.382141 | 0.682529 |
import tensorflow as tf
from ...utils.utils import merge_two_last_dims, shape_list
class TimeReduction(tf.keras.layers.Layer):
def __init__(self, factor: int, name: str = "TimeReduction", **kwargs):
super(TimeReduction, self).__init__(name=name, **kwargs)
self.time_reduction_factor = factor
... | tensorflow_asr/models/layers/subsampling.py |
import tensorflow as tf
from ...utils.utils import merge_two_last_dims, shape_list
class TimeReduction(tf.keras.layers.Layer):
def __init__(self, factor: int, name: str = "TimeReduction", **kwargs):
super(TimeReduction, self).__init__(name=name, **kwargs)
self.time_reduction_factor = factor
... | 0.953264 | 0.468608 |
from qtpy.QtWidgets import QProgressBar, QVBoxLayout, QHBoxLayout, QLabel, QSlider, QWidget, QSpacerItem, QSizePolicy
from qtpy import QtCore
import pyqtgraph as pg
import numpy as np
from __code._utilities.parent import Parent
from __code.radial_profile.event_handler import EventHandler
class Initialization(Parent)... | notebooks/__code/radial_profile/initialization.py | from qtpy.QtWidgets import QProgressBar, QVBoxLayout, QHBoxLayout, QLabel, QSlider, QWidget, QSpacerItem, QSizePolicy
from qtpy import QtCore
import pyqtgraph as pg
import numpy as np
from __code._utilities.parent import Parent
from __code.radial_profile.event_handler import EventHandler
class Initialization(Parent)... | 0.530236 | 0.192084 |
import tensorflow.compat.v1 as tf
from model_pruning.python import pruning_hook
class MockPruningObject(object):
"""Mock Pruning Object that has a run_update_step() function."""
def __init__(self):
self.logged_steps = []
def run_update_step(self, session, global_step): # pylint: disable=unused-argument
... | model_pruning/python/pruning_hook_test.py | import tensorflow.compat.v1 as tf
from model_pruning.python import pruning_hook
class MockPruningObject(object):
"""Mock Pruning Object that has a run_update_step() function."""
def __init__(self):
self.logged_steps = []
def run_update_step(self, session, global_step): # pylint: disable=unused-argument
... | 0.803058 | 0.401864 |
import errno
from abc import abstractmethod
import os
import struct
from twitter.common import log
from twitter.common.lang import Compatibility, Interface
from .filelike import FileLike
class RecordIO(object):
class Error(Exception): pass
class PrematureEndOfStream(Error): pass
class RecordSizeExceeded(Error... | src/python/twitter/common/recordio/recordio.py | import errno
from abc import abstractmethod
import os
import struct
from twitter.common import log
from twitter.common.lang import Compatibility, Interface
from .filelike import FileLike
class RecordIO(object):
class Error(Exception): pass
class PrematureEndOfStream(Error): pass
class RecordSizeExceeded(Error... | 0.630685 | 0.186206 |
from fatartifacts.database import base
from datetime import datetime
from pony import orm
from typing import *
import threading
def declare_entities(db):
class Location(db.Entity):
name = orm.Optional(str)
parent = orm.Optional('Location', reverse='children')
children = orm.Set('Location', cascade_dele... | fatartifacts/database/ponyorm.py | from fatartifacts.database import base
from datetime import datetime
from pony import orm
from typing import *
import threading
def declare_entities(db):
class Location(db.Entity):
name = orm.Optional(str)
parent = orm.Optional('Location', reverse='children')
children = orm.Set('Location', cascade_dele... | 0.647687 | 0.120801 |
from tornado.escape import json_encode
from tornado.web import RequestHandler
from webspider import constants
from webspider.exceptions import BaseException, ResourceNotFoundWebException
from webspider.web.formatter import Formatter
from webspider.utils.sql import remove_sessions
class BaseApiHandler(RequestHandler)... | webspider/web/handlers/base.py | from tornado.escape import json_encode
from tornado.web import RequestHandler
from webspider import constants
from webspider.exceptions import BaseException, ResourceNotFoundWebException
from webspider.web.formatter import Formatter
from webspider.utils.sql import remove_sessions
class BaseApiHandler(RequestHandler)... | 0.245899 | 0.061171 |
from typing import cast, List, Optional, Tuple
import argparse
import asyncio
from dataclasses import dataclass
import itertools
import random
import sys
import numpy as np
import cirq
def build_circuit() -> Tuple[cirq.Circuit, List[cirq.Qid]]:
# Builds an arbitrary circuit to test. Do not include a measurement g... | examples/direct_fidelity_estimation.py | from typing import cast, List, Optional, Tuple
import argparse
import asyncio
from dataclasses import dataclass
import itertools
import random
import sys
import numpy as np
import cirq
def build_circuit() -> Tuple[cirq.Circuit, List[cirq.Qid]]:
# Builds an arbitrary circuit to test. Do not include a measurement g... | 0.919199 | 0.645399 |
import pytest
import pandas as pd
from pandas import Series, TimedeltaIndex
class TestTimedeltaIndexRendering:
@pytest.mark.parametrize("method", ["__repr__", "__str__"])
def test_representation(self, method):
idx1 = TimedeltaIndex([], freq="D")
idx2 = TimedeltaIndex(["1 days"], freq="D")
... | pandas/tests/indexes/timedeltas/test_formats.py | import pytest
import pandas as pd
from pandas import Series, TimedeltaIndex
class TestTimedeltaIndexRendering:
@pytest.mark.parametrize("method", ["__repr__", "__str__"])
def test_representation(self, method):
idx1 = TimedeltaIndex([], freq="D")
idx2 = TimedeltaIndex(["1 days"], freq="D")
... | 0.560253 | 0.725916 |