code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from __future__ import absolute_import, division, print_function
import numpy as np
from .weno5m import WENO5M
class HenrickApproximator:
"""
Approximator for spatial derivatives by Henrick et al. [1]_ with WENO5JS.
Algorithm by Henrick et al. [1]_ is used to approximate spatial derivatives
for gov... | saf/nonlinear/henrickapproximator.py | from __future__ import absolute_import, division, print_function
import numpy as np
from .weno5m import WENO5M
class HenrickApproximator:
"""
Approximator for spatial derivatives by Henrick et al. [1]_ with WENO5JS.
Algorithm by Henrick et al. [1]_ is used to approximate spatial derivatives
for gov... | 0.942248 | 0.75775 |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from absl.testing import absltest
import mock
from grr_response_core.lib import flags
from grr_response_core.lib import parser
from grr_response_core.lib import parsers
from grr_response_core.lib.parsers imp... | grr/test_lib/parser_test_lib_test.py | from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from absl.testing import absltest
import mock
from grr_response_core.lib import flags
from grr_response_core.lib import parser
from grr_response_core.lib import parsers
from grr_response_core.lib.parsers imp... | 0.468304 | 0.320024 |
"""Loads dataset for the tagging (e.g., NER/POS) task."""
from typing import Mapping, Optional
import dataclasses
import tensorflow as tf
from official.core import input_reader
from official.modeling.hyperparams import config_definitions as cfg
from official.nlp.data import data_loader_factory
@dataclasses.dataclas... | official/nlp/data/tagging_data_loader.py | """Loads dataset for the tagging (e.g., NER/POS) task."""
from typing import Mapping, Optional
import dataclasses
import tensorflow as tf
from official.core import input_reader
from official.modeling.hyperparams import config_definitions as cfg
from official.nlp.data import data_loader_factory
@dataclasses.dataclas... | 0.924705 | 0.361108 |
import pandas as pd
import sys
from os.path import basename
from ner_measurement import NerMeasurement as NM
def measure(str_true, str_pred):
l_true = [ e.strip() for e in str_true.split(',') ]
l_pred = [ e.strip() for e in str_pred.split(',') ]
nm = NM(l_true, l_pred)
jc_sm = nm.jaccard_simmilarity()
... | ner/ner_eval.py | import pandas as pd
import sys
from os.path import basename
from ner_measurement import NerMeasurement as NM
def measure(str_true, str_pred):
l_true = [ e.strip() for e in str_true.split(',') ]
l_pred = [ e.strip() for e in str_pred.split(',') ]
nm = NM(l_true, l_pred)
jc_sm = nm.jaccard_simmilarity()
... | 0.153962 | 0.197987 |
# Python imports
import logging
# Third party imports
from google.api_core.exceptions import BadRequest
import pandas as pd
from jinja2 import Template
# Project imports
from utils import bq
import common
from retraction import retract_utils as ru
from constants.retraction import retract_utils as ru_consts
from cons... | data_steward/retraction/participant_row_counts.py |
# Python imports
import logging
# Third party imports
from google.api_core.exceptions import BadRequest
import pandas as pd
from jinja2 import Template
# Project imports
from utils import bq
import common
from retraction import retract_utils as ru
from constants.retraction import retract_utils as ru_consts
from cons... | 0.408513 | 0.350838 |
"""Utility functions or classes shared between BERT benchmarks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
# pylint: disable=g-bad-import-order
import numpy as np
from absl import flags
from absl.testing import flagsaver
impor... | official/benchmark/bert_benchmark_utils.py | """Utility functions or classes shared between BERT benchmarks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time
# pylint: disable=g-bad-import-order
import numpy as np
from absl import flags
from absl.testing import flagsaver
impor... | 0.878679 | 0.315868 |
import numpy as np
from textattack.attack_results import FailedAttackResult, SkippedAttackResult
from . import CSVLogger, FileLogger, VisdomLogger, WeightsAndBiasesLogger
class AttackLogManager:
"""Logs the results of an attack to all attached loggers."""
def __init__(self):
self.loggers = []
... | textattack/loggers/attack_log_manager.py | import numpy as np
from textattack.attack_results import FailedAttackResult, SkippedAttackResult
from . import CSVLogger, FileLogger, VisdomLogger, WeightsAndBiasesLogger
class AttackLogManager:
"""Logs the results of an attack to all attached loggers."""
def __init__(self):
self.loggers = []
... | 0.519765 | 0.218941 |
from xml.dom import minidom
from plant import CraneMoveTime
class Recipe(object):
"""
This class provides a Recipe for an Order. It is a list (or dictionary) of
tuples (str machineName, int timeAtMachine).
"""
def __init__(self):
"""
recipe is a list (or dictionary) that contains the tuples of time
inform... | Projects/PlantMaker/archive/20100517/src/order.py | from xml.dom import minidom
from plant import CraneMoveTime
class Recipe(object):
"""
This class provides a Recipe for an Order. It is a list (or dictionary) of
tuples (str machineName, int timeAtMachine).
"""
def __init__(self):
"""
recipe is a list (or dictionary) that contains the tuples of time
inform... | 0.524395 | 0.540924 |
import xarray as xr
import requests
from pydap.client import open_url
from pydap.cas.urs import setup_session
def get_era5_pressure(username, password, date, var, session):
vrb = {'pv':'060',
'crwc':'075',
'u':'131',
'v':'132',
'z':'129',
'cswc':'076',
'q':'133',
'... | visjobs/datas/get_ERA5.py |
import xarray as xr
import requests
from pydap.client import open_url
from pydap.cas.urs import setup_session
def get_era5_pressure(username, password, date, var, session):
vrb = {'pv':'060',
'crwc':'075',
'u':'131',
'v':'132',
'z':'129',
'cswc':'076',
'q':'133',
'... | 0.374791 | 0.236301 |
"""This file sets up all the urls for monorail pages."""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import logging
import webapp2
import settings
from components import prpc
from features import autolink
from features import dateaction
from features ... | appengine/monorail/registerpages.py |
"""This file sets up all the urls for monorail pages."""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import logging
import webapp2
import settings
from components import prpc
from features import autolink
from features import dateaction
from features ... | 0.54359 | 0.106319 |
from pathlib import Path
from typing import Optional, TextIO
from Pegasus import yaml
from Pegasus.vendor import attr
__all__ = (
"load",
"loads",
"dump",
"dumps",
"Braindump",
)
@attr.s(slots=True, kw_only=True)
class Braindump:
"""
Data class representing Braindump file.
.. todo::... | packages/pegasus-common/src/Pegasus/braindump.py | from pathlib import Path
from typing import Optional, TextIO
from Pegasus import yaml
from Pegasus.vendor import attr
__all__ = (
"load",
"loads",
"dump",
"dumps",
"Braindump",
)
@attr.s(slots=True, kw_only=True)
class Braindump:
"""
Data class representing Braindump file.
.. todo::... | 0.858763 | 0.161188 |
from undulate.bricks.generic import Drawable, Brick, BrickFactory, Point, SplineSegment
class FieldStart(Brick):
"""
[
"""
def __init__(self, **kwargs):
Brick.__init__(self, **kwargs)
position = int(kwargs.get("position", 0))
data = kwargs.get("data", "")
attributes = ... | undulate/bricks/register.py | from undulate.bricks.generic import Drawable, Brick, BrickFactory, Point, SplineSegment
class FieldStart(Brick):
"""
[
"""
def __init__(self, **kwargs):
Brick.__init__(self, **kwargs)
position = int(kwargs.get("position", 0))
data = kwargs.get("data", "")
attributes = ... | 0.631708 | 0.253913 |
import requests
import sys
import json
filePath = './loading/cologne.json'
def loadData(id):
"Loads parking lot data for the city Cologne"
response = requests.get("http://www.stadt-koeln.de/externe-dienste/open-data/parking-ts.php")
with open(filePath, 'wb') as f:
f.write(response.content)
with open(filePath, '... | Cologne.py | import requests
import sys
import json
filePath = './loading/cologne.json'
def loadData(id):
"Loads parking lot data for the city Cologne"
response = requests.get("http://www.stadt-koeln.de/externe-dienste/open-data/parking-ts.php")
with open(filePath, 'wb') as f:
f.write(response.content)
with open(filePath, '... | 0.195671 | 0.176903 |
from encodings import utf_8
from time import sleep
import paho.mqtt.client as mqtt
def connect(client_name = "laptop",host_name = "10.254.223.22"):
client =mqtt.Client(client_name)
client.connect(host_name)
return client
def send(client, data, topic):
client.publish(topic, data)
def receive(client... | Vision/communicate.py | from encodings import utf_8
from time import sleep
import paho.mqtt.client as mqtt
def connect(client_name = "laptop",host_name = "10.254.223.22"):
client =mqtt.Client(client_name)
client.connect(host_name)
return client
def send(client, data, topic):
client.publish(topic, data)
def receive(client... | 0.283385 | 0.113653 |
import os
import os.path
import sys
import h5py
import numpy as np
from numpy.lib.function_base import hamming
import ASCAD_test_models
import tensorflow as tf
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.layers import Flatten, Dense, Dropout, Input, Conv1D, MaxPooling1D, GlobalAverageP... | ASCAD_train_models.py | import os
import os.path
import sys
import h5py
import numpy as np
from numpy.lib.function_base import hamming
import ASCAD_test_models
import tensorflow as tf
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.layers import Flatten, Dense, Dropout, Input, Conv1D, MaxPooling1D, GlobalAverageP... | 0.708414 | 0.323006 |
import itertools
import logging
import math
from datetime import datetime, timedelta, timezone
import boto3
import numpy as np
import pandas as pd
import pyarrow as pa
import pytest
import awswrangler as wr
from ._utils import ensure_data_types, get_df_list
logging.getLogger("awswrangler").setLevel(logging.DEBUG)
... | tests/test_s3_parquet.py | import itertools
import logging
import math
from datetime import datetime, timedelta, timezone
import boto3
import numpy as np
import pandas as pd
import pyarrow as pa
import pytest
import awswrangler as wr
from ._utils import ensure_data_types, get_df_list
logging.getLogger("awswrangler").setLevel(logging.DEBUG)
... | 0.467818 | 0.490541 |
import json
import logging
import math
import os
import sys
from typing import List, Dict, Set, Tuple, Optional, Any, TypeVar, Callable
import target_spec
from test_results import (TargetResult, ReadTargetFromJson, TestResult,
ResultLine)
class LineStats(object):
def __init__(self, desc:... | tools/fuchsia/comparative_tester/generate_perf_report.py | import json
import logging
import math
import os
import sys
from typing import List, Dict, Set, Tuple, Optional, Any, TypeVar, Callable
import target_spec
from test_results import (TargetResult, ReadTargetFromJson, TestResult,
ResultLine)
class LineStats(object):
def __init__(self, desc:... | 0.835651 | 0.52074 |
import struct
from .symbol import BindingSymbol
from ...errors import CLEInvalidBinaryError
from ...address_translator import AT
import logging
l = logging.getLogger(name=__name__)
OPCODE_MASK = 0xF0
IMM_MASK = 0x0F
BIND_TYPE_POINTER = 1
BIND_TYPE_TEXT_ABSOLUTE32 = 2
BIND_TYPE_TEXT_PCREL32 = 3
BIND_OPCODE_DONE = 0... | cle/backends/macho/binding.py |
import struct
from .symbol import BindingSymbol
from ...errors import CLEInvalidBinaryError
from ...address_translator import AT
import logging
l = logging.getLogger(name=__name__)
OPCODE_MASK = 0xF0
IMM_MASK = 0x0F
BIND_TYPE_POINTER = 1
BIND_TYPE_TEXT_ABSOLUTE32 = 2
BIND_TYPE_TEXT_PCREL32 = 3
BIND_OPCODE_DONE = 0... | 0.413951 | 0.177063 |
from sympy.physics.quantum.circuitplot import labeller, render_label, Mz, CreateOneQubitGate,\
CreateCGate
from sympy.physics.quantum.gate import CNOT, H, SWAP, CGate, S, T
from sympy.external import import_module
from sympy.utilities.pytest import skip
mpl = import_module('matplotlib')
def test_render_label():
... | sympy/physics/quantum/tests/test_circuitplot.py | from sympy.physics.quantum.circuitplot import labeller, render_label, Mz, CreateOneQubitGate,\
CreateCGate
from sympy.physics.quantum.gate import CNOT, H, SWAP, CGate, S, T
from sympy.external import import_module
from sympy.utilities.pytest import skip
mpl = import_module('matplotlib')
def test_render_label():
... | 0.745306 | 0.81946 |
import os
import sqlite3
from collections import defaultdict
from getpass import getpass
from datetime import datetime
from pprint import pprint
import time
import calendar
header = """<!DOCTYPE NETSCAPE-Bookmark-file-1>
<!--This is an automatically generated file.
It will be read and overwritten.
Do Not... | d2f.py |
import os
import sqlite3
from collections import defaultdict
from getpass import getpass
from datetime import datetime
from pprint import pprint
import time
import calendar
header = """<!DOCTYPE NETSCAPE-Bookmark-file-1>
<!--This is an automatically generated file.
It will be read and overwritten.
Do Not... | 0.213541 | 0.075619 |
from mcalf.tests.helpers import class_map as c
t = 3 # Three images
x = 50 # 50 coordinates along x-axis
y = 20 # 20 coordinates along y-axis
n = 5 # Possible classifications [0, 1, 2, 3, 4]
class_map = c(t, x, y, n) # 3D array of classifications (t, y, x)
#%%
# Next, we shall import :func:`mcalf.visualisation... | examples/gallery/visualisation/plot_plot_class_map.py |
from mcalf.tests.helpers import class_map as c
t = 3 # Three images
x = 50 # 50 coordinates along x-axis
y = 20 # 20 coordinates along y-axis
n = 5 # Possible classifications [0, 1, 2, 3, 4]
class_map = c(t, x, y, n) # 3D array of classifications (t, y, x)
#%%
# Next, we shall import :func:`mcalf.visualisation... | 0.887485 | 0.739587 |
import sys
import torch.cuda
import os
from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension
from torch.utils.cpp_extension import CUDA_HOME, ROCM_HOME
from torch.testing._internal.common_utils import IS_WINDOWS
if sys.platform == 'win32':
vc_version = os.ge... | test/cpp_extensions/setup.py | import sys
import torch.cuda
import os
from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CppExtension, CUDAExtension
from torch.utils.cpp_extension import CUDA_HOME, ROCM_HOME
from torch.testing._internal.common_utils import IS_WINDOWS
if sys.platform == 'win32':
vc_version = os.ge... | 0.215186 | 0.087252 |
import numpy as np
import torch
from torch import nn as nn
from torch.autograd import grad
import nnpackage
from nnpackage import nn as L, Properties
__all__ = [
"Atomwise",
"ElementalAtomwise",
"DipoleMoment",
"ElementalDipoleMoment",
"Polarizability",
"ElectronicSpatialExtent",
]
class Ato... | src/nnpackage/atomistic/output_modules.py | import numpy as np
import torch
from torch import nn as nn
from torch.autograd import grad
import nnpackage
from nnpackage import nn as L, Properties
__all__ = [
"Atomwise",
"ElementalAtomwise",
"DipoleMoment",
"ElementalDipoleMoment",
"Polarizability",
"ElectronicSpatialExtent",
]
class Ato... | 0.950767 | 0.587943 |
import datetime
import argparse
from copy import deepcopy
from botocore.exceptions import ClientError
# Main is the first function that is called when this module is executed
def main(args, awsattack_main):
session = awsattack_main.get_active_session()
print = awsattack_main.print
get_regions = awsattac... | ttp/src/vpc_enum_vpn_src.py | import datetime
import argparse
from copy import deepcopy
from botocore.exceptions import ClientError
# Main is the first function that is called when this module is executed
def main(args, awsattack_main):
session = awsattack_main.get_active_session()
print = awsattack_main.print
get_regions = awsattac... | 0.192084 | 0.101723 |
import asyncio
import logging
import math
import traceback
from typing import List, Set
from datetime import datetime
import tldextract
from services import discord_user_service
import sql_item_persistence
from conversions.message_formatters import chunk_messages
from conversions.size_formatters import get_size_requi... | stock_check_result_reporter.py | import asyncio
import logging
import math
import traceback
from typing import List, Set
from datetime import datetime
import tldextract
from services import discord_user_service
import sql_item_persistence
from conversions.message_formatters import chunk_messages
from conversions.size_formatters import get_size_requi... | 0.388386 | 0.090173 |
import numpy as np
import loupe
def asarray(a):
"""Convert the input to an array.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This
includes lists, lists of tuples, tuples, tuples of tuples,
tuples of lists and ndarrays.... | loupe/util.py | import numpy as np
import loupe
def asarray(a):
"""Convert the input to an array.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This
includes lists, lists of tuples, tuples, tuples of tuples,
tuples of lists and ndarrays.... | 0.924891 | 0.723163 |
import typing
from attr import attrs
import pytest
class DatumaroComponent:
Datumaro = "datumaro"
class Requirements:
# Exact requirements
DATUM_GENERAL_REQ = "Datumaro general requirement"
DATUM_TELEMETRY = "Datumaro telemetry requirement"
# GitHub issues (not bugs)
# https://github.com/... | tests/requirements.py |
import typing
from attr import attrs
import pytest
class DatumaroComponent:
Datumaro = "datumaro"
class Requirements:
# Exact requirements
DATUM_GENERAL_REQ = "Datumaro general requirement"
DATUM_TELEMETRY = "Datumaro telemetry requirement"
# GitHub issues (not bugs)
# https://github.com/... | 0.531209 | 0.296368 |
# 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
# dis... | ironic/tests/unit/drivers/modules/ucs/test_helper.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
# dis... | 0.702428 | 0.266509 |
"""Test class for iBMC Management interface."""
import itertools
from unittest import mock
from oslo_utils import importutils
from ironic.common import boot_devices
from ironic.common import boot_modes
from ironic.common import exception
from ironic.conductor import task_manager
from ironic.drivers.modules.ibmc impo... | ironic/tests/unit/drivers/modules/ibmc/test_management.py | """Test class for iBMC Management interface."""
import itertools
from unittest import mock
from oslo_utils import importutils
from ironic.common import boot_devices
from ironic.common import boot_modes
from ironic.common import exception
from ironic.conductor import task_manager
from ironic.drivers.modules.ibmc impo... | 0.710025 | 0.196325 |
import json
import phantom.app as phantom
import requests
from bs4 import UnicodeDammit
from phantom.action_result import ActionResult
from phantom.base_connector import BaseConnector
# Usage of the consts file is recommended
from dossier_consts import *
class RetVal(tuple):
def __new__(cls, val1, val2=None):
... | dossier_connector.py |
import json
import phantom.app as phantom
import requests
from bs4 import UnicodeDammit
from phantom.action_result import ActionResult
from phantom.base_connector import BaseConnector
# Usage of the consts file is recommended
from dossier_consts import *
class RetVal(tuple):
def __new__(cls, val1, val2=None):
... | 0.524151 | 0.120594 |
import html
from itertools import groupby
from operator import itemgetter
from typing import TypeVar, Iterable, Generic, Tuple, Any, Optional
import matplotlib.colors
from qtpy.QtCore import QMutex, QMutexLocker
from qtpy.QtWidgets import QErrorMessage, QWidget
from corrscope.config import CorrError
def color2hex(c... | corrscope/gui/util.py | import html
from itertools import groupby
from operator import itemgetter
from typing import TypeVar, Iterable, Generic, Tuple, Any, Optional
import matplotlib.colors
from qtpy.QtCore import QMutex, QMutexLocker
from qtpy.QtWidgets import QErrorMessage, QWidget
from corrscope.config import CorrError
def color2hex(c... | 0.881162 | 0.241154 |
import boto3
from botocore.exceptions import ClientError
import json
import os
import time
import datetime
from dateutil import tz
from lib.account import *
from lib.common import *
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logging.getLogger('botocore').setLevel(logging.WARNING)
loggi... | aws-inventory/lambda/inventory-iam-analyzer.py | import boto3
from botocore.exceptions import ClientError
import json
import os
import time
import datetime
from dateutil import tz
from lib.account import *
from lib.common import *
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
logging.getLogger('botocore').setLevel(logging.WARNING)
loggi... | 0.213787 | 0.064036 |
import numpy as np
import h5py
import re
import sys
import operator
import argparse
from random import sample, seed
from math import ceil
from nltk.corpus import stopwords
from nltk.stem.wordnet import WordNetLemmatizer
from prep_hdf5 import line_to_words
def equal_length_chunks(l1, l2, l3, l4, l5):
"""
Spli... | aspect-extraction/scripts/prep_hdf5_test.py |
import numpy as np
import h5py
import re
import sys
import operator
import argparse
from random import sample, seed
from math import ceil
from nltk.corpus import stopwords
from nltk.stem.wordnet import WordNetLemmatizer
from prep_hdf5 import line_to_words
def equal_length_chunks(l1, l2, l3, l4, l5):
"""
Spli... | 0.236428 | 0.246499 |
from django.test import TestCase
from django.contrib.auth.models import User
from django.http import HttpRequest
from .factories import UserReferrerFactory, UserFactory, CampaignFactory
from referral_module import constants
from referral_module import models
def make_cookie_file(user_referrer):
cookie_file = '{... | referral_module/tests/test_user_registered.py | from django.test import TestCase
from django.contrib.auth.models import User
from django.http import HttpRequest
from .factories import UserReferrerFactory, UserFactory, CampaignFactory
from referral_module import constants
from referral_module import models
def make_cookie_file(user_referrer):
cookie_file = '{... | 0.64713 | 0.101145 |
from CIM15.IEC61970.Core.IdentifiedObject import IdentifiedObject
class FinancialInfo(IdentifiedObject):
"""Various current financial properties associated with a particular asset. Historical properties may be determined by ActivityRecords associated with the asset.Various current financial properties associated ... | CIM15/IEC61970/Informative/InfAssets/FinancialInfo.py |
from CIM15.IEC61970.Core.IdentifiedObject import IdentifiedObject
class FinancialInfo(IdentifiedObject):
"""Various current financial properties associated with a particular asset. Historical properties may be determined by ActivityRecords associated with the asset.Various current financial properties associated ... | 0.828627 | 0.354126 |
from __future__ import unicode_literals
from datetime import datetime
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.test import TestCase, Client
from django.urls import reverse
from django.utils.encoding import force_text
from ..models import Post, Comment
... | example/blog/tests/test_views.py | from __future__ import unicode_literals
from datetime import datetime
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.test import TestCase, Client
from django.urls import reverse
from django.utils.encoding import force_text
from ..models import Post, Comment
... | 0.603114 | 0.295649 |
import logging
from .registrations import Registrations
from ..smart_client import SmartClient
class NugetServer:
"""
Class used to access the Nuget Server API.
https://docs.microsoft.com/en-us/nuget/api/overview
"""
DEFAULT_SERVICE_INDEX_URL = "https://api.nuget.org/v3/index.json"
def ... | nuget_package_scanner/nuget/nuget_server.py | import logging
from .registrations import Registrations
from ..smart_client import SmartClient
class NugetServer:
"""
Class used to access the Nuget Server API.
https://docs.microsoft.com/en-us/nuget/api/overview
"""
DEFAULT_SERVICE_INDEX_URL = "https://api.nuget.org/v3/index.json"
def ... | 0.591841 | 0.174815 |
import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt
from types import SimpleNamespace
# Function to find steady state (ss) value for capital (k) of the basic Solow model using scipy.optimize
def ss_bas(n, s, B, alpha, delta):
"""
Args:
alpha (float): Return on physical capital
... | modelproject/modelproject.py | import numpy as np
from scipy import optimize
import matplotlib.pyplot as plt
from types import SimpleNamespace
# Function to find steady state (ss) value for capital (k) of the basic Solow model using scipy.optimize
def ss_bas(n, s, B, alpha, delta):
"""
Args:
alpha (float): Return on physical capital
... | 0.878105 | 0.731646 |
import unittest
import pkg_resources
import hashlib
from kado import constants as c
from kado.utils import ghash
from tests.lib import constants as tc
class TestGHash(unittest.TestCase):
"""Test case for :func:`kado.utils.ghash.ghash`."""
def test_ghash_sequence(self):
"""Basic ``ghash`` test on a... | tests/utils/test_ghash.py | import unittest
import pkg_resources
import hashlib
from kado import constants as c
from kado.utils import ghash
from tests.lib import constants as tc
class TestGHash(unittest.TestCase):
"""Test case for :func:`kado.utils.ghash.ghash`."""
def test_ghash_sequence(self):
"""Basic ``ghash`` test on a... | 0.429669 | 0.384103 |
import os
import logging
"""
This script was made by <NAME> for NFIR, unless specified, all code in this document was written by the
former name.
Refactoring and writing to output file by <NAME> to comply with PEP8
Conversion of list item to string and int was done by <NAME>.
"""
filesList = []
def input_check(p_... | File_scan/file_scanner.py | import os
import logging
"""
This script was made by <NAME> for NFIR, unless specified, all code in this document was written by the
former name.
Refactoring and writing to output file by <NAME> to comply with PEP8
Conversion of list item to string and int was done by <NAME>.
"""
filesList = []
def input_check(p_... | 0.25842 | 0.08374 |
import sys
import time
import pytest
sys.path.append('../../')
from libs.common import md5, file_put_contents
from classes.HashlistsLoaderThread import HashlistsLoaderThread
from CommonIntegration import CommonIntegration
class Test_HashlistsLoaderThread(CommonIntegration):
""" HashlistsLoaderThread integration ... | tests/integration/test_HashlistsLoaderThread.py | import sys
import time
import pytest
sys.path.append('../../')
from libs.common import md5, file_put_contents
from classes.HashlistsLoaderThread import HashlistsLoaderThread
from CommonIntegration import CommonIntegration
class Test_HashlistsLoaderThread(CommonIntegration):
""" HashlistsLoaderThread integration ... | 0.267313 | 0.208058 |
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Dict, List, Tuple
class Light:
""" Receiver - Luz Inteligente """
def __init__(self, name: str, room_name: str) -> None:
self.name = name
self.room_name = room_name
self.color = 'Default color'
... | behavioral/command/command_1.py | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Dict, List, Tuple
class Light:
""" Receiver - Luz Inteligente """
def __init__(self, name: str, room_name: str) -> None:
self.name = name
self.room_name = room_name
self.color = 'Default color'
... | 0.81468 | 0.220941 |
from argparse import ArgumentParser, SUPPRESS
from pathlib import Path
import numpy as np
import cv2
from openvino.inference_engine import IECore
from inpainting_gui import InpaintingGUI
from inpainting import ImageInpainting
def build_arg_parser():
parser = ArgumentParser(add_help=False)
args = parser.add_... | demos/image_inpainting_demo/python/image_inpainting_demo.py | from argparse import ArgumentParser, SUPPRESS
from pathlib import Path
import numpy as np
import cv2
from openvino.inference_engine import IECore
from inpainting_gui import InpaintingGUI
from inpainting import ImageInpainting
def build_arg_parser():
parser = ArgumentParser(add_help=False)
args = parser.add_... | 0.59302 | 0.211376 |
import asyncio
import gzip
import json
import logging
import sys
import unittest
import zlib
import six
if six.PY3:
from unittest import mock
else:
import mock
from engineio import asyncio_server
from engineio.async_drivers import aiohttp as async_aiohttp
from engineio import exceptions
from engineio import p... | tests/asyncio/test_asyncio_server.py | import asyncio
import gzip
import json
import logging
import sys
import unittest
import zlib
import six
if six.PY3:
from unittest import mock
else:
import mock
from engineio import asyncio_server
from engineio.async_drivers import aiohttp as async_aiohttp
from engineio import exceptions
from engineio import p... | 0.574156 | 0.156749 |
from spack import *
class Hpgmg(Package):
"""HPGMG implements full multigrid (FMG) algorithms using
finite-volume and finite-element methods.
Different algorithmic variants adjust the arithmetic intensity
and architectural properties that are tested. These FMG methods
converge up to discretization... | internal/notes/builtin-SAVE/packages/hpgmg/package.py | from spack import *
class Hpgmg(Package):
"""HPGMG implements full multigrid (FMG) algorithms using
finite-volume and finite-element methods.
Different algorithmic variants adjust the arithmetic intensity
and architectural properties that are tested. These FMG methods
converge up to discretization... | 0.816918 | 0.374333 |
from atom.api import Typed
from enaml.widgets.action_group import ProxyActionGroup
from .QtGui import QActionGroup
from .qt_action import QtAction
from .qt_toolkit_object import QtToolkitObject
class QCustomActionGroup(QActionGroup):
""" A QActionGroup subclass which fixes some toggling issues.
When a QAc... | enaml/qt/qt_action_group.py | from atom.api import Typed
from enaml.widgets.action_group import ProxyActionGroup
from .QtGui import QActionGroup
from .qt_action import QtAction
from .qt_toolkit_object import QtToolkitObject
class QCustomActionGroup(QActionGroup):
""" A QActionGroup subclass which fixes some toggling issues.
When a QAc... | 0.861771 | 0.25363 |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from ppytools.lang.timerhelper import timemeter
from pyhive import hive
import logging
logger = logging.getLogger(__name__)
class HiveClient(object):
"""HiveClient
Use Thrift server connect ... | ppytools/hiveclient.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
from ppytools.lang.timerhelper import timemeter
from pyhive import hive
import logging
logger = logging.getLogger(__name__)
class HiveClient(object):
"""HiveClient
Use Thrift server connect ... | 0.632162 | 0.101278 |
from __future__ import absolute_import, unicode_literals
import pytest
from demorphy.token_types import is_punkt, is_email, is_url, contains_num, is_roman_number, is_egzotic_entity, is_abbrev
class TestSmallMethods:
def test_punkt(self):
assert is_punkt(u"..,")
assert is_punkt(u". .,")
as... | tests/test_token_types.py | from __future__ import absolute_import, unicode_literals
import pytest
from demorphy.token_types import is_punkt, is_email, is_url, contains_num, is_roman_number, is_egzotic_entity, is_abbrev
class TestSmallMethods:
def test_punkt(self):
assert is_punkt(u"..,")
assert is_punkt(u". .,")
as... | 0.585931 | 0.607081 |
from tkinter.ttk import *
import Yatra
from tkinter import *
from threading import Thread
from selenium import webdriver
import tbo
class HomePage():
def __init__(self,geometry="1450x500",title="SUMIP"):
self.first = True
self.root = Tk()
self.geometry = geometry
self.title = title
... | Main.py | from tkinter.ttk import *
import Yatra
from tkinter import *
from threading import Thread
from selenium import webdriver
import tbo
class HomePage():
def __init__(self,geometry="1450x500",title="SUMIP"):
self.first = True
self.root = Tk()
self.geometry = geometry
self.title = title
... | 0.19498 | 0.134264 |
import networkx as nx
from pgmpy.models import ClusterGraph
class JunctionTree(ClusterGraph):
"""
Class for representing Junction Tree.
Junction tree is undirected graph where each node represents a clique
(list, tuple or set of nodes) and edges represent sepset between two cliques.
Each sepset... | pgmpy/models/JunctionTree.py |
import networkx as nx
from pgmpy.models import ClusterGraph
class JunctionTree(ClusterGraph):
"""
Class for representing Junction Tree.
Junction tree is undirected graph where each node represents a clique
(list, tuple or set of nodes) and edges represent sepset between two cliques.
Each sepset... | 0.920518 | 0.681167 |
from chainer_compiler.elichika.typing.ext.utils import *
from chainer_compiler.elichika.typing.types import *
from chainer_compiler.elichika.typing.shape_elem import *
__all__ = [ 'ty_MakeTensor'
, 'ty_Shape'
, 'ty_Size'
, 'ty_DType'
, 'ty_TensorArith'
, 't... | chainer_compiler/elichika/typing/ext/common.py | from chainer_compiler.elichika.typing.ext.utils import *
from chainer_compiler.elichika.typing.types import *
from chainer_compiler.elichika.typing.shape_elem import *
__all__ = [ 'ty_MakeTensor'
, 'ty_Shape'
, 'ty_Size'
, 'ty_DType'
, 'ty_TensorArith'
, 't... | 0.435661 | 0.374733 |
"""Tests for loader module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import textwrap
import gast
from tensorflow.python.autograph.pyct import loader
from tensorflow.python.autograph.pyct import parser
from tensorflow.python.platform import test
... | tensorflow/python/autograph/pyct/loader_test.py | """Tests for loader module."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import textwrap
import gast
from tensorflow.python.autograph.pyct import loader
from tensorflow.python.autograph.pyct import parser
from tensorflow.python.platform import test
... | 0.793146 | 0.303796 |
import pytest
from firebird.qa import db_factory, isql_act, Action
# version: 3.0
# resources: None
substitutions_1 = []
init_script_1 = """
recreate table crash (a1 integer,a2 integer,a3 integer, a4 integer) ;
commit;
insert into crash (a1, a2, a3, a4) values ( 1, 2, 3, 4);
insert into crash (a1, a... | tests/bugs/core_0907_test.py |
import pytest
from firebird.qa import db_factory, isql_act, Action
# version: 3.0
# resources: None
substitutions_1 = []
init_script_1 = """
recreate table crash (a1 integer,a2 integer,a3 integer, a4 integer) ;
commit;
insert into crash (a1, a2, a3, a4) values ( 1, 2, 3, 4);
insert into crash (a1, a... | 0.452536 | 0.174217 |
import logging
from typing import List
from kafka import KafkaConsumer, TopicPartition
from kafka.errors import KafkaError
from just_bin_it.exceptions import KafkaException
class Consumer:
"""
Consumes the messages from Kafka.
This contains the least amount of logic so as to make mocking and testing
... | just_bin_it/endpoints/kafka_consumer.py | import logging
from typing import List
from kafka import KafkaConsumer, TopicPartition
from kafka.errors import KafkaError
from just_bin_it.exceptions import KafkaException
class Consumer:
"""
Consumes the messages from Kafka.
This contains the least amount of logic so as to make mocking and testing
... | 0.810104 | 0.495178 |
from openapi_server.models.address import Address
from openapi_server.models.tx_summary import TxSummary
from openapi_server.models.address_tag import AddressTag
from openapi_server.models.address_tags import AddressTags
from openapi_server.models.neighbors import Neighbors
from openapi_server.models.neighbor import Ne... | gsrest/service/common_service.py | from openapi_server.models.address import Address
from openapi_server.models.tx_summary import TxSummary
from openapi_server.models.address_tag import AddressTag
from openapi_server.models.address_tags import AddressTags
from openapi_server.models.neighbors import Neighbors
from openapi_server.models.neighbor import Ne... | 0.650356 | 0.175609 |
import requests
import json
import boto3
from decimal import Decimal
import time
import datetime
from boto3.dynamodb.conditions import Key
params = {
'api_key': 'REGISTER ON AIRLABS.CO TO RETRIEVE YOUR API KEY', #REPLACE WITH YOUR API KEY
'dep_iata': 'LAS',
'_fields': 'dep_iata,arr_iata,airline_iata,flight_numbe... | cloudformation-templates/resources/Lambda/update-flight-LasVegasdeparture/flight.py | import requests
import json
import boto3
from decimal import Decimal
import time
import datetime
from boto3.dynamodb.conditions import Key
params = {
'api_key': 'REGISTER ON AIRLABS.CO TO RETRIEVE YOUR API KEY', #REPLACE WITH YOUR API KEY
'dep_iata': 'LAS',
'_fields': 'dep_iata,arr_iata,airline_iata,flight_numbe... | 0.245808 | 0.099426 |
__Author__ = "noduez"
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/7/11 10:19 AM
# @File : parse_links.py 链接解释器
# @Software: PyCharm
from html.parser import HTMLParser
from io import StringIO
from urllib.request import urlopen
from urllib.parse import urljoin
from bs4 import BeautifulSoup, SoupS... | ch09_WebCS/parse_links.py | __Author__ = "noduez"
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/7/11 10:19 AM
# @File : parse_links.py 链接解释器
# @Software: PyCharm
from html.parser import HTMLParser
from io import StringIO
from urllib.request import urlopen
from urllib.parse import urljoin
from bs4 import BeautifulSoup, SoupS... | 0.194521 | 0.139455 |
import gym
import numpy as np
from typing import List, Dict
from abc import abstractmethod
class Normalizer(object):
def __init__(self, n_inputs: int):
"""
Normalizer class. Normalizes the observations of the agents
Arguments:
----------
n_inputs: int
... | giadog/src/agents/ANN.py | import gym
import numpy as np
from typing import List, Dict
from abc import abstractmethod
class Normalizer(object):
def __init__(self, n_inputs: int):
"""
Normalizer class. Normalizes the observations of the agents
Arguments:
----------
n_inputs: int
... | 0.949681 | 0.519338 |
from __future__ import absolute_import, unicode_literals
import codecs
from ..util import u, slugify
import os
from ..util import ERROR_COLOR, RESET_COLOR
class TextExporter(object):
"""This Exporter can convert entries and journals into text files."""
names = ["text", "txt"]
extension = "txt"
@clas... | jrnl/plugins/text_exporter.py |
from __future__ import absolute_import, unicode_literals
import codecs
from ..util import u, slugify
import os
from ..util import ERROR_COLOR, RESET_COLOR
class TextExporter(object):
"""This Exporter can convert entries and journals into text files."""
names = ["text", "txt"]
extension = "txt"
@clas... | 0.771456 | 0.194731 |
# Copyright 2019 <NAME> <<EMAIL>>
import os
import unittest
import gerberex
class TestRs274x(unittest.TestCase):
@classmethod
def setUpClass(cls):
os.chdir(os.path.dirname(__file__))
cls.INDIR = 'data'
cls.OUTDIR = 'outputs'
cls.EXPECTSDIR = 'expects'
cls.OUTPREFIX = '... | tests/test_rs274x.py |
# Copyright 2019 <NAME> <<EMAIL>>
import os
import unittest
import gerberex
class TestRs274x(unittest.TestCase):
@classmethod
def setUpClass(cls):
os.chdir(os.path.dirname(__file__))
cls.INDIR = 'data'
cls.OUTDIR = 'outputs'
cls.EXPECTSDIR = 'expects'
cls.OUTPREFIX = '... | 0.339499 | 0.18188 |
"""Start an RPC server"""
from __future__ import absolute_import
import argparse
import ast
import multiprocessing
import sys
import logging
import tvm
from tvm import micro
from .. import rpc
def main(args):
"""Main function
Parameters
----------
args : argparse.Namespace
parsed args from co... | python/tvm/exec/rpc_server.py | """Start an RPC server"""
from __future__ import absolute_import
import argparse
import ast
import multiprocessing
import sys
import logging
import tvm
from tvm import micro
from .. import rpc
def main(args):
"""Main function
Parameters
----------
args : argparse.Namespace
parsed args from co... | 0.506591 | 0.110759 |
from weblab.core.coordinator.clients.weblabdeusto import WebLabDeustoClient
import os
import time
from weblab.core.reservations import WaitingReservation, ConfirmedReservation, WaitingConfirmationReservation
from weblab.data.command import Command
from weblab.data.experiments import ExperimentId
import threading
impo... | tools/ExperimentBot/run.py | from weblab.core.coordinator.clients.weblabdeusto import WebLabDeustoClient
import os
import time
from weblab.core.reservations import WaitingReservation, ConfirmedReservation, WaitingConfirmationReservation
from weblab.data.command import Command
from weblab.data.experiments import ExperimentId
import threading
impo... | 0.269326 | 0.148973 |
import sys
#sys.path.append('../')
sys.path.insert(0, '..')
import scipy.io
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from copy import deepcopy
import scipy.io
import numpy as np
import pandas as pd
import seaborn as sns
from scipy import random, linalg, dot, diag, all, allclose
impor... | CSSPy/evaluation_functions.py | import sys
#sys.path.append('../')
sys.path.insert(0, '..')
import scipy.io
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
from copy import deepcopy
import scipy.io
import numpy as np
import pandas as pd
import seaborn as sns
from scipy import random, linalg, dot, diag, all, allclose
impor... | 0.388386 | 0.665302 |
import logging
import requests
from .exceptions import APIError, Unauthorized, TransactionErrors
logger = logging.getLogger(__name__)
class APIProvider(object):
CONTENT_TYPE = 'application/json; charset=utf-8'
def __init__(self, client_id, client_secret, base_url, public_key, access_token=None):
s... | edenred/provider.py | import logging
import requests
from .exceptions import APIError, Unauthorized, TransactionErrors
logger = logging.getLogger(__name__)
class APIProvider(object):
CONTENT_TYPE = 'application/json; charset=utf-8'
def __init__(self, client_id, client_secret, base_url, public_key, access_token=None):
s... | 0.528047 | 0.073463 |
import argparse
import glob
import os
import random
import re
import sys
from datetime import date
from subprocess import check_output
from typing import List
from setuptools import setup, find_packages
def get_version():
# get version string from version.py
# TODO: ideally the version.py should be generate... | setup.py |
import argparse
import glob
import os
import random
import re
import sys
from datetime import date
from subprocess import check_output
from typing import List
from setuptools import setup, find_packages
def get_version():
# get version string from version.py
# TODO: ideally the version.py should be generate... | 0.374104 | 0.176175 |
import logging
from transformers.configuration_utils import PretrainedConfig
logger = logging.getLogger(__name__)
CHBERT_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
class CHBertConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a :class:`~chnlp_bert.CHBertModel`.
... | src/configuration_chbert.py | import logging
from transformers.configuration_utils import PretrainedConfig
logger = logging.getLogger(__name__)
CHBERT_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
class CHBertConfig(PretrainedConfig):
r"""
This is the configuration class to store the configuration of a :class:`~chnlp_bert.CHBertModel`.
... | 0.927569 | 0.336004 |
import random
import os
import collections
import string
import shell
from hypothesis.database import ExampleDatabase
from hypothesis import given, settings, HealthCheck
from hypothesis.strategies import text, lists, composite, integers, randoms, sampled_from
from test_util import run, rm_whitespace, rm_whitespace, clo... | test/bcounteach_hash_test.py | import random
import os
import collections
import string
import shell
from hypothesis.database import ExampleDatabase
from hypothesis import given, settings, HealthCheck
from hypothesis.strategies import text, lists, composite, integers, randoms, sampled_from
from test_util import run, rm_whitespace, rm_whitespace, clo... | 0.378229 | 0.172642 |
from load_data import Data
import numpy as np
import torch
import time
from collections import defaultdict
import argparse
import scipy.sparse as sp
from utils_NoGE import *
from model_NoGE import *
torch.manual_seed(1337)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if torch.cuda.is_available... | main_NoGE.py | from load_data import Data
import numpy as np
import torch
import time
from collections import defaultdict
import argparse
import scipy.sparse as sp
from utils_NoGE import *
from model_NoGE import *
torch.manual_seed(1337)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
if torch.cuda.is_available... | 0.752195 | 0.353414 |
from motion_primitives_py import MotionPrimitive
import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
from scipy.linalg import expm
import scipy.integrate as integrate
class EuclideanMotionPrimitive(MotionPrimitive):
"""
A motion primitive that is just a straight line, with the norm of the d... | motion_primitives_py/motion_primitives_py/motion_primitive_types/euclidean_motion_primitive.py | from motion_primitives_py import MotionPrimitive
import numpy as np
import matplotlib.pyplot as plt
import sympy as sym
from scipy.linalg import expm
import scipy.integrate as integrate
class EuclideanMotionPrimitive(MotionPrimitive):
"""
A motion primitive that is just a straight line, with the norm of the d... | 0.870322 | 0.660433 |
import os
import re
import shutil
import codecs
import hashlib
import chardet
import json
import stat
import subprocess
from .Config import g_conf
from .Router import Router
from enum import Enum
class Color(Enum):
BLACK = 30
RED = 31
GREEN = 32
YELLOW = 33
BLUE = 34
MAGENTA = 35
CYAN = 3... | Maverick/Utils.py |
import os
import re
import shutil
import codecs
import hashlib
import chardet
import json
import stat
import subprocess
from .Config import g_conf
from .Router import Router
from enum import Enum
class Color(Enum):
BLACK = 30
RED = 31
GREEN = 32
YELLOW = 33
BLUE = 34
MAGENTA = 35
CYAN = 3... | 0.31363 | 0.065306 |
from pprint import pformat
from six import iteritems
import re
class RailStationResponse(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | travel/docs/Amadeus-master/pactravel-master/swagger_client/models/rail_station_response.py | from pprint import pformat
from six import iteritems
import re
class RailStationResponse(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... | 0.705481 | 0.223992 |
import os
import numpy as np
import data_provider
import gc
import time
from itertools import combinations, permutations
'''
本脚本是將样本的激活数据的边覆盖情况具现化保存
数据结构边写边考虑
'''
'''
目前只考虑1-1的三种情况的覆盖
写尽可能考虑可拓展性
'''
def check_dir(dir_path):
if not os.path.exists(dir_path):
os.makedirs(dir_path)
# 获取两层之间的每个数据的对应的
def p... | process/process_coverage_percentile_lenet.py | import os
import numpy as np
import data_provider
import gc
import time
from itertools import combinations, permutations
'''
本脚本是將样本的激活数据的边覆盖情况具现化保存
数据结构边写边考虑
'''
'''
目前只考虑1-1的三种情况的覆盖
写尽可能考虑可拓展性
'''
def check_dir(dir_path):
if not os.path.exists(dir_path):
os.makedirs(dir_path)
# 获取两层之间的每个数据的对应的
def p... | 0.151498 | 0.384074 |
import imp
import inspect
import logging
import os
import os.path
import re
import sys
from functools import partial
from traceback import format_exc
from . import script_host
from ..api import decode_if_bytes, walk
from ..compat import IS_PYTHON3, find_module
from ..msgpack_rpc import ErrorResponse
from ..util import... | pynvim/plugin/host.py | import imp
import inspect
import logging
import os
import os.path
import re
import sys
from functools import partial
from traceback import format_exc
from . import script_host
from ..api import decode_if_bytes, walk
from ..compat import IS_PYTHON3, find_module
from ..msgpack_rpc import ErrorResponse
from ..util import... | 0.390941 | 0.053502 |
from typing import Optional, Dict, Any, TypeVar, Callable, Type, cast
T = TypeVar("T")
def from_dict(f: Callable[[Any], T], x: Any) -> Dict[str, T]:
assert isinstance(x, dict)
return { k: f(v) for (k, v) in x.items() }
def from_str(x: Any) -> str:
assert isinstance(x, str)
return x
def from_non... | src/google/events/cloud/pubsub/v1/MessagePublishedData.py |
from typing import Optional, Dict, Any, TypeVar, Callable, Type, cast
T = TypeVar("T")
def from_dict(f: Callable[[Any], T], x: Any) -> Dict[str, T]:
assert isinstance(x, dict)
return { k: f(v) for (k, v) in x.items() }
def from_str(x: Any) -> str:
assert isinstance(x, str)
return x
def from_non... | 0.939151 | 0.503479 |
# Copyright 2021 - 2022, <NAME> <<EMAIL>>, Dr. <NAME> <<EMAIL>>
# Use of this source code is governed by an MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.
import os
import sys
import re
import argparse
from dotenv import load_dotenv
from base.backends.sql import... | src/tui.py |
# Copyright 2021 - 2022, <NAME> <<EMAIL>>, Dr. <NAME> <<EMAIL>>
# Use of this source code is governed by an MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.
import os
import sys
import re
import argparse
from dotenv import load_dotenv
from base.backends.sql import... | 0.457621 | 0.101367 |
from typing import Callable, Optional, Union
import torch
from monai.metrics import compute_roc_auc
from monai.utils import Average, exact_version, optional_import
EpochMetric, _ = optional_import("ignite.metrics", "0.4.2", exact_version, "EpochMetric")
class ROCAUC(EpochMetric): # type: ignore[valid-type, misc]... | monai/handlers/roc_auc.py |
from typing import Callable, Optional, Union
import torch
from monai.metrics import compute_roc_auc
from monai.utils import Average, exact_version, optional_import
EpochMetric, _ = optional_import("ignite.metrics", "0.4.2", exact_version, "EpochMetric")
class ROCAUC(EpochMetric): # type: ignore[valid-type, misc]... | 0.97261 | 0.488588 |
from bokeh.models import ColumnDataSource
from TA_Coord import TA_Coord
from abc import ABCMeta, abstractmethod
class TA_DiscreteMass(object):
__metaclass__ = ABCMeta
## create mass
@abstractmethod
def __init__ (self, mass):
# initialise value
self.mass = mass
# create vector of... | Template_App/TA_Mass.py | from bokeh.models import ColumnDataSource
from TA_Coord import TA_Coord
from abc import ABCMeta, abstractmethod
class TA_DiscreteMass(object):
__metaclass__ = ABCMeta
## create mass
@abstractmethod
def __init__ (self, mass):
# initialise value
self.mass = mass
# create vector of... | 0.801975 | 0.394172 |
from django.conf.urls import url
from django.views.generic import TemplateView
from django.views.generic.edit import UpdateView
from .api.views import *
from .models import CounterTransfer as Table
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name="countertransfer/list.html"), name="index"),
url(... | saleor/countertransfer/urls.py | from django.conf.urls import url
from django.views.generic import TemplateView
from django.views.generic.edit import UpdateView
from .api.views import *
from .models import CounterTransfer as Table
urlpatterns = [
url(r'^$', TemplateView.as_view(template_name="countertransfer/list.html"), name="index"),
url(... | 0.23231 | 0.073364 |
"""Writing out derivative files."""
import numpy as np
from nipype.pipeline import engine as pe
from nipype.interfaces import utility as niu
from fmriprep import config
from fmriprep.config import DEFAULT_MEMORY_MIN_GB
from fmriprep.interfaces import DerivativesDataSink
def prepare_timing_parameters(metadata):
"... | fmriprep/workflows/bold/outputs.py | """Writing out derivative files."""
import numpy as np
from nipype.pipeline import engine as pe
from nipype.interfaces import utility as niu
from fmriprep import config
from fmriprep.config import DEFAULT_MEMORY_MIN_GB
from fmriprep.interfaces import DerivativesDataSink
def prepare_timing_parameters(metadata):
"... | 0.9357 | 0.583441 |
from optionaldict import optionaldict
from findy.vendor.wechatpy.client.api.base import BaseWeChatAPI
from findy.vendor.wechatpy.utils import to_text
class WeChatBatch(BaseWeChatAPI):
"""
https://work.weixin.qq.com/api/doc#90000/90135/90979
异步批量接口用于大批量数据的处理,提交后接口即返回,企业微信会在后台继续执行任务。
执行完成后,企业微信后台会通过... | findy/vendor/wechatpy/work/client/api/batch.py |
from optionaldict import optionaldict
from findy.vendor.wechatpy.client.api.base import BaseWeChatAPI
from findy.vendor.wechatpy.utils import to_text
class WeChatBatch(BaseWeChatAPI):
"""
https://work.weixin.qq.com/api/doc#90000/90135/90979
异步批量接口用于大批量数据的处理,提交后接口即返回,企业微信会在后台继续执行任务。
执行完成后,企业微信后台会通过... | 0.466116 | 0.208945 |
class Character:
def __init__(self):
self.attributes = {"Class & Level": "", "Name": "", "Background": "",
"Race": "", "Alignment": "", "Experience Points": ""}
self.skill_points = {"Strength": 0, "Dexterity": 0, "Constitution": 0,
"Intelligence": 0, "Wisd... | character.py | class Character:
def __init__(self):
self.attributes = {"Class & Level": "", "Name": "", "Background": "",
"Race": "", "Alignment": "", "Experience Points": ""}
self.skill_points = {"Strength": 0, "Dexterity": 0, "Constitution": 0,
"Intelligence": 0, "Wisd... | 0.573798 | 0.425128 |
__version__ = "0.2.0"
from collections.abc import Container
from functools import wraps
from itertools import count
import sys
from typing import Any
from weakref import WeakSet
class Dep:
stack = []
def __init__(self) -> None:
self._subs = WeakSet()
def add_sub(self, sub: "Watcher") -> None:
... | observ/__init__.py | __version__ = "0.2.0"
from collections.abc import Container
from functools import wraps
from itertools import count
import sys
from typing import Any
from weakref import WeakSet
class Dep:
stack = []
def __init__(self) -> None:
self._subs = WeakSet()
def add_sub(self, sub: "Watcher") -> None:
... | 0.574395 | 0.137417 |
from __future__ import annotations
from collections.abc import Mapping
from typing import Any
import voluptuous as vol
from wallbox import Wallbox
from homeassistant import config_entries, core
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.data_entry_flow import FlowResult
from . i... | homeassistant/components/wallbox/config_flow.py | from __future__ import annotations
from collections.abc import Mapping
from typing import Any
import voluptuous as vol
from wallbox import Wallbox
from homeassistant import config_entries, core
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.data_entry_flow import FlowResult
from . i... | 0.871187 | 0.133302 |
import binascii
import serial
import time
import logging
class DenonRemote(object):
"""Controller for Denon 2307CI Audio/Video receiver
This controller sends queries and commands to a Denon 2307CI receiver over
RS232.
Attributes:
port_name: A string name of serial port to use for communica... | denon_remote.py | import binascii
import serial
import time
import logging
class DenonRemote(object):
"""Controller for Denon 2307CI Audio/Video receiver
This controller sends queries and commands to a Denon 2307CI receiver over
RS232.
Attributes:
port_name: A string name of serial port to use for communica... | 0.903742 | 0.394667 |
"""Tests for the output module interface."""
from __future__ import unicode_literals
import unittest
from plaso.lib import definitions
from plaso.lib import timelib
from plaso.output import formatting_helper
from plaso.output import interface
from plaso.output import manager
from tests.cli import test_lib as cli_te... | tests/output/interface.py | """Tests for the output module interface."""
from __future__ import unicode_literals
import unittest
from plaso.lib import definitions
from plaso.lib import timelib
from plaso.output import formatting_helper
from plaso.output import interface
from plaso.output import manager
from tests.cli import test_lib as cli_te... | 0.842248 | 0.404566 |
# Import necessary modules
from nltk.sentiment.vader import SentimentIntensityAnalyzer
reviews = [
{
"company_name" : "<NAME>",
"title" : "Looks bad from the outside but it's worst inside",
"info" : "I worked at CreditMantri full-time (More than a year)",
"pro... | org/sentiment/glassdoor_review_analyzer.py | # Import necessary modules
from nltk.sentiment.vader import SentimentIntensityAnalyzer
reviews = [
{
"company_name" : "<NAME>",
"title" : "Looks bad from the outside but it's worst inside",
"info" : "I worked at CreditMantri full-time (More than a year)",
"pro... | 0.1844 | 0.439507 |
from __future__ import print_function
import os
import sys
import requests
import time
import pdb
class salt_api():
'''
salt_api objects
should contain attribs: token, minion_status_dict
should contain methods: get_token, get_minion_status
'''
def __init__(self, full_server_url, salt_api_servic... | flaskvc/salt_api_wrapper.py | from __future__ import print_function
import os
import sys
import requests
import time
import pdb
class salt_api():
'''
salt_api objects
should contain attribs: token, minion_status_dict
should contain methods: get_token, get_minion_status
'''
def __init__(self, full_server_url, salt_api_servic... | 0.19349 | 0.049889 |
import logger
from TestInput import TestInputSingleton
from basetestcase import BaseTestCase
from membase.helper.cluster_helper import ClusterOperationHelper
from membase.api.rest_client import RestConnection, RestHelper
from couchbase_helper.documentgenerator import BlobGenerator
from couchbase_helper.data_analysis_he... | pytests/analysis/clusterinfoanalysis.py | import logger
from TestInput import TestInputSingleton
from basetestcase import BaseTestCase
from membase.helper.cluster_helper import ClusterOperationHelper
from membase.api.rest_client import RestConnection, RestHelper
from couchbase_helper.documentgenerator import BlobGenerator
from couchbase_helper.data_analysis_he... | 0.463444 | 0.193833 |
import os
import numpy as np
from typing import List
import unittest
import torch
from forte.data.converter import Converter
from forte.data.converter import Feature
class ConverterTest(unittest.TestCase):
def setUp(self):
self.converter: Converter = Converter()
def test_convert1(self):
feat... | tests/forte/data/converter/converter_test.py | import os
import numpy as np
from typing import List
import unittest
import torch
from forte.data.converter import Converter
from forte.data.converter import Feature
class ConverterTest(unittest.TestCase):
def setUp(self):
self.converter: Converter = Converter()
def test_convert1(self):
feat... | 0.749454 | 0.671533 |
import collections
import functools
import os
from typing import Any, Callable, Iterable, Mapping, MutableSequence, Optional, Sequence, Union
from absl import logging
import numpy as np
import pandas as pd
import t5.data
from t5.models import mesh_transformer
from t5.models import utils as model_utils
import tensorfl... | t5/evaluation/eval_utils.py | import collections
import functools
import os
from typing import Any, Callable, Iterable, Mapping, MutableSequence, Optional, Sequence, Union
from absl import logging
import numpy as np
import pandas as pd
import t5.data
from t5.models import mesh_transformer
from t5.models import utils as model_utils
import tensorfl... | 0.877464 | 0.202581 |
"""Unit tests for Mujoco dm_control suite align check."""
from typing import Any, List, no_type_check
import dm_env
import numpy as np
from absl import logging
from absl.testing import absltest
from dm_control import suite
from envpool.mujoco.dmc import (
DmcAcrobotDMEnvPool,
DmcAcrobotEnvSpec,
DmcBallInCupDME... | envpool/mujoco/dmc/mujoco_dmc_align_test.py | """Unit tests for Mujoco dm_control suite align check."""
from typing import Any, List, no_type_check
import dm_env
import numpy as np
from absl import logging
from absl.testing import absltest
from dm_control import suite
from envpool.mujoco.dmc import (
DmcAcrobotDMEnvPool,
DmcAcrobotEnvSpec,
DmcBallInCupDME... | 0.829146 | 0.526708 |
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from scipy.spatial.transform import Rotation
from loss.ops.emd.emd_module import emdFunction
from misc.point_utils import get_knn_idx_dist, group, gather
def cd_loss(preds, gts):
def batch_pairwise_dist(x, y):
... | loss/reg_loss.py | import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from scipy.spatial.transform import Rotation
from loss.ops.emd.emd_module import emdFunction
from misc.point_utils import get_knn_idx_dist, group, gather
def cd_loss(preds, gts):
def batch_pairwise_dist(x, y):
... | 0.927978 | 0.465995 |
from __future__ import unicode_literals
import pytest
from django.conf.urls import url
from django.core.management import call_command
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import six
from rest_framework.compat import coreapi
from rest_framework.utils impor... | tests/test_generateschema.py | from __future__ import unicode_literals
import pytest
from django.conf.urls import url
from django.core.management import call_command
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import six
from rest_framework.compat import coreapi
from rest_framework.utils impor... | 0.553023 | 0.217919 |
def compliment():
import random
compliments = """Your smile is contagious
You look great today
You're a smart cookie
I bet you make babies smile
You have impeccable manners
I like your style
You have the best laugh
I appreciate you
You are the most perfect you there is
Your perspective is refreshing
You're an awesom... | code/misc_compliment.py | def compliment():
import random
compliments = """Your smile is contagious
You look great today
You're a smart cookie
I bet you make babies smile
You have impeccable manners
I like your style
You have the best laugh
I appreciate you
You are the most perfect you there is
Your perspective is refreshing
You're an awesom... | 0.278747 | 0.341089 |
from django.test import TestCase
from dali.gallery.models import Gallery, Picture, _get_viewable_size, _get_thumbnail_size
from dali.gallery.tests.utils import create_picture, get_image, get_temp_name
class GalleryTestCase(TestCase):
fixtures = ['gallery.json']
def setUp(self):
self.gallery = Gallery.... | dali/gallery/tests/models.py | from django.test import TestCase
from dali.gallery.models import Gallery, Picture, _get_viewable_size, _get_thumbnail_size
from dali.gallery.tests.utils import create_picture, get_image, get_temp_name
class GalleryTestCase(TestCase):
fixtures = ['gallery.json']
def setUp(self):
self.gallery = Gallery.... | 0.685213 | 0.352954 |
import argparse
import time
import reindex_helpers
from config import Config
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search
#load the args & config
parser = argparse.ArgumentParser("Run the reindex script")
parser.add_argument("--sourceindex", "-s", required=True, help="Source index to c... | tools/reindex/reindex.py | import argparse
import time
import reindex_helpers
from config import Config
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Search
#load the args & config
parser = argparse.ArgumentParser("Run the reindex script")
parser.add_argument("--sourceindex", "-s", required=True, help="Source index to c... | 0.253861 | 0.14682 |
# ### Decision Tree with Scikit-learn & Cross Validation [Split and LeaveOneOut]
# #### Required Libraries
# In[ ]:
import pandas as pd
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
from sklearn.cross_validation import train_test_split
from sklearn import tree
from sklearn im... | downloaded_kernels/loan_data/parsed_kernels/kernel_91.py |
# ### Decision Tree with Scikit-learn & Cross Validation [Split and LeaveOneOut]
# #### Required Libraries
# In[ ]:
import pandas as pd
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
from sklearn.cross_validation import train_test_split
from sklearn import tree
from sklearn im... | 0.571527 | 0.644253 |
import random
import sys
import requests
from bs4 import BeautifulSoup
from bullet import Bullet, Input, Password, SlidePrompt, YesNo
from openpyxl import Workbook
__VERSION__ = '0.1.1'
class URP:
def __init__(self):
self.port = ''
self.protocol = 'http://'
self.urp_index = 'newjw.cdues... | killurp.py |
import random
import sys
import requests
from bs4 import BeautifulSoup
from bullet import Bullet, Input, Password, SlidePrompt, YesNo
from openpyxl import Workbook
__VERSION__ = '0.1.1'
class URP:
def __init__(self):
self.port = ''
self.protocol = 'http://'
self.urp_index = 'newjw.cdues... | 0.284179 | 0.052985 |
from subprocess import call
import os
TMPL_GEN_TS = "keytool -import -noprompt -alias {0} -file {1} -keystore {2} -storepass:file {3}.storepass"
DEV_NULL = open('/dev/null', 'w')
class Keytool:
def __init__(self, cadir, certname, store_password, hosts_to_trust, certtype):
self.cadir = cadir
sel... | source/keytool.py | from subprocess import call
import os
TMPL_GEN_TS = "keytool -import -noprompt -alias {0} -file {1} -keystore {2} -storepass:file {3}.storepass"
DEV_NULL = open('/dev/null', 'w')
class Keytool:
def __init__(self, cadir, certname, store_password, hosts_to_trust, certtype):
self.cadir = cadir
sel... | 0.175821 | 0.063715 |
import os
import re
from nuitka import Options
from nuitka.plugins.PluginBase import NuitkaPluginBase
from nuitka.utils.FileOperations import copyFile, getFileList
from nuitka.utils.Importing import getSharedLibrarySuffix
from nuitka.utils.Utils import isWin32Windows
class NuitkaPluginZmq(NuitkaPluginBase):
"""T... | nuitka/plugins/standard/ZmqPlugin.py | import os
import re
from nuitka import Options
from nuitka.plugins.PluginBase import NuitkaPluginBase
from nuitka.utils.FileOperations import copyFile, getFileList
from nuitka.utils.Importing import getSharedLibrarySuffix
from nuitka.utils.Utils import isWin32Windows
class NuitkaPluginZmq(NuitkaPluginBase):
"""T... | 0.297164 | 0.122287 |