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 copy
import http.client
import json
import os
import subprocess
import time
from math import pi
import rospy
from franka_msgs.msg import ErrorRecoveryActionGoal
from sensor_msgs.msg import JointState
from franka_python.common import *
from franka_python.utils import publisher, subscriber
class ArmInterface:
... | franka_python/interfaces/arm_interface.py | import copy
import http.client
import json
import os
import subprocess
import time
from math import pi
import rospy
from franka_msgs.msg import ErrorRecoveryActionGoal
from sensor_msgs.msg import JointState
from franka_python.common import *
from franka_python.utils import publisher, subscriber
class ArmInterface:
... | 0.821546 | 0.201774 |
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
import spams
class SpamsTransformer(BaseEstimator, TransformerMixin):
"""
This class performs dictionary learning on data using the SPArse Modeling Software (SPAMS).
"""
def __init__(self, total_num_bases, l1_dictionar... | spams_transformer.py |
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
import spams
class SpamsTransformer(BaseEstimator, TransformerMixin):
"""
This class performs dictionary learning on data using the SPArse Modeling Software (SPAMS).
"""
def __init__(self, total_num_bases, l1_dictionar... | 0.921251 | 0.590218 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import re
from hypebot.core import name_complete_lib
from typing import Text
class ItemsLib(object):
"""Class for fetching item data from Riot API."""
_ITEM_ALIAS... | hypebot/plugins/league/items_lib.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import re
from hypebot.core import name_complete_lib
from typing import Text
class ItemsLib(object):
"""Class for fetching item data from Riot API."""
_ITEM_ALIAS... | 0.772316 | 0.142291 |
# If you need the npy arrays in the /data/ folder contact me or <NAME>
import numpy as np
import json
# Narrow-peaks
# H3K4me3 = np.load('../data/Binary/chr1/H3K4me3.npy')
# H3K9me3 = np.load('../data/Binary/chr1/H3K9me3.npy')
# H3K27ac = np.load('../data/Binary/chr1/H3K27ac.npy')
# Broad-peaks
# H3K27me3 = np.load(... | python/json_creator.py |
# If you need the npy arrays in the /data/ folder contact me or <NAME>
import numpy as np
import json
# Narrow-peaks
# H3K4me3 = np.load('../data/Binary/chr1/H3K4me3.npy')
# H3K9me3 = np.load('../data/Binary/chr1/H3K9me3.npy')
# H3K27ac = np.load('../data/Binary/chr1/H3K27ac.npy')
# Broad-peaks
# H3K27me3 = np.load(... | 0.282493 | 0.219777 |
import asyncio
import datetime
from collections import defaultdict
from typing import Union
import aiohttp
from more_itertools import chunked
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.sql.expression import and_
from sqlalchemy.sql.expression import exists
from sqlalchemy.sql.expression import or_
... | yui/apps/info/toranoana/tasks.py | import asyncio
import datetime
from collections import defaultdict
from typing import Union
import aiohttp
from more_itertools import chunked
from sqlalchemy.orm.exc import NoResultFound
from sqlalchemy.sql.expression import and_
from sqlalchemy.sql.expression import exists
from sqlalchemy.sql.expression import or_
... | 0.371479 | 0.114517 |
import copy
import json
import pytest
from aquarius.constants import BaseURLs
from aquarius.run import app
app = app
@pytest.fixture
def base_ddo_url():
return BaseURLs.BASE_AQUARIUS_URL + '/assets/ddo'
@pytest.fixture
def client_with_no_data():
client = app.test_client()
client.delete(BaseURLs.BASE_... | tests/conftest.py | import copy
import json
import pytest
from aquarius.constants import BaseURLs
from aquarius.run import app
app = app
@pytest.fixture
def base_ddo_url():
return BaseURLs.BASE_AQUARIUS_URL + '/assets/ddo'
@pytest.fixture
def client_with_no_data():
client = app.test_client()
client.delete(BaseURLs.BASE_... | 0.343232 | 0.21917 |
from typing import Optional
from mstrio.connection import Connection
from mstrio.users_and_groups.user import User
from mstrio.utils.helper import Dictable
from mstrio.utils.entity import auto_match_args_entity
class CertifiedInfo(Dictable):
"""Certification status, time of certification and information
abou... | mstrio/utils/certified_info.py | from typing import Optional
from mstrio.connection import Connection
from mstrio.users_and_groups.user import User
from mstrio.utils.helper import Dictable
from mstrio.utils.entity import auto_match_args_entity
class CertifiedInfo(Dictable):
"""Certification status, time of certification and information
abou... | 0.880508 | 0.219327 |
import torch.nn as nn
class DepthWiseConv2d(nn.Conv2d):
'''Depth-wise convolution 2d is a convolution layer with groups=channel width.
NOTE: in_channels = out_channels = groups
and this is set using 'channels' argument.
Arguments:
channels: int
Channel width of the input/ou... | storch/layers/convolution.py | import torch.nn as nn
class DepthWiseConv2d(nn.Conv2d):
'''Depth-wise convolution 2d is a convolution layer with groups=channel width.
NOTE: in_channels = out_channels = groups
and this is set using 'channels' argument.
Arguments:
channels: int
Channel width of the input/ou... | 0.963489 | 0.554621 |
import json
from abc import ABC, abstractmethod
from typing import Optional, List
class ErrorDefinition(ABC):
"""
ErrorDefinition is an abstraction for error properties that are known at authoring time (dev time).
A new error is authored by simply providing an implementation for this abstraction.
... | venv/lib/python3.8/site-packages/azureml/_common/_error_definition/error_definition.py | import json
from abc import ABC, abstractmethod
from typing import Optional, List
class ErrorDefinition(ABC):
"""
ErrorDefinition is an abstraction for error properties that are known at authoring time (dev time).
A new error is authored by simply providing an implementation for this abstraction.
... | 0.871105 | 0.464173 |
import clr, sys
clr.AddReference('ZyGames.Framework.Common');
clr.AddReference('ZyGames.Framework');
clr.AddReference('ZyGames.Framework.Game');
clr.AddReference('ZyGames.Tianjiexing.Model');
clr.AddReference('ZyGames.Tianjiexing.BLL');
clr.AddReference('ZyGames.Tianjiexing.Lang');
clr.AddReference('ZyGames.Tia... | Sample/Koudai/Server/release/Script/PyScript/Action/action12101.py | import clr, sys
clr.AddReference('ZyGames.Framework.Common');
clr.AddReference('ZyGames.Framework');
clr.AddReference('ZyGames.Framework.Game');
clr.AddReference('ZyGames.Tianjiexing.Model');
clr.AddReference('ZyGames.Tianjiexing.BLL');
clr.AddReference('ZyGames.Tianjiexing.Lang');
clr.AddReference('ZyGames.Tia... | 0.219421 | 0.053305 |
from __future__ import absolute_import, division, unicode_literals
from html5lib.filters.whitespace import Filter
from html5lib.constants import spaceCharacters
spaceCharacters = "".join(spaceCharacters)
def runTest(input, expected):
output = list(Filter(input))
errorMsg = "\n".join(["\n\nInput:", str(input)... | tools/third_party/html5lib/html5lib/tests/test_whitespace_filter.py | from __future__ import absolute_import, division, unicode_literals
from html5lib.filters.whitespace import Filter
from html5lib.constants import spaceCharacters
spaceCharacters = "".join(spaceCharacters)
def runTest(input, expected):
output = list(Filter(input))
errorMsg = "\n".join(["\n\nInput:", str(input)... | 0.620162 | 0.585723 |
import ast
import json
import pathlib
import subprocess
import time
import numpy as np
import requests
from util import logger
DETECTOR_MAP = {
'detectors': ['gpt-2'],
'gpt-detector': 'detector-large.pt',
'gltr-detector': ('gpt2-xl', 'BERT'),
'gpt-detector-server': 'http://... | reliability_assessment/neural_filter/model.py | import ast
import json
import pathlib
import subprocess
import time
import numpy as np
import requests
from util import logger
DETECTOR_MAP = {
'detectors': ['gpt-2'],
'gpt-detector': 'detector-large.pt',
'gltr-detector': ('gpt2-xl', 'BERT'),
'gpt-detector-server': 'http://... | 0.412648 | 0.086903 |
# python train_pixface.py -g 0 -i ./face --out result_face --snapshot_interval 10000
from __future__ import print_function
import argparse
import os
import chainer
from chainer import training
from chainer.training import extensions
from chainer import serializers
from net import StarGenerator
from net import StarD... | ML/FaceGen/train_starface.py |
# python train_pixface.py -g 0 -i ./face --out result_face --snapshot_interval 10000
from __future__ import print_function
import argparse
import os
import chainer
from chainer import training
from chainer.training import extensions
from chainer import serializers
from net import StarGenerator
from net import StarD... | 0.68437 | 0.124532 |
from sqlalchemy import Column, Table
from sqlalchemy.orm import mapper, relationship
from sqlalchemy.sql.expression import and_
from unmapped_entities import *
def table_def_from_entity(entity_class, metadata):
"""Construct an SQLAlchemy Table from one of the subclasses of Entity in
unmapped_entities. This is... | gtfs/entity/map_entities.py | from sqlalchemy import Column, Table
from sqlalchemy.orm import mapper, relationship
from sqlalchemy.sql.expression import and_
from unmapped_entities import *
def table_def_from_entity(entity_class, metadata):
"""Construct an SQLAlchemy Table from one of the subclasses of Entity in
unmapped_entities. This is... | 0.543833 | 0.333625 |
from __future__ import absolute_import
import os
import sys
from codecs import open
from setuptools import setup
from setuptools.command.test import test as TestCommand
from distutils.extension import Extension
import Cython.Compiler.Options
from Cython.Distutils import build_ext
from Cython.Build import cythonize
h... | setup.py | from __future__ import absolute_import
import os
import sys
from codecs import open
from setuptools import setup
from setuptools.command.test import test as TestCommand
from distutils.extension import Extension
import Cython.Compiler.Options
from Cython.Distutils import build_ext
from Cython.Build import cythonize
h... | 0.358802 | 0.147402 |
from celery.schedules import crontab
from .config_validator import ConfigValidator
from .utility import Utility
from string import Template
import configparser
import os
class ConfigManager(object):
sections_required = ["task_config", "log_config", "schedule",
"env_literal", "env_expand"]... | apputils/config_manager.py | from celery.schedules import crontab
from .config_validator import ConfigValidator
from .utility import Utility
from string import Template
import configparser
import os
class ConfigManager(object):
sections_required = ["task_config", "log_config", "schedule",
"env_literal", "env_expand"]... | 0.76074 | 0.07946 |
from typing import Counter
import numpy as np
import pandas as pd
import math
import matplotlib.pyplot as plt
import GPy
import GPyOpt
from GPyOpt.methods import BayesianOptimization
import matplotlib.pyplot as plt
import time
import pickle
import random
random.seed(a=1)
# n-dimensional Rastrigin function, global opt... | EA-BO-RastriginFunction.py | from typing import Counter
import numpy as np
import pandas as pd
import math
import matplotlib.pyplot as plt
import GPy
import GPyOpt
from GPyOpt.methods import BayesianOptimization
import matplotlib.pyplot as plt
import time
import pickle
import random
random.seed(a=1)
# n-dimensional Rastrigin function, global opt... | 0.759404 | 0.507202 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from beem.constants import STEEM_100_PERCENT
from beem.utils import resolve_authorperm, construct_authorperm
from datetime import datetime, timedelta
from decimal import D... | processors/engine_promote_post_processor.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from beem.constants import STEEM_100_PERCENT
from beem.utils import resolve_authorperm, construct_authorperm
from datetime import datetime, timedelta
from decimal import D... | 0.46393 | 0.062103 |
import graphene
import resolvers
class Info(graphene.ObjectType):
id = graphene.ID(required=True)
name = graphene.String(required=True)
description = graphene.String()
class Sentence(graphene.ObjectType):
id = graphene.ID(required=True)
text = graphene.String(required=True)
class Person(graphe... | maana-nltk/schema.py | import graphene
import resolvers
class Info(graphene.ObjectType):
id = graphene.ID(required=True)
name = graphene.String(required=True)
description = graphene.String()
class Sentence(graphene.ObjectType):
id = graphene.ID(required=True)
text = graphene.String(required=True)
class Person(graphe... | 0.532668 | 0.29269 |
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import (Column, ForeignKey, Integer, String, Boolean,
create_engine)
from sqlalchemy.orm import relationship, sessionmaker
from datetime import datetime
from contextlib import contextmanager
from setup_dirs import DATASTOR... | QCbotB/datastore.py | from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import (Column, ForeignKey, Integer, String, Boolean,
create_engine)
from sqlalchemy.orm import relationship, sessionmaker
from datetime import datetime
from contextlib import contextmanager
from setup_dirs import DATASTOR... | 0.727201 | 0.12787 |
from math import ceil
from typing import Any, Dict, Tuple
# internal
from vtelem.classes.byte_buffer import crc
from vtelem.classes.type_primitive import TypePrimitive
from vtelem.frame import Frame
from vtelem.frame.fields import MESSAGE_FIELDS
HEADER_SIZE: int = 0
for _field in MESSAGE_FIELDS:
HEADER_SIZE += _f... | vtelem/frame/message.py | from math import ceil
from typing import Any, Dict, Tuple
# internal
from vtelem.classes.byte_buffer import crc
from vtelem.classes.type_primitive import TypePrimitive
from vtelem.frame import Frame
from vtelem.frame.fields import MESSAGE_FIELDS
HEADER_SIZE: int = 0
for _field in MESSAGE_FIELDS:
HEADER_SIZE += _f... | 0.910058 | 0.420302 |
import logging
from azure.ai.ml import MLClient, dsl, Input
from test.constants_for_test import Timeouts
from test.utilities_for_test import submit_and_wait
_logger = logging.getLogger(__file__)
logging.basicConfig(level=logging.INFO)
class TestCounterfactualComponent:
def test_classification_all_args(
... | test/rai/test_counterfactual_component.py |
import logging
from azure.ai.ml import MLClient, dsl, Input
from test.constants_for_test import Timeouts
from test.utilities_for_test import submit_and_wait
_logger = logging.getLogger(__file__)
logging.basicConfig(level=logging.INFO)
class TestCounterfactualComponent:
def test_classification_all_args(
... | 0.582847 | 0.326701 |
import sys
from ABTestingBase import ABTestingBase
from CaptureOutput import CaptureOutput
from Displayer_3 import Displayer
from GameBuilder import GameBuilder
from LogDisplayer import LogDisplayer, CompositeDisplayer
class GameplayTests(ABTestingBase):
def test_profile_game(self):
sut = GameBuilder().w... | GameplayOptimisation.py | import sys
from ABTestingBase import ABTestingBase
from CaptureOutput import CaptureOutput
from Displayer_3 import Displayer
from GameBuilder import GameBuilder
from LogDisplayer import LogDisplayer, CompositeDisplayer
class GameplayTests(ABTestingBase):
def test_profile_game(self):
sut = GameBuilder().w... | 0.339937 | 0.149314 |
from rest_framework import generics
from rest_framework import permissions
from django.contrib.auth import get_user_model
from cl_app.models import Listing, ListingType
from cl_api.serializers import ListingSerializer, ListingTypeSerializer, UserSerializer
from cl_api.permissions import IsOwnerOrReadOnly, IsSuperUserOr... | cl_api/views.py | from rest_framework import generics
from rest_framework import permissions
from django.contrib.auth import get_user_model
from cl_app.models import Listing, ListingType
from cl_api.serializers import ListingSerializer, ListingTypeSerializer, UserSerializer
from cl_api.permissions import IsOwnerOrReadOnly, IsSuperUserOr... | 0.580828 | 0.229649 |
import urllib
import webbrowser
import requests
import click
from prompt_toolkit import prompt
from prompt_toolkit.contrib.completers import WordCompleter
from pygments import highlight
from pygments.lexers import DiffLexer
from pygments.formatters import TerminalFormatter
from terminaltables import AsciiTable
from .... | sweep/github/pull_request.py | import urllib
import webbrowser
import requests
import click
from prompt_toolkit import prompt
from prompt_toolkit.contrib.completers import WordCompleter
from pygments import highlight
from pygments.lexers import DiffLexer
from pygments.formatters import TerminalFormatter
from terminaltables import AsciiTable
from .... | 0.346873 | 0.072538 |
from __future__ import print_function
import os
import numpy as np
import sys
import random
import glob
data_dir=sys.argv[1] #data directory contains all mol2 files
output_script_dir = 'out_scripts' #generated scripts to execute, for different docking modules
output_data_dir = 'out_data' #generated pdb files... | Backend_Scripts/automatic_screening.py | from __future__ import print_function
import os
import numpy as np
import sys
import random
import glob
data_dir=sys.argv[1] #data directory contains all mol2 files
output_script_dir = 'out_scripts' #generated scripts to execute, for different docking modules
output_data_dir = 'out_data' #generated pdb files... | 0.084486 | 0.058319 |
import os
## Price
# The minimum rent you want to pay per month.
MIN_PRICE = 1500
# The maximum rent you want to pay per month.
MAX_PRICE = 2700
## Location preferences
# The Craigslist site you want to search on.
# For instance, https://sfbay.craigslist.org is SF and the Bay Area.
# You only need the beginning of... | settings.py | import os
## Price
# The minimum rent you want to pay per month.
MIN_PRICE = 1500
# The maximum rent you want to pay per month.
MAX_PRICE = 2700
## Location preferences
# The Craigslist site you want to search on.
# For instance, https://sfbay.craigslist.org is SF and the Bay Area.
# You only need the beginning of... | 0.497803 | 0.579757 |
import random
import json
import secrets
import numpy as np
from lib import static
import random as rd
class User:
def __init__(self, distributions_manager, datasets_manager):
self.lastName = str()
self.firstName = str()
self.age = int(round(distributions_manager.age_distribution.rvs(1)[0... | lib/user.py | import random
import json
import secrets
import numpy as np
from lib import static
import random as rd
class User:
def __init__(self, distributions_manager, datasets_manager):
self.lastName = str()
self.firstName = str()
self.age = int(round(distributions_manager.age_distribution.rvs(1)[0... | 0.611846 | 0.280179 |
import sublime_plugin
from ..helper import Helper
from ..utils import Utils
from ..constant import Constant
class PhpmePostGetterSetterCommand(sublime_plugin.TextCommand):
"""Do generate getter setter"""
def run(self, edit, mode, properties, cname):
self.uses = []
self.methods = []
se... | phpme/command/phpme_post_getter_setter_command.py | import sublime_plugin
from ..helper import Helper
from ..utils import Utils
from ..constant import Constant
class PhpmePostGetterSetterCommand(sublime_plugin.TextCommand):
"""Do generate getter setter"""
def run(self, edit, mode, properties, cname):
self.uses = []
self.methods = []
se... | 0.369201 | 0.115237 |
from flask import json, Response, request
from flask import Flask
from YtbRecordDBCRUD import api_test_v0
app = Flask(__name__)
# TODO: Modify the db api to include detailed error msg in response instead of just a single T/F status
# TODO: Need log on server side for dealing with request
# TODO: Error handling
@app... | YtbRecordDBCRUD/restapi_test_v0.py | from flask import json, Response, request
from flask import Flask
from YtbRecordDBCRUD import api_test_v0
app = Flask(__name__)
# TODO: Modify the db api to include detailed error msg in response instead of just a single T/F status
# TODO: Need log on server side for dealing with request
# TODO: Error handling
@app... | 0.16637 | 0.070816 |
import unittest
import openmesh
import os
import numpy as np
class ReadWriteSTL(unittest.TestCase):
def setUp(self):
if not os.path.exists('OutFiles'):
os.makedirs('OutFiles')
def test_read_write_read(self):
mesh1 = openmesh.read_trimesh("TestFiles/cube-minimal.stl")
open... | tests/test_read_write_stl.py | import unittest
import openmesh
import os
import numpy as np
class ReadWriteSTL(unittest.TestCase):
def setUp(self):
if not os.path.exists('OutFiles'):
os.makedirs('OutFiles')
def test_read_write_read(self):
mesh1 = openmesh.read_trimesh("TestFiles/cube-minimal.stl")
open... | 0.483405 | 0.395309 |
# -*- coding: utf-8 -*-
import sys
import os
import shlex
import subprocess
import time
sys.path.append(os.getenv('testpath'))
import libs.conf as conf
from libs.utils import exe_shell
from libs.logger import infoLogger
class TbCluster(object):
def __init__(self, zk_endpoint, endpoints):
self.endpoints =... | test-common/integrationtest/libs/clients/tb_cluster.py |
# -*- coding: utf-8 -*-
import sys
import os
import shlex
import subprocess
import time
sys.path.append(os.getenv('testpath'))
import libs.conf as conf
from libs.utils import exe_shell
from libs.logger import infoLogger
class TbCluster(object):
def __init__(self, zk_endpoint, endpoints):
self.endpoints =... | 0.093782 | 0.04548 |
import math
import torch
from torch import nn
from collections.abc import Iterable
from pixelflow.distributions import Distribution, StandardUniform
from pixelflow.transforms.subset import AutoregressiveSubsetTransform2d
from pixelflow.utils import sum_except_batch
class AutoregressiveSubsetFlow2d(Distribution):
... | pixelflow/flows/autoregressive_subset_flow.py | import math
import torch
from torch import nn
from collections.abc import Iterable
from pixelflow.distributions import Distribution, StandardUniform
from pixelflow.transforms.subset import AutoregressiveSubsetTransform2d
from pixelflow.utils import sum_except_batch
class AutoregressiveSubsetFlow2d(Distribution):
... | 0.904051 | 0.62223 |
import logging
import os
import time
from subprocess import check_call, check_output
logger = logging.getLogger("magma_access_gateway_installer")
class AGWInstaller:
MAGMA_VERSION = "focal-1.7.0"
MAGMA_ARTIFACTORY = "artifactory.magmacore.org/artifactory"
MAGMA_AGW_RUNTIME_DEPENDENCIES = [
"gra... | magma_access_gateway_installer/agw_installer.py |
import logging
import os
import time
from subprocess import check_call, check_output
logger = logging.getLogger("magma_access_gateway_installer")
class AGWInstaller:
MAGMA_VERSION = "focal-1.7.0"
MAGMA_ARTIFACTORY = "artifactory.magmacore.org/artifactory"
MAGMA_AGW_RUNTIME_DEPENDENCIES = [
"gra... | 0.63443 | 0.071916 |
from copy import copy
try:
# noinspection PyCompatibility
from urllib.parse import parse_qs
except ImportError:
# noinspection PyUnresolvedReferences,PyCompatibility
from urlparse import parse_qs
from requests import post, get, ConnectionError, Timeout
from requests.packages.urllib3.exceptions import... | limelight/request.py |
from copy import copy
try:
# noinspection PyCompatibility
from urllib.parse import parse_qs
except ImportError:
# noinspection PyUnresolvedReferences,PyCompatibility
from urlparse import parse_qs
from requests import post, get, ConnectionError, Timeout
from requests.packages.urllib3.exceptions import... | 0.658857 | 0.147832 |
import os
import glob
from .reader import reader as sql_reader
from mygrations.formats.mysql.definitions.database import database as database_definition
class database(database_definition):
def __init__(self, strings):
""" Constructor. Accepts a string or list of strings with different possible contents
... | mygrations/formats/mysql/file_reader/database.py | import os
import glob
from .reader import reader as sql_reader
from mygrations.formats.mysql.definitions.database import database as database_definition
class database(database_definition):
def __init__(self, strings):
""" Constructor. Accepts a string or list of strings with different possible contents
... | 0.581065 | 0.324904 |
import os
from re import IGNORECASE
from typing import List, Tuple, Optional, Type
from vbml import Pattern, Patcher
from vkbottle.user import Message
from .abc import Command
from .inspection import Inspector
from bot.utils.enum import Mode
inspector = Inspector()
inspector.pack()
class Manager:
commands: Li... | bot/commands/manager.py | import os
from re import IGNORECASE
from typing import List, Tuple, Optional, Type
from vbml import Pattern, Patcher
from vkbottle.user import Message
from .abc import Command
from .inspection import Inspector
from bot.utils.enum import Mode
inspector = Inspector()
inspector.pack()
class Manager:
commands: Li... | 0.740174 | 0.094929 |
from distutils.spawn import find_executable
from subprocess import call
import argparse
import logging
import os.path
import sys
FLAGS = set([
"--acls",
"--archive",
"--compress",
"--fuzzy",
"--hard-links",
"--human-readable",
"--itemize-changes",
"--verbose",
"--xattrs",
"--rs... | bin/sync.py | from distutils.spawn import find_executable
from subprocess import call
import argparse
import logging
import os.path
import sys
FLAGS = set([
"--acls",
"--archive",
"--compress",
"--fuzzy",
"--hard-links",
"--human-readable",
"--itemize-changes",
"--verbose",
"--xattrs",
"--rs... | 0.579876 | 0.12424 |
import json
import boto3
import os
import decimal
from datetime import datetime
from libcloud.dns.types import Provider, RecordType
from libcloud.dns.providers import get_driver
# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if ... | lambda_get_cf_records.py | import json
import boto3
import os
import decimal
from datetime import datetime
from libcloud.dns.types import Provider, RecordType
from libcloud.dns.providers import get_driver
# Helper class to convert a DynamoDB item to JSON.
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if ... | 0.250363 | 0.119923 |
import os
import h5py
from ._core import EXAMPLE_DATA_DIR
from ._core import hfile
from .. import h5tree
DLS_EXAMPLE_FILE = "DLS_i03_i04_NXmx_Therm_6_2.nxs"
TESTFILE = os.path.join(EXAMPLE_DATA_DIR, DLS_EXAMPLE_FILE)
def test_DLS_master_file():
"""
Test that missing external links are handled gracefully.
... | punx/tests/test_issue130.py | import os
import h5py
from ._core import EXAMPLE_DATA_DIR
from ._core import hfile
from .. import h5tree
DLS_EXAMPLE_FILE = "DLS_i03_i04_NXmx_Therm_6_2.nxs"
TESTFILE = os.path.join(EXAMPLE_DATA_DIR, DLS_EXAMPLE_FILE)
def test_DLS_master_file():
"""
Test that missing external links are handled gracefully.
... | 0.532668 | 0.522629 |
from src.models.card import Cards
from src.models.card import Type
from src.models.hero import Hero
from src.util.singleton import Singleton
@Singleton
class Data(object):
def __init__(self):
self.heroList = []
self.cardHeap = []
self.heroList.append(Hero("曹操", 4, "曹操的技能"))
self.... | src/data/data.py | from src.models.card import Cards
from src.models.card import Type
from src.models.hero import Hero
from src.util.singleton import Singleton
@Singleton
class Data(object):
def __init__(self):
self.heroList = []
self.cardHeap = []
self.heroList.append(Hero("曹操", 4, "曹操的技能"))
self.... | 0.360714 | 0.191971 |
from datetime import datetime, timedelta
import pandas as pd
import measures as m
import cases as c
import hospitalizations as h
import temperature as t
def get_prediction_train_data() -> pd.DataFrame:
# VACCINATIONS ARE EXCLUDED AS PREDICTOR VARIABLE
# bc NSW has only one week (last) of vaccination data
... | preprocessing_predictions.py | from datetime import datetime, timedelta
import pandas as pd
import measures as m
import cases as c
import hospitalizations as h
import temperature as t
def get_prediction_train_data() -> pd.DataFrame:
# VACCINATIONS ARE EXCLUDED AS PREDICTOR VARIABLE
# bc NSW has only one week (last) of vaccination data
... | 0.493897 | 0.440108 |
import os
import sys
import argparse
from pycocotools.coco import COCO
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--json", help = "Path to instances_train2017.json or instances_val2017.json")
parser.add_argument("--image_folder", help = "Path to original image folder... | src/datasets/coco.py | import os
import sys
import argparse
from pycocotools.coco import COCO
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--json", help = "Path to instances_train2017.json or instances_val2017.json")
parser.add_argument("--image_folder", help = "Path to original image folder... | 0.048383 | 0.078466 |
from __future__ import annotations
from enum import Enum
import json
import logging
from pathlib import Path
from typing import Optional
import click
from click_loglevel import LogLevel
from dotenv import find_dotenv, load_dotenv
from outgoing import Sender, from_config_file
from platformdirs import user_config_path
fr... | src/reponews/__main__.py | from __future__ import annotations
from enum import Enum
import json
import logging
from pathlib import Path
from typing import Optional
import click
from click_loglevel import LogLevel
from dotenv import find_dotenv, load_dotenv
from outgoing import Sender, from_config_file
from platformdirs import user_config_path
fr... | 0.606732 | 0.077134 |
from typing import OrderedDict
import rclpy
from rclpy.node import Node
import json
from pathlib import Path
import os
from ellie_msgs.msg import DetectedInfo
from ellie_msgs.srv import String
import time
import random
REALESE_TIME = 600
class Ellie(Node):
def __init__(self):
super().__init__("action_c... | src/ellie/ellie/ellie.py |
from typing import OrderedDict
import rclpy
from rclpy.node import Node
import json
from pathlib import Path
import os
from ellie_msgs.msg import DetectedInfo
from ellie_msgs.srv import String
import time
import random
REALESE_TIME = 600
class Ellie(Node):
def __init__(self):
super().__init__("action_c... | 0.359814 | 0.09236 |
import numpy as np
import pandas as pd
import os
import glob
import arrow
import csv
def get_stockpools(date, stocknum=(10, 20)):
first = str(int(date[:4]) - 2) + date[4:]
date0 = date[:4] + '-' + date[4:]
date0 = arrow.get(date0)
second = date0.shift(months=-1)
second = second.format('YYYYMM')
... | backtest.py | import numpy as np
import pandas as pd
import os
import glob
import arrow
import csv
def get_stockpools(date, stocknum=(10, 20)):
first = str(int(date[:4]) - 2) + date[4:]
date0 = date[:4] + '-' + date[4:]
date0 = arrow.get(date0)
second = date0.shift(months=-1)
second = second.format('YYYYMM')
... | 0.261802 | 0.186225 |
from tkinter import Text
from tkinter import END
from re import sub, compile, search
from config_interface._rc import _run as CRC
from config_interface.wdg.tools import TextHighlighting
from config_interface.tab_plugins.SSLPEM import openssl, msg_strings
class OpenSSLCnfText(Text):
def __init__(self, master, ... | config_interface/tab_plugins/SSLPEM/openssl_cnf.py |
from tkinter import Text
from tkinter import END
from re import sub, compile, search
from config_interface._rc import _run as CRC
from config_interface.wdg.tools import TextHighlighting
from config_interface.tab_plugins.SSLPEM import openssl, msg_strings
class OpenSSLCnfText(Text):
def __init__(self, master, ... | 0.38341 | 0.094594 |
from __future__ import print_function, division
from Card import Hand, Deck
from heapq import nlargest
class PokerHand(Hand):
"""Represents a poker hand."""
def suit_and_rank_hist(self):
"""Builds histograms of the suits and ranks that appear in the hand.
Stores the result in attributes suits... | Chapter18/Ex18-3.6.py | from __future__ import print_function, division
from Card import Hand, Deck
from heapq import nlargest
class PokerHand(Hand):
"""Represents a poker hand."""
def suit_and_rank_hist(self):
"""Builds histograms of the suits and ranks that appear in the hand.
Stores the result in attributes suits... | 0.724773 | 0.495545 |
from discord.ext import commands
import inspect
import re
from typing import Optional
from clarifai_grpc.grpc.api import service_pb2, resources_pb2
from clarifai_grpc.grpc.api.status import status_code_pb2
import imgurpython
from utilities import checks
CLARIFAI_COLOR_MODEL_ID = "eeed0b6733a644cea07cf4c60f87ebb7"
C... | Discord/cogs/images.py | from discord.ext import commands
import inspect
import re
from typing import Optional
from clarifai_grpc.grpc.api import service_pb2, resources_pb2
from clarifai_grpc.grpc.api.status import status_code_pb2
import imgurpython
from utilities import checks
CLARIFAI_COLOR_MODEL_ID = "eeed0b6733a644cea07cf4c60f87ebb7"
C... | 0.479016 | 0.146301 |
import ConfigParser
import ast
import grp
import json
import os
import numpy as np
import xlrd
def parseExcel(filename, clmnnames=-1, datastart=0, sheetname='Sheet1', *argv):
"""
Parse excel file into ....
filename = excel file name
clmnnames = row number where column names are stored (-... | ibcommon/parse.py | import ConfigParser
import ast
import grp
import json
import os
import numpy as np
import xlrd
def parseExcel(filename, clmnnames=-1, datastart=0, sheetname='Sheet1', *argv):
"""
Parse excel file into ....
filename = excel file name
clmnnames = row number where column names are stored (-... | 0.24015 | 0.376738 |
import json
import numpy as np
import os
import tensorflow as tf
def read_tensor_from_byte_array(byteArray,
input_height=224,
input_width=224,
input_mean=127.5,
input_std=127.5):
input_name... | examples/imagenet-transfer-learning/score.py | import json
import numpy as np
import os
import tensorflow as tf
def read_tensor_from_byte_array(byteArray,
input_height=224,
input_width=224,
input_mean=127.5,
input_std=127.5):
input_name... | 0.387806 | 0.163546 |
import argparse
from collections import namedtuple
from functools import reduce
import logging
import logging.config
import os
import os.path
from typing import Iterable
from psutil import virtual_memory
from pyspark.conf import SparkConf
from pyspark.mllib.evaluation import BinaryClassificationMetrics
from pyspark.sq... | metrics.py | import argparse
from collections import namedtuple
from functools import reduce
import logging
import logging.config
import os
import os.path
from typing import Iterable
from psutil import virtual_memory
from pyspark.conf import SparkConf
from pyspark.mllib.evaluation import BinaryClassificationMetrics
from pyspark.sq... | 0.779448 | 0.338378 |
import unittest
from io import StringIO
from msdparser import MSDParserError, parse_msd
class TestMSDParser(unittest.TestCase):
def test_constructor(self):
data = "#A:B;"
from_file = parse_msd(file=StringIO(data))
from_string = parse_msd(string=data)
self.assertEqual(... | msdparser/tests/test_module.py | import unittest
from io import StringIO
from msdparser import MSDParserError, parse_msd
class TestMSDParser(unittest.TestCase):
def test_constructor(self):
data = "#A:B;"
from_file = parse_msd(file=StringIO(data))
from_string = parse_msd(string=data)
self.assertEqual(... | 0.474631 | 0.683829 |
import pytest
from nbformat import notebooknode
from nb2hugo.preprocessors import FrontMatterPreprocessor
@pytest.fixture
def preprocessor():
"""Return an instance of FrontMatterPreprocessor."""
return FrontMatterPreprocessor()
def test_toml_frontmatter(preprocessor):
result = preprocessor._toml_frontma... | tests/preprocessors/test_frontmatter.py | import pytest
from nbformat import notebooknode
from nb2hugo.preprocessors import FrontMatterPreprocessor
@pytest.fixture
def preprocessor():
"""Return an instance of FrontMatterPreprocessor."""
return FrontMatterPreprocessor()
def test_toml_frontmatter(preprocessor):
result = preprocessor._toml_frontma... | 0.689306 | 0.345216 |
import pyparsing as pp
from classad._base_expression import CompoundExpression
from classad._expression import (
ClassAd,
AttributeExpression,
FunctionExpression,
ArithmeticExpression,
SubscriptableExpression,
TernaryExpression,
NamedExpression,
UnaryExpression,
)
from classad._primitiv... | classad/_grammar.py | import pyparsing as pp
from classad._base_expression import CompoundExpression
from classad._expression import (
ClassAd,
AttributeExpression,
FunctionExpression,
ArithmeticExpression,
SubscriptableExpression,
TernaryExpression,
NamedExpression,
UnaryExpression,
)
from classad._primitiv... | 0.420481 | 0.154121 |
from odd_models.models import DataEntity, DataSet, DataEntityType
from oddrn_generator import SnowflakeGenerator
from . import (
MetadataNamedtuple,
_data_set_metadata_schema_url,
_data_set_metadata_excluded_keys,
ColumnMetadataNamedtuple,
)
from .columns import map_column
from .metadata import append_... | odd_collector/adapters/snowflake/mappers/tables.py | from odd_models.models import DataEntity, DataSet, DataEntityType
from oddrn_generator import SnowflakeGenerator
from . import (
MetadataNamedtuple,
_data_set_metadata_schema_url,
_data_set_metadata_excluded_keys,
ColumnMetadataNamedtuple,
)
from .columns import map_column
from .metadata import append_... | 0.523177 | 0.298837 |
import asyncio
import logging
from time import time
from aiohttp import ClientSession, ClientTimeout, ClientResponse
class Requester:
"""
Wrapper around ClientSession to retry requests in case of timeouts and
log them
"""
def __init__(self, session: ClientSession,
timeout: int =... | bot/api/requester.py | import asyncio
import logging
from time import time
from aiohttp import ClientSession, ClientTimeout, ClientResponse
class Requester:
"""
Wrapper around ClientSession to retry requests in case of timeouts and
log them
"""
def __init__(self, session: ClientSession,
timeout: int =... | 0.450843 | 0.101189 |
import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from scipy.linalg import svd
class MVPR_forward():
def __init__(self,training_data, training_targets, validation_data,validation_targets, regularisation = 'TSVD', verbose=False, search='exponent'):
self.training_data = training... | MVPR.py | import numpy as np
from sklearn.preprocessing import PolynomialFeatures
from scipy.linalg import svd
class MVPR_forward():
def __init__(self,training_data, training_targets, validation_data,validation_targets, regularisation = 'TSVD', verbose=False, search='exponent'):
self.training_data = training... | 0.490236 | 0.424233 |
import ta
import numpy as np
import pandas as pd
def get_indicators(stock, indicators):
columns = stock.columns.to_list()
size = len(stock["close"])
for indicator in indicators:
name = indicator["name"]
for param in indicator["params"]:
if name == "SMA":
... | indicators.py | import ta
import numpy as np
import pandas as pd
def get_indicators(stock, indicators):
columns = stock.columns.to_list()
size = len(stock["close"])
for indicator in indicators:
name = indicator["name"]
for param in indicator["params"]:
if name == "SMA":
... | 0.06565 | 0.276623 |
import argparse
import subprocess
import os
def parse_args():
parser = argparse.ArgumentParser(
description='frappe_docker common CI elements', add_help=True)
parser.add_argument('service', action='store', type=str,
help='Name of the service to build: "erpnext" or "frappe"')
... | pipeline.py |
import argparse
import subprocess
import os
def parse_args():
parser = argparse.ArgumentParser(
description='frappe_docker common CI elements', add_help=True)
parser.add_argument('service', action='store', type=str,
help='Name of the service to build: "erpnext" or "frappe"')
... | 0.369998 | 0.116236 |
import os
import subprocess
import time
from datetime import datetime
import math
import getpass
username = getpass.getuser()
file_names = []
file_content_locator = []
file_sizes = []
file_system_name = 'FIUNAMFS'
file_system_version = '0.7'
volume_tag = 'FIUNAMFS.img'
cluster_length = '512'
num_of_clusters_dir = '4'... | proyectos/3/LopezUlysses/Proyecto3.py | import os
import subprocess
import time
from datetime import datetime
import math
import getpass
username = getpass.getuser()
file_names = []
file_content_locator = []
file_sizes = []
file_system_name = 'FIUNAMFS'
file_system_version = '0.7'
volume_tag = 'FIUNAMFS.img'
cluster_length = '512'
num_of_clusters_dir = '4'... | 0.035822 | 0.064095 |
class Usuario:
def __init__(self, email, apellido, nombre, password, sistema):
self.nombre = nombre
self.apellido = apellido
self.email = email
self.password = password
self.sistema=sistema
self.level = ""
def print(self):
print('-'.center(84,'... | clases/ejercicio_4/usuario.py | class Usuario:
def __init__(self, email, apellido, nombre, password, sistema):
self.nombre = nombre
self.apellido = apellido
self.email = email
self.password = password
self.sistema=sistema
self.level = ""
def print(self):
print('-'.center(84,'... | 0.161651 | 0.155784 |
import random
from typing import Union, Optional
import torch
from torchsde._brownian_lib import BrownianTree as _BrownianTree # noqa
from torchsde._brownian import utils # noqa
from torchsde._brownian.base_brownian import Brownian # noqa
class BrownianTree(Brownian):
"""Brownian tree with fixed entropy.
... | torchsde/brownian_lib/brownian_tree.py |
import random
from typing import Union, Optional
import torch
from torchsde._brownian_lib import BrownianTree as _BrownianTree # noqa
from torchsde._brownian import utils # noqa
from torchsde._brownian.base_brownian import Brownian # noqa
class BrownianTree(Brownian):
"""Brownian tree with fixed entropy.
... | 0.908755 | 0.483405 |
import sys, os, commands, string, subprocess, shutil, optparse, tempfile
""" version 1.1 """
def stop_err( msg ):
sys.stderr.write( "%s\n" % msg )
sys.exit()
def __main__():
galaxyhome=os.environ.get('GALAXY_HOME')
'''
n = len(sys.argv)
for i in range(0,n):
print sys.argv[i]
'''
... | tools/atlas2/vcfPrinter_1.1.py | import sys, os, commands, string, subprocess, shutil, optparse, tempfile
""" version 1.1 """
def stop_err( msg ):
sys.stderr.write( "%s\n" % msg )
sys.exit()
def __main__():
galaxyhome=os.environ.get('GALAXY_HOME')
'''
n = len(sys.argv)
for i in range(0,n):
print sys.argv[i]
'''
... | 0.086314 | 0.084644 |
import json
from unittest import mock
import pytest
from botocore.exceptions import ClientError
from powerlibs.aws.sns.publisher import SNSPublisher
from powerlibs.aws.sns.exceptions import SNSPublisherError
def test_topics(sns_publisher):
assert len(sns_publisher.topics) == 5
assert 'arn:aws:region:id:TEST... | tests/test_publisher.py | import json
from unittest import mock
import pytest
from botocore.exceptions import ClientError
from powerlibs.aws.sns.publisher import SNSPublisher
from powerlibs.aws.sns.exceptions import SNSPublisherError
def test_topics(sns_publisher):
assert len(sns_publisher.topics) == 5
assert 'arn:aws:region:id:TEST... | 0.647018 | 0.405037 |
import base64, random, string, sys, os
from StringIO import StringIO
import struct
def b64decode(data):
"""Decode base64, padding being optional.
:param data: Base64 data as an ASCII byte string
:returns: The decoded byte string.
"""
missing_padding = len(data) % 4
if missing_padding != 0:
data += b'='* (4 -... | scripts/utils.py | import base64, random, string, sys, os
from StringIO import StringIO
import struct
def b64decode(data):
"""Decode base64, padding being optional.
:param data: Base64 data as an ASCII byte string
:returns: The decoded byte string.
"""
missing_padding = len(data) % 4
if missing_padding != 0:
data += b'='* (4 -... | 0.379148 | 0.339882 |
from datetime import datetime
from email.message import EmailMessage
from typing import Iterable, Mapping, Optional, Union
from mailbits import ContentType
from .classes import Attachment, HTMLBody, MailItem, TextBody
from .util import AddressOrGroup, SingleAddress
def compose(
*,
to: Iterable[AddressOrGroup]... | src/eletter/core.py | from datetime import datetime
from email.message import EmailMessage
from typing import Iterable, Mapping, Optional, Union
from mailbits import ContentType
from .classes import Attachment, HTMLBody, MailItem, TextBody
from .util import AddressOrGroup, SingleAddress
def compose(
*,
to: Iterable[AddressOrGroup]... | 0.904184 | 0.344802 |
import subprocess
import sublime
import sublime_plugin
class SetContentsCommand(sublime_plugin.TextCommand):
def run(self, edit, text):
r = sublime.Region(0, self.view.size())
self.view.replace(edit, r, text)
self.view.end_edit(edit)
class ShowPanelMessageCommand(sublime_plugin.WindowC... | Brittany.py | import subprocess
import sublime
import sublime_plugin
class SetContentsCommand(sublime_plugin.TextCommand):
def run(self, edit, text):
r = sublime.Region(0, self.view.size())
self.view.replace(edit, r, text)
self.view.end_edit(edit)
class ShowPanelMessageCommand(sublime_plugin.WindowC... | 0.356671 | 0.140985 |
import os
from itertools import product
from math import floor
from pathlib import Path
import luigi
from .core import SagvcTask
class CallSomaticStructualVariantsWithManta(SagvcTask):
tumor_cram_path = luigi.Parameter()
normal_cram_path = luigi.Parameter()
fa_path = luigi.Parameter()
bed_path = lu... | sagvc/task/manta.py |
import os
from itertools import product
from math import floor
from pathlib import Path
import luigi
from .core import SagvcTask
class CallSomaticStructualVariantsWithManta(SagvcTask):
tumor_cram_path = luigi.Parameter()
normal_cram_path = luigi.Parameter()
fa_path = luigi.Parameter()
bed_path = lu... | 0.336658 | 0.127273 |
import argparse
import csv
import torch
import os
import numpy as np
import subprocess
import pathlib
from preprocess_koko import seq2frame
from utils import load_model
from collections import namedtuple
KOKO2022_labels = [
'sil',
'pau',
'br',
'a', 'i', 'u', 'e', 'o',
'k', 's', 't', 'n', 'h', 'm'... | create_from_csv.py | import argparse
import csv
import torch
import os
import numpy as np
import subprocess
import pathlib
from preprocess_koko import seq2frame
from utils import load_model
from collections import namedtuple
KOKO2022_labels = [
'sil',
'pau',
'br',
'a', 'i', 'u', 'e', 'o',
'k', 's', 't', 'n', 'h', 'm'... | 0.450118 | 0.40157 |
from setuptools import setup, find_namespace_packages
try:
from open_words.dict_id import WordsIds
from open_words.dict_line import WordsDict
from open_words.addons import LatinAddons
from open_words.stem_list import Stems
from open_words.uniques import Uniques
from open_words.inflects import I... | setup.py | from setuptools import setup, find_namespace_packages
try:
from open_words.dict_id import WordsIds
from open_words.dict_line import WordsDict
from open_words.addons import LatinAddons
from open_words.stem_list import Stems
from open_words.uniques import Uniques
from open_words.inflects import I... | 0.404037 | 0.123921 |
from OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField
from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde
# Generated with OTLEnumerationCreator. To modify: extend, do not edit
class KlOmvormerType(KeuzelijstField):
"""De soort omvorming die gebeurt er in de omvormer."""
na... | src/OTLMOW/OTLModel/Datatypes/KlOmvormerType.py | from OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField
from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde
# Generated with OTLEnumerationCreator. To modify: extend, do not edit
class KlOmvormerType(KeuzelijstField):
"""De soort omvorming die gebeurt er in de omvormer."""
na... | 0.429429 | 0.167593 |
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.suppor... | GooglePlayScrape.py | from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.suppor... | 0.206014 | 0.049085 |
from itertools import product
from pandas import DataFrame
from probability.distributions import BetaBinomial, BetaBinomialConjugate
from tqdm import tqdm
from typing import List, Tuple
from survey import Survey
from survey.attributes import SingleCategoryAttribute
from survey.custom_types import Categorical
from surv... | survey/experiments/_abstract/mixins.py | from itertools import product
from pandas import DataFrame
from probability.distributions import BetaBinomial, BetaBinomialConjugate
from tqdm import tqdm
from typing import List, Tuple
from survey import Survey
from survey.attributes import SingleCategoryAttribute
from survey.custom_types import Categorical
from surv... | 0.886874 | 0.436922 |
import hashlib
from pathlib import Path
from typing import Dict, Union
from urllib.request import urlretrieve
import gdown
from tqdm import tqdm
class TqdmUpTo(tqdm):
"""From https://github.com/tqdm/tqdm/blob/master/examples/tqdm_wget.py"""
def update_to(self, blocks=1, bsize=1, tsize=None):
"""
... | src/datasets/utils.py | import hashlib
from pathlib import Path
from typing import Dict, Union
from urllib.request import urlretrieve
import gdown
from tqdm import tqdm
class TqdmUpTo(tqdm):
"""From https://github.com/tqdm/tqdm/blob/master/examples/tqdm_wget.py"""
def update_to(self, blocks=1, bsize=1, tsize=None):
"""
... | 0.846641 | 0.257707 |
import numpy as np
import matplotlib.pyplot as plt
# calculates the y value of a function given its lagrange expansion
def lagrange_i(x_i, x_list, y_list):
y_i = 0
for j in range(len(x_list)):
l = 1
for m in range(len(x_list)):
if m != j:
l *= (x_i - x_list[m])/(x_lis... | A2/Q1ab.py | import numpy as np
import matplotlib.pyplot as plt
# calculates the y value of a function given its lagrange expansion
def lagrange_i(x_i, x_list, y_list):
y_i = 0
for j in range(len(x_list)):
l = 1
for m in range(len(x_list)):
if m != j:
l *= (x_i - x_list[m])/(x_lis... | 0.509032 | 0.690654 |
import itertools
import random
from typing import List, NamedTuple, Union, Callable, Tuple
import tqdm
from dsfs.linalg.vector import Vector, vector_mean, squared_distance, distance
def num_differences(v1: Vector, v2: Vector) -> int:
assert len(v1) == len(v2)
return len([x1 for x1, x2 in zip(v1, v2) if x1 !... | src/dsfs/clustering.py | import itertools
import random
from typing import List, NamedTuple, Union, Callable, Tuple
import tqdm
from dsfs.linalg.vector import Vector, vector_mean, squared_distance, distance
def num_differences(v1: Vector, v2: Vector) -> int:
assert len(v1) == len(v2)
return len([x1 for x1, x2 in zip(v1, v2) if x1 !... | 0.840619 | 0.741861 |
from django.db import models
# So that we can set the user as a foreign key
from django.conf import settings
# So that we can set date = today
from datetime import datetime
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
User = get_user_model()
from core.models import Colo... | src/team/models.py | from django.db import models
# So that we can set the user as a foreign key
from django.conf import settings
# So that we can set date = today
from datetime import datetime
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
User = get_user_model()
from core.models import Colo... | 0.659844 | 0.166811 |
from __future__ import print_function
import sys
import traceback
import os
import time
# Appending current working directory to sys.path
# So that user can run randomtester from the directory where sut.py is located
current_working_dir = os.getcwd()
sys.path.append(current_working_dir)
if "--help" not in sys.argv:
... | tstl/replay.py | from __future__ import print_function
import sys
import traceback
import os
import time
# Appending current working directory to sys.path
# So that user can run randomtester from the directory where sut.py is located
current_working_dir = os.getcwd()
sys.path.append(current_working_dir)
if "--help" not in sys.argv:
... | 0.130576 | 0.087175 |
import copy
import torch
from typing import Iterable
class EMA:
"""
Implementation of Exponential Moving Averages(EMA) for model parameters.
Args:
parameters: model parameters.
Iterable(torch.nn.Parameter)
decay_rate: decay rate for moving average.
... | model/ema.py | import copy
import torch
from typing import Iterable
class EMA:
"""
Implementation of Exponential Moving Averages(EMA) for model parameters.
Args:
parameters: model parameters.
Iterable(torch.nn.Parameter)
decay_rate: decay rate for moving average.
... | 0.868297 | 0.547162 |
from itertools import groupby
from src.goodies import remove_diacritics, string_to_pairs
from src.user_types import EditableText, InodesPaths
def get_editable_text(inodes_paths: InodesPaths) -> EditableText:
"""
Being given a mapping of inodes (ints) to paths (Path objects), return a textual representation
... | src/get_editable_text.py | from itertools import groupby
from src.goodies import remove_diacritics, string_to_pairs
from src.user_types import EditableText, InodesPaths
def get_editable_text(inodes_paths: InodesPaths) -> EditableText:
"""
Being given a mapping of inodes (ints) to paths (Path objects), return a textual representation
... | 0.69987 | 0.402451 |
import asyncio
import pathlib
import semver
import tarfile
import tempfile
from tensorflow import keras
from tensorflow.keras import callbacks
from tensorcraft import asynclib
from tensorcraft import client
class _RemoteCallback(callbacks.Callback):
"""Callback with default session for communication with remote... | tensorcraft/callbacks.py | import asyncio
import pathlib
import semver
import tarfile
import tempfile
from tensorflow import keras
from tensorflow.keras import callbacks
from tensorcraft import asynclib
from tensorcraft import client
class _RemoteCallback(callbacks.Callback):
"""Callback with default session for communication with remote... | 0.731155 | 0.155719 |
import numpy as np
import matplotlib.pyplot as plt
# Lagrange-Polynomial
def L(n, x, f):
x_ = np.linspace(-1, 1, n + 1)
y_ = f(x_)
l_ = np.zeros(x_.size)
res = 0.0
for i in range(n + 1):
deno, nume = 1.0, 1.0
for j in range(n + 1):
if i != j:
deno *= (x_... | Lagrange-Polynomial.py |
import numpy as np
import matplotlib.pyplot as plt
# Lagrange-Polynomial
def L(n, x, f):
x_ = np.linspace(-1, 1, n + 1)
y_ = f(x_)
l_ = np.zeros(x_.size)
res = 0.0
for i in range(n + 1):
deno, nume = 1.0, 1.0
for j in range(n + 1):
if i != j:
deno *= (x_... | 0.562177 | 0.54468 |
import urllib.parse
from flask import request, abort, render_template
from flask_login import current_user
from wikked.views import add_auth_data, add_navigation_data
from wikked.web import app, get_wiki
from wikked.webimpl import url_from_viewarg
from wikked.webimpl.decorators import requires_permission
from wikked.we... | wikked/views/history.py | import urllib.parse
from flask import request, abort, render_template
from flask_login import current_user
from wikked.views import add_auth_data, add_navigation_data
from wikked.web import app, get_wiki
from wikked.webimpl import url_from_viewarg
from wikked.webimpl.decorators import requires_permission
from wikked.we... | 0.316264 | 0.094427 |
import re
from lxml import etree as ET
from rdflib import BNode, URIRef, Literal, RDF
from rdflib.namespace import DCTERMS
import validators
from .namespaces import SBOL, PROV, XML_NS, NS
class Identified(object):
"""
Mixin to provide identity support to SBOL objects
"""
def __init__(self,
... | snekbol/identified.py | import re
from lxml import etree as ET
from rdflib import BNode, URIRef, Literal, RDF
from rdflib.namespace import DCTERMS
import validators
from .namespaces import SBOL, PROV, XML_NS, NS
class Identified(object):
"""
Mixin to provide identity support to SBOL objects
"""
def __init__(self,
... | 0.637031 | 0.095602 |
from rfxcom.protocol.base import BasePacketHandler
from rfxcom.protocol.rfxpacketutils import RfxPacketUtils
class Elec(BasePacketHandler):
"""The Elec protocol is a 17 byte packet used by energy sensors. The
sensors transmit this packet periodically and the key data it provides is
the current watt usage ... | rfxcom/protocol/elec.py | from rfxcom.protocol.base import BasePacketHandler
from rfxcom.protocol.rfxpacketutils import RfxPacketUtils
class Elec(BasePacketHandler):
"""The Elec protocol is a 17 byte packet used by energy sensors. The
sensors transmit this packet periodically and the key data it provides is
the current watt usage ... | 0.870005 | 0.460653 |
import platform
import os
if platform.system() == "Windows":
import winreg
# Find signtool.exe
def get_sdk8x_bin_paths(reg_keys=None, reg_path="Software\\Microsoft\\Windows Kits\\Installed Roots"):
if reg_keys is None:
reg_keys = ["KitsRoot", "KitsRoot81"]
ret = []
hk = winreg... | windows_signtool.py |
import platform
import os
if platform.system() == "Windows":
import winreg
# Find signtool.exe
def get_sdk8x_bin_paths(reg_keys=None, reg_path="Software\\Microsoft\\Windows Kits\\Installed Roots"):
if reg_keys is None:
reg_keys = ["KitsRoot", "KitsRoot81"]
ret = []
hk = winreg... | 0.171928 | 0.091585 |
# noqa
from django import forms
from common.forms import BaseComponentForm
from components.component import Component
from common.constants import API_TYPE_OP
from .toolkit import tools, configs
class HttpRelay(Component):
"""[FTA] 外网请求代理
{% block api_doc %}
描述
~~~~
参数说明
~... | paas-ce/paas/esb/components/bk/apis/fta/http_relay.py | # noqa
from django import forms
from common.forms import BaseComponentForm
from components.component import Component
from common.constants import API_TYPE_OP
from .toolkit import tools, configs
class HttpRelay(Component):
"""[FTA] 外网请求代理
{% block api_doc %}
描述
~~~~
参数说明
~... | 0.293911 | 0.137099 |
# https://docs.python.org/3.7/reference/datamodel.html
import sys
from fractions import Fraction
if sys.version_info[0] < 3:
print("You need Python 3 to run this script.")
sys.exit(1)
SQRT_THREE: float = 3.0 ** 0.5
class Eisenstein:
def __init__(self, co_real, co_omega=0):
assert isinstance(co... | eisenstein.py | # https://docs.python.org/3.7/reference/datamodel.html
import sys
from fractions import Fraction
if sys.version_info[0] < 3:
print("You need Python 3 to run this script.")
sys.exit(1)
SQRT_THREE: float = 3.0 ** 0.5
class Eisenstein:
def __init__(self, co_real, co_omega=0):
assert isinstance(co... | 0.698741 | 0.489626 |
import pickle
import numpy as np
import os
import scipy.sparse as sp
import torch
from scipy.sparse import linalg
from prettytable import PrettyTable
class DataLoader(object):
def __init__(self, xs, ys, batch_size, pad_with_last_sample=True):
"""
:param xs:
:param ys:
:param batch_... | util.py | import pickle
import numpy as np
import os
import scipy.sparse as sp
import torch
from scipy.sparse import linalg
from prettytable import PrettyTable
class DataLoader(object):
def __init__(self, xs, ys, batch_size, pad_with_last_sample=True):
"""
:param xs:
:param ys:
:param batch_... | 0.635449 | 0.457076 |
import numpy as np
import pandas as pd
from fuzzywuzzy import fuzz
from tqdm import tqdm
from scipy.cluster.hierarchy import linkage
import hcluster # requires dedupe-hcluster
from paper_reviewer_matcher import (
preprocess, compute_affinity
)
def compute_conflicts(df):
"""
Compute conflict for a given... | group_matching.py | import numpy as np
import pandas as pd
from fuzzywuzzy import fuzz
from tqdm import tqdm
from scipy.cluster.hierarchy import linkage
import hcluster # requires dedupe-hcluster
from paper_reviewer_matcher import (
preprocess, compute_affinity
)
def compute_conflicts(df):
"""
Compute conflict for a given... | 0.517083 | 0.211234 |
import collections
import itertools
import numpy as np
__all__ = ['chow_liu']
def chow_liu(X, root=None):
"""Return a Chow-Liu tree.
A Chow-Liu tree takes three steps to build:
1. Compute the mutual information between each pair of variables. The values are organised in
a fully connected grap... | hedgehog/structure.py | import collections
import itertools
import numpy as np
__all__ = ['chow_liu']
def chow_liu(X, root=None):
"""Return a Chow-Liu tree.
A Chow-Liu tree takes three steps to build:
1. Compute the mutual information between each pair of variables. The values are organised in
a fully connected grap... | 0.805441 | 0.796411 |
"""Relay Input Panel."""
# Standard Library Imports
from typing import Any, Dict, List
# Third Party Imports
from pubsub import pub
# RAMSTK Package Imports
from ramstk.views.gtk3 import _
from ramstk.views.gtk3.widgets import RAMSTKComboBox, RAMSTKEntry, RAMSTKFixedPanel
class RelayDesignElectricInputPanel(RAMSTK... | src/ramstk/views/gtk3/design_electric/components/relay.py | """Relay Input Panel."""
# Standard Library Imports
from typing import Any, Dict, List
# Third Party Imports
from pubsub import pub
# RAMSTK Package Imports
from ramstk.views.gtk3 import _
from ramstk.views.gtk3.widgets import RAMSTKComboBox, RAMSTKEntry, RAMSTKFixedPanel
class RelayDesignElectricInputPanel(RAMSTK... | 0.92612 | 0.329904 |
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q, Sum
from django.shortcuts import get_object_or_404, redirect
from django.utils.decorators import method_decorator
from django.views.decorators.http im... | gameserver/views/contest.py | from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.contenttypes.models import ContentType
from django.db.models import Q, Sum
from django.shortcuts import get_object_or_404, redirect
from django.utils.decorators import method_decorator
from django.views.decorators.http im... | 0.564339 | 0.078078 |
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import learning.tf_util as TFUtil
NAME = "fc_2layers_gated_1024units"
def build_net(input_tfs, reuse=False):
layers = [1024, 512]
gate_common_layers = [128]
gate_layers = [64]
activation = tf.nn.relu
weight_init = tf.glorot_uniform_initi... | learning/nets/fc_2layers_gated_1024units.py | import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import learning.tf_util as TFUtil
NAME = "fc_2layers_gated_1024units"
def build_net(input_tfs, reuse=False):
layers = [1024, 512]
gate_common_layers = [128]
gate_layers = [64]
activation = tf.nn.relu
weight_init = tf.glorot_uniform_initi... | 0.740925 | 0.485661 |
import logging
from abc import ABCMeta
from collections import namedtuple
from pyramid.httpexceptions import (
HTTPFound,
HTTPNotFound,
HTTPUnauthorized,
)
from pyramid.response import Response
from pyramid.view import (
view_config,
view_defaults,
forbidden_view_config,
notfound_view_c... | mnemon/web/views.py | import logging
from abc import ABCMeta
from collections import namedtuple
from pyramid.httpexceptions import (
HTTPFound,
HTTPNotFound,
HTTPUnauthorized,
)
from pyramid.response import Response
from pyramid.view import (
view_config,
view_defaults,
forbidden_view_config,
notfound_view_c... | 0.709321 | 0.075687 |
from util import plot_raw_surfaces
from config import DEVICE
import torch.nn.functional as F
from general import generate_layers, generate_surfaces
import torch
import torch.nn as nn
class UNetBlock(nn.Module):
def __init__(self, input_channel, output_channel, down_size=True):
super(UNetBlock, self).__in... | model.py |
from util import plot_raw_surfaces
from config import DEVICE
import torch.nn.functional as F
from general import generate_layers, generate_surfaces
import torch
import torch.nn as nn
class UNetBlock(nn.Module):
def __init__(self, input_channel, output_channel, down_size=True):
super(UNetBlock, self).__in... | 0.96074 | 0.331187 |
import gi
from gi.repository import Gtk as gtk
from gi.repository import Gdk as gdk
from gi.repository import AppIndicator3 as appindicator
from gi.repository import Notify as notify
import click
import json
import logging
import signal
import sqlite3
import subprocess
import sys
from os import makedirs
from os.path i... | vxscreenshots/vxscreenshots.py | import gi
from gi.repository import Gtk as gtk
from gi.repository import Gdk as gdk
from gi.repository import AppIndicator3 as appindicator
from gi.repository import Notify as notify
import click
import json
import logging
import signal
import sqlite3
import subprocess
import sys
from os import makedirs
from os.path i... | 0.265214 | 0.049704 |
import torch
from torch import Tensor
from torch.nn import CrossEntropyLoss, L1Loss, MSELoss
from torch.optim import Adam
from torch.optim.lr_scheduler import _LRScheduler, StepLR
from torch.optim.optimizer import Optimizer
from sonata.models import BaseModule
from sonata.models.hidt_components import (
Conditiona... | sonata/models/hidt_model.py | import torch
from torch import Tensor
from torch.nn import CrossEntropyLoss, L1Loss, MSELoss
from torch.optim import Adam
from torch.optim.lr_scheduler import _LRScheduler, StepLR
from torch.optim.optimizer import Optimizer
from sonata.models import BaseModule
from sonata.models.hidt_components import (
Conditiona... | 0.862786 | 0.364778 |
import time
from functools import wraps
def check_argument_is_positive_integer(unary_func):
def helper(n):
if type(n) == int and n > 0:
return unary_func(n)
else:
raise ValueError("n must be positive and of type int")
return helper
def factorial(n):
if n <= 0:
... | Python/zzz_training_challenge/Python_Challenge/solutions/ch03_recursion/intro/decorators.py |
import time
from functools import wraps
def check_argument_is_positive_integer(unary_func):
def helper(n):
if type(n) == int and n > 0:
return unary_func(n)
else:
raise ValueError("n must be positive and of type int")
return helper
def factorial(n):
if n <= 0:
... | 0.385028 | 0.447279 |