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 dataclasses
import sys
from functools import cache
from pathlib import Path
from typing import Callable
import aocd
from rich.console import Console
from rich.traceback import install
install(show_locals=True)
console = Console()
DAY = int("".join(s for s in Path(__file__).name if s.isdigit()))
# noinspection... | aoc2021/day21.py | import dataclasses
import sys
from functools import cache
from pathlib import Path
from typing import Callable
import aocd
from rich.console import Console
from rich.traceback import install
install(show_locals=True)
console = Console()
DAY = int("".join(s for s in Path(__file__).name if s.isdigit()))
# noinspection... | 0.381335 | 0.423935 |
import pytest
import dockerfile
def test_command_module():
"""namedtuple defaults to the parent python frame. we fix this"""
assert dockerfile.Command.__module__ == dockerfile.__name__
def test_all_cmds():
assert dockerfile.all_cmds()[:3] == ('add', 'arg', 'cmd')
def test_parse_file_ioerror():
wi... | tests/dockerfile_test.py | import pytest
import dockerfile
def test_command_module():
"""namedtuple defaults to the parent python frame. we fix this"""
assert dockerfile.Command.__module__ == dockerfile.__name__
def test_all_cmds():
assert dockerfile.all_cmds()[:3] == ('add', 'arg', 'cmd')
def test_parse_file_ioerror():
wi... | 0.300232 | 0.27382 |
import requests
from sim.exceptions import abort
from sim.response import Response
from sim.context import AppRequestContext
from wes import app, db, cache_pool
from wes.model import User, Category, Article
from wes.consts import RespCode, Permission, RoleUser, RoleAdmin, Roles, USER, CATEGORY, ARTICLE
from wes.api.de... | src/server_py3/aps/src/wes/api/v2/search/search.py |
import requests
from sim.exceptions import abort
from sim.response import Response
from sim.context import AppRequestContext
from wes import app, db, cache_pool
from wes.model import User, Category, Article
from wes.consts import RespCode, Permission, RoleUser, RoleAdmin, Roles, USER, CATEGORY, ARTICLE
from wes.api.de... | 0.477554 | 0.119819 |
QQQQ QQQQ_123 QQQQ123 PROTOCOL_v2 QQQ.bar baz.AA_a _AAA foo._AAA
QQQq QQQq123 pats.FOOO() _ _1 __1 _1A __1A _a __a __ ___ ___a ___1 __aA ___Aa
QQQQ : constant.other.caps.python, source.python
: source.python
QQQQ_123 : constant.other.caps.python, source.python
: source.pyth... | test/expressions/const1.py | QQQQ QQQQ_123 QQQQ123 PROTOCOL_v2 QQQ.bar baz.AA_a _AAA foo._AAA
QQQq QQQq123 pats.FOOO() _ _1 __1 _1A __1A _a __a __ ___ ___a ___1 __aA ___Aa
QQQQ : constant.other.caps.python, source.python
: source.python
QQQQ_123 : constant.other.caps.python, source.python
: source.pyth... | 0.461745 | 0.056366 |
from datetime import datetime
from time import time
from pyrogram import Client, filters
from pyrogram.types import Message, InlineKeyboardButton, InlineKeyboardMarkup
from config import Onik
from helpers.decorators import sudo_users_only
from helpers.filters import command
START_TIME = datetime.utcnow()
START_TIME_... | onik/start.py | from datetime import datetime
from time import time
from pyrogram import Client, filters
from pyrogram.types import Message, InlineKeyboardButton, InlineKeyboardMarkup
from config import Onik
from helpers.decorators import sudo_users_only
from helpers.filters import command
START_TIME = datetime.utcnow()
START_TIME_... | 0.416559 | 0.209773 |
from fastapi import Depends, APIRouter, HTTPException
from pydantic import BaseModel
from typing import List
import datetime
from starlette.responses import Response, FileResponse
from .auth import logged_in_user, User
from ..util import Database, asynctar
import mimetypes
import logging
router = APIRouter()
@route... | posda/fastapi/app/papi/routes/download.py | from fastapi import Depends, APIRouter, HTTPException
from pydantic import BaseModel
from typing import List
import datetime
from starlette.responses import Response, FileResponse
from .auth import logged_in_user, User
from ..util import Database, asynctar
import mimetypes
import logging
router = APIRouter()
@route... | 0.441432 | 0.108708 |
import pp
from pp import Port
from pp.routing.connect_bundle import connect_bundle
def test_connect_bundle():
xs_top = [-100, -90, -80, 0, 10, 20, 40, 50, 80, 90, 100, 105, 110, 115]
pitch = 127.0
N = len(xs_top)
xs_bottom = [(i - N / 2) * pitch for i in range(N)]
top_ports = [Port("top_{}".for... | pp/test/test_connect_bundle.py | import pp
from pp import Port
from pp.routing.connect_bundle import connect_bundle
def test_connect_bundle():
xs_top = [-100, -90, -80, 0, 10, 20, 40, 50, 80, 90, 100, 105, 110, 115]
pitch = 127.0
N = len(xs_top)
xs_bottom = [(i - N / 2) * pitch for i in range(N)]
top_ports = [Port("top_{}".for... | 0.525369 | 0.409398 |
import pandas as pd
import sqlite3
import string
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountV... | lib/TwitterSentiment.py | import pandas as pd
import sqlite3
import string
from sklearn.pipeline import Pipeline
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score
from sklearn.naive_bayes import MultinomialNB
from sklearn.feature_extraction.text import CountV... | 0.538012 | 0.163445 |
from typing import List
import math
import numpy as np
import tensorflow as tf
# Import aimet specific modules
import aimet_tensorflow.utils.common
import aimet_tensorflow.utils.op.conv
from aimet_tensorflow.layer_database import Layer, LayerDatabase
from aimet_common.utils import AimetLogger
from aimet_common.input_... | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/channel_pruning/data_subsampler.py | from typing import List
import math
import numpy as np
import tensorflow as tf
# Import aimet specific modules
import aimet_tensorflow.utils.common
import aimet_tensorflow.utils.op.conv
from aimet_tensorflow.layer_database import Layer, LayerDatabase
from aimet_common.utils import AimetLogger
from aimet_common.input_... | 0.760562 | 0.454835 |
__version__ = '3.00'
__all__ = ['Action', 'ExecuteCmd', 'SendError', 'SendLogSmtp',
'SendSmtp', 'SetRevisionFile', 'SetToken']
import logging
import re
import smtplib
import sys, subprocess, shlex
import textwrap
logger = logging.getLogger()
class Action(object):
def __init__(self, context, t... | svnhook/actions.py | __version__ = '3.00'
__all__ = ['Action', 'ExecuteCmd', 'SendError', 'SendLogSmtp',
'SendSmtp', 'SetRevisionFile', 'SetToken']
import logging
import re
import smtplib
import sys, subprocess, shlex
import textwrap
logger = logging.getLogger()
class Action(object):
def __init__(self, context, t... | 0.651466 | 0.140042 |
from __future__ import print_function, division, absolute_import
from functools import reduce
import inspect
from itertools import product
from math import exp
from operator import add
import os
import sympy as sp
from .core import ReactionDiffusionBase
from .util.grid import padded_centers, pxci_to_bi, stencil_pxci... | chemreac/symbolic.py | from __future__ import print_function, division, absolute_import
from functools import reduce
import inspect
from itertools import product
from math import exp
from operator import add
import os
import sympy as sp
from .core import ReactionDiffusionBase
from .util.grid import padded_centers, pxci_to_bi, stencil_pxci... | 0.46223 | 0.187988 |
from easybimehlanding.decorators import lazy_property
from easybimehlanding.configuration import Configuration
from easybimehlanding.controllers.file_manager_controller import FileManagerController
from easybimehlanding.controllers.liability_doctor_insurance_controller import LiabilityDoctorInsuranceController
from... | easybimehlanding/easybimehlanding_client.py | from easybimehlanding.decorators import lazy_property
from easybimehlanding.configuration import Configuration
from easybimehlanding.controllers.file_manager_controller import FileManagerController
from easybimehlanding.controllers.liability_doctor_insurance_controller import LiabilityDoctorInsuranceController
from... | 0.507568 | 0.138841 |
from math import pi
import numpy as np
from collections import namedtuple
from math import cos, sin
from ir_sim.util import range_seg_matrix, range_cir_seg, range_seg_seg
import random
class lidar2d:
def __init__(self, range_min=0, range_max=10, angle_min=0, angle_max=pi, number=36, scan_time=0.1, noise=True, std... | ir_sim/world/components/sensor/lidar_2d.py | from math import pi
import numpy as np
from collections import namedtuple
from math import cos, sin
from ir_sim.util import range_seg_matrix, range_cir_seg, range_seg_seg
import random
class lidar2d:
def __init__(self, range_min=0, range_max=10, angle_min=0, angle_max=pi, number=36, scan_time=0.1, noise=True, std... | 0.679391 | 0.314682 |
from .hashing import hash_machine
from .serializers import ReceiptSerializer
import uuid
import time
import json
import os
def validateProof(target, proof):
"""Core utility for validating proofs
Validates the inserted proof by comparing to the provided target hash, modifies the proof's
status as ``True``... | pymerkle/validations.py | from .hashing import hash_machine
from .serializers import ReceiptSerializer
import uuid
import time
import json
import os
def validateProof(target, proof):
"""Core utility for validating proofs
Validates the inserted proof by comparing to the provided target hash, modifies the proof's
status as ``True``... | 0.856962 | 0.415195 |
from __future__ import unicode_literals
import logging
import os
from django.apps import AppConfig
from django.db.backends.signals import connection_created
from django.db.utils import DatabaseError
from kolibri.core.sqlite.pragmas import CONNECTION_PRAGMAS
from kolibri.core.sqlite.pragmas import START_PRAGMAS
from ... | kolibri/core/apps.py | from __future__ import unicode_literals
import logging
import os
from django.apps import AppConfig
from django.db.backends.signals import connection_created
from django.db.utils import DatabaseError
from kolibri.core.sqlite.pragmas import CONNECTION_PRAGMAS
from kolibri.core.sqlite.pragmas import START_PRAGMAS
from ... | 0.464416 | 0.071949 |
from __future__ import print_function
import argparse
import os
import shutil
import time
from PIL import Image, ImageOps
import glob
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torch.nn.functional as F... | extract_features.py | from __future__ import print_function
import argparse
import os
import shutil
import time
from PIL import Image, ImageOps
import glob
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torch.nn.functional as F... | 0.505371 | 0.097433 |
from typing import Dict
from torch.optim import AdamW
from knodle.trainer.knn_denoising.knn_denoising import KnnDenoisingTrainer
from knodle.trainer.knn_denoising.config import KNNConfig
from knodle_experiments.training.model import get_model
from knodle_experiments.data.preprocess import create_tfidf_input
def get... | knodle_experiments/training/knn.py | from typing import Dict
from torch.optim import AdamW
from knodle.trainer.knn_denoising.knn_denoising import KnnDenoisingTrainer
from knodle.trainer.knn_denoising.config import KNNConfig
from knodle_experiments.training.model import get_model
from knodle_experiments.data.preprocess import create_tfidf_input
def get... | 0.793986 | 0.133839 |
import json
import pytest
import ckan.model as model
from ckan.lib.create_test_data import CreateTestData
from ckan.tests.legacy import StatusCodes
class TestAction(object):
@pytest.fixture(autouse=True)
def setup_class(self, clean_db, clean_index):
CreateTestData.create()
self.sysadmin_user ... | ckan/tests/legacy/logic/test_tag.py |
import json
import pytest
import ckan.model as model
from ckan.lib.create_test_data import CreateTestData
from ckan.tests.legacy import StatusCodes
class TestAction(object):
@pytest.fixture(autouse=True)
def setup_class(self, clean_db, clean_index):
CreateTestData.create()
self.sysadmin_user ... | 0.416559 | 0.376279 |
import os
import argparse
from sklearn.feature_selection import (
SelectKBest,
mutual_info_classif,
)
from imblearn.over_sampling import RandomOverSampler
from sklearn.metrics import roc_curve
import matplotlib.pyplot as plt
import classifiers as clfs
import utils
def main(args):
print("Loading and prep... | source/model_evaluator.py | import os
import argparse
from sklearn.feature_selection import (
SelectKBest,
mutual_info_classif,
)
from imblearn.over_sampling import RandomOverSampler
from sklearn.metrics import roc_curve
import matplotlib.pyplot as plt
import classifiers as clfs
import utils
def main(args):
print("Loading and prep... | 0.831998 | 0.376881 |
import traceback
from commands.base_commands import exchanges
try:
from evennia.commands.default import help, admin, system, building, batchprocess
except Exception as err:
traceback.print_exc()
print("<<ERROR>>: Error encountered in loading default commands: %s" % err)
try:
from evennia.commands.defa... | commands/cmdsets/standard.py | import traceback
from commands.base_commands import exchanges
try:
from evennia.commands.default import help, admin, system, building, batchprocess
except Exception as err:
traceback.print_exc()
print("<<ERROR>>: Error encountered in loading default commands: %s" % err)
try:
from evennia.commands.defa... | 0.25992 | 0.0584 |
import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'An... | Tensorflow Basics/Dense_Fashion-MNIST.py | import tensorflow as tf
from tensorflow import keras
import numpy as np
import matplotlib.pyplot as plt
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'An... | 0.801159 | 0.712782 |
"""
$Id: registry.py,v 1.5 2012/09/05 16:40:43 ivan Exp $
$Date: 2012/09/05 16:40:43 $
"""
import sys
(py_v_major, py_v_minor, py_v_micro, py_v_final, py_v_serial) = sys.version_info
# To be added soon:
# "Class" : {"subPropertyOf" : "http://www.w3.org/2000/01/rdf-schema#Class"},
# "Property"... | lib/rdflib/plugins/parsers/pyMicrodata/registry.py | """
$Id: registry.py,v 1.5 2012/09/05 16:40:43 ivan Exp $
$Date: 2012/09/05 16:40:43 $
"""
import sys
(py_v_major, py_v_minor, py_v_micro, py_v_final, py_v_serial) = sys.version_info
# To be added soon:
# "Class" : {"subPropertyOf" : "http://www.w3.org/2000/01/rdf-schema#Class"},
# "Property"... | 0.344113 | 0.34161 |
# Expect peculiar motion to be 0 in all three vectors if maser is rotating at the same
# velocity as the galaxy.
from scipy import *
from ephem import *
from pylab import *
import sys
import re
from functions import *
from spec2gpec_inp import *
def buff(charOfInterest,spaceCount): # Buffer
charDiff = len(str(... | inputs/spect.py |
# Expect peculiar motion to be 0 in all three vectors if maser is rotating at the same
# velocity as the galaxy.
from scipy import *
from ephem import *
from pylab import *
import sys
import re
from functions import *
from spec2gpec_inp import *
def buff(charOfInterest,spaceCount): # Buffer
charDiff = len(str(... | 0.596433 | 0.327843 |
## Review
[In the previous notebook](https://colab.research.google.com/github/AllenDowney/BiteSizeBayes/blob/master/03_cookie.ipynb) we started with Bayes's Theorem, written like this:
$P(A|B) = P(A) ~ P(B|A) ~/~ P(B)$
And applied it to the case where we use data, $D$, to update the probability of a hypothesis, $H$... | _build/jupyter_execute/04_dice.py |
## Review
[In the previous notebook](https://colab.research.google.com/github/AllenDowney/BiteSizeBayes/blob/master/03_cookie.ipynb) we started with Bayes's Theorem, written like this:
$P(A|B) = P(A) ~ P(B|A) ~/~ P(B)$
And applied it to the case where we use data, $D$, to update the probability of a hypothesis, $H$... | 0.9095 | 0.982457 |
from mock import Mock, patch
from unittest import TestCase
from samtranslator.model.eventsources.cloudwatchlogs import CloudWatchLogs
class CloudWatchLogsEventSource(TestCase):
def setUp(self):
self.logical_id = 'LogProcessor'
self.cloudwatch_logs_event_source = CloudWatchLogs(self.logical_id)
... | tests/model/eventsources/test_cloudwatchlogs_event_source.py | from mock import Mock, patch
from unittest import TestCase
from samtranslator.model.eventsources.cloudwatchlogs import CloudWatchLogs
class CloudWatchLogsEventSource(TestCase):
def setUp(self):
self.logical_id = 'LogProcessor'
self.cloudwatch_logs_event_source = CloudWatchLogs(self.logical_id)
... | 0.72487 | 0.161155 |
# Manage Jenkins XML config file output.
import hashlib
import pkg_resources
from xml.dom import minidom
import xml.etree.ElementTree as XML
from jenkins_jobs import errors
__all__ = [
"XmlJobGenerator",
"XmlJob"
]
def remove_ignorable_whitespace(node):
"""Remove insignificant whitespace from XML node... | jenkins_jobs/xml_config.py |
# Manage Jenkins XML config file output.
import hashlib
import pkg_resources
from xml.dom import minidom
import xml.etree.ElementTree as XML
from jenkins_jobs import errors
__all__ = [
"XmlJobGenerator",
"XmlJob"
]
def remove_ignorable_whitespace(node):
"""Remove insignificant whitespace from XML node... | 0.616474 | 0.28597 |
from mongoengine import (
Document,
UUIDField,
StringField,
BooleanField,
ReferenceField,
DateTimeField,
IntField,
EmailField,
FloatField,
)
class Users(Document):
public_id = UUIDField(binary=False, required=True, unique=True)
username = StringField(max_length=50, unique=T... | api_backend_server/web_app/models/__init__.py | from mongoengine import (
Document,
UUIDField,
StringField,
BooleanField,
ReferenceField,
DateTimeField,
IntField,
EmailField,
FloatField,
)
class Users(Document):
public_id = UUIDField(binary=False, required=True, unique=True)
username = StringField(max_length=50, unique=T... | 0.386763 | 0.161056 |
import six
from bromine.exceptions import (NoSuchElementException,
MultipleElementsFoundError,
StaleElementReferenceException)
from .base import Element
from .locator import Locator, XPath
from ..utils.image import ScreenshotFromPngBytes
from .scroll impo... | src/bromine/element/web_element.py | import six
from bromine.exceptions import (NoSuchElementException,
MultipleElementsFoundError,
StaleElementReferenceException)
from .base import Element
from .locator import Locator, XPath
from ..utils.image import ScreenshotFromPngBytes
from .scroll impo... | 0.568775 | 0.149935 |
from abc import ABCMeta, abstractmethod
import mmcv
import numpy as np
import pycocotools.mask as maskUtils
import torch.nn as nn
from mmdet.core import auto_fp16, get_classes, tensor2imgs
from mmdet.utils import print_log
import cv2
import random
import glob
CLASSES = ('person', 'bicycle', 'car', 'motorcycle', 'ai... | mmdet/models/detectors/base.py | from abc import ABCMeta, abstractmethod
import mmcv
import numpy as np
import pycocotools.mask as maskUtils
import torch.nn as nn
from mmdet.core import auto_fp16, get_classes, tensor2imgs
from mmdet.utils import print_log
import cv2
import random
import glob
CLASSES = ('person', 'bicycle', 'car', 'motorcycle', 'ai... | 0.794863 | 0.391988 |
import copy
import random
from .hand import TableCards, TakenCards, Hand
from .deck import Deck
class GameStateException(Exception):
pass
class GameState(object):
"""The GameState specifies the complete state of the game, including the
player's hands, cards on the table and scoring.
"""
def __... | gostop/core/gamestate.py | import copy
import random
from .hand import TableCards, TakenCards, Hand
from .deck import Deck
class GameStateException(Exception):
pass
class GameState(object):
"""The GameState specifies the complete state of the game, including the
player's hands, cards on the table and scoring.
"""
def __... | 0.728941 | 0.256471 |
import numpy as np
from ..util import real_numerical_types, sequence_types, create_hdf5_dataset,\
get_hdf5_value
from .LoglikelihoodWithData import LoglikelihoodWithData
from .LoglikelihoodWithModel import LoglikelihoodWithModel
class GammaLoglikelihood(LoglikelihoodWithModel):
"""
Class which evaluates a ... | pylinex/loglikelihood/GammaLoglikelihood.py | import numpy as np
from ..util import real_numerical_types, sequence_types, create_hdf5_dataset,\
get_hdf5_value
from .LoglikelihoodWithData import LoglikelihoodWithData
from .LoglikelihoodWithModel import LoglikelihoodWithModel
class GammaLoglikelihood(LoglikelihoodWithModel):
"""
Class which evaluates a ... | 0.917978 | 0.77437 |
from textwrap import dedent
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
from sqlalchemy import exc, sql
from sqlalchemy.engine.base import Connection
from sqlalchemy.engine.default import DefaultDialect, DefaultExecutionContext
from sqlalchemy.engine.url import URL
from trino import dbapi a... | trino/sqlalchemy/dialect.py | from textwrap import dedent
from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple
from sqlalchemy import exc, sql
from sqlalchemy.engine.base import Connection
from sqlalchemy.engine.default import DefaultDialect, DefaultExecutionContext
from sqlalchemy.engine.url import URL
from trino import dbapi a... | 0.873066 | 0.126812 |
from __future__ import absolute_import
import traceback
from ....... import jni
from .......jvm.jframe import JFrame
from .......jvm.jhost import JHost
from .......jvm.java import throwJavaException
from ......_jvm import get_jvm
from ......_jvm import jni_enter, jni_exit
from ......_jenv impor... | src/jt/javabridge/_java/org/cellprofiler/javabridge/reflect/ProxyHandler.py |
from __future__ import absolute_import
import traceback
from ....... import jni
from .......jvm.jframe import JFrame
from .......jvm.jhost import JHost
from .......jvm.java import throwJavaException
from ......_jvm import get_jvm
from ......_jvm import jni_enter, jni_exit
from ......_jenv impor... | 0.502686 | 0.055336 |
import cohesity_management_sdk.models.virtual_disk_id_information
import cohesity_management_sdk.models.protection_source
class VirtualDiskMappingResponse(object):
"""Implementation of the 'VirtualDiskMappingResponse' model.
Specifies information about virtual disks where a user can specify
mappings
... | cohesity_management_sdk/models/virtual_disk_mapping_response.py |
import cohesity_management_sdk.models.virtual_disk_id_information
import cohesity_management_sdk.models.protection_source
class VirtualDiskMappingResponse(object):
"""Implementation of the 'VirtualDiskMappingResponse' model.
Specifies information about virtual disks where a user can specify
mappings
... | 0.816662 | 0.220238 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from src.model.nets.base_net import BaseNet
class DenseHighRes3DNet(BaseNet):
def __init__(self, in_channels, out_channels):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.... | src/model/nets/dense_highres3d_net.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from src.model.nets.base_net import BaseNet
class DenseHighRes3DNet(BaseNet):
def __init__(self, in_channels, out_channels):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.... | 0.948799 | 0.335324 |
from __future__ import print_function
import argparse
import os
import sys
from json import loads
from math import ceil
from subprocess import Popen, PIPE
def coverage_buckets():
yield '0%'
yield '1-9%'
for start in range(10, 91, 10):
yield '{0}-{1}%'.format(start, start + 9)
yield '100%'
def locstats_ou... | llvm/utils/llvm-locstats/llvm-locstats.py |
from __future__ import print_function
import argparse
import os
import sys
from json import loads
from math import ceil
from subprocess import Popen, PIPE
def coverage_buckets():
yield '0%'
yield '1-9%'
for start in range(10, 91, 10):
yield '{0}-{1}%'.format(start, start + 9)
yield '100%'
def locstats_ou... | 0.301876 | 0.148726 |
import re
import numpy as np
from os.path import join
from epub_conversion import convert_wiki_to_lines
from epub_conversion.wiki_decoder import almost_smart_open
from .wikipedia_language_codes import LANGUAGE_CODES
from .file import true_exists
from .bash import execute_bash
from .successor_mask import (
load_re... | wikidata_linker_utils_src/src/python/wikidata_linker_utils/wikipedia.py | import re
import numpy as np
from os.path import join
from epub_conversion import convert_wiki_to_lines
from epub_conversion.wiki_decoder import almost_smart_open
from .wikipedia_language_codes import LANGUAGE_CODES
from .file import true_exists
from .bash import execute_bash
from .successor_mask import (
load_re... | 0.458591 | 0.232332 |
import sys
sys.path.append("../../..")
from scipy.linalg import null_space
import copy
import numpy as np
from numpy.linalg import matrix_rank, matrix_power, cholesky, inv
import torch
from torch.optim import Adam
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
import util.geometry_util as ge... | tests/experiments/optimization/excavator.py | import sys
sys.path.append("../../..")
from scipy.linalg import null_space
import copy
import numpy as np
from numpy.linalg import matrix_rank, matrix_power, cholesky, inv
import torch
from torch.optim import Adam
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
import util.geometry_util as ge... | 0.684897 | 0.499023 |
import sys
import os
import time
import math
import numpy as np
import itertools
import struct # get_image_size
import imghdr # get_image_size
#<annotation>
# <filename>000001</filename>
# <source>
# <database>Unknown</database>
# </source>
# <size>
# <width>353</width>
# <height>5... | tool/make_annotation.py | import sys
import os
import time
import math
import numpy as np
import itertools
import struct # get_image_size
import imghdr # get_image_size
#<annotation>
# <filename>000001</filename>
# <source>
# <database>Unknown</database>
# </source>
# <size>
# <width>353</width>
# <height>5... | 0.051534 | 0.096663 |
import argparse
import sys
import textwrap
from importlib import import_module
class CLIError(Exception):
"""Error for CLI commands.
A subcommand may raise this. The message will be forwarded to
the error() method of the argument parser."""
# Important: Following any change to command-line parameters,... | mgetool/cli/main.py | import argparse
import sys
import textwrap
from importlib import import_module
class CLIError(Exception):
"""Error for CLI commands.
A subcommand may raise this. The message will be forwarded to
the error() method of the argument parser."""
# Important: Following any change to command-line parameters,... | 0.31279 | 0.133443 |
from typing import List, Optional, Callable
from fastcore.all import is_listy, store_attr
import timeit
from torch import nn, Tensor
from .callback import Callback
from .data_callbacks import TargReplace
from ..models.model_builder import ModelBuilder
from ..models.model import Model
from ...utils.misc import is_part... | lumin/nn/callbacks/adversarial_callbacks.py | from typing import List, Optional, Callable
from fastcore.all import is_listy, store_attr
import timeit
from torch import nn, Tensor
from .callback import Callback
from .data_callbacks import TargReplace
from ..models.model_builder import ModelBuilder
from ..models.model import Model
from ...utils.misc import is_part... | 0.904318 | 0.432423 |
import numpy as np
from alphaomega.utils.exceptions import WrongDimension, WrongAttribute
class PCA:
"""
Usage: PCA is a dimensionality reductino technique. Use this class to apply PCA to your features.
"""
def __init__(self):
self.__new_data = 2
self.__transform = None
self.__... | alphaomega/ml/dimension_reduction/pca.py | import numpy as np
from alphaomega.utils.exceptions import WrongDimension, WrongAttribute
class PCA:
"""
Usage: PCA is a dimensionality reductino technique. Use this class to apply PCA to your features.
"""
def __init__(self):
self.__new_data = 2
self.__transform = None
self.__... | 0.893536 | 0.594257 |
import datetime
import json
import random
import pytest
import requests
from pylenium import Pylenium
from tests.pages.paybc import PayBCPage
from tests.utilities.settings import get_path_settings, get_settings, get_test_data
class TestPayment:
"""Payment test suite."""
# Only excute these tests by main fl... | integration-testing/tests/suites/test_payment.py | import datetime
import json
import random
import pytest
import requests
from pylenium import Pylenium
from tests.pages.paybc import PayBCPage
from tests.utilities.settings import get_path_settings, get_settings, get_test_data
class TestPayment:
"""Payment test suite."""
# Only excute these tests by main fl... | 0.553747 | 0.22378 |
import re
from ..punctuation import ALPHA_LOWER, ALPHA
from ...symbols import ORTH, NORM
_exc = {}
_abbr_period_exc = [
{ORTH: "A.B.D.", NORM: "Amerika"},
{ORTH: "Alb.", NORM: "albay"},
{ORTH: "Ank.", NORM: "Ankara"},
{ORTH: "Ar.Gör."},
{ORTH: "Arş.Gör."},
{ORTH: "Asb.", NORM: "astsubay"},
... | spacy/lang/tr/tokenizer_exceptions.py | import re
from ..punctuation import ALPHA_LOWER, ALPHA
from ...symbols import ORTH, NORM
_exc = {}
_abbr_period_exc = [
{ORTH: "A.B.D.", NORM: "Amerika"},
{ORTH: "Alb.", NORM: "albay"},
{ORTH: "Ank.", NORM: "Ankara"},
{ORTH: "Ar.Gör."},
{ORTH: "Arş.Gör."},
{ORTH: "Asb.", NORM: "astsubay"},
... | 0.303629 | 0.386358 |
import os
import tempfile
import pytest
from flytekitplugins.awssagemaker.distributed_training import setup_envars_for_testing
from flytekitplugins.awssagemaker.training import SagemakerBuiltinAlgorithmsTask, SagemakerTrainingJobConfig
import flytekit
from flytekit import task
from flytekit.common.tasks.sdk_runnable ... | plugins/tests/awssagemaker/test_training.py | import os
import tempfile
import pytest
from flytekitplugins.awssagemaker.distributed_training import setup_envars_for_testing
from flytekitplugins.awssagemaker.training import SagemakerBuiltinAlgorithmsTask, SagemakerTrainingJobConfig
import flytekit
from flytekit import task
from flytekit.common.tasks.sdk_runnable ... | 0.496338 | 0.32302 |
import re
import pprint
import subprocess
descs = {
"double": "Double",
"galvanic_mock": "Galvanic-mock",
"mock_derive": "Mock_Derive",
"mock_it": "Mock-it",
"mockall": "Mockall",
"mockers": "Mockers",
"mockiato": "Mockiato",
"mocktopus": "Mocktopus",
"pseudo": "Pseudo",
"simul... | compare.py |
import re
import pprint
import subprocess
descs = {
"double": "Double",
"galvanic_mock": "Galvanic-mock",
"mock_derive": "Mock_Derive",
"mock_it": "Mock-it",
"mockall": "Mockall",
"mockers": "Mockers",
"mockiato": "Mockiato",
"mocktopus": "Mocktopus",
"pseudo": "Pseudo",
"simul... | 0.551332 | 0.292302 |
import copy
import os
import shlex
import stat
import tempfile
from contextlib import contextmanager
from django.test import override_settings
__all__ = ("heroku_cli", "no_heroku_connect_write_restrictions")
@contextmanager
def heroku_cli(stdout="", stderr="", exit_code=0):
r"""
Context manager to mock the ... | heroku_connect/test/utils.py | import copy
import os
import shlex
import stat
import tempfile
from contextlib import contextmanager
from django.test import override_settings
__all__ = ("heroku_cli", "no_heroku_connect_write_restrictions")
@contextmanager
def heroku_cli(stdout="", stderr="", exit_code=0):
r"""
Context manager to mock the ... | 0.422266 | 0.122025 |
import numpy as np
import torch
import torch.nn as nn
import models.resnetM as resnetM
from .CLSTM import ConvLSTM
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
if type(in_planes) == np.int64:
in_planes = np.asscalar(in_planes)
return nn.Sequential(
nn.Conv2... | models/PCLNet.py | import numpy as np
import torch
import torch.nn as nn
import models.resnetM as resnetM
from .CLSTM import ConvLSTM
def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1):
if type(in_planes) == np.int64:
in_planes = np.asscalar(in_planes)
return nn.Sequential(
nn.Conv2... | 0.911321 | 0.519217 |
import os
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import Reshape
from tensorflow.keras.models import Mod... | Chapter7_Autoencoder/mnistDenoiseImages.py | import os
import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras.layers import Activation
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Flatten
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import Reshape
from tensorflow.keras.models import Mod... | 0.693992 | 0.397295 |
from rx.core import Observer, ObservableBase, Disposable
from rx.subjects import Subject
from rx.disposables import AnonymousDisposable
from rx.concurrency import current_thread_scheduler
from rx.core.notification import OnCompleted, OnError, OnNext
class ControlledSubject(ObservableBase, Observer):
def __init__(... | rx/backpressure/controlledsubject.py | from rx.core import Observer, ObservableBase, Disposable
from rx.subjects import Subject
from rx.disposables import AnonymousDisposable
from rx.concurrency import current_thread_scheduler
from rx.core.notification import OnCompleted, OnError, OnNext
class ControlledSubject(ObservableBase, Observer):
def __init__(... | 0.730963 | 0.102664 |
import functools
from peewee import fn
from playhouse.shortcuts import model_to_dict
from .model import NdsTrialStats, NdsTrialConfig
def query_nds_trial_stats(model_family, proposer, generator, model_spec, cell_spec, dataset,
num_epochs=None, reduction=None, include_intermediates=False):
... | src/sdk/pynni/nni/nas/benchmarks/nds/query.py | import functools
from peewee import fn
from playhouse.shortcuts import model_to_dict
from .model import NdsTrialStats, NdsTrialConfig
def query_nds_trial_stats(model_family, proposer, generator, model_spec, cell_spec, dataset,
num_epochs=None, reduction=None, include_intermediates=False):
... | 0.806205 | 0.273262 |
"""CLI Backend for the Node Stepper Part of the Debugger."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import numpy as np # pylint: disable=unused-import
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorfl... | tensorflow/python/debug/cli/stepper_cli.py | """CLI Backend for the Node Stepper Part of the Debugger."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import numpy as np # pylint: disable=unused-import
from six.moves import xrange # pylint: disable=redefined-builtin
from tensorfl... | 0.85928 | 0.196036 |
import psycopg2
import json
import sys
import psycopg2.extras
def connect_postgres(logger):
try:
key = ""
with open('db/key.json', 'r') as f:
key = json.load(f)
conn = psycopg2.connect(
host=key["host"],
port= key["port"],
user=key["user"],
... | app/db/postgresql.py | import psycopg2
import json
import sys
import psycopg2.extras
def connect_postgres(logger):
try:
key = ""
with open('db/key.json', 'r') as f:
key = json.load(f)
conn = psycopg2.connect(
host=key["host"],
port= key["port"],
user=key["user"],
... | 0.171442 | 0.074534 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import ray
import numpy as np
from runner import RunnerThread, process_rollout
from LSTM import LSTMPolicy
import tensorflow as tf
import six.moves.queue as queue
import gym
import sys
import os
from datetime i... | examples/a3c/driver.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import ray
import numpy as np
from runner import RunnerThread, process_rollout
from LSTM import LSTMPolicy
import tensorflow as tf
import six.moves.queue as queue
import gym
import sys
import os
from datetime i... | 0.578448 | 0.107954 |
import datetime
import pytest
import recurrence
from django.conf import settings
from django.contrib.auth import get_user_model
from django.utils import timezone
from rest_framework.test import APIClient
from allocation.models import AllocationRequest
from applications.models import (
Address,
Application,
... | api/tests/conftest.py | import datetime
import pytest
import recurrence
from django.conf import settings
from django.contrib.auth import get_user_model
from django.utils import timezone
from rest_framework.test import APIClient
from allocation.models import AllocationRequest
from applications.models import (
Address,
Application,
... | 0.498779 | 0.353456 |
# Copyright 2021 Tampere University and VTT Technical Research Centre of Finland
# This software was developed as a part of the ProCemPlus project: https://www.senecc.fi/projects/procemplus
# This source code is licensed under the MIT license. See LICENSE in the repository root directory.
# Author(s): <NAME> <<EMAIL>>... | economic_dispatch/simulation/start.py |
# Copyright 2021 Tampere University and VTT Technical Research Centre of Finland
# This software was developed as a part of the ProCemPlus project: https://www.senecc.fi/projects/procemplus
# This source code is licensed under the MIT license. See LICENSE in the repository root directory.
# Author(s): <NAME> <<EMAIL>>... | 0.813646 | 0.28531 |
from __future__ import absolute_import
from dp_tornado.engine.helper import Helper as dpHelper
try:
from PIL import Image
except ImportError:
Image = None
try:
from PIL import ImageDraw
except ImportError:
ImageDraw = None
try:
from PIL import ImageOps
except ImportError:
ImageOps = None
... | dp_tornado/helper/io/image/driver/pillow.py |
from __future__ import absolute_import
from dp_tornado.engine.helper import Helper as dpHelper
try:
from PIL import Image
except ImportError:
Image = None
try:
from PIL import ImageDraw
except ImportError:
ImageDraw = None
try:
from PIL import ImageOps
except ImportError:
ImageOps = None
... | 0.738669 | 0.204421 |
import unittest
from stocal import MassAction, Event, ReactionRule, Process
class Dilution(ReactionRule):
"""Dilution rule"""
Transition = MassAction
def novel_reactions(self, species):
yield self.Transition([species], [], 0.001)
class Polymerization(ReactionRule):
"""Polymerization rule"""
... | stocal/tests/test_tutorial.py | import unittest
from stocal import MassAction, Event, ReactionRule, Process
class Dilution(ReactionRule):
"""Dilution rule"""
Transition = MassAction
def novel_reactions(self, species):
yield self.Transition([species], [], 0.001)
class Polymerization(ReactionRule):
"""Polymerization rule"""
... | 0.571408 | 0.61231 |
import tensorflow as tf
from Models.BasicModel import BasicModel
class Model(BasicModel):
def __init__(self,
learning_rate,
init_word_embed,
init_idiom_embed,
size_embed=200,
num_units=100, # make sure that num_units = size_embed ... | Codes for baseline/Models/SAR.py | import tensorflow as tf
from Models.BasicModel import BasicModel
class Model(BasicModel):
def __init__(self,
learning_rate,
init_word_embed,
init_idiom_embed,
size_embed=200,
num_units=100, # make sure that num_units = size_embed ... | 0.854763 | 0.420183 |
import argparse
import subprocess
import re
parser = argparse.ArgumentParser(
description='Applies a template DEF to a user DEF.')
parser.add_argument('--templateDEF', '-t',required=True,
help='Template DEF')
parser.add_argument('--userDEF', '-u',required=True,
help='User ... | scripts/apply_def_template.py |
import argparse
import subprocess
import re
parser = argparse.ArgumentParser(
description='Applies a template DEF to a user DEF.')
parser.add_argument('--templateDEF', '-t',required=True,
help='Template DEF')
parser.add_argument('--userDEF', '-u',required=True,
help='User ... | 0.139191 | 0.084833 |
from .config.config import Config
from .termui.alignment import TopLeftAnchor, Dimension, CenterAnchor
from .session import Session
from .termui.bar_graph import BarGraph
from .termui.color import Color, Palette8Bit
from .termui.control import Border, BorderStyle
from .termui.dialog import DialogControl
DefaultAnchor ... | src/awsc/common.py | from .config.config import Config
from .termui.alignment import TopLeftAnchor, Dimension, CenterAnchor
from .session import Session
from .termui.bar_graph import BarGraph
from .termui.color import Color, Palette8Bit
from .termui.control import Border, BorderStyle
from .termui.dialog import DialogControl
DefaultAnchor ... | 0.693473 | 0.053576 |
import atexit
import html
import configparser
import os
import pickle
import re
import time
import urllib.error
import urllib.request
import praw
HTTPRE = re.compile('http[s]?://', re.IGNORECASE)
DOMRE = re.compile('\.\w{2,20}', re.IGNORECASE)
BLACKLIST = ['LE_TROLLFACEXD', 'figuratively_hilter', 'Text_Reader_Bot']
... | bot.py | import atexit
import html
import configparser
import os
import pickle
import re
import time
import urllib.error
import urllib.request
import praw
HTTPRE = re.compile('http[s]?://', re.IGNORECASE)
DOMRE = re.compile('\.\w{2,20}', re.IGNORECASE)
BLACKLIST = ['LE_TROLLFACEXD', 'figuratively_hilter', 'Text_Reader_Bot']
... | 0.134264 | 0.08472 |
from dal import autocomplete
from dal_select2.widgets import Select2Multiple
from dal_select2_taggit.widgets import TaggitSelect2
from django.db import models
from django.utils import timezone
from django.utils.text import slugify
from modelcluster.contrib.taggit import ClusterTaggableManager
from modelcluster.fields i... | code/flis_horison_scanning/models.py | from dal import autocomplete
from dal_select2.widgets import Select2Multiple
from dal_select2_taggit.widgets import TaggitSelect2
from django.db import models
from django.utils import timezone
from django.utils.text import slugify
from modelcluster.contrib.taggit import ClusterTaggableManager
from modelcluster.fields i... | 0.547948 | 0.202897 |
import argparse
def AddCommonArguments(parser):
"""Adds arguments common to parsers.
Args:
parser: ArgumentParser object, used to parse flags.
"""
parser.add_argument("--email",
type=str,
dest="email",
help="Email account... | public/acloud_common.py | import argparse
def AddCommonArguments(parser):
"""Adds arguments common to parsers.
Args:
parser: ArgumentParser object, used to parse flags.
"""
parser.add_argument("--email",
type=str,
dest="email",
help="Email account... | 0.613121 | 0.101589 |
# -*- coding: utf-8 -*-
"""
Provides entry-level logic for building the CLI. Commands and heavy-lifting logic should be in their own module.
"""
import click
from dcae_cli import util
from dcae_cli.commands.catalog import catalog
from dcae_cli.commands.component import component
from dcae_cli.commands.data_format imp... | dcae-cli/dcae_cli/cli.py |
# -*- coding: utf-8 -*-
"""
Provides entry-level logic for building the CLI. Commands and heavy-lifting logic should be in their own module.
"""
import click
from dcae_cli import util
from dcae_cli.commands.catalog import catalog
from dcae_cli.commands.component import component
from dcae_cli.commands.data_format imp... | 0.279927 | 0.091423 |
from grr.gui import renderers
from grr.lib import utils
class HexView(renderers.TemplateRenderer):
"""Display a HexView of a file.
Internal State:
- aff4_path: The name of the aff4 object we are viewing now.
- age: The version of the AFF4 object to display.
"""
table_width = 32
total_size = 0
# ... | gui/plugins/fileview_widgets.py | from grr.gui import renderers
from grr.lib import utils
class HexView(renderers.TemplateRenderer):
"""Display a HexView of a file.
Internal State:
- aff4_path: The name of the aff4 object we are viewing now.
- age: The version of the AFF4 object to display.
"""
table_width = 32
total_size = 0
# ... | 0.842248 | 0.253838 |
import os
import pytest
import time
import unittest
import numpy as np
import tensorflow as tf
from tensorforce import Agent, Environment, util
from test.unittest_base import UnittestBase
class TestSaving(UnittestBase, unittest.TestCase):
min_timesteps = 3
require_observe = True
directory = 'test/tes... | test/test_saving.py |
import os
import pytest
import time
import unittest
import numpy as np
import tensorflow as tf
from tensorforce import Agent, Environment, util
from test.unittest_base import UnittestBase
class TestSaving(UnittestBase, unittest.TestCase):
min_timesteps = 3
require_observe = True
directory = 'test/tes... | 0.5 | 0.246808 |
from future import standard_library
standard_library.install_aliases()
import os
from os.path import join
import json
import unicodecsv
import urllib.parse
from openelex import PROJECT_ROOT
from openelex.base.datasource import BaseDatasource
class Datasource(BaseDatasource):
# PUBLIC INTERFACE
def mappings(s... | openelex/us/oh/datasource.py | from future import standard_library
standard_library.install_aliases()
import os
from os.path import join
import json
import unicodecsv
import urllib.parse
from openelex import PROJECT_ROOT
from openelex.base.datasource import BaseDatasource
class Datasource(BaseDatasource):
# PUBLIC INTERFACE
def mappings(s... | 0.387459 | 0.164953 |
import os
import colorutils
import math
from collections import defaultdict
from pathlib import Path
from colorutils import Color as Colour
from datetime import datetime
ST_OUTPUT = {
"Merged Situations": [],
"Loglikelihood": float,
"Mean Posterior Probabilities": [],
}
class Util:
@staticmethod
... | src/cegpy/utilities/util.py | import os
import colorutils
import math
from collections import defaultdict
from pathlib import Path
from colorutils import Color as Colour
from datetime import datetime
ST_OUTPUT = {
"Merged Situations": [],
"Loglikelihood": float,
"Mean Posterior Probabilities": [],
}
class Util:
@staticmethod
... | 0.686685 | 0.380759 |
import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
from tkinter import Menu
from tkinter import Spinbox
from tkinter import messagebox as mBox
# 由于tkinter中没有ToolTip功能,所以自定义这个功能如下
class ToolTip(object):
def __init__(self, widget):
self.widget = widget
self.tip... | example_menu.py | import tkinter as tk
from tkinter import ttk
from tkinter import scrolledtext
from tkinter import Menu
from tkinter import Spinbox
from tkinter import messagebox as mBox
# 由于tkinter中没有ToolTip功能,所以自定义这个功能如下
class ToolTip(object):
def __init__(self, widget):
self.widget = widget
self.tip... | 0.301979 | 0.076132 |
from gym_TD.utils import logger
import time
def PPO_train_single(ppo, state, action, next_state, reward, done, info, writer, title, config):
if (action != info['RealAction']).any():
reward -= 0.3
ppo.record_single(state, action, reward, done)
if ppo.len_trajectory % config.horizon == 0:
ppo... | train/PPO/Callbacks.py | from gym_TD.utils import logger
import time
def PPO_train_single(ppo, state, action, next_state, reward, done, info, writer, title, config):
if (action != info['RealAction']).any():
reward -= 0.3
ppo.record_single(state, action, reward, done)
if ppo.len_trajectory % config.horizon == 0:
ppo... | 0.407451 | 0.332121 |
"""
"""
import numpy as np
import pandas as pd
from ._state import State
from ._metric import Metric
from biosteam import speed_up
__all__ = ('Model',)
# %% Functions
var_indices = lambda vars: [var.index for var in vars]
var_columns = lambda vars, names=None: indices_to_multiindex(var_indices(vars), names)
indices_... | biosteam/evaluation/_model.py | """
"""
import numpy as np
import pandas as pd
from ._state import State
from ._metric import Metric
from biosteam import speed_up
__all__ = ('Model',)
# %% Functions
var_indices = lambda vars: [var.index for var in vars]
var_columns = lambda vars, names=None: indices_to_multiindex(var_indices(vars), names)
indices_... | 0.87035 | 0.387372 |
from mock import sentinel
import testtools
from apmecclient.common import exceptions
from apmecclient.apmec.v1_0.meo import vim_utils
class TestVIMUtils(testtools.TestCase):
def test_args2body_vim(self):
config_param = {'project_name': sentinel.prj_name,
'username': sentinel.us... | apmecclient/tests/unit/vm/test_vim_utils.py |
from mock import sentinel
import testtools
from apmecclient.common import exceptions
from apmecclient.apmec.v1_0.meo import vim_utils
class TestVIMUtils(testtools.TestCase):
def test_args2body_vim(self):
config_param = {'project_name': sentinel.prj_name,
'username': sentinel.us... | 0.437343 | 0.127843 |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Removing unique constraint on 'Tag', fields ['db_key', 'db_category']
db.delete_unique(u'typecl... | src/typeclasses/migrations/0009_auto__del_unique_tag_db_key_db_category__add_unique_tag_db_key_db_cate.py | from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Removing unique constraint on 'Tag', fields ['db_key', 'db_category']
db.delete_unique(u'typecl... | 0.546496 | 0.143248 |
import sys
if sys.version_info[0] < 2 or sys.version_info[1] < 6:
print "Sorry, mqstat requires at least Python 2.6."
sys.exit(1)
import httplib
import urllib
import urlparse
import base64
import json
import os
import socket
import time
from time import localtime, strftime
VERSION = '3.1.5'
options = { "hos... | vendor/MNLogger/docs/tools/stats.py |
import sys
if sys.version_info[0] < 2 or sys.version_info[1] < 6:
print "Sorry, mqstat requires at least Python 2.6."
sys.exit(1)
import httplib
import urllib
import urlparse
import base64
import json
import os
import socket
import time
from time import localtime, strftime
VERSION = '3.1.5'
options = { "hos... | 0.137417 | 0.078819 |
from pathlib import Path
from vunit import VUnit
ROOT = Path(__file__).parent
VU = VUnit.from_argv()
LIB = VU.add_library("lib")
LIB.add_source_files(ROOT / "*.vhd")
def configure_tb_with_generic_config():
"""
Configure tb_with_generic_config test bench
"""
bench = LIB.entity("tb_with_generic_confi... | tests/acceptance/artificial/vhdl/run.py |
from pathlib import Path
from vunit import VUnit
ROOT = Path(__file__).parent
VU = VUnit.from_argv()
LIB = VU.add_library("lib")
LIB.add_source_files(ROOT / "*.vhd")
def configure_tb_with_generic_config():
"""
Configure tb_with_generic_config test bench
"""
bench = LIB.entity("tb_with_generic_confi... | 0.535341 | 0.163546 |
import logging as log
from milvus import *
from common.config import MILVUS_HOST, MILVUS_PORT, VECTOR_DIMENSION
import traceback
def milvus_client():
try:
milvus = Milvus(MILVUS_HOST, MILVUS_PORT)
return milvus
except Exception as e:
log.error(e)
log.error(traceback.format_exc(... | solutions/mols_search/mols-search-webserver/src/indexer/index.py | import logging as log
from milvus import *
from common.config import MILVUS_HOST, MILVUS_PORT, VECTOR_DIMENSION
import traceback
def milvus_client():
try:
milvus = Milvus(MILVUS_HOST, MILVUS_PORT)
return milvus
except Exception as e:
log.error(e)
log.error(traceback.format_exc(... | 0.322099 | 0.101947 |
from ..context import Context
from ..ext import priority
class B3HTTPPropagator:
"""b3 compatible propagator"""
SINGLE_HEADER_KEY = 'b3'
TRACE_ID_KEY = 'x-b3-traceid'
SPAN_ID_KEY = 'x-b3-spanid'
SAMPLED_KEY = 'x-b3-sampled'
FLAGS_KEY = '<KEY>'
_SAMPLE_PROPAGATE_VALUES = set(['1', 'True',... | ddtrace/propagation/b3.py |
from ..context import Context
from ..ext import priority
class B3HTTPPropagator:
"""b3 compatible propagator"""
SINGLE_HEADER_KEY = 'b3'
TRACE_ID_KEY = 'x-b3-traceid'
SPAN_ID_KEY = 'x-b3-spanid'
SAMPLED_KEY = 'x-b3-sampled'
FLAGS_KEY = '<KEY>'
_SAMPLE_PROPAGATE_VALUES = set(['1', 'True',... | 0.616359 | 0.138229 |
import os
import json
import tensorflow as tf
from transformers import TFBertPreTrainedModel, TFBertMainLayer, BertTokenizer
from transformers.modeling_tf_utils import get_initializer
import logging
logging.getLogger("transformers.tokenization_utils").setLevel(logging.ERROR)
class TFBertForMultiClassification(TFBertP... | 2-Inferencing/score.py | import os
import json
import tensorflow as tf
from transformers import TFBertPreTrainedModel, TFBertMainLayer, BertTokenizer
from transformers.modeling_tf_utils import get_initializer
import logging
logging.getLogger("transformers.tokenization_utils").setLevel(logging.ERROR)
class TFBertForMultiClassification(TFBertP... | 0.759582 | 0.136608 |
import os
import argparse
import numpy
import pandas
import json
import matplotlib.pyplot as plt
from narps import Narps, hypnums
hypnames = ['%d' % i for i in hypnums]
hypnames[:2] = ['1/3', '2/4']
def get_similarity_summary(narps, corrtype='spearman'):
corr_summary = []
for i, hyp in enumerate(hypnums):
... | ImageAnalyses/GetMeanSimilarity.py | import os
import argparse
import numpy
import pandas
import json
import matplotlib.pyplot as plt
from narps import Narps, hypnums
hypnames = ['%d' % i for i in hypnums]
hypnames[:2] = ['1/3', '2/4']
def get_similarity_summary(narps, corrtype='spearman'):
corr_summary = []
for i, hyp in enumerate(hypnums):
... | 0.254509 | 0.281521 |
import spacy
from allennlp.common import Params
from allennlp.common.testing import AllenNlpTestCase
from allennlp.data.tokenizers import Token, SpacyTokenizer
class TestSpacyTokenizer(AllenNlpTestCase):
def setup_method(self):
super().setup_method()
self.word_tokenizer = SpacyTokenizer()
de... | tests/data/tokenizers/spacy_tokenizer_test.py | import spacy
from allennlp.common import Params
from allennlp.common.testing import AllenNlpTestCase
from allennlp.data.tokenizers import Token, SpacyTokenizer
class TestSpacyTokenizer(AllenNlpTestCase):
def setup_method(self):
super().setup_method()
self.word_tokenizer = SpacyTokenizer()
de... | 0.5794 | 0.577138 |
import os
from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor
from io import BytesIO
from logging import getLogger as get_logger
from math import ceil
from statistics import mean
from typing import Optional
from megfile.errors import S3FileChangedError, patch_method, raise_s3_error, s... | megfile/lib/s3_prefetch_reader.py | import os
from collections import OrderedDict
from concurrent.futures import ThreadPoolExecutor
from io import BytesIO
from logging import getLogger as get_logger
from math import ceil
from statistics import mean
from typing import Optional
from megfile.errors import S3FileChangedError, patch_method, raise_s3_error, s... | 0.793066 | 0.241165 |
from sys import exit
import math
from TALinputs import TALinput
from multilanguage import Env, Lang, TALcolors
import LightCoinUtilities as Utilities
# METADATA OF THIS TAL_SERVICE:
problem="light_coin"
service="check_dynamic_strategy"
args_list = [
('n', int),
('version', str),
('goal', str),
('feed... | example_problems/tutorial/light_coin/services/check_dynamic_strategy/check_dynamic_strategy_server.py | from sys import exit
import math
from TALinputs import TALinput
from multilanguage import Env, Lang, TALcolors
import LightCoinUtilities as Utilities
# METADATA OF THIS TAL_SERVICE:
problem="light_coin"
service="check_dynamic_strategy"
args_list = [
('n', int),
('version', str),
('goal', str),
('feed... | 0.350199 | 0.221119 |
import math
from functools import partial
from keras import backend as K
from keras.callbacks import ModelCheckpoint, CSVLogger, LearningRateScheduler, ReduceLROnPlateau, EarlyStopping
from keras.models import load_model
from legacy.unet3dlegacy.metrics import (dice_coefficient, dice_coefficient_loss, dice_coef, dice... | legacy/unet3dlegacy/training.py | import math
from functools import partial
from keras import backend as K
from keras.callbacks import ModelCheckpoint, CSVLogger, LearningRateScheduler, ReduceLROnPlateau, EarlyStopping
from keras.models import load_model
from legacy.unet3dlegacy.metrics import (dice_coefficient, dice_coefficient_loss, dice_coef, dice... | 0.835752 | 0.250145 |
import argparse
import json
import logging
import subprocess
from typing import List, Optional
from statick_tool.issue import Issue
from statick_tool.package import Package
from statick_tool.tool_plugin import ToolPlugin
class HadolintToolPlugin(ToolPlugin): # type: ignore
"""Apply hadolint tool and gather res... | src/statick_tooling/plugins/tool/hadolint_tool_plugin.py |
import argparse
import json
import logging
import subprocess
from typing import List, Optional
from statick_tool.issue import Issue
from statick_tool.package import Package
from statick_tool.tool_plugin import ToolPlugin
class HadolintToolPlugin(ToolPlugin): # type: ignore
"""Apply hadolint tool and gather res... | 0.739799 | 0.082328 |
import RPi.GPIO as GPIO
from serial import Serial
from serial.serialutil import SerialException
from time import sleep, time
from datetime import timedelta, datetime
from logging import getLogger
logger = getLogger("django.dust_sensor")
class DustSensor(object):
_serial_port = ""
_serial_speed = 9600
_ve... | dust_sensor/DustSensor.py | import RPi.GPIO as GPIO
from serial import Serial
from serial.serialutil import SerialException
from time import sleep, time
from datetime import timedelta, datetime
from logging import getLogger
logger = getLogger("django.dust_sensor")
class DustSensor(object):
_serial_port = ""
_serial_speed = 9600
_ve... | 0.449876 | 0.127761 |
import sys
import os
import argparse
from pprint import pprint
from steembase import PrivateKey, PublicKey, Address
import steembase.transactions as transactions
from .configuration import Configuration
from .utils import (
resolveIdentifier,
yaml_parse_file,
formatTime,
)
from .ui import (
dump_recurs... | piston/__main__.py |
import sys
import os
import argparse
from pprint import pprint
from steembase import PrivateKey, PublicKey, Address
import steembase.transactions as transactions
from .configuration import Configuration
from .utils import (
resolveIdentifier,
yaml_parse_file,
formatTime,
)
from .ui import (
dump_recurs... | 0.428473 | 0.065276 |
import pytest
import pugh_torch as pt
import gdown
from pathlib import Path
import torch
from torch import nn
import shutil
GDRIVE_TEST_FILE_URL = (
"https://drive.google.com/file/d/1T8TuY-8w8XVsbOI15mJZQ9OKexBqUwPZ/view?usp=sharing"
)
@pytest.fixture
def model():
return nn.Linear(2, 4)
@pytest.fixture
def... | pugh_torch/tests/models/test_io.py | import pytest
import pugh_torch as pt
import gdown
from pathlib import Path
import torch
from torch import nn
import shutil
GDRIVE_TEST_FILE_URL = (
"https://drive.google.com/file/d/1T8TuY-8w8XVsbOI15mJZQ9OKexBqUwPZ/view?usp=sharing"
)
@pytest.fixture
def model():
return nn.Linear(2, 4)
@pytest.fixture
def... | 0.742141 | 0.520009 |
import datetime
import json
from django import forms
try:
from django.core.urlresolvers import reverse
except ImportError: # Django 1.11
from django.urls import reverse
from django.forms import Widget
from django.utils import formats
from django.utils.html import format_html
from django.utils.safestring import... | env/lib/python3.6/site-packages/jet/dashboard/dashboard_modules/yandex_metrika.py | import datetime
import json
from django import forms
try:
from django.core.urlresolvers import reverse
except ImportError: # Django 1.11
from django.urls import reverse
from django.forms import Widget
from django.utils import formats
from django.utils.html import format_html
from django.utils.safestring import... | 0.393385 | 0.081776 |
import sqlite3
from typing import List, Any
DB_PRODUCTS = "db.sqlite3"
# Создаем таблицу. Колонки таблицы указаны после CREAT TABLE products( ... )
def creat_table_products():
with sqlite3.connect(DB_PRODUCTS) as session:
cursor = session.cursor()
cursor.execute(
"""
CREATE... | lesson-11/homework/hw_11.py | import sqlite3
from typing import List, Any
DB_PRODUCTS = "db.sqlite3"
# Создаем таблицу. Колонки таблицы указаны после CREAT TABLE products( ... )
def creat_table_products():
with sqlite3.connect(DB_PRODUCTS) as session:
cursor = session.cursor()
cursor.execute(
"""
CREATE... | 0.384219 | 0.148942 |
from siptracklib.objectregistry import object_registry
from siptracklib import treenodes
from siptracklib import attribute
from siptracklib import password
from siptracklib import counter
def suggest_templates(base_node, template_type):
templates = []
for oid in base_node.transport_root.cmd.template.suggestTem... | siptracklib/template.py | from siptracklib.objectregistry import object_registry
from siptracklib import treenodes
from siptracklib import attribute
from siptracklib import password
from siptracklib import counter
def suggest_templates(base_node, template_type):
templates = []
for oid in base_node.transport_root.cmd.template.suggestTem... | 0.553023 | 0.172904 |
import itertools
from typing import List, Tuple
import numpy as np
from deeppavlov.core.common.metrics_registry import register_metric
@register_metric('accuracy')
def accuracy(y_true, y_predicted):
"""
Calculate accuracy in terms of absolute coincidence
Args:
y_true: array of true values
... | deeppavlov/metrics/accuracy.py |
import itertools
from typing import List, Tuple
import numpy as np
from deeppavlov.core.common.metrics_registry import register_metric
@register_metric('accuracy')
def accuracy(y_true, y_predicted):
"""
Calculate accuracy in terms of absolute coincidence
Args:
y_true: array of true values
... | 0.876806 | 0.536556 |
import ships
"""
This is the template for player 2's placement of ships.
I have kept this as a separate file as I intended to convert this into a AI opponent at another time.
"""
def second_player_placement(player2):
player2 = player2
boat_number = 0
max_ship = 10
placing = True
while placing:
... | second_player.py | import ships
"""
This is the template for player 2's placement of ships.
I have kept this as a separate file as I intended to convert this into a AI opponent at another time.
"""
def second_player_placement(player2):
player2 = player2
boat_number = 0
max_ship = 10
placing = True
while placing:
... | 0.321673 | 0.389808 |
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from swagger_client.api_client import ApiClient
class AccountsApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
... | kapua-client/python-client/swagger_client/api/accounts_api.py | from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from swagger_client.api_client import ApiClient
class AccountsApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
... | 0.73412 | 0.063511 |
import random as r
leagal_x=[0,10]
leagal_y=[0,10]
class Turtle:
def __init__(self):
#初始化体力值
self.hp=100
#初始化随机的起始位置
self.x=r.randint(leagal_x[0],leagal_x[1])
self.y = r.randint(leagal_y[0], leagal_y[1])
def move(self):
choice_x=r.choice([1,2,-1,-2])
if ... | Ar_Script/past/类_乌龟和鱼游戏(优化版) .py | import random as r
leagal_x=[0,10]
leagal_y=[0,10]
class Turtle:
def __init__(self):
#初始化体力值
self.hp=100
#初始化随机的起始位置
self.x=r.randint(leagal_x[0],leagal_x[1])
self.y = r.randint(leagal_y[0], leagal_y[1])
def move(self):
choice_x=r.choice([1,2,-1,-2])
if ... | 0.116399 | 0.148078 |
import sys
import unittest
import libsbml
class TestRequiredAttributes(unittest.TestCase):
def test_AlgebraicRule(self):
ar = libsbml.AlgebraicRule(2,4)
self.assertEqual( True, ar.hasRequiredAttributes() )
ar = None
pass
def test_AlgebraicRule_L1(self):
ar = libsbml.AlgebraicRule(1,2)
... | external/sbml/bindings/python/test/sbml/TestRequiredAttributes.py | import sys
import unittest
import libsbml
class TestRequiredAttributes(unittest.TestCase):
def test_AlgebraicRule(self):
ar = libsbml.AlgebraicRule(2,4)
self.assertEqual( True, ar.hasRequiredAttributes() )
ar = None
pass
def test_AlgebraicRule_L1(self):
ar = libsbml.AlgebraicRule(1,2)
... | 0.304248 | 0.337599 |
import sys
import os
import cgi
import http.server
import rctk
from rctk.toolkit import Toolkit
import json
basedir = os.path.dirname(rctk.__file__)
class PersistentRequestFactoryClass(object):
def __init__(self, app):
self.tk = Toolkit(app())
def __call__(self, *args):
return StandaloneHT... | rctk/serve_py3.py | import sys
import os
import cgi
import http.server
import rctk
from rctk.toolkit import Toolkit
import json
basedir = os.path.dirname(rctk.__file__)
class PersistentRequestFactoryClass(object):
def __init__(self, app):
self.tk = Toolkit(app())
def __call__(self, *args):
return StandaloneHT... | 0.092092 | 0.063193 |
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
from uuid import UUID
from pydantic import BaseModel, Field
USER_ONBOARDING_STATE = "onboarding_state"
class TimeScale(Enum):
month = "month"
week = "week"
day = "day"
class SubscriptionTypeResource... | backend/moonstreamapi/data.py | from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
from uuid import UUID
from pydantic import BaseModel, Field
USER_ONBOARDING_STATE = "onboarding_state"
class TimeScale(Enum):
month = "month"
week = "week"
day = "day"
class SubscriptionTypeResource... | 0.858021 | 0.205814 |
import datetime
import tempfile
import shutil
from testify import *
from testify.utils import turtle
from tron import scheduler, action, job
class ConstantSchedulerTest(TestCase):
@setup
def build_scheduler(self):
self.test_dir = tempfile.mkdtemp()
self.scheduler = scheduler.ConstantScheduler... | test/scheduler_test.py | import datetime
import tempfile
import shutil
from testify import *
from testify.utils import turtle
from tron import scheduler, action, job
class ConstantSchedulerTest(TestCase):
@setup
def build_scheduler(self):
self.test_dir = tempfile.mkdtemp()
self.scheduler = scheduler.ConstantScheduler... | 0.378689 | 0.446072 |
import boto3
import botocore
import time
import os
import sys
import subprocess
import json
from uuid import uuid4
from datetime import datetime
from collections import namedtuple
def awsIotCliCommandForNonProdStage(command, stageParams):
"""Custom AWS IoT CLI command using the input command parameters and the
... | tools/ota_e2e_tests/aws_ota_test/aws_ota_aws_agent.py | import boto3
import botocore
import time
import os
import sys
import subprocess
import json
from uuid import uuid4
from datetime import datetime
from collections import namedtuple
def awsIotCliCommandForNonProdStage(command, stageParams):
"""Custom AWS IoT CLI command using the input command parameters and the
... | 0.561455 | 0.134548 |