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 |
|---|---|---|---|---|
def get_bs_vs_tn(in_file_name, out_file_name, best_config_list):
'''
Note: best case for dense int8 new log is:
batch_size data_parallel model_parallel thread_num
16 4 1 8
batch size: 1 2 4 8 16 32 64 128 256 512 1024
data parallel: 1 2 4 8 16 32
model parallel: 1 2 4 8 1... | python/sklearn/linear-regression/workload-analysis/ssd-obj-detect/post-process/ssd-mobilenet-v1/sparse-int8/sparsity-0.3/get-heat-map.py |
def get_bs_vs_tn(in_file_name, out_file_name, best_config_list):
'''
Note: best case for dense int8 new log is:
batch_size data_parallel model_parallel thread_num
16 4 1 8
batch size: 1 2 4 8 16 32 64 128 256 512 1024
data parallel: 1 2 4 8 16 32
model parallel: 1 2 4 8 1... | 0.129389 | 0.315024 |
import fcntl
import lockfile
import logging
import os
class BetterLockfile(object):
"""
A lockfile (matching the specification of the builtin lockfile class)
based off of flock. Only uses a single lock file rather than one per process/thread.
"""
def __init__(self, path):
self.path = path
... | fakemtpd/better_lockfile.py | import fcntl
import lockfile
import logging
import os
class BetterLockfile(object):
"""
A lockfile (matching the specification of the builtin lockfile class)
based off of flock. Only uses a single lock file rather than one per process/thread.
"""
def __init__(self, path):
self.path = path
... | 0.424651 | 0.091301 |
from rest_framework import serializers
from .abstract import JSONSerializerField
ModelSerializer = serializers.ModelSerializer
Serializer = serializers.Serializer
from .. import settings as app_settings
from ..models import (
EventProcessingException,
Event,
Transfer,
TransferChargeFee,
TransferCh... | payments/api/serializers.py | from rest_framework import serializers
from .abstract import JSONSerializerField
ModelSerializer = serializers.ModelSerializer
Serializer = serializers.Serializer
from .. import settings as app_settings
from ..models import (
EventProcessingException,
Event,
Transfer,
TransferChargeFee,
TransferCh... | 0.774242 | 0.102799 |
def are_same(serial):
if (serial[0] != serial[1] and
serial[1] != serial[2] and
serial[0] != serial[2]):
return False
return True
def check_serial(serial):
try:
serials = serial.split('-')
print(serials)
except:
print ("error1")
return False
... | writeup-scripts/2017-2018/ESIEACTF/googleserials/googleserials.py | def are_same(serial):
if (serial[0] != serial[1] and
serial[1] != serial[2] and
serial[0] != serial[2]):
return False
return True
def check_serial(serial):
try:
serials = serial.split('-')
print(serials)
except:
print ("error1")
return False
... | 0.182936 | 0.398992 |
from typing import Dict, Optional, List, Union, Tuple
from bowtie._component import Component, jdumps, jsbool
from bowtie._progress import Progress
# pylint: disable=too-few-public-methods
class _Visual(Component):
"""Abstract class all visual components inherit.
Used to test if a an object is a visual com... | bowtie/visual.py |
from typing import Dict, Optional, List, Union, Tuple
from bowtie._component import Component, jdumps, jsbool
from bowtie._progress import Progress
# pylint: disable=too-few-public-methods
class _Visual(Component):
"""Abstract class all visual components inherit.
Used to test if a an object is a visual com... | 0.933862 | 0.454654 |
import requests
from py_behrtech.Parsers.messageParser import MessageParser
from py_behrtech.exceptions import check_status_code
from py_behrtech.functions import buildParameter
class Messages:
def __init__(self):
self.username = None
self.password = None
self.server_address = None
... | py_behrtech/Calls/messages.py | import requests
from py_behrtech.Parsers.messageParser import MessageParser
from py_behrtech.exceptions import check_status_code
from py_behrtech.functions import buildParameter
class Messages:
def __init__(self):
self.username = None
self.password = None
self.server_address = None
... | 0.799638 | 0.169819 |
from .cbor_handler import ByteArrayHandler, InvalidSequenceNumber
from .event_handler import EventHandler, InvalidApplicationError
from ..funcs.log import create_logger
from ..funcs.event import Event
from ..funcs.EventCreationTool import EventFactory
logger = create_logger('DatabaseHandler')
"""The database handler a... | 20-hs-redez-sem/groups/05-decentGames/src/logStore/database/database_handler.py | from .cbor_handler import ByteArrayHandler, InvalidSequenceNumber
from .event_handler import EventHandler, InvalidApplicationError
from ..funcs.log import create_logger
from ..funcs.event import Event
from ..funcs.EventCreationTool import EventFactory
logger = create_logger('DatabaseHandler')
"""The database handler a... | 0.68056 | 0.194291 |
import solver
import os
import time
import csv
from sys import argv
LOG_STATS = True
class StatGetter:
def __init__(self):
self.sourcedir = os.getcwd()
self.datadir = self.sourcedir + "/solutiondata/"
os.chdir(self.datadir)
self.statfile = open('stats.csv', 'a')
self.csv_writer = csv.writer(self.statfile)... | src/scramble_tournament.py |
import solver
import os
import time
import csv
from sys import argv
LOG_STATS = True
class StatGetter:
def __init__(self):
self.sourcedir = os.getcwd()
self.datadir = self.sourcedir + "/solutiondata/"
os.chdir(self.datadir)
self.statfile = open('stats.csv', 'a')
self.csv_writer = csv.writer(self.statfile)... | 0.243013 | 0.1191 |
from django.contrib.contenttypes.models import ContentType
from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
import requests
from links.models import Link, LinkType
from mks.models import Member, Party
SUCSESS_STATUS_CODE = 200
KIKAR_BASE_URL = 'http://www.kikar.org'
... | kikar/management/commands/update_links_from_kikar.py | from django.contrib.contenttypes.models import ContentType
from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
import requests
from links.models import Link, LinkType
from mks.models import Member, Party
SUCSESS_STATUS_CODE = 200
KIKAR_BASE_URL = 'http://www.kikar.org'
... | 0.331877 | 0.104204 |
import cairo
import os
import errno
import math
from drawingbackend import DrawingBackend
import networkx as nx
from translatable import Translatable
from rotatable import Rotatable
from node import Node
import pangocairo
import pango
import warnings
class CairoBackend(DrawingBackend):
DEFAULT_MARGIN = (10, 10, 10... | shaape/cairobackend.py | import cairo
import os
import errno
import math
from drawingbackend import DrawingBackend
import networkx as nx
from translatable import Translatable
from rotatable import Rotatable
from node import Node
import pangocairo
import pango
import warnings
class CairoBackend(DrawingBackend):
DEFAULT_MARGIN = (10, 10, 10... | 0.423458 | 0.194578 |
import json
import logging
import math
from dataclasses import dataclass, field
from typing import Optional
import torch
from fairseq import metrics
from fairseq.dataclass import ChoiceEnum
from fairseq.tasks import register_task
from tasks.ofa_task import OFATask, OFAConfig
from data.nlu_data.qqp_dataset import QQP... | tasks/nlu_tasks/qqp.py |
import json
import logging
import math
from dataclasses import dataclass, field
from typing import Optional
import torch
from fairseq import metrics
from fairseq.dataclass import ChoiceEnum
from fairseq.tasks import register_task
from tasks.ofa_task import OFATask, OFAConfig
from data.nlu_data.qqp_dataset import QQP... | 0.875641 | 0.27133 |
import logging
from ocs_ci.ocs.resources.pod import get_fio_rw_iops
from ocs_ci.framework.testlib import ManageTest, tier2
from ocs_ci.framework.pytest_customization.marks import polarion_id
from ocs_ci.framework.pytest_customization.marks import (
skipif_external_mode,
skipif_ocs_version,
)
from ocs_ci.ocs.res... | tests/manage/storageclass/test_create_sc_reclaim_policy_rep2_comp.py | import logging
from ocs_ci.ocs.resources.pod import get_fio_rw_iops
from ocs_ci.framework.testlib import ManageTest, tier2
from ocs_ci.framework.pytest_customization.marks import polarion_id
from ocs_ci.framework.pytest_customization.marks import (
skipif_external_mode,
skipif_ocs_version,
)
from ocs_ci.ocs.res... | 0.447943 | 0.275489 |
import pytest
from liquidcore.twofactor import devices
from django_otp.oath import hotp
from collections import namedtuple
NORMAL_USER_NAME = 'user'
NORMAL_USER_PW = 'password'
ADMIN_NAME = 'admin'
ADMIN_PW = '<PASSWORD>'
ADMIN_EMAIL = '<EMAIL>'
def _totp(device, now):
counter = int(now.timestamp() - device.t0) ... | testsuite/conftest.py | import pytest
from liquidcore.twofactor import devices
from django_otp.oath import hotp
from collections import namedtuple
NORMAL_USER_NAME = 'user'
NORMAL_USER_PW = 'password'
ADMIN_NAME = 'admin'
ADMIN_PW = '<PASSWORD>'
ADMIN_EMAIL = '<EMAIL>'
def _totp(device, now):
counter = int(now.timestamp() - device.t0) ... | 0.358241 | 0.135261 |
from __future__ import absolute_import
from __future__ import unicode_literals
from datetime import datetime
import six
from celery.exceptions import MaxRetriesExceededError
from celery.schedules import crontab
from celery.task import task
from celery.task.base import periodic_task
from celery.utils.log import get_tas... | corehq/apps/users/tasks.py | from __future__ import absolute_import
from __future__ import unicode_literals
from datetime import datetime
import six
from celery.exceptions import MaxRetriesExceededError
from celery.schedules import crontab
from celery.task import task
from celery.task.base import periodic_task
from celery.utils.log import get_tas... | 0.447702 | 0.12921 |
from textwrap import dedent
from typing import Dict
from .commands import CommandList
TAB_SPACE = " "
def _format_template(template: str) -> str:
return dedent(template)
class PipelineWriter:
def __init__(
self, pipeline_config: "PipelineConfig", env_vars: Dict[str, str]
) -... | src/docker_publisher_osparc_services/gitlab_ci_setup/pipeline_writer.py | from textwrap import dedent
from typing import Dict
from .commands import CommandList
TAB_SPACE = " "
def _format_template(template: str) -> str:
return dedent(template)
class PipelineWriter:
def __init__(
self, pipeline_config: "PipelineConfig", env_vars: Dict[str, str]
) -... | 0.830216 | 0.160529 |
import pprint
import re
import six
class ListImagesRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in d... | huaweicloud-sdk-iec/huaweicloudsdkiec/v1/model/list_images_request.py |
import pprint
import re
import six
class ListImagesRequest:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in d... | 0.501221 | 0.073364 |
from ledgerblue.comm import getDongle
from ledgerblue.commException import CommException
TESTNET=152
MAINNET=104
MIJIN_MAINNET=96
MIJIN_TESTNET=144
BIPP32_LENGTH = 20
bipp32_path = (
"8000002C"
+ "8000002B"
+ "%s"
+ "80000000"
+ "80000000")
APDU_GET_ACCOUNT = "E0020180"
APDU_SIGN_TX = "E0040080... | test_nem.py | from ledgerblue.comm import getDongle
from ledgerblue.commException import CommException
TESTNET=152
MAINNET=104
MIJIN_MAINNET=96
MIJIN_TESTNET=144
BIPP32_LENGTH = 20
bipp32_path = (
"8000002C"
+ "8000002B"
+ "%s"
+ "80000000"
+ "80000000")
APDU_GET_ACCOUNT = "E0020180"
APDU_SIGN_TX = "E0040080... | 0.294519 | 0.181916 |
try:
pass
except ImportError:
sys.exit("install SimpleWebSocketServer")
request_queue = queue.Queue()
class ElectrumWebSocket(WebSocket):
def handleMessage(self):
assert self.data[0:3] == "id:"
util.print_error("message received", self.data)
request_id = self.data[3:]
request_queue.put((self, request_id))
d... | lib/websockets.py | try:
pass
except ImportError:
sys.exit("install SimpleWebSocketServer")
request_queue = queue.Queue()
class ElectrumWebSocket(WebSocket):
def handleMessage(self):
assert self.data[0:3] == "id:"
util.print_error("message received", self.data)
request_id = self.data[3:]
request_queue.put((self, request_id))
d... | 0.128088 | 0.12031 |
import requests
from bs4 import BeautifulSoup
from csv import writer
#url="yahoo.com"
url="http://localhost/1/_PHP/_petroblog/"
rsp=requests.get(url)
rsp.status_code
print('STATUS CODE IS ',rsp.status_code)
#print a new line
print()
#print a new line
print()
#print out the raw content of the url o... | scrappy_006.py | import requests
from bs4 import BeautifulSoup
from csv import writer
#url="yahoo.com"
url="http://localhost/1/_PHP/_petroblog/"
rsp=requests.get(url)
rsp.status_code
print('STATUS CODE IS ',rsp.status_code)
#print a new line
print()
#print a new line
print()
#print out the raw content of the url o... | 0.037573 | 0.037327 |
import hashlib
import time
import zlib
try:
import ujson as json
except ImportError:
import json
from .utils import b
from .exceptions import (SerializeError,
CompressError)
class IdentityGenerator:
"""
Generator of identity for unique key,
you may overwrite it to meet y... | yaaredis/cache.py | import hashlib
import time
import zlib
try:
import ujson as json
except ImportError:
import json
from .utils import b
from .exceptions import (SerializeError,
CompressError)
class IdentityGenerator:
"""
Generator of identity for unique key,
you may overwrite it to meet y... | 0.716814 | 0.088426 |
def buildList(x,y):
lx,ly = [],[]
while x>0:
lx.append(x%2)
ly.append(y%2)
x >>= 1
y >>= 1
lx.reverse(), ly.reverse()
return lx,ly
def buildSetList(l,t): #t=tag
n,sl,w = len(l),[],-1
for i in range(n):
if l[i]==1:
sl += [(nz,1,max(0,n-nz-1),... | contests/icpc20sh/c7TLE.py |
def buildList(x,y):
lx,ly = [],[]
while x>0:
lx.append(x%2)
ly.append(y%2)
x >>= 1
y >>= 1
lx.reverse(), ly.reverse()
return lx,ly
def buildSetList(l,t): #t=tag
n,sl,w = len(l),[],-1
for i in range(n):
if l[i]==1:
sl += [(nz,1,max(0,n-nz-1),... | 0.048744 | 0.288989 |
import scrapy
from PocketLifeSpider.util.CommonUtils import *
from PocketLifeSpider.util.MongoDbUtils import MongoDbUtils
class Piece4Spider(scrapy.Spider):
name = 'piece4'
allowed_domains = ['www.xiaopin.tv']
start_urls = []
origin_url = 'http://www.xiaopin.tv'
type = 'piece'
# 电影总数
tota... | Spider/PocketLifeSpider/PocketLifeSpider/spiders/piece4.py | import scrapy
from PocketLifeSpider.util.CommonUtils import *
from PocketLifeSpider.util.MongoDbUtils import MongoDbUtils
class Piece4Spider(scrapy.Spider):
name = 'piece4'
allowed_domains = ['www.xiaopin.tv']
start_urls = []
origin_url = 'http://www.xiaopin.tv'
type = 'piece'
# 电影总数
tota... | 0.142157 | 0.081776 |
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
# Package meta-data.
NAME = 'deo'
DESCRIPTION = 'another jsonrpc2-http implementation'
URL = 'https://github.com/bsnacks000/deo'
EMAIL = '<EMAIL>'
AUTHOR = 'bsnacks000'
REQUIRES_PYTHON = '>=3.6.0'
VERSION = '... | setup.py | import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
# Package meta-data.
NAME = 'deo'
DESCRIPTION = 'another jsonrpc2-http implementation'
URL = 'https://github.com/bsnacks000/deo'
EMAIL = '<EMAIL>'
AUTHOR = 'bsnacks000'
REQUIRES_PYTHON = '>=3.6.0'
VERSION = '... | 0.359139 | 0.151028 |
from __future__ import division
from __future__ import unicode_literals
from deepchem.molnet import load_delaney
from deepchem.trans.transformers import FeaturizationTransformer
__author__ = "<NAME>"
__copyright__ = "Copyright 2016, Stanford University"
__license__ = "MIT"
import os
import unittest
import numpy as n... | deepchem/trans/tests/test_transformers.py | from __future__ import division
from __future__ import unicode_literals
from deepchem.molnet import load_delaney
from deepchem.trans.transformers import FeaturizationTransformer
__author__ = "<NAME>"
__copyright__ = "Copyright 2016, Stanford University"
__license__ = "MIT"
import os
import unittest
import numpy as n... | 0.786623 | 0.555978 |
import tensorflow as tf
from dl_portfolio.constraints import NonNegAndUnitNorm
from dl_portfolio.regularizers import WeightsOrthogonality
import pandas as pd
dataset = 'dataset2'
show_plot = False
save = True
nmf_model = "./final_models/nmf/dataset2/m_0_seed_4_20220322_123053"
resample = {
'method': 'nbb',
'w... | dl_portfolio/config/ae_config_dataset2.py | import tensorflow as tf
from dl_portfolio.constraints import NonNegAndUnitNorm
from dl_portfolio.regularizers import WeightsOrthogonality
import pandas as pd
dataset = 'dataset2'
show_plot = False
save = True
nmf_model = "./final_models/nmf/dataset2/m_0_seed_4_20220322_123053"
resample = {
'method': 'nbb',
'w... | 0.524882 | 0.246488 |
import datetime
import os
from typing import Union, Any, Dict
import airflow
from airflow import models
from airflow.operators import subdag_operator
from dependencies.utils import airflow_utils
from dependencies import blockbuster_constants
from subdags import analyze_dag
# Declare Constants
_AIRFLOW_ENV = 'AIRFLOW... | src/dags/blockbuster_training_analyze.py | import datetime
import os
from typing import Union, Any, Dict
import airflow
from airflow import models
from airflow.operators import subdag_operator
from dependencies.utils import airflow_utils
from dependencies import blockbuster_constants
from subdags import analyze_dag
# Declare Constants
_AIRFLOW_ENV = 'AIRFLOW... | 0.714728 | 0.286363 |
import string
from typing import Any, Dict, Tuple, Type
from passlib.apps import custom_app_context as pwd_context
from sqlalchemy import Column, Integer, String, Text
import database
from database import Base, DeclEnum
class Role(DeclEnum):
"""Roles available for users."""
admin = "admin", "Admin"
use... | mod_auth/models.py | import string
from typing import Any, Dict, Tuple, Type
from passlib.apps import custom_app_context as pwd_context
from sqlalchemy import Column, Integer, String, Text
import database
from database import Base, DeclEnum
class Role(DeclEnum):
"""Roles available for users."""
admin = "admin", "Admin"
use... | 0.889894 | 0.153454 |
import pandas as pd
import numpy as np
from datetime import date, timedelta, datetime
# Load data
rolling = pd.read_csv('unprepped_data\\PD 2021 Wk 26 Input - Sheet1.csv')
# Create a data set that gives 7 rows per date (unless those dates aren't included in the data set).
# - ie 1st Jan only has 4 rows of data (1st... | 2021-week-26.py | import pandas as pd
import numpy as np
from datetime import date, timedelta, datetime
# Load data
rolling = pd.read_csv('unprepped_data\\PD 2021 Wk 26 Input - Sheet1.csv')
# Create a data set that gives 7 rows per date (unless those dates aren't included in the data set).
# - ie 1st Jan only has 4 rows of data (1st... | 0.563618 | 0.349394 |
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from openapi_server.com.github.asyncmc.mojang.authentication.python.flask.model.base_model_ import Model
from openapi_server import util
class Authentication(Model):
"""NOTE: Thi... | generated-sources/python-flask/mojang-authentication/openapi_server/com/github/asyncmc/mojang/authentication/python/flask/model/authentication.py |
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from openapi_server.com.github.asyncmc.mojang.authentication.python.flask.model.base_model_ import Model
from openapi_server import util
class Authentication(Model):
"""NOTE: Thi... | 0.793106 | 0.0809 |
import argparse
import numpy as np
import pandas as pd
import scipy.stats as ss
from seglearn.transform import Segment, FeatureRep, FeatureRepMix
from viztracer import VizTracer
from utils import get_data
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'... | code/seglearn_sleep_w30s_s10s.py | import argparse
import numpy as np
import pandas as pd
import scipy.stats as ss
from seglearn.transform import Segment, FeatureRep, FeatureRepMix
from viztracer import VizTracer
from utils import get_data
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'... | 0.560974 | 0.367469 |
from ie_serving.models.local_model import LocalModel
from ie_serving.models.model_version_status import ModelVersionStatus
from ie_serving.server.rest_service import create_rest_api
from tensorflow_serving.apis import prediction_service_pb2, \
get_model_status_pb2, model_service_pb2
from tensorflow_serving.api... | tests/unit/conftest.py | from ie_serving.models.local_model import LocalModel
from ie_serving.models.model_version_status import ModelVersionStatus
from ie_serving.server.rest_service import create_rest_api
from tensorflow_serving.apis import prediction_service_pb2, \
get_model_status_pb2, model_service_pb2
from tensorflow_serving.api... | 0.563978 | 0.126677 |
from eth_utils import to_bytes, to_canonical_address, to_checksum_address
from raiden import constants
from raiden.utils import pex
from raiden.utils.typing import (
Address,
Any,
ChainID,
ChannelID,
Dict,
T_Address,
T_ChainID,
T_ChannelID,
TokenNetworkAddress,
TokenNetworkID,
... | raiden/transfer/identifiers.py | from eth_utils import to_bytes, to_canonical_address, to_checksum_address
from raiden import constants
from raiden.utils import pex
from raiden.utils.typing import (
Address,
Any,
ChainID,
ChannelID,
Dict,
T_Address,
T_ChainID,
T_ChannelID,
TokenNetworkAddress,
TokenNetworkID,
... | 0.868213 | 0.196923 |
import numpy as np
from datetime import datetime
import torch
import torch.nn as nn
from model import CNN
from preprocessing import make_env
from utils import get_test_acc, make_matrix
# Hyper params -- for pref
batch_size = 128
n_epochs = 15
# Training loop
def train(model, criterion, optimizer, train_loader, test_... | Fashion-MNIST/main.py | import numpy as np
from datetime import datetime
import torch
import torch.nn as nn
from model import CNN
from preprocessing import make_env
from utils import get_test_acc, make_matrix
# Hyper params -- for pref
batch_size = 128
n_epochs = 15
# Training loop
def train(model, criterion, optimizer, train_loader, test_... | 0.852997 | 0.353651 |
import os
import json
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from shutil import copytree
from pathlib import Path
from matplotlib.ticker import EngFormatter
from jinja2 import Environment, FileSystemLoader
def generate_html(path):
templates_dir = './visualization/tem... | visualization/main.py | import os
import json
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from shutil import copytree
from pathlib import Path
from matplotlib.ticker import EngFormatter
from jinja2 import Environment, FileSystemLoader
def generate_html(path):
templates_dir = './visualization/tem... | 0.562777 | 0.305043 |
import json
import pydoc
import inspect
import logging
import discord
from enum import Enum
from discord.ext.commands.bot import _get_variable
from .utils import objdiff
log = logging.getLogger(__name__)
class BetterLogRecord(logging.LogRecord):
def __init__(self, *args, **kwargs):
super(... | musicbot/constructs.py | import json
import pydoc
import inspect
import logging
import discord
from enum import Enum
from discord.ext.commands.bot import _get_variable
from .utils import objdiff
log = logging.getLogger(__name__)
class BetterLogRecord(logging.LogRecord):
def __init__(self, *args, **kwargs):
super(... | 0.578567 | 0.121425 |
from typing import List, Sequence
from marshmallow import EXCLUDE
import pymongo
from ebl.errors import NotFoundError
from ebl.fragmentarium.application.fragment_info_schema import FragmentInfoSchema
from ebl.fragmentarium.application.fragment_repository import FragmentRepository
from ebl.fragmentarium.application.fr... | ebl/fragmentarium/infrastructure/fragment_repository.py | from typing import List, Sequence
from marshmallow import EXCLUDE
import pymongo
from ebl.errors import NotFoundError
from ebl.fragmentarium.application.fragment_info_schema import FragmentInfoSchema
from ebl.fragmentarium.application.fragment_repository import FragmentRepository
from ebl.fragmentarium.application.fr... | 0.760206 | 0.228425 |
import unittest
from unittest import mock
from unittest.mock import call
import smbclient
from airflow.exceptions import AirflowException
from airflow.models import Connection
from airflow.providers.samba.hooks.samba import SambaHook
connection = Connection(host='ip', schema='share', login='username', password='pas... | tests/providers/samba/hooks/test_samba.py |
import unittest
from unittest import mock
from unittest.mock import call
import smbclient
from airflow.exceptions import AirflowException
from airflow.models import Connection
from airflow.providers.samba.hooks.samba import SambaHook
connection = Connection(host='ip', schema='share', login='username', password='pas... | 0.625552 | 0.33116 |
import geomstats.backend as gs
import geomstats.tests
from geomstats.geometry.euclidean import Euclidean
from geomstats.learning.radial_kernel_functions import \
biweight_radial_kernel, bump_radial_kernel, cosine_radial_kernel, \
gaussian_radial_kernel, inverse_multiquadric_radial_kernel, \
inverse_quadrat... | tests/tests_geomstats/test_radial_kernel_functions.py |
import geomstats.backend as gs
import geomstats.tests
from geomstats.geometry.euclidean import Euclidean
from geomstats.learning.radial_kernel_functions import \
biweight_radial_kernel, bump_radial_kernel, cosine_radial_kernel, \
gaussian_radial_kernel, inverse_multiquadric_radial_kernel, \
inverse_quadrat... | 0.913726 | 0.771176 |
"""Abstractions for composing layers."""
import re
from lingvo import compat as tf
from lingvo.core import base_layer
from lingvo.core import computation_cost
from lingvo.core import py_utils
from lingvo.core import quant_utils
from lingvo.core import recurrent
from lingvo.core import summary_utils
from lingvo.core im... | lingvo/core/builder_layers.py | """Abstractions for composing layers."""
import re
from lingvo import compat as tf
from lingvo.core import base_layer
from lingvo.core import computation_cost
from lingvo.core import py_utils
from lingvo.core import quant_utils
from lingvo.core import recurrent
from lingvo.core import summary_utils
from lingvo.core im... | 0.888596 | 0.533215 |
import tensorflow as tf
class Deep(object):
def __init__(self, x, keep_prob, num_classes):
# Parser input arguments into classes variables
self.X = x
self.NUM_CLASSES = num_classes
self.KEEP_PROB = keep_prob
# Call the create function to build computational graph of CNN2
... | tf-mnist/multiclass_deep_model.py | import tensorflow as tf
class Deep(object):
def __init__(self, x, keep_prob, num_classes):
# Parser input arguments into classes variables
self.X = x
self.NUM_CLASSES = num_classes
self.KEEP_PROB = keep_prob
# Call the create function to build computational graph of CNN2
... | 0.843348 | 0.501648 |
from datetime import datetime
import pytest
from freezegun import freeze_time
from app import statsd_client
from app.aws.mocks import sns_failed_callback, sns_success_callback
from app.celery.process_sns_receipts_tasks import process_sns_results
from app.dao.notifications_dao import get_notification_by_id
from app.mo... | tests/app/celery/test_process_sns_receipts_tasks.py | from datetime import datetime
import pytest
from freezegun import freeze_time
from app import statsd_client
from app.aws.mocks import sns_failed_callback, sns_success_callback
from app.celery.process_sns_receipts_tasks import process_sns_results
from app.dao.notifications_dao import get_notification_by_id
from app.mo... | 0.582254 | 0.119537 |
from __future__ import absolute_import
import collections
import os
import sys
from oslo_log import log
import yaml
import tobiko
LOG = log.getLogger(__name__)
def get_keystone_credentials(obj=None):
if not obj:
return default_keystone_credentials()
if tobiko.is_fixture(obj):
obj = tobiko... | tobiko/openstack/keystone/_credentials.py | from __future__ import absolute_import
import collections
import os
import sys
from oslo_log import log
import yaml
import tobiko
LOG = log.getLogger(__name__)
def get_keystone_credentials(obj=None):
if not obj:
return default_keystone_credentials()
if tobiko.is_fixture(obj):
obj = tobiko... | 0.384565 | 0.055464 |
# pylint: disable=too-many-lines, line-too-long
from pyubx2.ubxtypes_core import U1, U2, U4
UBX_PAYLOADS_POLL = {
# AID messages are deprecated in favour of MGA messages in >=Gen8
"AID-ALM": {},
"AID-ALM-SV": {"svid": U1},
"AID-AOP": {},
"AID-AOP-SV": {"svid": U1},
"AID-DATA": {},
"AID-EPH... | pyubx2/ubxtypes_poll.py | # pylint: disable=too-many-lines, line-too-long
from pyubx2.ubxtypes_core import U1, U2, U4
UBX_PAYLOADS_POLL = {
# AID messages are deprecated in favour of MGA messages in >=Gen8
"AID-ALM": {},
"AID-ALM-SV": {"svid": U1},
"AID-AOP": {},
"AID-AOP-SV": {"svid": U1},
"AID-DATA": {},
"AID-EPH... | 0.236604 | 0.238983 |
from django.conf import settings
from featureflipper.models import Feature
from featureflipper.signals import feature_defaulted
from featureflipper import FeatureProvider
import re
# Per-request flipper in URL
_REQUEST_ENABLE = re.compile("^enable_(?P<feature>\w+)$")
# Per-session flipper in URL
_SESSION_ENABLE = r... | featureflipper/middleware.py | from django.conf import settings
from featureflipper.models import Feature
from featureflipper.signals import feature_defaulted
from featureflipper import FeatureProvider
import re
# Per-request flipper in URL
_REQUEST_ENABLE = re.compile("^enable_(?P<feature>\w+)$")
# Per-session flipper in URL
_SESSION_ENABLE = r... | 0.643441 | 0.255651 |
import random
from sampledata.l10n.names import Name, Surname, FullName
from sampledata.l10n.cities import City
from sampledata.l10n.occupations import Occupation
from sampledata.l10n.skills import Skill
from ..exceptions import ParameterError
class LocalizedMixin(object):
def state_code(self, locale):
... | sampledata/mixins/localized_mixin.py | import random
from sampledata.l10n.names import Name, Surname, FullName
from sampledata.l10n.cities import City
from sampledata.l10n.occupations import Occupation
from sampledata.l10n.skills import Skill
from ..exceptions import ParameterError
class LocalizedMixin(object):
def state_code(self, locale):
... | 0.553264 | 0.237432 |
import torch
from collections import deque
class PPOBuffer(object):
"""
Replay Buffer to save samples for PPO
and diagnostic training data
"""
def __init__(self, batch_size, norm_adv=True):
# Samples
self.obs = [[], [], []]
self.actions = []
self.logps = []
... | src/ros_carla_rllib/memories.py | import torch
from collections import deque
class PPOBuffer(object):
"""
Replay Buffer to save samples for PPO
and diagnostic training data
"""
def __init__(self, batch_size, norm_adv=True):
# Samples
self.obs = [[], [], []]
self.actions = []
self.logps = []
... | 0.855519 | 0.617916 |
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from .settings import epayco_settings
from .signals import invalid_confirmation_received, confirmation_was_flagged, valid_confirmation_received, \
confirmation_was_approved, confirmation_was_rejected
fr... | epayco_django/models.py | from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from .settings import epayco_settings
from .signals import invalid_confirmation_received, confirmation_was_flagged, valid_confirmation_received, \
confirmation_was_approved, confirmation_was_rejected
fr... | 0.646237 | 0.109706 |
from pandac.PandaModules import *
from direct.distributed import DistributedObject
from direct.interval.ProjectileInterval import *
from direct.interval.IntervalGlobal import *
from direct.distributed.ClockDelta import *
from toontown.racing.DistributedVehicle import DistributedVehicle
from toontown.racing.DroppedGag i... | toontown/racing/DistributedGag.py | from pandac.PandaModules import *
from direct.distributed import DistributedObject
from direct.interval.ProjectileInterval import *
from direct.interval.IntervalGlobal import *
from direct.distributed.ClockDelta import *
from toontown.racing.DistributedVehicle import DistributedVehicle
from toontown.racing.DroppedGag i... | 0.493897 | 0.168446 |
from functools import partial
from multiprocessing.dummy import Pool
from scipy.io import wavfile
import argparse
from glob import glob
from parse import parse
import os, sys
import numpy as np
def gen_noise(n, type, sigma, noise_folder="../../data/NoiseDB/NoiseX_16kHz"):
"""Generate noise of a certain type and ... | src/timit-preprocessor/add_noise.py | from functools import partial
from multiprocessing.dummy import Pool
from scipy.io import wavfile
import argparse
from glob import glob
from parse import parse
import os, sys
import numpy as np
def gen_noise(n, type, sigma, noise_folder="../../data/NoiseDB/NoiseX_16kHz"):
"""Generate noise of a certain type and ... | 0.572723 | 0.310603 |
import logging
import os
import sys
from base64 import urlsafe_b64encode
from pprint import pformat
import tornado.escape
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
from bson import json_util # Installed with PyMongo.
from tornado.options import define, options
from moto... | doc/examples/tornado_change_stream_example.py | import logging
import os
import sys
from base64 import urlsafe_b64encode
from pprint import pformat
import tornado.escape
import tornado.ioloop
import tornado.options
import tornado.web
import tornado.websocket
from bson import json_util # Installed with PyMongo.
from tornado.options import define, options
from moto... | 0.210766 | 0.065755 |
from ethosu.vela.api import npu_generate_register_command_stream
from ethosu.vela.api import NpuAccelerator
from ethosu.vela.api import NpuActivation
from ethosu.vela.api import NpuActivationOp
from ethosu.vela.api import NpuAddressRange
from ethosu.vela.api import NpuBlockTraversal
from ethosu.vela.api import NpuConv2... | ethosu/vela/test/extapi/test_extapi_generate_commands.py | from ethosu.vela.api import npu_generate_register_command_stream
from ethosu.vela.api import NpuAccelerator
from ethosu.vela.api import NpuActivation
from ethosu.vela.api import NpuActivationOp
from ethosu.vela.api import NpuAddressRange
from ethosu.vela.api import NpuBlockTraversal
from ethosu.vela.api import NpuConv2... | 0.630571 | 0.239694 |
import numpy as np
from sklearn.utils import check_array, check_consistent_length
from ._label import is_labeled, is_unlabeled
from ._label_encoder import ExtLabelEncoder
from ._selection import rand_argmax
def compute_vote_vectors(y, w=None, classes=None, missing_label=np.nan):
"""Counts number of votes per cla... | skactiveml/utils/_aggregation.py | import numpy as np
from sklearn.utils import check_array, check_consistent_length
from ._label import is_labeled, is_unlabeled
from ._label_encoder import ExtLabelEncoder
from ._selection import rand_argmax
def compute_vote_vectors(y, w=None, classes=None, missing_label=np.nan):
"""Counts number of votes per cla... | 0.933043 | 0.599573 |
import json
import os
import datasets
_CITATION = """\
@inproceedings{NEURIPS2020_1457c0d6,
author = {<NAME> Mann, <NAME>, <NAME>, <NAME> and Dhariwal, Prafulla and Neelakantan, <NAME>, <NAME>, <NAME>, <NAME> Herbert-Voss, <NAME>, Gretchen and Henighan, Tom and Child, Rewon and Ramesh, Aditya and Ziegler, Daniel... | lm_eval/datasets/unscramble/unscramble.py | import json
import os
import datasets
_CITATION = """\
@inproceedings{NEURIPS2020_1457c0d6,
author = {<NAME> Mann, <NAME>, <NAME>, <NAME> and Dhariwal, Prafulla and Neelakantan, <NAME>, <NAME>, <NAME>, <NAME> Herbert-Voss, <NAME>, Gretchen and Henighan, Tom and Child, Rewon and Ramesh, Aditya and Ziegler, Daniel... | 0.377541 | 0.410579 |
import os
from collections import OrderedDict
from pathlib import Path
from typing import Dict
import math
import torch
from catalyst import utils
from catalyst.callbacks.checkpoint import BaseCheckpointCallback
from catalyst.dl import IRunner, Callback, CallbackOrder
__all__ = [
"BestMetricCheckpointCallback",
... | pytorch_toolbelt/utils/catalyst/utils.py | import os
from collections import OrderedDict
from pathlib import Path
from typing import Dict
import math
import torch
from catalyst import utils
from catalyst.callbacks.checkpoint import BaseCheckpointCallback
from catalyst.dl import IRunner, Callback, CallbackOrder
__all__ = [
"BestMetricCheckpointCallback",
... | 0.914352 | 0.202561 |
import anyio
import pytest
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.responses import JSONResponse
from starlette.testclient import TestClient
from starlette.websockets import WebSocket, WebSocketDisconnect
mock_service = Starlette()
@mock_service.route(... | tests/test_testclient.py | import anyio
import pytest
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.responses import JSONResponse
from starlette.testclient import TestClient
from starlette.websockets import WebSocket, WebSocketDisconnect
mock_service = Starlette()
@mock_service.route(... | 0.569015 | 0.253894 |
from .... pyaz_utils import _call_az
from . import ip_config
def add(frontend_ip, gateway_name, name, resource_group, subnet, ip_address=None, no_wait=None, primary=None, subnet_prefix=None):
'''
Add a new Private Link with a default IP Configuration and associate it with an existing Frontend IP
Required... | pyaz/network/application_gateway/private_link/__init__.py | from .... pyaz_utils import _call_az
from . import ip_config
def add(frontend_ip, gateway_name, name, resource_group, subnet, ip_address=None, no_wait=None, primary=None, subnet_prefix=None):
'''
Add a new Private Link with a default IP Configuration and associate it with an existing Frontend IP
Required... | 0.810891 | 0.177347 |
import unittest
from streamlink.plugins.huomao import Huomao
class TestPluginHuomao(unittest.TestCase):
def test_can_handle_url(self):
should_match = [
# Assert that an URL containing the http:// prefix is correctly read.
"http://www.huomao.com/123456",
"http://www.huo... | tests/plugins/test_huomao.py | import unittest
from streamlink.plugins.huomao import Huomao
class TestPluginHuomao(unittest.TestCase):
def test_can_handle_url(self):
should_match = [
# Assert that an URL containing the http:// prefix is correctly read.
"http://www.huomao.com/123456",
"http://www.huo... | 0.678859 | 0.352731 |
import unittest
__all__ = ('PyhistorianSuite',)
class _FakeTestCase(unittest.TestCase):
"""
Fake TestCases do not count as a test and has a custom message
"""
def __init__(self, obj):
self._obj = obj
unittest.TestCase.__init__(self, 'fake_test')
def fake_test(self):
pass... | pyhistorian/suite.py | import unittest
__all__ = ('PyhistorianSuite',)
class _FakeTestCase(unittest.TestCase):
"""
Fake TestCases do not count as a test and has a custom message
"""
def __init__(self, obj):
self._obj = obj
unittest.TestCase.__init__(self, 'fake_test')
def fake_test(self):
pass... | 0.667256 | 0.343287 |
# Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import socket
import textwrap
import platform
# Import Salt Testing Libs
try:
import pytest
except ImportError as import_error:
pytest = None
from tests.support.mixins import LoaderModuleMock... | tests/unit/grains/test_core.py | # Import Python libs
from __future__ import absolute_import, print_function, unicode_literals
import logging
import os
import socket
import textwrap
import platform
# Import Salt Testing Libs
try:
import pytest
except ImportError as import_error:
pytest = None
from tests.support.mixins import LoaderModuleMock... | 0.399343 | 0.150559 |
from base64 import b64decode
from malwareconfig.common import Decoder
class njRat(Decoder):
decoder_name = "njRat"
decoder__version = 1
decoder_author = "@kevthehermit"
decoder_description = "njRAT"
def __init__(self):
self.config = {}
def get_config(self):
'''
This ... | malwareconfig/decoders/njrat.py | from base64 import b64decode
from malwareconfig.common import Decoder
class njRat(Decoder):
decoder_name = "njRat"
decoder__version = 1
decoder_author = "@kevthehermit"
decoder_description = "njRAT"
def __init__(self):
self.config = {}
def get_config(self):
'''
This ... | 0.203114 | 0.138491 |
import os
import builtins
import functools
from xonsh.tools import print_exception
def _chdir_up(path):
""" Change directory to path or if path does not exist
the first valid parent.
"""
try:
os.chdir(path)
return path
except (FileNotFoundError, NotADirectoryError):
par... | xontrib/free_cwd.py | import os
import builtins
import functools
from xonsh.tools import print_exception
def _chdir_up(path):
""" Change directory to path or if path does not exist
the first valid parent.
"""
try:
os.chdir(path)
return path
except (FileNotFoundError, NotADirectoryError):
par... | 0.294215 | 0.065247 |
from __future__ import absolute_import, division, print_function, unicode_literals
from netCDF4 import Dataset
import numpy as np
import matplotlib.pyplot as plt
model = '_MPASLI'
def tscale(time):
"""
scale time to sqrt(time) to emphasize earlier times
"""
return np.sqrt(time)
def intscale(time):
... | components/mpas-source/testing_and_setup/compass/landice/MISMIP+/mismip+PlotGL.py | from __future__ import absolute_import, division, print_function, unicode_literals
from netCDF4 import Dataset
import numpy as np
import matplotlib.pyplot as plt
model = '_MPASLI'
def tscale(time):
"""
scale time to sqrt(time) to emphasize earlier times
"""
return np.sqrt(time)
def intscale(time):
... | 0.551091 | 0.413714 |
from PyQt5.QtCore import QObject, QMutex, QIODevice, pyqtSlot, pyqtSignal, pyqtProperty, QVariant, QUrl
from PyQt5.QtCore import QFile, QFileInfo
from PyQt5.QtNetwork import QNetworkRequest, QNetworkReply
from Logger import Logger
import json
import hashlib
import time
class CachedRemoteFile(QObject):
update = py... | CachedRemoteFile.py |
from PyQt5.QtCore import QObject, QMutex, QIODevice, pyqtSlot, pyqtSignal, pyqtProperty, QVariant, QUrl
from PyQt5.QtCore import QFile, QFileInfo
from PyQt5.QtNetwork import QNetworkRequest, QNetworkReply
from Logger import Logger
import json
import hashlib
import time
class CachedRemoteFile(QObject):
update = py... | 0.381335 | 0.078289 |
class Project(object):
"""
Class to hold all of the Project objects
"""
def __init__(self, raw_data):
self.raw_project_data = raw_data
@property
def ProjectId(self):
return self.raw_project_data.get("ProjectId")
@property
def ProjectTypeId(self):
return self.ra... | MapItFastLib/Projects.py | class Project(object):
"""
Class to hold all of the Project objects
"""
def __init__(self, raw_data):
self.raw_project_data = raw_data
@property
def ProjectId(self):
return self.raw_project_data.get("ProjectId")
@property
def ProjectTypeId(self):
return self.ra... | 0.767211 | 0.225108 |
import sys
import os
import argparse
import time
import logging
import nelly
def main(argv=None):
if argv is None:
argv = sys.argv[1:]
argparser = argparse.ArgumentParser()
argparser.add_argument('grammar',
nargs='?', default=None,
help='Input file')
argparser.add_argument... | nelly/main.py |
import sys
import os
import argparse
import time
import logging
import nelly
def main(argv=None):
if argv is None:
argv = sys.argv[1:]
argparser = argparse.ArgumentParser()
argparser.add_argument('grammar',
nargs='?', default=None,
help='Input file')
argparser.add_argument... | 0.221772 | 0.065995 |
import itertools
from pathlib import Path
import json
from collections import namedtuple
'''
An entity namedtuple consists of the entity's name (e.g. alien) and the
id (symbol) of the entity used to represent the entity in the state
'''
Entity = namedtuple("Entity", "name id")
'''
A Game namedtuple specifies an assig... | messenger/envs/config.py | import itertools
from pathlib import Path
import json
from collections import namedtuple
'''
An entity namedtuple consists of the entity's name (e.g. alien) and the
id (symbol) of the entity used to represent the entity in the state
'''
Entity = namedtuple("Entity", "name id")
'''
A Game namedtuple specifies an assig... | 0.402627 | 0.354405 |
import matplotlib.pyplot as plt
import numpy as np
import csv
import math
import statistics
import os
def set_box_color(bp, color, ls):
plt.setp(bp['boxes'], color='black', ls=ls, lw=1)
plt.setp(bp['whiskers'], color='black', lw=1)
plt.setp(bp['caps'], color='black', lw=1)
plt.setp(bp['medians'], lw=1)... | final-results/presentation-plots/times.py | import matplotlib.pyplot as plt
import numpy as np
import csv
import math
import statistics
import os
def set_box_color(bp, color, ls):
plt.setp(bp['boxes'], color='black', ls=ls, lw=1)
plt.setp(bp['whiskers'], color='black', lw=1)
plt.setp(bp['caps'], color='black', lw=1)
plt.setp(bp['medians'], lw=1)... | 0.265499 | 0.492005 |
from __future__ import annotations
import dataclasses
import enum
import io
import secrets
import struct
from typing import Callable, Generator, Optional, Sequence, Tuple
from . import exceptions, extensions
from .typing import Data
try:
from .speedups import apply_mask
except ImportError: # pra... | resources/WPy32/python-3.10.2/Lib/site-packages/websockets/frames.py | from __future__ import annotations
import dataclasses
import enum
import io
import secrets
import struct
from typing import Callable, Generator, Optional, Sequence, Tuple
from . import exceptions, extensions
from .typing import Data
try:
from .speedups import apply_mask
except ImportError: # pra... | 0.814643 | 0.142888 |
from urllib.parse import urljoin
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.db import transaction
from django.urls import reverse
from django.utils.translation import gettext as _
from pretalx.event.utils import crea... | src/pretalx/common/management/commands/init.py | from urllib.parse import urljoin
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand
from django.db import transaction
from django.urls import reverse
from django.utils.translation import gettext as _
from pretalx.event.utils import crea... | 0.38885 | 0.108898 |
from to_python.core.types import FunctionType, \
FunctionArgument, \
FunctionArgumentValues, \
FunctionReturnTypes, \
FunctionSignature, \
FunctionDoc, \
FunctionData, \
CompoundFunctionData
DUMP_PARTIAL = [
CompoundFunctionData(
server=[
FunctionData(
si... | functions/marker_functions.py | from to_python.core.types import FunctionType, \
FunctionArgument, \
FunctionArgumentValues, \
FunctionReturnTypes, \
FunctionSignature, \
FunctionDoc, \
FunctionData, \
CompoundFunctionData
DUMP_PARTIAL = [
CompoundFunctionData(
server=[
FunctionData(
si... | 0.760917 | 0.479686 |
# noqa
from __future__ import unicode_literals
from django.conf import settings
from common.http import http_delete, http_get, http_post, http_put
from common.log import logger
from release.constants import EventStatusEnum
def _gen_header(app_code, auth_token):
headers = {
"Content-Type": "application/... | paas-ce/paas/paas/components/engine.py | # noqa
from __future__ import unicode_literals
from django.conf import settings
from common.http import http_delete, http_get, http_post, http_put
from common.log import logger
from release.constants import EventStatusEnum
def _gen_header(app_code, auth_token):
headers = {
"Content-Type": "application/... | 0.367951 | 0.073696 |
import os
import argparse
import getpass
import spam.ansirunner
import spam.plugins.rados as rados
def execute_ping(host_list, remote_user, remote_pass,
sudo=False, sudo_user=None, sudo_pass=None):
'''
Execute ls on some hosts
'''
runner = spam.ansirunner.AnsibleRunner()
result, ... | pyansible/examples/simple_commands.py |
import os
import argparse
import getpass
import spam.ansirunner
import spam.plugins.rados as rados
def execute_ping(host_list, remote_user, remote_pass,
sudo=False, sudo_user=None, sudo_pass=None):
'''
Execute ls on some hosts
'''
runner = spam.ansirunner.AnsibleRunner()
result, ... | 0.223377 | 0.056288 |
import struct
import logging
import argparse
import os
import socket
import time
import random
import dpkt
import threading
class LATRDPacket(object):
IDLE_PACKET_MASK = 0x000000000003F800
PRODUCER_ID_MASK = 0x03FC000000000000
TIME_SLICE_WRAP_MASK = 0x0003FFFFFFFC0000
TIME_SLICE_BUFFER_M... | tools/python/latrd_pcap_replay.py | import struct
import logging
import argparse
import os
import socket
import time
import random
import dpkt
import threading
class LATRDPacket(object):
IDLE_PACKET_MASK = 0x000000000003F800
PRODUCER_ID_MASK = 0x03FC000000000000
TIME_SLICE_WRAP_MASK = 0x0003FFFFFFFC0000
TIME_SLICE_BUFFER_M... | 0.582135 | 0.104067 |
from datetime import datetime
from jsonschema import validate
from jsonschema.exceptions import ValidationError as JsonSchemaValidationError
from .sentinel_exception import (
MappingValidationError,
)
def map_sentinel_data(mappings, data, logger, data_type, subtype):
"""Filter the raw data and returns the f... | azure_sentinel/utils/sentinel_helper.py | from datetime import datetime
from jsonschema import validate
from jsonschema.exceptions import ValidationError as JsonSchemaValidationError
from .sentinel_exception import (
MappingValidationError,
)
def map_sentinel_data(mappings, data, logger, data_type, subtype):
"""Filter the raw data and returns the f... | 0.893864 | 0.471588 |
from datetime import timedelta
from homeassistant.const import ENERGY_KILO_WATT_HOUR, TEMP_CELSIUS, PRESSURE_BAR
DOMAIN = "ebusd"
TIME_SECONDS = "seconds"
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=15)
# SensorTypes from ebusdpy module :
# 0='decimal', 1='time-schedule', 2='switch', 3='string', 4='value;status'
... | homeassistant/components/ebusd/const.py | from datetime import timedelta
from homeassistant.const import ENERGY_KILO_WATT_HOUR, TEMP_CELSIUS, PRESSURE_BAR
DOMAIN = "ebusd"
TIME_SECONDS = "seconds"
MIN_TIME_BETWEEN_UPDATES = timedelta(seconds=15)
# SensorTypes from ebusdpy module :
# 0='decimal', 1='time-schedule', 2='switch', 3='string', 4='value;status'
... | 0.592667 | 0.327077 |
import pytest
from stresscheckMHLWja import StressCheck
def test_calc_withoutmethod(stchk):
with pytest.raises(ValueError) as excinfo:
stchk.calc()
exc_msg = excinfo.value.args[0]
assert "Method is not set" in exc_msg
@pytest.mark.parametrize("method", ["sum", "table"])
def test_change_method(st... | tests/func/test_func.py | import pytest
from stresscheckMHLWja import StressCheck
def test_calc_withoutmethod(stchk):
with pytest.raises(ValueError) as excinfo:
stchk.calc()
exc_msg = excinfo.value.args[0]
assert "Method is not set" in exc_msg
@pytest.mark.parametrize("method", ["sum", "table"])
def test_change_method(st... | 0.446495 | 0.682825 |
from asynctest import patch
from homeassistant import config_entries, setup
from homeassistant.components.coolmaster.const import AVAILABLE_MODES, DOMAIN
def _flow_data():
options = {"host": "1.1.1.1"}
for mode in AVAILABLE_MODES:
options[mode] = True
return options
async def test_form(hass):
... | tests/components/coolmaster/test_config_flow.py | from asynctest import patch
from homeassistant import config_entries, setup
from homeassistant.components.coolmaster.const import AVAILABLE_MODES, DOMAIN
def _flow_data():
options = {"host": "1.1.1.1"}
for mode in AVAILABLE_MODES:
options[mode] = True
return options
async def test_form(hass):
... | 0.731826 | 0.486149 |
import os.path
import astropy.io.fits as pyfits
import logging
from collections import namedtuple
from casacore.tables import table as casacore_table
from casacore.images import image as casacore_image
from tkp.accessors.lofarcasaimage import LofarCasaImage
from tkp.accessors.lofarhdf5image import LofarHdf5Image
from t... | tkp/accessors/detection.py | import os.path
import astropy.io.fits as pyfits
import logging
from collections import namedtuple
from casacore.tables import table as casacore_table
from casacore.images import image as casacore_image
from tkp.accessors.lofarcasaimage import LofarCasaImage
from tkp.accessors.lofarhdf5image import LofarHdf5Image
from t... | 0.504394 | 0.289598 |
import datetime
from os import mkdir, rmdir
from shutil import rmtree
from flask import current_app
from purchasing.opportunities.models import Category, Vendor
from purchasing.data.importer.nigp import main as import_nigp
from purchasing_test.test_base import BaseTestCase
from purchasing_test.factories import Dep... | purchasing_test/integration/opportunities/test_opportunities_base.py |
import datetime
from os import mkdir, rmdir
from shutil import rmtree
from flask import current_app
from purchasing.opportunities.models import Category, Vendor
from purchasing.data.importer.nigp import main as import_nigp
from purchasing_test.test_base import BaseTestCase
from purchasing_test.factories import Dep... | 0.264453 | 0.086593 |
from typing import (
Any,
Dict,
)
import logging
from urllib.parse import urljoin
import requests
logger = logging.getLogger(__name__)
class HttpClient:
def __init__(
self,
base_url: str,
api_token: str,
timeout: float = None,
verify_tls: bool = True,
user... | cachetclient/httpclient.py | from typing import (
Any,
Dict,
)
import logging
from urllib.parse import urljoin
import requests
logger = logging.getLogger(__name__)
class HttpClient:
def __init__(
self,
base_url: str,
api_token: str,
timeout: float = None,
verify_tls: bool = True,
user... | 0.624064 | 0.079175 |
import os
import common_pygame
import random
pygame = common_pygame.pygame
screen= common_pygame.screen
class BackGen():
def __init__(self, single_sprites):
self.single_sprites=single_sprites
self.compteur=0
self.asteroidList=list()
self.ast = self.single_sprites['asteroid1.png']
self.rotateAst=0
de... | sources/background.py | import os
import common_pygame
import random
pygame = common_pygame.pygame
screen= common_pygame.screen
class BackGen():
def __init__(self, single_sprites):
self.single_sprites=single_sprites
self.compteur=0
self.asteroidList=list()
self.ast = self.single_sprites['asteroid1.png']
self.rotateAst=0
de... | 0.117243 | 0.274294 |
from __future__ import print_function
import sys
import os
import regreg.api as rr
import numpy as np
from selection.reduced_optimization.generative_model import generate_data, generate_data_random
from selection.reduced_optimization.initial_soln import instance
from selection.tests.instance import logistic_instance,... | sandbox/bayesian/lasso_selection.py | from __future__ import print_function
import sys
import os
import regreg.api as rr
import numpy as np
from selection.reduced_optimization.generative_model import generate_data, generate_data_random
from selection.reduced_optimization.initial_soln import instance
from selection.tests.instance import logistic_instance,... | 0.538741 | 0.385057 |
from __future__ import division
from collections import defaultdict
import itertools
import numpy as np
import six
__all__ = ['eval_detection_voc']
def bbox_iou(bbox_a, bbox_b):
"""Calculate the Intersection of Unions (IoUs) between bounding boxes.
IoU is calculated as a ratio of area of the intersection
... | Utils/voc_cal_ap.py | from __future__ import division
from collections import defaultdict
import itertools
import numpy as np
import six
__all__ = ['eval_detection_voc']
def bbox_iou(bbox_a, bbox_b):
"""Calculate the Intersection of Unions (IoUs) between bounding boxes.
IoU is calculated as a ratio of area of the intersection
... | 0.95018 | 0.817756 |
import inspect
from collections.abc import Iterable
from colossalai.registry import *
def build_from_config(module, config: dict):
"""Returns an object of :class:`module` constructed from `config`.
Args:
module: A python or user-defined class
config: A python dict containing information us... | colossalai/builder/builder.py |
import inspect
from collections.abc import Iterable
from colossalai.registry import *
def build_from_config(module, config: dict):
"""Returns an object of :class:`module` constructed from `config`.
Args:
module: A python or user-defined class
config: A python dict containing information us... | 0.905789 | 0.563438 |
from typing import Union, Dict, List, Any
from e2e.Libs.BLS import PrivateKey, Signature
from e2e.Classes.Transactions.Data import Data
from e2e.Classes.Consensus.Element import Element
from e2e.Classes.Consensus.Verification import Verification, SignedVerification
from e2e.Classes.Consensus.VerificationPacket impo... | e2e/Vectors/Generation/PrototypeChain.py |
from typing import Union, Dict, List, Any
from e2e.Libs.BLS import PrivateKey, Signature
from e2e.Classes.Transactions.Data import Data
from e2e.Classes.Consensus.Element import Element
from e2e.Classes.Consensus.Verification import Verification, SignedVerification
from e2e.Classes.Consensus.VerificationPacket impo... | 0.727879 | 0.403567 |
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from tb_rest_client.api_client import ApiClient
class RpcV2ControllerApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manua... | tb_rest_client/api/api_ce/rpc_v_2_controller_api.py | from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from tb_rest_client.api_client import ApiClient
class RpcV2ControllerApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manua... | 0.674908 | 0.041715 |
import pytest
from eth2.beacon.state_machines.forks.serenity.blocks import SerenityBeaconBlock
from eth2.beacon.tools.builder.proposer import create_mock_block
from eth2.beacon.types.historical_batch import HistoricalBatch
@pytest.mark.parametrize(
(
"validator_count,"
"slots_per_epoch,"
... | tests/eth2/core/beacon/state_machines/test_state_transition.py | import pytest
from eth2.beacon.state_machines.forks.serenity.blocks import SerenityBeaconBlock
from eth2.beacon.tools.builder.proposer import create_mock_block
from eth2.beacon.types.historical_batch import HistoricalBatch
@pytest.mark.parametrize(
(
"validator_count,"
"slots_per_epoch,"
... | 0.516839 | 0.522933 |
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
from model import SSD600, MultiBoxLoss
from datasets import GTSDBDataset
from utils import *
import os
# Data parameters
data_folder = '..\\RESOURCES\\' # folder with data files
# Model parameters
n_classes = len(label_map) # number of ... | SRC/train.py | import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
from model import SSD600, MultiBoxLoss
from datasets import GTSDBDataset
from utils import *
import os
# Data parameters
data_folder = '..\\RESOURCES\\' # folder with data files
# Model parameters
n_classes = len(label_map) # number of ... | 0.563018 | 0.379034 |
from django.core.urlresolvers import reverse
from django.template import defaultfilters as filters
from django.utils.http import urlencode
from django.utils.translation import ugettext_lazy as _
from horizon import tables
from openstack_dashboard import api
class DeleteFlavor(tables.DeleteAction):
data_type_si... | openstack_dashboard/dashboards/admin/flavors/tables.py |
from django.core.urlresolvers import reverse
from django.template import defaultfilters as filters
from django.utils.http import urlencode
from django.utils.translation import ugettext_lazy as _
from horizon import tables
from openstack_dashboard import api
class DeleteFlavor(tables.DeleteAction):
data_type_si... | 0.554712 | 0.084342 |
import os
import sys
import json
def getConfigDir():
if sys.platform == "win32":
app_config_dir = os.getenv("LOCALAPPDATA")
else:
app_config_dir = os.getenv("HOME")
if os.getenv("XDG_CONFIG_HOME"):
app_config_dir = os.getenv("XDG_CONFIG_HOME")
configDir = os.path.join(... | pyconfigstore3/utils.py | import os
import sys
import json
def getConfigDir():
if sys.platform == "win32":
app_config_dir = os.getenv("LOCALAPPDATA")
else:
app_config_dir = os.getenv("HOME")
if os.getenv("XDG_CONFIG_HOME"):
app_config_dir = os.getenv("XDG_CONFIG_HOME")
configDir = os.path.join(... | 0.106958 | 0.044911 |
from copy import deepcopy
from file_system import FileNotFoundError, StatInfo
from mock_file_system import MockFileSystem
from test_file_system import TestFileSystem
import unittest
_TEST_DATA = {
'404.html': '404.html contents',
'apps': {
'a11y.html': 'a11y.html contents',
'about_apps.html': 'about_apps.... | chrome/common/extensions/docs/server2/mock_file_system_test.py |
from copy import deepcopy
from file_system import FileNotFoundError, StatInfo
from mock_file_system import MockFileSystem
from test_file_system import TestFileSystem
import unittest
_TEST_DATA = {
'404.html': '404.html contents',
'apps': {
'a11y.html': 'a11y.html contents',
'about_apps.html': 'about_apps.... | 0.558327 | 0.266975 |
import etcd3aio.etcdrpc as etcdrpc
import etcd3aio.utils as utils
_OPERATORS = {
etcdrpc.Compare.EQUAL: "==",
etcdrpc.Compare.NOT_EQUAL: "!=",
etcdrpc.Compare.LESS: "<",
etcdrpc.Compare.GREATER: ">"
}
class BaseCompare(object):
def __init__(self, key, range_end=None):
self.key = key
... | etcd3aio/transactions.py | import etcd3aio.etcdrpc as etcdrpc
import etcd3aio.utils as utils
_OPERATORS = {
etcdrpc.Compare.EQUAL: "==",
etcdrpc.Compare.NOT_EQUAL: "!=",
etcdrpc.Compare.LESS: "<",
etcdrpc.Compare.GREATER: ">"
}
class BaseCompare(object):
def __init__(self, key, range_end=None):
self.key = key
... | 0.197677 | 0.094594 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('contacts', '0008_create_table_index'),
]
operations = [
migrations.AlterField(
model_name='comment',
... | contacts/migrations/0009_auto_20181031_1015.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('contacts', '0008_create_table_index'),
]
operations = [
migrations.AlterField(
model_name='comment',
... | 0.603114 | 0.10325 |
import logging
import time
import numpy as np
import tensorflow as tf
from easy_rec.python.input.input import Input
from easy_rec.python.utils import odps_util
from easy_rec.python.utils.tf_utils import get_tf_type
try:
import common_io
except Exception:
common_io = None
try:
from datahub import DataHub
from... | easy_rec/python/input/datahub_input.py | import logging
import time
import numpy as np
import tensorflow as tf
from easy_rec.python.input.input import Input
from easy_rec.python.utils import odps_util
from easy_rec.python.utils.tf_utils import get_tf_type
try:
import common_io
except Exception:
common_io = None
try:
from datahub import DataHub
from... | 0.447702 | 0.257765 |
import sys
import os
import json
import PySimpleGUI as sg
from shutil import copyfile
import copy
# C:\Users\timkay\AppData\Local\Arduino15
# c:/Users/timkay/AppData/Local/Arduino15/packages/arduino/hardware/avr/1.8.2/boards.txt
# c:/Users/timkay/AppData/Local/Arduino15/packages/arduino/hardware/samd/1.8.5/boards.txt... | arduino-boards.py | import sys
import os
import json
import PySimpleGUI as sg
from shutil import copyfile
import copy
# C:\Users\timkay\AppData\Local\Arduino15
# c:/Users/timkay/AppData/Local/Arduino15/packages/arduino/hardware/avr/1.8.2/boards.txt
# c:/Users/timkay/AppData/Local/Arduino15/packages/arduino/hardware/samd/1.8.5/boards.txt... | 0.15219 | 0.08141 |
file_path
#Code starts here
def read_file(path):
file = open(path,"r")
sentence = file.read()
file.close()
return sentence
sample_message = read_file(file_path)
print(sample_message)
# --------------
#Code starts here
def read_file(path1,path2):
file1 = open(path1,"r")
... | Handling-Program-flow-in-Python/code.py | file_path
#Code starts here
def read_file(path):
file = open(path,"r")
sentence = file.read()
file.close()
return sentence
sample_message = read_file(file_path)
print(sample_message)
# --------------
#Code starts here
def read_file(path1,path2):
file1 = open(path1,"r")
... | 0.094171 | 0.0713 |
# (c) 2020, <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: nomad_job_info
author: <NAME> (@chris93111)
version_added: "1.3.0"
short_desc... | venv/lib/python3.6/site-packages/ansible_collections/community/general/plugins/modules/nomad_job_info.py |
# (c) 2020, <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = '''
---
module: nomad_job_info
author: <NAME> (@chris93111)
version_added: "1.3.0"
short_desc... | 0.587115 | 0.272623 |
from contextlib import nullcontext
import pytest
from src.game_engine.engine import Engine
from src.game_engine.board import (
Board,
OutsideBoardException,
WrongPlayerException,
NotEnoughArgumentsException,
PositionTakenException,
PlayerWonStatus,
)
class TestBoard:
# pylint: disable=no-s... | tests/test_engine.py | from contextlib import nullcontext
import pytest
from src.game_engine.engine import Engine
from src.game_engine.board import (
Board,
OutsideBoardException,
WrongPlayerException,
NotEnoughArgumentsException,
PositionTakenException,
PlayerWonStatus,
)
class TestBoard:
# pylint: disable=no-s... | 0.754644 | 0.592843 |
from __future__ import absolute_import
from .Visitor import ScopeTrackingTransform
from .Nodes import StatListNode, SingleAssignmentNode, CFuncDefNode, DefNode
from .ExprNodes import DictNode, DictItemNode, NameNode, UnicodeNode
from .PyrexTypes import py_object_type
from .StringEncoding import EncodedString
from . im... | Cython/Compiler/AnalysedTreeTransforms.py | from __future__ import absolute_import
from .Visitor import ScopeTrackingTransform
from .Nodes import StatListNode, SingleAssignmentNode, CFuncDefNode, DefNode
from .ExprNodes import DictNode, DictItemNode, NameNode, UnicodeNode
from .PyrexTypes import py_object_type
from .StringEncoding import EncodedString
from . im... | 0.526343 | 0.322126 |
import aiohttp
from asynctest import patch
from homeassistant import config_entries, setup
from homeassistant.components.nws.const import DOMAIN
async def test_form(hass, mock_simple_nws_config):
"""Test we get the form."""
hass.config.latitude = 35
hass.config.longitude = -90
await setup.async_setu... | tests/components/nws/test_config_flow.py | import aiohttp
from asynctest import patch
from homeassistant import config_entries, setup
from homeassistant.components.nws.const import DOMAIN
async def test_form(hass, mock_simple_nws_config):
"""Test we get the form."""
hass.config.latitude = 35
hass.config.longitude = -90
await setup.async_setu... | 0.671686 | 0.471892 |