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 numpy as np
import ray
import torch
from ray.rllib.agents.ppo import ppo
from ray.rllib.models.preprocessors import get_preprocessor
from ray.tune import register_env
from games.base import MeanFieldGame
from games.mfg_wrapper import MFGGymWrapper
from simulator.mean_fields.base import MeanField
from solver.bas... | solver/ppo_solver.py | import numpy as np
import ray
import torch
from ray.rllib.agents.ppo import ppo
from ray.rllib.models.preprocessors import get_preprocessor
from ray.tune import register_env
from games.base import MeanFieldGame
from games.mfg_wrapper import MFGGymWrapper
from simulator.mean_fields.base import MeanField
from solver.bas... | 0.866712 | 0.196036 |
# Will hold our game board data
board = ["-", "-", "-",
"-", "-", "-",
"-", "-", "-"]
# Lets us know if the game is over yet
game_still_going = True
# Tells us who the winner is
winner = None
# Tells us who the current player is (X goes first)
current_player = "X"
# ------------- Functions -----... | main.py |
# Will hold our game board data
board = ["-", "-", "-",
"-", "-", "-",
"-", "-", "-"]
# Lets us know if the game is over yet
game_still_going = True
# Tells us who the winner is
winner = None
# Tells us who the current player is (X goes first)
current_player = "X"
# ------------- Functions -----... | 0.599602 | 0.517022 |
import os
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib as mpl
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection
import seaborn as sns
from munging import compute_means, compute_er... | modules/visualization.py | import os
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib as mpl
import matplotlib.patches as mpatches
from matplotlib.collections import PatchCollection
import seaborn as sns
from munging import compute_means, compute_er... | 0.550245 | 0.470615 |
import datetime
import logging
import os
import random
import sys
import tempfile
import uuid
from unittest.mock import MagicMock, patch
import cloudpickle
import pendulum
import pytest
import prefect
from prefect.core.edge import Edge
from prefect.core.flow import Flow
from prefect.core.task import Parameter, Task
f... | tests/core/test_flow.py | import datetime
import logging
import os
import random
import sys
import tempfile
import uuid
from unittest.mock import MagicMock, patch
import cloudpickle
import pendulum
import pytest
import prefect
from prefect.core.edge import Edge
from prefect.core.flow import Flow
from prefect.core.task import Parameter, Task
f... | 0.426322 | 0.347814 |
import argparse
import data
import io_model
import matplotlib.pyplot as plt
import numpy as np
import os
import performance_data
import plots
import sequence
import torch
import training_data
import utils
parser = argparse.ArgumentParser()
parser.add_argument("dataset_name", type=str, help="name of test dataset")
pars... | code/behavior_sequence_predictions_plot.py | import argparse
import data
import io_model
import matplotlib.pyplot as plt
import numpy as np
import os
import performance_data
import plots
import sequence
import torch
import training_data
import utils
parser = argparse.ArgumentParser()
parser.add_argument("dataset_name", type=str, help="name of test dataset")
pars... | 0.739705 | 0.317439 |
import copy
import logging
from collections.abc import Mapping
import salt.utils.data
from salt.defaults import DEFAULT_TARGET_DELIM
from salt.exceptions import SaltInvocationError
from salt.utils.decorators.jinja import jinja_filter
from salt.utils.odict import OrderedDict
log = logging.getLogger(__name__)
def upd... | salt/utils/dictupdate.py | import copy
import logging
from collections.abc import Mapping
import salt.utils.data
from salt.defaults import DEFAULT_TARGET_DELIM
from salt.exceptions import SaltInvocationError
from salt.utils.decorators.jinja import jinja_filter
from salt.utils.odict import OrderedDict
log = logging.getLogger(__name__)
def upd... | 0.654011 | 0.149562 |
import urllib.request
import panel as pn
from awesome_panel.express.assets import FONTAWESOME_PANEL_EXPRESS_CSS
FONTAWESOME_CSS_URL = "https://use.fontawesome.com/releases/v5.11.2/css/all.css"
_EXTENDED = False
_FONTAWESOME_PANEL_EXPRESS_HEADER = """
div.bk.pas div.bk *::before, div.bk.pab div.bk *::bef... | package/awesome_panel/express/fontawesome/fontawesome.py | import urllib.request
import panel as pn
from awesome_panel.express.assets import FONTAWESOME_PANEL_EXPRESS_CSS
FONTAWESOME_CSS_URL = "https://use.fontawesome.com/releases/v5.11.2/css/all.css"
_EXTENDED = False
_FONTAWESOME_PANEL_EXPRESS_HEADER = """
div.bk.pas div.bk *::before, div.bk.pab div.bk *::bef... | 0.396419 | 0.13887 |
import pprint
import re # noqa: F401
import six
from memsource_cli.models.enabled_check_dto import EnabledCheckDto # noqa: F401,E501
from memsource_cli.models.regexp_check_rule_dto_v2 import RegexpCheckRuleDtoV2 # noqa: F401,E501
class QualityAssuranceChecksDto(object):
"""NOTE: This class is auto generated ... | memsource_cli/models/quality_assurance_checks_dto.py | import pprint
import re # noqa: F401
import six
from memsource_cli.models.enabled_check_dto import EnabledCheckDto # noqa: F401,E501
from memsource_cli.models.regexp_check_rule_dto_v2 import RegexpCheckRuleDtoV2 # noqa: F401,E501
class QualityAssuranceChecksDto(object):
"""NOTE: This class is auto generated ... | 0.55941 | 0.169853 |
from .api.santiebeati import SantiEBeatiClient
from .santo import Santo
from typing import List
class Factory(object):
"""Santi factory"""
@staticmethod
def make_santi_from_santiebeati() -> List[Santo]:
"""Get list of santi from santiebeati.it"""
return SantiEBeatiClient().query_santi(10... | mannaggia/santi/factory.py | from .api.santiebeati import SantiEBeatiClient
from .santo import Santo
from typing import List
class Factory(object):
"""Santi factory"""
@staticmethod
def make_santi_from_santiebeati() -> List[Santo]:
"""Get list of santi from santiebeati.it"""
return SantiEBeatiClient().query_santi(10... | 0.677367 | 0.634402 |
import os
import shutil
import json
import ast
import logging
from ambari_server.serverClassPath import ServerClassPath
from ambari_commons.exceptions import FatalException
from ambari_commons.inet_utils import download_file
from ambari_commons.logging_utils import print_info_msg, print_error_msg, print_warning_msg
f... | ambari-server/src/main/python/ambari_server/setupMpacks.py | import os
import shutil
import json
import ast
import logging
from ambari_server.serverClassPath import ServerClassPath
from ambari_commons.exceptions import FatalException
from ambari_commons.inet_utils import download_file
from ambari_commons.logging_utils import print_info_msg, print_error_msg, print_warning_msg
f... | 0.285671 | 0.056626 |
import os
import Levenshtein
from lxml import etree
from .utils import get_current_time_in_utc, nsmap, segment_to_tm_segment
from .version import __version__
class TranslationMemory():
def __init__(self, tm_path, source_language, target_language):
self.tm_path = tm_path
if os.path.exists(tm_path... | toraman/translationmemory.py | import os
import Levenshtein
from lxml import etree
from .utils import get_current_time_in_utc, nsmap, segment_to_tm_segment
from .version import __version__
class TranslationMemory():
def __init__(self, tm_path, source_language, target_language):
self.tm_path = tm_path
if os.path.exists(tm_path... | 0.351089 | 0.126812 |
import locale
import subprocess
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../"))
import easygui_qt
from PyQt4 import QtCore, QtGui
def launch(name, *args):
"""Executes a script designed specifically for this launcher.
The parameter "name" is the name of the function... | easygui_qt/demos/launcher.py | import locale
import subprocess
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "../"))
import easygui_qt
from PyQt4 import QtCore, QtGui
def launch(name, *args):
"""Executes a script designed specifically for this launcher.
The parameter "name" is the name of the function... | 0.264358 | 0.070977 |
from __future__ import division
from __future__ import print_function
import time
import tensorflow as tf
from gcn_model.utils import *
from gcn_model.models import GCN
from model.hyparameter import parameter
import argparse
# define parameter
para = parameter(argparse.ArgumentParser())
para = para.get_para()
# Lo... | OD/run_gcn_rlstm.py |
from __future__ import division
from __future__ import print_function
import time
import tensorflow as tf
from gcn_model.utils import *
from gcn_model.models import GCN
from model.hyparameter import parameter
import argparse
# define parameter
para = parameter(argparse.ArgumentParser())
para = para.get_para()
# Lo... | 0.868353 | 0.314419 |
import os
import re
import sys
from distutils.command.build_py import build_py
from distutils.command.sdist import sdist
from setuptools import setup, find_packages
from eucaconsole import __version__
DATA_DIR = '/usr/share/'
py_version = sys.version_info[:2]
if py_version < (2, 7):
# Workaround for https://... | setup.py |
import os
import re
import sys
from distutils.command.build_py import build_py
from distutils.command.sdist import sdist
from setuptools import setup, find_packages
from eucaconsole import __version__
DATA_DIR = '/usr/share/'
py_version = sys.version_info[:2]
if py_version < (2, 7):
# Workaround for https://... | 0.313945 | 0.107297 |
import argparse
from sys import exit
import json
import psycopg2
from utils import eprint
# Figure out how to connect to PSQL from
# http://www.postgresqltutorial.com/postgresql-python/connect/
def read_cmd():
"""Reading command line options."""
desc = "Program for linking CS-Khan content for EMA reputation sy... | ks_content_linking.py | import argparse
from sys import exit
import json
import psycopg2
from utils import eprint
# Figure out how to connect to PSQL from
# http://www.postgresqltutorial.com/postgresql-python/connect/
def read_cmd():
"""Reading command line options."""
desc = "Program for linking CS-Khan content for EMA reputation sy... | 0.201342 | 0.079282 |
import os
import pytest
FIXTURES_DIR = os.path.join(os.path.dirname(__file__), 'fixture')
def test_audit_config(plan_runner):
"Test audit config."
iam_audit_config = '{allServices={DATA_READ=[], DATA_WRITE=["user:<EMAIL>"]}}'
_, resources = plan_runner(FIXTURES_DIR, iam_audit_config=iam_audit_config)
asse... | tests/modules/organization/test_plan.py |
import os
import pytest
FIXTURES_DIR = os.path.join(os.path.dirname(__file__), 'fixture')
def test_audit_config(plan_runner):
"Test audit config."
iam_audit_config = '{allServices={DATA_READ=[], DATA_WRITE=["user:<EMAIL>"]}}'
_, resources = plan_runner(FIXTURES_DIR, iam_audit_config=iam_audit_config)
asse... | 0.416915 | 0.330593 |
import json
from argparse import ArgumentParser
from pathlib import Path
LINK_ROOT = 'https://tablebase.lichess.ovh/tables/standard/7'
GIGABYTE = 1_000_000_000
def folder_from_egtb_name(name: str) -> str:
"""
Determine EGTB folder (Xvy_pawn(less|ful)) from EGTB name
:param name: EGTB name
"""
l,... | generatemdtables.py | import json
from argparse import ArgumentParser
from pathlib import Path
LINK_ROOT = 'https://tablebase.lichess.ovh/tables/standard/7'
GIGABYTE = 1_000_000_000
def folder_from_egtb_name(name: str) -> str:
"""
Determine EGTB folder (Xvy_pawn(less|ful)) from EGTB name
:param name: EGTB name
"""
l,... | 0.625095 | 0.414306 |
import uuid
import httpretty
from keystoneclient import exceptions
from keystoneclient.tests.v2_0 import utils
from keystoneclient.v2_0 import tenants
class TenantTests(utils.TestCase):
def setUp(self):
super(TenantTests, self).setUp()
self.INVIS_ID = uuid.uuid4().hex
self.DEMO_ID = uu... | keystoneclient/tests/v2_0/test_tenants.py |
import uuid
import httpretty
from keystoneclient import exceptions
from keystoneclient.tests.v2_0 import utils
from keystoneclient.v2_0 import tenants
class TenantTests(utils.TestCase):
def setUp(self):
super(TenantTests, self).setUp()
self.INVIS_ID = uuid.uuid4().hex
self.DEMO_ID = uu... | 0.496826 | 0.188417 |
import numpy as np
import pandas as pd
import junkoda_cellularlib._cellularlib as c # library in C++
from .clusters import Clusters
from .graph import Graph
class Watershed:
"""
Watershed(img=None, pixel_theshold=0.0, merge_threshold=-1)
Args:
img (array): 2D array of float64
pix... | py/junkoda_cellularlib/watershed.py | import numpy as np
import pandas as pd
import junkoda_cellularlib._cellularlib as c # library in C++
from .clusters import Clusters
from .graph import Graph
class Watershed:
"""
Watershed(img=None, pixel_theshold=0.0, merge_threshold=-1)
Args:
img (array): 2D array of float64
pix... | 0.856332 | 0.435241 |
import sklearnex
def test_monkey_patching():
_tokens = sklearnex.get_patch_names()
_values = sklearnex.get_patch_map().values()
_classes = list()
for v in _values:
for c in v:
_classes.append(c[0])
sklearnex.patch_sklearn()
for i, _ in enumerate(_tokens):... | sklearnex/tests/test_monkeypatch.py |
import sklearnex
def test_monkey_patching():
_tokens = sklearnex.get_patch_names()
_values = sklearnex.get_patch_map().values()
_classes = list()
for v in _values:
for c in v:
_classes.append(c[0])
sklearnex.patch_sklearn()
for i, _ in enumerate(_tokens):... | 0.526099 | 0.218523 |
from __future__ import print_function
from collections import namedtuple
import optparse, os, shutil, subprocess, types
home=os.path.expanduser("~")
assert os.path.isdir(home), "home directory must be present"
class Path(str):
def __new__(cls, *unix_paths):
args = []
for path in unix_paths:
... | scripts/code_standards/path_resolv.py |
from __future__ import print_function
from collections import namedtuple
import optparse, os, shutil, subprocess, types
home=os.path.expanduser("~")
assert os.path.isdir(home), "home directory must be present"
class Path(str):
def __new__(cls, *unix_paths):
args = []
for path in unix_paths:
... | 0.512205 | 0.166506 |
import os
import sys
import textwrap
from os.path import exists
from nose import SkipTest
from pip import wheel
from pip.download import path_to_url as path_to_url_d
from tests.lib import tests_data, reset_env, run_pip, pyversion_nodot, write_file, path_to_url, find_links, pip_install_local
def test_pip_wheel_fails_... | tests/functional/test_wheel.py | import os
import sys
import textwrap
from os.path import exists
from nose import SkipTest
from pip import wheel
from pip.download import path_to_url as path_to_url_d
from tests.lib import tests_data, reset_env, run_pip, pyversion_nodot, write_file, path_to_url, find_links, pip_install_local
def test_pip_wheel_fails_... | 0.236428 | 0.259216 |
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
def weights_init_xavier(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1 or classname.find('Linear') != -1:
init.xavier_uniform_(m.weight)
class ResidualBlock(nn.Module):
def __init_... | net.py | import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
def weights_init_xavier(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1 or classname.find('Linear') != -1:
init.xavier_uniform_(m.weight)
class ResidualBlock(nn.Module):
def __init_... | 0.937462 | 0.498535 |
from idlelib import config
import sys
import os
import tempfile
from test.support import captured_stderr, findfile
import unittest
from unittest import mock
import idlelib
from idlelib.idle_test.mock_idle import Func
# Tests should not depend on fortuitous user configurations.
# They must not affect actual user .cfg f... | Lib/idlelib/idle_test/test_config.py | from idlelib import config
import sys
import os
import tempfile
from test.support import captured_stderr, findfile
import unittest
from unittest import mock
import idlelib
from idlelib.idle_test.mock_idle import Func
# Tests should not depend on fortuitous user configurations.
# They must not affect actual user .cfg f... | 0.446736 | 0.194186 |
import os.path as op
import sys
import logging
from jcvi.formats.sam import get_prefix
from jcvi.apps.base import OptionParser, ActionDispatcher, need_update, sh, \
get_abs_path, backup
def main():
actions = (
('index', 'wraps gmap_build'),
('align', 'wraps gsnap'),
('gmap', ... | apps/gmap.py | import os.path as op
import sys
import logging
from jcvi.formats.sam import get_prefix
from jcvi.apps.base import OptionParser, ActionDispatcher, need_update, sh, \
get_abs_path, backup
def main():
actions = (
('index', 'wraps gmap_build'),
('align', 'wraps gsnap'),
('gmap', ... | 0.296756 | 0.188287 |
from django.http import HttpResponse, JsonResponse
from User.models import User
# Create your views here.
def calrecs(request,username):
# Get User stats by username
#UserStats = Question.objects.order_by('-pub_date')[:5]
try:
user = User.objects.get(username=username)
age = user.age
... | supersizeme/calrecs/views.py | from django.http import HttpResponse, JsonResponse
from User.models import User
# Create your views here.
def calrecs(request,username):
# Get User stats by username
#UserStats = Question.objects.order_by('-pub_date')[:5]
try:
user = User.objects.get(username=username)
age = user.age
... | 0.364778 | 0.330039 |
import graphene
from graphene import resolve_only_args, relay
from graphene.contrib.django import DjangoNode, DjangoConnectionField
from graphql_relay.node.node import from_global_id
from graphql.core.type import (
GraphQLArgument,
GraphQLString,
GraphQLInt,
GraphQLFloat,
GraphQLBoolean,
GraphQL... | reeltalk/schema.py | import graphene
from graphene import resolve_only_args, relay
from graphene.contrib.django import DjangoNode, DjangoConnectionField
from graphql_relay.node.node import from_global_id
from graphql.core.type import (
GraphQLArgument,
GraphQLString,
GraphQLInt,
GraphQLFloat,
GraphQLBoolean,
GraphQL... | 0.562297 | 0.149562 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | tests/backend/test_loss_channel.py |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the... | 0.929592 | 0.53127 |
import json
import logging
import mimetypes
import os
import sys
import time
from abc import ABC, abstractmethod
from typing import Optional
import requests
import telegram
from telegram import ChatAction
from telegram.ext import CallbackContext
from telegram.ext import Updater, MessageHandler, Filters
mimetypes.init... | services/django_server/mydata/logbook/management/commands/mytelegrambot.py | import json
import logging
import mimetypes
import os
import sys
import time
from abc import ABC, abstractmethod
from typing import Optional
import requests
import telegram
from telegram import ChatAction
from telegram.ext import CallbackContext
from telegram.ext import Updater, MessageHandler, Filters
mimetypes.init... | 0.58059 | 0.079782 |
__author__ = 'github.com/samshadwell'
# Token constants
T_End = -1
T_Plus = 0
T_Minus = 1
T_Times = 2
T_Over = 3
T_Less = 4
T_Greater = 5
T_LParen = 10
T_RParen = 11
T_LBrace = 12
T_RBrace = 13
T_Is = 20
T_If = 21
T_Else = 22
T_True = 30
T_False = 31
T_And = 32
T_Or = 33
T_Not = 34
T_Word = 40
T_Num = 41
T_Quote ... | src/trumpscript/constants.py | __author__ = 'github.com/samshadwell'
# Token constants
T_End = -1
T_Plus = 0
T_Minus = 1
T_Times = 2
T_Over = 3
T_Less = 4
T_Greater = 5
T_LParen = 10
T_RParen = 11
T_LBrace = 12
T_RBrace = 13
T_Is = 20
T_If = 21
T_Else = 22
T_True = 30
T_False = 31
T_And = 32
T_Or = 33
T_Not = 34
T_Word = 40
T_Num = 41
T_Quote ... | 0.278355 | 0.22465 |
import sys
sys.path.append('../')
import re
import json
import builtins
from ADC_function import *
from lxml.html import fromstring
from multiprocessing.dummy import Pool as ThreadPool
from difflib import SequenceMatcher
from unicodedata import category
from number_parser import is_uncensored
G_registered_storyline_si... | WebCrawler/storyline.py | import sys
sys.path.append('../')
import re
import json
import builtins
from ADC_function import *
from lxml.html import fromstring
from multiprocessing.dummy import Pool as ThreadPool
from difflib import SequenceMatcher
from unicodedata import category
from number_parser import is_uncensored
G_registered_storyline_si... | 0.185394 | 0.154026 |
__version__ = '1.0'
__author__ = '<NAME> <<EMAIL>>'
#append STAF lib path into sys.path if it is not there.
import sys
STAF_LIB_PATH = '/opt/staf/lib'
if not '/opt/staf/lib' in sys.path:
sys.path.append(STAF_LIB_PATH)
import os, PySTAF
class STAFLibrary:
"""
STAF Library is a test library for robot framew... | STAFLibrary/__init__.py | __version__ = '1.0'
__author__ = '<NAME> <<EMAIL>>'
#append STAF lib path into sys.path if it is not there.
import sys
STAF_LIB_PATH = '/opt/staf/lib'
if not '/opt/staf/lib' in sys.path:
sys.path.append(STAF_LIB_PATH)
import os, PySTAF
class STAFLibrary:
"""
STAF Library is a test library for robot framew... | 0.373304 | 0.130396 |
from django.core.paginator import Paginator
from django.http.response import HttpResponse
from django.shortcuts import render
from django.db.models import Count
from .models import Post, PostTag
RESULTS_PER_PAGE = 12
def post_view(request, post_slug):
blog_post = Post.objects.filter(slug=post_slug).first... | web/blog/views.py | from django.core.paginator import Paginator
from django.http.response import HttpResponse
from django.shortcuts import render
from django.db.models import Count
from .models import Post, PostTag
RESULTS_PER_PAGE = 12
def post_view(request, post_slug):
blog_post = Post.objects.filter(slug=post_slug).first... | 0.244995 | 0.060087 |
import numpy as np
from astropy.tests.helper import pytest
from astropy.utils.data import get_pkg_data_filename
import astropy.units as u
from ..utils import validate_data_table, sed_conversion, generate_energy_edges, build_data_table
from astropy.io import ascii
# Read data
fname = get_pkg_data_filename('data/CrabN... | gammafit/tests/test_utils.py | import numpy as np
from astropy.tests.helper import pytest
from astropy.utils.data import get_pkg_data_filename
import astropy.units as u
from ..utils import validate_data_table, sed_conversion, generate_energy_edges, build_data_table
from astropy.io import ascii
# Read data
fname = get_pkg_data_filename('data/CrabN... | 0.678859 | 0.501221 |
import os
import shutil
import zipfile
from pathlib import Path
from distutils.dir_util import copy_tree
import tqdm
from tqdm import tqdm
def prepare_firebase():
cwd = os.getcwd()
print("Prepare target folder for libraries")
target_dir = os.path.join(cwd, "Libraries")
if os.path.exists(target_dir):... | Tools/main.py | import os
import shutil
import zipfile
from pathlib import Path
from distutils.dir_util import copy_tree
import tqdm
from tqdm import tqdm
def prepare_firebase():
cwd = os.getcwd()
print("Prepare target folder for libraries")
target_dir = os.path.join(cwd, "Libraries")
if os.path.exists(target_dir):... | 0.136724 | 0.069922 |
from netapp.netapp_object import NetAppObject
class SecuritySshInfo(NetAppObject):
"""
Provide SSH configuration
When returned as part of the output, all elements of this typedef
are reported, unless limited by a set of desired attributes
specified by the caller.
<p>
When used as input to s... | generated-libraries/python/netapp/security/security_ssh_info.py | from netapp.netapp_object import NetAppObject
class SecuritySshInfo(NetAppObject):
"""
Provide SSH configuration
When returned as part of the output, all elements of this typedef
are reported, unless limited by a set of desired attributes
specified by the caller.
<p>
When used as input to s... | 0.862076 | 0.201028 |
from typing import Any, Dict, Optional
import numpy as np
import pandas as pd
from streamlit_prophet.lib.utils.load import load_config
config, _, _ = load_config(
"config_streamlit.toml", "config_instructions.toml", "config_readme.toml"
)
def make_test_df(
ds: Optional[Dict[Any, Any]] = None,
cols: Opti... | tests/samples/df.py | from typing import Any, Dict, Optional
import numpy as np
import pandas as pd
from streamlit_prophet.lib.utils.load import load_config
config, _, _ = load_config(
"config_streamlit.toml", "config_instructions.toml", "config_readme.toml"
)
def make_test_df(
ds: Optional[Dict[Any, Any]] = None,
cols: Opti... | 0.864124 | 0.384219 |
import argparse
import json
import uuid
from azure.common.client_factory import get_client_from_cli_profile
from azure.mgmt.eventgrid import EventGridManagementClient
from azure.mgmt.eventgrid.models import EventSubscription
from azure.mgmt.storage import StorageManagementClient
from azure.mgmt.storage.models import ... | src/utils/add-corpus-storage-accounts/add-corpus-storage-account.py |
import argparse
import json
import uuid
from azure.common.client_factory import get_client_from_cli_profile
from azure.mgmt.eventgrid import EventGridManagementClient
from azure.mgmt.eventgrid.models import EventSubscription
from azure.mgmt.storage import StorageManagementClient
from azure.mgmt.storage.models import ... | 0.513181 | 0.085595 |
import unittest
from azure.communication.chat._shared.communication_identifier_serializer import CommunicationUserIdentifierSerializer
from azure.communication.chat._shared.models import(
CommunicationIdentifierModel,
CommunicationUserIdentifier,
CommunicationCloudEnvironment,
UnknownIdentifier,
Pho... | sdk/communication/azure-communication-chat/tests/_shared/test_communication_identifier_serializer.py | import unittest
from azure.communication.chat._shared.communication_identifier_serializer import CommunicationUserIdentifierSerializer
from azure.communication.chat._shared.models import(
CommunicationIdentifierModel,
CommunicationUserIdentifier,
CommunicationCloudEnvironment,
UnknownIdentifier,
Pho... | 0.403802 | 0.127734 |
from testfixtures import LogCapture
from twisted.trial import unittest
from twisted.python.failure import Failure
from twisted.internet import defer, reactor
from pydispatch import dispatcher
from scrapy.utils.signal import send_catch_log, send_catch_log_deferred
class SendCatchLogTest(unittest.TestCase):
@defe... | tests/test_utils_signal.py | from testfixtures import LogCapture
from twisted.trial import unittest
from twisted.python.failure import Failure
from twisted.internet import defer, reactor
from pydispatch import dispatcher
from scrapy.utils.signal import send_catch_log, send_catch_log_deferred
class SendCatchLogTest(unittest.TestCase):
@defe... | 0.699254 | 0.330053 |
import scaffoldgraph.vis.utils as vis_utils
import matplotlib.pyplot as plt
import random
import pytest
import re
from rdkit.Chem.Draw import rdMolDraw2D
from rdkit import Chem
from scaffoldgraph.utils import suppress_rdlogger
from . import long_test_network
SVG_PATTERN = r'(?:<\?xml\b[^>]*>[^<]*)?(?:<!--.*?-->[^<]... | tests/vis/test_vis_utils.py | import scaffoldgraph.vis.utils as vis_utils
import matplotlib.pyplot as plt
import random
import pytest
import re
from rdkit.Chem.Draw import rdMolDraw2D
from rdkit import Chem
from scaffoldgraph.utils import suppress_rdlogger
from . import long_test_network
SVG_PATTERN = r'(?:<\?xml\b[^>]*>[^<]*)?(?:<!--.*?-->[^<]... | 0.647241 | 0.573977 |
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form mu... | src/cocomud.py |
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form mu... | 0.695235 | 0.037538 |
import logging
import json
import requests
import voluptuous as vol
from typing import Any, Dict, List, Optional
from homeassistant.components.climate import (ClimateDevice, PLATFORM_SCHEMA)
from homeassistant.components.climate.const import (
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
PRESET_AWAY,
PRESET_COMFORT,... | custom_components/toon_climate/climate.py | import logging
import json
import requests
import voluptuous as vol
from typing import Any, Dict, List, Optional
from homeassistant.components.climate import (ClimateDevice, PLATFORM_SCHEMA)
from homeassistant.components.climate.const import (
HVAC_MODE_HEAT,
HVAC_MODE_OFF,
PRESET_AWAY,
PRESET_COMFORT,... | 0.854263 | 0.127707 |
import cio
from cio.backends import cache, storage
from cio.backends.exceptions import NodeDoesNotExist
from cio.utils.uri import URI
from tests import BaseTest
class CacheTest(BaseTest):
uri = 'i18n://sv-se@label/email.txt'
def test_cached_node(self):
with self.assertRaises(NodeDoesNotExist):
... | tests/test_cache.py | import cio
from cio.backends import cache, storage
from cio.backends.exceptions import NodeDoesNotExist
from cio.utils.uri import URI
from tests import BaseTest
class CacheTest(BaseTest):
uri = 'i18n://sv-se@label/email.txt'
def test_cached_node(self):
with self.assertRaises(NodeDoesNotExist):
... | 0.495361 | 0.242026 |
from unittest import TestCase
from unittest.mock import Mock, patch
from kytos.core.events import KytosEvent
from tests.integration.helpers import (get_controller_mock, get_interface_mock,
get_switch_mock)
LINK_DATA = {
"active": False,
"enabled": True,
"endpoint_a":... | tests/integration/test_main.py | from unittest import TestCase
from unittest.mock import Mock, patch
from kytos.core.events import KytosEvent
from tests.integration.helpers import (get_controller_mock, get_interface_mock,
get_switch_mock)
LINK_DATA = {
"active": False,
"enabled": True,
"endpoint_a":... | 0.725454 | 0.51379 |
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
from Crypto.Signature import PKCS1_v1_5
from base64 import b64decode
import logging
from functools import wraps
_logger = logging.getLogger(__name__)
class ScriptDownloadError(Exception):
''' 无法从系统下载脚本'''
def __init__(self, script_name, err):
... | edo_client/rse.py |
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA256
from Crypto.Signature import PKCS1_v1_5
from base64 import b64decode
import logging
from functools import wraps
_logger = logging.getLogger(__name__)
class ScriptDownloadError(Exception):
''' 无法从系统下载脚本'''
def __init__(self, script_name, err):
... | 0.380989 | 0.067886 |
import pytest
import os
import numpy as np
import scipy.interpolate as si
import matplotlib.image as mpimg
from ogusa import utils, parameter_plots, income
# Load in test results and parameters
CUR_PATH = os.path.abspath(os.path.dirname(__file__))
base_params = utils.safe_read_pickle(
os.path.join(CUR_PATH, 'test... | ogusa/tests/test_parameter_plots.py | import pytest
import os
import numpy as np
import scipy.interpolate as si
import matplotlib.image as mpimg
from ogusa import utils, parameter_plots, income
# Load in test results and parameters
CUR_PATH = os.path.abspath(os.path.dirname(__file__))
base_params = utils.safe_read_pickle(
os.path.join(CUR_PATH, 'test... | 0.4856 | 0.630258 |
import os, util
from string import Template
jvpp_ifc_template = Template("""
package $plugin_package;
/**
* <p>Java representation of plugin's api file.
* <br>It was generated by jvpp_impl_gen.py based on $inputfile
* <br>(python representation of api file generated by vppapigen).
*/
public interface JVpp${plugi... | vpp-api/java/jvpp/gen/jvppgen/jvpp_impl_gen.py |
import os, util
from string import Template
jvpp_ifc_template = Template("""
package $plugin_package;
/**
* <p>Java representation of plugin's api file.
* <br>It was generated by jvpp_impl_gen.py based on $inputfile
* <br>(python representation of api file generated by vppapigen).
*/
public interface JVpp${plugi... | 0.515376 | 0.048541 |
import logging
import os
import sys
from colorsys import hsv_to_rgb
import mp2
try:
import cPickle as pickle
except ImportError: # Python 3.x
import pickle
import colorlog
import numpy as np
from PIL import Image
logger = logging.getLogger()
logger.setLevel(colorlog.colorlog.logging.DEBUG)
handler = colo... | MP4/mp4.py |
import logging
import os
import sys
from colorsys import hsv_to_rgb
import mp2
try:
import cPickle as pickle
except ImportError: # Python 3.x
import pickle
import colorlog
import numpy as np
from PIL import Image
logger = logging.getLogger()
logger.setLevel(colorlog.colorlog.logging.DEBUG)
handler = colo... | 0.612889 | 0.315723 |
from django.db import models
from otree.models import Participant
from django.db import transaction
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from otree_tools import cp
from django.db.models import F, ExpressionWrapper, DurationField, Sum... | otree_tools/models/models.py | from django.db import models
from otree.models import Participant
from django.db import transaction
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.fields import GenericForeignKey
from otree_tools import cp
from django.db.models import F, ExpressionWrapper, DurationField, Sum... | 0.521715 | 0.257164 |
from multiprocessing import Pool, cpu_count
import random, sys
from time import perf_counter
# This method uses the same functional paradigm as Pool/map.
def monte_carlo_sim(num_trials):
"""Returns the number of x,y pairs in [0, 1] that lie inside the unit circle."""
return sum(map(lambda t: 1 if t[0]**2 + t... | lecture-2/estimate_pi.py | from multiprocessing import Pool, cpu_count
import random, sys
from time import perf_counter
# This method uses the same functional paradigm as Pool/map.
def monte_carlo_sim(num_trials):
"""Returns the number of x,y pairs in [0, 1] that lie inside the unit circle."""
return sum(map(lambda t: 1 if t[0]**2 + t... | 0.487795 | 0.333435 |
from PySide2.QtWidgets import QWidget, QFileDialog
from .layout.mg_state_machine_widget_ui import Ui_MGStateMachineWidget
from tool.core.widget_manager import WidgetManager
import numpy as np
class MGStateMachineWidget(QWidget, Ui_MGStateMachineWidget):
COMPONENT_NAME = "morphablegraph_state_machine"
def __i... | tool/plugins/morphablegraphs/gui/mg_state_machine_widget.py | from PySide2.QtWidgets import QWidget, QFileDialog
from .layout.mg_state_machine_widget_ui import Ui_MGStateMachineWidget
from tool.core.widget_manager import WidgetManager
import numpy as np
class MGStateMachineWidget(QWidget, Ui_MGStateMachineWidget):
COMPONENT_NAME = "morphablegraph_state_machine"
def __i... | 0.549641 | 0.099252 |
from __future__ import unicode_literals
import imaplib
import json
import logging
import os
import poplib
import subprocess
import yaml
from django.core.exceptions import ValidationError
from django.core.files import File
from django.core.files.base import ContentFile
from django.db import models, transaction
from d... | mayan/apps/sources/models.py | from __future__ import unicode_literals
import imaplib
import json
import logging
import os
import poplib
import subprocess
import yaml
from django.core.exceptions import ValidationError
from django.core.files import File
from django.core.files.base import ContentFile
from django.db import models, transaction
from d... | 0.343672 | 0.0524 |
from solidityobf.common.tree_walker import walker
from solidityobf.common.classes import Function, Ident, Statements, Program, Expr
def get_funcs(program):
ret, arg = walker(program, function=get_funcs_func)
return ret
def get_funcs_func(program, arg):
if program.__class__ == Function:
ret = [p... | src/solidityobf/common/finder.py | from solidityobf.common.tree_walker import walker
from solidityobf.common.classes import Function, Ident, Statements, Program, Expr
def get_funcs(program):
ret, arg = walker(program, function=get_funcs_func)
return ret
def get_funcs_func(program, arg):
if program.__class__ == Function:
ret = [p... | 0.561095 | 0.206514 |
from functools import partial
from itertools import product
import multiprocessing as mp
import os
from attrdict import AttrDict
import numpy as np
import torch
import torchvision.transforms as transforms
from PIL import Image
import pandas as pd
from torch.utils.data import Dataset, DataLoader
import joblib
from skim... | src/loaders.py | from functools import partial
from itertools import product
import multiprocessing as mp
import os
from attrdict import AttrDict
import numpy as np
import torch
import torchvision.transforms as transforms
from PIL import Image
import pandas as pd
from torch.utils.data import Dataset, DataLoader
import joblib
from skim... | 0.751922 | 0.192748 |
from functools import partial
import pygame as pg
from pong.colors import BLACK, WHITE
from pong.const import DEFAULT_ACCEPT_KEYS, FPS, HEIGHT, WIDTH
from pong.scenes.base import AbstractMenuScene
from pong.sprites.menu import MenuActionGroup, MenuCursor, MenuItem
class MainMenu(AbstractMenuScene):
def scene(se... | pong/scenes/main_menu/main_menu.py | from functools import partial
import pygame as pg
from pong.colors import BLACK, WHITE
from pong.const import DEFAULT_ACCEPT_KEYS, FPS, HEIGHT, WIDTH
from pong.scenes.base import AbstractMenuScene
from pong.sprites.menu import MenuActionGroup, MenuCursor, MenuItem
class MainMenu(AbstractMenuScene):
def scene(se... | 0.220384 | 0.068226 |
class DescriptionAttribute:
"""
Specifies a description for a property or event.
DescriptionAttribute()
DescriptionAttribute(description: str)
"""
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return DescriptionAttribute()
instance=ZZZ()
"""hardcoded/returns an instance of the cl... | release/stubs.min/System/ComponentModel/__init___parts/DescriptionAttribute.py | class DescriptionAttribute:
"""
Specifies a description for a property or event.
DescriptionAttribute()
DescriptionAttribute(description: str)
"""
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return DescriptionAttribute()
instance=ZZZ()
"""hardcoded/returns an instance of the cl... | 0.813238 | 0.285328 |
from typing import (
Any, Dict, Union
)
from dbt.exceptions import (
doc_invalid_args,
doc_target_not_found,
)
from dbt.config.runtime import RuntimeConfig
from dbt.contracts.graph.compiled import CompileResultNode
from dbt.contracts.graph.manifest import Manifest
from dbt.contracts.graph.parsed import Par... | core/dbt/context/docs.py | from typing import (
Any, Dict, Union
)
from dbt.exceptions import (
doc_invalid_args,
doc_target_not_found,
)
from dbt.config.runtime import RuntimeConfig
from dbt.contracts.graph.compiled import CompileResultNode
from dbt.contracts.graph.manifest import Manifest
from dbt.contracts.graph.parsed import Par... | 0.812979 | 0.111048 |
import asyncio
import logging
import os
import time
import numpy as np
from plato.config import Config
from plato.processors import registry as processor_registry
from plato.utils import csv_processor
from plato.servers import fedavg
class Server(fedavg.Server):
"""Cross-silo federated learning server using fed... | plato/servers/fedavg_cs.py | import asyncio
import logging
import os
import time
import numpy as np
from plato.config import Config
from plato.processors import registry as processor_registry
from plato.utils import csv_processor
from plato.servers import fedavg
class Server(fedavg.Server):
"""Cross-silo federated learning server using fed... | 0.722918 | 0.2561 |
# no functions
# classes
class AbstractAnalysisDisplay(object, IDisposable):
"""
Superclass for all Revit Analysis Display types
Note: We're using the user facing name from Revit (Analysis Display), rather than the same name that the Revit API
uses ... | release/stubs/Revit/AnalysisDisplay.py |
# no functions
# classes
class AbstractAnalysisDisplay(object, IDisposable):
"""
Superclass for all Revit Analysis Display types
Note: We're using the user facing name from Revit (Analysis Display), rather than the same name that the Revit API
uses ... | 0.666171 | 0.383468 |
from email.utils import getaddresses
# Third Party Stuff
from django.utils import six
from .common import * # noqa F405
from .common import (
DATABASES,
INSTALLED_APPS,
{% if cookiecutter.add_django_auth_wall.lower() == 'y' %}MIDDLEWARE,{%- endif %}
REST_FRAMEWORK,
TEMPLATES,
env
)
# SITE C... | {{cookiecutter.github_repository}}/settings/production.py | from email.utils import getaddresses
# Third Party Stuff
from django.utils import six
from .common import * # noqa F405
from .common import (
DATABASES,
INSTALLED_APPS,
{% if cookiecutter.add_django_auth_wall.lower() == 'y' %}MIDDLEWARE,{%- endif %}
REST_FRAMEWORK,
TEMPLATES,
env
)
# SITE C... | 0.459076 | 0.073563 |
from mnemonic import Mnemonic
from binascii import hexlify, unhexlify
from random import choice
from typing import AnyStr, Optional
import string
import os
import unicodedata
import binascii
from .exceptions import SemanticError
from .cryptocurrencies import get_cryptocurrency
from .libs.base58 import check_decode
... | hdwallet/utils.py |
from mnemonic import Mnemonic
from binascii import hexlify, unhexlify
from random import choice
from typing import AnyStr, Optional
import string
import os
import unicodedata
import binascii
from .exceptions import SemanticError
from .cryptocurrencies import get_cryptocurrency
from .libs.base58 import check_decode
... | 0.871229 | 0.4206 |
import os
import load_data
import sentiment_analysis
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.naive_bayes import MultinomialNB
from sklearn.externals import joblib
from sklearn.model_selection import... | naive_bayes_classification.py | import os
import load_data
import sentiment_analysis
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.pipeline import Pipeline, FeatureUnion
from sklearn.naive_bayes import MultinomialNB
from sklearn.externals import joblib
from sklearn.model_selection import... | 0.605333 | 0.293379 |
from vyper.exceptions import TypeMismatch
def test_basic_in_list(get_contract_with_gas_estimation):
code = """
@external
def testin(x: int128) -> bool:
y: int128 = 1
s: int128[4] = [1, 2, 3, 4]
if (x + 1) in s:
return True
return False
"""
c = get_contract_with_gas_estimation(cod... | tests/parser/features/iteration/test_range_in.py | from vyper.exceptions import TypeMismatch
def test_basic_in_list(get_contract_with_gas_estimation):
code = """
@external
def testin(x: int128) -> bool:
y: int128 = 1
s: int128[4] = [1, 2, 3, 4]
if (x + 1) in s:
return True
return False
"""
c = get_contract_with_gas_estimation(cod... | 0.757166 | 0.723273 |
import datetime
import logging
from sqlalchemy.sql import text as sa_text
import sqlalchemy
import urllib
from sqlalchemy import create_engine
import pandas as pd
import requests
import os
import azure.functions as func
from .. import shared
def main(mytimer: func.TimerRequest) -> None:
utc_timestamp = datetime.... | dataSyncFunction/ECDC/__init__.py | import datetime
import logging
from sqlalchemy.sql import text as sa_text
import sqlalchemy
import urllib
from sqlalchemy import create_engine
import pandas as pd
import requests
import os
import azure.functions as func
from .. import shared
def main(mytimer: func.TimerRequest) -> None:
utc_timestamp = datetime.... | 0.150372 | 0.198841 |
from jaseci.element.element import element
from jaseci.utils.utils import logger
from jaseci.utils.id_list import id_list
from jaseci.jac.ir.jac_code import jac_code
from jaseci.jac.interpreter.sentinel_interp import sentinel_interp
class sentinel(element, jac_code, sentinel_interp):
"""
Sentinel class for Ja... | jaseci_core/jaseci/actor/sentinel.py | from jaseci.element.element import element
from jaseci.utils.utils import logger
from jaseci.utils.id_list import id_list
from jaseci.jac.ir.jac_code import jac_code
from jaseci.jac.interpreter.sentinel_interp import sentinel_interp
class sentinel(element, jac_code, sentinel_interp):
"""
Sentinel class for Ja... | 0.642881 | 0.180215 |
import pytest
from mock import MagicMock
from service.word_service import *
async def __default_coroutine__(value=None):
return value
def __mock_objects__():
word_service.db_layer = MagicMock()
word_service.db_layer.word.save.return_value = __default_coroutine__()
word_service.producer = MagicMock(... | test/test_word_service.py | import pytest
from mock import MagicMock
from service.word_service import *
async def __default_coroutine__(value=None):
return value
def __mock_objects__():
word_service.db_layer = MagicMock()
word_service.db_layer.word.save.return_value = __default_coroutine__()
word_service.producer = MagicMock(... | 0.582135 | 0.299643 |
from dagster import AssetKey, DagsterEventType, EventRecordsFilter, check, seven
from .utils import capture_error
def _normalize_asset_cursor_str(cursor_string):
# the cursor for assets is derived from a json serialized string of the path. Because there are
# json serialization differences between JS and Py... | python_modules/dagster-graphql/dagster_graphql/implementation/fetch_assets.py | from dagster import AssetKey, DagsterEventType, EventRecordsFilter, check, seven
from .utils import capture_error
def _normalize_asset_cursor_str(cursor_string):
# the cursor for assets is derived from a json serialized string of the path. Because there are
# json serialization differences between JS and Py... | 0.576423 | 0.271976 |
import os
import asyncio
import logging
from typing import Union
from grpc.experimental import aio as aiogrpc
import ray.new_dashboard.utils as dashboard_utils
import ray.new_dashboard.consts as dashboard_consts
from ray.ray_constants import env_bool
from ray.new_dashboard.utils import async_loop_forever, create_task
... | dashboard/modules/event/event_agent.py | import os
import asyncio
import logging
from typing import Union
from grpc.experimental import aio as aiogrpc
import ray.new_dashboard.utils as dashboard_utils
import ray.new_dashboard.consts as dashboard_consts
from ray.ray_constants import env_bool
from ray.new_dashboard.utils import async_loop_forever, create_task
... | 0.75274 | 0.076098 |
import sys
import os
import ntpath
import numpy as np
import logging
import subprocess
from PyQt5.QtWidgets import QDialog, QApplication, QTableWidgetItem, QFileDialog
from .chartWindow import *
from .imageDetailWindow import *
from .dashboardWindow import *
from .SortFilterProxyModel import *
from .fitsHeaderTab impo... | astrodom/mainWindow.py | import sys
import os
import ntpath
import numpy as np
import logging
import subprocess
from PyQt5.QtWidgets import QDialog, QApplication, QTableWidgetItem, QFileDialog
from .chartWindow import *
from .imageDetailWindow import *
from .dashboardWindow import *
from .SortFilterProxyModel import *
from .fitsHeaderTab impo... | 0.257952 | 0.037292 |
from typing import List
from collections import defaultdict
class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
"""
reduce to house rob problem
whether to pick the number or not
F[n] = max
F[n-1] if not pick n
F[n-2] + reward if pick n
... | 740 Delete and Earn.py | from typing import List
from collections import defaultdict
class Solution:
def deleteAndEarn(self, nums: List[int]) -> int:
"""
reduce to house rob problem
whether to pick the number or not
F[n] = max
F[n-1] if not pick n
F[n-2] + reward if pick n
... | 0.836788 | 0.536313 |
import datetime
from mock import Mock
import unittest
from infra.tools.antibody import compute_stats
class TestComputeStats(unittest.TestCase):
def test_ratio_calculator(self):
reg_num = [['2014-01', 1], ['2014-02', 3], ['2014-07', 5]]
reg_den = [['2014-07', 10], ['2014-02', 6], ['2014-01', 9]]
reg_ra... | infra/tools/antibody/test/compute_stats_test.py |
import datetime
from mock import Mock
import unittest
from infra.tools.antibody import compute_stats
class TestComputeStats(unittest.TestCase):
def test_ratio_calculator(self):
reg_num = [['2014-01', 1], ['2014-02', 3], ['2014-07', 5]]
reg_den = [['2014-07', 10], ['2014-02', 6], ['2014-01', 9]]
reg_ra... | 0.530236 | 0.633651 |
from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV3
from directory_constants import choices
from directory_constants.urls import domestic as domestic_urls
from directory_components import forms
from directory_forms_api_client.forms import ZendeskActionMixin
from directory_validators.url im... | euexit/forms.py | from captcha.fields import ReCaptchaField
from captcha.widgets import ReCaptchaV3
from directory_constants import choices
from directory_constants.urls import domestic as domestic_urls
from directory_components import forms
from directory_forms_api_client.forms import ZendeskActionMixin
from directory_validators.url im... | 0.614625 | 0.145844 |
import time
import numpy as np
import pandas as pd
import networkx as nx
from tqdm import tqdm
from scipy import sparse
from helpers import sampling, simple_print
from sklearn.decomposition import NMF
class BoostedFactorization:
"""
LENS-NMF boosted matrix factorization model.
"""
def __init__(self, r... | src/boosted_embedding.py | import time
import numpy as np
import pandas as pd
import networkx as nx
from tqdm import tqdm
from scipy import sparse
from helpers import sampling, simple_print
from sklearn.decomposition import NMF
class BoostedFactorization:
"""
LENS-NMF boosted matrix factorization model.
"""
def __init__(self, r... | 0.818918 | 0.535706 |
import logging
import rex.crash
import rex.exploit.cgc.type2.cgc_type2_general
from rex import Vulnerability
from rex.exploit import CannotExploit
from ..technique import Technique
import claripy
import angr
l = logging.getLogger("rex.exploit.techniques.explore_for_exploit")
l.setLevel("DEBUG")
class WriteInfo(obj... | rex/exploit/techniques/explore_for_exploit.py | import logging
import rex.crash
import rex.exploit.cgc.type2.cgc_type2_general
from rex import Vulnerability
from rex.exploit import CannotExploit
from ..technique import Technique
import claripy
import angr
l = logging.getLogger("rex.exploit.techniques.explore_for_exploit")
l.setLevel("DEBUG")
class WriteInfo(obj... | 0.333937 | 0.204501 |
from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .models import StoreUser
from .forms import StoreUserForm
from checkout.models import ShopOrder, OrderLineItem
from cart.contexts import cart_conte... | user_profiles/views.py | from django.shortcuts import render, redirect, reverse, get_object_or_404
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .models import StoreUser
from .forms import StoreUserForm
from checkout.models import ShopOrder, OrderLineItem
from cart.contexts import cart_conte... | 0.564098 | 0.060169 |
"""Testing helper for table driven code selection"""
from typing import Any
import sys
from Base import serialize
from Base import ir
from CpuA32 import opcode_tab as a32
from CpuA32 import symbolic
from CodeGenA32 import isel_tab
from CodeGenA32 import regs
def OpToStr(op: Any) -> str:
if isinstance(op, (ise... | CodeGenA32/isel_tester.py | """Testing helper for table driven code selection"""
from typing import Any
import sys
from Base import serialize
from Base import ir
from CpuA32 import opcode_tab as a32
from CpuA32 import symbolic
from CodeGenA32 import isel_tab
from CodeGenA32 import regs
def OpToStr(op: Any) -> str:
if isinstance(op, (ise... | 0.58522 | 0.38743 |
u"""PyTest for :mod:`sirepo.template.srw_importer`
:copyright: Copyright (c) 2016 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
import pytest
from sirepo import srunit
@srunit.wrap_in_request(want_co... | tests/template/srw_import_test.py | u"""PyTest for :mod:`sirepo.template.srw_importer`
:copyright: Copyright (c) 2016 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
import pytest
from sirepo import srunit
@srunit.wrap_in_request(want_co... | 0.656438 | 0.332798 |
import torch
import logging
import math
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
from ..builder import BACKBONES
from mmcv.runner import load_checkpoint
from mmcv.cnn import (constant_init, kaiming_init)
__all__ = ['Res2NeXt29']
class ResNeXtBottleneck(nn.Module):
expansion = ... | mmcls/models/backbones/res2next_cifar.py | import torch
import logging
import math
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
from ..builder import BACKBONES
from mmcv.runner import load_checkpoint
from mmcv.cnn import (constant_init, kaiming_init)
__all__ = ['Res2NeXt29']
class ResNeXtBottleneck(nn.Module):
expansion = ... | 0.935069 | 0.490663 |
from setuptools import setup, Extension
import sys
import numpy as np
from Cython.Build import cythonize
from smt import __version__
CLASSIFIERS = """\
Development Status :: 5 - Production/Stable
Intended Audience :: Science/Research
Intended Audience :: Developers
License :: OSI Approved :: BSD License
Programming L... | setup.py | from setuptools import setup, Extension
import sys
import numpy as np
from Cython.Build import cythonize
from smt import __version__
CLASSIFIERS = """\
Development Status :: 5 - Production/Stable
Intended Audience :: Science/Research
Intended Audience :: Developers
License :: OSI Approved :: BSD License
Programming L... | 0.420124 | 0.273523 |
from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtWidgets import QTextEdit, QApplication, QAction
class DarkNotepadTextEdit(QTextEdit):
fileDropped = pyqtSignal(str)
zoomSignal = pyqtSignal(int)
cursorOnTop = pyqtSignal()
showInExplorer = pyqtSignal()
def __init__(self):
super().__init... | pyqt_dark_notepad/darkNotepadTextEdit.py | from PyQt5.QtCore import pyqtSignal, Qt
from PyQt5.QtWidgets import QTextEdit, QApplication, QAction
class DarkNotepadTextEdit(QTextEdit):
fileDropped = pyqtSignal(str)
zoomSignal = pyqtSignal(int)
cursorOnTop = pyqtSignal()
showInExplorer = pyqtSignal()
def __init__(self):
super().__init... | 0.496582 | 0.115886 |
import subprocess
import sys
from functools import lru_cache
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import Any, Dict, Tuple
import jsonschema
import requests
import yaml
from kubernetes.client.api_client import ApiClient
api_client = ApiClient()
BASE_URL_SPEC = "https://raw.git... | tests/chart_tests/helm_template_generator.py |
import subprocess
import sys
from functools import lru_cache
from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import Any, Dict, Tuple
import jsonschema
import requests
import yaml
from kubernetes.client.api_client import ApiClient
api_client = ApiClient()
BASE_URL_SPEC = "https://raw.git... | 0.533641 | 0.094552 |
import asyncio
from pprint import pprint
from asyncdb import AsyncDB
from asyncdb.exceptions import default_exception_handler
async def connect(db):
async with await db.connection() as conn:
pprint(await conn.test_connection())
await conn.execute("create table tests(id integer, name text)")
... | probe/test_aiosqlite.py | import asyncio
from pprint import pprint
from asyncdb import AsyncDB
from asyncdb.exceptions import default_exception_handler
async def connect(db):
async with await db.connection() as conn:
pprint(await conn.test_connection())
await conn.execute("create table tests(id integer, name text)")
... | 0.305386 | 0.215413 |
import xlrd, sys, os
from docx import Document
from docx.shared import Inches
def splitdatafromxls():
print('Opening file..')
# Give the location of the xls file
cur_path = os.path.dirname(__file__)
rel_path = os.path.relpath('datasource/PMI-network-data.xlsx')
#loc = ("/Users/andre/Google Driv... | modules/split_data_from_xls.py | import xlrd, sys, os
from docx import Document
from docx.shared import Inches
def splitdatafromxls():
print('Opening file..')
# Give the location of the xls file
cur_path = os.path.dirname(__file__)
rel_path = os.path.relpath('datasource/PMI-network-data.xlsx')
#loc = ("/Users/andre/Google Driv... | 0.099733 | 0.372676 |
from __future__ import unicode_literals
from django.db import migrations
_OLD_MODEL = """
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
class Meta(AbstractUser.Meta):
swappa... | spirit/user/migrations/0007_auto_20161114_1536.py | from __future__ import unicode_literals
from django.db import migrations
_OLD_MODEL = """
from __future__ import unicode_literals
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
class Meta(AbstractUser.Meta):
swappa... | 0.613815 | 0.07703 |
from django.contrib.gis.geos import Polygon
from django.contrib.gis.gdal import SpatialReference, CoordTransform, DataSource
from eoxserver.contrib import gdal
from eoxserver.backends.access import get_vsi_path, get_vsi_env, gdal_open
from eoxserver.render.coverage.objects import Coverage
BROWSE_MODE_RGB = "rgb"
BR... | eoxserver/render/browse/objects.py |
from django.contrib.gis.geos import Polygon
from django.contrib.gis.gdal import SpatialReference, CoordTransform, DataSource
from eoxserver.contrib import gdal
from eoxserver.backends.access import get_vsi_path, get_vsi_env, gdal_open
from eoxserver.render.coverage.objects import Coverage
BROWSE_MODE_RGB = "rgb"
BR... | 0.810366 | 0.207877 |
import random
import numpy as np
import scipy.integrate as integrate
from collections import defaultdict
from hashFunction import hash_sha1
# this code is modified from
# https://github.com/ekzhu/datasketch/blob/master/datasketch/lsh.py
# Mersenne prime
MERSENNE_PRIME = (1 << 31) - 1
MAX_PERMU = (1 << 31)
MAX_HASH = ... | model-inference/deduplication/indexing/lsh/minHashLSH.py | import random
import numpy as np
import scipy.integrate as integrate
from collections import defaultdict
from hashFunction import hash_sha1
# this code is modified from
# https://github.com/ekzhu/datasketch/blob/master/datasketch/lsh.py
# Mersenne prime
MERSENNE_PRIME = (1 << 31) - 1
MAX_PERMU = (1 << 31)
MAX_HASH = ... | 0.857723 | 0.676834 |
from azureml.core import Run
import pandas as pd
import numpy as np
import os
import argparse
import datetime
import joblib
from sklearn.metrics import mean_squared_error, mean_absolute_error
from sklearn.linear_model import LinearRegression
from timeseries_utilities import ColumnDropper, SimpleLagger, SimpleCalenda... | Custom_Script/scripts/train.py |
from azureml.core import Run
import pandas as pd
import numpy as np
import os
import argparse
import datetime
import joblib
from sklearn.metrics import mean_squared_error, mean_absolute_error
from sklearn.linear_model import LinearRegression
from timeseries_utilities import ColumnDropper, SimpleLagger, SimpleCalenda... | 0.680454 | 0.31455 |
import secrets
import requests
from requests_oauthlib import OAuth1
class Pylogy:
def __init__(self,api_key,secret):
self.api_key = api_key
self.secret = secret
# REST Methods
def _get(self,uri):
headeroauth = OAuth1(self.api_key,self.secret,signature_method='PLAINTEXT')
re... | Pylogy.py | import secrets
import requests
from requests_oauthlib import OAuth1
class Pylogy:
def __init__(self,api_key,secret):
self.api_key = api_key
self.secret = secret
# REST Methods
def _get(self,uri):
headeroauth = OAuth1(self.api_key,self.secret,signature_method='PLAINTEXT')
re... | 0.338733 | 0.068631 |
from .parseable_str import parse_b58_double_sha256, parse_bech32, parse_colon_prefix, parseable_str
from pycoin.contrib import segwit_addr
from pycoin.encoding.bytes32 import from_bytes_32
from pycoin.intbytes import int2byte
from pycoin.encoding.hexbytes import b2h, h2b
from .Contract import Contract
def hparse(ap... | pycoin/networks/ParseAPI.py | from .parseable_str import parse_b58_double_sha256, parse_bech32, parse_colon_prefix, parseable_str
from pycoin.contrib import segwit_addr
from pycoin.encoding.bytes32 import from_bytes_32
from pycoin.intbytes import int2byte
from pycoin.encoding.hexbytes import b2h, h2b
from .Contract import Contract
def hparse(ap... | 0.730097 | 0.284539 |
from collections import defaultdict
from typing import Any, Dict, List, Optional, Sequence, Iterable, Tuple, TypeVar, Union
import numpy as np
import tensorflow as tf
import torch
from fastestimator.backend.concat import concat
from fastestimator.backend.reduce_max import reduce_max
from fastestimator.backend.reduce_... | fastestimator/trace/xai/saliency.py | from collections import defaultdict
from typing import Any, Dict, List, Optional, Sequence, Iterable, Tuple, TypeVar, Union
import numpy as np
import tensorflow as tf
import torch
from fastestimator.backend.concat import concat
from fastestimator.backend.reduce_max import reduce_max
from fastestimator.backend.reduce_... | 0.898062 | 0.496704 |
from experiment.train_single_model import Experiment
from sample.sample_model import get_model
from sample.sample_dataset import load_dataset
import torch
from algorithms.bayesian_optimization import Bayesian
from algorithms.grid_search_algorithm import GridSearch
from algorithms.evolutionary_optimization import Evolut... | sample/run_sample.py | from experiment.train_single_model import Experiment
from sample.sample_model import get_model
from sample.sample_dataset import load_dataset
import torch
from algorithms.bayesian_optimization import Bayesian
from algorithms.grid_search_algorithm import GridSearch
from algorithms.evolutionary_optimization import Evolut... | 0.811003 | 0.403684 |
from getratings.models.ratings import Ratings
class NA_Velkoz_Mid_Aatrox(Ratings):
pass
class NA_Velkoz_Mid_Ahri(Ratings):
pass
class NA_Velkoz_Mid_Akali(Ratings):
pass
class NA_Velkoz_Mid_Alistar(Ratings):
pass
class NA_Velkoz_Mid_Amumu(Ratings):
pass
class NA_Velkoz_Mid_Anivia(Ratings):
... | loldib/getratings/models/NA/na_velkoz/na_velkoz_mid.py | from getratings.models.ratings import Ratings
class NA_Velkoz_Mid_Aatrox(Ratings):
pass
class NA_Velkoz_Mid_Ahri(Ratings):
pass
class NA_Velkoz_Mid_Akali(Ratings):
pass
class NA_Velkoz_Mid_Alistar(Ratings):
pass
class NA_Velkoz_Mid_Amumu(Ratings):
pass
class NA_Velkoz_Mid_Anivia(Ratings):
... | 0.18769 | 0.082512 |
from direct.interval.IntervalGlobal import Sequence, Parallel, Func, Wait, ActorInterval
from ..floor import FloorBase
class Floor(FloorBase):
model_path = 'floors/bells/scene.bam'
walkable_path = 'floors/bells/walkable.png'
music_path = 'floors/bells/music.ogg'
sound_path = 'floors/bells/sfx/'
s... | game/floors/bells.py | from direct.interval.IntervalGlobal import Sequence, Parallel, Func, Wait, ActorInterval
from ..floor import FloorBase
class Floor(FloorBase):
model_path = 'floors/bells/scene.bam'
walkable_path = 'floors/bells/walkable.png'
music_path = 'floors/bells/music.ogg'
sound_path = 'floors/bells/sfx/'
s... | 0.547948 | 0.145176 |
from .codec import CTCCodec
from shared_code import preprocessor as prep
from tensorflow import make_tensor_proto, make_ndarray
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2_grpc
from time import time
import azure.functions as func
import grpc
import json
imp... | handwritten/__init__.py | from .codec import CTCCodec
from shared_code import preprocessor as prep
from tensorflow import make_tensor_proto, make_ndarray
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2_grpc
from time import time
import azure.functions as func
import grpc
import json
imp... | 0.32146 | 0.095265 |
import os
import sys
import setuptools
from setuptools import Extension
from setuptools.command.build_py import build_py as _build_py
import distutils.dir_util
import distutils.log
class build_py(_build_py):
def run(self):
self.run_command("build_ext")
return super().run()
kaldi_root = os.getenv('... | python/setup.py | import os
import sys
import setuptools
from setuptools import Extension
from setuptools.command.build_py import build_py as _build_py
import distutils.dir_util
import distutils.log
class build_py(_build_py):
def run(self):
self.run_command("build_ext")
return super().run()
kaldi_root = os.getenv('... | 0.179387 | 0.061593 |
import math
import re
from projection import Projection
def get_world_size(minlat, minlon, maxlat, maxlon):
"""Return the world size in X-Z coordinates."""
x1, z1 = Projection.project(minlon, minlat)
x2, z2 = Projection.project(maxlon, maxlat)
xSize = math.fabs(x2 - x1)
zSize = math.fabs(z2 - z1)
... | resources/osm_importer/utils/misc_utils.py | import math
import re
from projection import Projection
def get_world_size(minlat, minlon, maxlat, maxlon):
"""Return the world size in X-Z coordinates."""
x1, z1 = Projection.project(minlon, minlat)
x2, z2 = Projection.project(maxlon, maxlat)
xSize = math.fabs(x2 - x1)
zSize = math.fabs(z2 - z1)
... | 0.647352 | 0.402245 |
from copy import deepcopy
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.test.testcases import TestCase
from djstripe.models import Invoice, Refund
from . import (
FAKE_BALANCE_TRANSACTION,
FAKE_BALANCE_TRANSACTION_REFUND,
FAKE_CARD_AS_PAYMENT_METHOD,
FAKE_... | tests/test_refund.py | from copy import deepcopy
from unittest.mock import patch
from django.contrib.auth import get_user_model
from django.test.testcases import TestCase
from djstripe.models import Invoice, Refund
from . import (
FAKE_BALANCE_TRANSACTION,
FAKE_BALANCE_TRANSACTION_REFUND,
FAKE_CARD_AS_PAYMENT_METHOD,
FAKE_... | 0.372619 | 0.231853 |
import os
import pytest
from dvc.fs.repo import RepoFileSystem
from tests.unit.fs.test_repo import make_subrepo
@pytest.fixture
def repo_fs(tmp_dir, dvc, scm):
fs_structure = {
"models": { # mixed dvc + git directory
"train.py": "train dot py",
"test.py": "test dot py",
... | tests/unit/fs/test_repo_info.py | import os
import pytest
from dvc.fs.repo import RepoFileSystem
from tests.unit.fs.test_repo import make_subrepo
@pytest.fixture
def repo_fs(tmp_dir, dvc, scm):
fs_structure = {
"models": { # mixed dvc + git directory
"train.py": "train dot py",
"test.py": "test dot py",
... | 0.436862 | 0.392919 |
import csv
import os
import shutil
import time
import json
import requests
class ExportDatabaseFormsResult:
"""Class to store data exported from ActivityInfo"""
def __init__(self, header, records, job_id, database_id, resource_id=None):
self.jobId = job_id
self.databaseId = database_id,
... | internos/activityinfo/exports.py | import csv
import os
import shutil
import time
import json
import requests
class ExportDatabaseFormsResult:
"""Class to store data exported from ActivityInfo"""
def __init__(self, header, records, job_id, database_id, resource_id=None):
self.jobId = job_id
self.databaseId = database_id,
... | 0.637257 | 0.128143 |