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 tensorflow as tf
slim = tf.contrib.slim
from tensorflow.contrib.framework.python.ops import add_arg_scope
from utils.slim_utils import _build_variable_getter, _add_variable_to_collections, convert_data_format
from tensorflow.python.ops import nn_ops
@add_arg_scope
def convolution(inputs,
num_... | utils/sn_conv.py | import tensorflow as tf
slim = tf.contrib.slim
from tensorflow.contrib.framework.python.ops import add_arg_scope
from utils.slim_utils import _build_variable_getter, _add_variable_to_collections, convert_data_format
from tensorflow.python.ops import nn_ops
@add_arg_scope
def convolution(inputs,
num_... | 0.959001 | 0.472866 |
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
# Installed Packages
from knox.models import AuthToken
from knox import settings
# Django Packages
from django.contrib.auth import get_user_model
url = reverse("rest-social-email-auth:user-login")... | tests/views/test_user_login_view.py | from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase
# Installed Packages
from knox.models import AuthToken
from knox import settings
# Django Packages
from django.contrib.auth import get_user_model
url = reverse("rest-social-email-auth:user-login")... | 0.599837 | 0.438485 |
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
from mock import ANY
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
try:
from ansible.modules.network.fortios import fortios_ips_glob... | v6.0.6/ips/test_fortios_ips_global.py |
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
from mock import ANY
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
try:
from ansible.modules.network.fortios import fortios_ips_glob... | 0.699152 | 0.200597 |
from .models import account
from django.contrib.auth import authenticate,login,logout
from django.views.decorators.csrf import csrf_exempt
from rest_framework.response import Response
from rest_framework.decorators import api_view
import json
from .serializers import accountSerializer
from django.contrib.sessions.model... | backendApi/accounts/views.py | from .models import account
from django.contrib.auth import authenticate,login,logout
from django.views.decorators.csrf import csrf_exempt
from rest_framework.response import Response
from rest_framework.decorators import api_view
import json
from .serializers import accountSerializer
from django.contrib.sessions.model... | 0.375936 | 0.066873 |
import sys
class handleParameter():
def __init__(self):
self.args = []
for arg in sys.argv[1:]:
if sys.platform == 'win32' and sys.stdin.encoding == 'cp936':
arg = arg.decode('gbk')
self.args.append(arg)
def getAction(self):
if self.... | qcloudcli/handleParameter.py | import sys
class handleParameter():
def __init__(self):
self.args = []
for arg in sys.argv[1:]:
if sys.platform == 'win32' and sys.stdin.encoding == 'cp936':
arg = arg.decode('gbk')
self.args.append(arg)
def getAction(self):
if self.... | 0.14436 | 0.083143 |
from django.test import TestCase
from .models import Post, Profile, Neighbourhood
from datetime import datetime
from django.contrib.auth.models import User
class ProfileTest(TestCase):
''' test class for Profile model'''
def setUp(self):
''' method called before each test case'''
self.user = ... | hoodapp/tests.py | from django.test import TestCase
from .models import Post, Profile, Neighbourhood
from datetime import datetime
from django.contrib.auth.models import User
class ProfileTest(TestCase):
''' test class for Profile model'''
def setUp(self):
''' method called before each test case'''
self.user = ... | 0.486575 | 0.349699 |
import sys
import io
import subprocess
import threading
import time
import uuid
import os.path
import requests
import json
from random import randint
from UniqueConfiguration import UniqueConfiguration
from CommonConfiguration import CommonConfiguration
from printer import console_out
class BrokerActions:
def __in... | orchestration/v1/run/BrokerActions.py | import sys
import io
import subprocess
import threading
import time
import uuid
import os.path
import requests
import json
from random import randint
from UniqueConfiguration import UniqueConfiguration
from CommonConfiguration import CommonConfiguration
from printer import console_out
class BrokerActions:
def __in... | 0.109396 | 0.065935 |
import sqlalchemy
from databases import Database
from fastapi import Depends, FastAPI
from pytest import fixture
from fastapi_pagination import (
LimitOffsetPage,
LimitOffsetPaginationParams,
Page,
PaginationParams,
)
from fastapi_pagination.ext.databases import paginate
from ..base import (
BaseP... | tests/ext/test_databases.py | import sqlalchemy
from databases import Database
from fastapi import Depends, FastAPI
from pytest import fixture
from fastapi_pagination import (
LimitOffsetPage,
LimitOffsetPaginationParams,
Page,
PaginationParams,
)
from fastapi_pagination.ext.databases import paginate
from ..base import (
BaseP... | 0.451568 | 0.110711 |
from django.shortcuts import render
import django_filters
from rest_framework import filters
import json
import logging
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from django.http import HttpResponse
from django.http import HttpRequest
from iec_lookup.services.iec_lookup_s... | iec/iec_lookup/controllers/iec_lookup_controller.py | from django.shortcuts import render
import django_filters
from rest_framework import filters
import json
import logging
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from django.http import HttpResponse
from django.http import HttpRequest
from iec_lookup.services.iec_lookup_s... | 0.316898 | 0.059265 |
import os.path
import subprocess
from textwrap import dedent
import pytest
from pex.common import safe_open
from pex.compatibility import PY2
from pex.testing import run_pex_command
from pex.typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Any
@pytest.mark.skipif(PY2, reason="Example code used ... | tests/integration/test_issue_1802.py | import os.path
import subprocess
from textwrap import dedent
import pytest
from pex.common import safe_open
from pex.compatibility import PY2
from pex.testing import run_pex_command
from pex.typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import Any
@pytest.mark.skipif(PY2, reason="Example code used ... | 0.225929 | 0.092852 |
import numpy as np
import math
state_dim = 2
n_actions = 27
class environment():
def __init__(self):
self.states_dim = 2
self.n_actions = 27
self.possible_actions_orig = [(i, j, k) for i in range(-1,2) for j in range(-1,2) for k in range(-1,2)]
self.mapping_actions = [i for i in range(27)]... | environment.py | import numpy as np
import math
state_dim = 2
n_actions = 27
class environment():
def __init__(self):
self.states_dim = 2
self.n_actions = 27
self.possible_actions_orig = [(i, j, k) for i in range(-1,2) for j in range(-1,2) for k in range(-1,2)]
self.mapping_actions = [i for i in range(27)]... | 0.387459 | 0.297132 |
#!/usr/bin/env python
import requests
import json
import sys
import os
# Set the environment variable GPT_API_KEY to your API key
GPT_API_KEY = os.environ['GPT_API_KEY']
def get_gpt_guess(question):
prompt = "Q: {}\nA:".format(question)
data = json.dumps({
"prompt": prompt,
"max_tokens": 150,
... | gpt3-ask.py | #!/usr/bin/env python
import requests
import json
import sys
import os
# Set the environment variable GPT_API_KEY to your API key
GPT_API_KEY = os.environ['GPT_API_KEY']
def get_gpt_guess(question):
prompt = "Q: {}\nA:".format(question)
data = json.dumps({
"prompt": prompt,
"max_tokens": 150,
... | 0.211173 | 0.216342 |
import threading
from peewee import *
from playhouse.kv import JSONKeyStore
from playhouse.kv import KeyStore
from playhouse.kv import PickledKeyStore
from playhouse.tests.base import PeeweeTestCase
from playhouse.tests.base import skip_if
class TestKeyStore(PeeweeTestCase):
def setUp(self):
super(TestKe... | playhouse/tests/test_kv.py | import threading
from peewee import *
from playhouse.kv import JSONKeyStore
from playhouse.kv import KeyStore
from playhouse.kv import PickledKeyStore
from playhouse.tests.base import PeeweeTestCase
from playhouse.tests.base import skip_if
class TestKeyStore(PeeweeTestCase):
def setUp(self):
super(TestKe... | 0.497803 | 0.458288 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.eager import def_function
from tensorflow.python.framework import ops
from tensorflow.python.keras import backend_config
from tensorflow.python.keras.optimizer_v2 import optimizer_v2
from... | swiss_army_keras/optimizers.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.eager import def_function
from tensorflow.python.framework import ops
from tensorflow.python.keras import backend_config
from tensorflow.python.keras.optimizer_v2 import optimizer_v2
from... | 0.880707 | 0.243406 |
import os
import json
import logging
import numpy
from osgeo import gdal
from ground_surveyor import gsconfig
def pick_best_pile_layer(pile_md_filename,
selection_options):
pile_md = json.load(open(pile_md_filename))
best_i = -1
best_value = 0
target_field = selec... | ground_surveyor/uf_mosaic.py | import os
import json
import logging
import numpy
from osgeo import gdal
from ground_surveyor import gsconfig
def pick_best_pile_layer(pile_md_filename,
selection_options):
pile_md = json.load(open(pile_md_filename))
best_i = -1
best_value = 0
target_field = selec... | 0.178669 | 0.251182 |
import select
import socket
from typing import Union
from tmtccmd.utility.logger import get_console_logger
from tmtccmd.com_if.com_interface_base import CommunicationInterface
from tmtccmd.tm.definitions import TelemetryListT
from tmtccmd.utility.tmtc_printer import TmTcPrinter
from tmtccmd.config.definitions import E... | src/tmtccmd/com_if/tcpip_udp_com_if.py | import select
import socket
from typing import Union
from tmtccmd.utility.logger import get_console_logger
from tmtccmd.com_if.com_interface_base import CommunicationInterface
from tmtccmd.tm.definitions import TelemetryListT
from tmtccmd.utility.tmtc_printer import TmTcPrinter
from tmtccmd.config.definitions import E... | 0.698638 | 0.063395 |
import os
from os.path import join, exists
import numpy as np
from pgl.utils.data.dataloader import Dataloader
from pgl.utils.data.dataset import StreamDataset as PglStreamDataset
from pahelix.utils.data_utils import save_data_list_to_npz, load_npz_to_data_list
__all__ = ['StreamDataset']
class StreamDataset(obje... | pahelix/datasets/stream_dataset.py | import os
from os.path import join, exists
import numpy as np
from pgl.utils.data.dataloader import Dataloader
from pgl.utils.data.dataset import StreamDataset as PglStreamDataset
from pahelix.utils.data_utils import save_data_list_to_npz, load_npz_to_data_list
__all__ = ['StreamDataset']
class StreamDataset(obje... | 0.396535 | 0.259896 |
import json
import re
from tornado import httpclient
from tornado.gen import coroutine
from torip import utilities
from torip.exceptions import ToripException
__author__ = 'mendrugory'
IPV4_REGEX_PATTERN = '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'
de... | torip/ipapis.py | import json
import re
from tornado import httpclient
from tornado.gen import coroutine
from torip import utilities
from torip.exceptions import ToripException
__author__ = 'mendrugory'
IPV4_REGEX_PATTERN = '^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$'
de... | 0.466846 | 0.208562 |
__author__ = '<NAME>'
import time
import re
import threading
import docker
import tweepy
from config import CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_SECRET
CLIENT = docker.from_env()
AUTH = tweepy.OAuthHandler(consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET)
AUTH.set_access_token(ACCESS_TOKEN,... | main.py | __author__ = '<NAME>'
import time
import re
import threading
import docker
import tweepy
from config import CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN, ACCESS_SECRET
CLIENT = docker.from_env()
AUTH = tweepy.OAuthHandler(consumer_key=CONSUMER_KEY, consumer_secret=CONSUMER_SECRET)
AUTH.set_access_token(ACCESS_TOKEN,... | 0.368178 | 0.066965 |
import signal
import subprocess
from time import sleep
from os.path import join
from dateutil.parser import parse
from datetime import datetime
from autonmap.client import client_server
from autonmap.client import config_manager
from autonmap.client import process_manager
from autonmap.client import report_client
"""... | autonmap/client/client.py | import signal
import subprocess
from time import sleep
from os.path import join
from dateutil.parser import parse
from datetime import datetime
from autonmap.client import client_server
from autonmap.client import config_manager
from autonmap.client import process_manager
from autonmap.client import report_client
"""... | 0.435421 | 0.059976 |
import os
import unittest
import random
import numpy as np
from sklearn.svm import SVC
from sklearn.datasets import load_wine, load_iris
from stree.Splitter import Splitter
from .utils import load_dataset, load_disc_dataset
class Splitter_test(unittest.TestCase):
def __init__(self, *args, **kwargs):
self... | stree/tests/Splitter_test.py | import os
import unittest
import random
import numpy as np
from sklearn.svm import SVC
from sklearn.datasets import load_wine, load_iris
from stree.Splitter import Splitter
from .utils import load_dataset, load_disc_dataset
class Splitter_test(unittest.TestCase):
def __init__(self, *args, **kwargs):
self... | 0.659624 | 0.539347 |
from __future__ import print_function
import XInput
from inputs import get_gamepad
import inputs
import time
import threading
import random
import vgamepad as vg
# Array of the buttons (using 0 for LT and 1 for RT)
button = [None] * 10
button = [vg.XUSB_BUTTON.XUSB_GAMEPAD_A, vg.XUSB_BUTTON.XUSB_GAMEPAD_Y, vg.XUSB_BUT... | scripts/RC.py | from __future__ import print_function
import XInput
from inputs import get_gamepad
import inputs
import time
import threading
import random
import vgamepad as vg
# Array of the buttons (using 0 for LT and 1 for RT)
button = [None] * 10
button = [vg.XUSB_BUTTON.XUSB_GAMEPAD_A, vg.XUSB_BUTTON.XUSB_GAMEPAD_Y, vg.XUSB_BUT... | 0.272702 | 0.26341 |
import sympy
from sympy.utilities import lambdify
from ndispers._baseclass import Medium, wl, T
from ndispers.helper import vars2
class FusedSilica(Medium):
"""
Fused Silica glass
Dispersion formula for refractive index
---------------------------------------
n(wl_um) = sqrt(1 + B1 * wl_um**2/... | ndispers/media/glasses/_fusedsilica.py | import sympy
from sympy.utilities import lambdify
from ndispers._baseclass import Medium, wl, T
from ndispers.helper import vars2
class FusedSilica(Medium):
"""
Fused Silica glass
Dispersion formula for refractive index
---------------------------------------
n(wl_um) = sqrt(1 + B1 * wl_um**2/... | 0.792906 | 0.427337 |
import json
import os
import sys
from os import environ
from pathlib import Path
from typing import Dict, Iterable
import boto3
import pytest
from _pytest.monkeypatch import MonkeyPatch
from moto import mock_ec2
from mypy_boto3_ec2.client import EC2Client
from pytest_cases import fixture
from .manage_ec2 import creat... | tests/conftest.py | import json
import os
import sys
from os import environ
from pathlib import Path
from typing import Dict, Iterable
import boto3
import pytest
from _pytest.monkeypatch import MonkeyPatch
from moto import mock_ec2
from mypy_boto3_ec2.client import EC2Client
from pytest_cases import fixture
from .manage_ec2 import creat... | 0.450359 | 0.189221 |
from typing import List
from quantity import Quantity
from quantity_space import QuantitySpace
from quantity_state import QuantityState
class QualitativeState:
def __init__(self):
self.qualitative_state_quantities = []
def add_quantity(self, quantity: Quantity, value: QuantitySpace, gradient: str):
... | qualitative-reasoning/qualitative_state.py | from typing import List
from quantity import Quantity
from quantity_space import QuantitySpace
from quantity_state import QuantityState
class QualitativeState:
def __init__(self):
self.qualitative_state_quantities = []
def add_quantity(self, quantity: Quantity, value: QuantitySpace, gradient: str):
... | 0.898383 | 0.438304 |
from urls import requests_url
def test_get_requests_succeeds(valid_request_model, client, request_headers):
"""
Tests that response is okay.
Args:
valid_request_model (Model): a valid model created by a fixture.
client (FlaskClient): a test client created by a fixture.
request_hea... | tests/views/test_request_endpoints.py | from urls import requests_url
def test_get_requests_succeeds(valid_request_model, client, request_headers):
"""
Tests that response is okay.
Args:
valid_request_model (Model): a valid model created by a fixture.
client (FlaskClient): a test client created by a fixture.
request_hea... | 0.841858 | 0.381623 |
Crypits_0_Dice_Reward_Types = {
'[1]': 'crypits',
'[2]': 'crypits',
'[3]': 'crypits',
'[4]': 'crypits',
'[5]': 'crypits',
'[6]': 'crypits',
'[7]': 'crypits',
'[8]': 'crypits',
'[9]': 'crypits',
'[10]': 'crypits',
'[11]': 'crypits',
'[12]': 'crypits',
'[13... | crypits_rewards.py | Crypits_0_Dice_Reward_Types = {
'[1]': 'crypits',
'[2]': 'crypits',
'[3]': 'crypits',
'[4]': 'crypits',
'[5]': 'crypits',
'[6]': 'crypits',
'[7]': 'crypits',
'[8]': 'crypits',
'[9]': 'crypits',
'[10]': 'crypits',
'[11]': 'crypits',
'[12]': 'crypits',
'[13... | 0.428233 | 0.383468 |
from functools import wraps, partial
from typing import Union, Optional, TypeVar, Type
import pytest
import andi
class Foo:
pass
class Bar:
pass
class Baz:
pass
def test_andi():
def func1(x: Foo):
pass
def func2():
pass
def func3(x: Bar, y: Foo):
pass
ass... | tests/test_inspect.py | from functools import wraps, partial
from typing import Union, Optional, TypeVar, Type
import pytest
import andi
class Foo:
pass
class Bar:
pass
class Baz:
pass
def test_andi():
def func1(x: Foo):
pass
def func2():
pass
def func3(x: Bar, y: Foo):
pass
ass... | 0.893495 | 0.712282 |
import socket
import selectors
import types
import fire
class SocketReader():
def __init__(self, host, port, sep = '\n'):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen()
sock.setblocking(False)
self.sock = sock
sel = s... | wrappers/SocketReader.py | import socket
import selectors
import types
import fire
class SocketReader():
def __init__(self, host, port, sep = '\n'):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((host, port))
sock.listen()
sock.setblocking(False)
self.sock = sock
sel = s... | 0.196518 | 0.083106 |
from typing import Any, Union
from collections import deque, OrderedDict
from collections.abc import Mapping
from typing_extensions import Literal
from typing_json.typechecking import is_instance, is_namedtuple
from typing_json.encoding import JSON_BASE_TYPES, is_json_encodable
_UNREACHABLE_ERROR_MSG = "Should never ... | typing_json/decoding.py |
from typing import Any, Union
from collections import deque, OrderedDict
from collections.abc import Mapping
from typing_extensions import Literal
from typing_json.typechecking import is_instance, is_namedtuple
from typing_json.encoding import JSON_BASE_TYPES, is_json_encodable
_UNREACHABLE_ERROR_MSG = "Should never ... | 0.659295 | 0.189484 |
from __future__ import print_function
import roslib
roslib.load_manifest('mct_blob_finder')
import rospy
import threading
import sys
from cv_bridge.cv_bridge import CvBridge
from mct_blob_finder import BlobFinder
import mct_introspection
# Messages
from sensor_msgs.msg import Image
from mct_msg_and_srv.msg import Se... | mct_blob_finder/nodes/blob_finder_node.py | from __future__ import print_function
import roslib
roslib.load_manifest('mct_blob_finder')
import rospy
import threading
import sys
from cv_bridge.cv_bridge import CvBridge
from mct_blob_finder import BlobFinder
import mct_introspection
# Messages
from sensor_msgs.msg import Image
from mct_msg_and_srv.msg import Se... | 0.350199 | 0.180865 |
import re
from typing import Optional
from wikitextparser import WikiText, Section
from to_python.core.context import ParseFunctionSide, ContextData
from to_python.core.filter import FilterAbstract
from to_python.core.format import colorize_token_list
from to_python.core.signature import SignatureParser, SignatureTok... | to_python/filters/data_list/signature.py | import re
from typing import Optional
from wikitextparser import WikiText, Section
from to_python.core.context import ParseFunctionSide, ContextData
from to_python.core.filter import FilterAbstract
from to_python.core.format import colorize_token_list
from to_python.core.signature import SignatureParser, SignatureTok... | 0.567098 | 0.223504 |
import pyglet
import pyperclip
import keyword
import tokenize
import io
import os
from pyno.utils import x_y_pan_scale, font
from pyno.draw import quad_aligned
highlight = set(list(__builtins__.keys()) +
list(keyword.__dict__.keys()) +
keyword.kwlist +
['call', 'clean... | pyno/codeEditor.py | import pyglet
import pyperclip
import keyword
import tokenize
import io
import os
from pyno.utils import x_y_pan_scale, font
from pyno.draw import quad_aligned
highlight = set(list(__builtins__.keys()) +
list(keyword.__dict__.keys()) +
keyword.kwlist +
['call', 'clean... | 0.448668 | 0.128416 |
class BoolNode:
def __init__(self,token):
self.token = token
self.position = token.position
def __repr__(self):
return f'{self.token}'
class NumberNode:
def __init__(self,token):
self.token = token
self.position = token.position
def __repr__(self):
retu... | server/zeta_basic/PARSER/AbstractSyntaxTreeNodes.py | class BoolNode:
def __init__(self,token):
self.token = token
self.position = token.position
def __repr__(self):
return f'{self.token}'
class NumberNode:
def __init__(self,token):
self.token = token
self.position = token.position
def __repr__(self):
retu... | 0.8415 | 0.244916 |
import socket , re , datetime , threading , time
#IRC Information
SERVER = 'irc.freenode.net'
PORT = 6667
NICKNAME = 'write nickname here'
CHANNEL = '#write channel here'
network = SERVER.split('.')
#Terminal Colours
Black = '\x1b[30m'
Red = '\x1b[31m'
Green = '\x1b[32m'
Yellow = '\x1b[33m'
Blue = '\x1b[34m'... | IRC.py |
import socket , re , datetime , threading , time
#IRC Information
SERVER = 'irc.freenode.net'
PORT = 6667
NICKNAME = 'write nickname here'
CHANNEL = '#write channel here'
network = SERVER.split('.')
#Terminal Colours
Black = '\x1b[30m'
Red = '\x1b[31m'
Green = '\x1b[32m'
Yellow = '\x1b[33m'
Blue = '\x1b[34m'... | 0.042196 | 0.078184 |
import os
import sys
from simpleimage import SimpleImage
def get_pixel_dist(pixel, red, green, blue):
"""
Returns the color distance between pixel and mean RGB value
Input:
pixel (Pixel): pixel with RGB values to be compared
red (int): average red value across all images
green (int... | sc_projects/SC101/stanCodoshop/stanCodoshop.py | import os
import sys
from simpleimage import SimpleImage
def get_pixel_dist(pixel, red, green, blue):
"""
Returns the color distance between pixel and mean RGB value
Input:
pixel (Pixel): pixel with RGB values to be compared
red (int): average red value across all images
green (int... | 0.717309 | 0.690957 |
from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import logging
from flexget import plugin
from flexget.event import event
from flexget.utils.tools import split_title_year
log = logging.getLogger('est_series_tvmaze')
... | flexget/plugins/estimators/est_release_series_tvmaze.py | from __future__ import unicode_literals, division, absolute_import
from builtins import * # noqa pylint: disable=unused-import, redefined-builtin
import logging
from flexget import plugin
from flexget.event import event
from flexget.utils.tools import split_title_year
log = logging.getLogger('est_series_tvmaze')
... | 0.577019 | 0.059374 |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaurant20to50, obj[15]: Direct... | duke-cs671-fall21-coupon-recommendation/outputs/rules/RF/17_features/numtrees_20/rule_6.py | def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaurant20to50, obj[15]: Direct... | 0.067443 | 0.267947 |
import numpy as np
from os import listdir
from matplotlib import pyplot as plt
def apply_spectrum(data, pca, numinput=256, power=1.0):
colored = data.dot(np.diag(np.power(pca.sValues[:numinput], power)))
return colored/colored.std()
def get_params_and_errors(net, toy, nunits=256, folder='.',
... | whitening/utils.py | import numpy as np
from os import listdir
from matplotlib import pyplot as plt
def apply_spectrum(data, pca, numinput=256, power=1.0):
colored = data.dot(np.diag(np.power(pca.sValues[:numinput], power)))
return colored/colored.std()
def get_params_and_errors(net, toy, nunits=256, folder='.',
... | 0.29584 | 0.318339 |
from DB import DataBase
class Users:
def __init__(self, id_user=0, name="", email="", tel="", postal_code="",
state="", city="", district="", street="", number="", residence_type=""):
self.id_user = id_user
self.name = name
self.email = email
self.tel = tel
... | Users.py | from DB import DataBase
class Users:
def __init__(self, id_user=0, name="", email="", tel="", postal_code="",
state="", city="", district="", street="", number="", residence_type=""):
self.id_user = id_user
self.name = name
self.email = email
self.tel = tel
... | 0.421314 | 0.256122 |
import dash
from dash import html
import dash_bootstrap_components as dbc
from dash import dcc
from dash.dependencies import Input, Output, State
from db import connect_to_db, query_fg, query_tokens, query_futures
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
e... | dash/app.py | import dash
from dash import html
import dash_bootstrap_components as dbc
from dash import dcc
from dash.dependencies import Input, Output, State
from db import connect_to_db, query_fg, query_tokens, query_futures
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
e... | 0.625209 | 0.157687 |
import numpy as np
import pytest
from numpy import testing as npt
from metriculous.evaluators._classification_utils import (
ClassificationData,
ProbabilityMatrix,
)
class TestProbabilityMatrix:
def test_that_it_can_be_initialized_from_nested_list(self) -> None:
_ = ProbabilityMatrix(
... | src/metriculous/evaluators/_classification_utils_test.py | import numpy as np
import pytest
from numpy import testing as npt
from metriculous.evaluators._classification_utils import (
ClassificationData,
ProbabilityMatrix,
)
class TestProbabilityMatrix:
def test_that_it_can_be_initialized_from_nested_list(self) -> None:
_ = ProbabilityMatrix(
... | 0.808067 | 0.791902 |
import base64
import os
import os.path
import re
import stat
import string
import subprocess
import sys
import zlib
def _FileMatches(path, excl_regexps):
"""Returns true if the specified path matches none of the
specified exclude regular expresions.
"""
for r in excl_regexps:
if re.match(r, path):
r... | backend/prod/package.py | import base64
import os
import os.path
import re
import stat
import string
import subprocess
import sys
import zlib
def _FileMatches(path, excl_regexps):
"""Returns true if the specified path matches none of the
specified exclude regular expresions.
"""
for r in excl_regexps:
if re.match(r, path):
r... | 0.412885 | 0.197174 |
class Restaurant():
def __init__(self, rest_name, rest_cuisine):
self.rest_name = rest_name
self.rest_cuisine = rest_cuisine
self.number_served = 0
def describe_restaurant(self):
print(f"The restaurant name is {self.rest_name} and cuisine is {self.rest_cuisine}")
def open_r... | Learn Python Book/Stage 9 (Classes)/restaurant.py | class Restaurant():
def __init__(self, rest_name, rest_cuisine):
self.rest_name = rest_name
self.rest_cuisine = rest_cuisine
self.number_served = 0
def describe_restaurant(self):
print(f"The restaurant name is {self.rest_name} and cuisine is {self.rest_cuisine}")
def open_r... | 0.386648 | 0.213521 |
import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
from PINSoftware.MachineState import MachineState
def SingleSwitch(id_, label, default=False):
... | PINSoftware/DashComponents.py | import dash_core_components as dcc
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash
from dash.dependencies import Input, Output, State
from dash.exceptions import PreventUpdate
from PINSoftware.MachineState import MachineState
def SingleSwitch(id_, label, default=False):
... | 0.770378 | 0.272526 |
from revelation.isa import decode
from revelation.instruction import Instruction
import opcode_factory
import pytest
@pytest.mark.parametrize('name,instr',
[('add32', opcode_factory.add32(rd=0, rn=0, rm=0)),
('add16', opcode_factory.add16(rd=0, rn=0, rm=... | revelation/test/test_decode.py | from revelation.isa import decode
from revelation.instruction import Instruction
import opcode_factory
import pytest
@pytest.mark.parametrize('name,instr',
[('add32', opcode_factory.add32(rd=0, rn=0, rm=0)),
('add16', opcode_factory.add16(rd=0, rn=0, rm=... | 0.332961 | 0.123577 |
import re
from elram.repository.services import CommandException
class CommandParser:
_commands_mapping = {
'add_attendee': (
r'^(?P<nickname>\w+) vino$',
r'^(?P<nickname>\w+) viene$',
r'^(?P<nickname>\w+) va$',
r'^(?P<nickname>\w+) fue$',
r'^v... | elram/conversations/command_parser.py | import re
from elram.repository.services import CommandException
class CommandParser:
_commands_mapping = {
'add_attendee': (
r'^(?P<nickname>\w+) vino$',
r'^(?P<nickname>\w+) viene$',
r'^(?P<nickname>\w+) va$',
r'^(?P<nickname>\w+) fue$',
r'^v... | 0.400046 | 0.305529 |
import pyautogui, os, psutil, sys, subprocess, cv2, signal, patterns
from time import time
from time import sleep
PROCESS_BNET = "Battle.net.exe"
EXE_BNET = "C:\Program Files (x86)\Battle.net\Battle.net Launcher.exe"
PROCESS_WOW = "Wow.exe"
SECONDS_MAX_WAIT = 15
SECONDS_MAX_WAIT_PROCESS = 30
SECONDS_SLEEP =... | wow-launcher-script.py |
import pyautogui, os, psutil, sys, subprocess, cv2, signal, patterns
from time import time
from time import sleep
PROCESS_BNET = "Battle.net.exe"
EXE_BNET = "C:\Program Files (x86)\Battle.net\Battle.net Launcher.exe"
PROCESS_WOW = "Wow.exe"
SECONDS_MAX_WAIT = 15
SECONDS_MAX_WAIT_PROCESS = 30
SECONDS_SLEEP =... | 0.106935 | 0.0545 |
import pickle
import pytorch_lightning as pl
from torch.utils.data import DataLoader
from source.Dataset.PawsDataset import PawsDataset
class PawsDataModule(pl.LightningDataModule):
"""
Paws DataModule
"""
def __init__(self, params, st1_tokenizer, st2_tokenizer, fold):
super(PawsDataModule,... | source/DataModule/PawsDataModule.py | import pickle
import pytorch_lightning as pl
from torch.utils.data import DataLoader
from source.Dataset.PawsDataset import PawsDataset
class PawsDataModule(pl.LightningDataModule):
"""
Paws DataModule
"""
def __init__(self, params, st1_tokenizer, st2_tokenizer, fold):
super(PawsDataModule,... | 0.805823 | 0.286144 |
import inspect
import logging
class logger(object):
def __init__(self, name, level):
"""
Initialize the class with some basic attributes.
"""
self.level = level
self.name = name
self.setLogLevel(self.level)
def setLogLevel(self,level):
try:
... | logger.py | import inspect
import logging
class logger(object):
def __init__(self, name, level):
"""
Initialize the class with some basic attributes.
"""
self.level = level
self.name = name
self.setLogLevel(self.level)
def setLogLevel(self,level):
try:
... | 0.336876 | 0.063395 |
# [SET_DRESS_CHANGED] [00 00 ]
sm.giveAndEquip(1352601)
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
sm.forcedInput(0)
sm.forcedInput(2)
sm.sendDelay(30)
sm.forcedInput(0)
sm.forcedInput(4)
OBJECT_1 = sm.sendNpcController(3000141, -150, 220)
sm.showNpcSpecia... | scripts/field/angelic_tuto4.py |
# [SET_DRESS_CHANGED] [00 00 ]
sm.giveAndEquip(1352601)
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, True, False, False)
sm.forcedInput(0)
sm.forcedInput(2)
sm.sendDelay(30)
sm.forcedInput(0)
sm.forcedInput(4)
OBJECT_1 = sm.sendNpcController(3000141, -150, 220)
sm.showNpcSpecia... | 0.348645 | 0.198666 |
import numpy as np
import OpenGL.GL as gl
import math
import ctypes
import hashlib
cache = {}
class base(object):
"""Base class for 2d geometries with modelview and projection transforms"""
version = """#version 300 es\n"""
vertex_code = """
uniform mat4 modelview;
uniform m... | geometry/__init__.py | import numpy as np
import OpenGL.GL as gl
import math
import ctypes
import hashlib
cache = {}
class base(object):
"""Base class for 2d geometries with modelview and projection transforms"""
version = """#version 300 es\n"""
vertex_code = """
uniform mat4 modelview;
uniform m... | 0.694717 | 0.221888 |
import boto3
from services.common import *
iam = boto3.client('iam')
def _process_create_user(event: dict, set_tag: bool = False) -> list:
""" Process CreateUser event. """
user_name = event['responseElements']['user']['userName']
if set_tag is True:
tags = iam.list_user_tags(UserName=user_na... | functions/watcher/services/iam.py | import boto3
from services.common import *
iam = boto3.client('iam')
def _process_create_user(event: dict, set_tag: bool = False) -> list:
""" Process CreateUser event. """
user_name = event['responseElements']['user']['userName']
if set_tag is True:
tags = iam.list_user_tags(UserName=user_na... | 0.375592 | 0.152379 |
import numpy as np
import datetime
from matplotlib import pyplot as plt
from betellib import tweet, build_string, get_mags_from_AAVSO
def make_plot(days_ago, dates, mag):
print('Making plot...')
time_span = np.max(dates) - np.min(dates)
min_plot = 0
max_plot = 1.4
x_days = 2000
# Make bin... | betel5y.py | import numpy as np
import datetime
from matplotlib import pyplot as plt
from betellib import tweet, build_string, get_mags_from_AAVSO
def make_plot(days_ago, dates, mag):
print('Making plot...')
time_span = np.max(dates) - np.min(dates)
min_plot = 0
max_plot = 1.4
x_days = 2000
# Make bin... | 0.616705 | 0.377512 |
from __future__ import annotations
from dataclasses import dataclass, field
from itertools import chain, count, repeat
from typing import Dict, Iterable, Iterator, List, Optional, Set, Tuple
from dataslots import with_slots
import tsim.core.index as Index
from tsim.core.entity import DeleteResult, EntityRef
from ts... | tsim/core/network/node.py |
from __future__ import annotations
from dataclasses import dataclass, field
from itertools import chain, count, repeat
from typing import Dict, Iterable, Iterator, List, Optional, Set, Tuple
from dataslots import with_slots
import tsim.core.index as Index
from tsim.core.entity import DeleteResult, EntityRef
from ts... | 0.954223 | 0.464841 |
from collections import deque
class Solution:
# The given root is the root of the Binary Tree
# Return the root of the generated BST
def InOrder(self, root, inorder):
# code here
if(root != None):
self.InOrder(root.left, inorder)
inorder.append(root.data)
... | Competitive Programming/Binary Search Trees/Convert Binary tree into BST.py | from collections import deque
class Solution:
# The given root is the root of the Binary Tree
# Return the root of the generated BST
def InOrder(self, root, inorder):
# code here
if(root != None):
self.InOrder(root.left, inorder)
inorder.append(root.data)
... | 0.873026 | 0.718881 |
import numpy as np
import scipy as sp
import scipy.linalg
import pybie2d
from qfs.two_d_qfs import QFS_Evaluator
from ....annular.poisson import AnnularPoissonSolver
from ....annular.annular import ApproximateAnnularGeometry, RealAnnularGeometry
from ....derivatives import fourier, fd_x_4, fd_y_4
from ....utilities imp... | ipde/solvers/single_boundary/interior/poisson.py | import numpy as np
import scipy as sp
import scipy.linalg
import pybie2d
from qfs.two_d_qfs import QFS_Evaluator
from ....annular.poisson import AnnularPoissonSolver
from ....annular.annular import ApproximateAnnularGeometry, RealAnnularGeometry
from ....derivatives import fourier, fd_x_4, fd_y_4
from ....utilities imp... | 0.641647 | 0.511778 |
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision
from art.data_generators import *
from art.utils import *
from art.classifiers import *
from art.attacks import *
import numpy as np
import resnet as resnet
import argparse
import models
from tqdm import tqdm
parser = argparse.Argument... | whitebox_and_black.py | import torch.nn as nn
import torchvision.transforms as transforms
import torchvision
from art.data_generators import *
from art.utils import *
from art.classifiers import *
from art.attacks import *
import numpy as np
import resnet as resnet
import argparse
import models
from tqdm import tqdm
parser = argparse.Argument... | 0.638723 | 0.310015 |
import os, json, logging, requests
PROTOCOL = 'http://'
IP_ADDRESS = '127.0.0.1'
IO_PORT = '8078'
class BaseRequest(object):
def __init__(self, ip=IP_ADDRESS, port=IO_PORT):
self.ip_address = ip
self.port = port
self.url_base = PROTOCOL + self.ip_address + ':' + str(self.port)
se... | thingsboard_gateway/sin_edge_sdk/base_request.py | import os, json, logging, requests
PROTOCOL = 'http://'
IP_ADDRESS = '127.0.0.1'
IO_PORT = '8078'
class BaseRequest(object):
def __init__(self, ip=IP_ADDRESS, port=IO_PORT):
self.ip_address = ip
self.port = port
self.url_base = PROTOCOL + self.ip_address + ':' + str(self.port)
se... | 0.294824 | 0.068787 |
import copy
import os
import time
from typing import Dict
import torch
import torch.nn as nn
class InputBlock(nn.Conv2d):
def __init__(self, nfilters, input_channels, kernel_size=3):
super().__init__(input_channels, nfilters, kernel_size=kernel_size, padding=1)
class BNConv(nn.Module):
def __init__... | selfplaylab/net.py | import copy
import os
import time
from typing import Dict
import torch
import torch.nn as nn
class InputBlock(nn.Conv2d):
def __init__(self, nfilters, input_channels, kernel_size=3):
super().__init__(input_channels, nfilters, kernel_size=kernel_size, padding=1)
class BNConv(nn.Module):
def __init__... | 0.945121 | 0.400456 |
from pyspark import Row
from pyspark.sql import SparkSession
spark = SparkSession \
.builder \
.appName("lex-spark") \
.master("local[*]") \
.getOrCreate()
sc = spark.sparkContext
file = r".\lex.txt" # 修改1
rdd = sc.textFile(file)
info = rdd.map(lambda x: x.split("\t")) # lex.txt的分割方式是/t
info_array ... | School/Spark_exp/pycharm/lex.py | from pyspark import Row
from pyspark.sql import SparkSession
spark = SparkSession \
.builder \
.appName("lex-spark") \
.master("local[*]") \
.getOrCreate()
sc = spark.sparkContext
file = r".\lex.txt" # 修改1
rdd = sc.textFile(file)
info = rdd.map(lambda x: x.split("\t")) # lex.txt的分割方式是/t
info_array ... | 0.277473 | 0.378316 |
import random
import tempfile
from collections import Counter
from concurrent.futures import as_completed, ProcessPoolExecutor
from itertools import product
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pystan
from tqdm import tqdm
from .. import config, estimation
from ..preprocessing... | dynast/benchmarking/simulation.py | import random
import tempfile
from collections import Counter
from concurrent.futures import as_completed, ProcessPoolExecutor
from itertools import product
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pystan
from tqdm import tqdm
from .. import config, estimation
from ..preprocessing... | 0.738103 | 0.379206 |
import pandas as pd
def data_clean():
'''data_clean() 函数用于数据清洁,大致步骤如下:
1. 统一设置国家代码为新索引
2. 去掉多余的数据列
3. 将不规范空值替换为 NaN,并进行填充
'''
# 读取数据文件
df_data = pd.read_excel("ClimateChange.xlsx", sheetname='Data')
df_country = pd.read_excel("ClimateChange.xlsx", sheetname='Country')
# 处理 data 数据... | Answers/week2-challenge-04/carbon_dioxide.py | import pandas as pd
def data_clean():
'''data_clean() 函数用于数据清洁,大致步骤如下:
1. 统一设置国家代码为新索引
2. 去掉多余的数据列
3. 将不规范空值替换为 NaN,并进行填充
'''
# 读取数据文件
df_data = pd.read_excel("ClimateChange.xlsx", sheetname='Data')
df_country = pd.read_excel("ClimateChange.xlsx", sheetname='Country')
# 处理 data 数据... | 0.218669 | 0.459015 |
import numpy as np
from scipy.optimize import minimize, brute, fmin
from .confidence import (parametric_bootstrap, nonparametric_bootstrap,
delta, contour_walk, increase_bounds,
HomogeneousResult)
from .plotting import plot_probability as pp, plot_confidence_region as pc... | senpy/neyer.py |
import numpy as np
from scipy.optimize import minimize, brute, fmin
from .confidence import (parametric_bootstrap, nonparametric_bootstrap,
delta, contour_walk, increase_bounds,
HomogeneousResult)
from .plotting import plot_probability as pp, plot_confidence_region as pc... | 0.893379 | 0.538923 |
from datetime import datetime
from typing import Optional
import attr
@attr.dataclass
class Sanitasi:
sekolah_id: str
semester_id: str
sumber_air_id: str
sumber_air_minum_id: str
ketersediaan_air: str
kecukupan_air: str
minum_siswa: str
memproses_air: str
siswa_bawa_air: str
t... | dapodik/sekolah/sanitasi.py | from datetime import datetime
from typing import Optional
import attr
@attr.dataclass
class Sanitasi:
sekolah_id: str
semester_id: str
sumber_air_id: str
sumber_air_minum_id: str
ketersediaan_air: str
kecukupan_air: str
minum_siswa: str
memproses_air: str
siswa_bawa_air: str
t... | 0.723993 | 0.275733 |
from pyspark.sql import SparkSession
from pyspark import SparkContext
from pyspark.sql.types import StructType, StructField, StringType, IntegerType
from pyspark.sql.functions import udf, col, from_json, flatten, explode, desc, count
from datetime import datetime
import argparse
def getChart(df):
df=df.withColumn(... | ETL.py | from pyspark.sql import SparkSession
from pyspark import SparkContext
from pyspark.sql.types import StructType, StructField, StringType, IntegerType
from pyspark.sql.functions import udf, col, from_json, flatten, explode, desc, count
from datetime import datetime
import argparse
def getChart(df):
df=df.withColumn(... | 0.590425 | 0.286762 |
import codecs
import io
import os
import re
import shutil
import typing as tp
__all__ = ['read_re_sub_and_write', 'find_files', 'split', 'read_in_file', 'write_to_file',
'write_out_file_if_different', 'make_noncolliding_name', 'try_unlink',
'DevNullFilelikeObject', 'read_lines']
from satella.cod... | satella/files.py | import codecs
import io
import os
import re
import shutil
import typing as tp
__all__ = ['read_re_sub_and_write', 'find_files', 'split', 'read_in_file', 'write_to_file',
'write_out_file_if_different', 'make_noncolliding_name', 'try_unlink',
'DevNullFilelikeObject', 'read_lines']
from satella.cod... | 0.588889 | 0.279189 |
import base64
import binascii
import hashlib
import hmac
import requests
import scrypt
class InvalidRequestException(Exception):
"""Exception containing information about failed request."""
def __init__(self, message, status=None):
"""Instantiate exception with message and (optional) status object.
... | keybaseclient/raw_api.py | import base64
import binascii
import hashlib
import hmac
import requests
import scrypt
class InvalidRequestException(Exception):
"""Exception containing information about failed request."""
def __init__(self, message, status=None):
"""Instantiate exception with message and (optional) status object.
... | 0.767429 | 0.116061 |
from unittest import TestCase
from neo.Prompt import Utils
from neocore.Fixed8 import Fixed8
from neocore.UInt160 import UInt160
class TestInputParser(TestCase):
def test_utils_1(self):
args = [1, 2, 3]
args, neo, gas = Utils.get_asset_attachments(args)
self.assertEqual(args, [1, 2, 3]... | neo/Prompt/test_utils.py | from unittest import TestCase
from neo.Prompt import Utils
from neocore.Fixed8 import Fixed8
from neocore.UInt160 import UInt160
class TestInputParser(TestCase):
def test_utils_1(self):
args = [1, 2, 3]
args, neo, gas = Utils.get_asset_attachments(args)
self.assertEqual(args, [1, 2, 3]... | 0.726231 | 0.641296 |
import numpy as np
from numpy.lib.stride_tricks import as_strided
import numbers
def rolled(arr_in, window_shape, step=1):
"""Rolling window view of the input n-dimensional array.
Windows are overlapping views of the input array, with adjacent windows
shifted by a single row or column (or an index of a ... | deddiag_loader/utils.py |
import numpy as np
from numpy.lib.stride_tricks import as_strided
import numbers
def rolled(arr_in, window_shape, step=1):
"""Rolling window view of the input n-dimensional array.
Windows are overlapping views of the input array, with adjacent windows
shifted by a single row or column (or an index of a ... | 0.92433 | 0.872782 |
import numpy as np
import pandas as pd
import joblib
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.base import BaseEstimator, TransformerMixin
from classifier import config
from classifier.utils.process_data import text_processors
class SentimentClassifier(Ba... | src/classifier/sentiment_model.py | import numpy as np
import pandas as pd
import joblib
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.base import BaseEstimator, TransformerMixin
from classifier import config
from classifier.utils.process_data import text_processors
class SentimentClassifier(Ba... | 0.888934 | 0.654978 |
import scanpy as sc
from sctriangulate import *
from sctriangulate.colors import *
from sctriangulate.preprocessing import *
print('===================\nimport modules test:',u'\u2713','\n====================')
sctriangulate_setting(backend='Agg')
adata = sc.read('input.h5ad')
sctri = ScTriangulate(dir='output',adata... | test/mini_test.py | import scanpy as sc
from sctriangulate import *
from sctriangulate.colors import *
from sctriangulate.preprocessing import *
print('===================\nimport modules test:',u'\u2713','\n====================')
sctriangulate_setting(backend='Agg')
adata = sc.read('input.h5ad')
sctri = ScTriangulate(dir='output',adata... | 0.291888 | 0.159054 |
import os
import unittest
import logging
import shutil
import tempfile
import ciftify.config
from ciftify.utils import run
import pytest
from pytest import raises
from unittest.mock import patch
import pandas as pd
import numpy as np
def get_test_data_path():
return os.path.join(os.path.dirname(os.path.dirname(__f... | tests/functional/test_ciftify_seed_corr.py | import os
import unittest
import logging
import shutil
import tempfile
import ciftify.config
from ciftify.utils import run
import pytest
from pytest import raises
from unittest.mock import patch
import pandas as pd
import numpy as np
def get_test_data_path():
return os.path.join(os.path.dirname(os.path.dirname(__f... | 0.335024 | 0.254796 |
from collections import defaultdict
import itertools
from cdecimal import Decimal
from gryphon.lib.logger import get_logger
from gryphon.lib.models.emeraldhavoc.orderbook import Orderbook
from gryphon.lib.money import Money
from gryphon.lib.metrics import midpoint
logger = get_logger(__name__)
CURRENCY_MISMATCH_ER... | gryphon/lib/arbitrage.py | from collections import defaultdict
import itertools
from cdecimal import Decimal
from gryphon.lib.logger import get_logger
from gryphon.lib.models.emeraldhavoc.orderbook import Orderbook
from gryphon.lib.money import Money
from gryphon.lib.metrics import midpoint
logger = get_logger(__name__)
CURRENCY_MISMATCH_ER... | 0.85067 | 0.420302 |
import sys
sys.path.extend(('lib', 'db'))
from kleros import db, Dispute, Round, Vote, Config, Court, JurorStake, Deposit, Juror
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func
from datetime import datetime
from time import gmtime, strftime
import statistics
app = Flask(_... | flaskr/monitor.py |
import sys
sys.path.extend(('lib', 'db'))
from kleros import db, Dispute, Round, Vote, Config, Court, JurorStake, Deposit, Juror
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import func
from datetime import datetime
from time import gmtime, strftime
import statistics
app = Flask(_... | 0.302803 | 0.095392 |
from collections import defaultdict
from docopt import docopt
import logging
import logzero
from logzero import logger as log
import re
import os
SCRIPTDIR = os.path.dirname(os.path.realpath(__file__))
def re_match_group(pattern, string):
m = re.search(pattern, string)
if m is not None:
return m.gro... | bin/summarize_logs.py | from collections import defaultdict
from docopt import docopt
import logging
import logzero
from logzero import logger as log
import re
import os
SCRIPTDIR = os.path.dirname(os.path.realpath(__file__))
def re_match_group(pattern, string):
m = re.search(pattern, string)
if m is not None:
return m.gro... | 0.303629 | 0.085556 |
import cv2
import io
import base64
import numpy as np
import tempfile
from flask import flash, send_file
from makeup_service.server.face_makeup_facade import FaceMakeupFacade
face_makeup = FaceMakeupFacade()
def transform_image(request):
allowed_extensions = {'png', 'jpg', 'jpeg'}
colors = get_colors(request... | makeup_service/server/request_processor.py | import cv2
import io
import base64
import numpy as np
import tempfile
from flask import flash, send_file
from makeup_service.server.face_makeup_facade import FaceMakeupFacade
face_makeup = FaceMakeupFacade()
def transform_image(request):
allowed_extensions = {'png', 'jpg', 'jpeg'}
colors = get_colors(request... | 0.40486 | 0.109491 |
from __future__ import absolute_import
from __future__ import print_function
import cv2
import numpy as np
import tensorflow as tf
import imagedt
from .DataInterface import *
from ...image.process import noise_padd
slim = tf.contrib.slim
def dynamically_loaded_data(image_paths, labels, height=224, width=224):
la... | imagedt/tensorflow/tools/data_provider.py | from __future__ import absolute_import
from __future__ import print_function
import cv2
import numpy as np
import tensorflow as tf
import imagedt
from .DataInterface import *
from ...image.process import noise_padd
slim = tf.contrib.slim
def dynamically_loaded_data(image_paths, labels, height=224, width=224):
la... | 0.74055 | 0.260389 |
import sys
from flask import Flask, render_template, json, request
import logging as l
import os
from datetime import datetime
from stat import *
URL_BASE = "https://satai.dk"
app = Flask(__name__)
items = [{"url": ("%s" % URL_BASE), "name": "Loading ...", "date": "...", "size": "..."}]
source = '/mnt/... | app.py | import sys
from flask import Flask, render_template, json, request
import logging as l
import os
from datetime import datetime
from stat import *
URL_BASE = "https://satai.dk"
app = Flask(__name__)
items = [{"url": ("%s" % URL_BASE), "name": "Loading ...", "date": "...", "size": "..."}]
source = '/mnt/... | 0.137272 | 0.081155 |
import inspect
from fedoralink.fedorans import RDF
from fedoralink.utils import fullname
def _type_matches(types_from_metadata, types_being_matched):
for a_type in types_being_matched:
if a_type not in types_from_metadata:
return False
return True
def _has_predicates(metadata, predicates... | fedoralink/type_manager.py | import inspect
from fedoralink.fedorans import RDF
from fedoralink.utils import fullname
def _type_matches(types_from_metadata, types_being_matched):
for a_type in types_being_matched:
if a_type not in types_from_metadata:
return False
return True
def _has_predicates(metadata, predicates... | 0.676086 | 0.330201 |
import sys
from webots_ros2_core.utils import append_webots_python_lib_to_path
from tf2_msgs.msg import TFMessage
from sensor_msgs.msg import LaserScan
from builtin_interfaces.msg import Time
from geometry_msgs.msg import TransformStamped
import transforms3d
try:
append_webots_python_lib_to_path()
from con... | webots_ros2_core/webots_ros2_core/laser_publisher.py | import sys
from webots_ros2_core.utils import append_webots_python_lib_to_path
from tf2_msgs.msg import TFMessage
from sensor_msgs.msg import LaserScan
from builtin_interfaces.msg import Time
from geometry_msgs.msg import TransformStamped
import transforms3d
try:
append_webots_python_lib_to_path()
from con... | 0.486088 | 0.193281 |
import calendar
import datetime
import re
from typing import Generator, List, Optional, Tuple, Union
RE_DATE_RANGE = re.compile('\[(?P<start>\d+):(?P<stop>\d+)(:(?P<step>\d+))?\]')
all_months = range(1, 13)
def is_yearmon(s: str) -> bool:
"""
Check if a string represents a valid date in YYYYMM format
"... | workflow/wsim_workflow/dates.py |
import calendar
import datetime
import re
from typing import Generator, List, Optional, Tuple, Union
RE_DATE_RANGE = re.compile('\[(?P<start>\d+):(?P<stop>\d+)(:(?P<step>\d+))?\]')
all_months = range(1, 13)
def is_yearmon(s: str) -> bool:
"""
Check if a string represents a valid date in YYYYMM format
"... | 0.858481 | 0.563798 |
from os import listdir,chdir
import warnings
import csv
from random import shuffle
import logging
import cv2
from PIL import Image
from torchvision import transforms
import torch
warnings.filterwarnings('ignore')
loader = transforms.Compose([transforms.ToTensor()])
unloader = transforms.ToPILImage()
def load_label(... | datahelper.py | from os import listdir,chdir
import warnings
import csv
from random import shuffle
import logging
import cv2
from PIL import Image
from torchvision import transforms
import torch
warnings.filterwarnings('ignore')
loader = transforms.Compose([transforms.ToTensor()])
unloader = transforms.ToPILImage()
def load_label(... | 0.697815 | 0.329338 |
import os
import shutil
import unittest
import tempfile
from bento.core \
import \
PackageDescription, PackageOptions
from bento.core.node \
import \
create_root_with_source_tree
from bento.commands.tests.utils \
import \
create_fake_package_from_bento_infos, prepare_configure
from ... | bento/commands/tests/test_recursive.py | import os
import shutil
import unittest
import tempfile
from bento.core \
import \
PackageDescription, PackageOptions
from bento.core.node \
import \
create_root_with_source_tree
from bento.commands.tests.utils \
import \
create_fake_package_from_bento_infos, prepare_configure
from ... | 0.271155 | 0.170646 |
import torch
from torch import nn
import math
class LanguageTransformer(nn.Module):
def __init__(self, vocab_size,
d_model, nhead,
num_encoder_layers, num_decoder_layers,
dim_feedforward, max_seq_length,
pos_dropout, trans_dropout):
super... | model/sequence/transformer.py | import torch
from torch import nn
import math
class LanguageTransformer(nn.Module):
def __init__(self, vocab_size,
d_model, nhead,
num_encoder_layers, num_decoder_layers,
dim_feedforward, max_seq_length,
pos_dropout, trans_dropout):
super... | 0.938927 | 0.361334 |
from keras.applications import InceptionV3
from keras.models import Model, load_model
from keras.layers import Input, Dropout, Dense, BatchNormalization
from keras.layers import GlobalAveragePooling2D, Concatenate
from keras.utils import to_categorical
import tensorflow as tf
import pandas as pd
import os
import numpy ... | model_generator.py | from keras.applications import InceptionV3
from keras.models import Model, load_model
from keras.layers import Input, Dropout, Dense, BatchNormalization
from keras.layers import GlobalAveragePooling2D, Concatenate
from keras.utils import to_categorical
import tensorflow as tf
import pandas as pd
import os
import numpy ... | 0.85814 | 0.393909 |
def selection_sort(array: list) -> int:
comparisons = 0
for i in range(len(array)):
min_index = i
for j in range(i, len(array)):
if array[min_index] < array[j]:
min_index = j
comparisons += 1
array[i], array[min_index] = array[min_index], array[i]
... | sorting_algorytms.py | def selection_sort(array: list) -> int:
comparisons = 0
for i in range(len(array)):
min_index = i
for j in range(i, len(array)):
if array[min_index] < array[j]:
min_index = j
comparisons += 1
array[i], array[min_index] = array[min_index], array[i]
... | 0.303629 | 0.594963 |
MARKDOWN = "markdown"
HTML = "html"
# List of supported documentation formats
SUPPORTED_DOC_FORMATS = [
MARKDOWN,
HTML,
]
class FileExtension:
"""The FileExtension class makes it possible to get the file extension
based on the format of the file.
"""
@classmethod
def get(cls, docFormat)... | rosautodoc/formatConverters.py | MARKDOWN = "markdown"
HTML = "html"
# List of supported documentation formats
SUPPORTED_DOC_FORMATS = [
MARKDOWN,
HTML,
]
class FileExtension:
"""The FileExtension class makes it possible to get the file extension
based on the format of the file.
"""
@classmethod
def get(cls, docFormat)... | 0.665519 | 0.303758 |
import os
import pytest
import sqlalchemy as sa
import pandas as pd
from pandas.testing import assert_frame_equal
import pemi
from pemi.fields import *
class TestPdDataSubject():
def test_it_creates_an_empty_dataframe(self):
dsubj = pemi.PdDataSubject(schema=pemi.Schema(
f1=StringField(),
... | tests/test_data_subject.py | import os
import pytest
import sqlalchemy as sa
import pandas as pd
from pandas.testing import assert_frame_equal
import pemi
from pemi.fields import *
class TestPdDataSubject():
def test_it_creates_an_empty_dataframe(self):
dsubj = pemi.PdDataSubject(schema=pemi.Schema(
f1=StringField(),
... | 0.358241 | 0.473414 |
from contextlib import closing
from dataclasses import dataclass, field
import hashlib
import os
from pathlib import Path
import re
import shutil
import socket
import subprocess
import sys
import textwrap
from threading import Thread
from time import sleep
import traceback
from typing import Any, Callable, Dict, List, ... | stickybeak/injector.py | from contextlib import closing
from dataclasses import dataclass, field
import hashlib
import os
from pathlib import Path
import re
import shutil
import socket
import subprocess
import sys
import textwrap
from threading import Thread
from time import sleep
import traceback
from typing import Any, Callable, Dict, List, ... | 0.548915 | 0.123339 |
import torch
import re
import os
import collections
from torch._six import string_classes, int_classes
import cv2
from opt import opt
from tqdm import tqdm
import time
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import math
import copy
from put_gif import put_gif
import stati... | fn.py | import torch
import re
import os
import collections
from torch._six import string_classes, int_classes
import cv2
from opt import opt
from tqdm import tqdm
import time
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
import math
import copy
from put_gif import put_gif
import stati... | 0.473414 | 0.225822 |
__author__ = 'Praveenkumar'
import os
import zmq
import sys
import time
import argparse
import thread
import json
from naoqi import ALProxy
from os.path import dirname
from os.path import abspath
dev = os.environ["INDRIYA_ROOT"]
dir1 = os.path.join(dev,"scripts","msgs")
sys.path.append(dir1)
import kinect_body_pb2... | src/indriya_robot_interface/KinectStateListener.py | __author__ = 'Praveenkumar'
import os
import zmq
import sys
import time
import argparse
import thread
import json
from naoqi import ALProxy
from os.path import dirname
from os.path import abspath
dev = os.environ["INDRIYA_ROOT"]
dir1 = os.path.join(dev,"scripts","msgs")
sys.path.append(dir1)
import kinect_body_pb2... | 0.086925 | 0.037999 |
import json
import requests
# 7
class Organization:
"""`Organization` is for handling activity for an organization.
This class handles registering a license, creating a user within an organization, and
logging in an organization.
https://dfxapiversion10.docs.apiary.io/#reference/0/organizations
... | dfxapiclient/organizations.py | import json
import requests
# 7
class Organization:
"""`Organization` is for handling activity for an organization.
This class handles registering a license, creating a user within an organization, and
logging in an organization.
https://dfxapiversion10.docs.apiary.io/#reference/0/organizations
... | 0.806891 | 0.438725 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.svm imp... | Project3_Classification_SQL/FootballPlayerRankingApp/footballPlayerRankingApp.py | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score
from sklearn.svm imp... | 0.464173 | 0.194999 |
import poplib
import sys
from importlib import reload
from email.parser import Parser
from email.parser import BytesParser
from email.header import decode_header
from email.utils import parseaddr
import email.iterators
def decode_str(s):
value, charset = decode_header(s)[0]
if charset:
value = value.de... | spider/common/pop.py | import poplib
import sys
from importlib import reload
from email.parser import Parser
from email.parser import BytesParser
from email.header import decode_header
from email.utils import parseaddr
import email.iterators
def decode_str(s):
value, charset = decode_header(s)[0]
if charset:
value = value.de... | 0.143698 | 0.078572 |
from rewpapi.common.http import Request
class RemoteListingResidential(Request):
def __init__(self, base_site, auth):
super(RemoteListingResidential, self).__init__(auth)
self._base_site = base_site
self._auth = auth
self._endpoint = base_site + "/api/listings/residential/"
de... | rewpapi/listings/listing.py | from rewpapi.common.http import Request
class RemoteListingResidential(Request):
def __init__(self, base_site, auth):
super(RemoteListingResidential, self).__init__(auth)
self._base_site = base_site
self._auth = auth
self._endpoint = base_site + "/api/listings/residential/"
de... | 0.545286 | 0.110807 |
from collections import namedtuple
import tensorflow as tf
import numpy as np
from mvc.action_output import ActionOutput
from mvc.models.networks.base_network import BaseNetwork
from mvc.models.networks.ddpg import initializer, build_target_update
from mvc.models.networks.ddpg import build_optim
from mvc.parametric_f... | mvc/models/networks/td3.py | from collections import namedtuple
import tensorflow as tf
import numpy as np
from mvc.action_output import ActionOutput
from mvc.models.networks.base_network import BaseNetwork
from mvc.models.networks.ddpg import initializer, build_target_update
from mvc.models.networks.ddpg import build_optim
from mvc.parametric_f... | 0.923605 | 0.444384 |
PupDB_FILENAME = "SVTB-DB.json_db"
PupDB_MRTkey = "MostRecentTweet"
PupDB_MRLkey = "MostRecentRiverLevel"
PupDB_MRFkey = "MostRecentForecastLevel"
PupDB_ACTIONkey = "CurrentFloodingActionLevel"
HIGHEST_TAG = "Highest Observation:"
LATEST_TAG = "Latest observed"
FORECAST_TAG = "Highest Forecast:"
OBSERVATION_TAGS = [... | RiverGuages.py | PupDB_FILENAME = "SVTB-DB.json_db"
PupDB_MRTkey = "MostRecentTweet"
PupDB_MRLkey = "MostRecentRiverLevel"
PupDB_MRFkey = "MostRecentForecastLevel"
PupDB_ACTIONkey = "CurrentFloodingActionLevel"
HIGHEST_TAG = "Highest Observation:"
LATEST_TAG = "Latest observed"
FORECAST_TAG = "Highest Forecast:"
OBSERVATION_TAGS = [... | 0.443118 | 0.109921 |
from __future__ import annotations
from typing import Any, Iterable, Optional, TYPE_CHECKING
if TYPE_CHECKING:
from .odm.basefield import Field
class Key:
def __init__(self, project: str, kind: str, namespace: Optional[str] = None, id: Optional[int] = None, name: Optional[str] = None) -> None:
self.... | datatypes.py | from __future__ import annotations
from typing import Any, Iterable, Optional, TYPE_CHECKING
if TYPE_CHECKING:
from .odm.basefield import Field
class Key:
def __init__(self, project: str, kind: str, namespace: Optional[str] = None, id: Optional[int] = None, name: Optional[str] = None) -> None:
self.... | 0.889433 | 0.121712 |
import numpy
import numpy.matlib
import style
import matplotlib.pyplot
WATER_DENSITY = 1000
GRAVITATIONAL_ACCELERATION = 9.8
class Beam:
'''
Get natural frequencies and shapes of modes
'''
def __init__(self, node_number, mass_ratio, top_tension,
length, diameter, bending_stiffness, h... | Beam.py | import numpy
import numpy.matlib
import style
import matplotlib.pyplot
WATER_DENSITY = 1000
GRAVITATIONAL_ACCELERATION = 9.8
class Beam:
'''
Get natural frequencies and shapes of modes
'''
def __init__(self, node_number, mass_ratio, top_tension,
length, diameter, bending_stiffness, h... | 0.811974 | 0.390127 |