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 |
|---|---|---|---|---|
import os
import fire
from alive_progress import alive_bar
from typing import Union
from validator import is_dir, is_extension, is_bool, is_in_range, is_positive_number
from utils import natural_keys, show_info, setup_logger, append_prefix, enumerate_with_step, gen_random_filename, UserResponse, ask
logger = setup_lo... | src/rename_to_sequential.py | import os
import fire
from alive_progress import alive_bar
from typing import Union
from validator import is_dir, is_extension, is_bool, is_in_range, is_positive_number
from utils import natural_keys, show_info, setup_logger, append_prefix, enumerate_with_step, gen_random_filename, UserResponse, ask
logger = setup_lo... | 0.721449 | 0.133924 |
import dolfin
from ocellaris.utils import ocellaris_error, OcellarisCppExpression
from . import register_known_field, KnownField, DEFAULT_POLYDEG
@register_known_field('VectorField')
class VectorField(KnownField):
description = 'Vector field'
def __init__(self, simulation, field_inp):
"""
A ... | ocellaris/solver_parts/fields/vector_field.py |
import dolfin
from ocellaris.utils import ocellaris_error, OcellarisCppExpression
from . import register_known_field, KnownField, DEFAULT_POLYDEG
@register_known_field('VectorField')
class VectorField(KnownField):
description = 'Vector field'
def __init__(self, simulation, field_inp):
"""
A ... | 0.600071 | 0.395193 |
from .utils import (
TestCase,
CustomException,
run_tests_in_session,
)
import itertools
import slash
from slash.loader import Loader
class TestTest(TestCase):
"""
Test the :class:`Test` class, which is the quickest way to create test classes in Slash
"""
def test_test_class(self):
... | tests/test_test.py | from .utils import (
TestCase,
CustomException,
run_tests_in_session,
)
import itertools
import slash
from slash.loader import Loader
class TestTest(TestCase):
"""
Test the :class:`Test` class, which is the quickest way to create test classes in Slash
"""
def test_test_class(self):
... | 0.558327 | 0.544317 |
import datetime
import functools
import maya.cmds as cmds
def undo_chunk(function):
""" Undo チャンク用デコレーター """
@functools.wraps(function)
def wrapper(*args, **kwargs):
cmds.undoInfo(ock=True)
ret = function(*args, **kwargs)
cmds.undoInfo(cck=True)
return ret
return wra... | nnutil/decorator.py |
import datetime
import functools
import maya.cmds as cmds
def undo_chunk(function):
""" Undo チャンク用デコレーター """
@functools.wraps(function)
def wrapper(*args, **kwargs):
cmds.undoInfo(ock=True)
ret = function(*args, **kwargs)
cmds.undoInfo(cck=True)
return ret
return wra... | 0.400046 | 0.136206 |
import unittest
import json
import os
from neural_net import NeuralNet
class CreateFromFileTests(unittest.TestCase):
def make_temp_params_file(self, net_params):
self.net_params = net_params
os.makedirs('test_temp', exist_ok=True)
fname = os.path.join('test_temp', 'neural_net.json')
... | tests/neural_net/create_from_file_tests.py | import unittest
import json
import os
from neural_net import NeuralNet
class CreateFromFileTests(unittest.TestCase):
def make_temp_params_file(self, net_params):
self.net_params = net_params
os.makedirs('test_temp', exist_ok=True)
fname = os.path.join('test_temp', 'neural_net.json')
... | 0.532182 | 0.450722 |
import os
import glob
from setuptools import setup, find_packages
from setuptools import Extension
from Cython.Build import cythonize
from Cython.Distutils import build_ext
with open('README.rst') as f:
long_description = f.read()
def read_requirements(path):
"""
递归读取requirements
:param path: path... | setup.py | import os
import glob
from setuptools import setup, find_packages
from setuptools import Extension
from Cython.Build import cythonize
from Cython.Distutils import build_ext
with open('README.rst') as f:
long_description = f.read()
def read_requirements(path):
"""
递归读取requirements
:param path: path... | 0.325199 | 0.130729 |
from math import log
def epmi(matrix):
"""
Exponential pointwise mutual information
"""
row_sum = matrix.sum(axis=1)
col_sum = matrix.sum(axis=0)
total = row_sum.sum(axis=0)[0, 0]
inv_col_sum = 1 / col_sum # shape (1,n)
inv_row_sum = 1 / row_sum # shape (n,1)
inv_col_sum = inv... | pydsm/weighting.py | from math import log
def epmi(matrix):
"""
Exponential pointwise mutual information
"""
row_sum = matrix.sum(axis=1)
col_sum = matrix.sum(axis=0)
total = row_sum.sum(axis=0)[0, 0]
inv_col_sum = 1 / col_sum # shape (1,n)
inv_row_sum = 1 / row_sum # shape (n,1)
inv_col_sum = inv... | 0.75101 | 0.788949 |
from obspy import UTCDateTime
import numpy as np
import pickle
import stdb
from obspy.clients.fdsn import Client
from splitpy import Split, utils
from . import test_args, get_meta
from pathlib import Path
def test_split(tmp_path):
args = test_args.test_get_args_calc_auto()
args.startT = UTCDateTime('2016-08-2... | splitpy/tests/test_scripts.py | from obspy import UTCDateTime
import numpy as np
import pickle
import stdb
from obspy.clients.fdsn import Client
from splitpy import Split, utils
from . import test_args, get_meta
from pathlib import Path
def test_split(tmp_path):
args = test_args.test_get_args_calc_auto()
args.startT = UTCDateTime('2016-08-2... | 0.362518 | 0.135775 |
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, NoAlertPresentException
class Application:
def __init__(self):
self.wd = webdriver.Firefox()
self.wd.implicitly_wait(30)
def logout(self):
wd = self.wd
wd.find_element_by_link_text("... | application.py | from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, NoAlertPresentException
class Application:
def __init__(self):
self.wd = webdriver.Firefox()
self.wd.implicitly_wait(30)
def logout(self):
wd = self.wd
wd.find_element_by_link_text("... | 0.424173 | 0.04879 |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
unescapeHTML,
)
class FlickrIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.|secure\.)?flickr\.com/photos/(?P<uploader_id>[\w\-_@]+)/(?P<id>\d+).*'
_TEST = {
'url': 'h... | youtube_dl/extractor/flickr.py | from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
unescapeHTML,
)
class FlickrIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.|secure\.)?flickr\.com/photos/(?P<uploader_id>[\w\-_@]+)/(?P<id>\d+).*'
_TEST = {
'url': 'h... | 0.453262 | 0.148973 |
import argparse
import json
import logging
import pickle
import re
from collections import Counter, defaultdict
import torch
from pyrocov.fasta import NextcladeDB
logger = logging.getLogger(__name__)
logging.basicConfig(format="%(relativeCreated) 9d %(message)s", level=logging.INFO)
def count_mutations(mutation_c... | featurize_nextclade.py |
import argparse
import json
import logging
import pickle
import re
from collections import Counter, defaultdict
import torch
from pyrocov.fasta import NextcladeDB
logger = logging.getLogger(__name__)
logging.basicConfig(format="%(relativeCreated) 9d %(message)s", level=logging.INFO)
def count_mutations(mutation_c... | 0.61115 | 0.174692 |
from queue import PriorityQueue
from objects.node import Node
def greedySearch(grid, intitialNode, goalNode):
frontier = PriorityQueue()
grid.matrix[intitialNode.x][intitialNode.y].visited = True
grid.matrix[intitialNode.x][intitialNode.y].value = "00"
grid.matrix[intitialNode.x][intitialNode.y].cost... | algorithms/greedySearch.py | from queue import PriorityQueue
from objects.node import Node
def greedySearch(grid, intitialNode, goalNode):
frontier = PriorityQueue()
grid.matrix[intitialNode.x][intitialNode.y].visited = True
grid.matrix[intitialNode.x][intitialNode.y].value = "00"
grid.matrix[intitialNode.x][intitialNode.y].cost... | 0.348423 | 0.573738 |
import pandas as pd
from sklearn import preprocessing
from .transformation import Transformation
class Scale(Transformation):
title = "Scale {field} using a {method} scaler"
key = "Scale"
is_global = True
fields = {
"field": {"name": "Fields", "type": "string", "help": "The fields to scale","r... | data_scout/transformations/preprocessing.py | import pandas as pd
from sklearn import preprocessing
from .transformation import Transformation
class Scale(Transformation):
title = "Scale {field} using a {method} scaler"
key = "Scale"
is_global = True
fields = {
"field": {"name": "Fields", "type": "string", "help": "The fields to scale","r... | 0.799794 | 0.384854 |
from django.test import TestCase
from backend.models import Festival
from backend.tests.helpers import login, create_user, create_festival
from backend.tests.helpers import create_client
class DeleteFestivalTests(TestCase):
def test_no_client_name_provided(self):
"""
delete_festival() is to retur... | backend/tests/test_delete_festival.py | from django.test import TestCase
from backend.models import Festival
from backend.tests.helpers import login, create_user, create_festival
from backend.tests.helpers import create_client
class DeleteFestivalTests(TestCase):
def test_no_client_name_provided(self):
"""
delete_festival() is to retur... | 0.459804 | 0.099558 |
from pathlib import Path
from openeo_classification.features import *
from openeo_classification.sample import *
from openeo_classification.connection import creo
from openeo_classification.job_management import *
import openeo_classification
import os
import pandas as pd
from openeo_classification.connection import c... | src/openeo_classification/scripts/extract_samples.py | from pathlib import Path
from openeo_classification.features import *
from openeo_classification.sample import *
from openeo_classification.connection import creo
from openeo_classification.job_management import *
import openeo_classification
import os
import pandas as pd
from openeo_classification.connection import c... | 0.494141 | 0.26719 |
import rospy
from hal_hw_interface.hal_obj_base import HalObjBase
from hal_hw_interface.exception import HalHWInterfaceException
class RosHalComponent(HalObjBase):
"""Base class implementing a HAL user component in a ROS node
This class provides the skeleton of a ROS node that runs a
Machinekit HAL user ... | hal_hw_interface/src/hal_hw_interface/ros_hal_component.py | import rospy
from hal_hw_interface.hal_obj_base import HalObjBase
from hal_hw_interface.exception import HalHWInterfaceException
class RosHalComponent(HalObjBase):
"""Base class implementing a HAL user component in a ROS node
This class provides the skeleton of a ROS node that runs a
Machinekit HAL user ... | 0.737347 | 0.416797 |
import os
import lmdb # install lmdb by "pip install lmdb"
from PIL import Image
def checkImageIsValid(file):
valid = True
try:
Image.open(file).load()
except OSError:
valid = False
return valid
def writeCache(env, cache):
with env.begin(write=True) as txn:
for k, v in cac... | tools/create_dataset_ic13.py | import os
import lmdb # install lmdb by "pip install lmdb"
from PIL import Image
def checkImageIsValid(file):
valid = True
try:
Image.open(file).load()
except OSError:
valid = False
return valid
def writeCache(env, cache):
with env.begin(write=True) as txn:
for k, v in cac... | 0.180612 | 0.120206 |
from IMLearn.learners import UnivariateGaussian, MultivariateGaussian
import numpy as np
import plotly.graph_objects as go
import plotly.io as pio
pio.templates.default = "simple_white"
def test_univariate_gaussian():
# Question 1 - Draw samples and print fitted model
uni_gauss = UnivariateGaussian()
X = ... | exercises/fit_gaussian_estimators.py | from IMLearn.learners import UnivariateGaussian, MultivariateGaussian
import numpy as np
import plotly.graph_objects as go
import plotly.io as pio
pio.templates.default = "simple_white"
def test_univariate_gaussian():
# Question 1 - Draw samples and print fitted model
uni_gauss = UnivariateGaussian()
X = ... | 0.857917 | 0.596962 |
from __future__ import annotations
from abc import ABC
from typing import List, Iterator, Optional, Tuple, FrozenSet, Iterable, Union
from sahyun_bot.commander_settings import Command, ResponseHook, DEFAULT_MAX_SEARCH, DEFAULT_MAX_PICK, DEFAULT_MAX_PRINT
from sahyun_bot.elastic import CustomDLC
from sahyun_bot.link_j... | sahyun_bot/commands/request_queue.py | from __future__ import annotations
from abc import ABC
from typing import List, Iterator, Optional, Tuple, FrozenSet, Iterable, Union
from sahyun_bot.commander_settings import Command, ResponseHook, DEFAULT_MAX_SEARCH, DEFAULT_MAX_PICK, DEFAULT_MAX_PRINT
from sahyun_bot.elastic import CustomDLC
from sahyun_bot.link_j... | 0.910369 | 0.18567 |
from apps.grabbo.models import Company
import pytest
@pytest.mark.django_db
class TestModelStrings:
def test_job_board_string(self, job_board):
assert str(job_board) == job_board.name
def test_company_str(self, company):
assert str(company) == company.name
def test_job_location_str(self... | apps/grabbo/tests/test_models.py | from apps.grabbo.models import Company
import pytest
@pytest.mark.django_db
class TestModelStrings:
def test_job_board_string(self, job_board):
assert str(job_board) == job_board.name
def test_company_str(self, company):
assert str(company) == company.name
def test_job_location_str(self... | 0.566139 | 0.515681 |
from unittest import TestCase
from trollbox.image_model import ImageModel
from PySide.QtGui import QApplication
from PySide.QtCore import Qt
import json, tempfile, os, subprocess
app = None
class Test_ImageModel(TestCase):
def setUp(self):
global app
if not app:
app = QApplication([])... | trollbox/test/test_image_model.py | from unittest import TestCase
from trollbox.image_model import ImageModel
from PySide.QtGui import QApplication
from PySide.QtCore import Qt
import json, tempfile, os, subprocess
app = None
class Test_ImageModel(TestCase):
def setUp(self):
global app
if not app:
app = QApplication([])... | 0.379034 | 0.333476 |
import argparse
import json
import sys
from ssl import SSLContext, PROTOCOL_SSLv23
requiredArgs = {
'api_key': 'Sms77.io API key',
'to': 'Receiver(s) separated by comma',
'text': 'Message text'
}
def bool_arg(obj):
return dict(obj, **{
'action': 'store_const',
'const': 1,
})
op... | sms77.py |
import argparse
import json
import sys
from ssl import SSLContext, PROTOCOL_SSLv23
requiredArgs = {
'api_key': 'Sms77.io API key',
'to': 'Receiver(s) separated by comma',
'text': 'Message text'
}
def bool_arg(obj):
return dict(obj, **{
'action': 'store_const',
'const': 1,
})
op... | 0.386532 | 0.087447 |
print """\033[033m
____ ____ _____
/ ___|___ / ____ _ __ _ _ /__ /_____
\___ \ |_ \| __|| '__|| | | | / /| ____|
___) ___) | |__ | | | |_| | / /_ | ____|
|____/____/|____||_| \__,_|/____/|_____|
Release v1.3
By @JR0ch17\033[0m
"""
import sys, os, commands, requests
from argparse ... | s3cruze.py |
print """\033[033m
____ ____ _____
/ ___|___ / ____ _ __ _ _ /__ /_____
\___ \ |_ \| __|| '__|| | | | / /| ____|
___) ___) | |__ | | | |_| | / /_ | ____|
|____/____/|____||_| \__,_|/____/|_____|
Release v1.3
By @JR0ch17\033[0m
"""
import sys, os, commands, requests
from argparse ... | 0.211824 | 0.058615 |
import json
import os
import jsonschema
from pkg_resources import resource_filename
class MetFile:
"""Class used to read and write .json catalog metadata files."""
SCHEMA_PATH = resource_filename('opera', 'schema/catalog_metadata_schema.json')
def __init__(self, met_dict=None):
"""
Con... | src/opera/util/metfile.py | import json
import os
import jsonschema
from pkg_resources import resource_filename
class MetFile:
"""Class used to read and write .json catalog metadata files."""
SCHEMA_PATH = resource_filename('opera', 'schema/catalog_metadata_schema.json')
def __init__(self, met_dict=None):
"""
Con... | 0.747432 | 0.156975 |
import requests
from .base import Base
from pastry.exceptions import HttpError
from pastry.pastry_client import PastryClient
class Cookbooks(Base):
'''
Provides methods for interacting with chef cookbooks
'''
_base_url = '/organizations/%(org)s/cookbooks'
@classmethod
def index(cls):
... | pastry/resources/cookbooks.py |
import requests
from .base import Base
from pastry.exceptions import HttpError
from pastry.pastry_client import PastryClient
class Cookbooks(Base):
'''
Provides methods for interacting with chef cookbooks
'''
_base_url = '/organizations/%(org)s/cookbooks'
@classmethod
def index(cls):
... | 0.737631 | 0.204481 |
import pytest
from open_alchemy.models_file import types
from open_alchemy.models_file.model import source as models_source
_SQLAlchemyModelArtifacts = types.SQLAlchemyModelArtifacts
_ArgArtifacts = types.ArgArtifacts
_ColumnArtifacts = types.ColumnArtifacts
_ColumnArgArtifacts = types.ColumnArgArtifacts
_TypedDictA... | tests/open_alchemy/models_file/model/test_source/test_source.py |
import pytest
from open_alchemy.models_file import types
from open_alchemy.models_file.model import source as models_source
_SQLAlchemyModelArtifacts = types.SQLAlchemyModelArtifacts
_ArgArtifacts = types.ArgArtifacts
_ColumnArtifacts = types.ColumnArtifacts
_ColumnArgArtifacts = types.ColumnArgArtifacts
_TypedDictA... | 0.858955 | 0.29044 |
from django import forms
from django.forms.widgets import RadioSelect
from crits.campaigns.campaign import Campaign
from crits.core import form_consts
from crits.core.forms import add_bucketlist_to_form, add_ticket_to_form
from crits.core.handlers import get_source_names, get_item_names
from crits.backdoors.handlers i... | crits/samples/forms.py | from django import forms
from django.forms.widgets import RadioSelect
from crits.campaigns.campaign import Campaign
from crits.core import form_consts
from crits.core.forms import add_bucketlist_to_form, add_ticket_to_form
from crits.core.handlers import get_source_names, get_item_names
from crits.backdoors.handlers i... | 0.581897 | 0.105717 |
import sys
import os
import json
import webbrowser
import tkinter as tk
from os.path import dirname, realpath
from functools import partial
pw_prefix = dirname(dirname(realpath(__file__)))
apps_dir = f"{pw_prefix}/share/pi-ware/apps/"
icon: tk.PhotoImage
class WrapLabel(tk.Label):
def __init__(self, parent, just... | store.py |
import sys
import os
import json
import webbrowser
import tkinter as tk
from os.path import dirname, realpath
from functools import partial
pw_prefix = dirname(dirname(realpath(__file__)))
apps_dir = f"{pw_prefix}/share/pi-ware/apps/"
icon: tk.PhotoImage
class WrapLabel(tk.Label):
def __init__(self, parent, just... | 0.298594 | 0.062417 |
from db import models
def test_get_habilidade_by_name(client, test_habilidade, fake_login_superuser):
response = client.get(f"/api/v1/habilidade/name/{test_habilidade.nome}")
habilidade = response.json()
t_habilidade = {"id": test_habilidade.id, "nome": test_habilidade.nome}
assert response.status_c... | {{cookiecutter.project_slug}}/backend/app/api/api_v1/routers/tests/test_habilidade.py | from db import models
def test_get_habilidade_by_name(client, test_habilidade, fake_login_superuser):
response = client.get(f"/api/v1/habilidade/name/{test_habilidade.nome}")
habilidade = response.json()
t_habilidade = {"id": test_habilidade.id, "nome": test_habilidade.nome}
assert response.status_c... | 0.543348 | 0.415907 |
from __future__ import (
annotations,
)
import logging
from datetime import (
datetime,
)
from typing import (
AsyncIterator,
Optional,
Type,
TypeVar,
)
from uuid import (
UUID,
uuid4,
)
from dependency_injector.wiring import (
Provide,
inject,
)
from minos.aggregate.events im... | packages/core/minos-microservice-aggregate/minos/aggregate/entities/models.py | from __future__ import (
annotations,
)
import logging
from datetime import (
datetime,
)
from typing import (
AsyncIterator,
Optional,
Type,
TypeVar,
)
from uuid import (
UUID,
uuid4,
)
from dependency_injector.wiring import (
Provide,
inject,
)
from minos.aggregate.events im... | 0.895437 | 0.086093 |
import re
import os
from PIL import Image, ImageDraw, ImageFont
class Manille:
def __init__(self, color1=(250,14,66), color2=(34,230,150), bonusColor1=(0,230,0), bonusColor2=(0,230,0)):
self.sc_team1 = 0
self.sc_team2 = 0
self.cl_team1 = color1
self.cl_team2 = color2
self.cl... | Manille/manille.py | import re
import os
from PIL import Image, ImageDraw, ImageFont
class Manille:
def __init__(self, color1=(250,14,66), color2=(34,230,150), bonusColor1=(0,230,0), bonusColor2=(0,230,0)):
self.sc_team1 = 0
self.sc_team2 = 0
self.cl_team1 = color1
self.cl_team2 = color2
self.cl... | 0.146606 | 0.184804 |
import io, sys, json
from json.decoder import JSONDecodeError
from wtu.table import Table
# bokeh
from bokeh.core.properties import value
from bokeh.io import show, output_file
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, save
from bokeh.transform import dodge
import collections as cl
... | histogram_property_links.py | import io, sys, json
from json.decoder import JSONDecodeError
from wtu.table import Table
# bokeh
from bokeh.core.properties import value
from bokeh.io import show, output_file
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure, save
from bokeh.transform import dodge
import collections as cl
... | 0.249173 | 0.309402 |
import json
from unittest.mock import patch
import boto3
from aws_secrets.config.providers.secretsmanager.entry import SecretManagerEntry
from aws_secrets.tags.cmd import CmdTag
from botocore.stub import Stubber
KEY_ARN = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab'
KEY_ARN1 = 'arn:aw... | tests/config/providers/secretsmanager/test_entry.py | import json
from unittest.mock import patch
import boto3
from aws_secrets.config.providers.secretsmanager.entry import SecretManagerEntry
from aws_secrets.tags.cmd import CmdTag
from botocore.stub import Stubber
KEY_ARN = 'arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab'
KEY_ARN1 = 'arn:aw... | 0.690246 | 0.195729 |
from abc import ABC, abstractmethod
from typing import Union, List, Any
class ParallelWrapperBase(ABC):
def __init__(self, *_, **__):
"""
Note:
Parallel wrapper is designed to wrap the same kind of environments,
they may have different parameters, but must have the same act... | machin/env/wrappers/base.py | from abc import ABC, abstractmethod
from typing import Union, List, Any
class ParallelWrapperBase(ABC):
def __init__(self, *_, **__):
"""
Note:
Parallel wrapper is designed to wrap the same kind of environments,
they may have different parameters, but must have the same act... | 0.938976 | 0.539832 |
import logging
import time
import os
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
def build_speechlet_response(title, output, reprompt_text, should_end_session):
return {
'outputSpeech': {
'type': 'PlainText',
'text': output
},
'card': {
'... | Goodbye/lamda_function.py | import logging
import time
import os
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
def build_speechlet_response(title, output, reprompt_text, should_end_session):
return {
'outputSpeech': {
'type': 'PlainText',
'text': output
},
'card': {
'... | 0.42477 | 0.155078 |
from pathlib import Path
from typing import Dict, List, Union, Hashable
import cfgrib
import xarray
from src.enumerations.unified_forecast_variables import ForecastVariables
from src.modules.config.constants import KEY_LOCAL_FILE_PATHS, \
KEY_LEVEL_TYPE, KEY_LIST_INDEX
NOT_RELEVANT_ATTRIBUTES = ['time', 'latitud... | src/modules/parsing/parse_grib_data.py | from pathlib import Path
from typing import Dict, List, Union, Hashable
import cfgrib
import xarray
from src.enumerations.unified_forecast_variables import ForecastVariables
from src.modules.config.constants import KEY_LOCAL_FILE_PATHS, \
KEY_LEVEL_TYPE, KEY_LIST_INDEX
NOT_RELEVANT_ATTRIBUTES = ['time', 'latitud... | 0.773644 | 0.32029 |
import logging
from dropbox.client import DropboxOAuth2Flow
from pyramid.httpexceptions import HTTPFound, HTTPClientError, HTTPForbidden
from pyramid.security import forget, remember, NO_PERMISSION_REQUIRED
from .models import User
from pyramid.view import view_config
LOG = logging.getLogger(__name__)
@view_config(... | stevetags/login.py | import logging
from dropbox.client import DropboxOAuth2Flow
from pyramid.httpexceptions import HTTPFound, HTTPClientError, HTTPForbidden
from pyramid.security import forget, remember, NO_PERMISSION_REQUIRED
from .models import User
from pyramid.view import view_config
LOG = logging.getLogger(__name__)
@view_config(... | 0.426441 | 0.064742 |
from copy import deepcopy
from inspect import getmro
from typing import Type
from pydantic import BaseModel, ValidationError
from sanic.exceptions import InvalidUsage, ServerError, SanicException
from sanic.log import error_logger
from sanic.request import Request
class ParsedArgsObj(dict):
def __getattr__(self,... | sanic_dantic/basic_definition.py | from copy import deepcopy
from inspect import getmro
from typing import Type
from pydantic import BaseModel, ValidationError
from sanic.exceptions import InvalidUsage, ServerError, SanicException
from sanic.log import error_logger
from sanic.request import Request
class ParsedArgsObj(dict):
def __getattr__(self,... | 0.750187 | 0.194349 |
import os
import datetime
import flask
from flask import Flask, jsonify, render_template, redirect
from flask_pyoidc import OIDCAuthentication
from flask_pyoidc.provider_configuration import ProviderConfiguration, ClientMetadata
from flask_pyoidc.user_session import UserSession
os.environ["CURL_CA_BUNDLE"] = ""
app ... | python/iexcloud_openid_client_example/app.py | import os
import datetime
import flask
from flask import Flask, jsonify, render_template, redirect
from flask_pyoidc import OIDCAuthentication
from flask_pyoidc.provider_configuration import ProviderConfiguration, ClientMetadata
from flask_pyoidc.user_session import UserSession
os.environ["CURL_CA_BUNDLE"] = ""
app ... | 0.291384 | 0.070208 |
import six
from .utils import FCN
class _Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
_Singleton._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
return _Singleton._instances[cls]
class Capability(six.with_m... | owmeta_core/capability.py | import six
from .utils import FCN
class _Singleton(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
_Singleton._instances[cls] = super(_Singleton, cls).__call__(*args, **kwargs)
return _Singleton._instances[cls]
class Capability(six.with_m... | 0.829596 | 0.35421 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
def nearest_neighbor(components, X, distance='L1'):
# Initializing the tensor flow variables
init = tf.global_variables_initializer()
# Launch the session
sess ... | drama/trash/NN.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import tensorflow as tf
def nearest_neighbor(components, X, distance='L1'):
# Initializing the tensor flow variables
init = tf.global_variables_initializer()
# Launch the session
sess ... | 0.617397 | 0.422922 |
import logging
from pathlib import Path
from textwrap import dedent
from neotasker import task_supervisor
mydir = Path(__file__).parent.as_posix()
import sys
sys.path.insert(0, mydir + '/..')
from tebot import TeBot
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('tebot').setLevel(logging.DEBUG)
logging... | demo/demo.py | import logging
from pathlib import Path
from textwrap import dedent
from neotasker import task_supervisor
mydir = Path(__file__).parent.as_posix()
import sys
sys.path.insert(0, mydir + '/..')
from tebot import TeBot
logging.basicConfig(level=logging.DEBUG)
logging.getLogger('tebot').setLevel(logging.DEBUG)
logging... | 0.233794 | 0.068257 |
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from app import app
column = dbc.Col(
[
dcc.Markdown(
"""
## Process
#### Data d... | pages/process.py | import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from app import app
column = dbc.Col(
[
dcc.Markdown(
"""
## Process
#### Data d... | 0.522689 | 0.472744 |
from pysal.model.spvcm.utils import south
from pysal.model.spvcm import api as spvcm
from pysal.model.spvcm._constants import TEST_SEED
from pysal.model.spvcm.diagnostics import (
psrf,
mcse,
hpd_interval,
effective_size,
geweke,
)
import numpy as np
import os
FULL_PATH = os.path.dirname(os.path.ab... | pysal/model/spvcm/tests/make_data.py | from pysal.model.spvcm.utils import south
from pysal.model.spvcm import api as spvcm
from pysal.model.spvcm._constants import TEST_SEED
from pysal.model.spvcm.diagnostics import (
psrf,
mcse,
hpd_interval,
effective_size,
geweke,
)
import numpy as np
import os
FULL_PATH = os.path.dirname(os.path.ab... | 0.344003 | 0.14682 |
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... | planning_poker/migrations/0001_initial.py |
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... | 0.501709 | 0.137996 |
import torch
from torch.utils.data import Dataset
import os
import numpy as np
import pandas as pd
import nibabel as nib
class BiobankRegAgeDataset(torch.utils.data.Dataset):
def __init__(self, image_path='/data/biobank/MNI_aligned_preprocessed_data',
mask_path='MNI_aligned_preprocessed_2d_blob_m... | biobank_dataloader.py | import torch
from torch.utils.data import Dataset
import os
import numpy as np
import pandas as pd
import nibabel as nib
class BiobankRegAgeDataset(torch.utils.data.Dataset):
def __init__(self, image_path='/data/biobank/MNI_aligned_preprocessed_data',
mask_path='MNI_aligned_preprocessed_2d_blob_m... | 0.81721 | 0.413063 |
import numpy as np
import termcolor
import helpers
# read in input and clean from '\n' characters
hight_map = np.array(helpers.read_input_at_once(__file__, 'char'))
hight_map = hight_map[:, :-1].astype(int)
# track the low points
low_points = hight_map.copy()
# to shift the hight map in each dierction in a loop
m... | Python/Day 9: Smoke Basin 2.py | import numpy as np
import termcolor
import helpers
# read in input and clean from '\n' characters
hight_map = np.array(helpers.read_input_at_once(__file__, 'char'))
hight_map = hight_map[:, :-1].astype(int)
# track the low points
low_points = hight_map.copy()
# to shift the hight map in each dierction in a loop
m... | 0.2587 | 0.479565 |
from copy import deepcopy
import numpy as np
from .imprt import preset_import
from .log import get_logger
logger = get_logger()
def normalize_uint(arr):
r"""Normalizes the input ``uint`` array such that its ``dtype`` maximum
becomes :math:`1`.
Args:
arr (numpy.ndarray): Input array of type ``ui... | third_party/xiuminglib/xiuminglib/img.py | from copy import deepcopy
import numpy as np
from .imprt import preset_import
from .log import get_logger
logger = get_logger()
def normalize_uint(arr):
r"""Normalizes the input ``uint`` array such that its ``dtype`` maximum
becomes :math:`1`.
Args:
arr (numpy.ndarray): Input array of type ``ui... | 0.890503 | 0.609088 |
import torch
from torch.functional import norm
import torch.nn.functional as F
import os
from ProcessData.lafan1.extract import *
from ProcessData.Skeleton import *
from ProcessData.Utils import *
from numpy import pi
from typing import Tuple
import Format
def unwrap(x):
"""From https://discuss.pytorch.org/t/np-un... | ProcessData/ProcessData.py | import torch
from torch.functional import norm
import torch.nn.functional as F
import os
from ProcessData.lafan1.extract import *
from ProcessData.Skeleton import *
from ProcessData.Utils import *
from numpy import pi
from typing import Tuple
import Format
def unwrap(x):
"""From https://discuss.pytorch.org/t/np-un... | 0.708414 | 0.538741 |
from apiwrappers import Method, Request, Url
from apiwrappers.auth import TokenAuth
class HttpBin:
def __init__(self, host, driver):
self.url = Url(host)
self.driver = driver
def get(self, params=None):
"""The request's query parameters."""
request = Request(Method.GET, self.u... | tests/test_drivers/httpbin_client.py | from apiwrappers import Method, Request, Url
from apiwrappers.auth import TokenAuth
class HttpBin:
def __init__(self, host, driver):
self.url = Url(host)
self.driver = driver
def get(self, params=None):
"""The request's query parameters."""
request = Request(Method.GET, self.u... | 0.880219 | 0.12424 |
from django.test import TestCase
from django.core.exceptions import FieldDoesNotExist
from admin_anchors.utils import (
get_selected_obj,
get_selected_field,
create_admin_anchor,
)
from tests.project.gaming.models import Player, Team
class GetSelectedObjTestCase(TestCase):
def test_direct_related_obje... | tests/tests/test_utils.py | from django.test import TestCase
from django.core.exceptions import FieldDoesNotExist
from admin_anchors.utils import (
get_selected_obj,
get_selected_field,
create_admin_anchor,
)
from tests.project.gaming.models import Player, Team
class GetSelectedObjTestCase(TestCase):
def test_direct_related_obje... | 0.529507 | 0.261254 |
from abc import ABCMeta, abstractmethod
import re
import numpy as np
def procbody(body, fpdtype):
# At single precision suffix all floating point constants by 'f'
if fpdtype == np.float32:
body = re.sub(r'(?=\d*[.eE])(?=\.?\d)\d*\.?\d*(?:[eE][+-]?\d+)?',
r'\g<0>f', body)
r... | pyfr/backends/base/generator.py |
from abc import ABCMeta, abstractmethod
import re
import numpy as np
def procbody(body, fpdtype):
# At single precision suffix all floating point constants by 'f'
if fpdtype == np.float32:
body = re.sub(r'(?=\d*[.eE])(?=\.?\d)\d*\.?\d*(?:[eE][+-]?\d+)?',
r'\g<0>f', body)
r... | 0.696165 | 0.188922 |
import asyncio
from math import ceil
import discord
from discord.ext import commands
class CommandHelpEntry:
def __init__(self, name, usage, desc):
self.name = name
self.usage = usage
self.desc = desc
class CustomHelpCommand(commands.DefaultHelpCommand):
def __init__(self):
... | utils/help_command.py | import asyncio
from math import ceil
import discord
from discord.ext import commands
class CommandHelpEntry:
def __init__(self, name, usage, desc):
self.name = name
self.usage = usage
self.desc = desc
class CustomHelpCommand(commands.DefaultHelpCommand):
def __init__(self):
... | 0.424293 | 0.110976 |
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Container',
fields=[
... | src/nepal/migrations/0001_initial.py | from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Container',
fields=[
... | 0.573798 | 0.164382 |
from re import split
from datetime import datetime
from random import randint
class Node():
tot_palavras=0
palavras_distintas=0
numero_rotacoes=0
def __init__(self, palavra, linha):
self.palavra=palavra
self.linha=[linha]
self.fator_equi=0
self.altura=1
self.meno... | Data Structures-Trees/tests/testAVL.py | from re import split
from datetime import datetime
from random import randint
class Node():
tot_palavras=0
palavras_distintas=0
numero_rotacoes=0
def __init__(self, palavra, linha):
self.palavra=palavra
self.linha=[linha]
self.fator_equi=0
self.altura=1
self.meno... | 0.076178 | 0.122287 |
import proto # type: ignore
from google.cloud.dataqna_v1alpha.types import question as gcd_question
from google.cloud.dataqna_v1alpha.types import user_feedback as gcd_user_feedback
from google.protobuf import field_mask_pb2 # type: ignore
__protobuf__ = proto.module(
package='google.cloud.dataqna.v1alpha',
... | google/cloud/dataqna/v1alpha/dataqna-v1alpha-py/google/cloud/dataqna_v1alpha/types/question_service.py | import proto # type: ignore
from google.cloud.dataqna_v1alpha.types import question as gcd_question
from google.cloud.dataqna_v1alpha.types import user_feedback as gcd_user_feedback
from google.protobuf import field_mask_pb2 # type: ignore
__protobuf__ = proto.module(
package='google.cloud.dataqna.v1alpha',
... | 0.681621 | 0.102934 |
from .models import CommentRow, Comment
from .models import CoverageType, ReportCoverage, CoverageEntry, CoverageSection, Table
def render_pr_comment(report_coverage: ReportCoverage, icon_mapping, include_package_coverage=True):
overall_cov = report_coverage.overall
packages_cov = report_coverage.packages
... | main/render.py | from .models import CommentRow, Comment
from .models import CoverageType, ReportCoverage, CoverageEntry, CoverageSection, Table
def render_pr_comment(report_coverage: ReportCoverage, icon_mapping, include_package_coverage=True):
overall_cov = report_coverage.overall
packages_cov = report_coverage.packages
... | 0.538983 | 0.131145 |
# Lint as: python3
"""Multilingual Disaster Response Messages dataset."""
import csv
import datasets
_DESCRIPTION = """\
This dataset contains 30,000 messages drawn from events including an earthquake in Haiti in 2010, an earthquake in Chile in 2010, floods in Pakistan in 2010, super-storm Sandy in the U.S.A. in ... | datasets/disaster_response_messages/disaster_response_messages.py |
# Lint as: python3
"""Multilingual Disaster Response Messages dataset."""
import csv
import datasets
_DESCRIPTION = """\
This dataset contains 30,000 messages drawn from events including an earthquake in Haiti in 2010, an earthquake in Chile in 2010, floods in Pakistan in 2010, super-storm Sandy in the U.S.A. in ... | 0.856782 | 0.651161 |
import unittest
from ..src import main
class TestMain(unittest.TestCase):
"""
Only tests valid data since main is not designed to handle
invalid input.
"""
def test__replace_digraphs__with_valid_data(self):
self.assertEqual(["s", "h", "a"], main._replace_digraphs(["し", "ゃ"]))
sel... | test/test.py |
import unittest
from ..src import main
class TestMain(unittest.TestCase):
"""
Only tests valid data since main is not designed to handle
invalid input.
"""
def test__replace_digraphs__with_valid_data(self):
self.assertEqual(["s", "h", "a"], main._replace_digraphs(["し", "ゃ"]))
sel... | 0.441432 | 0.402803 |
__all__ = [
"Mecha",
"MechaOptions",
"AstCacheBackend",
]
import logging
import os
import pickle
import sys
from contextlib import contextmanager
from dataclasses import InitVar, dataclass
from io import BufferedReader, BufferedWriter
from pathlib import Path
from typing import (
Any,
Dict,
It... | mecha/api.py | __all__ = [
"Mecha",
"MechaOptions",
"AstCacheBackend",
]
import logging
import os
import pickle
import sys
from contextlib import contextmanager
from dataclasses import InitVar, dataclass
from io import BufferedReader, BufferedWriter
from pathlib import Path
from typing import (
Any,
Dict,
It... | 0.688154 | 0.14777 |
import nlp
import pandas as pd
import pdb
class AmazonQACsvConfig(nlp.BuilderConfig):
"""BuilderConfig for amazon qa CSV."""
def __init__(self, **kwargs):
"""BuilderConfig for AmazonQA.
Args:
**kwargs: keyword arguments forwarded to super.
"""
... | data/amazon_qg/amazon_qg.py | import nlp
import pandas as pd
import pdb
class AmazonQACsvConfig(nlp.BuilderConfig):
"""BuilderConfig for amazon qa CSV."""
def __init__(self, **kwargs):
"""BuilderConfig for AmazonQA.
Args:
**kwargs: keyword arguments forwarded to super.
"""
... | 0.5144 | 0.239116 |
import os
import subprocess
from amaranth import *
from amaranth.build import *
from amaranth.vendor.lattice_ice40 import LatticeICE40Platform
from amaranth_boards.fomu_hacker import FomuHackerPlatform as _FomuHackerPlatform
from amaranth_boards.fomu_pvt import FomuPVTPlatform as _FomuPVTPlatform
from amaranth_boards... | luna/gateware/platform/fomu.py | import os
import subprocess
from amaranth import *
from amaranth.build import *
from amaranth.vendor.lattice_ice40 import LatticeICE40Platform
from amaranth_boards.fomu_hacker import FomuHackerPlatform as _FomuHackerPlatform
from amaranth_boards.fomu_pvt import FomuPVTPlatform as _FomuPVTPlatform
from amaranth_boards... | 0.470737 | 0.178168 |
import json
import logging
import requests
from lexicon.exceptions import AuthenticationError
from lexicon.providers.base import Provider as BaseProvider
LOGGER = logging.getLogger(__name__)
ENDPOINT = "https://api.infomaniak.com"
NAMESERVER_DOMAINS = ["infomaniak.com"]
def provider_parser(subparser):
"""Gen... | lexicon/providers/infomaniak.py | import json
import logging
import requests
from lexicon.exceptions import AuthenticationError
from lexicon.providers.base import Provider as BaseProvider
LOGGER = logging.getLogger(__name__)
ENDPOINT = "https://api.infomaniak.com"
NAMESERVER_DOMAINS = ["infomaniak.com"]
def provider_parser(subparser):
"""Gen... | 0.528047 | 0.140838 |
from __future__ import annotations
from base64 import encodebytes
from urllib.parse import unquote_to_bytes
from dataclasses import dataclass
from ipaddress import ip_address
import regex as re
__all__ = ("Proxy",)
@dataclass
class Proxy:
"""Proxy."""
addr: str = ""
port: int = 80
usr: str = ""
... | pyatom/base/proxy.py | from __future__ import annotations
from base64 import encodebytes
from urllib.parse import unquote_to_bytes
from dataclasses import dataclass
from ipaddress import ip_address
import regex as re
__all__ = ("Proxy",)
@dataclass
class Proxy:
"""Proxy."""
addr: str = ""
port: int = 80
usr: str = ""
... | 0.810366 | 0.288481 |
import zeeguu.core
from zeeguu.core.user_statistics.reading_sessions import reading_sessions
from ._common_api_parameters import _get_student_cohort_and_period_from_POST_params
from .. import api, json_result, with_session
db = zeeguu.core.db
@api.route("/student_reading_sessions", methods=["POST"])
@with_session
de... | zeeguu/api/api/teacher_dashboard/student_readings.py | import zeeguu.core
from zeeguu.core.user_statistics.reading_sessions import reading_sessions
from ._common_api_parameters import _get_student_cohort_and_period_from_POST_params
from .. import api, json_result, with_session
db = zeeguu.core.db
@api.route("/student_reading_sessions", methods=["POST"])
@with_session
de... | 0.474875 | 0.237068 |
import pytest
import requests
import threading
import time
from pathlib import Path
from coworks.config import Config, LocalConfig
from coworks.cws.client import client
from coworks.cws.runner import ThreadedLocalServer
from coworks.utils import import_attr
from tests.src.example import TechMS
class TestClass:
... | tests/cws/test_example.py | import pytest
import requests
import threading
import time
from pathlib import Path
from coworks.config import Config, LocalConfig
from coworks.cws.client import client
from coworks.cws.runner import ThreadedLocalServer
from coworks.utils import import_attr
from tests.src.example import TechMS
class TestClass:
... | 0.364891 | 0.228845 |
import torch
import torch.nn as nn
import torch.nn.functional as F
__all__ = ['yolo_init_weight', 'WeightLoader']
def yolo_init_weight(model):
for m in model.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, a=0.1, mode='fan_in')
if m.bias is not None:
... | mmdet/models/utils/brick.py | import torch
import torch.nn as nn
import torch.nn.functional as F
__all__ = ['yolo_init_weight', 'WeightLoader']
def yolo_init_weight(model):
for m in model.modules():
if isinstance(m, nn.Conv2d):
nn.init.kaiming_normal_(m.weight, a=0.1, mode='fan_in')
if m.bias is not None:
... | 0.959459 | 0.420838 |
import json
from django.core.urlresolvers import reverse
import seaserv
from seaserv import seafile_api
from seahub.profile.models import Profile
from seahub.test_utils import BaseTestCase
from tests.common.utils import randstring
class SharedReposTest(BaseTestCase):
def share_repo_to_user(self):
seafi... | tests/api/endpoints/test_shared_repos.py | import json
from django.core.urlresolvers import reverse
import seaserv
from seaserv import seafile_api
from seahub.profile.models import Profile
from seahub.test_utils import BaseTestCase
from tests.common.utils import randstring
class SharedReposTest(BaseTestCase):
def share_repo_to_user(self):
seafi... | 0.223971 | 0.164449 |
import pprint
import re # noqa: F401
import six
class SpirentSignature(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
and... | tests/aat/api/v1/client/models/spirent_signature.py | import pprint
import re # noqa: F401
import six
class SpirentSignature(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
and... | 0.682679 | 0.245616 |
import os
import sys
import numpy as np
from datetime import datetime as dt
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from utils import DataManagement
sys.path.insert(0, 'openpose') # append path of openpose
from entity import params, JointType
def main():
... | python/analysis.py | import os
import sys
import numpy as np
from datetime import datetime as dt
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from utils import DataManagement
sys.path.insert(0, 'openpose') # append path of openpose
from entity import params, JointType
def main():
... | 0.160299 | 0.542863 |
import operator
from pathlib import Path
import cv2
import numpy as np
from core.leras import nn
class FaceEnhancer(object):
"""
x4 face enhancer
"""
def __init__(self, place_model_on_cpu=False, run_on_cpu=False):
nn.initialize(data_format="NHWC")
tf = nn.tf
class FaceEnhance... | facelib/FaceEnhancer.py | import operator
from pathlib import Path
import cv2
import numpy as np
from core.leras import nn
class FaceEnhancer(object):
"""
x4 face enhancer
"""
def __init__(self, place_model_on_cpu=False, run_on_cpu=False):
nn.initialize(data_format="NHWC")
tf = nn.tf
class FaceEnhance... | 0.863593 | 0.380442 |
import math
import numpy as np
import geopandas as gpd
import shapely
import pycountry
import pyproj
from renewablepotentialslib.conversion import transform_bounds, eu_country_code_to_iso3
from renewablepotentialslib import EPSG_3035, EPSG_3035_PROJ4, WGS84, WGS84_PROJ4
def determine_pixel_areas(crs, bounds, resolu... | lib/renewablepotentialslib/shape_utils.py | import math
import numpy as np
import geopandas as gpd
import shapely
import pycountry
import pyproj
from renewablepotentialslib.conversion import transform_bounds, eu_country_code_to_iso3
from renewablepotentialslib import EPSG_3035, EPSG_3035_PROJ4, WGS84, WGS84_PROJ4
def determine_pixel_areas(crs, bounds, resolu... | 0.832509 | 0.747777 |
""" Runtime Information
"""
__docformat__ = 'restructuredtext'
import os
import sys
import time
try:
import locale
except ImportError: # pragma: no cover
locale = None
import platform
from zope.component import ComponentLookupError
from zope.component import adapter
from zope.component import getUtility
f... | src/zope/applicationcontrol/runtimeinfo.py | """ Runtime Information
"""
__docformat__ = 'restructuredtext'
import os
import sys
import time
try:
import locale
except ImportError: # pragma: no cover
locale = None
import platform
from zope.component import ComponentLookupError
from zope.component import adapter
from zope.component import getUtility
f... | 0.408631 | 0.093512 |
import random
# Creating class and initializing attributes
class Dice:
def __init__(self):
self.number1 = 1
self.number2 = 1
self.number3 = 1
# Get random integer between 1 to 6 and setting the value for each player
def player1_roll(self):
player1_dice = random.ra... | Exercise3/exercise7.py |
import random
# Creating class and initializing attributes
class Dice:
def __init__(self):
self.number1 = 1
self.number2 = 1
self.number3 = 1
# Get random integer between 1 to 6 and setting the value for each player
def player1_roll(self):
player1_dice = random.ra... | 0.464416 | 0.316633 |
from os import path
from commands2 import ParallelCommandGroup, SequentialCommandGroup, WaitCommand
from wpimath.trajectory import TrajectoryConfig, TrajectoryUtil
from subsystems.drivesubsystem import DriveSubsystem
from subsystems.intakesubsystem import IntakeSubsystem
from subsystems.indexersubsystem import Indexe... | commands/auto/fourblnoninvasive.py | from os import path
from commands2 import ParallelCommandGroup, SequentialCommandGroup, WaitCommand
from wpimath.trajectory import TrajectoryConfig, TrajectoryUtil
from subsystems.drivesubsystem import DriveSubsystem
from subsystems.intakesubsystem import IntakeSubsystem
from subsystems.indexersubsystem import Indexe... | 0.505859 | 0.125735 |
import os
import sys
from ..core import Variable, QtGui, QtCore, QtWidgets, componentsList
from ..components import RadarDisplay, Menu, LevelButtonWindow, \
LinkSharedVariables, SelectRegion, Window, FileNavigator, \
LayoutComponent, FileDetail
from ._parse_field import _parse_field
from ._common import startM... | artview/scripts/layout.py | import os
import sys
from ..core import Variable, QtGui, QtCore, QtWidgets, componentsList
from ..components import RadarDisplay, Menu, LevelButtonWindow, \
LinkSharedVariables, SelectRegion, Window, FileNavigator, \
LayoutComponent, FileDetail
from ._parse_field import _parse_field
from ._common import startM... | 0.355999 | 0.084116 |
from mininet.topo import SingleSwitchTopo
from mininet.net import Mininet
from mininet.log import info, setLogLevel
from time import time
from select import poll, POLLIN
from subprocess import Popen, PIPE
def monitorFiles( outfiles, seconds, timeoutms ):
"Monitor set of files and return [(host, line)...]"
de... | platforms/bmv2-mininet/docker/third-party/mininet/examples/multipoll.py | from mininet.topo import SingleSwitchTopo
from mininet.net import Mininet
from mininet.log import info, setLogLevel
from time import time
from select import poll, POLLIN
from subprocess import Popen, PIPE
def monitorFiles( outfiles, seconds, timeoutms ):
"Monitor set of files and return [(host, line)...]"
de... | 0.290578 | 0.127707 |
import unittest
from rdkit import Chem
from rdkit.Chem.rdMolDescriptors import GetMorganFingerprintAsBitVect
from rdkit.DataStructs import FingerprintSimilarity
from slgnn.data_processing.zinc_sample_smiles import SmilesSampler
class TestSamplingSmiles(unittest.TestCase):
def setUp(self):
self.sampler =... | slgnn/tests/test_smiles_sampling.py | import unittest
from rdkit import Chem
from rdkit.Chem.rdMolDescriptors import GetMorganFingerprintAsBitVect
from rdkit.DataStructs import FingerprintSimilarity
from slgnn.data_processing.zinc_sample_smiles import SmilesSampler
class TestSamplingSmiles(unittest.TestCase):
def setUp(self):
self.sampler =... | 0.342132 | 0.580174 |
import unittest
from displacy.mercury_english_query import summarize_doc
import spacy
class TestPrintToken(unittest.TestCase):
english_nlp = spacy.load("en_core_web_sm")
def print_token_labels(self, spacy_doc):
for token in spacy_doc:
print(token.text,token.pos_, token.tag_, token.dep_, ... | test/TestPrintQueryPosTagDetail.py | import unittest
from displacy.mercury_english_query import summarize_doc
import spacy
class TestPrintToken(unittest.TestCase):
english_nlp = spacy.load("en_core_web_sm")
def print_token_labels(self, spacy_doc):
for token in spacy_doc:
print(token.text,token.pos_, token.tag_, token.dep_, ... | 0.452536 | 0.601886 |
import os
from ioformat import read_text_file
import mess_io.writer
PATH = os.path.dirname(os.path.realpath(__file__))
GEO = (('C', (-4.0048955763, -0.3439866053, -0.0021431734)),
('O', (-1.3627056155, -0.3412713280, 0.0239463418)),
('H', (-4.7435343957, 1.4733340928, 0.7491098889)),
('H', (-4.74... | autoio-interfaces/mess_io/tests/test_write_montecarlo.py | import os
from ioformat import read_text_file
import mess_io.writer
PATH = os.path.dirname(os.path.realpath(__file__))
GEO = (('C', (-4.0048955763, -0.3439866053, -0.0021431734)),
('O', (-1.3627056155, -0.3412713280, 0.0239463418)),
('H', (-4.7435343957, 1.4733340928, 0.7491098889)),
('H', (-4.74... | 0.3492 | 0.265928 |
from utils import rc
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
typemapper = { }
handler_tracker = [ ]
class HandlerMetaClass(type):
"""
Metaclass that keeps a registry of class -> handler
mappings.
"""
def __new__(cls, name, bases, attrs):
new_cls = typ... | external_apps/django-piston/piston/handler.py | from utils import rc
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
typemapper = { }
handler_tracker = [ ]
class HandlerMetaClass(type):
"""
Metaclass that keeps a registry of class -> handler
mappings.
"""
def __new__(cls, name, bases, attrs):
new_cls = typ... | 0.397471 | 0.079389 |
from typing import List
import numpy as np
import tensorflow as tf
import tensorflow.keras.layers as L
class SlotAttention(L.Layer): # pylint: disable=too-many-instance-attributes
"""Slot Attention module."""
def __init__( # pylint: disable=too-many-arguments
self,
num_iterations: int,
... | components/slot_attention.py | from typing import List
import numpy as np
import tensorflow as tf
import tensorflow.keras.layers as L
class SlotAttention(L.Layer): # pylint: disable=too-many-instance-attributes
"""Slot Attention module."""
def __init__( # pylint: disable=too-many-arguments
self,
num_iterations: int,
... | 0.968709 | 0.597549 |
# Created by: <NAME>(KCL)
import pandas as pd
import torch
import math
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.preprocessing import MinMaxScaler
class Data():
def __init__(self):
self.data = pd.read_csv("csv/lineMergeDataWithHeading.csv")
self.data.drop... | AI/csv_data.py |
# Created by: <NAME>(KCL)
import pandas as pd
import torch
import math
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.preprocessing import MinMaxScaler
class Data():
def __init__(self):
self.data = pd.read_csv("csv/lineMergeDataWithHeading.csv")
self.data.drop... | 0.631708 | 0.381911 |
from __future__ import absolute_import
from __future__ import unicode_literals
import random
import pytest
from six.moves import range
import six.moves.cPickle as pickle
from blazeutils.datastructures import DumbObject, OrderedProperties, OrderedDict, \
LazyOrderedDict, LazyDict, UniqueList
# leave this here it... | blazeutils/tests/test_datastructures.py | from __future__ import absolute_import
from __future__ import unicode_literals
import random
import pytest
from six.moves import range
import six.moves.cPickle as pickle
from blazeutils.datastructures import DumbObject, OrderedProperties, OrderedDict, \
LazyOrderedDict, LazyDict, UniqueList
# leave this here it... | 0.544438 | 0.508666 |
import argparse
import os
import copy
import time
import random
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from models.parallel import DataParallelModel, DataParallelCriterion
from models.mobilenetv2 im... | train.py | import argparse
import os
import copy
import time
import random
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from models.parallel import DataParallelModel, DataParallelCriterion
from models.mobilenetv2 im... | 0.790854 | 0.533519 |
import sys
if sys.platform != 'win32':
raise ImportError("The '_winapi' module is only available on Windows")
# Declare external Win32 functions
from _pypy_winbase_cffi import ffi as _ffi
_kernel32 = _ffi.dlopen('kernel32')
GetVersion = _kernel32.GetVersion
NULL = _ffi.NULL
# Now the _subprocess module implemen... | pypy3-v6.0.0-linux64/lib_pypy/_winapi.py | import sys
if sys.platform != 'win32':
raise ImportError("The '_winapi' module is only available on Windows")
# Declare external Win32 functions
from _pypy_winbase_cffi import ffi as _ffi
_kernel32 = _ffi.dlopen('kernel32')
GetVersion = _kernel32.GetVersion
NULL = _ffi.NULL
# Now the _subprocess module implemen... | 0.391871 | 0.094594 |
from Levenshtein import distance as lev
from hdwallet import BIP44HDWallet
from hdwallet.cryptocurrencies import *
from hdwallet.derivations import BIP44Derivation
from hdwallet.utils import generate_mnemonic
from typing import Optional
import progressbar as pb
import sys, csv
prompt = '''
... | keygen.py | from Levenshtein import distance as lev
from hdwallet import BIP44HDWallet
from hdwallet.cryptocurrencies import *
from hdwallet.derivations import BIP44Derivation
from hdwallet.utils import generate_mnemonic
from typing import Optional
import progressbar as pb
import sys, csv
prompt = '''
... | 0.466603 | 0.258724 |
import os
import numpy as np
import scipy.sparse
from probnum.linalg import problinsolve
from benchmarks.benchmark_utils import SPD_MATRIX_5x5
def load_poisson_linear_system():
"""
Poisson equation with Dirichlet conditions.
- Laplace(u) = f in the interior
u = u_D on the boundary... | benchmarks/linearsolvers.py | import os
import numpy as np
import scipy.sparse
from probnum.linalg import problinsolve
from benchmarks.benchmark_utils import SPD_MATRIX_5x5
def load_poisson_linear_system():
"""
Poisson equation with Dirichlet conditions.
- Laplace(u) = f in the interior
u = u_D on the boundary... | 0.752377 | 0.396682 |
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 AttributeSummary(object):
"""
Summary of an entity attribute.
"""
#: A constant which can be used wi... | src/oci/data_catalog/models/attribute_summary.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 AttributeSummary(object):
"""
Summary of an entity attribute.
"""
#: A constant which can be used wi... | 0.882687 | 0.268453 |
import math
import easyagents.core as core
class Fast(core.AgentCallback):
"""Train for small number of episodes / steps in order to do a dry run of the algorithms or callbacks."""
def __init__(self, num_iterations=None):
self._num_iterations = num_iterations
self._num_episodes_per_iteration ... | easyagents/callbacks/duration.py | import math
import easyagents.core as core
class Fast(core.AgentCallback):
"""Train for small number of episodes / steps in order to do a dry run of the algorithms or callbacks."""
def __init__(self, num_iterations=None):
self._num_iterations = num_iterations
self._num_episodes_per_iteration ... | 0.724968 | 0.373247 |
from unittest import mock
import pytest
from google.cloud import bigquery as bq
class TestStandardSqlDataType:
@staticmethod
def _get_target_class():
from google.cloud.bigquery.standard_sql import StandardSqlDataType
return StandardSqlDataType
def _make_one(self, *args, **kw):
... | tests/unit/test_standard_sql_types.py |
from unittest import mock
import pytest
from google.cloud import bigquery as bq
class TestStandardSqlDataType:
@staticmethod
def _get_target_class():
from google.cloud.bigquery.standard_sql import StandardSqlDataType
return StandardSqlDataType
def _make_one(self, *args, **kw):
... | 0.586168 | 0.490419 |
from flask_babel import gettext
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SelectField
from wtforms.validators import InputRequired, Email, EqualTo, URL, \
ValidationError
class Length(object):
def __init__(self, min=-1, max=-1, message=None):
self.min = min
... | forms.py | from flask_babel import gettext
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SelectField
from wtforms.validators import InputRequired, Email, EqualTo, URL, \
ValidationError
class Length(object):
def __init__(self, min=-1, max=-1, message=None):
self.min = min
... | 0.608943 | 0.096919 |
import time
import sys
import os
texp = sys.argv[1]
first = sys.argv[2]
# start timing
t = time.time()
clock0 = time.time()
import numpy as np
from lib.RTACtoolsAnalysis import RTACtoolsAnalysis, make_obslist
from lib.RTAUtils import phflux_powerlaw
from lib.RTAManageXml import ManageXml
timport = time.time() - t
pri... | RTAscience/timing/time_ctools3d_binned_blindfit.py |
import time
import sys
import os
texp = sys.argv[1]
first = sys.argv[2]
# start timing
t = time.time()
clock0 = time.time()
import numpy as np
from lib.RTACtoolsAnalysis import RTACtoolsAnalysis, make_obslist
from lib.RTAUtils import phflux_powerlaw
from lib.RTAManageXml import ManageXml
timport = time.time() - t
pri... | 0.256925 | 0.170025 |
import logging
import numpy as np
import os
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.externals import joblib
logger = logging.getLogger(__name__)
class DataLoader():
"""A class for loading and transforming data for the lstm model"""
def __init__(self, filename, split, ... | core/data_processor.py | import logging
import numpy as np
import os
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from sklearn.externals import joblib
logger = logging.getLogger(__name__)
class DataLoader():
"""A class for loading and transforming data for the lstm model"""
def __init__(self, filename, split, ... | 0.493897 | 0.316699 |
from typing import Callable, Any, Generic, NoReturn, TypeVar, Awaitable
from nonebot.matcher import Matcher
from nonebot.params import CommandArg, State
from nonebot.adapters import Bot, Event, Message, MessageSegment, MessageTemplate
from nonebot.typing import T_State as TBotState
import asyncio
import nonebot
class ... | util/args.py | from typing import Callable, Any, Generic, NoReturn, TypeVar, Awaitable
from nonebot.matcher import Matcher
from nonebot.params import CommandArg, State
from nonebot.adapters import Bot, Event, Message, MessageSegment, MessageTemplate
from nonebot.typing import T_State as TBotState
import asyncio
import nonebot
class ... | 0.623033 | 0.191762 |
from django.contrib.auth import authenticate, get_user_model
from django import forms
from streampage.models import Primitives, communityUsers, Communities, Datatypes, DatatypeFields, Posts, CommunityTags, \
DatatTypeTags, PostTags, UserTags
from django_countries import countries
import json
class UsersLogi... | mystream/streampage/forms.py | from django.contrib.auth import authenticate, get_user_model
from django import forms
from streampage.models import Primitives, communityUsers, Communities, Datatypes, DatatypeFields, Posts, CommunityTags, \
DatatTypeTags, PostTags, UserTags
from django_countries import countries
import json
class UsersLogi... | 0.479016 | 0.083778 |
from infi.gevent_utils.os import path
from infi.app_repo.errors import FilenameParsingFailed
from logging import getLogger
from re import match
logger = getLogger(__name__)
NAME = r"""(?P<package_name>[a-zA-Z]*[a-zA-Z\-_\.]+[0-9_]?[a-zA-Z\-_]+[a-zA-Z][0-9]{0,2})"""
VERSION = r"""v?(?P<package_version>(?:[\d+\.]+)(?:-... | src/infi/app_repo/filename_parser.py | from infi.gevent_utils.os import path
from infi.app_repo.errors import FilenameParsingFailed
from logging import getLogger
from re import match
logger = getLogger(__name__)
NAME = r"""(?P<package_name>[a-zA-Z]*[a-zA-Z\-_\.]+[0-9_]?[a-zA-Z\-_]+[a-zA-Z][0-9]{0,2})"""
VERSION = r"""v?(?P<package_version>(?:[\d+\.]+)(?:-... | 0.405096 | 0.195229 |
import os
import re
import tempfile
import numpy
import borg
logger = borg.get_logger(__name__, default_level = "INFO")
def parse_competition(stdout):
"""Parse output from a standard competition solver."""
match = re.search(r"^s +([a-zA-Z ]+) *\r?$", stdout, re.M)
if match:
(answer_type,) = mat... | borg/domains/pb/solvers.py |
import os
import re
import tempfile
import numpy
import borg
logger = borg.get_logger(__name__, default_level = "INFO")
def parse_competition(stdout):
"""Parse output from a standard competition solver."""
match = re.search(r"^s +([a-zA-Z ]+) *\r?$", stdout, re.M)
if match:
(answer_type,) = mat... | 0.604165 | 0.199308 |
import importlib.util
import os
from typing import Text, Dict
import click
from gino_admin import create_admin_app
from gino_admin.utils import parse_db_uri
@click.group()
def cli():
pass
# todo: change config commands to some stored in one place list
# todo: add check for config values, errors
@click.command... | gino_admin/cli.py | import importlib.util
import os
from typing import Text, Dict
import click
from gino_admin import create_admin_app
from gino_admin.utils import parse_db_uri
@click.group()
def cli():
pass
# todo: change config commands to some stored in one place list
# todo: add check for config values, errors
@click.command... | 0.19235 | 0.094761 |
import pickle
import math
import torch
from torch import nn
import torch.distributions as dist
import numpy as np
from scipy.stats import logistic
from scipy.optimize import linear_sum_assignment
from functools import reduce
EPS = 1e-16
# Save an object.
# https://stackoverflow.com/questions/19201290/how-to-save-a-d... | code/python/utils.py |
import pickle
import math
import torch
from torch import nn
import torch.distributions as dist
import numpy as np
from scipy.stats import logistic
from scipy.optimize import linear_sum_assignment
from functools import reduce
EPS = 1e-16
# Save an object.
# https://stackoverflow.com/questions/19201290/how-to-save-a-d... | 0.907574 | 0.498169 |