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 |
|---|---|---|---|---|
from collections import OrderedDict
import os
import git
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from common import models as common_models
from .mixins import AbstractProjectResourceModel
from .utils import name_validator
from ..ansible.ga... | api/ansible_api/models/role.py | from collections import OrderedDict
import os
import git
from django.db import models
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from common import models as common_models
from .mixins import AbstractProjectResourceModel
from .utils import name_validator
from ..ansible.ga... | 0.461259 | 0.057838 |
import numpy as np
from openravepy import RaveCreateTrajectory, Robot
from prpy.util import ComputeUnitTiming, GetCollisionCheckPts, IsTimedTrajectory
def get_feasible_path(robot, path):
"""
Check a path for feasibility (collision) and return a truncated path
containing the path only up to just before the... | src/magi/actions/util.py | import numpy as np
from openravepy import RaveCreateTrajectory, Robot
from prpy.util import ComputeUnitTiming, GetCollisionCheckPts, IsTimedTrajectory
def get_feasible_path(robot, path):
"""
Check a path for feasibility (collision) and return a truncated path
containing the path only up to just before the... | 0.824921 | 0.54359 |
import logging
import multiprocessing as mp
import os
import pickle
import subprocess
import timeit
from pathlib import Path
import atom3.database as db
import atom3.sequence as sequ
import pandas as pd
import parallel as par
from atom3.utils import extract_hmm_profile, slice_list
def add_conservation_parser(subpars... | atom3/conservation.py | import logging
import multiprocessing as mp
import os
import pickle
import subprocess
import timeit
from pathlib import Path
import atom3.database as db
import atom3.sequence as sequ
import pandas as pd
import parallel as par
from atom3.utils import extract_hmm_profile, slice_list
def add_conservation_parser(subpars... | 0.46563 | 0.101902 |
import pyeccodes.accessors as _
def load(h):
def wrapped(h):
table2Version = h.get_l('table2Version')
indicatorOfParameter = h.get_l('indicatorOfParameter')
if table2Version == 253 and indicatorOfParameter == 228:
return 'Instantaneous Wind Speed in m/s'
if table2Ve... | pyeccodes/defs/grib1/localConcepts/efkl/name_def.py | import pyeccodes.accessors as _
def load(h):
def wrapped(h):
table2Version = h.get_l('table2Version')
indicatorOfParameter = h.get_l('indicatorOfParameter')
if table2Version == 253 and indicatorOfParameter == 228:
return 'Instantaneous Wind Speed in m/s'
if table2Ve... | 0.583441 | 0.499512 |
# basic
import sys
import getpass
import pandas as pd
import pathlib
from sqlalchemy import *
# plot
import plotly.graph_objs as go
import plotly.offline as pltly
pltly.init_notebook_mode(connected=True)
#%%Database Connection
# This function creates a database connection to the reeem_db.
# The default user is reee... | visualisation/generation/OSeMBE_generation_graphs.py | # basic
import sys
import getpass
import pandas as pd
import pathlib
from sqlalchemy import *
# plot
import plotly.graph_objs as go
import plotly.offline as pltly
pltly.init_notebook_mode(connected=True)
#%%Database Connection
# This function creates a database connection to the reeem_db.
# The default user is reee... | 0.277473 | 0.198394 |
from dataclasses import dataclass
import pele_platform.Checker.main as ck
import pele_platform.Frag.simulation as fr
import pele_platform.Adaptive.simulation as ad
import pele_platform.site_finder.main as al
import pele_platform.gpcr.main as gpcr
import pele_platform.out_in.main as outin
from pele_platform.PPI.main imp... | pele_platform/Utilities/Helpers/launcher.py | from dataclasses import dataclass
import pele_platform.Checker.main as ck
import pele_platform.Frag.simulation as fr
import pele_platform.Adaptive.simulation as ad
import pele_platform.site_finder.main as al
import pele_platform.gpcr.main as gpcr
import pele_platform.out_in.main as outin
from pele_platform.PPI.main imp... | 0.433502 | 0.121165 |
import numpy as np
import argparse
from train import train
from models.FC import FC
from torch.utils.data import TensorDataset
from SDR import SDR
import torch
# Some constants for the experiment
# Num of bits for the SDR input for character
# The ASCII input has 7 bits. To have sparse representation (< 2%)
# We set 5... | exp15.py | import numpy as np
import argparse
from train import train
from models.FC import FC
from torch.utils.data import TensorDataset
from SDR import SDR
import torch
# Some constants for the experiment
# Num of bits for the SDR input for character
# The ASCII input has 7 bits. To have sparse representation (< 2%)
# We set 5... | 0.684053 | 0.314919 |
import abc
from datetime import datetime, timedelta
import os
import random
import sys
import time
from typing import Set, Iterable, Optional, ClassVar
from urllib.parse import urlsplit, unquote
import attr
from bs4 import BeautifulSoup
import requests
import requests_html
# Epsilon value
EPS = sys.float_info.epsilon... | wiki_graph/scrape/scrape.py | import abc
from datetime import datetime, timedelta
import os
import random
import sys
import time
from typing import Set, Iterable, Optional, ClassVar
from urllib.parse import urlsplit, unquote
import attr
from bs4 import BeautifulSoup
import requests
import requests_html
# Epsilon value
EPS = sys.float_info.epsilon... | 0.647798 | 0.218169 |
from __future__ import print_function, division
import numpy as np
from pytest import fixture
from kipoi.data import (PreloadedDataset, Dataset, BatchDataset,
SampleIterator, SampleGenerator,
BatchIterator, BatchGenerator)
from kipoi_utils.data_utils import get_dataset_it... | tests/test_12_dataloader_classes.py | from __future__ import print_function, division
import numpy as np
from pytest import fixture
from kipoi.data import (PreloadedDataset, Dataset, BatchDataset,
SampleIterator, SampleGenerator,
BatchIterator, BatchGenerator)
from kipoi_utils.data_utils import get_dataset_it... | 0.79999 | 0.561816 |
from unittest import TestCase
from command import Command
from output import Output
class TestAction(TestCase):
def test_init(self):
name = '<NAME>'
obj = Output.getinstance()
method = obj.print_sentence
help_text = 'The print_sentence method of the Output singleton'
insta... | Tests/test_action.py | from unittest import TestCase
from command import Command
from output import Output
class TestAction(TestCase):
def test_init(self):
name = '<NAME>'
obj = Output.getinstance()
method = obj.print_sentence
help_text = 'The print_sentence method of the Output singleton'
insta... | 0.619126 | 0.334943 |
import re
# pro učely VERBOSE
import ita
def makeException(_msg, _lineno = None, file = None ):
e = SyntaxError()
e.msg = _msg
e.lineno = _lineno
e.filename = file
return e
class Rule:
def __init__(self, nonterm, code, params = None, info = None):
self.nonterm = nonterm
s... | ita/parser.py | import re
# pro učely VERBOSE
import ita
def makeException(_msg, _lineno = None, file = None ):
e = SyntaxError()
e.msg = _msg
e.lineno = _lineno
e.filename = file
return e
class Rule:
def __init__(self, nonterm, code, params = None, info = None):
self.nonterm = nonterm
s... | 0.122235 | 0.267652 |
import Services.Exceptions.exceptions_hospital
class Hospital:
def __init__(self, active, size, max_patients, max_employees, pharmacy, pharmacy_size = None, pharmacy_active = False):
self.__size = size
self.__active = active
self.__max_patients = max_patients
self.__max_employees =... | python3/pyCity/Services/hospital.py | import Services.Exceptions.exceptions_hospital
class Hospital:
def __init__(self, active, size, max_patients, max_employees, pharmacy, pharmacy_size = None, pharmacy_active = False):
self.__size = size
self.__active = active
self.__max_patients = max_patients
self.__max_employees =... | 0.324449 | 0.116236 |
import streamlit as st
from Pose_Estimation.poseEstimation_utils import get_pose_estimation
from Pose_Estimation.poseEstimation_info import get_info_poseEstimation
from gluoncv import model_zoo, data, utils
import mxnet as mx
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import os
# ---... | Pose_Estimation/poseEstimation_main.py |
import streamlit as st
from Pose_Estimation.poseEstimation_utils import get_pose_estimation
from Pose_Estimation.poseEstimation_info import get_info_poseEstimation
from gluoncv import model_zoo, data, utils
import mxnet as mx
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import os
# ---... | 0.229535 | 0.271019 |
from sympy import *
def getCoords():
x1 = float(input("Entre com o valor de x1: "))
y1 = float(input("Entre com o valor de y1: "))
x2 = float(input("Entre com o valor de x2: "))
y2 = float(input("Entre com o valor de y2: "))
x3 = float(input("Entre com o valor de x3: "))
y3 = float(input("Entr... | main.py | from sympy import *
def getCoords():
x1 = float(input("Entre com o valor de x1: "))
y1 = float(input("Entre com o valor de y1: "))
x2 = float(input("Entre com o valor de x2: "))
y2 = float(input("Entre com o valor de y2: "))
x3 = float(input("Entre com o valor de x3: "))
y3 = float(input("Entr... | 0.467575 | 0.619644 |
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import pickle
import matplotlib
import numpy as np
# To suppress plots from popping up
import matplotlib.pyplot as plt
from pysb.integrate import Solver
from pysb.bng import generate_equations
from pysb.exp... | models/braf_model/run_model.py | from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
import os
import pickle
import matplotlib
import numpy as np
# To suppress plots from popping up
import matplotlib.pyplot as plt
from pysb.integrate import Solver
from pysb.bng import generate_equations
from pysb.exp... | 0.579519 | 0.380586 |
import logging
from pprint import pformat
import pendulum
import requests
from fcache.cache import FileCache
from requests.exceptions import HTTPError
from .const import *
from .endpoints import Football, Shield
from .helpers import *
from .__version__ import __version__
logger = logging.getLogger(__name__)
EPOCH =... | nflapi/nfl.py | import logging
from pprint import pformat
import pendulum
import requests
from fcache.cache import FileCache
from requests.exceptions import HTTPError
from .const import *
from .endpoints import Football, Shield
from .helpers import *
from .__version__ import __version__
logger = logging.getLogger(__name__)
EPOCH =... | 0.516839 | 0.075109 |
import simplex_solver as ss
import tkinter as tk
from tkinter import ttk
__author__ = 'ieg'
__version__ = '1.0'
class SimplexCalculator(tk.Frame):
"""Display a GUI through which the user spawns an entry form for a particular LPP.
Public Variables
----------
master : tk.Frame
Frame obje... | simplex_solver/src/simplex.py | import simplex_solver as ss
import tkinter as tk
from tkinter import ttk
__author__ = 'ieg'
__version__ = '1.0'
class SimplexCalculator(tk.Frame):
"""Display a GUI through which the user spawns an entry form for a particular LPP.
Public Variables
----------
master : tk.Frame
Frame obje... | 0.731251 | 0.336713 |
from testrail_yak import Milestone
from testrail_yak.lib.testrail import APIClient
from tests import BASEURL, reqmock
client = APIClient(BASEURL)
m = Milestone(client)
def test_get(reqmock):
milestone_id = 1
reqmock.get(f"{BASEURL}/index.php?/api/v2/get_milestone/{milestone_id}",
status_code=200,
... | tests/test_milestone.py | from testrail_yak import Milestone
from testrail_yak.lib.testrail import APIClient
from tests import BASEURL, reqmock
client = APIClient(BASEURL)
m = Milestone(client)
def test_get(reqmock):
milestone_id = 1
reqmock.get(f"{BASEURL}/index.php?/api/v2/get_milestone/{milestone_id}",
status_code=200,
... | 0.399929 | 0.395951 |
import os
import pickle
import tensorflow as tf
import numpy as np
import tf_util
import gym
import argparse
import load_policy
def weight_variable(shape): # weight initialization
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.cons... | hw1/run_DAgger.py | import os
import pickle
import tensorflow as tf
import numpy as np
import tf_util
import gym
import argparse
import load_policy
def weight_variable(shape): # weight initialization
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.cons... | 0.590543 | 0.219515 |
from __future__ import absolute_import
import cStringIO
import json
import logging
import os
import shutil
import sys
import tempfile
import types
import mitogen.service
import ansible_mitogen.target # TODO: circular import
try:
from shlex import quote as shlex_quote
except ImportError:
from pipes import quo... | ansible_mitogen/runner.py | from __future__ import absolute_import
import cStringIO
import json
import logging
import os
import shutil
import sys
import tempfile
import types
import mitogen.service
import ansible_mitogen.target # TODO: circular import
try:
from shlex import quote as shlex_quote
except ImportError:
from pipes import quo... | 0.490236 | 0.155271 |
import os
import smpl.util as util
import smpl.log_module as logger
import platform
import re
from smpl.package import LibraryPackage
from smpl.config_file import ConfigObject, PackageParms
import smpl.exec as exec
package_name = "openssl"
openssl_name = "openssl-1.1.1f"
# package_url = "https://dl.bintra... | smpl/openssl.py | import os
import smpl.util as util
import smpl.log_module as logger
import platform
import re
from smpl.package import LibraryPackage
from smpl.config_file import ConfigObject, PackageParms
import smpl.exec as exec
package_name = "openssl"
openssl_name = "openssl-1.1.1f"
# package_url = "https://dl.bintra... | 0.182389 | 0.062046 |
words=['aargh',
'aarrgh',
'aarrghh',
'abapical',
'abasia',
'abasias',
'abba',
'abbas',
'abelian',
'abrachia',
'abrachias',
'abrosia',
'abrosias',
'abseil',
'abseiled',
'abseiling',
'abseils',
'acapnia',
'acapnias',
'accidia',
'accidias',
'acetin',
'acetins',
'achillea',
'achilleas',
'acholia',
'acholias',
'aciculum',
'... | Dictionary/crswd-d.py | words=['aargh',
'aarrgh',
'aarrghh',
'abapical',
'abasia',
'abasias',
'abba',
'abbas',
'abelian',
'abrachia',
'abrachias',
'abrosia',
'abrosias',
'abseil',
'abseiled',
'abseiling',
'abseils',
'acapnia',
'acapnias',
'accidia',
'accidias',
'acetin',
'acetins',
'achillea',
'achilleas',
'acholia',
'acholias',
'aciculum',
'... | 0.350088 | 0.113285 |
import unittest
import sys
sys.path.append('.')
import habrahabr
from tests.base import BaseTest
class BaseResourceTest(BaseTest, unittest.TestCase):
"""This object represents Tests for BaseResource."""
def setUp(self):
auth = habrahabr.Auth(client='foo.bar', token='<PASSWORD>')
auth._endpo... | tests/test_base.py | import unittest
import sys
sys.path.append('.')
import habrahabr
from tests.base import BaseTest
class BaseResourceTest(BaseTest, unittest.TestCase):
"""This object represents Tests for BaseResource."""
def setUp(self):
auth = habrahabr.Auth(client='foo.bar', token='<PASSWORD>')
auth._endpo... | 0.449151 | 0.345519 |
import pytest
from star.seismology import Seismology
vmax0: float = 3.05 # mHz
deltav0: float = 134.9 # µHz
Teff0: int = 5777
def test_simple():
vmax = 1
deltav = 200
Teff = 5000
s = Seismology(vmax, deltav, Teff)
assert isinstance(s, Seismology)
assert isinstance(s.vmax, ... | star/tests/test_seismology.py | import pytest
from star.seismology import Seismology
vmax0: float = 3.05 # mHz
deltav0: float = 134.9 # µHz
Teff0: int = 5777
def test_simple():
vmax = 1
deltav = 200
Teff = 5000
s = Seismology(vmax, deltav, Teff)
assert isinstance(s, Seismology)
assert isinstance(s.vmax, ... | 0.644001 | 0.641843 |
from pyvcloud.vcd.client import E
from pyvcloud.vcd.client import EntityType
from pyvcloud.vcd.client import NSMAP
from pyvcloud.vcd.client import QueryResultFormat
from pyvcloud.vcd.client import RelationType
from pyvcloud.vcd.utils import get_admin_href
class System(object):
def __init__(self, client, admin_hr... | pyvcloud/vcd/system.py |
from pyvcloud.vcd.client import E
from pyvcloud.vcd.client import EntityType
from pyvcloud.vcd.client import NSMAP
from pyvcloud.vcd.client import QueryResultFormat
from pyvcloud.vcd.client import RelationType
from pyvcloud.vcd.utils import get_admin_href
class System(object):
def __init__(self, client, admin_hr... | 0.748628 | 0.085366 |
import argparse
import os
import sys
import textwrap
description = '''
Will update `~/.config/mimeapps.list` to add mime type associations for all
mime types that can be opened as listed in the given application `.desktop`
file. Will update `~/.config/mimeapps.list` such that it first contains a new
`[Default Applica... | xdg-mime-default-all.py |
import argparse
import os
import sys
import textwrap
description = '''
Will update `~/.config/mimeapps.list` to add mime type associations for all
mime types that can be opened as listed in the given application `.desktop`
file. Will update `~/.config/mimeapps.list` such that it first contains a new
`[Default Applica... | 0.399694 | 0.088308 |
# Standard Python Libraries
from datetime import datetime
from typing import Any, Dict
# TODO Research .attribute only valid properties
class Model(object):
"""The Model class."""
_valid_properties: Dict[str, Any] = dict()
@classmethod
def _is_builtin(cls, obj):
return isinstance(obj, (int... | src/models/models.py |
# Standard Python Libraries
from datetime import datetime
from typing import Any, Dict
# TODO Research .attribute only valid properties
class Model(object):
"""The Model class."""
_valid_properties: Dict[str, Any] = dict()
@classmethod
def _is_builtin(cls, obj):
return isinstance(obj, (int... | 0.705886 | 0.264136 |
import audio.audioHandler as audio
import numpy as np
import matplotlib.pyplot as plt
import csv
import time
from app.supression.spectralSubtraction import spectralSubtraction
from app.supression.fastLMS import fastLMS
from app.supression.plca import plcaWavelet
def runTests():
audioPrefix = 'audio_files/'
r... | tests/tests.py | import audio.audioHandler as audio
import numpy as np
import matplotlib.pyplot as plt
import csv
import time
from app.supression.spectralSubtraction import spectralSubtraction
from app.supression.fastLMS import fastLMS
from app.supression.plca import plcaWavelet
def runTests():
audioPrefix = 'audio_files/'
r... | 0.356671 | 0.449453 |
import os
import dj_database_url
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = os.path.dirname(PROJECT_DIR)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.co... | backend/weatherwarner/settings/base.py | import os
import dj_database_url
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = os.path.dirname(PROJECT_DIR)
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.co... | 0.416085 | 0.137417 |
import csv
from django.core.management.base import BaseCommand
from sidekick.models import (
NetworkServiceDevice,
NetworkServiceL2,
)
class Command(BaseCommand):
help = "Import existing network service L2 details"
def add_arguments(self, parser):
parser.add_argument(
'--file', ... | sidekick/management/commands/import_network_service_l2.py | import csv
from django.core.management.base import BaseCommand
from sidekick.models import (
NetworkServiceDevice,
NetworkServiceL2,
)
class Command(BaseCommand):
help = "Import existing network service L2 details"
def add_arguments(self, parser):
parser.add_argument(
'--file', ... | 0.366363 | 0.085709 |
# Copyright (C) 2021-2014 Alibaba Group Holding Limited
import platform
import os
import argparse
import shutil
import subprocess
import hashlib
import re
from pbxproj import XcodeProject
TARGET_APPLICATION = 0
TARGET_STATIC_LIBRARY = 1
TARGET_SHARED_LIBRARY = 2
__jenova_prefined_libraries = ["Ope... | TBJGameSDK/toolchain/emscripten/mod-pbxproj/taoxcode_exporter.py |
# Copyright (C) 2021-2014 Alibaba Group Holding Limited
import platform
import os
import argparse
import shutil
import subprocess
import hashlib
import re
from pbxproj import XcodeProject
TARGET_APPLICATION = 0
TARGET_STATIC_LIBRARY = 1
TARGET_SHARED_LIBRARY = 2
__jenova_prefined_libraries = ["Ope... | 0.267408 | 0.066055 |
import argparse
import lasagne.init as LI
import lasagne.layers as L
import lasagne.nonlinearities as LN
import numpy as np
import yaml
from rllab.algos.trpo import TRPO
from rllab.baselines.gaussian_conv_baseline import GaussianConvBaseline
from rllab.core.network import ConvNetwork
from rllab.core.network import wrap... | scripts/trpo_visual_servoing.py | import argparse
import lasagne.init as LI
import lasagne.layers as L
import lasagne.nonlinearities as LN
import numpy as np
import yaml
from rllab.algos.trpo import TRPO
from rllab.baselines.gaussian_conv_baseline import GaussianConvBaseline
from rllab.core.network import ConvNetwork
from rllab.core.network import wrap... | 0.624408 | 0.267097 |
import pandas as pd
class Backtest:
def __init__(self, agent, cash, stock=0, logging=False, ticker=None):
self.agent = agent
self.cash = cash
self.stock = stock
self.logging = logging
self.ticker = ticker
if logging:
if ticker is None:
rai... | build/lib/algotrader/backtest.py | import pandas as pd
class Backtest:
def __init__(self, agent, cash, stock=0, logging=False, ticker=None):
self.agent = agent
self.cash = cash
self.stock = stock
self.logging = logging
self.ticker = ticker
if logging:
if ticker is None:
rai... | 0.099684 | 0.209692 |
from oct.utils import *
import logging
from ..load.metadata import Metadata
cp, np, convolve, gpuAvailable, freeMemory, e = checkForCupy()
class Structure:
""" Structure contrast OCT reconstruction """
def __init__(self, mode='log'):
acceptedModes = 'log+linear'
if mode in acceptedModes:
... | oct/reconstruct/structure.py | from oct.utils import *
import logging
from ..load.metadata import Metadata
cp, np, convolve, gpuAvailable, freeMemory, e = checkForCupy()
class Structure:
""" Structure contrast OCT reconstruction """
def __init__(self, mode='log'):
acceptedModes = 'log+linear'
if mode in acceptedModes:
... | 0.704465 | 0.275507 |
# Authors: <NAME> <<EMAIL>>
# License: MIT
from __future__ import print_function
import numpy as np
from .ugtm_plot import plot
from .ugtm_plot import plotMultiPanelGTM
from .ugtm_plot import plot_html_GTM
from .ugtm_plot import plot_html_GTM_projection
class ReturnU(object):
def __init__(self, matU, betaInv):
... | ugtm/ugtm_classes.py | # Authors: <NAME> <<EMAIL>>
# License: MIT
from __future__ import print_function
import numpy as np
from .ugtm_plot import plot
from .ugtm_plot import plotMultiPanelGTM
from .ugtm_plot import plot_html_GTM
from .ugtm_plot import plot_html_GTM_projection
class ReturnU(object):
def __init__(self, matU, betaInv):
... | 0.950755 | 0.780704 |
# Imports
from typing import (
Dict,
List,
Optional,
NamedTuple
)
class CanisterAPIResponse(NamedTuple):
""" Namedtuple representation of a request response.
This class is the raw representation of a returned response
from the Canister API. """
# Status of the request
status: str
... | canister/objects.py |
# Imports
from typing import (
Dict,
List,
Optional,
NamedTuple
)
class CanisterAPIResponse(NamedTuple):
""" Namedtuple representation of a request response.
This class is the raw representation of a returned response
from the Canister API. """
# Status of the request
status: str
... | 0.929704 | 0.572305 |
from unittest import TestCase
from .common import transform_test_file
def html_lines(title, body_lines):
result = [
'<html>',
'<head>',
f'<title>{title}</title>',
'</head>',
'<body>',
]
result.extend(body_lines)
result.extend(['</body>', '</html>'])
return ... | contingent/step03_transform/tests/test_transformer.py | from unittest import TestCase
from .common import transform_test_file
def html_lines(title, body_lines):
result = [
'<html>',
'<head>',
f'<title>{title}</title>',
'</head>',
'<body>',
]
result.extend(body_lines)
result.extend(['</body>', '</html>'])
return ... | 0.625209 | 0.412116 |
import os
import tensorflow as tf
from utils.constants import *
from utils.strings import *
from utils.util import print_and_log_message, print_and_log_message_list
class BaseAgent(object):
'''Base class containing all the parameters for reinforcement learning'''
def __init__(self, config, logger):
... | code/model/baseagent.py |
import os
import tensorflow as tf
from utils.constants import *
from utils.strings import *
from utils.util import print_and_log_message, print_and_log_message_list
class BaseAgent(object):
'''Base class containing all the parameters for reinforcement learning'''
def __init__(self, config, logger):
... | 0.706393 | 0.128061 |
import sys
import configargparse
from bulbutil import logger
def get():
parser = configargparse.ArgumentParser(
description='An util to control TP-link smart bulbs.\n',
default_config_files=('/etc/bulbutil.conf', '~/.config/bulbutil.conf', './bulbutil.conf'),
args_for_setting_config_path... | bulbutil/config.py | import sys
import configargparse
from bulbutil import logger
def get():
parser = configargparse.ArgumentParser(
description='An util to control TP-link smart bulbs.\n',
default_config_files=('/etc/bulbutil.conf', '~/.config/bulbutil.conf', './bulbutil.conf'),
args_for_setting_config_path... | 0.444806 | 0.305115 |
from typing import Callable, List, Optional, Union
from torchdrug import data
# isort: off
from torch import nn
"""
Necessary because torchdrug silently overwrites the default nn.Module. This is quite
invasive and causes significant side-effects in the rest of the code.
See: https://github.com/DeepGraphLearning/torc... | src/gt4sd/training_pipelines/torchdrug/dataset.py | from typing import Callable, List, Optional, Union
from torchdrug import data
# isort: off
from torch import nn
"""
Necessary because torchdrug silently overwrites the default nn.Module. This is quite
invasive and causes significant side-effects in the rest of the code.
See: https://github.com/DeepGraphLearning/torc... | 0.961893 | 0.516778 |
import pytest
from bratiaa.agree import *
from bratiaa.agree_view import F1AgreementView, extended_iaa_report
from bratiaa.utils import tokenize
AGREE_2_ROOT = 'data/agreement/agree-2'
def test_view_instance_disagreements():
f1_agreement_view = F1AgreementView(AGREE_2_ROOT)
expected_disagreements = {
... | tests/bratiaa/test_agree_view.py | import pytest
from bratiaa.agree import *
from bratiaa.agree_view import F1AgreementView, extended_iaa_report
from bratiaa.utils import tokenize
AGREE_2_ROOT = 'data/agreement/agree-2'
def test_view_instance_disagreements():
f1_agreement_view = F1AgreementView(AGREE_2_ROOT)
expected_disagreements = {
... | 0.391639 | 0.379005 |
import os
import sys
import numpy as np
import numpy.random as rnd
from itertools import product
from detect.utils import genome_utils
BASES = {'A','T','C','G'}
BASE_PAIR = {'A':'T', 'T':'A', 'C':'G', 'G':'C'}
kmers = [''.join(kmer) for kmer in product(BASES, repeat=4)]
jmers = [''.join(kmer) for kmer in product(BASE... | detect/utils/tnf_utils.py | import os
import sys
import numpy as np
import numpy.random as rnd
from itertools import product
from detect.utils import genome_utils
BASES = {'A','T','C','G'}
BASE_PAIR = {'A':'T', 'T':'A', 'C':'G', 'G':'C'}
kmers = [''.join(kmer) for kmer in product(BASES, repeat=4)]
jmers = [''.join(kmer) for kmer in product(BASE... | 0.202443 | 0.332907 |
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
import datetime
from pessoas.models import Pessoa
from predios.models import Predio
from pequenos_grupos.models import Celula
from django.db.models import F, Q, Count, Sum
import json
from django.utils.encoding impor... | home/views.py | from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
import datetime
from pessoas.models import Pessoa
from predios.models import Predio
from pequenos_grupos.models import Celula
from django.db.models import F, Q, Count, Sum
import json
from django.utils.encoding impor... | 0.362856 | 0.161485 |
# They sent you a list of the rules valid messages should obey and a list of received messages they've collected so far (your puzzle input).
# The rules for valid messages (the top part of your puzzle input) are numbered and build upon each other. For example:
# 0: 1 2
# 1: "a"
# 2: 1 3 | 3 1
# 3: "b"
# Some rules, ... | Day19/Day19.py |
# They sent you a list of the rules valid messages should obey and a list of received messages they've collected so far (your puzzle input).
# The rules for valid messages (the top part of your puzzle input) are numbered and build upon each other. For example:
# 0: 1 2
# 1: "a"
# 2: 1 3 | 3 1
# 3: "b"
# Some rules, ... | 0.746231 | 0.686646 |
import logging
from enum import Enum
from typing import Any, Mapping
import backoff
import pendulum
from facebook_business.exceptions import FacebookRequestError
from source_facebook_marketing.api import API
from .common import JobException, JobTimeoutException, retry_pattern
backoff_policy = retry_pattern(backoff.... | airbyte-integrations/connectors/source-facebook-marketing/source_facebook_marketing/async_job.py |
import logging
from enum import Enum
from typing import Any, Mapping
import backoff
import pendulum
from facebook_business.exceptions import FacebookRequestError
from source_facebook_marketing.api import API
from .common import JobException, JobTimeoutException, retry_pattern
backoff_policy = retry_pattern(backoff.... | 0.803868 | 0.093802 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Trip',
fields=[
('id', models.AutoField(auto_created=True,... | travels/migrations/0001_initial.py |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Trip',
fields=[
('id', models.AutoField(auto_created=True,... | 0.572245 | 0.255692 |
import re
from typing import Any, Dict
from abc import ABC, abstractmethod
class Validator(ABC):
"""Base validator class.
All Validator classes must inherit from this one.
"""
@abstractmethod
def _validate(self, *args, **kwargs) -> bool:
pass
def __call__(self, *args, **kwargs):
... | backend/kale/config/validators.py |
import re
from typing import Any, Dict
from abc import ABC, abstractmethod
class Validator(ABC):
"""Base validator class.
All Validator classes must inherit from this one.
"""
@abstractmethod
def _validate(self, *args, **kwargs) -> bool:
pass
def __call__(self, *args, **kwargs):
... | 0.932714 | 0.267393 |
class FunctionMultiplication:
def __init__(self, f1, f2):
self.f1 = f1
self.f2 = f2
def __str__(self):
return "(" + str(self.f1) + ") * (" + str(self.f2) + ")"
def __call__(self, x, y):
return self.f1(x,y) * self.f2(x,y)
def __add__(self, other):
return Functi... | FEM/src/Function.py | class FunctionMultiplication:
def __init__(self, f1, f2):
self.f1 = f1
self.f2 = f2
def __str__(self):
return "(" + str(self.f1) + ") * (" + str(self.f2) + ")"
def __call__(self, x, y):
return self.f1(x,y) * self.f2(x,y)
def __add__(self, other):
return Functi... | 0.742328 | 0.257911 |
from dataclasses import dataclass
from datetime import datetime, timedelta, date, time
from collections import OrderedDict
from typing import List, Optional
from helpers.timing import (
day_str,
get_hour_short_str,
short_day_str,
to_french_short_weekday,
)
@dataclass
class Schedule:
date_time: dat... | helpers/schedules.py | from dataclasses import dataclass
from datetime import datetime, timedelta, date, time
from collections import OrderedDict
from typing import List, Optional
from helpers.timing import (
day_str,
get_hour_short_str,
short_day_str,
to_french_short_weekday,
)
@dataclass
class Schedule:
date_time: dat... | 0.914104 | 0.260495 |
from azure.cli.core.util import sdk_no_wait
def elastic_monitor_list(client,
resource_group_name=None):
if resource_group_name:
return client.list_by_resource_group(resource_group_name=resource_group_name)
return client.list()
def elastic_monitor_show(client,
... | src/elastic/azext_elastic/generated/custom.py |
from azure.cli.core.util import sdk_no_wait
def elastic_monitor_list(client,
resource_group_name=None):
if resource_group_name:
return client.list_by_resource_group(resource_group_name=resource_group_name)
return client.list()
def elastic_monitor_show(client,
... | 0.360377 | 0.048025 |
def filter_distance(total_distances, filtered_paths, available_paths, distance_thresh, min_path, min_dist):
'''
Accepts a paths defaultdict(dict), the result of all_shortest_paths(G),
and removes (in-place) all paths between the nodes indicated by pair whose
total route distance is more than distance_th... | code/filter_paths.py | def filter_distance(total_distances, filtered_paths, available_paths, distance_thresh, min_path, min_dist):
'''
Accepts a paths defaultdict(dict), the result of all_shortest_paths(G),
and removes (in-place) all paths between the nodes indicated by pair whose
total route distance is more than distance_th... | 0.780495 | 0.690748 |
"""Module to test custom log handlers."""
from logging import Handler
import pytest
pytest.importorskip('kafka.errors')
from kafka.errors import NoBrokersAvailable
from mock import patch
from nicos.core import ConfigurationError
from nicos.utils.loggers import get_facility_log_handlers
from nicos_ess import get_l... | test/nicos_ess/test_devices/test_log_handler_importer.py |
"""Module to test custom log handlers."""
from logging import Handler
import pytest
pytest.importorskip('kafka.errors')
from kafka.errors import NoBrokersAvailable
from mock import patch
from nicos.core import ConfigurationError
from nicos.utils.loggers import get_facility_log_handlers
from nicos_ess import get_l... | 0.674908 | 0.215898 |
window_size = 60
batch_size = 64
train_set = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)
model = tf.keras.models.Sequential([
tf.keras.layers.Conv1D(filters=32, kernel_size=5, strides = 1, padding='causal', activation='relu', input_shape = [None, 1]),
# Output from above fed to 2 LS... | Day41_42_Sunspots_LSTM_Conv_Dense/sunspots_Conv_LSTM_DNN_Lambda.py | window_size = 60
batch_size = 64
train_set = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)
model = tf.keras.models.Sequential([
tf.keras.layers.Conv1D(filters=32, kernel_size=5, strides = 1, padding='causal', activation='relu', input_shape = [None, 1]),
# Output from above fed to 2 LS... | 0.947284 | 0.57332 |
try:
import onnxruntime as ort
ONNX_RUNTIME = True
except ImportError:
ONNX_RUNTIME = False
import numpy as np
import torch
from transformers import AutoConfig
from transformers.configuration_utils import PretrainedConfig
from transformers.modeling_outputs import SequenceClassifierOutput
from transformer... | src/python/txtai/models/onnx.py | try:
import onnxruntime as ort
ONNX_RUNTIME = True
except ImportError:
ONNX_RUNTIME = False
import numpy as np
import torch
from transformers import AutoConfig
from transformers.configuration_utils import PretrainedConfig
from transformers.modeling_outputs import SequenceClassifierOutput
from transformer... | 0.87576 | 0.266447 |
from flask_login import UserMixin
from werkzeug.security import generate_password_hash,check_password_hash
from datetime import datetime
from . import login_manager
from . import db
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class User(UserMixin, db.Model):
__tablen... | app/models.py | from flask_login import UserMixin
from werkzeug.security import generate_password_hash,check_password_hash
from datetime import datetime
from . import login_manager
from . import db
@login_manager.user_loader
def load_user(user_id):
return User.query.get(int(user_id))
class User(UserMixin, db.Model):
__tablen... | 0.420243 | 0.045205 |
import os
import binascii
import json
from datetime import datetime
import requests
from flask import (
Blueprint, jsonify, redirect, request,
render_template, send_file, session)
from werkzeug.utils import secure_filename
from bbc1.core import bbclib
from bbc1.core.bbc_config import DEFAULT_COR... | fileproof/view.py | import os
import binascii
import json
from datetime import datetime
import requests
from flask import (
Blueprint, jsonify, redirect, request,
render_template, send_file, session)
from werkzeug.utils import secure_filename
from bbc1.core import bbclib
from bbc1.core.bbc_config import DEFAULT_COR... | 0.201656 | 0.050471 |
from .. import db
from datetime import datetime
post_tag = db.Table('post_tags',
db.Column('tag_id', db.Integer, db.ForeignKey('tags.id')),
db.Column('post_id', db.Integer, db.ForeignKey('posts.id'))
)
post_file = db.Table('post_files',
... | app/model/post.py | from .. import db
from datetime import datetime
post_tag = db.Table('post_tags',
db.Column('tag_id', db.Integer, db.ForeignKey('tags.id')),
db.Column('post_id', db.Integer, db.ForeignKey('posts.id'))
)
post_file = db.Table('post_files',
... | 0.334155 | 0.040807 |
import sys
import unittest
import actionlib
import rospy
from control_msgs.msg import (
FollowJointTrajectoryAction,
FollowJointTrajectoryGoal,
FollowJointTrajectoryResult,
)
from std_srvs.srv import Trigger
from trajectory_msgs.msg import JointTrajectoryPoint
from ur_dashboard_msgs.msg import RobotMode,... | ur_robot_driver/test/trajectory_test.py |
import sys
import unittest
import actionlib
import rospy
from control_msgs.msg import (
FollowJointTrajectoryAction,
FollowJointTrajectoryGoal,
FollowJointTrajectoryResult,
)
from std_srvs.srv import Trigger
from trajectory_msgs.msg import JointTrajectoryPoint
from ur_dashboard_msgs.msg import RobotMode,... | 0.509032 | 0.254306 |
import elib_miz
from elib_wx import (
LOGGER, airports_db, exc, weather_dcs_generate, weather_from_icao, weather_from_metar_data,
weather_from_metar_string, weather_from_miz, weather_to_mission, weather_to_miz, weather_translate,
)
from elib_wx.weather_abc import WeatherABC
from elib_wx.weather_dcs import DCSW... | elib_wx/weather.py | import elib_miz
from elib_wx import (
LOGGER, airports_db, exc, weather_dcs_generate, weather_from_icao, weather_from_metar_data,
weather_from_metar_string, weather_from_miz, weather_to_mission, weather_to_miz, weather_translate,
)
from elib_wx.weather_abc import WeatherABC
from elib_wx.weather_dcs import DCSW... | 0.785267 | 0.194463 |
from app.lib.utils.request import request
from app.lib.utils.encode import urlencode, base64encode
from app.lib.utils.common import get_capta, filter_str, get_useragent
class S2_013_BaseVerify:
def __init__(self, url):
self.info = {
'name': 'Struts2 S2-013漏洞,又名CVE-2013-1966漏洞',
'de... | python/app/plugins/http/Struts2/S2_013.py |
from app.lib.utils.request import request
from app.lib.utils.encode import urlencode, base64encode
from app.lib.utils.common import get_capta, filter_str, get_useragent
class S2_013_BaseVerify:
def __init__(self, url):
self.info = {
'name': 'Struts2 S2-013漏洞,又名CVE-2013-1966漏洞',
'de... | 0.304972 | 0.124346 |
from builtins import range
import argparse
from nested_sampling import NestedSampling, MonteCarloWalker, Harmonic, run_nested_sampling, Replica
from nested_sampling.utils.cv_trapezoidal import compute_cv_c
def main():
parser = argparse.ArgumentParser(description="do nested sampling on a p[article in a n-dimension... | examples/harmonic/run_hparticle.py | from builtins import range
import argparse
from nested_sampling import NestedSampling, MonteCarloWalker, Harmonic, run_nested_sampling, Replica
from nested_sampling.utils.cv_trapezoidal import compute_cv_c
def main():
parser = argparse.ArgumentParser(description="do nested sampling on a p[article in a n-dimension... | 0.676299 | 0.376337 |
from django.shortcuts import render, get_object_or_404
from catalog.models import Book, Author, BookInstance, Genre
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
import datetime
from django.http import HttpResponseRedirect
from django.urls import reverse
from catalog.forms i... | catalog/views.py | from django.shortcuts import render, get_object_or_404
from catalog.models import Book, Author, BookInstance, Genre
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
import datetime
from django.http import HttpResponseRedirect
from django.urls import reverse
from catalog.forms i... | 0.662687 | 0.092524 |
import os
import shutil
import os.path as op
from copy import deepcopy
import numpy as np
import pandas as pd
def new_subject(rec_dir, export='000', out_dir_nm='pyplr_analysis'):
'''Get a handle on a new subject for data analysis.
Parameters
----------
rec_dir : str
Full path to a Pupil L... | pyplr/utils.py | import os
import shutil
import os.path as op
from copy import deepcopy
import numpy as np
import pandas as pd
def new_subject(rec_dir, export='000', out_dir_nm='pyplr_analysis'):
'''Get a handle on a new subject for data analysis.
Parameters
----------
rec_dir : str
Full path to a Pupil L... | 0.583322 | 0.311931 |
from time import sleep
from os import getcwd, system
print("""
________________________________________________________________________________________________________________________
/$$$$$$ /$$ /$$ /$$ /$$ /$$ /$$ /$$ /$$$$$$ /$$ /$$
/$$__ $$ | $$ ... | Spawn_NonSteamGame.py | from time import sleep
from os import getcwd, system
print("""
________________________________________________________________________________________________________________________
/$$$$$$ /$$ /$$ /$$ /$$ /$$ /$$ /$$ /$$$$$$ /$$ /$$
/$$__ $$ | $$ ... | 0.175361 | 0.668677 |
from crotchpath import Crotchpath
from path import Path
from footpath import Footpath
import matplotlib as plt
import matplotlib.pyplot as plt
import numpy as np
import math
class Robotpath(Crotchpath):
def __init__(self, start_transform, end_transform, foot_center_to_floor):
super().__init__(start_transfo... | resources/library/pycontrol/src/soccer_pycontrol/robotpath.py | from crotchpath import Crotchpath
from path import Path
from footpath import Footpath
import matplotlib as plt
import matplotlib.pyplot as plt
import numpy as np
import math
class Robotpath(Crotchpath):
def __init__(self, start_transform, end_transform, foot_center_to_floor):
super().__init__(start_transfo... | 0.5144 | 0.664282 |
import logging
import os
import hydra
from hydra.utils import instantiate
from omegaconf import DictConfig, OmegaConf
from pytorch_lightning import Trainer, seed_everything
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning.core.memory import ModelSummary
from pytorch_lightning.loggers imp... | scripts/efficientnets/run.py |
import logging
import os
import hydra
from hydra.utils import instantiate
from omegaconf import DictConfig, OmegaConf
from pytorch_lightning import Trainer, seed_everything
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning.core.memory import ModelSummary
from pytorch_lightning.loggers imp... | 0.774242 | 0.425725 |
__author__ = '<NAME>'
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import pyqtSignal
from model_roles_all import AllRolesModel
from Rota_System.UI.Roles.commands_roles_sublist import CommandExcludeRole, CommandIncludeRole
class SelectionOfRolesModel(AllRolesModel):
"""
used to manipulate a selection of... | Rota_System/UI/Roles/model_roles_sublist.py | __author__ = '<NAME>'
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import pyqtSignal
from model_roles_all import AllRolesModel
from Rota_System.UI.Roles.commands_roles_sublist import CommandExcludeRole, CommandIncludeRole
class SelectionOfRolesModel(AllRolesModel):
"""
used to manipulate a selection of... | 0.540924 | 0.06148 |
from module.tests import setup_database, dataset
from module.server.models.user import User, State, load_user
def test_create_and_add_user(dataset):
"""Creating an user object with parameters"""
db = dataset
# User object
usr = User(
name="Some Name Surname",
phone="+380961122333",
... | module/tests/models/test_user_model.py | from module.tests import setup_database, dataset
from module.server.models.user import User, State, load_user
def test_create_and_add_user(dataset):
"""Creating an user object with parameters"""
db = dataset
# User object
usr = User(
name="Some Name Surname",
phone="+380961122333",
... | 0.487551 | 0.525917 |
import math
import cv2
import gesture_detect.frame_processor as fp
def _get_contours(array):
# 利用findContours检测图像中的轮廓, 其中返回值contours包含了图像中所有轮廓的坐标点
_, contours, _ = cv2.findContours(array, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
return contours
# 根据图像中凹凸点中的 (开始点, 结束点, 远点)的坐标, 利用余弦定理计算两根手指之间的夹角, 其必为锐角, 根据锐角的... | gesture_detect/gesture_detector.py | import math
import cv2
import gesture_detect.frame_processor as fp
def _get_contours(array):
# 利用findContours检测图像中的轮廓, 其中返回值contours包含了图像中所有轮廓的坐标点
_, contours, _ = cv2.findContours(array, cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
return contours
# 根据图像中凹凸点中的 (开始点, 结束点, 远点)的坐标, 利用余弦定理计算两根手指之间的夹角, 其必为锐角, 根据锐角的... | 0.282988 | 0.292267 |
import numpy
from gnuradio import gr
import json,time,os,pmt,binascii
class burst_snr(gr.sync_block):
"""
Computes log scale SNR of burst
'Average Length' is the number of samples for the running average,
should be less than 100. Applies coorection factor based on samples
per symbol since we... | python/burst_snr.py |
import numpy
from gnuradio import gr
import json,time,os,pmt,binascii
class burst_snr(gr.sync_block):
"""
Computes log scale SNR of burst
'Average Length' is the number of samples for the running average,
should be less than 100. Applies coorection factor based on samples
per symbol since we... | 0.610686 | 0.337258 |
from __future__ import absolute_import
import copy
import json
import os
import sys
from contextlib import contextmanager
def update_dict_copy(a, b):
temp = copy.deepcopy(a)
temp.update(b)
return temp
@contextmanager
def inserted_sys_path(path):
if path:
sys.path.insert(0, path)
yiel... | clinto/parsers/base.py | from __future__ import absolute_import
import copy
import json
import os
import sys
from contextlib import contextmanager
def update_dict_copy(a, b):
temp = copy.deepcopy(a)
temp.update(b)
return temp
@contextmanager
def inserted_sys_path(path):
if path:
sys.path.insert(0, path)
yiel... | 0.529263 | 0.120129 |
"""Savitzky-Golaf IAF tests."""
from __future__ import division, print_function
from nose.tools import assert_raises, assert_sequence_equal
from philistine.mne import attenuation_iaf, savgol_iaf
from philistine.mne.utils import _generate_raw
def test_basic_sgf_iaf():
"""Test basic Savitzky-Golay filtered IAF f... | philistine/mne/tests/test_sgf_iaf.py | """Savitzky-Golaf IAF tests."""
from __future__ import division, print_function
from nose.tools import assert_raises, assert_sequence_equal
from philistine.mne import attenuation_iaf, savgol_iaf
from philistine.mne.utils import _generate_raw
def test_basic_sgf_iaf():
"""Test basic Savitzky-Golay filtered IAF f... | 0.932576 | 0.532547 |
begin_unit
comment|'# Copyright (c) 2010 Citrix Systems, Inc.'
nl|'\n'
comment|'# Copyright (c) 2013 OpenStack Foundation'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You... | nova/virt/xenapi/volumeops.py | begin_unit
comment|'# Copyright (c) 2010 Citrix Systems, Inc.'
nl|'\n'
comment|'# Copyright (c) 2013 OpenStack Foundation'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You... | 0.516108 | 0.064594 |
import numpy as np
import skimage.measure
import vsi.utils.geometry_utils as geometry_utils
import vsi.utils.camera_utils as camera_utils
def rectify_calibrated_euclidean(camera0, camera1, img0_shape, img1_shape):
""" compute epipolar rectification homographies by rotating image planes
Parameters
----------
... | python/vsi/utils/stereo_utils.py | import numpy as np
import skimage.measure
import vsi.utils.geometry_utils as geometry_utils
import vsi.utils.camera_utils as camera_utils
def rectify_calibrated_euclidean(camera0, camera1, img0_shape, img1_shape):
""" compute epipolar rectification homographies by rotating image planes
Parameters
----------
... | 0.910008 | 0.558267 |
import turtle
from stack import Stack
from pprint import pprint
class PathFinder:
"""Find path in a maze"""
PATH = "o"
WALL = "*"
USED = "-"
def __init__(self, start: tuple, finish: tuple, maze=None, path=None, draw_maze=False):
self.start_pos = start
self.exit = finish
sel... | path_finder/maze_runner.py | import turtle
from stack import Stack
from pprint import pprint
class PathFinder:
"""Find path in a maze"""
PATH = "o"
WALL = "*"
USED = "-"
def __init__(self, start: tuple, finish: tuple, maze=None, path=None, draw_maze=False):
self.start_pos = start
self.exit = finish
sel... | 0.451327 | 0.364438 |
import sys
try:
ParserException
except NameError,e:
class ParserException(Exception): pass
try:
ParserFatalException
except NameError,e:
class ParserFatalException(ParserException): pass
try:
ParserWarningException
except NameError,e:
class ParserWarningException(ParserException): pass
try:
ActionFailed... | src/fpgParser.py |
import sys
try:
ParserException
except NameError,e:
class ParserException(Exception): pass
try:
ParserFatalException
except NameError,e:
class ParserFatalException(ParserException): pass
try:
ParserWarningException
except NameError,e:
class ParserWarningException(ParserException): pass
try:
ActionFailed... | 0.177205 | 0.30948 |
import sys
from time import time
from time import sleep
import xarray as xr
import boto3
import os
import rioxarray
import rasterio
import argparse
def _split_full_path(bucket_full_path):
if 's3://' in bucket_full_path:
bucket_full_path=bucket_full_path.replace('s3://','')
print(bucket_full_path)
... | api/convert_kelvin_celsius.py |
import sys
from time import time
from time import sleep
import xarray as xr
import boto3
import os
import rioxarray
import rasterio
import argparse
def _split_full_path(bucket_full_path):
if 's3://' in bucket_full_path:
bucket_full_path=bucket_full_path.replace('s3://','')
print(bucket_full_path)
... | 0.163012 | 0.110735 |
from pathlib import Path
from typing import Tuple, Dict, Optional
# noinspection PyProtectedMember
from pandas import DataFrame, read_csv, merge, concat
from linguistic_distributional_models.utils.logging import print_progress
from linguistic_distributional_models.utils.maths import distance, DistanceType
from sensor... | predictors/predictors.py | from pathlib import Path
from typing import Tuple, Dict, Optional
# noinspection PyProtectedMember
from pandas import DataFrame, read_csv, merge, concat
from linguistic_distributional_models.utils.logging import print_progress
from linguistic_distributional_models.utils.maths import distance, DistanceType
from sensor... | 0.925894 | 0.594257 |
import math
import numpy as np
class AdaBoostHelper:
def __init__(self, X, y, n, m):
self.cache = dict()
self.X = X.toarray()
self.y = np.ones(n)
self.y[y == 0] = -1
self.n = n
self.m = m
self.D = np.array([1 / n for i in range(n)])
def calc_yhat(self,... | src/hw3/utils.py | import math
import numpy as np
class AdaBoostHelper:
def __init__(self, X, y, n, m):
self.cache = dict()
self.X = X.toarray()
self.y = np.ones(n)
self.y[y == 0] = -1
self.n = n
self.m = m
self.D = np.array([1 / n for i in range(n)])
def calc_yhat(self,... | 0.306527 | 0.440108 |
import glob
import json
import os.path
import random
import re
import click
import numpy as np
import torchopenl3
from scipy import spatial
from tqdm.auto import tqdm
from preprocess import LENGTH_SAMPLES, ensure_length
from transforms import CONFIG, pydubread
# Is this the model we want?
model = torchopenl3.models.... | modelscores.py | import glob
import json
import os.path
import random
import re
import click
import numpy as np
import torchopenl3
from scipy import spatial
from tqdm.auto import tqdm
from preprocess import LENGTH_SAMPLES, ensure_length
from transforms import CONFIG, pydubread
# Is this the model we want?
model = torchopenl3.models.... | 0.357119 | 0.179279 |
import sys
sys.path.insert(0, "../modules")
"""Create two cusp tipping elements"""
from core.tipping_element import cusp
cusp_element_0 = cusp( a = -4, b = 1, c = 0, x_0 = 0.5 )
cusp_element_1 = cusp( a = -4, b = 1, c = 0, x_0 = 0.5 )
"""Create two linear couplings with strength 0.15 and 0.2"""
from core.coupling imp... | examples/tutorial.py | import sys
sys.path.insert(0, "../modules")
"""Create two cusp tipping elements"""
from core.tipping_element import cusp
cusp_element_0 = cusp( a = -4, b = 1, c = 0, x_0 = 0.5 )
cusp_element_1 = cusp( a = -4, b = 1, c = 0, x_0 = 0.5 )
"""Create two linear couplings with strength 0.15 and 0.2"""
from core.coupling imp... | 0.591015 | 0.541348 |
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from ...utils.api_object import APIObject
from ...utils.types import MISSING
if TYPE_CHECKING:
from typing import List
from ..app.select_menu import SelectOption
from ..message.button import ButtonStyl... | pincer/objects/message/component.py |
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
from ...utils.api_object import APIObject
from ...utils.types import MISSING
if TYPE_CHECKING:
from typing import List
from ..app.select_menu import SelectOption
from ..message.button import ButtonStyl... | 0.849269 | 0.241489 |
import pkg_resources
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from astropy.io import ascii
from astropy.table import QTable, Column
import astropy.units as u
from astropy.convolution import Gaussian1DKernel, convolve
from synphot import SpectralElement
import stsynpho... | measure_extinction/utils/make_obsdata_from_model.py |
import pkg_resources
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from astropy.io import ascii
from astropy.table import QTable, Column
import astropy.units as u
from astropy.convolution import Gaussian1DKernel, convolve
from synphot import SpectralElement
import stsynpho... | 0.804866 | 0.578686 |
import random
import unittest
from subprocess import check_output, Popen, PIPE
from binary_tree import Tree, tree_insert, pre_order, in_order, post_order
def sort_orders(output):
"""
Takes the stdout of the default runners for the robson traversal,
and parses it into the separate lists.
"""
pres ... | tests/test.py |
import random
import unittest
from subprocess import check_output, Popen, PIPE
from binary_tree import Tree, tree_insert, pre_order, in_order, post_order
def sort_orders(output):
"""
Takes the stdout of the default runners for the robson traversal,
and parses it into the separate lists.
"""
pres ... | 0.314261 | 0.426083 |
import sys
import argparse
import numpy as np
import pandas as pd
import geoip2.database
from joblib import load
import datetime
try:
from config import *
from config import __prog__, __version__
except:
print('* Config file not found! Error!')
sys.exit(1)
try:
from utils import *
except:
prin... | firewall_log_analysis.py | import sys
import argparse
import numpy as np
import pandas as pd
import geoip2.database
from joblib import load
import datetime
try:
from config import *
from config import __prog__, __version__
except:
print('* Config file not found! Error!')
sys.exit(1)
try:
from utils import *
except:
prin... | 0.229535 | 0.101145 |
from datetime import datetime
from shopyoapi.init import db
from shopyoapi.models import PkModel
from modules.box__ecommerce.product.models import Product
class Order(db.Model):
__tablename__ = "orders"
id = db.Column(db.Integer, primary_key=True)
time = db.Column(db.DateTime, default=datetime.now())
... | shopyo/modules/box__ecommerce/shop/models.py | from datetime import datetime
from shopyoapi.init import db
from shopyoapi.models import PkModel
from modules.box__ecommerce.product.models import Product
class Order(db.Model):
__tablename__ = "orders"
id = db.Column(db.Integer, primary_key=True)
time = db.Column(db.DateTime, default=datetime.now())
... | 0.377426 | 0.075927 |
from PIL import Image as im
from helper.functions import loadOBJ
import numpy as np, sys, os
class Template:
def saveImageTraining(self,avgImageSave=True):
pass
def loadImage(self):
pass
def save(self):
pass
def getRawRepr(self):
return self.__rawRepr
def setRaw... | baseClasses/Template.py | from PIL import Image as im
from helper.functions import loadOBJ
import numpy as np, sys, os
class Template:
def saveImageTraining(self,avgImageSave=True):
pass
def loadImage(self):
pass
def save(self):
pass
def getRawRepr(self):
return self.__rawRepr
def setRaw... | 0.289874 | 0.143397 |
import pprint
import re # noqa: F401
import six
class WEntryLinkInfo(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the... | laserfiche_api/models/w_entry_link_info.py | import pprint
import re # noqa: F401
import six
class WEntryLinkInfo(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the... | 0.693992 | 0.065038 |
from prometheus_client import Gauge
from app.prom.database import util as db_util
from app.prom.metrics.abstract_metric import AbstractMetric
TABLESPACE = '''tablespace'''
TYPE = '''type'''
CURR_BYTES = '''curr_bytes'''
USED_BYTES = '''used_bytes'''
MAX_BYTES = '''max_bytes'''
FREE_BYTES = '''free'''
AUTOEXTENSIBLE =... | app/prom/metrics/general/tablespace.py | from prometheus_client import Gauge
from app.prom.database import util as db_util
from app.prom.metrics.abstract_metric import AbstractMetric
TABLESPACE = '''tablespace'''
TYPE = '''type'''
CURR_BYTES = '''curr_bytes'''
USED_BYTES = '''used_bytes'''
MAX_BYTES = '''max_bytes'''
FREE_BYTES = '''free'''
AUTOEXTENSIBLE =... | 0.563618 | 0.140897 |
import hashlib
from constants import *
from XXX import big
from XXX import curve
from XXX.ecp import *
# Calculate a public/private EC GF(p) key pair.
def ECP_KeyPairGenerate(S):
G = generator()
if S is None:
s = big.rand(curve.r)
else:
s = big.from_bytes(S) % curve.r
Y = s * G
... | version3/python/ecdh.py |
import hashlib
from constants import *
from XXX import big
from XXX import curve
from XXX.ecp import *
# Calculate a public/private EC GF(p) key pair.
def ECP_KeyPairGenerate(S):
G = generator()
if S is None:
s = big.rand(curve.r)
else:
s = big.from_bytes(S) % curve.r
Y = s * G
... | 0.535098 | 0.285764 |
from discord import Forbidden
from discord.ext import commands
from .emoji import SEE_DM
from .i18n import i18n, embed
class Kenny2help(commands.HelpCommand):
def get_destination(self):
return self.context.author
async def send_the_help(self, emb):
try:
await self.get_destination().send(embed=emb)
except F... | kenny2automate/help.py | from discord import Forbidden
from discord.ext import commands
from .emoji import SEE_DM
from .i18n import i18n, embed
class Kenny2help(commands.HelpCommand):
def get_destination(self):
return self.context.author
async def send_the_help(self, emb):
try:
await self.get_destination().send(embed=emb)
except F... | 0.192009 | 0.08886 |
from __future__ import annotations
import json
import os
import math
from typing import Dict, List, Set, Tuple
ColorEntry = Tuple[float, str, Tuple[int, int, int]]
class DuplicateNameError(Exception):
"""Custom error for duplicate asset name"""
pass
# Constants
COLOR_DIFFERENCE_THRESHOLD = 5
EXTENSION_TEMP... | oneHookLibrary/Script/asset_script_v2.py | from __future__ import annotations
import json
import os
import math
from typing import Dict, List, Set, Tuple
ColorEntry = Tuple[float, str, Tuple[int, int, int]]
class DuplicateNameError(Exception):
"""Custom error for duplicate asset name"""
pass
# Constants
COLOR_DIFFERENCE_THRESHOLD = 5
EXTENSION_TEMP... | 0.841109 | 0.159381 |
"""Types which provide many builds and composite them into a single binary."""
import logging
import pathlib
import subprocess
import zmake.build_config as build_config
import zmake.multiproc
import zmake.util as util
def _write_dts_file(dts_file, config_header, output_bin, ro_filename, rw_filename):
"""Generate... | zephyr/zmake/zmake/output_packers.py | """Types which provide many builds and composite them into a single binary."""
import logging
import pathlib
import subprocess
import zmake.build_config as build_config
import zmake.multiproc
import zmake.util as util
def _write_dts_file(dts_file, config_header, output_bin, ro_filename, rw_filename):
"""Generate... | 0.852644 | 0.239216 |
# Inspired by:
# https://github.com/aubio/aubio/issues/78
import aubio
import numpy
import os
import pyaudio
import shutil
import sys
from colors import color
from datetime import datetime
MIDRANGE_LOW = 160
MIDRANGE_HIGH = 180
SAMPLES = 1024
def main():
stream = get_audio_stream()
pDetection = aubio.pitc... | pitch.py |
# Inspired by:
# https://github.com/aubio/aubio/issues/78
import aubio
import numpy
import os
import pyaudio
import shutil
import sys
from colors import color
from datetime import datetime
MIDRANGE_LOW = 160
MIDRANGE_HIGH = 180
SAMPLES = 1024
def main():
stream = get_audio_stream()
pDetection = aubio.pitc... | 0.49048 | 0.349311 |
## Using data from ArtGAN Github and after running cleanGenreCsv.py to get a cleaned version of the ArtGAN genre CSV
from fastai.vision import *
import pathlib
import PIL
import pandas as pd
import matplotlib.pyplot as plt
import numpy
import warnings
# Prevent warnings from appearing more than once
warnings.filte... | classify_genre.py |
## Using data from ArtGAN Github and after running cleanGenreCsv.py to get a cleaned version of the ArtGAN genre CSV
from fastai.vision import *
import pathlib
import PIL
import pandas as pd
import matplotlib.pyplot as plt
import numpy
import warnings
# Prevent warnings from appearing more than once
warnings.filte... | 0.339499 | 0.49109 |
import rlkit.torch.pytorch_util as ptu
## Use GPU accelerator
ptu.set_gpu_mode(False)
import argparse
import numpy as np
from rlkit.data_management.env_replay_buffer import EnvReplayBuffer
from rlkit.launchers.launcher_util import setup_logger
from rlkit.samplers.data_collector.path_collector import RiskConditionedP... | model/train_risk_conditioned_sac.py | import rlkit.torch.pytorch_util as ptu
## Use GPU accelerator
ptu.set_gpu_mode(False)
import argparse
import numpy as np
from rlkit.data_management.env_replay_buffer import EnvReplayBuffer
from rlkit.launchers.launcher_util import setup_logger
from rlkit.samplers.data_collector.path_collector import RiskConditionedP... | 0.561936 | 0.464416 |
r"""
Building the required library in this example requires a source distribution
of NumPy or clone of the NumPy git repository since distributions.c is not
included in binary distributions.
On *nix, execute in numpy/random/src/distributions
export ${PYTHON_VERSION}=3.8 # Python version
export PYTHON_INCLUDE=... | libs/numpy/random/_examples/numba/extending_distributions.py | r"""
Building the required library in this example requires a source distribution
of NumPy or clone of the NumPy git repository since distributions.c is not
included in binary distributions.
On *nix, execute in numpy/random/src/distributions
export ${PYTHON_VERSION}=3.8 # Python version
export PYTHON_INCLUDE=... | 0.617628 | 0.261278 |
from enum import Enum
from itertools import cycle
from operator import itemgetter
class Direction(Enum):
LEFT = (-1, 0)
RIGHT = (1, 0)
UP = (0, -1)
DOWN = (0, 1)
CART_DIRECTIONS = {
'<': Direction.LEFT,
'>': Direction.RIGHT,
'^': Direction.UP,
'v': Direction.DOWN
}
CART_DIRECTIONS_S... | 2018/day_13.py | from enum import Enum
from itertools import cycle
from operator import itemgetter
class Direction(Enum):
LEFT = (-1, 0)
RIGHT = (1, 0)
UP = (0, -1)
DOWN = (0, 1)
CART_DIRECTIONS = {
'<': Direction.LEFT,
'>': Direction.RIGHT,
'^': Direction.UP,
'v': Direction.DOWN
}
CART_DIRECTIONS_S... | 0.560734 | 0.283298 |
from feature_reduction.feature_analyser import visualise_features_LDA
import os
from utils import handyman
import trainer as t
from feature_extraction import extractor
import pandas as pd
if __name__ == "__main__":
#load data
rfe = handyman.load_pickle(os.path.join("Results", "LS", "user_with_activities", "ran... | main_LS_analyze_reduction.py | from feature_reduction.feature_analyser import visualise_features_LDA
import os
from utils import handyman
import trainer as t
from feature_extraction import extractor
import pandas as pd
if __name__ == "__main__":
#load data
rfe = handyman.load_pickle(os.path.join("Results", "LS", "user_with_activities", "ran... | 0.239616 | 0.209712 |
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form ... | geoportal/tests/functional/test_xsd.py |
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form ... | 0.657978 | 0.116613 |