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 pandas as pd
import os
data_dir = os.path.abspath(os.path.dirname(__file__))
__all__ = ['mudflocs']
def _load(f, as_gray=False):
"""Load an image file located in the data directory.
Args:
f (str): File name.
as_gray (bool): optional, True if conversion of the image to graysc... | safas/data/__init__.py | import pandas as pd
import os
data_dir = os.path.abspath(os.path.dirname(__file__))
__all__ = ['mudflocs']
def _load(f, as_gray=False):
"""Load an image file located in the data directory.
Args:
f (str): File name.
as_gray (bool): optional, True if conversion of the image to graysc... | 0.797911 | 0.529993 |
import unittest
import sys
from ctypes import *
import _ctypes_test
class ValuesTestCase(unittest.TestCase):
def test_an_integer(self):
# This test checks and changes an integer stored inside the
# _ctypes_test dll/shared lib.
ctdll = CDLL(_ctypes_test.__file__)
an_integer = c_int... | Lib/ctypes/test/test_values.py | import unittest
import sys
from ctypes import *
import _ctypes_test
class ValuesTestCase(unittest.TestCase):
def test_an_integer(self):
# This test checks and changes an integer stored inside the
# _ctypes_test dll/shared lib.
ctdll = CDLL(_ctypes_test.__file__)
an_integer = c_int... | 0.430147 | 0.50238 |
import datetime
import functools
import inspect
import json
import pickle
import zlib
from google.cloud.datastore import entity as entity_module
from google.cloud.datastore import helpers
from google.cloud.ndb import _datastore_api
from google.cloud.ndb import _datastore_types
from google.cloud.ndb import exceptions
... | ndb/src/google/cloud/ndb/model.py | import datetime
import functools
import inspect
import json
import pickle
import zlib
from google.cloud.datastore import entity as entity_module
from google.cloud.datastore import helpers
from google.cloud.ndb import _datastore_api
from google.cloud.ndb import _datastore_types
from google.cloud.ndb import exceptions
... | 0.737442 | 0.166879 |
import argparse
from glob import glob
from os import environ, makedirs, remove
from os.path import exists, normpath, realpath
from shutil import rmtree
from sys import argv
from traceback import print_exc
from vang.pio.shell import run_command
def get_jars(root):
return [realpath(p) for p in
glob(nor... | vang/wildcat/wildcat_war_release_info.py | import argparse
from glob import glob
from os import environ, makedirs, remove
from os.path import exists, normpath, realpath
from shutil import rmtree
from sys import argv
from traceback import print_exc
from vang.pio.shell import run_command
def get_jars(root):
return [realpath(p) for p in
glob(nor... | 0.26341 | 0.11358 |
import google
from ruamel import yaml
from six.moves import zip
from google.appengine.api import yaml_errors
from google.appengine.api import yaml_listener
from google.appengine.api import yaml_test_util
from absl.testing import absltest
class TestEventListener(absltest.TestCase):
"""Tests for EventListener cla... | tests/google/appengine/api/yaml_listener_unittest.py | import google
from ruamel import yaml
from six.moves import zip
from google.appengine.api import yaml_errors
from google.appengine.api import yaml_listener
from google.appengine.api import yaml_test_util
from absl.testing import absltest
class TestEventListener(absltest.TestCase):
"""Tests for EventListener cla... | 0.561455 | 0.328206 |
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
import math
from ccxt.base.decimal_to_precision import DECIMAL_PLACES
from ccxt.base.decimal_to_precision import PAD_WITH_ZERO
from ccxt.base.decimal_to_precision... | ccxt/phemex.py |
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
import math
from ccxt.base.decimal_to_precision import DECIMAL_PLACES
from ccxt.base.decimal_to_precision import PAD_WITH_ZERO
from ccxt.base.decimal_to_precision... | 0.61115 | 0.206154 |
# Lint as: python3
"""Helper functions/classes for model definition."""
import functools
from typing import Any, Callable
from flax import linen as nn
import jax
from jax import lax
from jax import random
import jax.numpy as jnp
class MLP(nn.Module):
"""A simple MLP."""
net_depth: int = 8 # The depth of t... | nerf/model_utils.py |
# Lint as: python3
"""Helper functions/classes for model definition."""
import functools
from typing import Any, Callable
from flax import linen as nn
import jax
from jax import lax
from jax import random
import jax.numpy as jnp
class MLP(nn.Module):
"""A simple MLP."""
net_depth: int = 8 # The depth of t... | 0.961678 | 0.656345 |
import asyncio
from asyncio.exceptions import TimeoutError
from pyrogram import Client, filters
from pyrogram.errors import (PhoneCodeExpired, PhoneCodeInvalid,
PhoneNumberInvalid, SessionPasswordNeeded)
from wbb import app
from wbb.core.decorators.errors import capture_err
"""
Credits:
... | wbb/modules/genstr.py | import asyncio
from asyncio.exceptions import TimeoutError
from pyrogram import Client, filters
from pyrogram.errors import (PhoneCodeExpired, PhoneCodeInvalid,
PhoneNumberInvalid, SessionPasswordNeeded)
from wbb import app
from wbb.core.decorators.errors import capture_err
"""
Credits:
... | 0.720073 | 0.174199 |
import copy
import os
import fixtures
import mock
from oslo_config import cfg
from oslo_log import log
import oslo_messaging
from oslotest import base
import pecan
import testscenarios
from magnum.common import context as magnum_context
from magnum.common import keystone as magnum_keystone
from magnum.objects import... | magnum/tests/base.py |
import copy
import os
import fixtures
import mock
from oslo_config import cfg
from oslo_log import log
import oslo_messaging
from oslotest import base
import pecan
import testscenarios
from magnum.common import context as magnum_context
from magnum.common import keystone as magnum_keystone
from magnum.objects import... | 0.514888 | 0.081155 |
from django.conf import settings
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.utils import timezone
from django.utils.encoding import smart_str
from cStringIO import StringIO
from django.http.response import HttpResponse
import... | OJCR/models.py |
from django.conf import settings
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.utils import timezone
from django.utils.encoding import smart_str
from cStringIO import StringIO
from django.http.response import HttpResponse
import... | 0.402275 | 0.06486 |
import collections
import inspect
import sys
class PluginLibrary(type):
def __init__(cls, name, bases, attrs):
module_name = cls.__module__.lower()
class_name = name.lower()
if not hasattr(cls, 'cache'):
cls.cache = collections.defaultdict(dict)
else:
# Do ... | pycri/plugins/__init__.py | import collections
import inspect
import sys
class PluginLibrary(type):
def __init__(cls, name, bases, attrs):
module_name = cls.__module__.lower()
class_name = name.lower()
if not hasattr(cls, 'cache'):
cls.cache = collections.defaultdict(dict)
else:
# Do ... | 0.337422 | 0.072308 |
from math import tanh
from pysqlite2 import dbapi2 as sqlite
class searchnet:
def __init__(self, dbname):
self.con = sqlite.connect(dbname)
def __del__(self):
self.con.close()
def maketables(self):
self.con.execute('create table hiddennode(create_key)')
self.con.execute('create table wordhidden(fromid, to... | nn.py | from math import tanh
from pysqlite2 import dbapi2 as sqlite
class searchnet:
def __init__(self, dbname):
self.con = sqlite.connect(dbname)
def __del__(self):
self.con.close()
def maketables(self):
self.con.execute('create table hiddennode(create_key)')
self.con.execute('create table wordhidden(fromid, to... | 0.226014 | 0.252476 |
import jsonschema
from mock import Mock, patch, MagicMock, PropertyMock
from testtools.matchers import Is, Equals
from trove.common import exception
from trove.common import remote
from trove.datastore import models as datastore_models
from trove.extensions.mgmt.datastores.service import DatastoreVersionController
f... | trove/tests/unittests/mgmt/test_datastore_controller.py |
import jsonschema
from mock import Mock, patch, MagicMock, PropertyMock
from testtools.matchers import Is, Equals
from trove.common import exception
from trove.common import remote
from trove.datastore import models as datastore_models
from trove.extensions.mgmt.datastores.service import DatastoreVersionController
f... | 0.641759 | 0.293765 |
import os
import sys
import signal
CURDIR = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(CURDIR, "helpers"))
from client import client, prompt, end_of_block
log = None
# uncomment the line below for debugging
# log=sys.stdout
with client(name="client1>", log=log) as client1, client(
... | tests/queries/0_stateless/01065_window_view_event_hop_watch_bounded.py | import os
import sys
import signal
CURDIR = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(CURDIR, "helpers"))
from client import client, prompt, end_of_block
log = None
# uncomment the line below for debugging
# log=sys.stdout
with client(name="client1>", log=log) as client1, client(
... | 0.330363 | 0.188511 |
import ast
import pytest
import vcr
import json
import os
from superai.client import Client
# To record new cassette, use real app_id and run pytest against runnig endpoint
def scrub_string(string, replacement=""):
def before_record_response(response):
response = str(response).replace(string, replaceme... | tests/apis/test_data.py | import ast
import pytest
import vcr
import json
import os
from superai.client import Client
# To record new cassette, use real app_id and run pytest against runnig endpoint
def scrub_string(string, replacement=""):
def before_record_response(response):
response = str(response).replace(string, replaceme... | 0.432782 | 0.273813 |
import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from ..utils import ext_loader
ext_module = ext_loader.load_ext('_ext', [
'sigmoid_focal_loss_forward', 'sigmoid_focal_loss_backward',
'softmax_focal_loss_forward', 'softmax_focal_los... | mmcv/ops/focal_loss.py | import torch
import torch.nn as nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from ..utils import ext_loader
ext_module = ext_loader.load_ext('_ext', [
'sigmoid_focal_loss_forward', 'sigmoid_focal_loss_backward',
'softmax_focal_loss_forward', 'softmax_focal_los... | 0.940831 | 0.603348 |
import copy
import argparse
from os.path import expanduser
from unittest.mock import patch
from docutils import nodes
from docutils.statemachine import ViewList
from docutils.parsers.rst import directives
from sphinx import addnodes
from sphinx.directives import ObjectDescription
from sphinx.util.compat import Direct... | azdev/operations/help/refdoc/common/directives.py | import copy
import argparse
from os.path import expanduser
from unittest.mock import patch
from docutils import nodes
from docutils.statemachine import ViewList
from docutils.parsers.rst import directives
from sphinx import addnodes
from sphinx.directives import ObjectDescription
from sphinx.util.compat import Direct... | 0.396302 | 0.065217 |
import csv
from pathlib import Path
import re
from shutil import unpack_archive
from sys import stderr, stdout
SRC_DIR = Path('backend', 'data', 'fused', 'example')
DEST_DIR = Path('backend', 'data', 'wrangled', 'example')
CENSUS_HEADERS = {
'year': 'year',
'GEO.id': 'uid',
'GEO.id2': 'fips',... | backend/scripts/wrangle/wrangle_example.py | import csv
from pathlib import Path
import re
from shutil import unpack_archive
from sys import stderr, stdout
SRC_DIR = Path('backend', 'data', 'fused', 'example')
DEST_DIR = Path('backend', 'data', 'wrangled', 'example')
CENSUS_HEADERS = {
'year': 'year',
'GEO.id': 'uid',
'GEO.id2': 'fips',... | 0.181336 | 0.224906 |
import re
import unicodedata
from collections import Counter
from pybtex.style.formatting.unsrt import Style as UnsrtStyle
from pybtex.style.labels import BaseLabelStyle
from pybtex.plugin import register_plugin
_alphanum_ = re.compile('[^A-Za-z0-9-]+', re.UNICODE)
def strip_accents(s):
return ''.join((c for c i... | doc/authorlist_format.py | import re
import unicodedata
from collections import Counter
from pybtex.style.formatting.unsrt import Style as UnsrtStyle
from pybtex.style.labels import BaseLabelStyle
from pybtex.plugin import register_plugin
_alphanum_ = re.compile('[^A-Za-z0-9-]+', re.UNICODE)
def strip_accents(s):
return ''.join((c for c i... | 0.415729 | 0.22688 |
import glob
import io
import json
import os
import random
import shutil
import stat
import string
import tempfile
import unittest
import runsteps
def fill_directory(path, files):
"""Populate a directory with empty files
Args:
path: The name of a directory for storing the empty files
files: A ... | tests/unit/test_Runner.py | import glob
import io
import json
import os
import random
import shutil
import stat
import string
import tempfile
import unittest
import runsteps
def fill_directory(path, files):
"""Populate a directory with empty files
Args:
path: The name of a directory for storing the empty files
files: A ... | 0.473657 | 0.438966 |
import io
import os
import shutil
import tempfile
from docker import errors
import pytest
import six
from .base import BaseAPIIntegrationTest, BUSYBOX
from ..helpers import random_name, requires_api_version, requires_experimental
class BuildTest(BaseAPIIntegrationTest):
def test_build_streaming(self):
... | tests/integration/api_build_test.py | import io
import os
import shutil
import tempfile
from docker import errors
import pytest
import six
from .base import BaseAPIIntegrationTest, BUSYBOX
from ..helpers import random_name, requires_api_version, requires_experimental
class BuildTest(BaseAPIIntegrationTest):
def test_build_streaming(self):
... | 0.305697 | 0.122182 |
from functools import reduce, partial
from absl.testing import absltest
import numpy as np
import unittest
from jax import test_util as jtu
import jax.numpy as jnp
import jax.scipy.special
from jax import random
from jax import jacfwd, jit
from jax.experimental import stax
from jax.experimental.jet import jet, fact... | tests/jet_test.py |
from functools import reduce, partial
from absl.testing import absltest
import numpy as np
import unittest
from jax import test_util as jtu
import jax.numpy as jnp
import jax.scipy.special
from jax import random
from jax import jacfwd, jit
from jax.experimental import stax
from jax.experimental.jet import jet, fact... | 0.549882 | 0.518668 |
from datetime import datetime
from django.shortcuts import render, redirect
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.views.generic.detail import DetailView
from django.views.generic import TemplateView
from django.contrib.auth.m... | math_tournaments/tournaments/views/views_tournament.py | from datetime import datetime
from django.shortcuts import render, redirect
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.views.generic.detail import DetailView
from django.views.generic import TemplateView
from django.contrib.auth.m... | 0.402979 | 0.063628 |
# ....................{ IMPORTS }....................
from beartype._cave._cavefast import (
EllipsisType,
FunctionType,
FunctionOrMethodCType,
MethodBoundInstanceOrClassType,
ModuleType,
NoneType,
NotImplementedType,
)
# See the "beartype.cave" submodule for furth... | beartype/_data/cls/datacls.py | # ....................{ IMPORTS }....................
from beartype._cave._cavefast import (
EllipsisType,
FunctionType,
FunctionOrMethodCType,
MethodBoundInstanceOrClassType,
ModuleType,
NoneType,
NotImplementedType,
)
# See the "beartype.cave" submodule for furth... | 0.567937 | 0.156781 |
from six.moves.queue import Empty, Queue
from weblib.error import ResponseNotValid
from grab.spider.base_service import BaseService
from grab.spider.task import Task
from grab.spider.error import FatalError, SpiderError
class TaskDispatcherService(BaseService):
def __init__(self, spider):
self.input_queu... | grab/spider/task_dispatcher_service.py | from six.moves.queue import Empty, Queue
from weblib.error import ResponseNotValid
from grab.spider.base_service import BaseService
from grab.spider.task import Task
from grab.spider.error import FatalError, SpiderError
class TaskDispatcherService(BaseService):
def __init__(self, spider):
self.input_queu... | 0.363421 | 0.113924 |
import re
import os
import sys
import time
import subprocess
import RPi.GPIO as GPIO
import multiprocessing as mp
from collections import defaultdict
from configparser import ConfigParser
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(17, GPIO.OUT)
GPIO.output(17, GPIO.HIGH)
cmds = {
'blk': "lsblk | aw... | misc.py | import re
import os
import sys
import time
import subprocess
import RPi.GPIO as GPIO
import multiprocessing as mp
from collections import defaultdict
from configparser import ConfigParser
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(17, GPIO.OUT)
GPIO.output(17, GPIO.HIGH)
cmds = {
'blk': "lsblk | aw... | 0.221351 | 0.055515 |
"""Model implementations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from abc import ABCMeta
from abc import abstractmethod
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.contrib.slim.python.slim.nets import inception... | research/tcn/model.py |
"""Model implementations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from abc import ABCMeta
from abc import abstractmethod
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.contrib.slim.python.slim.nets import inception... | 0.971953 | 0.323941 |
import os
from bson import json_util
from pymongo import MongoClient, errors
from chalice import Chalice, Response, BadRequestError
app = Chalice(app_name='socian', debug=True)
@app.route('/', cors=True)
def index():
"""index view"""
return Response(body="Welcome to Socian API!", status_code=200, headers={'Co... | app.py | import os
from bson import json_util
from pymongo import MongoClient, errors
from chalice import Chalice, Response, BadRequestError
app = Chalice(app_name='socian', debug=True)
@app.route('/', cors=True)
def index():
"""index view"""
return Response(body="Welcome to Socian API!", status_code=200, headers={'Co... | 0.482673 | 0.121061 |
import salt.modules.win_wua as win_wua
import salt.utils.platform
import salt.utils.win_update
from tests.support.mock import MagicMock, patch
from tests.support.unit import TestCase, skipIf
UPDATES_LIST = {
"ca3bb521-a8ea-4e26-a563-2ad6e3108b9a": {"KBs": ["KB4481252"]},
"07609d43-d518-4e77-856e-d1b316d1b8a8":... | tests/unit/modules/test_win_wua.py | import salt.modules.win_wua as win_wua
import salt.utils.platform
import salt.utils.win_update
from tests.support.mock import MagicMock, patch
from tests.support.unit import TestCase, skipIf
UPDATES_LIST = {
"ca3bb521-a8ea-4e26-a563-2ad6e3108b9a": {"KBs": ["KB4481252"]},
"07609d43-d518-4e77-856e-d1b316d1b8a8":... | 0.626124 | 0.282233 |
class Franchise:
def __init__(self, address, menus):
self.address = address
self.menus = menus
def __repr__(self):
return self.address
def available_menus(self, time):
availible_menus = []
for menu in menus:
if time >= menu.start_time and time <= menu.end_time:
availibl... | BastaFozzalin/Bastafozzalin.py | class Franchise:
def __init__(self, address, menus):
self.address = address
self.menus = menus
def __repr__(self):
return self.address
def available_menus(self, time):
availible_menus = []
for menu in menus:
if time >= menu.start_time and time <= menu.end_time:
availibl... | 0.340814 | 0.172625 |
import numpy as np
class NMF:
"""
NMFの計算,値を保持する.
Attributes
----------
W, H: numpy.ndarray
計算で使用する行列
loss_LOG: list
目的関数の計算結果のログ
epsilon: float
ゼロ除算回避用の微小な値
"""
W = None
H = None
loss_LOG = None
# probdist_V = None
epsilon = None
def __... | nmf/modules/nmf.py | import numpy as np
class NMF:
"""
NMFの計算,値を保持する.
Attributes
----------
W, H: numpy.ndarray
計算で使用する行列
loss_LOG: list
目的関数の計算結果のログ
epsilon: float
ゼロ除算回避用の微小な値
"""
W = None
H = None
loss_LOG = None
# probdist_V = None
epsilon = None
def __... | 0.761716 | 0.594904 |
# NOTE: workaround to import modules
import os
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../'))
import unittest # noqa: E402
from unittest.mock import patch # noqa: E402
from checkers_py import oneapi_env_checker # noqa: E402
from modules.check import CheckSummary, Ch... | checkers_py/tests/test_oneapi_env_checker.py |
# NOTE: workaround to import modules
import os
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../../'))
import unittest # noqa: E402
from unittest.mock import patch # noqa: E402
from checkers_py import oneapi_env_checker # noqa: E402
from modules.check import CheckSummary, Ch... | 0.492676 | 0.36232 |
from PyQt5.QtWidgets import QApplication, QSizePolicy
from PyQt5 import QtWidgets, QtCore, QtGui
import sys
from collections import OrderedDict
from smtirf import gui
# ==============================================================================
# MAIN APPLICATION
# =================================================... | smtirf_viewer.py | from PyQt5.QtWidgets import QApplication, QSizePolicy
from PyQt5 import QtWidgets, QtCore, QtGui
import sys
from collections import OrderedDict
from smtirf import gui
# ==============================================================================
# MAIN APPLICATION
# =================================================... | 0.335242 | 0.062245 |
from __future__ import annotations
from typing import Callable, TYPE_CHECKING
from unittest.mock import MagicMock, Mock, PropertyMock
from pytest import fixture
from tests.example_data.data_loading.pandas.pandas_data_loader import PandasDataLoader
from tests.example_data.data_loading.pandas.pands_data_loading_conf i... | tests/conftest.py | from __future__ import annotations
from typing import Callable, TYPE_CHECKING
from unittest.mock import MagicMock, Mock, PropertyMock
from pytest import fixture
from tests.example_data.data_loading.pandas.pandas_data_loader import PandasDataLoader
from tests.example_data.data_loading.pandas.pands_data_loading_conf i... | 0.788624 | 0.304416 |
from django.contrib import admin
from world.prayer.models import Prayer, PrayerAnswer, InvocableEntity, EntityAlias
from django.shortcuts import reverse
from django.utils.html import escape
from django.utils.safestring import mark_safe
from evennia.utils.utils import crop
class PrayerAnswerInline(admin.TabularInline)... | world/prayer/admin.py | from django.contrib import admin
from world.prayer.models import Prayer, PrayerAnswer, InvocableEntity, EntityAlias
from django.shortcuts import reverse
from django.utils.html import escape
from django.utils.safestring import mark_safe
from evennia.utils.utils import crop
class PrayerAnswerInline(admin.TabularInline)... | 0.519765 | 0.202739 |
import warnings
import _warnings
import io
import sys
import __pypy__
def test_defaults():
assert _warnings._onceregistry == {}
assert _warnings._defaultaction == 'default'
expected = [('default', None, DeprecationWarning, '__main__', 0),
('ignore', None, DeprecationWarning, None, 0),
... | pypy/module/_warnings/test/apptest_warnings.py |
import warnings
import _warnings
import io
import sys
import __pypy__
def test_defaults():
assert _warnings._onceregistry == {}
assert _warnings._defaultaction == 'default'
expected = [('default', None, DeprecationWarning, '__main__', 0),
('ignore', None, DeprecationWarning, None, 0),
... | 0.315841 | 0.334739 |
from tests.dell10g import enable
from tests.util.protocol_util import with_protocol, ProtocolTest, SshTester, TelnetTester
class Dell10GConfigureTest(ProtocolTest):
__test__ = False
tester_class = SshTester
test_switch = "dell10g"
@with_protocol
def test_entering_configure_unknown_interface_mod... | tests/dell10g/test_configure.py |
from tests.dell10g import enable
from tests.util.protocol_util import with_protocol, ProtocolTest, SshTester, TelnetTester
class Dell10GConfigureTest(ProtocolTest):
__test__ = False
tester_class = SshTester
test_switch = "dell10g"
@with_protocol
def test_entering_configure_unknown_interface_mod... | 0.3027 | 0.248007 |
from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, emit, disconnect
from datetime import datetime
import tbapy
# Set this variable to "threading", "eventlet" or "gevent" to test the
# different async modes, or leave it set to None for the application to choose
# the best op... | app/app.py | from flask import Flask, render_template, session, request
from flask_socketio import SocketIO, emit, disconnect
from datetime import datetime
import tbapy
# Set this variable to "threading", "eventlet" or "gevent" to test the
# different async modes, or leave it set to None for the application to choose
# the best op... | 0.54698 | 0.174516 |
"""Generate examples of two objects moving in different directions."""
import random
import sys
import numpy as np
from six.moves import xrange
import tensorflow as tf
tf.flags.DEFINE_string('out_file', '',
'Output file for the tfrecords.')
def _add_object(obj_type, image, image2, xpos, ypos... | research/next_frame_prediction/cross_conv/example_gen.py |
"""Generate examples of two objects moving in different directions."""
import random
import sys
import numpy as np
from six.moves import xrange
import tensorflow as tf
tf.flags.DEFINE_string('out_file', '',
'Output file for the tfrecords.')
def _add_object(obj_type, image, image2, xpos, ypos... | 0.596551 | 0.633297 |
import os
import json
import tccli.options_define as OptionsDefine
import tccli.format_output as FormatOutput
from tccli import __version__
from tccli.utils import Utils
from tccli.exceptions import ConfigurationError
from tencentcloud.common import credential
from tencentcloud.common.profile.http_profile import HttpPr... | tccli/services/tke/tke_client.py | import os
import json
import tccli.options_define as OptionsDefine
import tccli.format_output as FormatOutput
from tccli import __version__
from tccli.utils import Utils
from tccli.exceptions import ConfigurationError
from tencentcloud.common import credential
from tencentcloud.common.profile.http_profile import HttpPr... | 0.210523 | 0.063919 |
from __future__ import unicode_literals
from collections import OrderedDict
from ..es import Provider as AddressProvider
class Provider(AddressProvider):
city_prefixes = ('Sur', 'Norte')
city_adjectives = ('Nueva', 'Vieja')
city_suffixes = ('de la Montaña', 'los bajos', 'los altos')
street_prefixes... | wsltools/utils/faker/providers/address/es_MX/__init__.py |
from __future__ import unicode_literals
from collections import OrderedDict
from ..es import Provider as AddressProvider
class Provider(AddressProvider):
city_prefixes = ('Sur', 'Norte')
city_adjectives = ('Nueva', 'Vieja')
city_suffixes = ('de la Montaña', 'los bajos', 'los altos')
street_prefixes... | 0.659953 | 0.242273 |
import time
import comet_ml
import torch.nn.functional as F
from torchvision.utils import save_image
from tqdm import tqdm, trange
from ..utils.wt import *
# Train function for UNet 128 (64->128) without data augmentation
def train_unet128(epoch, state_dict, model, optimizer, train_loader, valid_loader, args, logg... | training/wt_unet.py | import time
import comet_ml
import torch.nn.functional as F
from torchvision.utils import save_image
from tqdm import tqdm, trange
from ..utils.wt import *
# Train function for UNet 128 (64->128) without data augmentation
def train_unet128(epoch, state_dict, model, optimizer, train_loader, valid_loader, args, logg... | 0.565419 | 0.307995 |
import discord
from discord.ext import commands
from aiohttp import request
import random
import time
from os import system
import os
import datetime
import numpy
from colorama import Fore, Back, Style
import re
import requests
import sys
import json
import base64, codecs
with open('config.json') as f:
config = js... | bot.py | import discord
from discord.ext import commands
from aiohttp import request
import random
import time
from os import system
import os
import datetime
import numpy
from colorama import Fore, Back, Style
import re
import requests
import sys
import json
import base64, codecs
with open('config.json') as f:
config = js... | 0.130729 | 0.164181 |
from komand.exceptions import PluginException
import json
from typing import Dict, Iterable, Any
import requests
import copy
def get_query(url: str, query: str) -> requests.Response:
try:
response = requests.get(url, params={"q": query}, allow_redirects=False)
except requests.exceptions.HTTPError as ... | plugins/threatminer/komand_threatminer/util/utils.py | from komand.exceptions import PluginException
import json
from typing import Dict, Iterable, Any
import requests
import copy
def get_query(url: str, query: str) -> requests.Response:
try:
response = requests.get(url, params={"q": query}, allow_redirects=False)
except requests.exceptions.HTTPError as ... | 0.55941 | 0.185154 |
from pytest import *
from unittest.mock import Mock, call, sentinel
from textwrap import dedent
import io
import datetime
from math import radians, degrees
from navtools import waypoint_merge
from navtools import navigation
from navtools import lowrance_usr
from uuid import UUID
def test_parse_datetime():
EST = d... | test/test_waypoint_merge.py | from pytest import *
from unittest.mock import Mock, call, sentinel
from textwrap import dedent
import io
import datetime
from math import radians, degrees
from navtools import waypoint_merge
from navtools import navigation
from navtools import lowrance_usr
from uuid import UUID
def test_parse_datetime():
EST = d... | 0.558568 | 0.339869 |
import unittest
from myhdl_lib import *
from t_hsd_custom import t_hsd_custom
class Test_hsd_custom(t_hsd_custom):
'''|
| The main class for unit-testing. Add your tests here.
|________'''
def __init__(self):
# call base class constructor
t_hsd_custom.__init__(self)
# Automatical... | examples/hsd_custom/test/utest_hsd_custom.py | import unittest
from myhdl_lib import *
from t_hsd_custom import t_hsd_custom
class Test_hsd_custom(t_hsd_custom):
'''|
| The main class for unit-testing. Add your tests here.
|________'''
def __init__(self):
# call base class constructor
t_hsd_custom.__init__(self)
# Automatical... | 0.347759 | 0.432123 |
from .heatmap import *
from .ranksymbolthememap import *
from .mapvmap import *
from .geolines import *
from functools import wraps
from typing import List
from iclientpy import SymbolSetting, MapvOptions
def init_map_decorator(clz: type):
def init_method(func):
@wraps(func)
def init_m... | iclientpy/iclientpy/viz/__init__.py | from .heatmap import *
from .ranksymbolthememap import *
from .mapvmap import *
from .geolines import *
from functools import wraps
from typing import List
from iclientpy import SymbolSetting, MapvOptions
def init_map_decorator(clz: type):
def init_method(func):
@wraps(func)
def init_m... | 0.690872 | 0.164349 |
from click import style, echo, wrap_text
from collections import OrderedDict
import unicodedata
import fmf.utils
import pprint
import shlex
import re
import os
log = fmf.utils.Logging('tmt').logger
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Exceptions
# ~~~~~~~~~~~~~~~~~~~~~~~... | tmt/utils.py | from click import style, echo, wrap_text
from collections import OrderedDict
import unicodedata
import fmf.utils
import pprint
import shlex
import re
import os
log = fmf.utils.Logging('tmt').logger
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# Exceptions
# ~~~~~~~~~~~~~~~~~~~~~~~... | 0.530966 | 0.198608 |
libc_data = {
'imports': [
(0x23eadb0, 8, 9, '*.stderr'),
(0x23eadb8, 8, 9, '*.error_one_per_line'),
(0x23eadc0, 8, 9, '*.__morecore'),
(0x23eadd0, 8, 9, '*.__key_encryptsession_pk_LOCAL'),
(0x23eadd8, 8, 9, '*.__progname_full'),
(0x23eade0, 8, 9, '*.__ctype32_tolower... | vivisect/tests/linux_amd64_libc_2_27_data.py | libc_data = {
'imports': [
(0x23eadb0, 8, 9, '*.stderr'),
(0x23eadb8, 8, 9, '*.error_one_per_line'),
(0x23eadc0, 8, 9, '*.__morecore'),
(0x23eadd0, 8, 9, '*.__key_encryptsession_pk_LOCAL'),
(0x23eadd8, 8, 9, '*.__progname_full'),
(0x23eade0, 8, 9, '*.__ctype32_tolower... | 0.195902 | 0.13658 |
"""Tests for core.storage.file.gae_models."""
from __future__ import absolute_import # pylint: disable=import-only-modules
from __future__ import unicode_literals # pylint: disable=import-only-modules
from core.platform import models
from core.tests import test_utils
import feconf
(base_models, file_models) = mode... | core/storage/file/gae_models_test.py |
"""Tests for core.storage.file.gae_models."""
from __future__ import absolute_import # pylint: disable=import-only-modules
from __future__ import unicode_literals # pylint: disable=import-only-modules
from core.platform import models
from core.tests import test_utils
import feconf
(base_models, file_models) = mode... | 0.678007 | 0.175998 |
from typing import Any, ClassVar, Mapping
import torch.autograd
from torch import linalg
from torch.nn import functional
from ..base import EntityRelationEmbeddingModel
from ...constants import DEFAULT_EMBEDDING_HPO_EMBEDDING_DIM_RANGE
from ...nn.init import xavier_uniform_, xavier_uniform_norm_
from ...typing import... | src/pykeen/models/unimodal/trans_e.py | from typing import Any, ClassVar, Mapping
import torch.autograd
from torch import linalg
from torch.nn import functional
from ..base import EntityRelationEmbeddingModel
from ...constants import DEFAULT_EMBEDDING_HPO_EMBEDDING_DIM_RANGE
from ...nn.init import xavier_uniform_, xavier_uniform_norm_
from ...typing import... | 0.908962 | 0.513303 |
from typing import Optional
from vizier.api.routes.base import UrlFactory
class DatastoreClientUrlFactory(object):
"""Url factory for API client datastores that access and manipulate datasets
for a vizier project. This class is a wrapper around a UrlFactory and the
project identifier.
"""
def __i... | vizier/api/routes/datastore.py | from typing import Optional
from vizier.api.routes.base import UrlFactory
class DatastoreClientUrlFactory(object):
"""Url factory for API client datastores that access and manipulate datasets
for a vizier project. This class is a wrapper around a UrlFactory and the
project identifier.
"""
def __i... | 0.929144 | 0.305393 |
from unittest import TestCase, mock
import pytest
from django.contrib.auth import get_user_model
from django.test import RequestFactory
from django.utils import timezone
from rest_framework.authtoken.models import Token
from custom_auth.oauth.serializers import (
GithubLoginSerializer,
GoogleLoginSerializer,
... | api/custom_auth/oauth/tests/test_unit_serializers.py | from unittest import TestCase, mock
import pytest
from django.contrib.auth import get_user_model
from django.test import RequestFactory
from django.utils import timezone
from rest_framework.authtoken.models import Token
from custom_auth.oauth.serializers import (
GithubLoginSerializer,
GoogleLoginSerializer,
... | 0.45302 | 0.316264 |
from oslo_log import log as logging
from vitrage_tempest_tests.tests.api.topology.base import BaseTopologyTest
import vitrage_tempest_tests.tests.utils as utils
from vitrageclient.exc import ClientException
import unittest
LOG = logging.getLogger(__name__)
NOVA_QUERY = '{"and": [{"==": {"vitrage_category": "RESOUR... | vitrage_tempest_tests/tests/api/topology/test_topology.py |
from oslo_log import log as logging
from vitrage_tempest_tests.tests.api.topology.base import BaseTopologyTest
import vitrage_tempest_tests.tests.utils as utils
from vitrageclient.exc import ClientException
import unittest
LOG = logging.getLogger(__name__)
NOVA_QUERY = '{"and": [{"==": {"vitrage_category": "RESOUR... | 0.46952 | 0.319652 |
from horizon import views
from django.utils.translation import ugettext_lazy as _ # noqa
from horizon import tables
from horizon import tabs
from horizon import forms
from openstack_dashboard.dashboards.fogbow.attachment \
import tabs as project_tabs
from openstack_dashboard.dashboards.fogbow.attachment \
im... | openstack_dashboard/dashboards/fogbow/attachment/views.py | from horizon import views
from django.utils.translation import ugettext_lazy as _ # noqa
from horizon import tables
from horizon import tabs
from horizon import forms
from openstack_dashboard.dashboards.fogbow.attachment \
import tabs as project_tabs
from openstack_dashboard.dashboards.fogbow.attachment \
im... | 0.363647 | 0.1291 |
# Remember that if this were an exam problem, in order to be marked
# this file must meet certain requirements:
# - it must contain ONLY syntactically valid python code (any syntax
# or indentation error that stops the file from running would result
# in a mark of zero);
# - you MAY NOT use global variables; the f... | unnest.py |
# Remember that if this were an exam problem, in order to be marked
# this file must meet certain requirements:
# - it must contain ONLY syntactically valid python code (any syntax
# or indentation error that stops the file from running would result
# in a mark of zero);
# - you MAY NOT use global variables; the f... | 0.408749 | 0.861771 |
# Cuando termine de solicitar la información, ud tendrá una matriz con todos los datos necesarios para hacer un estudio y así no permitir que la empresa SInoMelaSeMeLasInvento S.A. prohiba Halloween. Para ello ud mostrará los siguientes datos:
# Cantidad de familias con un porcentaje mayor de 50% de consumo de dulces... | Ejercicios/c. Listas de listas/Reto 11-12. 21 a 22-04.py |
# Cuando termine de solicitar la información, ud tendrá una matriz con todos los datos necesarios para hacer un estudio y así no permitir que la empresa SInoMelaSeMeLasInvento S.A. prohiba Halloween. Para ello ud mostrará los siguientes datos:
# Cantidad de familias con un porcentaje mayor de 50% de consumo de dulces... | 0.223038 | 0.787073 |
from api.v1.views import app_views
from flask import abort, jsonify, request
from flasgger.utils import swag_from
from models import storage, CNC
from os import environ
STORAGE_TYPE = environ.get('HBNB_TYPE_STORAGE')
@swag_from('swagger_yaml/places_by_city.yml', methods=['GET', 'POST'])
@app_views.route('/cities/<cit... | api/v1/views/places.py | from api.v1.views import app_views
from flask import abort, jsonify, request
from flasgger.utils import swag_from
from models import storage, CNC
from os import environ
STORAGE_TYPE = environ.get('HBNB_TYPE_STORAGE')
@swag_from('swagger_yaml/places_by_city.yml', methods=['GET', 'POST'])
@app_views.route('/cities/<cit... | 0.470007 | 0.067886 |
from thetis import *
physical_constants['rho0'] = 1027.0 # NOTE must match empirical setup
depth = 50.0
class MaxNuCallback(DiagnosticCallback):
"""
Calculates max viscosity
"""
name = 'maxnu'
variable_names = ['nu']
def __call__(self):
return [self.solver_obj.fields.eddy_visc_3d.da... | examples/katophillips/katophillips.py | from thetis import *
physical_constants['rho0'] = 1027.0 # NOTE must match empirical setup
depth = 50.0
class MaxNuCallback(DiagnosticCallback):
"""
Calculates max viscosity
"""
name = 'maxnu'
variable_names = ['nu']
def __call__(self):
return [self.solver_obj.fields.eddy_visc_3d.da... | 0.663887 | 0.427576 |
import warnings
warnings.filterwarnings("ignore")
import jieba # 分词包
import numpy # numpy计算包
import codecs # codecs提供的open方法来指定打开的文件的语言编码,它会在读取的时候自动转换为内部unicode
import re
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image
from urllib import request
from bs4 import BeautifulSoup as bs
from word... | crawler/test.py | import warnings
warnings.filterwarnings("ignore")
import jieba # 分词包
import numpy # numpy计算包
import codecs # codecs提供的open方法来指定打开的文件的语言编码,它会在读取的时候自动转换为内部unicode
import re
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image
from urllib import request
from bs4 import BeautifulSoup as bs
from word... | 0.050799 | 0.1779 |
import xml.dom
from . import test_cssrule
import cssutils
class CSSStyleRuleTestCase(test_cssrule.CSSRuleTestCase):
def setUp(self):
super(CSSStyleRuleTestCase, self).setUp()
self.r = cssutils.css.CSSStyleRule()
self.rRO = cssutils.css.CSSStyleRule(readonly=True)
self.r_type = css... | venv/Lib/site-packages/cssutils/tests/test_cssstylerule.py |
import xml.dom
from . import test_cssrule
import cssutils
class CSSStyleRuleTestCase(test_cssrule.CSSRuleTestCase):
def setUp(self):
super(CSSStyleRuleTestCase, self).setUp()
self.r = cssutils.css.CSSStyleRule()
self.rRO = cssutils.css.CSSStyleRule(readonly=True)
self.r_type = css... | 0.312265 | 0.222035 |
# # MAD Portfolio Optimization
#
# Portfolio optimization and modern portfolio theory has a long and important history in finance and investment. The principal idea is to find a blend of investments in financial securities that achieves an optimal trade-off between financial risk and return. The introduction of mode... | _build/jupyter_execute/notebooks/02/mad-portfolio-optimization.py |
# # MAD Portfolio Optimization
#
# Portfolio optimization and modern portfolio theory has a long and important history in finance and investment. The principal idea is to find a blend of investments in financial securities that achieves an optimal trade-off between financial risk and return. The introduction of mode... | 0.813831 | 0.866472 |
import cvxpy.utilities as u
from cvxpy.expressions.expression import Expression
import cvxpy.lin_ops.lin_utils as lu
class Minimize(u.Canonical):
"""An optimization objective for minimization.
"""
NAME = "minimize"
def __init__(self, expr):
self._expr = Expression.cast_to_const(expr)
... | src/tools/ecos/cvxpy/cvxpy/problems/objective.py | import cvxpy.utilities as u
from cvxpy.expressions.expression import Expression
import cvxpy.lin_ops.lin_utils as lu
class Minimize(u.Canonical):
"""An optimization objective for minimization.
"""
NAME = "minimize"
def __init__(self, expr):
self._expr = Expression.cast_to_const(expr)
... | 0.861363 | 0.465023 |
from typhon.autohelp import autohelp, method
from typhon.errors import userError
from typhon.objects.root import Object, audited
from typhon.prelude import getGlobalValue
@autohelp
@audited.DF
class _NullObject(Object):
"""
The null object.
"""
def toString(self):
return u"null"
def opt... | typhon/objects/constants.py |
from typhon.autohelp import autohelp, method
from typhon.errors import userError
from typhon.objects.root import Object, audited
from typhon.prelude import getGlobalValue
@autohelp
@audited.DF
class _NullObject(Object):
"""
The null object.
"""
def toString(self):
return u"null"
def opt... | 0.703244 | 0.26746 |
import json
from ..importing import import_class_from_path
class Cache:
"""
Defines a generic caching client, that can be used with several adapters.
All lone scalar (being exlusively ints/floats, not ints/floats in dict, sets, lists, etc.)
are converted to unicode strings (redis is the only servic... | flashback/caching/cache.py |
import json
from ..importing import import_class_from_path
class Cache:
"""
Defines a generic caching client, that can be used with several adapters.
All lone scalar (being exlusively ints/floats, not ints/floats in dict, sets, lists, etc.)
are converted to unicode strings (redis is the only servic... | 0.814754 | 0.693622 |
import docker
from requests.exceptions import ConnectionError
from cpac.backends.platform import Backend, Platform_Meta
class Docker(Backend):
def __init__(self, **kwargs):
self.platform = Platform_Meta('Docker', '🐳')
print(f"Loading {self.platform.symbol} {self.platform.name}")
self.cl... | src/cpac/backends/docker.py | import docker
from requests.exceptions import ConnectionError
from cpac.backends.platform import Backend, Platform_Meta
class Docker(Backend):
def __init__(self, **kwargs):
self.platform = Platform_Meta('Docker', '🐳')
print(f"Loading {self.platform.symbol} {self.platform.name}")
self.cl... | 0.375248 | 0.051249 |
import cloudpickle
import os
import pendulum
import sys
import tempfile
from unittest.mock import MagicMock
import pytest
import prefect
from prefect import Flow
from prefect.environments.storage import Docker
from prefect.utilities.exceptions import SerializationError
def test_create_docker_storage():
storage ... | tests/environments/storage/test_docker_storage.py | import cloudpickle
import os
import pendulum
import sys
import tempfile
from unittest.mock import MagicMock
import pytest
import prefect
from prefect import Flow
from prefect.environments.storage import Docker
from prefect.utilities.exceptions import SerializationError
def test_create_docker_storage():
storage ... | 0.460774 | 0.421373 |
import os
import re
import csv
import sys
import json
import argparse
import random
from random import shuffle
import logging
from glob import glob
import numpy as np
from statistics import mean
OFFSET_IDX = 1e5 # start roughly after memesdataset files max idx
logging.basicConfig(format='%(asctime)s : %(levelname)s -... | utils/prep_memotion.py | import os
import re
import csv
import sys
import json
import argparse
import random
from random import shuffle
import logging
from glob import glob
import numpy as np
from statistics import mean
OFFSET_IDX = 1e5 # start roughly after memesdataset files max idx
logging.basicConfig(format='%(asctime)s : %(levelname)s -... | 0.097745 | 0.091829 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the ... | tests/test_combine.py |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the ... | 0.86959 | 0.426919 |
import os
# IMPORTATION THIRDPARTY
import pytest
# IMPORTATION INTERNAL
from gamestonk_terminal.portfolio.brokers.degiro import degiro_controller
# pylint: disable=E1101
# pylint: disable=W0603
# pylint: disable=E1111
@pytest.mark.vcr(record_mode="none")
@pytest.mark.parametrize(
"queue, expected",
[
... | tests/gamestonk_terminal/portfolio/brokers/degiro/test_degiro_controller.py | import os
# IMPORTATION THIRDPARTY
import pytest
# IMPORTATION INTERNAL
from gamestonk_terminal.portfolio.brokers.degiro import degiro_controller
# pylint: disable=E1101
# pylint: disable=W0603
# pylint: disable=E1111
@pytest.mark.vcr(record_mode="none")
@pytest.mark.parametrize(
"queue, expected",
[
... | 0.42668 | 0.249356 |
from .JavaScriptFunctionGenerator import FunctionType, JavaScriptFunctionGenerator
from .JavaScriptGeneratorUtils import indent
class JavaScriptClassGenerator:
@staticmethod
def get_generated_class_name(name):
return '{}Buffer'.format(name)
@staticmethod
def get_generated_getter_name(attribut... | generators/javascript/javascript_builder/JavaScriptClassGenerator.py | from .JavaScriptFunctionGenerator import FunctionType, JavaScriptFunctionGenerator
from .JavaScriptGeneratorUtils import indent
class JavaScriptClassGenerator:
@staticmethod
def get_generated_class_name(name):
return '{}Buffer'.format(name)
@staticmethod
def get_generated_getter_name(attribut... | 0.524151 | 0.124559 |
import json
import urllib2
import argparse
import os
import ConfigParser
import httplib2
__author__ = "<NAME> <<EMAIL>>"
__version__ = "0.1"
class REST_Kernel:
def __init__(self, base_uri):
self.base_uri = base_uri
self.user_agent = "MeltdownPY {0}".format(__version__)
def __post(self, body, ... | cli/meltdown.py | import json
import urllib2
import argparse
import os
import ConfigParser
import httplib2
__author__ = "<NAME> <<EMAIL>>"
__version__ = "0.1"
class REST_Kernel:
def __init__(self, base_uri):
self.base_uri = base_uri
self.user_agent = "MeltdownPY {0}".format(__version__)
def __post(self, body, ... | 0.289372 | 0.065366 |
import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
import igraph as ig
from utils.constants import DatasetType, GraphVisualizationTool, network_repository_cora_url, cora_label_to_color_map
from utils.utils import convert_adj_to_edge_index
def plot_in_out_degree_distributions(edge_index, num_of... | utils/visualizations.py | import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
import igraph as ig
from utils.constants import DatasetType, GraphVisualizationTool, network_repository_cora_url, cora_label_to_color_map
from utils.utils import convert_adj_to_edge_index
def plot_in_out_degree_distributions(edge_index, num_of... | 0.812384 | 0.822724 |
from oslo_log import log as logging
import six
from cinder import context
from cinder.i18n import _LW
from cinder.volume import driver
from cinder.volume.drivers.emc import emc_vmax_common
from cinder.zonemanager import utils as fczm_utils
LOG = logging.getLogger(__name__)
class EMCVMAXFCDriver(driver.FibreChannel... | cinder/volume/drivers/emc/emc_vmax_fc.py |
from oslo_log import log as logging
import six
from cinder import context
from cinder.i18n import _LW
from cinder.volume import driver
from cinder.volume.drivers.emc import emc_vmax_common
from cinder.zonemanager import utils as fczm_utils
LOG = logging.getLogger(__name__)
class EMCVMAXFCDriver(driver.FibreChannel... | 0.788176 | 0.24262 |
from .log import log
from .empty import empty
from .base import BaseTest
from .engine import Engine
from .context import Context
from .resolver import OperatorResolver
class Test(BaseTest):
"""
Test represents the test definition in `grappa` with extensible and
dynamic, runtime inferred DSL based on regis... | grappa/test.py | from .log import log
from .empty import empty
from .base import BaseTest
from .engine import Engine
from .context import Context
from .resolver import OperatorResolver
class Test(BaseTest):
"""
Test represents the test definition in `grappa` with extensible and
dynamic, runtime inferred DSL based on regis... | 0.90325 | 0.360855 |
import grok
import z3c.flashmessage.interfaces
from grokui.base.layout import GrokUIView
from grokui.admin.interfaces import ISecurityNotifier
from grokui.admin.utilities import getVersion
from grokui.admin.security import SecurityNotifier
from ZODB.interfaces import IDatabase
from ZODB.FileStorage.FileStorage impor... | src/grokui/admin/server.py |
import grok
import z3c.flashmessage.interfaces
from grokui.base.layout import GrokUIView
from grokui.admin.interfaces import ISecurityNotifier
from grokui.admin.utilities import getVersion
from grokui.admin.security import SecurityNotifier
from ZODB.interfaces import IDatabase
from ZODB.FileStorage.FileStorage impor... | 0.579043 | 0.06724 |
import datetime
from googlecloudsdk.third_party.apitools.base.protorpclite import messages
from googlecloudsdk.third_party.apitools.base.protorpclite import util
__all__ = [
'DateTimeField',
'DateTimeMessage',
'VoidMessage',
]
class VoidMessage(messages.Message):
"""Empty message."""
class DateTim... | lib/googlecloudsdk/third_party/apitools/base/protorpclite/message_types.py | import datetime
from googlecloudsdk.third_party.apitools.base.protorpclite import messages
from googlecloudsdk.third_party.apitools.base.protorpclite import util
__all__ = [
'DateTimeField',
'DateTimeMessage',
'VoidMessage',
]
class VoidMessage(messages.Message):
"""Empty message."""
class DateTim... | 0.863722 | 0.14256 |
# DJANGO
from django.conf import settings
from django.conf.urls import patterns, include, url, static
from django.views.generic import TemplateView
# API
from addata.api import get_api
urlpatterns = patterns('',
# api
url(r'^api/', include(get_api().urls)),
# addata
url(r'^admonitor/', include('addat... | vavs_project/vavs_project/urls.py |
# DJANGO
from django.conf import settings
from django.conf.urls import patterns, include, url, static
from django.views.generic import TemplateView
# API
from addata.api import get_api
urlpatterns = patterns('',
# api
url(r'^api/', include(get_api().urls)),
# addata
url(r'^admonitor/', include('addat... | 0.278061 | 0.057652 |
import asyncio
from contextlib import nullcontext
from typing import TYPE_CHECKING, Optional
import grpc
from jina.clients.base import BaseClient
from jina.clients.helper import callback_exec, callback_exec_on_error
from jina.excepts import BadClient, BadClientInput, BaseJinaException
from jina.logging.profile import... | jina/clients/base/grpc.py | import asyncio
from contextlib import nullcontext
from typing import TYPE_CHECKING, Optional
import grpc
from jina.clients.base import BaseClient
from jina.clients.helper import callback_exec, callback_exec_on_error
from jina.excepts import BadClient, BadClientInput, BaseJinaException
from jina.logging.profile import... | 0.617974 | 0.062445 |
import time
import glob
import os
import numpy as np
import pandas as pd
from sklearn.base import clone
from sklearn.metrics import make_scorer
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.model_selection import train_test_split, GridSearchCV, RandomizedSearchCV, ParameterGrid, cross_val... | examples/Cluster-based_Input_Weight_Initialization_for_Echo_State_Networks.py | import time
import glob
import os
import numpy as np
import pandas as pd
from sklearn.base import clone
from sklearn.metrics import make_scorer
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from sklearn.model_selection import train_test_split, GridSearchCV, RandomizedSearchCV, ParameterGrid, cross_val... | 0.523177 | 0.356083 |
import pygame, sys, random
from pygame.locals import *
# Set up pygame.
pygame.init()
mainClock = pygame.time.Clock()
# Set up the window.
WINDOWWIDTH = 400
WINDOWHEIGHT = 400
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Collision Detection')
# Set up the co... | Invent Your Own Computer Games with Python/ch19_collision_detection/collision_detection.py | import pygame, sys, random
from pygame.locals import *
# Set up pygame.
pygame.init()
mainClock = pygame.time.Clock()
# Set up the window.
WINDOWWIDTH = 400
WINDOWHEIGHT = 400
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Collision Detection')
# Set up the co... | 0.279042 | 0.185467 |
from typing import Any, Callable, Mapping, Sequence, Tuple
import fedjax
import jax
ClientId = bytes
Grads = fedjax.Params
@fedjax.dataclass
class ServerState:
"""State of server passed between rounds.
Attributes:
params: A pytree representing the server model parameters.
opt_state: A pytree represent... | examples/fed_avg.py | from typing import Any, Callable, Mapping, Sequence, Tuple
import fedjax
import jax
ClientId = bytes
Grads = fedjax.Params
@fedjax.dataclass
class ServerState:
"""State of server passed between rounds.
Attributes:
params: A pytree representing the server model parameters.
opt_state: A pytree represent... | 0.90853 | 0.416559 |
import datetime
import json
import optparse
import sys
import time
import traceback
import urllib
from datetime import timedelta
from email.mime.text import MIMEText
from subprocess import Popen, PIPE
SUCCESS_SUBJECT = ('[CHROME TESTING]: Builder status %s: PASSED.')
FAILURE_SUBJECT = ('[CHROME TESTING]: Builder sta... | chrome/test/chromedriver/test/waterfall_builder_monitor.py | import datetime
import json
import optparse
import sys
import time
import traceback
import urllib
from datetime import timedelta
from email.mime.text import MIMEText
from subprocess import Popen, PIPE
SUCCESS_SUBJECT = ('[CHROME TESTING]: Builder status %s: PASSED.')
FAILURE_SUBJECT = ('[CHROME TESTING]: Builder sta... | 0.348867 | 0.083441 |
try:
from flask import render_template, jsonify, request, Flask, send_from_directory, redirect
import json, time, random, requests, os
import secrets
import discord
from discord.ext import commands
from discord.ext.commands import bot
import asyncio
import aiohttp
import requests
... | Image_Uploader.py | try:
from flask import render_template, jsonify, request, Flask, send_from_directory, redirect
import json, time, random, requests, os
import secrets
import discord
from discord.ext import commands
from discord.ext.commands import bot
import asyncio
import aiohttp
import requests
... | 0.219505 | 0.070816 |
"""Unit tests for the BackendNode and BackendNodeCollection classes."""
from collections import OrderedDict
from datetime import datetime
from uuid import UUID
import pytz
from aiida.backends.testbase import AiidaTestCase
from aiida.common import exceptions, timezone
class TestBackendNode(AiidaTestCase):
"""Te... | tests/orm/implementation/test_nodes.py | """Unit tests for the BackendNode and BackendNodeCollection classes."""
from collections import OrderedDict
from datetime import datetime
from uuid import UUID
import pytz
from aiida.backends.testbase import AiidaTestCase
from aiida.common import exceptions, timezone
class TestBackendNode(AiidaTestCase):
"""Te... | 0.923988 | 0.526708 |
from setuptools import setup
description = """PyAge2 - Age of Empires II Learning Environment
`PyAge2` allows to interact with "Age of Empires II: The Conquerors" game from OpenAI Gym compatible Reinforcement Learning environment.
The environment runs the game process, injects the DLL that runs a server allowing ex... | setup.py |
from setuptools import setup
description = """PyAge2 - Age of Empires II Learning Environment
`PyAge2` allows to interact with "Age of Empires II: The Conquerors" game from OpenAI Gym compatible Reinforcement Learning environment.
The environment runs the game process, injects the DLL that runs a server allowing ex... | 0.7413 | 0.594816 |
import idfy_rest_client.models.error
import idfy_rest_client.models.environment_info
class IdentificationResponse(object):
"""Implementation of the 'IdentificationResponse' model.
The reponse for the identity process. Contains users name, id number etc
Attributes:
name (string): The fu... | idfy_rest_client/models/identification_response.py | import idfy_rest_client.models.error
import idfy_rest_client.models.environment_info
class IdentificationResponse(object):
"""Implementation of the 'IdentificationResponse' model.
The reponse for the identity process. Contains users name, id number etc
Attributes:
name (string): The fu... | 0.630912 | 0.166303 |
import torch
from torch.utils.data.dataloader import DataLoader, default_collate
from jacinle.random import reset_global_seed, gen_seed
__all__ = ['JacDataLoader']
class _InitFunctionWrapper(object):
def __init__(self, base_seed, fn_init, args, kwargs):
self._base_seed = base_seed
self._fn_init... | third_party/Jacinle/jactorch/data/dataloader.py |
import torch
from torch.utils.data.dataloader import DataLoader, default_collate
from jacinle.random import reset_global_seed, gen_seed
__all__ = ['JacDataLoader']
class _InitFunctionWrapper(object):
def __init__(self, base_seed, fn_init, args, kwargs):
self._base_seed = base_seed
self._fn_init... | 0.712432 | 0.164014 |
"""Contains the basic structure necessary to execute the simulation.
"""
# EdgeSimPy components
from edge_sim_py.simulator import Simulator
from edge_sim_py.components.topology import Topology
from edge_sim_py.components.base_station import BaseStation
from edge_sim_py.components.user import User
from edge_sim_py.compo... | argos/__main__.py | """Contains the basic structure necessary to execute the simulation.
"""
# EdgeSimPy components
from edge_sim_py.simulator import Simulator
from edge_sim_py.components.topology import Topology
from edge_sim_py.components.base_station import BaseStation
from edge_sim_py.components.user import User
from edge_sim_py.compo... | 0.898902 | 0.60935 |
male = [
'William',
'Noah',
'Oscar',
'Lucas',
'Carl',
'Oliver',
'Victor',
'Alfred',
'Malthe',
'Emil',
'Valdemar',
'Elias',
'Magnus',
'Aksel',
'Frederik',
'Felix',
'Elliot',
'August',
'Anton',
'Nohr',
'Alexander',
'Villads',
'Chr... | john_doe/names/denmark.py | male = [
'William',
'Noah',
'Oscar',
'Lucas',
'Carl',
'Oliver',
'Victor',
'Alfred',
'Malthe',
'Emil',
'Valdemar',
'Elias',
'Magnus',
'Aksel',
'Frederik',
'Felix',
'Elliot',
'August',
'Anton',
'Nohr',
'Alexander',
'Villads',
'Chr... | 0.291283 | 0.175256 |
import discord
from discord.ext import commands
orange=discord.Color.orange()
class Bot(commands.Cog):
def __init__(self,bot):
self.bot=bot
@commands.Cog.listener()
async def on_command(self, ctx):
channel = self.bot.get_channel(841906846389764146)
embed = discord.Embed(title=f"<:Chchibi:8433793611... | childe/commands.py | import discord
from discord.ext import commands
orange=discord.Color.orange()
class Bot(commands.Cog):
def __init__(self,bot):
self.bot=bot
@commands.Cog.listener()
async def on_command(self, ctx):
channel = self.bot.get_channel(841906846389764146)
embed = discord.Embed(title=f"<:Chchibi:8433793611... | 0.486575 | 0.094093 |
import subprocess
import argparse
import pathlib
import shutil
import stat
import json
import sys
import os
DEFAULT = {
"deb_version": "0.0.1",
"deb_architecture": "amd64",
"deb_maintainer": "Mr. Robot",
"deb_description": "Something awesome",
"deb_package": 'noname'
}
def expand_path(path):
... | scripts/meson_dist_deb_build.py | import subprocess
import argparse
import pathlib
import shutil
import stat
import json
import sys
import os
DEFAULT = {
"deb_version": "0.0.1",
"deb_architecture": "amd64",
"deb_maintainer": "Mr. Robot",
"deb_description": "Something awesome",
"deb_package": 'noname'
}
def expand_path(path):
... | 0.379148 | 0.146331 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensor2tensor.trax.backend import numpy as np
from tensor2tensor.trax.layers import base as layers
def tree_flatten(tree):
"""Flatten a tree into a list."""
if isinstance(tree, (list, tuple)):
# ... | tensor2tensor/trax/optimizers/base.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensor2tensor.trax.backend import numpy as np
from tensor2tensor.trax.layers import base as layers
def tree_flatten(tree):
"""Flatten a tree into a list."""
if isinstance(tree, (list, tuple)):
# ... | 0.951852 | 0.521837 |
from gevent.lock import RLock
import binascii
import gevent.socket
import json
import os
import logging
MSG_SIZE_LIMIT = 1024 * 1024 * 128 # 128 MB
MSG_CONTINUATION_MARKER = '\x00\x00\x00continued\x00\x00\x00'
def _seq_split(to_split):
while to_split:
yield to_split[:MSG_SIZE_LIMIT] + (MSG_CONTINUATION_... | ajenti-core/aj/gate/stream.py | from gevent.lock import RLock
import binascii
import gevent.socket
import json
import os
import logging
MSG_SIZE_LIMIT = 1024 * 1024 * 128 # 128 MB
MSG_CONTINUATION_MARKER = '\x00\x00\x00continued\x00\x00\x00'
def _seq_split(to_split):
while to_split:
yield to_split[:MSG_SIZE_LIMIT] + (MSG_CONTINUATION_... | 0.413359 | 0.095687 |
from DBUtils.PooledDB import PooledDB
from config import *
class MySQL(object):
"""
MYSQL数据库对象,负责产生数据库连接
此类中的连接采用连接池实现获取连接对象, conn = Mysql.getConn()
释放连接对象, conn.close()或del conn
"""
# 连接池对象
__pool = None
def __init__(self):
# 数据库构造函数,从连接池中取出连接,并生成操作游标
self._conn = My... | db_util/connector.py | from DBUtils.PooledDB import PooledDB
from config import *
class MySQL(object):
"""
MYSQL数据库对象,负责产生数据库连接
此类中的连接采用连接池实现获取连接对象, conn = Mysql.getConn()
释放连接对象, conn.close()或del conn
"""
# 连接池对象
__pool = None
def __init__(self):
# 数据库构造函数,从连接池中取出连接,并生成操作游标
self._conn = My... | 0.353875 | 0.234297 |
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('firstfloor', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='profile',
name='friend_list',
... | firstfloor/migrations/0002_auto_20200718_2000.py |
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('firstfloor', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='profile',
name='friend_list',
... | 0.500244 | 0.160463 |
import re
import redis
import logging
import traceback
from common.utils.timer import FuncTimer
from . import EngineBase
from .models import ResultSet, ReviewSet, ReviewResult
__author__ = 'hhyo'
logger = logging.getLogger('default')
class RedisEngine(EngineBase):
def get_connection(self, db_name=None):
... | sql/engines/redis.py | import re
import redis
import logging
import traceback
from common.utils.timer import FuncTimer
from . import EngineBase
from .models import ResultSet, ReviewSet, ReviewResult
__author__ = 'hhyo'
logger = logging.getLogger('default')
class RedisEngine(EngineBase):
def get_connection(self, db_name=None):
... | 0.300438 | 0.094177 |
from typing import Type, Optional
from .PermissionHandler import PermissionHandler
from .Permission import Permission
from .Check import Check, Perm
def get_check(cls, name) -> Optional[Check]:
"""
Gets the class variables and converts them to a check if they are not already.
"""
default = getattr(cl... | perm_banana/banana.py | from typing import Type, Optional
from .PermissionHandler import PermissionHandler
from .Permission import Permission
from .Check import Check, Perm
def get_check(cls, name) -> Optional[Check]:
"""
Gets the class variables and converts them to a check if they are not already.
"""
default = getattr(cl... | 0.868199 | 0.259405 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import copy
import sys
import math
from collections import defaultdict
from motmetrics.math_util import quiet_divide
import numpy as np
import pandas as pd
import paddle
import paddle.nn.functional... | Paddle_Industry_Practice_Sample_Library/Multi-Class_Vehicle_Tracking/mcmot_metrics.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import copy
import sys
import math
from collections import defaultdict
from motmetrics.math_util import quiet_divide
import numpy as np
import pandas as pd
import paddle
import paddle.nn.functional... | 0.579757 | 0.145661 |
from snapDB.snapTypeBase import snapTypeBase
from snapDB.enumerations import QualityFlags
from gsf.binaryStream import binaryStream
from gsf import Limits, ByteSize, override
from uuid import UUID
import struct
import numpy as np
class historianValue(snapTypeBase):
"""
The standard SNAPdb value used for the o... | src/openHistorian/historianValue.py |
from snapDB.snapTypeBase import snapTypeBase
from snapDB.enumerations import QualityFlags
from gsf.binaryStream import binaryStream
from gsf import Limits, ByteSize, override
from uuid import UUID
import struct
import numpy as np
class historianValue(snapTypeBase):
"""
The standard SNAPdb value used for the o... | 0.853119 | 0.310956 |