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 smtplib
from unittest.mock import patch, Mock
import pytest
from logbook import Logger
from fibratus.output.smtp import SmtpOutput
@pytest.fixture(scope='module')
def smtp_adapter():
config = {
'host': 'smtp.gmail.com',
'from': '<EMAIL>',
'password': '<PASSWORD>',
'to': ['... | tests/unit/output/smtp.py | import smtplib
from unittest.mock import patch, Mock
import pytest
from logbook import Logger
from fibratus.output.smtp import SmtpOutput
@pytest.fixture(scope='module')
def smtp_adapter():
config = {
'host': 'smtp.gmail.com',
'from': '<EMAIL>',
'password': '<PASSWORD>',
'to': ['... | 0.409221 | 0.414662 |
from __future__ import unicode_literals
import re
from calendar import timegm
from datetime import MAXYEAR, timedelta
from dateutil import relativedelta
from dateutil.tz import tzlocal, tzutc
from faker.utils import is_string
from faker.utils.datetime_safe import date, datetime, real_date, real_datetime
from .. i... | frappe-bench/env/lib/python2.7/site-packages/faker/providers/date_time/__init__.py |
from __future__ import unicode_literals
import re
from calendar import timegm
from datetime import MAXYEAR, timedelta
from dateutil import relativedelta
from dateutil.tz import tzlocal, tzutc
from faker.utils import is_string
from faker.utils.datetime_safe import date, datetime, real_date, real_datetime
from .. i... | 0.555676 | 0.089296 |
import json
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.common.abstract_client import AbstractClient
from tencentcloud.dayu.v20180709 import models
class DayuClient(AbstractClient):
_apiVersion = '2018-07-09'
_endpoint = 'dayu.tencentcloud... | tencentcloud/dayu/v20180709/dayu_client.py |
import json
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.common.abstract_client import AbstractClient
from tencentcloud.dayu.v20180709 import models
class DayuClient(AbstractClient):
_apiVersion = '2018-07-09'
_endpoint = 'dayu.tencentcloud... | 0.324128 | 0.055158 |
import os
import re
import sys
import glob
if len(sys.argv) < 2 or sys.argv[1] != 'YES!':
print('CAUTION: running this will alter **ALL** .py files in every subdirectory!')
print('To ensure you are certain you want to run it, call %s again with the argument "YES!"' % sys.argv[0])
sys.exit(1)
re_function... | addon_common/scripts/strip_debugging.py |
import os
import re
import sys
import glob
if len(sys.argv) < 2 or sys.argv[1] != 'YES!':
print('CAUTION: running this will alter **ALL** .py files in every subdirectory!')
print('To ensure you are certain you want to run it, call %s again with the argument "YES!"' % sys.argv[0])
sys.exit(1)
re_function... | 0.150029 | 0.082401 |
import mock
from six.moves import http_client
import sys
from cinder import context
from cinder import exception
from cinder.objects import volume as obj_volume
from cinder import test
from cinder.tests.unit import fake_constants as fake
from cinder.volume.drivers import nimble
from cinder.volume import volume_types... | cinder/tests/unit/volume/drivers/test_nimble.py |
import mock
from six.moves import http_client
import sys
from cinder import context
from cinder import exception
from cinder.objects import volume as obj_volume
from cinder import test
from cinder.tests.unit import fake_constants as fake
from cinder.volume.drivers import nimble
from cinder.volume import volume_types... | 0.292797 | 0.118615 |
import roslib
roslib.load_manifest('SAFMC-21-D2-Team2')
import sys
import rospy
from statistics import mean
import numpy as np
import cv2 as cv
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
class BoxCV:
def __init__(self, output=False):
... | src/box.py |
import roslib
roslib.load_manifest('SAFMC-21-D2-Team2')
import sys
import rospy
from statistics import mean
import numpy as np
import cv2 as cv
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
class BoxCV:
def __init__(self, output=False):
... | 0.214034 | 0.1941 |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from de... | pybind/slxos/v16r_1_00b/routing_system/router/router_bgp/address_family/ipv6/ipv6_unicast/default_vrf/af_common_cmds_holder/graceful_restart/__init__.py | from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from de... | 0.667148 | 0.067424 |
import json
from pyrogram import Client, filters
from firebase import firebase
from process import check, searches, truecaller_search, fb_search, logreturn, log, eyecon_search
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from creds import cred
firebase = firebase.FirebaseApplication(cred.DB_UR... | main.py | import json
from pyrogram import Client, filters
from firebase import firebase
from process import check, searches, truecaller_search, fb_search, logreturn, log, eyecon_search
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from creds import cred
firebase = firebase.FirebaseApplication(cred.DB_UR... | 0.257765 | 0.088072 |
# Import `FEModel3D` from `PyNite`
from PyNite import FEModel3D
# Import 'Visualization' for rendering the model
from PyNite import Visualization
# Create a new finite element model
SimpleBeam = FEModel3D()
# Add nodes (14 ft apart)
SimpleBeam.AddNode('N1', 0, 0, 0)
SimpleBeam.AddNode('N2', 14*12, 0, 0)
# Add a be... | Examples/Simple Beam - Point Load.py |
# Import `FEModel3D` from `PyNite`
from PyNite import FEModel3D
# Import 'Visualization' for rendering the model
from PyNite import Visualization
# Create a new finite element model
SimpleBeam = FEModel3D()
# Add nodes (14 ft apart)
SimpleBeam.AddNode('N1', 0, 0, 0)
SimpleBeam.AddNode('N2', 14*12, 0, 0)
# Add a be... | 0.798344 | 0.6508 |
import gi
try:
gi.require_version('Gtk', '3.0')
gi.require_version('Gdk', '3.0')
except Exception as e:
print(e)
exit(-1)
from gi.repository import Gtk
from gi.repository import Gdk
import sys
import importlib
import comun
from config import Configuration
from croni import Croni
from autostart import A... | src/main.py |
import gi
try:
gi.require_version('Gtk', '3.0')
gi.require_version('Gdk', '3.0')
except Exception as e:
print(e)
exit(-1)
from gi.repository import Gtk
from gi.repository import Gdk
import sys
import importlib
import comun
from config import Configuration
from croni import Croni
from autostart import A... | 0.31237 | 0.13707 |
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('application', '0049_auto_20201119_0924'),
]
operations = [
migrations.RemoveField(
model_name='landingpages',
name='button_text_en',
),
migrations.RemoveFie... | application/migrations/0050_auto_20201222_1046.py |
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('application', '0049_auto_20201119_0924'),
]
operations = [
migrations.RemoveField(
model_name='landingpages',
name='button_text_en',
),
migrations.RemoveFie... | 0.594904 | 0.097347 |
import argparse
import logging
import os
import random
import socket
import sys
import traceback
import numpy as np
import psutil
import setproctitle
import torch
import wandb
from mpi4py import MPI
# add the FedML root directory to the python path
sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../.... | fedml_experiments/distributed/fedavg/main_fedavg.py | import argparse
import logging
import os
import random
import socket
import sys
import traceback
import numpy as np
import psutil
import setproctitle
import torch
import wandb
from mpi4py import MPI
# add the FedML root directory to the python path
sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../.... | 0.441432 | 0.173113 |
"""End-to-end tests for federated trainer tasks."""
import collections
import os.path
from absl.testing import parameterized
import tensorflow as tf
import tensorflow_federated as tff
from optimization.cifar100 import federated_cifar100
from optimization.emnist import federated_emnist
from optimization.emnist_ae imp... | optimization/main/federated_tasks_test.py | """End-to-end tests for federated trainer tasks."""
import collections
import os.path
from absl.testing import parameterized
import tensorflow as tf
import tensorflow_federated as tff
from optimization.cifar100 import federated_cifar100
from optimization.emnist import federated_emnist
from optimization.emnist_ae imp... | 0.838944 | 0.402627 |
import re # noqa: F401
from xero_python.models import BaseModel
class EmployeeLeaveBalance(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is ... | xero_python/payrolluk/models/employee_leave_balance.py | import re # noqa: F401
from xero_python.models import BaseModel
class EmployeeLeaveBalance(BaseModel):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is ... | 0.784773 | 0.140631 |
import numpy as np
import scipy.linalg as spla
from scipy.spatial.distance import cdist
def chol2inv(chol):
return spla.cho_solve((chol, False), np.eye(chol.shape[ 0 ]))
def matrixInverse(M):
return chol2inv(spla.cholesky(M, lower=False))
def compute_kernel(lls, lsf, x, z):
ls = np.exp(lls)
sf = n... | numpy/deepgp_approxep/EQ_kernel.py | import numpy as np
import scipy.linalg as spla
from scipy.spatial.distance import cdist
def chol2inv(chol):
return spla.cho_solve((chol, False), np.eye(chol.shape[ 0 ]))
def matrixInverse(M):
return chol2inv(spla.cholesky(M, lower=False))
def compute_kernel(lls, lsf, x, z):
ls = np.exp(lls)
sf = n... | 0.579638 | 0.640833 |
# pylint: disable-msg=C6310
"""Channel Tic Tac Toe
This module demonstrates the App Engine Channel API by implementing a
simple tic-tac-toe game.
"""
import datetime
import logging
import os
import random
import re
import uuid
import sys
from django.utils import simplejson
from google.appengine.api import channel
f... | apps/samples/appengine-channelapi/appengine/chatactoe.py |
# pylint: disable-msg=C6310
"""Channel Tic Tac Toe
This module demonstrates the App Engine Channel API by implementing a
simple tic-tac-toe game.
"""
import datetime
import logging
import os
import random
import re
import uuid
import sys
from django.utils import simplejson
from google.appengine.api import channel
f... | 0.480722 | 0.081703 |
from jumpscale import j
from zerorobot.template.base import TemplateBase
from zerorobot.template.state import StateCheckError
from zerorobot.service_collection import ServiceNotFoundError
ZERODB_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zerodb/0.0.1'
NODE_CLIENT = 'local'
class Vdisk(TemplateBase):
v... | templates/vdisk/vdisk.py | from jumpscale import j
from zerorobot.template.base import TemplateBase
from zerorobot.template.state import StateCheckError
from zerorobot.service_collection import ServiceNotFoundError
ZERODB_TEMPLATE_UID = 'github.com/threefoldtech/0-templates/zerodb/0.0.1'
NODE_CLIENT = 'local'
class Vdisk(TemplateBase):
v... | 0.591015 | 0.138666 |
import logging
SUPPORTED_SCALING_FACTORS = [(7, 8), (3, 4), (5, 8), (1, 2), (3, 8), (1, 4), (1, 8)]
_LOGGER = logging.getLogger(__name__)
def scale_jpeg_camera_image(cam_image, width, height):
"""Scale a camera image as close as possible to one of the supported scaling factors."""
turbo_jpeg = TurboJPEGSin... | homeassistant/components/homekit/img_util.py |
import logging
SUPPORTED_SCALING_FACTORS = [(7, 8), (3, 4), (5, 8), (1, 2), (3, 8), (1, 4), (1, 8)]
_LOGGER = logging.getLogger(__name__)
def scale_jpeg_camera_image(cam_image, width, height):
"""Scale a camera image as close as possible to one of the supported scaling factors."""
turbo_jpeg = TurboJPEGSin... | 0.803135 | 0.201401 |
from hangulize import *
class Dutch(Language):
"""For transcribing Dutch."""
__iso639__ = {1: 'nl', 2: 'dut', 3: 'nld'}
__tmp__ = '%,;&'
vowels = 'aeEioOuUyQ'
cs = 'b', 'B', 'c', 'C', 'd', 'D', 'f', 'F', 'g', 'G', 'h', 'j', 'J', \
'k', 'K', 'l', 'm', 'n', 'N', 'p', 'P', 'q', 'r', 's', '... | hangulize/langs/nld/__init__.py | from hangulize import *
class Dutch(Language):
"""For transcribing Dutch."""
__iso639__ = {1: 'nl', 2: 'dut', 3: 'nld'}
__tmp__ = '%,;&'
vowels = 'aeEioOuUyQ'
cs = 'b', 'B', 'c', 'C', 'd', 'D', 'f', 'F', 'g', 'G', 'h', 'j', 'J', \
'k', 'K', 'l', 'm', 'n', 'N', 'p', 'P', 'q', 'r', 's', '... | 0.316369 | 0.221656 |
from units import unit
from items import item
import time
going = True
coins = 10
player_score = 0
player_round = 0
n_shop_items = 2
n_shop_units = 4
n_roster = 5
roster = []
for i in range(n_roster):
roster.append(0)
shop_units = []
shop_items = []
shop_units = []
for i in range(n_shop_units):
shop_units... | main.py | from units import unit
from items import item
import time
going = True
coins = 10
player_score = 0
player_round = 0
n_shop_items = 2
n_shop_units = 4
n_roster = 5
roster = []
for i in range(n_roster):
roster.append(0)
shop_units = []
shop_items = []
shop_units = []
for i in range(n_shop_units):
shop_units... | 0.087474 | 0.238517 |
import pandas as pd
import os
# creating a class named Song
class Song:
def __init__(self, song_name, path): # initializing object
self.song_name = song_name
self.path = path
# defining the function to return song info
def getinfo(self):
#handling none input type
if se... | modules/getinfo.py | import pandas as pd
import os
# creating a class named Song
class Song:
def __init__(self, song_name, path): # initializing object
self.song_name = song_name
self.path = path
# defining the function to return song info
def getinfo(self):
#handling none input type
if se... | 0.222109 | 0.120129 |
import os
from distutils.util import convert_path
from fnmatch import fnmatchcase
from setuptools import find_packages, setup
standard_exclude = ('*.pyc', '*~', '.*', '*.bak', '*.swp*')
standard_exclude_directories = (
'.*', 'CVS', '_darcs', './build', './dist', 'EGG-INFO', '*.egg-info')
def long_description()... | setup.py |
import os
from distutils.util import convert_path
from fnmatch import fnmatchcase
from setuptools import find_packages, setup
standard_exclude = ('*.pyc', '*~', '.*', '*.bak', '*.swp*')
standard_exclude_directories = (
'.*', 'CVS', '_darcs', './build', './dist', 'EGG-INFO', '*.egg-info')
def long_description()... | 0.329392 | 0.120206 |
### Python imports
import pathlib
### Third Party imports
import numpy as np
import pandas as pd
import pytest
### Project imports
from t4.formats import FormatRegistry
from t4.util import QuiltException
### Constants
### Code
def test_buggy_parquet():
"""
Test that T4 avoids crashing on bad Pandas metad... | api/python/tests/test_formats.py |
### Python imports
import pathlib
### Third Party imports
import numpy as np
import pandas as pd
import pytest
### Project imports
from t4.formats import FormatRegistry
from t4.util import QuiltException
### Constants
### Code
def test_buggy_parquet():
"""
Test that T4 avoids crashing on bad Pandas metad... | 0.672224 | 0.44071 |
class parser:
"""Parser for OpenFlow packets
(C) Copyright Stanford University
Date October 2009
Created by ykk
"""
def __init__(self, messages):
"""Initialize
"""
##Internal reference to OpenFlow messages
self.__messages = messages
def describe(self, p... | utils/demo/pylibopenflow/of/msg.py | class parser:
"""Parser for OpenFlow packets
(C) Copyright Stanford University
Date October 2009
Created by ykk
"""
def __init__(self, messages):
"""Initialize
"""
##Internal reference to OpenFlow messages
self.__messages = messages
def describe(self, p... | 0.459804 | 0.331661 |
import inspect
import os
import random
import string
import time
import pytest
from fixedrec import RecordFile, RecordFileError
DATADIR = os.path.join(os.path.split(__file__)[0], 'data') + '/blockfile-'
def fname(d):
fn_name = inspect.currentframe().f_back.f_code.co_name
return d / fn_name
def test_open(t... | tests/test_recordfile.py | import inspect
import os
import random
import string
import time
import pytest
from fixedrec import RecordFile, RecordFileError
DATADIR = os.path.join(os.path.split(__file__)[0], 'data') + '/blockfile-'
def fname(d):
fn_name = inspect.currentframe().f_back.f_code.co_name
return d / fn_name
def test_open(t... | 0.231875 | 0.40987 |
from inspect import cleandoc
from testfixtures import compare
from mlinspect._pipeline_inspector import PipelineInspector
from mlinspect.inspections import CompletenessOfColumns
def test_completeness_merge():
"""
Tests whether CompletenessOfColumns works for joins
"""
test_code = cleandoc("""
... | test/inspections/test_completeness_of_columns.py | from inspect import cleandoc
from testfixtures import compare
from mlinspect._pipeline_inspector import PipelineInspector
from mlinspect.inspections import CompletenessOfColumns
def test_completeness_merge():
"""
Tests whether CompletenessOfColumns works for joins
"""
test_code = cleandoc("""
... | 0.660172 | 0.467879 |
import os, sys
from pip.req import InstallRequirement, RequirementSet
from pip.req import parse_requirements
from pip.log import logger
from pip.locations import build_prefix, src_prefix
from pip.basecommand import Command
from pip.index import PackageFinder
from pip.exceptions import InstallationError
class InstallC... | docs/docs_env/Lib/site-packages/pip-1.0-py2.5.egg/pip/commands/install.py | import os, sys
from pip.req import InstallRequirement, RequirementSet
from pip.req import parse_requirements
from pip.log import logger
from pip.locations import build_prefix, src_prefix
from pip.basecommand import Command
from pip.index import PackageFinder
from pip.exceptions import InstallationError
class InstallC... | 0.341253 | 0.069795 |
from __future__ import absolute_import
import bson
import mock
from st2common.constants.triggers import TIMER_TRIGGER_TYPES
from st2common.models.db.trigger import TriggerDB
from st2common.models.system.common import ResourceReference
from st2common.persistence.trigger import TriggerType
from st2common.persistence.tr... | st2reactor/tests/unit/test_timer.py |
from __future__ import absolute_import
import bson
import mock
from st2common.constants.triggers import TIMER_TRIGGER_TYPES
from st2common.models.db.trigger import TriggerDB
from st2common.models.system.common import ResourceReference
from st2common.persistence.trigger import TriggerType
from st2common.persistence.tr... | 0.758332 | 0.267996 |
from django.conf import settings
from django.shortcuts import redirect
from django.urls import reverse, reverse_lazy
from django.utils.http import is_safe_url
from django.utils.translation import gettext_lazy as _
from django.views.generic import FormView, TemplateView
from mtp_common.auth.api_client import get_api_ses... | mtp_noms_ops/apps/security/views/eligibility.py | from django.conf import settings
from django.shortcuts import redirect
from django.urls import reverse, reverse_lazy
from django.utils.http import is_safe_url
from django.utils.translation import gettext_lazy as _
from django.views.generic import FormView, TemplateView
from mtp_common.auth.api_client import get_api_ses... | 0.393152 | 0.064271 |
import os
import urllib.request
from PIL import Image
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import config
def save_image_from_message(message, telbot):
cid = message.chat.id
image_id = get_image_id_from_message(message)
# prepare image for downloading
file_path = tel... | image_utils.py | import os
import urllib.request
from PIL import Image
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import config
def save_image_from_message(message, telbot):
cid = message.chat.id
image_id = get_image_id_from_message(message)
# prepare image for downloading
file_path = tel... | 0.385953 | 0.166743 |
import datetime
from unittest import mock
from django.db import (
IntegrityError, NotSupportedError, connection, transaction,
)
from django.db.models import (
CheckConstraint, Deferrable, F, Func, Q, UniqueConstraint,
)
from django.db.models.fields.json import KeyTextTransform
from django.db.models.functions i... | tests/postgres_tests/test_constraints.py | import datetime
from unittest import mock
from django.db import (
IntegrityError, NotSupportedError, connection, transaction,
)
from django.db.models import (
CheckConstraint, Deferrable, F, Func, Q, UniqueConstraint,
)
from django.db.models.fields.json import KeyTextTransform
from django.db.models.functions i... | 0.645232 | 0.34679 |
import time
import logging
import json
from sjsclient import client
logging.basicConfig()
logger = logging.getLogger()
logger.setLevel(logging.INFO)
sjs = client.Client("http://jobserver.ml-test-blog.internal:8090")
myApp = sjs.apps.get("ml")
myContext = sjs.contexts.get("ml-context")
def testHandler(event, context... | aws-blog-jobserver-emr/python_lambda/models.py | import time
import logging
import json
from sjsclient import client
logging.basicConfig()
logger = logging.getLogger()
logger.setLevel(logging.INFO)
sjs = client.Client("http://jobserver.ml-test-blog.internal:8090")
myApp = sjs.apps.get("ml")
myContext = sjs.contexts.get("ml-context")
def testHandler(event, context... | 0.158695 | 0.049543 |
WIDTH = 8
HEIGHT = 8
FIRST = 0x20
LAST = 0x7f
_FONT =\
b'\x00\x00\x00\x00\x00\x00\x00\x00'\
b'\x18\x3c\x3c\x18\x18\x00\x18\x00'\
b'\x6c\x6c\x6c\x00\x00\x00\x00\x00'\
b'\x6c\x6c\xfe\x6c\xfe\x6c\x6c\x00'\
b'\x18\x7e\xc0\x7c\x06\xfc\x18\x00'\
b'\x00\xc6\xcc\x18\x30\x66\xc6\x00'\
b'\x38\x6c\x38\x76\xdc\xcc\x76\x00'\
b'\x30... | fonts/diamonstealth64_8x8.py | WIDTH = 8
HEIGHT = 8
FIRST = 0x20
LAST = 0x7f
_FONT =\
b'\x00\x00\x00\x00\x00\x00\x00\x00'\
b'\x18\x3c\x3c\x18\x18\x00\x18\x00'\
b'\x6c\x6c\x6c\x00\x00\x00\x00\x00'\
b'\x6c\x6c\xfe\x6c\xfe\x6c\x6c\x00'\
b'\x18\x7e\xc0\x7c\x06\xfc\x18\x00'\
b'\x00\xc6\xcc\x18\x30\x66\xc6\x00'\
b'\x38\x6c\x38\x76\xdc\xcc\x76\x00'\
b'\x30... | 0.130161 | 0.462109 |
import click
from tripaille.cli import pass_context
from tripaille.decorators import custom_exception, str_output
@click.command('load_blast')
@click.argument("name", type=str)
@click.argument("program", type=str)
@click.argument("programversion", type=str)
@click.argument("sourcename", type=str)
@click.argument("bla... | tripaille/commands/analysis/load_blast.py | import click
from tripaille.cli import pass_context
from tripaille.decorators import custom_exception, str_output
@click.command('load_blast')
@click.argument("name", type=str)
@click.argument("program", type=str)
@click.argument("programversion", type=str)
@click.argument("sourcename", type=str)
@click.argument("bla... | 0.577138 | 0.181173 |
from .abstract_data_operation_config import AbstractDataOperationConfig
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class ReadOperationConfig(AbstractDataOperationConfi... | src/oci/data_integration/models/read_operation_config.py |
from .abstract_data_operation_config import AbstractDataOperationConfig
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class ReadOperationConfig(AbstractDataOperationConfi... | 0.812793 | 0.302436 |
import hashlib
import json
import pathlib
from unittest import mock
from gs_quant.api.gs.risk import GsRiskApi
from gs_quant.json_encoder import JSONEncoder
from gs_quant.markets import PricingContext
from gs_quant.session import Environment, GsSession
def _remove_unwanted(json_text):
json_dict = json.loads(json... | gs_quant/test/utils/test_utils.py | import hashlib
import json
import pathlib
from unittest import mock
from gs_quant.api.gs.risk import GsRiskApi
from gs_quant.json_encoder import JSONEncoder
from gs_quant.markets import PricingContext
from gs_quant.session import Environment, GsSession
def _remove_unwanted(json_text):
json_dict = json.loads(json... | 0.441673 | 0.211722 |
import yaml
import os
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
def load_config(config_file):
"""Load config file with yaml.
Args:
config_file: config_file
Returns:
config file
"""
with open(config_file, 'r') as stream:
... | src/parameters.py | import yaml
import os
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
def load_config(config_file):
"""Load config file with yaml.
Args:
config_file: config_file
Returns:
config file
"""
with open(config_file, 'r') as stream:
... | 0.579995 | 0.144179 |
from os import listdir
from os.path import exists, join, isfile
from argparse import ArgumentParser
from tqdm import tqdm
def load_label_map(file_path):
action_names = []
with open(file_path) as input_stream:
for line in input_stream:
line_parts = line.strip().split(';')
if le... | models/action_recognition/model_templates/gesture-recognition/tools/data/prepare_jester_annot.py | from os import listdir
from os.path import exists, join, isfile
from argparse import ArgumentParser
from tqdm import tqdm
def load_label_map(file_path):
action_names = []
with open(file_path) as input_stream:
for line in input_stream:
line_parts = line.strip().split(';')
if le... | 0.454956 | 0.35928 |
import numpy as np
def load_streamflow(path):
"""load streamflow into memory
Args:
path (str|DataFrame): path of streamflow csv file, or pandas DataFrame
Returns:
tuple: (date of np.datetime64, streamflow of float)
"""
if isinstance(path, str):
date, Q = np.loadtxt(
... | src/hydrotoolbox/baseflow/utils.py | import numpy as np
def load_streamflow(path):
"""load streamflow into memory
Args:
path (str|DataFrame): path of streamflow csv file, or pandas DataFrame
Returns:
tuple: (date of np.datetime64, streamflow of float)
"""
if isinstance(path, str):
date, Q = np.loadtxt(
... | 0.741487 | 0.582669 |
import numpy as np
import pytest
import autogalaxy as ag
from autoarray.inversion import inversions
from autogalaxy.mock.mock import MockLightProfile
class MockFitImaging:
def __init__(self, model_images_of_galaxies):
self.model_images_of_galaxies = model_images_of_galaxies
class TestFit... | test_autogalaxy/unit/fit/test_fit.py | import numpy as np
import pytest
import autogalaxy as ag
from autoarray.inversion import inversions
from autogalaxy.mock.mock import MockLightProfile
class MockFitImaging:
def __init__(self, model_images_of_galaxies):
self.model_images_of_galaxies = model_images_of_galaxies
class TestFit... | 0.799677 | 0.590484 |
import numpy as np
import networkx as nx
from networkx.utils import np_random_state
def _process_params(G, center):
if not isinstance(G, nx.Graph):
empty_graph = nx.Graph()
empty_graph.add_nodes_from(G)
G = empty_graph
center = np.zeros(2) if center is None else np.asarray(center)
return G, center
def spring... | fr_nx.py | import numpy as np
import networkx as nx
from networkx.utils import np_random_state
def _process_params(G, center):
if not isinstance(G, nx.Graph):
empty_graph = nx.Graph()
empty_graph.add_nodes_from(G)
G = empty_graph
center = np.zeros(2) if center is None else np.asarray(center)
return G, center
def spring... | 0.79542 | 0.676112 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
__all__ = [
'GetVirtualMachineScaleSetResult',
'AwaitableGetVirtualMachineScaleSetResult',
'get_virtual_machine_scale_set',
]
@pulumi.ou... | sdk/python/pulumi_azure_nextgen/compute/v20160330/get_virtual_machine_scale_set.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from . import outputs
__all__ = [
'GetVirtualMachineScaleSetResult',
'AwaitableGetVirtualMachineScaleSetResult',
'get_virtual_machine_scale_set',
]
@pulumi.ou... | 0.833155 | 0.074467 |
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
import tkinter as tk
from main import main, conversion
import math
import sys
from onefile import *
import os
print (os.getcwd())
def center_window(win, width=300, height=200):
# get screen width and height
screen_width = ro... | src/convert_tool.py | from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
import tkinter as tk
from main import main, conversion
import math
import sys
from onefile import *
import os
print (os.getcwd())
def center_window(win, width=300, height=200):
# get screen width and height
screen_width = ro... | 0.181118 | 0.088978 |
import logging
from base64 import b64decode
from pyramid.view import view_config
from pyramid.security import NO_PERMISSION_REQUIRED
from pyramid.security import authenticated_userid
from pyramid.security import Authenticated
from pyramid.httpexceptions import HTTPFound
from six.moves.urllib.parse import urlparse
fr... | pyramid_oauth2_provider/views.py |
import logging
from base64 import b64decode
from pyramid.view import view_config
from pyramid.security import NO_PERMISSION_REQUIRED
from pyramid.security import authenticated_userid
from pyramid.security import Authenticated
from pyramid.httpexceptions import HTTPFound
from six.moves.urllib.parse import urlparse
fr... | 0.752649 | 0.118385 |
from chainer.training import extension
from chainer.training import trigger as trigger_module
class LossSplit(extension.Extension):
def __init__(self, trigger=(10000, 'iteration'), postprocess=None,
segmentation_loss_key='main/loss/mask',
detection_loss_loc_key='main/loss/loc', d... | multi_task/extensions/loss_split.py | from chainer.training import extension
from chainer.training import trigger as trigger_module
class LossSplit(extension.Extension):
def __init__(self, trigger=(10000, 'iteration'), postprocess=None,
segmentation_loss_key='main/loss/mask',
detection_loss_loc_key='main/loss/loc', d... | 0.925048 | 0.133472 |
from __future__ import absolute_import
from __future__ import unicode_literals
from pyramid.view import view_config
from schematizer.api.decorators import log_api
from schematizer.api.decorators import transform_api_response
from schematizer.api.exceptions import exceptions_v1
from schematizer.api.requests import req... | schematizer/views/notes.py | from __future__ import absolute_import
from __future__ import unicode_literals
from pyramid.view import view_config
from schematizer.api.decorators import log_api
from schematizer.api.decorators import transform_api_response
from schematizer.api.exceptions import exceptions_v1
from schematizer.api.requests import req... | 0.663124 | 0.109658 |
import click
import sys
import traceback
import os
import opencc
from lightnovel import LightNovel
from utils import echo
from provider import lk_new
from provider import wenku8
from provider import lk_mobile
echo.init_subroutine()
@click.group()
def cli():
pass
@cli.command()
# general options
@click.option('-... | cli.py | import click
import sys
import traceback
import os
import opencc
from lightnovel import LightNovel
from utils import echo
from provider import lk_new
from provider import wenku8
from provider import lk_mobile
echo.init_subroutine()
@click.group()
def cli():
pass
@cli.command()
# general options
@click.option('-... | 0.193833 | 0.073696 |
from CodaClient import Client, Currency, CurrencyFormat
import os
import schedule
import time
import urllib3
import random
from requests.exceptions import ConnectionError
from prometheus_client import Counter, start_http_server
def getenv_default_map(env_var: str, f, default):
value = os.getenv(env_var)
if val... | automation/services/coda-user-agent/agent.py | from CodaClient import Client, Currency, CurrencyFormat
import os
import schedule
import time
import urllib3
import random
from requests.exceptions import ConnectionError
from prometheus_client import Counter, start_http_server
def getenv_default_map(env_var: str, f, default):
value = os.getenv(env_var)
if val... | 0.46393 | 0.111 |
from __future__ import absolute_import
from collections import namedtuple
from typing import (Any, Callable, Dict, # pylint: disable=unused-import
Generator, Iterable, List, Text, Union, cast)
from .errors import WorkflowException
MutationState = namedtuple("MutationTracker", ["generation", "rea... | cwltool/mutation.py | from __future__ import absolute_import
from collections import namedtuple
from typing import (Any, Callable, Dict, # pylint: disable=unused-import
Generator, Iterable, List, Text, Union, cast)
from .errors import WorkflowException
MutationState = namedtuple("MutationTracker", ["generation", "rea... | 0.692538 | 0.128662 |
from .input_components.OneChannel import OneChannel
from .input_components.TwoEmbChannel import TwoEmbChannel
from .input_components.SixChannel import SixChannel
from .input_components.OneChannel_DocLevel import OneChannel_DocLevel
from .middle_components.parallel_conv import NParallelConvOnePoolNFC
from .middle_compon... | networks/cnn.py | from .input_components.OneChannel import OneChannel
from .input_components.TwoEmbChannel import TwoEmbChannel
from .input_components.SixChannel import SixChannel
from .input_components.OneChannel_DocLevel import OneChannel_DocLevel
from .middle_components.parallel_conv import NParallelConvOnePoolNFC
from .middle_compon... | 0.675765 | 0.322046 |
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import math
#https://github.com/ShichenLiu/CondenseNet
class Lear... | modles/condensenet.py | from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import math
#https://github.com/ShichenLiu/CondenseNet
class Lear... | 0.939157 | 0.36659 |
import random
import json
from pygame.locals import *
import os
import pygame
import pygameMenu
from pygameMenu.locals import *
WIDTH = 900
HEIGHT = 700
FPS = 60
pygame.init()
os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.se... | The Defender.py | import random
import json
from pygame.locals import *
import os
import pygame
import pygameMenu
from pygameMenu.locals import *
WIDTH = 900
HEIGHT = 700
FPS = 60
pygame.init()
os.environ['SDL_VIDEO_CENTERED'] = '1'
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.se... | 0.139338 | 0.116362 |
from flask import Flask
from {{cookiecutter.app_name}} import auth, api
from {{cookiecutter.app_name}}.extensions import db, jwt, migrate, apispec
{%- if cookiecutter.use_celery == "yes"%}, celery{% endif%}
def create_app(testing=False, cli=False):
"""Application factory, used to create application"""
app = ... | {{cookiecutter.project_name}}/{{cookiecutter.app_name}}/app.py | from flask import Flask
from {{cookiecutter.app_name}} import auth, api
from {{cookiecutter.app_name}}.extensions import db, jwt, migrate, apispec
{%- if cookiecutter.use_celery == "yes"%}, celery{% endif%}
def create_app(testing=False, cli=False):
"""Application factory, used to create application"""
app = ... | 0.532425 | 0.093347 |
import copy
from cinderclient import exceptions as cinder_exp
import mock
from oslo_config import cfg
import six
from heat.common import exception
from heat.common import template_format
from heat.engine.clients.os import cinder
from heat.engine.clients.os import nova
from heat.engine.resources.aws.ec2 import instan... | heat/tests/aws/test_volume.py |
import copy
from cinderclient import exceptions as cinder_exp
import mock
from oslo_config import cfg
import six
from heat.common import exception
from heat.common import template_format
from heat.engine.clients.os import cinder
from heat.engine.clients.os import nova
from heat.engine.resources.aws.ec2 import instan... | 0.485112 | 0.25682 |
import collections
import itertools
from textwrap import dedent
import pytest
import pytablewriter as ptw
from ..._common import print_test_result
from ...data import (
float_header_list,
float_value_matrix,
headers,
mix_header_list,
mix_value_matrix,
value_matrix,
value_matrix_iter,
... | test/writer/text/test_csv_writer.py | import collections
import itertools
from textwrap import dedent
import pytest
import pytablewriter as ptw
from ..._common import print_test_result
from ...data import (
float_header_list,
float_value_matrix,
headers,
mix_header_list,
mix_value_matrix,
value_matrix,
value_matrix_iter,
... | 0.378115 | 0.445047 |
import argparse
import sys
from pathlib import Path
from typing import Callable, Dict
from determined.common.declarative_argparse import Arg, BoolOptArg, Cmd, Group
from . import cluster_utils
from .preflight import check_docker_install
def handle_cluster_up(args: argparse.Namespace) -> None:
if not args.no_pre... | harness/determined/deploy/local/cli.py | import argparse
import sys
from pathlib import Path
from typing import Callable, Dict
from determined.common.declarative_argparse import Arg, BoolOptArg, Cmd, Group
from . import cluster_utils
from .preflight import check_docker_install
def handle_cluster_up(args: argparse.Namespace) -> None:
if not args.no_pre... | 0.378 | 0.118207 |
from typing import Dict
from typing import Optional
from typing import Type
import asyncio
import time
import traceback
try:
from prometheus_client import Counter
from prometheus_client import Histogram
except ImportError:
Counter = Histogram = None
ERROR_NONE = "none"
ERROR_GENERAL_EXCEPTION = "excepti... | guillotina/metrics.py | from typing import Dict
from typing import Optional
from typing import Type
import asyncio
import time
import traceback
try:
from prometheus_client import Counter
from prometheus_client import Histogram
except ImportError:
Counter = Histogram = None
ERROR_NONE = "none"
ERROR_GENERAL_EXCEPTION = "excepti... | 0.795777 | 0.198763 |
import time
import logging
import requests
from .tor_proxy import TorProxy, TOR_SOCKS_PROXIES
from .free_proxy import FreeProxy
# Timeout for web server response (seconds)
TIMEOUT = 5
# Maximum retries count for executing request if an error occurred
MAX_RETRIES = 3
# The delay after executing an HTTP request (sec... | utils/http_request.py | import time
import logging
import requests
from .tor_proxy import TorProxy, TOR_SOCKS_PROXIES
from .free_proxy import FreeProxy
# Timeout for web server response (seconds)
TIMEOUT = 5
# Maximum retries count for executing request if an error occurred
MAX_RETRIES = 3
# The delay after executing an HTTP request (sec... | 0.568296 | 0.082143 |
from insights import CommandParser, parser
from insights.parsers import SkipException, parse_fixed_table
from insights.specs import Specs
class PodmanList(CommandParser):
"""
A general class for parsing tabular podman list information. Parsing
rules are:
* The first line is the header line.
* Th... | insights/parsers/podman_list.py | from insights import CommandParser, parser
from insights.parsers import SkipException, parse_fixed_table
from insights.specs import Specs
class PodmanList(CommandParser):
"""
A general class for parsing tabular podman list information. Parsing
rules are:
* The first line is the header line.
* Th... | 0.714429 | 0.445469 |
import os
from flask import Flask, render_template, request, url_for, abort, redirect
from flask_cloudy import Storage
import pandas as pd
import math
port = int(os.getenv('PORT', 8000))
curr_file = None
app = Flask(__name__)
app.config.update({
"STORAGE_PROVIDER": "LOCAL", # Can also be S3, GOOGLE_STORAGE, etc.... | quiz0/main.py | import os
from flask import Flask, render_template, request, url_for, abort, redirect
from flask_cloudy import Storage
import pandas as pd
import math
port = int(os.getenv('PORT', 8000))
curr_file = None
app = Flask(__name__)
app.config.update({
"STORAGE_PROVIDER": "LOCAL", # Can also be S3, GOOGLE_STORAGE, etc.... | 0.105498 | 0.065098 |
"""This file implements the functionalities of a minitaur using pybullet."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import copy
import math
import re
import numpy as np
from locomotion.robots import minitaur_constants
from locomot... | locomotion/robots/minitaur.py | """This file implements the functionalities of a minitaur using pybullet."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import copy
import math
import re
import numpy as np
from locomotion.robots import minitaur_constants
from locomot... | 0.937683 | 0.497253 |
import os
import sys
import glog as log
import json
import pkg_resources
import tempfile
import struct
import base64
import traceback
import avro.schema
from avro.datafile import DataFileReader, DataFileWriter
from avro.io import DatumReader, DatumWriter, BinaryDecoder, BinaryEncoder
from confluent_kafka.avro.cached_s... | multivitamin/data/response/io.py | import os
import sys
import glog as log
import json
import pkg_resources
import tempfile
import struct
import base64
import traceback
import avro.schema
from avro.datafile import DataFileReader, DataFileWriter
from avro.io import DatumReader, DatumWriter, BinaryDecoder, BinaryEncoder
from confluent_kafka.avro.cached_s... | 0.579281 | 0.111048 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = [
'EndpointGroupEndpointConfigurationArgs',
'EndpointGroupPortOverridesArgs',
'ForwardingRuleRuleActionArgs',
'ForwardingRuleRuleActionForwardGro... | sdk/python/pulumi_alicloud/ga/_inputs.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
__all__ = [
'EndpointGroupEndpointConfigurationArgs',
'EndpointGroupPortOverridesArgs',
'ForwardingRuleRuleActionArgs',
'ForwardingRuleRuleActionForwardGro... | 0.856453 | 0.080647 |
import webapp2
import jinja2
from google.appengine.ext import db
from google.appengine.api import users
from data.models import Monster, Profile, Vote, Product
import handlers.base
import configuration.site
import xml.etree.ElementTree as ET
from google.appengine.ext import blobstore
from google.appengine.ext.webapp im... | handlers/product.py | import webapp2
import jinja2
from google.appengine.ext import db
from google.appengine.api import users
from data.models import Monster, Profile, Vote, Product
import handlers.base
import configuration.site
import xml.etree.ElementTree as ET
from google.appengine.ext import blobstore
from google.appengine.ext.webapp im... | 0.403097 | 0.119974 |
import logging
import os
import subprocess
from patroni.exceptions import PostgresException
from patroni.utils import polling_loop
from six import string_types
from threading import Lock
logger = logging.getLogger(__name__)
class CancellableSubprocess(object):
def __init__(self):
self._is_cancelled = F... | patroni/postgresql/cancellable.py | import logging
import os
import subprocess
from patroni.exceptions import PostgresException
from patroni.utils import polling_loop
from six import string_types
from threading import Lock
logger = logging.getLogger(__name__)
class CancellableSubprocess(object):
def __init__(self):
self._is_cancelled = F... | 0.350755 | 0.04653 |
import struct
from typing import ClassVar, Optional
import attr
import marshmallow
from marshmallow import post_load
from elgas.parameters.enumerations import ParameterObjectType
from elgas.utils import pop_many, pretty_text
@attr.s(auto_attribs=True)
class ErrorCounter:
object_type: ClassVar[ParameterObjectTyp... | elgas/parameters/error_counter.py | import struct
from typing import ClassVar, Optional
import attr
import marshmallow
from marshmallow import post_load
from elgas.parameters.enumerations import ParameterObjectType
from elgas.utils import pop_many, pretty_text
@attr.s(auto_attribs=True)
class ErrorCounter:
object_type: ClassVar[ParameterObjectTyp... | 0.821295 | 0.33012 |
from mock import Mock, patch
@patch('cvm.services.VRouterPortService._port_needs_an_update', Mock(return_value=True))
def test_create_port(vrouter_port_service, database, vrouter_api_client, vmi_model):
database.ports_to_update.append(vmi_model)
vrouter_port_service.sync_ports()
vrouter_api_client.delet... | tests/unit/services/test_vrouter_port_service.py | from mock import Mock, patch
@patch('cvm.services.VRouterPortService._port_needs_an_update', Mock(return_value=True))
def test_create_port(vrouter_port_service, database, vrouter_api_client, vmi_model):
database.ports_to_update.append(vmi_model)
vrouter_port_service.sync_ports()
vrouter_api_client.delet... | 0.690455 | 0.150465 |
import sqlite3
import os
import re
import json
def all_files(d: str, ignore=None):
rv = list()
offset = len(os.path.dirname(d))
for root, subdirs, files in os.walk(d):
root = root[offset:]
root = root.lstrip('/')
files = [f'{root}/{f}' for f in files]
if ignore:
... | scripts/pack.py | import sqlite3
import os
import re
import json
def all_files(d: str, ignore=None):
rv = list()
offset = len(os.path.dirname(d))
for root, subdirs, files in os.walk(d):
root = root[offset:]
root = root.lstrip('/')
files = [f'{root}/{f}' for f in files]
if ignore:
... | 0.202917 | 0.084531 |
import json
import requests
import six
from six.moves import urllib
from firebase_admin import _auth_utils
from firebase_admin import _user_import
MAX_LIST_USERS_RESULTS = 1000
MAX_IMPORT_USERS_SIZE = 1000
class Sentinel(object):
def __init__(self, description):
self.description = description
DELET... | venv/lib/python3.7/site-packages/firebase_admin/_user_mgt.py | import json
import requests
import six
from six.moves import urllib
from firebase_admin import _auth_utils
from firebase_admin import _user_import
MAX_LIST_USERS_RESULTS = 1000
MAX_IMPORT_USERS_SIZE = 1000
class Sentinel(object):
def __init__(self, description):
self.description = description
DELET... | 0.849691 | 0.251269 |
r"""YAML backend:
- Format to support: YAML, http://yaml.org
- Requirements: PyYAML (yaml), http://pyyaml.org
- Development Status :: 5 - Production/Stable
- Limitations: ac_ordered is not effective and just ignored.
- Special options:
- All keyword options of yaml.safe_load, yaml.load, yaml.safe_dump and
yaml.... | anyconfig/backend/yaml.py | r"""YAML backend:
- Format to support: YAML, http://yaml.org
- Requirements: PyYAML (yaml), http://pyyaml.org
- Development Status :: 5 - Production/Stable
- Limitations: ac_ordered is not effective and just ignored.
- Special options:
- All keyword options of yaml.safe_load, yaml.load, yaml.safe_dump and
yaml.... | 0.810854 | 0.243929 |
from __future__ import unicode_literals
from .. import util
import soupsieve as sv
from soupsieve import SelectorSyntaxError
class TestNthChild(util.TestCase):
"""Test `nth` child selectors."""
def test_nth_child(self):
"""Test `nth` child."""
markup = """
<body>
<p id="0"></... | venv/lib/python3.6/site-packages/tests/test_level3/test_nth_child.py | from __future__ import unicode_literals
from .. import util
import soupsieve as sv
from soupsieve import SelectorSyntaxError
class TestNthChild(util.TestCase):
"""Test `nth` child selectors."""
def test_nth_child(self):
"""Test `nth` child."""
markup = """
<body>
<p id="0"></... | 0.822153 | 0.430447 |
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as plt
from .utils import Utils
class StructureFunction:
"""
This class provides methods for computing and analyzing struture functions
Args:
mrq (MultiResolutionQuantity): ... | mfanalysis/structurefunction.py | from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as plt
from .utils import Utils
class StructureFunction:
"""
This class provides methods for computing and analyzing struture functions
Args:
mrq (MultiResolutionQuantity): ... | 0.773858 | 0.614799 |
import binascii
import codecs
import hashlib
import struct
import abc
import dataclasses
from typing import Dict, Callable, Any, Optional
from keylime import config
from keylime import keylime_logging
from keylime.failure import Failure, Component
logger = keylime_logging.init_logging("ima")
TCG_EVENT_NAME_LEN_MAX =... | keylime/ima_ast.py | import binascii
import codecs
import hashlib
import struct
import abc
import dataclasses
from typing import Dict, Callable, Any, Optional
from keylime import config
from keylime import keylime_logging
from keylime.failure import Failure, Component
logger = keylime_logging.init_logging("ima")
TCG_EVENT_NAME_LEN_MAX =... | 0.797872 | 0.207074 |
import colorsys
import sys
# Color scheme formula:
# dictionary of all the keys found in the color.conf file, with as value
# a tuple of hue, saturation, and value adjustments
recipe1 = {
"dmenu color": {
"c_m_normal_bg": (0, -0.5, -0.7),
"c_m_normal_fg": (0, -0.8, 0),
"c_m_selected_bg": ... | .config/i3/config.d/available/colorgen.py |
import colorsys
import sys
# Color scheme formula:
# dictionary of all the keys found in the color.conf file, with as value
# a tuple of hue, saturation, and value adjustments
recipe1 = {
"dmenu color": {
"c_m_normal_bg": (0, -0.5, -0.7),
"c_m_normal_fg": (0, -0.8, 0),
"c_m_selected_bg": ... | 0.345436 | 0.214136 |
import signal
import sys
import unittest
import warnings
from unittest import mock
import asyncio
from asyncio import base_subprocess
from asyncio import subprocess
from test.test_asyncio import utils as test_utils
from test import support
if sys.platform != 'win32':
from asyncio import unix_events
... | toolchain/riscv/MSYS/python/Lib/test/test_asyncio/test_subprocess.py | import signal
import sys
import unittest
import warnings
from unittest import mock
import asyncio
from asyncio import base_subprocess
from asyncio import subprocess
from test.test_asyncio import utils as test_utils
from test import support
if sys.platform != 'win32':
from asyncio import unix_events
... | 0.334481 | 0.183082 |
import argparse
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
def parse_args():
parser = argparse.ArgumentParser()
... | cfg.py |
import argparse
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Boolean value expected.')
def parse_args():
parser = argparse.ArgumentParser()
... | 0.564098 | 0.155046 |
import os
if os.sep==".":
endsep = "/"
else:
endsep = "."
def whichdb(filename):
"""Guess which db package to use to open a db file.
Return values:
- None if the database file can't be read;
- empty string if the file can be read but can't be recognized
- the module name (e.g. "dbm" or ... | Lib/whichdb.py |
import os
if os.sep==".":
endsep = "/"
else:
endsep = "."
def whichdb(filename):
"""Guess which db package to use to open a db file.
Return values:
- None if the database file can't be read;
- empty string if the file can be read but can't be recognized
- the module name (e.g. "dbm" or ... | 0.564819 | 0.143427 |
from __future__ import print_function
import os
import os.path
from os.path import join
import platform
from setuptools import setup
from setuptools import Extension
from Cython.Build import cythonize
home_dir = os.getenv('HOME')
print('home_dir:', home_dir)
torch_install_dir = os.getenv('TORCH_INSTALL')
if torch_in... | setup.py |
from __future__ import print_function
import os
import os.path
from os.path import join
import platform
from setuptools import setup
from setuptools import Extension
from Cython.Build import cythonize
home_dir = os.getenv('HOME')
print('home_dir:', home_dir)
torch_install_dir = os.getenv('TORCH_INSTALL')
if torch_in... | 0.239527 | 0.046747 |
import os
import pickle
from argparse import ArgumentParser
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import tqdm
from torch.nn.utils.rnn import pack_padded_sequence
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from utils.data import E... | experiments/training_scripts/cgan/cnn_vs_dense_gan_train.py | import os
import pickle
from argparse import ArgumentParser
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import tqdm
from torch.nn.utils.rnn import pack_padded_sequence
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter
from utils.data import E... | 0.530723 | 0.137504 |
from __future__ import absolute_import, division, print_function, unicode_literals
from urllib.parse import parse_qsl
from django import forms
from django.contrib import admin
from django.db import connection, transaction
from .constants import CHOICE_ATTRIBUTE_OPTIONS, SIMPLE_ATTRIBUTE_OPTIONS
from .models import A... | django_project/src/attributes/admin.py | from __future__ import absolute_import, division, print_function, unicode_literals
from urllib.parse import parse_qsl
from django import forms
from django.contrib import admin
from django.db import connection, transaction
from .constants import CHOICE_ATTRIBUTE_OPTIONS, SIMPLE_ATTRIBUTE_OPTIONS
from .models import A... | 0.631594 | 0.069038 |
from pathlib import Path
import shutil
import click
import numpy as np
import numpy.lib.format as fmt
def get_header(files, axis):
"""get header for concatenated file
Parameters
----------
files : path-like
npy files to concatenate
axis : int, default=0
axis to cocatenate along
... | simianpy/scripts/util/concat.py | from pathlib import Path
import shutil
import click
import numpy as np
import numpy.lib.format as fmt
def get_header(files, axis):
"""get header for concatenated file
Parameters
----------
files : path-like
npy files to concatenate
axis : int, default=0
axis to cocatenate along
... | 0.592195 | 0.291371 |
'''Autogenerates mock interface implementations for MSHTML interfaces.'''
import os
import string
import sys
import com_mock
# Adjust our module path so we can import com_mock.
script_dir = os.path.abspath(os.path.dirname(__file__))
client_root = os.path.normpath(os.path.join(script_dir, '../../..'))
# The interfac... | ceee/testing/utils/mshtml_mocks.py | '''Autogenerates mock interface implementations for MSHTML interfaces.'''
import os
import string
import sys
import com_mock
# Adjust our module path so we can import com_mock.
script_dir = os.path.abspath(os.path.dirname(__file__))
client_root = os.path.normpath(os.path.join(script_dir, '../../..'))
# The interfac... | 0.303525 | 0.050729 |
import torch
import torch.nn as nn
from torch.nn.utils import weight_norm
from audio_zen.fvcore.nn import FlopCountAnalysis, flop_count_str
class Chomp1d(nn.Module):
def __init__(self, chomp_size):
super(Chomp1d, self).__init__()
self.chomp_size = chomp_size
def forward(self, x):
ret... | audio_zen/model/module/causal_conv.py | import torch
import torch.nn as nn
from torch.nn.utils import weight_norm
from audio_zen.fvcore.nn import FlopCountAnalysis, flop_count_str
class Chomp1d(nn.Module):
def __init__(self, chomp_size):
super(Chomp1d, self).__init__()
self.chomp_size = chomp_size
def forward(self, x):
ret... | 0.953449 | 0.419707 |
import cPickle
from fltk import *
Fl.scheme('plastic')
class Subject:
def __init__(self):
self.observers = []
def attach(self, observer):
self.observers.append(observer)
def detach(self, observer):
self.observers.remove(observer)
def notify(self, event=None):
... | PyCommon/modules/GUI/ysBaseUI.py | import cPickle
from fltk import *
Fl.scheme('plastic')
class Subject:
def __init__(self):
self.observers = []
def attach(self, observer):
self.observers.append(observer)
def detach(self, observer):
self.observers.remove(observer)
def notify(self, event=None):
... | 0.18451 | 0.065247 |
class MkldnnTest(object):
mkldnn_target_test_filename = 'mkl-dnn-c'
def __init__(self, target):
self.target = target
def tear_down(self):
self.target.run('rm /tmp/%s' % self.mkldnn_target_test_filename)
def test_mkldnn_can_compile_and_execute(self):
mkldnn_src_dir = '/... | lib/oeqa/runtime/miutils/tests/mkl_dnn_test.py | class MkldnnTest(object):
mkldnn_target_test_filename = 'mkl-dnn-c'
def __init__(self, target):
self.target = target
def tear_down(self):
self.target.run('rm /tmp/%s' % self.mkldnn_target_test_filename)
def test_mkldnn_can_compile_and_execute(self):
mkldnn_src_dir = '/... | 0.302906 | 0.147187 |
from django.db import models
from archfinch.main.models import Item, SlicedRawManager
from archfinch.users.models import User
from archfinch.links.thresholds import *
class LinkManager(SlicedRawManager):
def recommended_generic(self, category=None, tags=None, new=False):
'''
Fetches links recommend... | links/models.py | from django.db import models
from archfinch.main.models import Item, SlicedRawManager
from archfinch.users.models import User
from archfinch.links.thresholds import *
class LinkManager(SlicedRawManager):
def recommended_generic(self, category=None, tags=None, new=False):
'''
Fetches links recommend... | 0.331877 | 0.122392 |
import traceback
import sys
import time
import datetime
import string
import sqlite3
'''USER CONFIGURATION'''
#TIMESTAMP = '%A %d %B %Y'
TIMESTAMP = '%a %d %b %Y'
#The time format.
# "%A %d %B %Y" = "Wendesday 04 June 2014"
#http://docs.python.org/2/library/time.html#time.strftime
HEADER = ""
#Put this at the top o... | Redmash/redmash_db.py | import traceback
import sys
import time
import datetime
import string
import sqlite3
'''USER CONFIGURATION'''
#TIMESTAMP = '%A %d %B %Y'
TIMESTAMP = '%a %d %b %Y'
#The time format.
# "%A %d %B %Y" = "Wendesday 04 June 2014"
#http://docs.python.org/2/library/time.html#time.strftime
HEADER = ""
#Put this at the top o... | 0.104924 | 0.083143 |
import numpy as np
from pathlib import Path
import matplotlib.pyplot as plt
import math
from MiniFramework.NeuralNet_4_0 import *
from MiniFramework.ActivationLayer import *
from MiniFramework.ClassificationLayer import *
from MiniFramework.DataReader_2_0 import *
train_data_name = "../../Data/ch10.train.npz"
test_d... | 基础教程/A2-神经网络基本原理/第7步 - 深度神经网络/src/ch14-DnnBasic/Level3_ch10.py |
import numpy as np
from pathlib import Path
import matplotlib.pyplot as plt
import math
from MiniFramework.NeuralNet_4_0 import *
from MiniFramework.ActivationLayer import *
from MiniFramework.ClassificationLayer import *
from MiniFramework.DataReader_2_0 import *
train_data_name = "../../Data/ch10.train.npz"
test_d... | 0.511717 | 0.461563 |
import os.path
import random
from os.path import join
import numpy as np
from bert4keras.backend import keras, K
from bert4keras.layers import Loss
from bert4keras.models import build_transformer_model
from bert4keras.tokenizers import Tokenizer
from bert4keras.optimizers import Adam, extend_with_weight_decay
from bert... | main.py | import os.path
import random
from os.path import join
import numpy as np
from bert4keras.backend import keras, K
from bert4keras.layers import Loss
from bert4keras.models import build_transformer_model
from bert4keras.tokenizers import Tokenizer
from bert4keras.optimizers import Adam, extend_with_weight_decay
from bert... | 0.538012 | 0.17441 |
from widgets.MessageFrame import MessageFrame
from widgets.ConsoleFrame import ConsoleFrame
from widgets.PCANSettingsWindow import PCANSettingsWindow
from lib.PCAN_RS_232 import PCAN_RS_232
from tkinter import *
from widgets.InformationFrame import InformationFrame
from widgets.ButtonFrame import ButtonFrame
from seria... | PCAN_Interface_Application.py | from widgets.MessageFrame import MessageFrame
from widgets.ConsoleFrame import ConsoleFrame
from widgets.PCANSettingsWindow import PCANSettingsWindow
from lib.PCAN_RS_232 import PCAN_RS_232
from tkinter import *
from widgets.InformationFrame import InformationFrame
from widgets.ButtonFrame import ButtonFrame
from seria... | 0.298287 | 0.075892 |
from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import os
import json
import utility
import re
import requests
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "lib"))
from splunklib.six.moves.urllib.parse import quote_plus
from splunklib.searchcommands im... | bin/changedispatchttl.py | from __future__ import absolute_import, division, print_function, unicode_literals
import sys
import os
import json
import utility
import re
import requests
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "lib"))
from splunklib.six.moves.urllib.parse import quote_plus
from splunklib.searchcommands im... | 0.390011 | 0.075551 |
import asyncio
import voluptuous as vol
from homeassistant.components.knx import ATTR_DISCOVER_DEVICES, DATA_KNX
from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice
from homeassistant.const import CONF_NAME
from homeassistant.core import callback
import homeassistant.helpers.config_validation as... | homeassistant/components/switch/knx.py | import asyncio
import voluptuous as vol
from homeassistant.components.knx import ATTR_DISCOVER_DEVICES, DATA_KNX
from homeassistant.components.switch import PLATFORM_SCHEMA, SwitchDevice
from homeassistant.const import CONF_NAME
from homeassistant.core import callback
import homeassistant.helpers.config_validation as... | 0.668231 | 0.107017 |
"""Tests using pytest_resilient_circuits"""
from __future__ import print_function
import pytest
from resilient_circuits.util import get_config_data, get_function_definition
from resilient_circuits import SubmitTestFunction, FunctionResult
PACKAGE_NAME = "fn_codegen_test"
FUNCTION_NAME = "utilities_base64_to_artifact"... | fn_codegen_test/tests/test_utilities_base64_to_artifact.py | """Tests using pytest_resilient_circuits"""
from __future__ import print_function
import pytest
from resilient_circuits.util import get_config_data, get_function_definition
from resilient_circuits import SubmitTestFunction, FunctionResult
PACKAGE_NAME = "fn_codegen_test"
FUNCTION_NAME = "utilities_base64_to_artifact"... | 0.807157 | 0.418697 |
from __future__ import annotations # postpone evaluation of annotations
import logging
from typing import Any, Dict, List, Optional, Tuple
import cv2
import numpy as np
import numpy.typing as npt
from pyquaternion import Quaternion
from scipy import ndimage
from scipy.spatial.transform import Rotation as R
from sqla... | nuplan/database/nuplan_db/ego_pose.py | from __future__ import annotations # postpone evaluation of annotations
import logging
from typing import Any, Dict, List, Optional, Tuple
import cv2
import numpy as np
import numpy.typing as npt
from pyquaternion import Quaternion
from scipy import ndimage
from scipy.spatial.transform import Rotation as R
from sqla... | 0.953286 | 0.389488 |
from pprint import pprint
import pandas as pd
import ccxt
from model import Balance
class ApiClient(ccxt.cryptopia):
def __init__(self, apikey=None, secret=None, **config):
super().__init__(config)
if apikey is not None and secret is not None:
self.apiKey = apikey
self.s... | clitopia/api.py | from pprint import pprint
import pandas as pd
import ccxt
from model import Balance
class ApiClient(ccxt.cryptopia):
def __init__(self, apikey=None, secret=None, **config):
super().__init__(config)
if apikey is not None and secret is not None:
self.apiKey = apikey
self.s... | 0.251464 | 0.109301 |
REQUIREMENTS_MAP = {
'appengine':
{'module_name': 'load_appengine_pipeline',
'depends_on': 'projects',
'api_name': 'appengine_api',
'dao_name': 'appengine_dao'},
'backend_services':
{'module_name': 'load_backend_services_pipeline',
'depends_on': 'projects',
... | google/cloud/security/inventory/pipeline_requirements_map.py | REQUIREMENTS_MAP = {
'appengine':
{'module_name': 'load_appengine_pipeline',
'depends_on': 'projects',
'api_name': 'appengine_api',
'dao_name': 'appengine_dao'},
'backend_services':
{'module_name': 'load_backend_services_pipeline',
'depends_on': 'projects',
... | 0.276007 | 0.057679 |
import requests
from tx.router import plugin_config, plugin
from tx.router.logging import l
import logging
import connexion
import sys
from werkzeug.datastructures import Headers
from flask import Response, request
from tempfile import TemporaryFile
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def set_f... | api/__init__.py | import requests
from tx.router import plugin_config, plugin
from tx.router.logging import l
import logging
import connexion
import sys
from werkzeug.datastructures import Headers
from flask import Response, request
from tempfile import TemporaryFile
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def set_f... | 0.308086 | 0.082033 |
from base.base_model import BaseModel
import tensorflow as tf
class Denoising(BaseModel):
def __init__(self, config):
super(Denoising, self).__init__(config)
self.build_model()
self.init_saver()
def build_model(self):
# Placeholders
self.is_training = tf.placeholder(t... | models/denoising.py | from base.base_model import BaseModel
import tensorflow as tf
class Denoising(BaseModel):
def __init__(self, config):
super(Denoising, self).__init__(config)
self.build_model()
self.init_saver()
def build_model(self):
# Placeholders
self.is_training = tf.placeholder(t... | 0.886899 | 0.191045 |
import requests
import json
import re
import youtube_dl
print("Youtube Pocket - youtube music/playlist downloader\n")
USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
VID_PATTERN = r"^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.be... | test_data/get_data_test.py | import requests
import json
import re
import youtube_dl
print("Youtube Pocket - youtube music/playlist downloader\n")
USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"
VID_PATTERN = r"^(https?:\/\/)?(www\.)?(youtube\.com|youtu\.be... | 0.138258 | 0.096323 |
import os
import sys
import platform
import re
import argparse
import threading
import queue
import webbrowser
import logging
import ipaddress
from PIL import Image, ImageTk
import tkinterdnd2 as tkdnd
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.simpledialog import Dialog as BaseDialog
from tkinter.me... | ndrop/__main_tk__.py |
import os
import sys
import platform
import re
import argparse
import threading
import queue
import webbrowser
import logging
import ipaddress
from PIL import Image, ImageTk
import tkinterdnd2 as tkdnd
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.simpledialog import Dialog as BaseDialog
from tkinter.me... | 0.472683 | 0.082401 |