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 time
import json
class TTLeague:
def __init__(self, setCount=3):
self.setCount = setCount
def __str__(self):
return str(self.__dict__)
class Match:
def __init__(self, player1, player2):
# type: (Player, Player) -> None
self.timestamp = int(time.time() * 1000)
... | TTLeague.py | import time
import json
class TTLeague:
def __init__(self, setCount=3):
self.setCount = setCount
def __str__(self):
return str(self.__dict__)
class Match:
def __init__(self, player1, player2):
# type: (Player, Player) -> None
self.timestamp = int(time.time() * 1000)
... | 0.323166 | 0.169097 |
import requests
import mwparserfromhell
import pywikibot
import setup_families
import re
import json
import os
import errno
def Import():
site = pywikibot.Site("eft:en")
questPage = pywikibot.Page(site, u"Quests")
questText = questPage.text
hideoutPage = pywikibot.Page(site, u"Hideou... | scanner.py |
import requests
import mwparserfromhell
import pywikibot
import setup_families
import re
import json
import os
import errno
def Import():
site = pywikibot.Site("eft:en")
questPage = pywikibot.Page(site, u"Quests")
questText = questPage.text
hideoutPage = pywikibot.Page(site, u"Hideou... | 0.067182 | 0.055772 |
from __future__ import absolute_import
from __future__ import division
from __future__ import generator_stop
from __future__ import print_function
import warnings
from abc import abstractmethod
import numpy as np
from tensorflow.keras.utils import Sequence
from erinn.preprocessing import add_noise
from e... | erinn/generator.py | from __future__ import absolute_import
from __future__ import division
from __future__ import generator_stop
from __future__ import print_function
import warnings
from abc import abstractmethod
import numpy as np
from tensorflow.keras.utils import Sequence
from erinn.preprocessing import add_noise
from e... | 0.786705 | 0.219045 |
from nipype.interfaces.base import (
TraitedSpec, traits, File, CommandLineInputSpec, CommandLine)
import os
import os.path as op
from nipype.interfaces.base import isdefined
# ants_reg_path = os.path.abspath(
# os.path.join(os.path.dirname(__file__), 'resources', 'bash',
# 'antsRegistrationSy... | banana/interfaces/ants.py | from nipype.interfaces.base import (
TraitedSpec, traits, File, CommandLineInputSpec, CommandLine)
import os
import os.path as op
from nipype.interfaces.base import isdefined
# ants_reg_path = os.path.abspath(
# os.path.join(os.path.dirname(__file__), 'resources', 'bash',
# 'antsRegistrationSy... | 0.519034 | 0.205177 |
import collections
import itertools
from blaze.action import Action, ActionSpace, Policy
from blaze.config.environment import Resource
from tests.mocks.config import get_push_groups
def get_action_space():
action_space = ActionSpace(get_push_groups())
action_space.seed(4096)
return action_space
class ... | tests/action/test_policy.py | import collections
import itertools
from blaze.action import Action, ActionSpace, Policy
from blaze.config.environment import Resource
from tests.mocks.config import get_push_groups
def get_action_space():
action_space = ActionSpace(get_push_groups())
action_space.seed(4096)
return action_space
class ... | 0.560734 | 0.44746 |
import json
import subprocess
import urllib.request
# Flintrock modules
from flintrock.exceptions import ClusterInvalidState
def test_describe_stopped_cluster(stopped_cluster):
p = subprocess.run([
'flintrock', 'describe', stopped_cluster],
stdout=subprocess.PIPE)
assert p.returncode == 0
... | tests/test_acceptance.py | import json
import subprocess
import urllib.request
# Flintrock modules
from flintrock.exceptions import ClusterInvalidState
def test_describe_stopped_cluster(stopped_cluster):
p = subprocess.run([
'flintrock', 'describe', stopped_cluster],
stdout=subprocess.PIPE)
assert p.returncode == 0
... | 0.348867 | 0.516595 |
import hypothesis.strategies as st
from hypothesis.stateful import (
Bundle,
consumes,
RuleBasedStateMachine,
rule,
multiple,
invariant,
)
from collision_tutorial import box, box_manager, base_algorithms
from .hypothesis_helpers import *
# We know that we'll get back collisions that should mat... | tests/test_manager.py | import hypothesis.strategies as st
from hypothesis.stateful import (
Bundle,
consumes,
RuleBasedStateMachine,
rule,
multiple,
invariant,
)
from collision_tutorial import box, box_manager, base_algorithms
from .hypothesis_helpers import *
# We know that we'll get back collisions that should mat... | 0.725551 | 0.526221 |
import os
def get_env(name, default=None):
return os.environ.get(name, default)
DEBUG = bool(get_env('DEBUG'))
# External URL for host (includes protocol)
BASE_HOST = get_env('BASE_HOST')
BASE_DOMAIN = get_env('BASE_DOMAIN')
BASE_USE_SSL = BASE_HOST.startswith('https://')
APPS_PATH = get_env('APPS_PATH', '/c... | gateway-manager/src/settings.py |
import os
def get_env(name, default=None):
return os.environ.get(name, default)
DEBUG = bool(get_env('DEBUG'))
# External URL for host (includes protocol)
BASE_HOST = get_env('BASE_HOST')
BASE_DOMAIN = get_env('BASE_DOMAIN')
BASE_USE_SSL = BASE_HOST.startswith('https://')
APPS_PATH = get_env('APPS_PATH', '/c... | 0.212518 | 0.030792 |
from difflib import SequenceMatcher
import inspect
import unittest
import sasoptpy as so
from sasoptpy.core.util import *
def match_ratio(a, b):
seq = SequenceMatcher(None, a, b)
return seq.ratio()
class TestUtil(unittest.TestCase):
"""
Unit tests for core utility functions
"""
@classmetho... | tests/core/test_util.py | from difflib import SequenceMatcher
import inspect
import unittest
import sasoptpy as so
from sasoptpy.core.util import *
def match_ratio(a, b):
seq = SequenceMatcher(None, a, b)
return seq.ratio()
class TestUtil(unittest.TestCase):
"""
Unit tests for core utility functions
"""
@classmetho... | 0.715821 | 0.646516 |
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.WGL import _types as _cs
# End users want this...
from OpenGL.raw.WGL._types import *
from OpenGL.raw.WGL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_EXTENSION_NAME = 'WGL_EXT_pixel_format'
def ... | OpenGLWrapper_JE/venv/Lib/site-packages/OpenGL/raw/WGL/EXT/pixel_format.py | from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.WGL import _types as _cs
# End users want this...
from OpenGL.raw.WGL._types import *
from OpenGL.raw.WGL import _errors
from OpenGL.constant import Constant as _C
import ctypes
_EXTENSION_NAME = 'WGL_EXT_pixel_format'
def ... | 0.299105 | 0.041269 |
import _thread
import docker
import os
import socket
from http.server import HTTPServer, SimpleHTTPRequestHandler
class TestFixtureServer(object):
def __init__(self):
self.port = 9999
self.ip = self.get_python_server_ip()
def get_python_server_ip(self):
# https://stackoverflow.com/a... | test_utils.py | import _thread
import docker
import os
import socket
from http.server import HTTPServer, SimpleHTTPRequestHandler
class TestFixtureServer(object):
def __init__(self):
self.port = 9999
self.ip = self.get_python_server_ip()
def get_python_server_ip(self):
# https://stackoverflow.com/a... | 0.379608 | 0.081556 |
from lets_plot.geo_data.gis.request import RegionQuery, MapRegion
from lets_plot.geo_data.gis.response import GeocodedFeature, GeoPoint, GeoRect, Namesake, NamesakeParent, AmbiguousFeature, Boundary
def assert_geocoded(expected: GeocodedFeature, actual: GeocodedFeature):
assert expected.query == actual.query
... | python-package/test/geo_data/gis/assertions.py |
from lets_plot.geo_data.gis.request import RegionQuery, MapRegion
from lets_plot.geo_data.gis.response import GeocodedFeature, GeoPoint, GeoRect, Namesake, NamesakeParent, AmbiguousFeature, Boundary
def assert_geocoded(expected: GeocodedFeature, actual: GeocodedFeature):
assert expected.query == actual.query
... | 0.865665 | 0.888807 |
import logging.handlers
import time
import mock
import pytest
from openvisualizer.motehandler.moteprobe.mockmoteprobe import MockMoteProbe
# ============================ logging =================================
LOGFILE_NAME = 'test_moteprobe.log'
log = logging.getLogger('test_moteprobe')
log.setLevel(logging.ERR... | tests/ov/test_moteprobe.py |
import logging.handlers
import time
import mock
import pytest
from openvisualizer.motehandler.moteprobe.mockmoteprobe import MockMoteProbe
# ============================ logging =================================
LOGFILE_NAME = 'test_moteprobe.log'
log = logging.getLogger('test_moteprobe')
log.setLevel(logging.ERR... | 0.328853 | 0.235746 |
from matplotlib import pyplot
from PIL import Image
from numpy import asarray
from scipy.spatial.distance import cosine
from mtcnn.mtcnn import MTCNN
from keras_vggface.vggface import VGGFace
from keras_vggface.utils import preprocess_input
import pandas as pd
col_names = ['Name','Faculty Number', 'Status']
#data-fram... | recognize.py | from matplotlib import pyplot
from PIL import Image
from numpy import asarray
from scipy.spatial.distance import cosine
from mtcnn.mtcnn import MTCNN
from keras_vggface.vggface import VGGFace
from keras_vggface.utils import preprocess_input
import pandas as pd
col_names = ['Name','Faculty Number', 'Status']
#data-fram... | 0.525612 | 0.375535 |
import requests, re, json, time
class watcher:
def twitterWatcher(self, user):
dicTweet = {}
if not user.startswith('http'):
urlAccount = "https://twitter.com/"+user
else:
urlAccount = user
req = requests.get(urlAccount)
page = req.text
if req.status_code == 200:
try:
tweets = re.fin... | Littlebrother/core/watcher.py | import requests, re, json, time
class watcher:
def twitterWatcher(self, user):
dicTweet = {}
if not user.startswith('http'):
urlAccount = "https://twitter.com/"+user
else:
urlAccount = user
req = requests.get(urlAccount)
page = req.text
if req.status_code == 200:
try:
tweets = re.fin... | 0.033337 | 0.123736 |
from monai.inferers import SimpleInferer
from monai.transforms import (
Activationsd,
AsDiscreted,
CenterSpatialCropd,
EnsureChannelFirstd,
LoadImaged,
NormalizeIntensityd,
Orientationd,
Spacingd,
ToNumpyd,
ToTensord,
)
from monailabel.interfaces.tasks.infer import InferTask, I... | sample-apps/segmentation_left_atrium/lib/infer.py |
from monai.inferers import SimpleInferer
from monai.transforms import (
Activationsd,
AsDiscreted,
CenterSpatialCropd,
EnsureChannelFirstd,
LoadImaged,
NormalizeIntensityd,
Orientationd,
Spacingd,
ToNumpyd,
ToTensord,
)
from monailabel.interfaces.tasks.infer import InferTask, I... | 0.820397 | 0.445168 |
import logging
from flask import Flask
from flask_wtf.csrf import CSRFProtect
import lmnop.portal.tools
from lmnop import __version__
from lmnop.portal.database import DatabaseClient
# maintains a database connection pool
db_client = DatabaseClient()
# implements csrf protection on the password form
csrf = CSRFProt... | portal/src/lmnop/portal/app.py | import logging
from flask import Flask
from flask_wtf.csrf import CSRFProtect
import lmnop.portal.tools
from lmnop import __version__
from lmnop.portal.database import DatabaseClient
# maintains a database connection pool
db_client = DatabaseClient()
# implements csrf protection on the password form
csrf = CSRFProt... | 0.471223 | 0.115836 |
import tensorflow as tf
from . import utils
batch_size = 50
input_size = utils.HEIGHT * utils.WIDTH * utils.NETWORK_DEPTH
# number of classes: 60 fruit classes + 1 resulted due to the build_image_data.py script that leaves the first class as a background class
num_classes = 75
# probability to keep the values after a ... | src/image_classification/network_structure/fruit_network.py | import tensorflow as tf
from . import utils
batch_size = 50
input_size = utils.HEIGHT * utils.WIDTH * utils.NETWORK_DEPTH
# number of classes: 60 fruit classes + 1 resulted due to the build_image_data.py script that leaves the first class as a background class
num_classes = 75
# probability to keep the values after a ... | 0.824921 | 0.594316 |
import sys
from tabulate import tabulate
from contextlib import contextmanager
from cpt import __version__ as version
class Printer(object):
def __init__(self, printer=None):
self.printer = printer or sys.stdout.write
def print_in_docker(self, container=None):
text = """
... | cpt/printer.py | import sys
from tabulate import tabulate
from contextlib import contextmanager
from cpt import __version__ as version
class Printer(object):
def __init__(self, printer=None):
self.printer = printer or sys.stdout.write
def print_in_docker(self, container=None):
text = """
... | 0.15511 | 0.075176 |
import pprint
import re # noqa: F401
import six
from jamf.configuration import Configuration
class ComputerGeneralUpdate(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
opena... | jamf/models/computer_general_update.py | import pprint
import re # noqa: F401
import six
from jamf.configuration import Configuration
class ComputerGeneralUpdate(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
opena... | 0.669637 | 0.10697 |
import jwt
import base64
import json
from unittest.mock import Mock, patch
from urllib.parse import urlparse
from stellar_sdk.keypair import Keypair
from stellar_sdk.exceptions import NotFoundError
from stellar_sdk.sep.ed25519_public_key_signer import Ed25519PublicKeySigner
from stellar_sdk.transaction_envelope import... | polaris/polaris/tests/auth_test.py | import jwt
import base64
import json
from unittest.mock import Mock, patch
from urllib.parse import urlparse
from stellar_sdk.keypair import Keypair
from stellar_sdk.exceptions import NotFoundError
from stellar_sdk.sep.ed25519_public_key_signer import Ed25519PublicKeySigner
from stellar_sdk.transaction_envelope import... | 0.721841 | 0.30562 |
import collections
import click
import evdev as evd
HP_ELAN_PEN = "ELAN2514:00 04F3:280E"
Device = collections.namedtuple('Device', ('id', 'name', 'evdev'))
@click.command()
@click.option('--list', 'select_from_list', is_flag=True, default=False, required=False,
help="List event devices and prompt for ... | gusbite/hps360/hps360pen.py | import collections
import click
import evdev as evd
HP_ELAN_PEN = "ELAN2514:00 04F3:280E"
Device = collections.namedtuple('Device', ('id', 'name', 'evdev'))
@click.command()
@click.option('--list', 'select_from_list', is_flag=True, default=False, required=False,
help="List event devices and prompt for ... | 0.362405 | 0.144541 |
from nonebot import on_command,CommandSession
from nonebot.permission import *
from aiocqhttp import MessageSegment
from Ganyu.service.bot_api import *
@on_command("store",aliases=("商店","买东西"),permission=EVERYBODY,only_to_me=False)
async def store(session:CommandSession):
un = session.event['user_id']
... | Hutao/plugins/life_game/store.py | from nonebot import on_command,CommandSession
from nonebot.permission import *
from aiocqhttp import MessageSegment
from Ganyu.service.bot_api import *
@on_command("store",aliases=("商店","买东西"),permission=EVERYBODY,only_to_me=False)
async def store(session:CommandSession):
un = session.event['user_id']
... | 0.182062 | 0.126246 |
import os
import sys
import unittest
import inirdr
TEST_PATH, _ = os.path.split(os.path.abspath(__file__))
class ConfigTests(unittest.TestCase):
"""Verifies loading of config1.ini
"""
def setUp(self):
"""Load for comparison in individual tests
"""
with open(TEST_PATH... | tests/__init__.py | import os
import sys
import unittest
import inirdr
TEST_PATH, _ = os.path.split(os.path.abspath(__file__))
class ConfigTests(unittest.TestCase):
"""Verifies loading of config1.ini
"""
def setUp(self):
"""Load for comparison in individual tests
"""
with open(TEST_PATH... | 0.331769 | 0.425187 |
from bs4 import BeautifulSoup as bs
from splinter import Browser
from webdriver_manager.chrome import ChromeDriverManager
import pandas as pd
def scrape_all():
# excutable path
executable_path = {"executable_path": ChromeDriverManager().install()}
browser = Browser('chrome', **executable_path, headless=Fa... | Missions_to_Mars/app/scrape_mars.py | from bs4 import BeautifulSoup as bs
from splinter import Browser
from webdriver_manager.chrome import ChromeDriverManager
import pandas as pd
def scrape_all():
# excutable path
executable_path = {"executable_path": ChromeDriverManager().install()}
browser = Browser('chrome', **executable_path, headless=Fa... | 0.396652 | 0.151467 |
__author__ = '<NAME>, <NAME>'
import ast
from pyon.public import BadRequest, IonObject, log
from interface import objects
def get_typed_value(value, schema_entry=None, targettype=None, strict=False):
"""
Performs a value type check or conversion according to a schema entry or specified target type.
Sup... | src/ion/util/parse_utils.py | __author__ = '<NAME>, <NAME>'
import ast
from pyon.public import BadRequest, IonObject, log
from interface import objects
def get_typed_value(value, schema_entry=None, targettype=None, strict=False):
"""
Performs a value type check or conversion according to a schema entry or specified target type.
Sup... | 0.642208 | 0.249036 |
import argparse
from pathlib import Path
def get_parser():
parser = argparse.ArgumentParser("demucs", description="Train and evaluate Conv TasNet.")
parser.add_argument(
"--raw",
type=Path,
help="Path to raw audio, can be faster, see python3 -m demucs.raw to extract.",
default... | demucs/parser.py |
import argparse
from pathlib import Path
def get_parser():
parser = argparse.ArgumentParser("demucs", description="Train and evaluate Conv TasNet.")
parser.add_argument(
"--raw",
type=Path,
help="Path to raw audio, can be faster, see python3 -m demucs.raw to extract.",
default... | 0.709422 | 0.113187 |
import shlex
from enum import Enum
from pathlib import Path
from typing import Union, Sequence, Optional, List, Callable, Any, cast, TYPE_CHECKING
from tests.ext_subprocess import get_text_input_from_data
if TYPE_CHECKING:
from tests.fixtures.cli import FlexlateFixture
from _pytest.capture import CaptureFixture
... | tests/integration/cli_stub.py | import shlex
from enum import Enum
from pathlib import Path
from typing import Union, Sequence, Optional, List, Callable, Any, cast, TYPE_CHECKING
from tests.ext_subprocess import get_text_input_from_data
if TYPE_CHECKING:
from tests.fixtures.cli import FlexlateFixture
from _pytest.capture import CaptureFixture
... | 0.77768 | 0.130424 |
import json
import logging
import re
import time
from argparse import ArgumentParser
from datetime import date
from getpass import getpass
from bs4 import BeautifulSoup
from requests import Response
from requests import Session
from .data import HOST
from .data.js_equality import chkpwd
from .data.route import Parsed... | cli_cqu/__init__.py | import json
import logging
import re
import time
from argparse import ArgumentParser
from datetime import date
from getpass import getpass
from bs4 import BeautifulSoup
from requests import Response
from requests import Session
from .data import HOST
from .data.js_equality import chkpwd
from .data.route import Parsed... | 0.239172 | 0.082512 |
import click, os, sys
from baseq.snv import cli
from baseq.snv.qc.cmd import *
@cli.command(short_help="Check the enrichment quality, input: bam, interval and outpath")
@click.argument("bampath")
@click.argument("interval")
@click.argument("outpath")
def enrich_saturation(bampath, interval, outpath):
pass
@cli.co... | baseq/snv/cmd.py | import click, os, sys
from baseq.snv import cli
from baseq.snv.qc.cmd import *
@cli.command(short_help="Check the enrichment quality, input: bam, interval and outpath")
@click.argument("bampath")
@click.argument("interval")
@click.argument("outpath")
def enrich_saturation(bampath, interval, outpath):
pass
@cli.co... | 0.257578 | 0.066509 |
import json
from copy import (deepcopy)
from datetime import timedelta
from pyfiles.common_helpers import (geoLoc_to_pointRow, geoJSON_to_pointRow,
OTPTimeStampToNormalDateTime, OTPDurationToNormalDuration,
shift_time_to_specific_date)
from pyfi... | pyfiles/common/trip.py | import json
from copy import (deepcopy)
from datetime import timedelta
from pyfiles.common_helpers import (geoLoc_to_pointRow, geoJSON_to_pointRow,
OTPTimeStampToNormalDateTime, OTPDurationToNormalDuration,
shift_time_to_specific_date)
from pyfi... | 0.221182 | 0.231842 |
import errno
import logging
import pprint
import signal
import sys
import time
import weakref
import psutil
from saltfactories.exceptions import ProcessNotStarted
from saltfactories.utils import ports
log = logging.getLogger(__name__)
def collect_child_processes(pid):
"""
Try to collect any started child ... | saltfactories/utils/processes/helpers.py | import errno
import logging
import pprint
import signal
import sys
import time
import weakref
import psutil
from saltfactories.exceptions import ProcessNotStarted
from saltfactories.utils import ports
log = logging.getLogger(__name__)
def collect_child_processes(pid):
"""
Try to collect any started child ... | 0.249905 | 0.092647 |
import itertools
import datetime
import pickle
import os
import logging
import numpy as np
from numpy.lib import recfunctions
import pandas as pd
from src.util import CONSTANT_NINF, get_dir_path
from src.environment import Environment
class Agent:
"""
Reinforcement Learning Agent Class for learning the poli... | src/agent.py | import itertools
import datetime
import pickle
import os
import logging
import numpy as np
from numpy.lib import recfunctions
import pandas as pd
from src.util import CONSTANT_NINF, get_dir_path
from src.environment import Environment
class Agent:
"""
Reinforcement Learning Agent Class for learning the poli... | 0.684475 | 0.382314 |
from django.conf.urls import url, include
from . import views
from .forms import PytitionUserCreationForm
from .views import PetitionCreationWizard
from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<petition_i... | pytition/petition/urls.py | from django.conf.urls import url, include
from . import views
from .forms import PytitionUserCreationForm
from .views import PetitionCreationWizard
from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^(?P<petition_i... | 0.242744 | 0.099777 |
import SCRAM
from os.path import exists, join, dirname, isdir
from os import environ, makedirs, execv
from sys import argv
def create_productstores(area):
from SCRAM.BuildSystem.BuildFile import BuildFile
sym = None
if area.symlinks() > 0:
from SCRAM.Core.ProdSymLinks import ProdSymLinks
s... | SCRAM/Core/Utils.py | import SCRAM
from os.path import exists, join, dirname, isdir
from os import environ, makedirs, execv
from sys import argv
def create_productstores(area):
from SCRAM.BuildSystem.BuildFile import BuildFile
sym = None
if area.symlinks() > 0:
from SCRAM.Core.ProdSymLinks import ProdSymLinks
s... | 0.100569 | 0.099996 |
import unittest
from unittest.mock import patch
import numpy as np
from auv_cal.plane_fitting import Plane
fit_points = np.array(
[
[-1.35292, -6.46749, 12.57575],
[-1.34562, -5.09195, 11.92035],
[-1.46393, 4.62872, 8.63609],
[-1.46479, -4.10360, 7.33406],
[-1.45952, 2.291... | auv_cal/tests/test_plane_fitting.py | import unittest
from unittest.mock import patch
import numpy as np
from auv_cal.plane_fitting import Plane
fit_points = np.array(
[
[-1.35292, -6.46749, 12.57575],
[-1.34562, -5.09195, 11.92035],
[-1.46393, 4.62872, 8.63609],
[-1.46479, -4.10360, 7.33406],
[-1.45952, 2.291... | 0.530966 | 0.609495 |
import unittest
class SwapArray:
""" A sequence of elements that can only be modified by swapping one element
with the successive one.
"""
def __init__(self, python_list):
""" Initializes the SwapArray with the elements found in python_list. """
self._arr = python_li... | past-exams/2017-01-26/solutions/exercise1_solution.py | import unittest
class SwapArray:
""" A sequence of elements that can only be modified by swapping one element
with the successive one.
"""
def __init__(self, python_list):
""" Initializes the SwapArray with the elements found in python_list. """
self._arr = python_li... | 0.652795 | 0.590336 |
from ..tdagent import TDAgent
import numpy as np
class PAMR(TDAgent):
""" Passive aggressive mean reversion strategy for portfolio selection.
There are three variants with different parameters, see original article
for details.
Reference:
<NAME>, <NAME>, <NAME>, and <NAME>.
Pamr: Pass... | better/tdagent/algorithms/pamr.py | from ..tdagent import TDAgent
import numpy as np
class PAMR(TDAgent):
""" Passive aggressive mean reversion strategy for portfolio selection.
There are three variants with different parameters, see original article
for details.
Reference:
<NAME>, <NAME>, <NAME>, and <NAME>.
Pamr: Pass... | 0.63273 | 0.496765 |
import torch
from torch import nn
import torch.nn.functional as F
from .egt_layers import EGT_Layer, Graph
class EGT_Base(nn.Module):
def __init__(self,
node_width = 128 ,
edge_width = 32 ,
num_heads = 8 ,
... | lib/models/egt.py | import torch
from torch import nn
import torch.nn.functional as F
from .egt_layers import EGT_Layer, Graph
class EGT_Base(nn.Module):
def __init__(self,
node_width = 128 ,
edge_width = 32 ,
num_heads = 8 ,
... | 0.86859 | 0.159185 |
import os
import pytest
import json
import arrow
from pprint import pprint # noqa: F401
from django.core import mail
from django.conf import settings
from web.models import Resource, ResourceImage
@pytest.mark.client
@pytest.mark.django_db
def test_submission_event_online(rf, client, db, normal_user):
with op... | web/tests/test_api.py | import os
import pytest
import json
import arrow
from pprint import pprint # noqa: F401
from django.core import mail
from django.conf import settings
from web.models import Resource, ResourceImage
@pytest.mark.client
@pytest.mark.django_db
def test_submission_event_online(rf, client, db, normal_user):
with op... | 0.341253 | 0.290691 |
import logging
from js9 import j
from JumpScale9.logging.Handlers import TelegramFormatter, TelegramHandler
from zerorobot.robot import Robot
telegram_logger = logging.getLogger('telegram_logger')
telegram_logger.disabled = True
TEMPLATE = """
listen = ":6600"
data_repo = ""
template_repo = [""]
config_repo = ""
c... | JumpScale9Zrobot/servers/zerorobot/ZeroRobotServer.py | import logging
from js9 import j
from JumpScale9.logging.Handlers import TelegramFormatter, TelegramHandler
from zerorobot.robot import Robot
telegram_logger = logging.getLogger('telegram_logger')
telegram_logger.disabled = True
TEMPLATE = """
listen = ":6600"
data_repo = ""
template_repo = [""]
config_repo = ""
c... | 0.572364 | 0.116966 |
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime
import tensorflow as tf
from src.utils import DenseBlock
class MyoPINN(tf.keras.Model):
def __init__(
self,
N,
layers,
layer_width,
lr,
loss_weights=(1, 1, 0, 0, 0, 0),
... | src/models/pinns/inference_model.py | import matplotlib.pyplot as plt
import numpy as np
import time
import datetime
import tensorflow as tf
from src.utils import DenseBlock
class MyoPINN(tf.keras.Model):
def __init__(
self,
N,
layers,
layer_width,
lr,
loss_weights=(1, 1, 0, 0, 0, 0),
... | 0.748168 | 0.410106 |
from __future__ import division, print_function, absolute_import
import fnmatch
import os
import shutil
import sys
import unittest
import numpy as np
import tensorflow as tf
from nnef_tools import convert
from nnef_tools.activation_export import activation_test
from nnef_tools.activation_export.tensorflow import tf... | nnef_tests/conversion/tf_py_test_runner.py |
from __future__ import division, print_function, absolute_import
import fnmatch
import os
import shutil
import sys
import unittest
import numpy as np
import tensorflow as tf
from nnef_tools import convert
from nnef_tools.activation_export import activation_test
from nnef_tools.activation_export.tensorflow import tf... | 0.486332 | 0.169337 |
import numpy as np
from .dt import DecisionTree
def bootstrap_sample(X, Y):
N, M = X.shape
idxs = np.random.choice(N, N, replace=True)
return X[idxs], Y[idxs]
class RandomForest:
def __init__(
self, n_trees, max_depth, n_feats, classifier=True, criterion="entropy"
):
"""
... | book-code/numpy-ml/numpy_ml/trees/rf.py | import numpy as np
from .dt import DecisionTree
def bootstrap_sample(X, Y):
N, M = X.shape
idxs = np.random.choice(N, N, replace=True)
return X[idxs], Y[idxs]
class RandomForest:
def __init__(
self, n_trees, max_depth, n_feats, classifier=True, criterion="entropy"
):
"""
... | 0.941 | 0.630457 |
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
import accounts.views
from accounts.views import *
from checkout.views import CheckoutAjaxView, RequestsAjaxView
from dashboard.views import DashboardView
from rest_fra... | frontend/src/digitalmarket/urls.py | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
import accounts.views
from accounts.views import *
from checkout.views import CheckoutAjaxView, RequestsAjaxView
from dashboard.views import DashboardView
from rest_fra... | 0.292494 | 0.082365 |
from plantseg.dataprocessing.dataprocessing import DataPostProcessing3D
from plantseg.dataprocessing.dataprocessing import DataPreProcessing3D
from plantseg.pipeline import gui_logger
from plantseg.pipeline.utils import load_paths
from plantseg.predictions.predict import UnetPredictions
from plantseg.predictions.utils ... | plantseg/pipeline/raw2seg.py | from plantseg.dataprocessing.dataprocessing import DataPostProcessing3D
from plantseg.dataprocessing.dataprocessing import DataPreProcessing3D
from plantseg.pipeline import gui_logger
from plantseg.pipeline.utils import load_paths
from plantseg.predictions.predict import UnetPredictions
from plantseg.predictions.utils ... | 0.60054 | 0.222426 |
from argparse import ArgumentParser
from os import path
from re import fullmatch
from math import sqrt
from random import randint
import numpy as np
from detail.load import load
from detail.dump import dump
def transpose(matrix):
return list(map(list, [*zip(*matrix)]))
def relabel(matrix):
replacements =... | generate.py | from argparse import ArgumentParser
from os import path
from re import fullmatch
from math import sqrt
from random import randint
import numpy as np
from detail.load import load
from detail.dump import dump
def transpose(matrix):
return list(map(list, [*zip(*matrix)]))
def relabel(matrix):
replacements =... | 0.494385 | 0.32461 |
def push_up (grid):
"""merge grid values upwards"""
#push up
for i in range(3):
for row in range(len(grid)):
for column in range(len(grid[row])):
if grid[row-1][column] == 0 and row > 0:
grid[row-1][column] = grid[row][column]
grid... | push.py |
def push_up (grid):
"""merge grid values upwards"""
#push up
for i in range(3):
for row in range(len(grid)):
for column in range(len(grid[row])):
if grid[row-1][column] == 0 and row > 0:
grid[row-1][column] = grid[row][column]
grid... | 0.17427 | 0.485234 |
from GoogleNews import GoogleNews
import pandas as pd
import datetime as dt
from newspaper import Article
from newspaper import Config
def Extraction(name):
today = dt.date.today()
today = today.strftime('%m-%d-%Y')
yesterday = dt.date.today() - dt.timedelta(days=1)
yesterday = yesterday.strftime('%m-... | NewsExtraction.py | from GoogleNews import GoogleNews
import pandas as pd
import datetime as dt
from newspaper import Article
from newspaper import Config
def Extraction(name):
today = dt.date.today()
today = today.strftime('%m-%d-%Y')
yesterday = dt.date.today() - dt.timedelta(days=1)
yesterday = yesterday.strftime('%m-... | 0.174797 | 0.121973 |
import _thread
import asyncio
import json
import falcon
import os
from wsgiref.simple_server import make_server
from pathlib import Path
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from falcon_apispec import FalconPlugin
from mitmproxy.addons.browserup.har.har_schemas import Matc... | mitmproxy/addons/browserup/browserup_addons_manager.py | import _thread
import asyncio
import json
import falcon
import os
from wsgiref.simple_server import make_server
from pathlib import Path
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from falcon_apispec import FalconPlugin
from mitmproxy.addons.browserup.har.har_schemas import Matc... | 0.365117 | 0.112162 |
from federatedml.param.boosting_param import DecisionTreeParam
from federatedml.ensemble.basic_algorithms import HeteroFastDecisionTreeGuest, HeteroFastDecisionTreeHost, \
HeteroDecisionTreeGuest, HeteroDecisionTreeHost
from federatedml.util import consts
def produce_hetero_tree_learner(role, tree_param: Decision... | python/federatedml/ensemble/secureboost/secureboost_util/tree_model_io.py | from federatedml.param.boosting_param import DecisionTreeParam
from federatedml.ensemble.basic_algorithms import HeteroFastDecisionTreeGuest, HeteroFastDecisionTreeHost, \
HeteroDecisionTreeGuest, HeteroDecisionTreeHost
from federatedml.util import consts
def produce_hetero_tree_learner(role, tree_param: Decision... | 0.536556 | 0.101145 |
from django.apps import apps
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.contrib.auth.management import create_permissions
try:
# Django < 1.11
from django.contrib.contenttypes.management import update_contenttypes as create_contenttypes
except I... | codenerix/management/commands/refresh_permissions.py |
from django.apps import apps
from django.core.management.base import BaseCommand
from django.contrib.auth.models import User
from django.contrib.auth.management import create_permissions
try:
# Django < 1.11
from django.contrib.contenttypes.management import update_contenttypes as create_contenttypes
except I... | 0.434941 | 0.066509 |
import unittest
import os
from dao.unverified_reminder_messages_dao import UnverifiedReminderMessagesDAO
class TestUnverifiedReminderMessagesDAO(unittest.TestCase):
def setUp(self):
self.db_addr = "database/test_db.db"
os.popen(f"sqlite3 {self.db_addr} < database/schema.sql")
self.unverifie... | src/tests/dao_test/unverified_reminder_messages_dao_test.py | import unittest
import os
from dao.unverified_reminder_messages_dao import UnverifiedReminderMessagesDAO
class TestUnverifiedReminderMessagesDAO(unittest.TestCase):
def setUp(self):
self.db_addr = "database/test_db.db"
os.popen(f"sqlite3 {self.db_addr} < database/schema.sql")
self.unverifie... | 0.361165 | 0.128799 |
import os
import sys
sys.path.append(os.getcwd())
import torch
import torch.nn.functional as F
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
from workspace.workspace_cls import SENT_WORDID, SENT_LABELID, SENT_WORD_MASK, SENT_ORIGINAL_TXT
import numpy
import random
from torch.uti... | src/experiment_oproto_sentiment.py | import os
import sys
sys.path.append(os.getcwd())
import torch
import torch.nn.functional as F
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
from workspace.workspace_cls import SENT_WORDID, SENT_LABELID, SENT_WORD_MASK, SENT_ORIGINAL_TXT
import numpy
import random
from torch.uti... | 0.427158 | 0.271472 |
from itertools import izip_longest
ERROR_COUNT = -1
class PaginationHelper:
def __init__(self, collection, items_per_page):
self.collection = collection
self.items_per_page = items_per_page
def grouper(self, fillvalue=None):
# see 'grouper' in https://docs.python.org/2/library/iterto... | PaginationHelper.py | from itertools import izip_longest
ERROR_COUNT = -1
class PaginationHelper:
def __init__(self, collection, items_per_page):
self.collection = collection
self.items_per_page = items_per_page
def grouper(self, fillvalue=None):
# see 'grouper' in https://docs.python.org/2/library/iterto... | 0.538983 | 0.385259 |
import copy
import datetime
import munch
from shade import exc
from shade.tests import fakes
from shade.tests.unit import base
class TestFloatingIP(base.RequestsMockTestCase):
mock_floating_ip_list_rep = {
'floatingips': [
{
'router_id': 'd23abc8d-2991-4a55-ba98-2aaea84cc72f',... | shade/tests/unit/test_floating_ip_neutron.py | import copy
import datetime
import munch
from shade import exc
from shade.tests import fakes
from shade.tests.unit import base
class TestFloatingIP(base.RequestsMockTestCase):
mock_floating_ip_list_rep = {
'floatingips': [
{
'router_id': 'd23abc8d-2991-4a55-ba98-2aaea84cc72f',... | 0.507324 | 0.192463 |
import argparse
import os
import torch
class AbsPoseConfig:
def __init__(self):
description = 'Absolute Pose Regression'
parser = argparse.ArgumentParser(description=description)
self.parser = parser
# Add different groups for arguments
prog_group = parser.add_ar... | utils/common/config_parser.py | import argparse
import os
import torch
class AbsPoseConfig:
def __init__(self):
description = 'Absolute Pose Regression'
parser = argparse.ArgumentParser(description=description)
self.parser = parser
# Add different groups for arguments
prog_group = parser.add_ar... | 0.561936 | 0.147432 |
import collections
import logging
import os
import re
from guild import util
log = logging.getLogger("guild")
class OpRefError(ValueError):
pass
OpRef = collections.namedtuple(
"OpRef", ["pkg_type", "pkg_name", "pkg_version", "model_name", "op_name"]
)
def _opref_for_op(op_name, model_ref):
(pkg_ty... | guild/opref.py |
import collections
import logging
import os
import re
from guild import util
log = logging.getLogger("guild")
class OpRefError(ValueError):
pass
OpRef = collections.namedtuple(
"OpRef", ["pkg_type", "pkg_name", "pkg_version", "model_name", "op_name"]
)
def _opref_for_op(op_name, model_ref):
(pkg_ty... | 0.331444 | 0.35056 |
import pickle as pk
from sklearn.preprocessing import MinMaxScaler
from pandas import read_csv
from config import *
class DataReader:
def __init__(self):
self.google_trace_config = Config.GOOGLE_TRACE_DATA_CONFIG
self.normal_data_file = PROJECT_DIR + '/data/input_data/{}/normalized_data.pkl'.for... | lib/preprocess/read_data.py | import pickle as pk
from sklearn.preprocessing import MinMaxScaler
from pandas import read_csv
from config import *
class DataReader:
def __init__(self):
self.google_trace_config = Config.GOOGLE_TRACE_DATA_CONFIG
self.normal_data_file = PROJECT_DIR + '/data/input_data/{}/normalized_data.pkl'.for... | 0.299208 | 0.192369 |
import inspect
import logging
import pkgutil
from django.db.utils import ProgrammingError
from django.core.exceptions import ObjectDoesNotExist
from tethys_apps.base import TethysAppBase, TethysExtensionBase
from tethys_apps.base.testing.environment import is_testing_environment
tethys_log = logging.getLogger('tethys... | tethys_apps/harvester.py | import inspect
import logging
import pkgutil
from django.db.utils import ProgrammingError
from django.core.exceptions import ObjectDoesNotExist
from tethys_apps.base import TethysAppBase, TethysExtensionBase
from tethys_apps.base.testing.environment import is_testing_environment
tethys_log = logging.getLogger('tethys... | 0.497315 | 0.072933 |
from typing import Pattern, Dict
from recognizers_text.utilities import RegExpUtility
from recognizers_number.number.extractors import BaseNumberExtractor
from recognizers_number.number.parsers import BaseNumberParser
from recognizers_number.number.portuguese.extractors import PortugueseCardinalExtractor
from recogni... | Python/libraries/recognizers-date-time/recognizers_date_time/date_time/portuguese/duration_parser_config.py |
from typing import Pattern, Dict
from recognizers_text.utilities import RegExpUtility
from recognizers_number.number.extractors import BaseNumberExtractor
from recognizers_number.number.parsers import BaseNumberParser
from recognizers_number.number.portuguese.extractors import PortugueseCardinalExtractor
from recogni... | 0.898026 | 0.246375 |
import os.path
from pystache.loader import Loader
# TODO: add test cases for this class.
class SpecLoader(object):
"""
Supports loading custom-specified templates (from TemplateSpec instances).
"""
def __init__(self, loader=None):
if loader is None:
loader = Loader()
s... | external_tools/pystache/specloader.py | import os.path
from pystache.loader import Loader
# TODO: add test cases for this class.
class SpecLoader(object):
"""
Supports loading custom-specified templates (from TemplateSpec instances).
"""
def __init__(self, loader=None):
if loader is None:
loader = Loader()
s... | 0.476336 | 0.206294 |
from .utils import *
from .organizer import *
def grid4_h(ax, base_name, coarse_grain_type,
mc='k',
plot_kw={'ylim':(1e-4,2e2)},
show_fit=False,
show_detail=True,
iprint=False):
"""
Parameters
----------
ax : list of plt.Axes
base_name :... | pyutils/plot.py | from .utils import *
from .organizer import *
def grid4_h(ax, base_name, coarse_grain_type,
mc='k',
plot_kw={'ylim':(1e-4,2e2)},
show_fit=False,
show_detail=True,
iprint=False):
"""
Parameters
----------
ax : list of plt.Axes
base_name :... | 0.318061 | 0.397061 |
import sys
from game.settings import *
from game import color as clr
__author__ = 'bengt'
class Piece(object):
"""Pieces are laid out on the board on an 8x8 grid."""
def __init__(self, x, y, colour):
self.x = x
self.y = y
self.state = 'BOARD'
self.flipped = False
self... | game/piece.py | import sys
from game.settings import *
from game import color as clr
__author__ = 'bengt'
class Piece(object):
"""Pieces are laid out on the board on an 8x8 grid."""
def __init__(self, x, y, colour):
self.x = x
self.y = y
self.state = 'BOARD'
self.flipped = False
self... | 0.528047 | 0.31093 |
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import urlfetch
from django.utils import simplejson as json
base = 'https://github.com/login/oauth/access_token'
client_id = '?client_id='
redirect_url = '&redirect_uri=https://githubanywhere.appspot.com/cal... | appengine/main.py |
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
from google.appengine.api import urlfetch
from django.utils import simplejson as json
base = 'https://github.com/login/oauth/access_token'
client_id = '?client_id='
redirect_url = '&redirect_uri=https://githubanywhere.appspot.com/cal... | 0.300438 | 0.039048 |
from .utils import inverse as _inverse, my_pow as _my_pow, is_prime_miller as _is_prime_miller, ex_crt as _ex_crt
from random import randint as _randint
def get_prime(bit_length = 2048, strong = False):
while True:
x = _randint(2 ** (bit_length - 1) + 1, 2 ** bit_length - 1)
x += 1 - (x & 1)
if _is_prime_miller... | CNSPP/RSA.py | from .utils import inverse as _inverse, my_pow as _my_pow, is_prime_miller as _is_prime_miller, ex_crt as _ex_crt
from random import randint as _randint
def get_prime(bit_length = 2048, strong = False):
while True:
x = _randint(2 ** (bit_length - 1) + 1, 2 ** bit_length - 1)
x += 1 - (x & 1)
if _is_prime_miller... | 0.113924 | 0.281404 |
ISO_693_3 = {
'ara': 'Arabic',
'eng': 'English',
'jpn': 'Japanese',
'fra': 'French',
'deu': 'German',
'spa': 'Spanish',
'ita': 'Italian',
'vie': 'Vietnamese',
'rus': 'Russian',
'cmn': 'Mandarin Chinese',
'kor': 'Korean',
'nld': 'Dutch',
'heb': 'Hebrew',
'ind': 'In... | scripts/populate_db/populate_db/iso693_3.py | ISO_693_3 = {
'ara': 'Arabic',
'eng': 'English',
'jpn': 'Japanese',
'fra': 'French',
'deu': 'German',
'spa': 'Spanish',
'ita': 'Italian',
'vie': 'Vietnamese',
'rus': 'Russian',
'cmn': 'Mandarin Chinese',
'kor': 'Korean',
'nld': 'Dutch',
'heb': 'Hebrew',
'ind': 'In... | 0.289271 | 0.377971 |
import os
import sys
import pandas as pd
from pyts.image import MarkovTransitionField, GramianAngularField
from multiprocessing import Pool, cpu_count
from image_concat import concat_images
def extract_period(df, column, index, period=10, reversed=True):
"""Extracts a period of data from the dataframe column at t... | lib/image_creation.py | import os
import sys
import pandas as pd
from pyts.image import MarkovTransitionField, GramianAngularField
from multiprocessing import Pool, cpu_count
from image_concat import concat_images
def extract_period(df, column, index, period=10, reversed=True):
"""Extracts a period of data from the dataframe column at t... | 0.451327 | 0.490785 |
from inspect import signature, Signature
# Note: A better version of this lives now on lined, an otosense repo and pip installable package
class Compose:
def __init__(self, *funcs):
"""Performs function composition.
That is, get a callable that is equivalent to a chain of callables.
For exa... | gist/compose_functions.py | from inspect import signature, Signature
# Note: A better version of this lives now on lined, an otosense repo and pip installable package
class Compose:
def __init__(self, *funcs):
"""Performs function composition.
That is, get a callable that is equivalent to a chain of callables.
For exa... | 0.916086 | 0.881207 |
import datetime
import json
import os
import sys
import time
from PIL import Image, ImageDraw, ImageFont
from requests import get
from waveshare_epd import epd1in54_V2 # Update this if needed for a different e-paper screen.
'''
Script to retrieve the number of confirmed Covid-19 cases in the past 7 day
in a local aut... | src/display_cases.py | import datetime
import json
import os
import sys
import time
from PIL import Image, ImageDraw, ImageFont
from requests import get
from waveshare_epd import epd1in54_V2 # Update this if needed for a different e-paper screen.
'''
Script to retrieve the number of confirmed Covid-19 cases in the past 7 day
in a local aut... | 0.332094 | 0.285683 |
import ujson as json
import os
import threading
import numpy as np
from .hammingdb import HammingDb
from zounds.persistence import TimeSliceEncoder, TimeSliceDecoder
from zounds.timeseries import ConstantRateTimeSeries
from zounds.timeseries import TimeSlice
class SearchResults(object):
def __init__(self, query, ... | zounds/index/index.py | import ujson as json
import os
import threading
import numpy as np
from .hammingdb import HammingDb
from zounds.persistence import TimeSliceEncoder, TimeSliceDecoder
from zounds.timeseries import ConstantRateTimeSeries
from zounds.timeseries import TimeSlice
class SearchResults(object):
def __init__(self, query, ... | 0.513668 | 0.162945 |
import random
import constants
from constants import WEAPON_TIER_SELECTION
from ecs.components.criticals.abc import CriticalComponent
from ecs.components.criticals.cleave import CleaveComponent
from ecs.components.criticals.execute import ExecuteComponent
from ecs.components.criticals.extradamage import ExtraDamageCom... | src/factories/weapon.py | import random
import constants
from constants import WEAPON_TIER_SELECTION
from ecs.components.criticals.abc import CriticalComponent
from ecs.components.criticals.cleave import CleaveComponent
from ecs.components.criticals.execute import ExecuteComponent
from ecs.components.criticals.extradamage import ExtraDamageCom... | 0.432782 | 0.173866 |
import dolfin as dl
import numpy as np
from datetime import datetime
from seird_problem import seird_fwd_problem
from seird_initial_with_recovered import generate_initial_condition
import os
import argparse
import sys
import timeit
STATE = 0
PARAMETER = 1
if __name__ == "__main__":
parser = argparse.ArgumentPar... | Model/seird/run_prediction_qoi_11August2020.py | import dolfin as dl
import numpy as np
from datetime import datetime
from seird_problem import seird_fwd_problem
from seird_initial_with_recovered import generate_initial_condition
import os
import argparse
import sys
import timeit
STATE = 0
PARAMETER = 1
if __name__ == "__main__":
parser = argparse.ArgumentPar... | 0.332094 | 0.189859 |
import math
from PyQt5 import QtGui, QtCore, QtWidgets, uic
from PyQt5.QtGui import QFont
import qdarkstyle # This awesome style sheet was made by <NAME> and <NAME> - https://github.com/ColinDuquesnoy/QDarkStyleSheet
from collections import OrderedDict
import os
import pyqtgraph as pg
import guiMapper
import guiSeque... | Software/GUI_code/mainWindow.py | import math
from PyQt5 import QtGui, QtCore, QtWidgets, uic
from PyQt5.QtGui import QFont
import qdarkstyle # This awesome style sheet was made by <NAME> and <NAME> - https://github.com/ColinDuquesnoy/QDarkStyleSheet
from collections import OrderedDict
import os
import pyqtgraph as pg
import guiMapper
import guiSeque... | 0.441191 | 0.081483 |
import socket,time
from config import conf
from data import *
class _SuperSocket_metaclass(type):
def __repr__(self):
if self.desc is not None:
return "<%s: %s>" % (self.__name__,self.desc)
else:
return "<%s>" % self.__name__
class SuperSocket:
__metaclass__ = _SuperS... | donghuangzhong/src/lib/scapy/supersocket.py |
import socket,time
from config import conf
from data import *
class _SuperSocket_metaclass(type):
def __repr__(self):
if self.desc is not None:
return "<%s: %s>" % (self.__name__,self.desc)
else:
return "<%s>" % self.__name__
class SuperSocket:
__metaclass__ = _SuperS... | 0.399694 | 0.053651 |
import numpy as np
import collections
import logging
from ..core import Node, register_node_type, ThreadPollInput
from pyqtgraph.Qt import QtCore, QtGui
from pyqtgraph.util.mutex import Mutex
try:
import pyaudio
HAVE_PYAUDIO = True
except ImportError:
HAVE_PYAUDIO = False
if HAVE_PYAUDIO:
format_con... | pyacq/devices/audio_pyaudio.py |
import numpy as np
import collections
import logging
from ..core import Node, register_node_type, ThreadPollInput
from pyqtgraph.Qt import QtCore, QtGui
from pyqtgraph.util.mutex import Mutex
try:
import pyaudio
HAVE_PYAUDIO = True
except ImportError:
HAVE_PYAUDIO = False
if HAVE_PYAUDIO:
format_con... | 0.493653 | 0.256558 |
import lasagne
import cPickle
import random
import numpy as np
class base_model(object):
"""the base model for both transductive and inductive learning."""
def __init__(self, args):
"""
args (an object): contains the arguments used for initalizing the model.
"""
self.embedding_... | base_model.py | import lasagne
import cPickle
import random
import numpy as np
class base_model(object):
"""the base model for both transductive and inductive learning."""
def __init__(self, args):
"""
args (an object): contains the arguments used for initalizing the model.
"""
self.embedding_... | 0.7011 | 0.189727 |
from afqa_toolbox.features import block_properties
import numpy as np
import cv2
class FeatSEP:
"""Feature extraction for Bimodal Separation"""
def __init__(self, blk_size=32, foreground_ratio=0.8):
"""Initialize
:param blk_size: Size of individual blocks
:param foreground_ratio : Rat... | afqa_toolbox/features/sep.py | from afqa_toolbox.features import block_properties
import numpy as np
import cv2
class FeatSEP:
"""Feature extraction for Bimodal Separation"""
def __init__(self, blk_size=32, foreground_ratio=0.8):
"""Initialize
:param blk_size: Size of individual blocks
:param foreground_ratio : Rat... | 0.809125 | 0.540985 |
from uuid import uuid4
from clarity_ext.extensions import GeneralExtension
from clarity_ext_scripts.covid.create_samples.common import ValidatedSampleListFile
from clarity_ext_scripts.covid.services.knm_service import KNMClientFromExtension
from clarity_ext_scripts.covid.partner_api_client import (
ORG_URI_BY_NAME,... | clarity-ext-scripts/clarity_ext_scripts/covid/create_samples/assign_unregistered_to_anonymous.py | from uuid import uuid4
from clarity_ext.extensions import GeneralExtension
from clarity_ext_scripts.covid.create_samples.common import ValidatedSampleListFile
from clarity_ext_scripts.covid.services.knm_service import KNMClientFromExtension
from clarity_ext_scripts.covid.partner_api_client import (
ORG_URI_BY_NAME,... | 0.464659 | 0.12536 |
import pybullet as p
import numpy as np
from gym.utils import seeding
from hamstir_gym.utils import DATA_DIR
class Modder:
def __init__(self, h=256, w=256):
self.h,self.w = h, w
self.np_pixels = np.zeros((h,w,3),dtype=np.int32)
self.pixels = [0]*self.h*self.w*3
self.seed()
... | hamstir_gym/modder.py | import pybullet as p
import numpy as np
from gym.utils import seeding
from hamstir_gym.utils import DATA_DIR
class Modder:
def __init__(self, h=256, w=256):
self.h,self.w = h, w
self.np_pixels = np.zeros((h,w,3),dtype=np.int32)
self.pixels = [0]*self.h*self.w*3
self.seed()
... | 0.490236 | 0.374505 |
from os.path import basename
import numpy as np
from PIL import Image
import torch
import torch.nn.functional as F
from .base_filter import BaseFilter
from .utils import linear_srgb, rgb2hexstr
class OBSColorKey(BaseFilter):
def __init__(self, args, img, gt_mask, gt_ignore=None):
super().... | filters/obs_color_key.py | from os.path import basename
import numpy as np
from PIL import Image
import torch
import torch.nn.functional as F
from .base_filter import BaseFilter
from .utils import linear_srgb, rgb2hexstr
class OBSColorKey(BaseFilter):
def __init__(self, args, img, gt_mask, gt_ignore=None):
super().... | 0.639173 | 0.311545 |
import os
import unittest
from mock import mock
from kalliope import ResourcesManager
from kalliope.core.Models import Resources
from kalliope.core.Models.Dna import Dna
class TestResourcesmanager(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_is_settings_o... | Tests/test_resources_manager.py | import os
import unittest
from mock import mock
from kalliope import ResourcesManager
from kalliope.core.Models import Resources
from kalliope.core.Models.Dna import Dna
class TestResourcesmanager(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_is_settings_o... | 0.392337 | 0.200636 |
def _check_method_presence(cls, base, method):
"""
Test if a method is present in a class and whether it's inherited, overwritten, or "new".
Table to explain return values:
(cls, base)
False, False Neither child nor base has the method
False, True The child class inherits the method from ... | Battery_Testing_Software/labphew/core/base/tools.py | def _check_method_presence(cls, base, method):
"""
Test if a method is present in a class and whether it's inherited, overwritten, or "new".
Table to explain return values:
(cls, base)
False, False Neither child nor base has the method
False, True The child class inherits the method from ... | 0.669313 | 0.322113 |
import numpy as np
from numpy.linalg import matrix_rank, inv, det
def completeIntersection(E1, E2):
""" Exploits determinant multilinearity
Args:
E1 (np.array): homogeneous matrix of conic section 1
E2 (np.array): homogeneous matrix of conic section 2
"""
# characteristic polynom: C1... | AccessQueues/nudge/utils_intersectConics.py | import numpy as np
from numpy.linalg import matrix_rank, inv, det
def completeIntersection(E1, E2):
""" Exploits determinant multilinearity
Args:
E1 (np.array): homogeneous matrix of conic section 1
E2 (np.array): homogeneous matrix of conic section 2
"""
# characteristic polynom: C1... | 0.666605 | 0.693285 |
from __future__ import absolute_import, division, print_function
from collections import OrderedDict
try:
from tensorflow.python.keras._impl.keras.layers import pooling
except ImportError:
from tensorflow.contrib.keras.python.keras.layers import pooling
from polyaxon_schemas.layers.pooling import (
Avera... | polyaxon_lib/layers/pooling.py | from __future__ import absolute_import, division, print_function
from collections import OrderedDict
try:
from tensorflow.python.keras._impl.keras.layers import pooling
except ImportError:
from tensorflow.contrib.keras.python.keras.layers import pooling
from polyaxon_schemas.layers.pooling import (
Avera... | 0.853821 | 0.102484 |
import gensim
import os
import glob
import re
import pathlib
import logging
logging.basicConfig(
format='%(asctime)s : %(levelname)s : %(message)s',
level=logging.INFO)
def removeacentos(texto):
txt = re.sub(r"\s+", " ", texto).lower()
acentos = [('áâàãä', 'a'),
('éèêë', '... | codigo_w2v/word2vec.py | import gensim
import os
import glob
import re
import pathlib
import logging
logging.basicConfig(
format='%(asctime)s : %(levelname)s : %(message)s',
level=logging.INFO)
def removeacentos(texto):
txt = re.sub(r"\s+", " ", texto).lower()
acentos = [('áâàãä', 'a'),
('éèêë', '... | 0.169475 | 0.099777 |
from collections import Counter
# Maths------------------------------------------------------------------------
def compound_interest(investment, rate, time):
counter = 0
total = investment
interest = 1 + (rate * 0.01)
while counter < time:
total = total * interest
counter += 1
ret... | parse.py | from collections import Counter
# Maths------------------------------------------------------------------------
def compound_interest(investment, rate, time):
counter = 0
total = investment
interest = 1 + (rate * 0.01)
while counter < time:
total = total * interest
counter += 1
ret... | 0.368747 | 0.298453 |
import argparse
from config.load import load
from tiff.resize import resize
from tiff.parcels import subdivide
from tiff.visualize import parcel, support
from tiff.support import generate_supports, generate_support
import logging
from pathlib import Path
from tabulate import tabulate
import numpy
def main():
par... | terrain.py |
import argparse
from config.load import load
from tiff.resize import resize
from tiff.parcels import subdivide
from tiff.visualize import parcel, support
from tiff.support import generate_supports, generate_support
import logging
from pathlib import Path
from tabulate import tabulate
import numpy
def main():
par... | 0.439988 | 0.175839 |
from mock import MagicMock, patch, call
from six import iteritems
from gitfs.utils.args import Args
class TestArgs(object):
def test_args(self):
mocked_os = MagicMock()
mocked_log = MagicMock()
mocked_grp = MagicMock()
mocked_pass = MagicMock()
mocked_file = MagicMock()... | tests/utils/test_args.py |
from mock import MagicMock, patch, call
from six import iteritems
from gitfs.utils.args import Args
class TestArgs(object):
def test_args(self):
mocked_os = MagicMock()
mocked_log = MagicMock()
mocked_grp = MagicMock()
mocked_pass = MagicMock()
mocked_file = MagicMock()... | 0.562777 | 0.254058 |
from collections import OrderedDict
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.preprocessing import MinMaxScaler, StandardScaler, LabelEncoder
import numpy as np
import pandas as pd
def feature_transform(df, CONFIG):
"""Processing dataset for model training
Load datase... | src/utils/feature_engineering.py | from collections import OrderedDict
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.preprocessing import MinMaxScaler, StandardScaler, LabelEncoder
import numpy as np
import pandas as pd
def feature_transform(df, CONFIG):
"""Processing dataset for model training
Load datase... | 0.890372 | 0.538316 |
import theano
import theano.tensor as T
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
import load
# load data
x_train, t_train, x_test, t_test = load.cifar10(dtype=theano.config.floatX)
labels_test = np.argmax(t_test, axis=1)
# define symbolic Theano variables
x = T.matrix()
t = T.matrix()
# defin... | 5_fancy_net.py | import theano
import theano.tensor as T
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
import load
# load data
x_train, t_train, x_test, t_test = load.cifar10(dtype=theano.config.floatX)
labels_test = np.argmax(t_test, axis=1)
# define symbolic Theano variables
x = T.matrix()
t = T.matrix()
# defin... | 0.614625 | 0.530297 |
# 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/backend/test_states_probabilities.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.953232 | 0.572783 |
import logging
from typing import cast, List, Optional, Tuple
import itertools
import numpy as np
from qiskit_nature.drivers import QMolecule
from qiskit_nature.operators.second_quantization import FermionicOp
from qiskit_nature.results import EigenstateResult
from ..second_quantized_property import LegacyDriverRes... | qiskit_nature/properties/second_quantization/electronic/angular_momentum.py | import logging
from typing import cast, List, Optional, Tuple
import itertools
import numpy as np
from qiskit_nature.drivers import QMolecule
from qiskit_nature.operators.second_quantization import FermionicOp
from qiskit_nature.results import EigenstateResult
from ..second_quantized_property import LegacyDriverRes... | 0.899328 | 0.618204 |
import time
import os
import logging
from urllib.parse import urlparse
from urllib.request import urlretrieve
from queue import Queue
from threading import Thread, Lock
import multiprocessing
import asyncio
import aiohttp
import aiofiles
import PIL
from PIL import Image
FORMAT = "[%(threadName)s, %(asctime)s, %(level... | src/concurrency in python/python concurrecy/python-concurrency-getting-started/06/demos/python-concurrency-getting-started-develop-asyncio/thumbnail_maker.py | import time
import os
import logging
from urllib.parse import urlparse
from urllib.request import urlretrieve
from queue import Queue
from threading import Thread, Lock
import multiprocessing
import asyncio
import aiohttp
import aiofiles
import PIL
from PIL import Image
FORMAT = "[%(threadName)s, %(asctime)s, %(level... | 0.336985 | 0.074973 |
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AccountStatement',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True,... | nubank_django/migrations/0001_initial.py |
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AccountStatement',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True,... | 0.653348 | 0.198783 |
import os
import sys
import optparse
import struct
import yaml
script_path = sys.path[0] # http://stackoverflow.com/questions/4934806/how-can-i-find-scripts-directory-with-python
ops = None
def decode_string(buf, off):
strlen, = struct.unpack('>L', buf[off:off + 4])
off += 4
strdata = buf[off:off + str... | vehicle/OVMS.V3/components/duktape/tools/dump_bytecode.py |
import os
import sys
import optparse
import struct
import yaml
script_path = sys.path[0] # http://stackoverflow.com/questions/4934806/how-can-i-find-scripts-directory-with-python
ops = None
def decode_string(buf, off):
strlen, = struct.unpack('>L', buf[off:off + 4])
off += 4
strdata = buf[off:off + str... | 0.232484 | 0.228006 |
import numpy as np
import pytest
from landlab import FieldError, RasterModelGrid
from landlab.components import FlowAccumulator, FlowDirectorSteepest
from landlab.utils.distance_to_divide import calculate_distance_to_divide
def test_no_flow_receivers():
"""Test that correct error is raised when no flow recievers... | tests/utils/test_distance_from_divide.py | import numpy as np
import pytest
from landlab import FieldError, RasterModelGrid
from landlab.components import FlowAccumulator, FlowDirectorSteepest
from landlab.utils.distance_to_divide import calculate_distance_to_divide
def test_no_flow_receivers():
"""Test that correct error is raised when no flow recievers... | 0.721154 | 0.576393 |
import pandas as pd
from datetime import datetime
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from sqlalchemy import create_engine
import os
user=os.getenv('MYSQL_user')
pw=os.getenv('MYSQL')
str_sql = 'mysql+mysqlconnector://' + user + ':' + pw + '@localhost'
m_engine = create... | NWHL_format.py | import pandas as pd
from datetime import datetime
from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from sqlalchemy import create_engine
import os
user=os.getenv('MYSQL_user')
pw=os.getenv('MYSQL')
str_sql = 'mysql+mysqlconnector://' + user + ':' + pw + '@localhost'
m_engine = create... | 0.185209 | 0.160661 |
import os.path as op
import json
from collections import defaultdict
import numpy as np
from nipype import logging
import pandas as pd
from nipype.utils.filemanip import fname_presuffix, split_filename
from .images import to_lps
from .reports import topup_selection_to_report
from nilearn.image import load_img, index_im... | qsiprep/interfaces/epi_fmap.py | import os.path as op
import json
from collections import defaultdict
import numpy as np
from nipype import logging
import pandas as pd
from nipype.utils.filemanip import fname_presuffix, split_filename
from .images import to_lps
from .reports import topup_selection_to_report
from nilearn.image import load_img, index_im... | 0.721351 | 0.252488 |
import time
import pickle
import numpy as np
from threading import Thread
from typing import Any, List, Dict
from nxs_libs.queue import NxsQueuePuller, NxsQueuePusher
from nxs_utils.nxs_helper import init_redis_client
from nxs_utils.logging import write_log, NxsLogLevel
class NxsRedisQueuePuller(NxsQueuePuller):
... | nxs_libs/queue/nxs_redis_queue.py | import time
import pickle
import numpy as np
from threading import Thread
from typing import Any, List, Dict
from nxs_libs.queue import NxsQueuePuller, NxsQueuePusher
from nxs_utils.nxs_helper import init_redis_client
from nxs_utils.logging import write_log, NxsLogLevel
class NxsRedisQueuePuller(NxsQueuePuller):
... | 0.513425 | 0.109968 |