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 __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from joint_vae import multimodal_elbo_loss
from joint_vae import encoder_decoder
import convolutional_multi_vae
flags = tf.flags
FLAGS = tf.app.flags.FLAGS
# TODO(vrama): Provide sa... | experiments/kronecker_multi_vae.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from joint_vae import multimodal_elbo_loss
from joint_vae import encoder_decoder
import convolutional_multi_vae
flags = tf.flags
FLAGS = tf.app.flags.FLAGS
# TODO(vrama): Provide sa... | 0.822474 | 0.140956 |
import os
import unittest
from PyQt5.QtTest import QTest
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import Qt, QRect
from Paint4Brains.GUI.MainWindow import MainWindow
from Paint4Brains.GUI.MainWidget import MainWidget
class TestMainWindow(unittest.TestCase):
"""Test a few GUI methods.
Due to... | tests/test_GUI.py | import os
import unittest
from PyQt5.QtTest import QTest
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import Qt, QRect
from Paint4Brains.GUI.MainWindow import MainWindow
from Paint4Brains.GUI.MainWidget import MainWidget
class TestMainWindow(unittest.TestCase):
"""Test a few GUI methods.
Due to... | 0.533154 | 0.306047 |
import re,sys
class AuthenBase(object):
"""
Basisklasse fuer Authentifizierung
Die Autentifizierung basiert auf einer
Sessionvariable namens user. Ist diese
gesetzt gilt der Benutzer als angemeldet
"""
user = None
session = None
usrrights = None
userlist = {}
db = None
def __i... | WEB-INF/mframe/authenbase.py | import re,sys
class AuthenBase(object):
"""
Basisklasse fuer Authentifizierung
Die Autentifizierung basiert auf einer
Sessionvariable namens user. Ist diese
gesetzt gilt der Benutzer als angemeldet
"""
user = None
session = None
usrrights = None
userlist = {}
db = None
def __i... | 0.196017 | 0.078997 |
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from oca.models.base_model_ import Model
from oca import util
class HomeScreenContent(Model):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generato... | services/oca3/oca/models/home_screen_content.py |
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from oca.models.base_model_ import Model
from oca import util
class HomeScreenContent(Model):
"""NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generato... | 0.83025 | 0.082846 |
import torch
import torch.nn as nn
class CostVolume(nn.Module):
def __init__(self, max_disp, feature_similarity='correlation'):
"""Construct cost volume based on different
similarity measures
Args:
max_disp: max disparity candidate
feature_similarity: type of simil... | ofa/stereo_matching/networks/cost.py | import torch
import torch.nn as nn
class CostVolume(nn.Module):
def __init__(self, max_disp, feature_similarity='correlation'):
"""Construct cost volume based on different
similarity measures
Args:
max_disp: max disparity candidate
feature_similarity: type of simil... | 0.85555 | 0.507141 |
import os
import traceback
from pathlib import Path
import zoopla as z
import albert as v0
__title__ = "Zoopla - Search Properties"
__version__ = "0.4.0"
__triggers__ = "z "
__authors__ = "<NAME>"
__homepage__ = "https://github.com/bergercookie/zoopla-albert-plugin"
iconPath = v0.iconLookup("zoopla")
if not iconPa... | plugins/zoopla/__init__.py |
import os
import traceback
from pathlib import Path
import zoopla as z
import albert as v0
__title__ = "Zoopla - Search Properties"
__version__ = "0.4.0"
__triggers__ = "z "
__authors__ = "<NAME>"
__homepage__ = "https://github.com/bergercookie/zoopla-albert-plugin"
iconPath = v0.iconLookup("zoopla")
if not iconPa... | 0.239616 | 0.111725 |
# NB: uses scandir for speed, on OPALS Shell an install might be required with
# python -m pip install scandir --user
# Dependencies
import os
import glob
import pandas
import re
import scandir
import copy
import sys
import subprocess
import shutil
from dklidar import settings
## 1) Determine output folder structure... | scripts/fill_processing_gaps.py |
# NB: uses scandir for speed, on OPALS Shell an install might be required with
# python -m pip install scandir --user
# Dependencies
import os
import glob
import pandas
import re
import scandir
import copy
import sys
import subprocess
import shutil
from dklidar import settings
## 1) Determine output folder structure... | 0.166608 | 0.16637 |
import logging
from functools import partial
import requests
from rest_tools.server import from_environment
from rest_tools.client import RestClient
def get_token(url, client_id, client_secret, client_realm='master'):
url = f'{url}/auth/realms/{client_realm}/protocol/openid-connect/token'
args = {
'g... | krs/token.py | import logging
from functools import partial
import requests
from rest_tools.server import from_environment
from rest_tools.client import RestClient
def get_token(url, client_id, client_secret, client_realm='master'):
url = f'{url}/auth/realms/{client_realm}/protocol/openid-connect/token'
args = {
'g... | 0.411347 | 0.035046 |
import numpy as np
import scipy
from scipy.spatial.transform import Rotation as Rot
import cv2
import json
from tqdm import tqdm
DEBUG = False
def get_distance(p4, p6, cam_proj_4, cam_proj_6):
'''
calculate minimum distance with epipolar constraint
Args:
p4: key point on camera 4 -- shape: (3,)
... | matching/pose_optimize/multiview_geo.py | import numpy as np
import scipy
from scipy.spatial.transform import Rotation as Rot
import cv2
import json
from tqdm import tqdm
DEBUG = False
def get_distance(p4, p6, cam_proj_4, cam_proj_6):
'''
calculate minimum distance with epipolar constraint
Args:
p4: key point on camera 4 -- shape: (3,)
... | 0.739046 | 0.622646 |
import swig_decoders
class Scorer(swig_decoders.Scorer):
"""Wrapper for Scorer.
:param alpha: 与语言模型相关的参数。当alpha = 0时不要使用语言模型
:type alpha: float
:param beta: 与字计数相关的参数。当beta = 0时不要使用统计字
:type beta: float
:model_path: 语言模型的路径
:type model_path: str
"""
def __init__(self, alpha, bet... | masr/masr/decoders/swig_wrapper.py |
import swig_decoders
class Scorer(swig_decoders.Scorer):
"""Wrapper for Scorer.
:param alpha: 与语言模型相关的参数。当alpha = 0时不要使用语言模型
:type alpha: float
:param beta: 与字计数相关的参数。当beta = 0时不要使用统计字
:type beta: float
:model_path: 语言模型的路径
:type model_path: str
"""
def __init__(self, alpha, bet... | 0.631708 | 0.537952 |
import sys
import rlglue.network.Network as Network
from rlglue.types import Action
from rlglue.types import Observation
class ClientAgent:
kUnknownMessage = "Unknown Message: "
network = None
agent = None
# (agent) -> void
def __init__(self, agent):
self.agen... | rlglue/agent/ClientAgent.py |
import sys
import rlglue.network.Network as Network
from rlglue.types import Action
from rlglue.types import Observation
class ClientAgent:
kUnknownMessage = "Unknown Message: "
network = None
agent = None
# (agent) -> void
def __init__(self, agent):
self.agen... | 0.315841 | 0.193623 |
from tkinter import *
from utilitarios import verificar_colar
from Calculadora import Calculadora as calc
from pyperclip import copy, paste
# Janela
app = Tk()
app.geometry('300x380')
app.resizable(False, False)
app.title('Calculadora')
# Display
frame = Frame(app, bg='white', borderwidth=1, relief='solid', width=2... | interface.py | from tkinter import *
from utilitarios import verificar_colar
from Calculadora import Calculadora as calc
from pyperclip import copy, paste
# Janela
app = Tk()
app.geometry('300x380')
app.resizable(False, False)
app.title('Calculadora')
# Display
frame = Frame(app, bg='white', borderwidth=1, relief='solid', width=2... | 0.422266 | 0.146179 |
from queue import Queue, Empty
from threading import *
def singleton(cls):
_instance = {}
def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls]
return _singleton
@singleton
class MessageBus(object):
def __ini... | app/lib/message_bus.py | from queue import Queue, Empty
from threading import *
def singleton(cls):
_instance = {}
def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls]
return _singleton
@singleton
class MessageBus(object):
def __ini... | 0.432902 | 0.075007 |
import keras_tuner as kt
from tensorflow import keras, ones
from sklearned.tasks.skatertasks import cached_surrogate_data
from pprint import pprint
from functools import partial
SLUGGISH_MOVING_AVERAGE_BEST = {'test_error': 0.04533515537923001,
'train_error': 0.011145835494209172,
... | experiments_on_skaters_old_style/hyperband_slow_precision_ema_ensemble.py | import keras_tuner as kt
from tensorflow import keras, ones
from sklearned.tasks.skatertasks import cached_surrogate_data
from pprint import pprint
from functools import partial
SLUGGISH_MOVING_AVERAGE_BEST = {'test_error': 0.04533515537923001,
'train_error': 0.011145835494209172,
... | 0.78695 | 0.325279 |
import datetime
import logging
import os
from pathlib import Path
import shutil
import arrow
import matplotlib.backends.backend_agg
import matplotlib.figure
from nemo_nowcast import NowcastWorker
import netCDF4
import numpy
import pytz
from salishsea_tools import nc_tools
from nowcast import lib, residuals
NAME = "m... | nowcast/workers/make_ssh_files.py | import datetime
import logging
import os
from pathlib import Path
import shutil
import arrow
import matplotlib.backends.backend_agg
import matplotlib.figure
from nemo_nowcast import NowcastWorker
import netCDF4
import numpy
import pytz
from salishsea_tools import nc_tools
from nowcast import lib, residuals
NAME = "m... | 0.601477 | 0.208743 |
import numpy as np
import tensorflow as tf
class ShapeDtype(object):
"""A NumPy ndarray-like object abstracted as shape and dtype.
Main use is for representing input and output signatures.
"""
__slots__ = ['shape', 'dtype']
def __init__(self, shape, dtype=np.float32):
"""Creates a `ShapeDtype` instanc... | trax/shapes.py | import numpy as np
import tensorflow as tf
class ShapeDtype(object):
"""A NumPy ndarray-like object abstracted as shape and dtype.
Main use is for representing input and output signatures.
"""
__slots__ = ['shape', 'dtype']
def __init__(self, shape, dtype=np.float32):
"""Creates a `ShapeDtype` instanc... | 0.929975 | 0.758824 |
from adafruit_servokit import ServoKit
import rospy
import sensor_msgs.msg
from sensor_msgs.msg import LaserScan
from std_msgs.msg import Float32MultiArray
import message_filters
import time
kit = ServoKit(channels = 16)
def callback(msg1, msg2):
"""
INPUT: msg1: data from cam_values node, msg2:... | listener.py | from adafruit_servokit import ServoKit
import rospy
import sensor_msgs.msg
from sensor_msgs.msg import LaserScan
from std_msgs.msg import Float32MultiArray
import message_filters
import time
kit = ServoKit(channels = 16)
def callback(msg1, msg2):
"""
INPUT: msg1: data from cam_values node, msg2:... | 0.393735 | 0.223451 |
from migen import *
from litex.soc.cores.clock.common import *
from litex.soc.cores.clock.xilinx_common import *
# Xilinx / Spartan6 --------------------------------------------------------------------------------
class S6PLL(XilinxClocking):
nclkouts_max = 6
clkin_freq_range = (19e6, 540e6)
def __init... | litex/soc/cores/clock/xilinx_s6.py |
from migen import *
from litex.soc.cores.clock.common import *
from litex.soc.cores.clock.xilinx_common import *
# Xilinx / Spartan6 --------------------------------------------------------------------------------
class S6PLL(XilinxClocking):
nclkouts_max = 6
clkin_freq_range = (19e6, 540e6)
def __init... | 0.483405 | 0.140248 |
import sys
import argparse
_SEX = {
'0': 'UNKNOWN',
'1': 'MALE',
'2': 'FEMALE'
}
_KAR_SEX = {
'0': None,
'1': 'XY',
'2': 'XX'
}
_VARIABLE_FIELDS = ['Relationship', 'Siblings', 'Second Order', 'Third Order', 'Other Comments']
FNAME_TEMPLATE = 'ALL.chr{}.shapeit2_integrated_snvindels_v2a_2702... | opencga-app/app/misc/demo/1000G_yml_generator.py |
import sys
import argparse
_SEX = {
'0': 'UNKNOWN',
'1': 'MALE',
'2': 'FEMALE'
}
_KAR_SEX = {
'0': None,
'1': 'XY',
'2': 'XX'
}
_VARIABLE_FIELDS = ['Relationship', 'Siblings', 'Second Order', 'Third Order', 'Other Comments']
FNAME_TEMPLATE = 'ALL.chr{}.shapeit2_integrated_snvindels_v2a_2702... | 0.281504 | 0.09611 |
import os.path
import re
from collections import deque
HERE = os.path.dirname(os.path.abspath(__file__))
def create_bot(source, low, high):
def bot(namespace):
chips = namespace.get(source)
if chips is not None and len(chips) > 1:
return {high: max(chips), low: min(chips)}
bot.__... | 2016/puzzle10.py | import os.path
import re
from collections import deque
HERE = os.path.dirname(os.path.abspath(__file__))
def create_bot(source, low, high):
def bot(namespace):
chips = namespace.get(source)
if chips is not None and len(chips) > 1:
return {high: max(chips), low: min(chips)}
bot.__... | 0.279042 | 0.35869 |
import pandas as pd
import numpy as np
from node import Node
from tree import Tree
from func import module
root2 = Node("Hello", None, None, None)
objModule = module()
class cart:
def Cart(self, numOfnode, d, a, target_a):
attribute_value = []
arr1 = []
arr2 = []
gini = []
... | 170227_Pattern_Lab_01/CART.py | import pandas as pd
import numpy as np
from node import Node
from tree import Tree
from func import module
root2 = Node("Hello", None, None, None)
objModule = module()
class cart:
def Cart(self, numOfnode, d, a, target_a):
attribute_value = []
arr1 = []
arr2 = []
gini = []
... | 0.182717 | 0.328206 |
import os
import sys
import pathlib
import numpy as np
import itertools
import pandas as pd
from pandas import ExcelWriter
path = pathlib.Path(os.getcwd())
module_path = str(path.parent) + '/'
sys.path.append(module_path)
import pymdp.core.utils as utils
from pymdp.core.utils import create_B_matrix_stubs, get_model... | examples/B_matrix_demo.py | import os
import sys
import pathlib
import numpy as np
import itertools
import pandas as pd
from pandas import ExcelWriter
path = pathlib.Path(os.getcwd())
module_path = str(path.parent) + '/'
sys.path.append(module_path)
import pymdp.core.utils as utils
from pymdp.core.utils import create_B_matrix_stubs, get_model... | 0.318167 | 0.206974 |
from .order_generator import OrderGenWInteract
from .model_strategy import WeightStrategyBase
import copy
class SoftTopkStrategy(WeightStrategyBase):
def __init__(
self,
model,
dataset,
topk,
order_generator_cls_or_obj=OrderGenWInteract,
max_sold_weight=1.0,
... | qlib/contrib/strategy/cost_control.py | from .order_generator import OrderGenWInteract
from .model_strategy import WeightStrategyBase
import copy
class SoftTopkStrategy(WeightStrategyBase):
def __init__(
self,
model,
dataset,
topk,
order_generator_cls_or_obj=OrderGenWInteract,
max_sold_weight=1.0,
... | 0.552057 | 0.265562 |
# Exercício de avaliação de expressão aritmética.
# Só podem ser usadas as estruturas Pilha e Fila implementadas em aulas anteriores.
# Deve ter análise de tempo e espaço para função avaliação
from aula4.pilha import Pilha
from aula5.fila import Fila
class ErroLexico(Exception):
pass
class ErroSintatico(Except... | aula5/exercicio.py |
# Exercício de avaliação de expressão aritmética.
# Só podem ser usadas as estruturas Pilha e Fila implementadas em aulas anteriores.
# Deve ter análise de tempo e espaço para função avaliação
from aula4.pilha import Pilha
from aula5.fila import Fila
class ErroLexico(Exception):
pass
class ErroSintatico(Except... | 0.204779 | 0.540378 |
import csv
from math import floor
import sys
def find_extremes(d):
""" Input: a dict key:value
Output: min and max values from all elements in the dict
"""
values = d.values()
return min(values), max(values)
def group_by_attributes(fonts):
""" Classify a set of fonts by their ammount of black ink (p... | util.py | import csv
from math import floor
import sys
def find_extremes(d):
""" Input: a dict key:value
Output: min and max values from all elements in the dict
"""
values = d.values()
return min(values), max(values)
def group_by_attributes(fonts):
""" Classify a set of fonts by their ammount of black ink (p... | 0.334046 | 0.372619 |
# Author:: <NAME> (mailto:<EMAIL>)
"""
Project Configuration for Yellowstone Variables
"""
import logging
from typing import Dict, List, Tuple
from .data_columns import DataColumns
logger = logging.getLogger(__name__)
class YellowstoneConfig(DataColumns):
"""
Variable Storage Class
"""
API_S... | camply/config/yellowstone_config.py |
# Author:: <NAME> (mailto:<EMAIL>)
"""
Project Configuration for Yellowstone Variables
"""
import logging
from typing import Dict, List, Tuple
from .data_columns import DataColumns
logger = logging.getLogger(__name__)
class YellowstoneConfig(DataColumns):
"""
Variable Storage Class
"""
API_S... | 0.697197 | 0.136897 |
import psycopg2
import pandas as pd
def query(predicted_class):
db_name = 'curly_db'
username = 'ubuntu'
con = None
con = psycopg2.connect(database = db_name, user = username, host='localhost')
# Query the product database for products for the given class
sql_query ="""
SELECT products_... | query.py | import psycopg2
import pandas as pd
def query(predicted_class):
db_name = 'curly_db'
username = 'ubuntu'
con = None
con = psycopg2.connect(database = db_name, user = username, host='localhost')
# Query the product database for products for the given class
sql_query ="""
SELECT products_... | 0.197444 | 0.177205 |
import web
import json
from yummly import Yummly
from datetime import datetime, date, time
urls= (
'/', 'index',
'/checkin','checkin',
'/status','status',
'/frgData','frgData',
'/frgupcData','frgupcData',
'/slist','slist',
'/rec','rec'
)
db = web.database(dbn='sqlite', db='test.sqlite')
class index:
def GET... | Web/testupc.py | import web
import json
from yummly import Yummly
from datetime import datetime, date, time
urls= (
'/', 'index',
'/checkin','checkin',
'/status','status',
'/frgData','frgData',
'/frgupcData','frgupcData',
'/slist','slist',
'/rec','rec'
)
db = web.database(dbn='sqlite', db='test.sqlite')
class index:
def GET... | 0.064161 | 0.07024 |
from __future__ import annotations
__all__ = ['workflow_derivative_couplings']
import os
from os.path import join
from typing import List, Tuple, Union
from noodles import gather, schedule, unpack
from noodles.interface import PromisedObject
from qmflows.type_hints import PathLike
from .. import logger
from ..commo... | nanoqm/workflows/workflow_coupling.py | from __future__ import annotations
__all__ = ['workflow_derivative_couplings']
import os
from os.path import join
from typing import List, Tuple, Union
from noodles import gather, schedule, unpack
from noodles.interface import PromisedObject
from qmflows.type_hints import PathLike
from .. import logger
from ..commo... | 0.913315 | 0.277497 |
import unittest
import os
from rkd.api.testing import BasicTestingCase
from rkd.test import TestTask
from rkd.contract import ArgumentEnv
CURRENT_SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))
class TestTaskInterface(BasicTestingCase):
def test_table(self):
"""Simply test table() - the table... | test/test_contract_task_interface.py |
import unittest
import os
from rkd.api.testing import BasicTestingCase
from rkd.test import TestTask
from rkd.contract import ArgumentEnv
CURRENT_SCRIPT_PATH = os.path.dirname(os.path.realpath(__file__))
class TestTaskInterface(BasicTestingCase):
def test_table(self):
"""Simply test table() - the table... | 0.631026 | 0.431944 |
import urllib2,sys,time,datetime,os,pymysql.cursors
from setting import headers, domain, start_url, file_output
read_file=open("readed.txt","a")
alldatas={}
readed_file = open("readed.txt","r")
for lines in readed_file:
data = lines.strip("\n")
alldatas[data]="readed"
connection = pymysql.connect(host... | YouXin/app.py | import urllib2,sys,time,datetime,os,pymysql.cursors
from setting import headers, domain, start_url, file_output
read_file=open("readed.txt","a")
alldatas={}
readed_file = open("readed.txt","r")
for lines in readed_file:
data = lines.strip("\n")
alldatas[data]="readed"
connection = pymysql.connect(host... | 0.037204 | 0.126138 |
import logging
import hashlib, os
from itsdangerous import BadData, SignatureExpired, URLSafeTimedSerializer
from werkzeug.security import safe_str_cmp
from flask import abort, redirect, url_for
from flaskcbv.response import Response
from generic import TemplateView
try:
from flask import current_app
secret_... | flaskcbv/view/crud.py | import logging
import hashlib, os
from itsdangerous import BadData, SignatureExpired, URLSafeTimedSerializer
from werkzeug.security import safe_str_cmp
from flask import abort, redirect, url_for
from flaskcbv.response import Response
from generic import TemplateView
try:
from flask import current_app
secret_... | 0.375363 | 0.071074 |
import pandas as pd
import numpy as np
import pickle
import os
import re
def pkl_to_df(model_dir):
''' Perform ETL on all models in a specified directory (that exist as .pkl files), transform into tidy formatted DataFrame. Training loss is averaged over chunks to a per-epoch level.'''
try:
os.chdir(os... | src/visualization/model_etl.py | import pandas as pd
import numpy as np
import pickle
import os
import re
def pkl_to_df(model_dir):
''' Perform ETL on all models in a specified directory (that exist as .pkl files), transform into tidy formatted DataFrame. Training loss is averaged over chunks to a per-epoch level.'''
try:
os.chdir(os... | 0.341692 | 0.305956 |
from django.db import models
from django.contrib.auth.models import User
from dateutil.rrule import *
from datetime import datetime, timedelta
from django.utils.timezone import utc
from django.forms.util import from_current_timezone
# Create your models here.
FREQUENCY_CHOICES = (
('YEARLY','yearly'),
('MONTH... | calendar_events/models.py | from django.db import models
from django.contrib.auth.models import User
from dateutil.rrule import *
from datetime import datetime, timedelta
from django.utils.timezone import utc
from django.forms.util import from_current_timezone
# Create your models here.
FREQUENCY_CHOICES = (
('YEARLY','yearly'),
('MONTH... | 0.603465 | 0.194578 |
import json
import time
from io import BytesIO
from pony.orm import db_session, commit
import config
import utils
from core.exceptions import ParamNotValid
from core.log import logger
from core.models import VmImageInfoMapper
from core.openstack_utils import create_glance_client
from core.openstack_utils import creat... | osplugin/service/vm_image_service.py | import json
import time
from io import BytesIO
from pony.orm import db_session, commit
import config
import utils
from core.exceptions import ParamNotValid
from core.log import logger
from core.models import VmImageInfoMapper
from core.openstack_utils import create_glance_client
from core.openstack_utils import creat... | 0.421314 | 0.086478 |
from __future__ import division
import numpy as np
from ..base import Camera
from ...util import transforms
class NDCCamera(Camera):
""" Camera that presents a view on the world in normalized device
coordinates (-1..1).
"""
pass
class PixelCamera(Camera):
""" Camera that presents a view on t... | vispy/scene/cameras/cams2d.py | from __future__ import division
import numpy as np
from ..base import Camera
from ...util import transforms
class NDCCamera(Camera):
""" Camera that presents a view on the world in normalized device
coordinates (-1..1).
"""
pass
class PixelCamera(Camera):
""" Camera that presents a view on t... | 0.897582 | 0.699424 |
import copy
import sys
from typing import Any, Callable, Dict, Optional, Tuple
import numpy as np
from tqdm import tqdm
from .implicit import ExplicitIntegrator, ImplicitIntegrator
from .integrator import Integrator
class PredictorCorrectorIntegrator(Integrator):
@staticmethod
def __check_init_args(predicto... | dz/dz-05/src/integrators/predictor_corrector.py | import copy
import sys
from typing import Any, Callable, Dict, Optional, Tuple
import numpy as np
from tqdm import tqdm
from .implicit import ExplicitIntegrator, ImplicitIntegrator
from .integrator import Integrator
class PredictorCorrectorIntegrator(Integrator):
@staticmethod
def __check_init_args(predicto... | 0.709523 | 0.182262 |
# set up linting conditions
# pylint: disable = c-extension-no-member
# pylint: disable = import-error
import subprocess
import os
import PyQt5.QtCore as qc
import numpy as np
import ffmpeg
from cgt.io.ffmpegbase import FfmpegBase
from cgt.util.framestats import FrameStats, VideoIntensityStats
class VideoAnalyser(F... | cgt/io/videoanalyser.py | # set up linting conditions
# pylint: disable = c-extension-no-member
# pylint: disable = import-error
import subprocess
import os
import PyQt5.QtCore as qc
import numpy as np
import ffmpeg
from cgt.io.ffmpegbase import FfmpegBase
from cgt.util.framestats import FrameStats, VideoIntensityStats
class VideoAnalyser(F... | 0.603114 | 0.267232 |
"""Defines the abstract register class."""
from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Iterable, Mapping
from collections.abc import Sequence as abcSequence
from typing import (
TYPE_CHECKING,
Any,
NamedTuple,
Optional,
Type,
TypeVar,
... | pulser/register/base_register.py | """Defines the abstract register class."""
from __future__ import annotations
from abc import ABC, abstractmethod
from collections.abc import Iterable, Mapping
from collections.abc import Sequence as abcSequence
from typing import (
TYPE_CHECKING,
Any,
NamedTuple,
Optional,
Type,
TypeVar,
... | 0.969928 | 0.40987 |
from thetis import *
# define mesh
lx = 16
ly = 1.1
nx = lx*5
ny = 5
mesh2d = RectangleMesh(nx, ny, lx, ly)
x, y = SpatialCoordinate(mesh2d)
# define function spaces
V = get_functionspace(mesh2d, "CG", 1)
P1_2d = get_functionspace(mesh2d, "DG", 1)
# define underlying bathymetry
bathymetry_2d = Function(V, name='Bat... | examples/sediment_trench_2d/trench_hydro.py | from thetis import *
# define mesh
lx = 16
ly = 1.1
nx = lx*5
ny = 5
mesh2d = RectangleMesh(nx, ny, lx, ly)
x, y = SpatialCoordinate(mesh2d)
# define function spaces
V = get_functionspace(mesh2d, "CG", 1)
P1_2d = get_functionspace(mesh2d, "DG", 1)
# define underlying bathymetry
bathymetry_2d = Function(V, name='Bat... | 0.539711 | 0.570451 |
from django import forms
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth import logout
from django.core.exceptions import SuspiciousOperation
from django.db import models
from django.forms import ModelForm, Textarea, formset_factory
from django.forms.models impor... | mgmt/views.py |
from django import forms
from django.contrib.auth.decorators import login_required, permission_required
from django.contrib.auth import logout
from django.core.exceptions import SuspiciousOperation
from django.db import models
from django.forms import ModelForm, Textarea, formset_factory
from django.forms.models impor... | 0.165762 | 0.069795 |
from unittest.mock import create_autospec, ANY, patch, call
import pytest
from stack.commands import DatabaseConnection
from stack.commands.set.firmware.model.version_regex import Command
from stack.exception import CommandError
from stack.commands.set.firmware.model.version_regex.plugin_basic import Plugin
class Test... | test-framework/test-suites/unit/tests/command/stack/commands/set/firmware/model/version_regex/test_command_stack_commands_set_firmware_model_version_regex_plugin_basic.py | from unittest.mock import create_autospec, ANY, patch, call
import pytest
from stack.commands import DatabaseConnection
from stack.commands.set.firmware.model.version_regex import Command
from stack.exception import CommandError
from stack.commands.set.firmware.model.version_regex.plugin_basic import Plugin
class Test... | 0.756358 | 0.533641 |
from __future__ import absolute_import, division, print_function
import sys
import click
from polyaxon_cli.client import PolyaxonClient
from polyaxon_cli.client.exceptions import (
PolyaxonClientException,
PolyaxonHTTPError,
PolyaxonShouldExitError
)
from polyaxon_cli.logger import clean_outputs
from pol... | polyaxon_cli/cli/upload.py | from __future__ import absolute_import, division, print_function
import sys
import click
from polyaxon_cli.client import PolyaxonClient
from polyaxon_cli.client.exceptions import (
PolyaxonClientException,
PolyaxonHTTPError,
PolyaxonShouldExitError
)
from polyaxon_cli.logger import clean_outputs
from pol... | 0.431944 | 0.069479 |
import numpy as np
import re
import itertools
from collections import Counter
from os import listdir
from os.path import isfile, join
def clean_str(string):
"""
Tokenization/string cleaning for all datasets except for SST.
Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_d... | cnn-text-classification-tf/corpus_handel.py | import numpy as np
import re
import itertools
from collections import Counter
from os import listdir
from os.path import isfile, join
def clean_str(string):
"""
Tokenization/string cleaning for all datasets except for SST.
Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_d... | 0.675229 | 0.46642 |
# Default values:
config = {
"cid": "none",
}
import sys
import time
from cbcommslib import CbApp
from cbconfig import *
import json
from twisted.internet import reactor
class Client():
def __init__(self, aid):
self.aid = aid
self.count = 0
self.previousTime = time.time()
self... | simple_button_app_a.py |
# Default values:
config = {
"cid": "none",
}
import sys
import time
from cbcommslib import CbApp
from cbconfig import *
import json
from twisted.internet import reactor
class Client():
def __init__(self, aid):
self.aid = aid
self.count = 0
self.previousTime = time.time()
self... | 0.235988 | 0.124772 |
from decimal import Decimal
from django.db import transaction
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework.serializers import Serializer
from money.models import CurrencyData, Denomination, \
AccountingGroup, Money, VAT, VATPeriod, Cost, Price, C... | backend/money/serializers.py | from decimal import Decimal
from django.db import transaction
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework.serializers import Serializer
from money.models import CurrencyData, Denomination, \
AccountingGroup, Money, VAT, VATPeriod, Cost, Price, C... | 0.562777 | 0.216923 |
# 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_heterodyne.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.915105 | 0.497559 |
from pyot.utils import loop_run
from pyot.models import val
async def async_content_locale():
content = await val.Content(platform="NA").query(locale="en-US").get()
assert isinstance(content.version, str)
for item in [content.characters, content.maps, content.chromas, content.skins,
content.skin_... | test/test_val_content.py | from pyot.utils import loop_run
from pyot.models import val
async def async_content_locale():
content = await val.Content(platform="NA").query(locale="en-US").get()
assert isinstance(content.version, str)
for item in [content.characters, content.maps, content.chromas, content.skins,
content.skin_... | 0.650467 | 0.287959 |
from __future__ import absolute_import
from __future__ import unicode_literals
import functools
from distutils.version import LooseVersion
from django.utils.translation import ugettext
from corehq.apps.app_manager import id_strings
from memoized import memoized
from corehq.apps.app_manager.util import module_offers_s... | corehq/apps/app_manager/app_strings.py | from __future__ import absolute_import
from __future__ import unicode_literals
import functools
from distutils.version import LooseVersion
from django.utils.translation import ugettext
from corehq.apps.app_manager import id_strings
from memoized import memoized
from corehq.apps.app_manager.util import module_offers_s... | 0.391057 | 0.080033 |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import un... | sdk/storage/azure-storage-file/tests/test_directory.py |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import un... | 0.701202 | 0.194215 |
from collections import defaultdict
from dataclasses import dataclass, asdict, field
from pathlib import Path
from typing import Set, Union
import glob
import click
import frontmatter
try:
import ruamel.yaml as yaml
except ImportError:
import ruamel_yaml as yaml
namespace_comment = "### YamlMime:QSharpNamesp... | src/Documentation/Summarizer/summarize_documentation.py |
from collections import defaultdict
from dataclasses import dataclass, asdict, field
from pathlib import Path
from typing import Set, Union
import glob
import click
import frontmatter
try:
import ruamel.yaml as yaml
except ImportError:
import ruamel_yaml as yaml
namespace_comment = "### YamlMime:QSharpNamesp... | 0.63624 | 0.196788 |
import os
import glob
from flask import current_app
from packaging.specifiers import SpecifierSet, InvalidSpecifier
from packaging.version import parse as parse_version
from cloudify._compat import parse_qs
from dsl_parser import parser
from dsl_parser.import_resolver.default_import_resolver import (
DefaultImpor... | rest-service/manager_rest/resolver_with_catalog_support.py |
import os
import glob
from flask import current_app
from packaging.specifiers import SpecifierSet, InvalidSpecifier
from packaging.version import parse as parse_version
from cloudify._compat import parse_qs
from dsl_parser import parser
from dsl_parser.import_resolver.default_import_resolver import (
DefaultImpor... | 0.564939 | 0.089534 |
from ccxt.base.exchange import Exchange
import hashlib
from ccxt.base.errors import ExchangeError
class chbtc (Exchange):
def describe(self):
return self.deep_extend(super(chbtc, self).describe(), {
'id': 'chbtc',
'name': 'CHBTC',
'countries': 'CN',
'rateL... | python/ccxt/chbtc.py |
from ccxt.base.exchange import Exchange
import hashlib
from ccxt.base.errors import ExchangeError
class chbtc (Exchange):
def describe(self):
return self.deep_extend(super(chbtc, self).describe(), {
'id': 'chbtc',
'name': 'CHBTC',
'countries': 'CN',
'rateL... | 0.588534 | 0.172137 |
import time
from lib import misc
def _all_true(vec):
for v in vec:
if not v:
return False
return True
def move_abs(posins, moveins, newpos, startstep=4, maxstep=128, minstep=1, delay=0.05, channel_ofs=0):
"""
move_abs, generic function to control read-out/positioner combo
Inpu... | source/addons/positioning.py | import time
from lib import misc
def _all_true(vec):
for v in vec:
if not v:
return False
return True
def move_abs(posins, moveins, newpos, startstep=4, maxstep=128, minstep=1, delay=0.05, channel_ofs=0):
"""
move_abs, generic function to control read-out/positioner combo
Inpu... | 0.38445 | 0.489198 |
import colorsys,sys
from pymol import cmd
aa_1_3 = {
'A': 'ALA',
'C': 'CYS',
'D': 'ASP',
'E': 'GLU',
'F': 'PHE',
'G': 'GLY',
'H': 'HIS',
'I': 'ILE',
'K': 'LYS',
'L': 'LEU',
'M': 'MET',
'N': 'ASN',
'P': 'PRO',
'Q': 'GLN',
'R': 'ARG',
'S': 'SER',
'T': 'THR',
'V': 'VAL... | scripts/PyMolUtils/ColorByRes.py | import colorsys,sys
from pymol import cmd
aa_1_3 = {
'A': 'ALA',
'C': 'CYS',
'D': 'ASP',
'E': 'GLU',
'F': 'PHE',
'G': 'GLY',
'H': 'HIS',
'I': 'ILE',
'K': 'LYS',
'L': 'LEU',
'M': 'MET',
'N': 'ASN',
'P': 'PRO',
'Q': 'GLN',
'R': 'ARG',
'S': 'SER',
'T': 'THR',
'V': 'VAL... | 0.299003 | 0.214589 |
import copy
from typing import Iterable
import pandas as pd
import plotly.graph_objs as go
from ..graph import BaseGraph, SubplotsGraph
from ..analysis_position.parse_position import get_position_data
def _get_cum_return_data_with_position(
position: dict,
report_normal: pd.DataFrame,
label_data: pd.D... | qlib/contrib/report/analysis_position/cumulative_return.py |
import copy
from typing import Iterable
import pandas as pd
import plotly.graph_objs as go
from ..graph import BaseGraph, SubplotsGraph
from ..analysis_position.parse_position import get_position_data
def _get_cum_return_data_with_position(
position: dict,
report_normal: pd.DataFrame,
label_data: pd.D... | 0.68215 | 0.242133 |
import time
import sys
import subprocess
import platform
# Bloco de bibliotecas do usuario
import Adafruit_DHT
import RPi.GPIO as GPIO
'''
Fazer um programa para ler a temperatura e umidade, atraves do sensor
fornecido. Apresentar os resultados em tela.
'''
# Define o tipo de sensor DHT11
sensor = Adafruit_DHT.DHT11
... | sources/EE1054-Atividade07-Questao03-DHT.py | import time
import sys
import subprocess
import platform
# Bloco de bibliotecas do usuario
import Adafruit_DHT
import RPi.GPIO as GPIO
'''
Fazer um programa para ler a temperatura e umidade, atraves do sensor
fornecido. Apresentar os resultados em tela.
'''
# Define o tipo de sensor DHT11
sensor = Adafruit_DHT.DHT11
... | 0.123564 | 0.186262 |
import tensorflow as tf
from models import model
# Obtained by running the official NCF model with the following command:
# python ncf_main.py --dataset ml-20m
# and printing the number of users and items here:
# https://github.com/tensorflow/models/blob/d089975f630a8a01be63e45ef08a31be14bb96b4/official/recomme... | scripts/tf_cnn_benchmarks/models/experimental/official_ncf_model.py | import tensorflow as tf
from models import model
# Obtained by running the official NCF model with the following command:
# python ncf_main.py --dataset ml-20m
# and printing the number of users and items here:
# https://github.com/tensorflow/models/blob/d089975f630a8a01be63e45ef08a31be14bb96b4/official/recomme... | 0.596551 | 0.471041 |
from devtools_testutils import AzureMgmtTestCase, ResourceGroupPreparer
from azure.mgmt.botservice import AzureBotService
from azure.mgmt.botservice.models import (
Bot,
BotProperties,
BotChannel,
ErrorException,
sku
)
class BotServiceChannelsTestCase(AzureMgmtTestCase):
def setUp(self):
... | sdk/botservice/azure-mgmt-botservice/tests/test_mgmt_botservice_channels.py | from devtools_testutils import AzureMgmtTestCase, ResourceGroupPreparer
from azure.mgmt.botservice import AzureBotService
from azure.mgmt.botservice.models import (
Bot,
BotProperties,
BotChannel,
ErrorException,
sku
)
class BotServiceChannelsTestCase(AzureMgmtTestCase):
def setUp(self):
... | 0.508788 | 0.129899 |
import autograd.numpy as np
import autograd.numpy.random as npr
from autograd.scipy.misc import logsumexp
from autograd import grad
from autograd.util import flatten
from autograd.optimizers import adam
from vbproj.misc import gamma_lnpdf
def make_nn_regression_funs(Xtrain, Ytrain,
layer_s... | code/vbproj/models/nn.py | import autograd.numpy as np
import autograd.numpy.random as npr
from autograd.scipy.misc import logsumexp
from autograd import grad
from autograd.util import flatten
from autograd.optimizers import adam
from vbproj.misc import gamma_lnpdf
def make_nn_regression_funs(Xtrain, Ytrain,
layer_s... | 0.675444 | 0.653155 |
import os
import copy
from tqdm import trange
from ..recommender import Recommender
from ...exception import ScoreException
from ...utils import get_rng
class NCFBase(Recommender):
"""Base class of NCF family.
Parameters
----------
num_epochs: int, optional, default: 20
Number of epochs.
... | cornac/models/ncf/recom_ncf_base.py |
import os
import copy
from tqdm import trange
from ..recommender import Recommender
from ...exception import ScoreException
from ...utils import get_rng
class NCFBase(Recommender):
"""Base class of NCF family.
Parameters
----------
num_epochs: int, optional, default: 20
Number of epochs.
... | 0.893455 | 0.477432 |
import argparse
import os
import cv2
import torch
import torch.nn.parallel
import numpy as np
import math
import valid
import sys
import common.config as config
import common.TBLogger as TBLogger
from common.utils import makedir_if_not_exist, StoreDictKeyPair, save_obj, load_obj
from torch import optim
from torch.u... | experiments/normal_estimation/train.py | import argparse
import os
import cv2
import torch
import torch.nn.parallel
import numpy as np
import math
import valid
import sys
import common.config as config
import common.TBLogger as TBLogger
from common.utils import makedir_if_not_exist, StoreDictKeyPair, save_obj, load_obj
from torch import optim
from torch.u... | 0.514156 | 0.291564 |
import h5py
import os
from tqdm import tqdm
input_dump_dir = 'dumps/sbcd_sqd_ftinb84_kl_x4_20181220_concat/dump/phrase/'
select = 0
print(f'************** {select} *****************')
input_dump_paths = sorted(
[os.path.join(input_dump_dir, name) for name in os.listdir(input_dump_dir) if 'hdf5' in name]
)[select:]... | densephrases/scripts/dump/filter_hdf5.py | import h5py
import os
from tqdm import tqdm
input_dump_dir = 'dumps/sbcd_sqd_ftinb84_kl_x4_20181220_concat/dump/phrase/'
select = 0
print(f'************** {select} *****************')
input_dump_paths = sorted(
[os.path.join(input_dump_dir, name) for name in os.listdir(input_dump_dir) if 'hdf5' in name]
)[select:]... | 0.173323 | 0.078395 |
import shutil
from mbci_lab.ui.mbci_ui import *
from mbci_lab.core.worker import Worker
from mbci_lab.core.constants import Constants, SourceType
from mbci_lab.ui.popUp import PopUp
from mbci_lab.common.logger import Logger as Log
TAG = "MainWindow"
class MainWindow(QtGui.QMainWindow):
"""
Handles the ui e... | mbci_lab/ui/mainWindow.py | import shutil
from mbci_lab.ui.mbci_ui import *
from mbci_lab.core.worker import Worker
from mbci_lab.core.constants import Constants, SourceType
from mbci_lab.ui.popUp import PopUp
from mbci_lab.common.logger import Logger as Log
TAG = "MainWindow"
class MainWindow(QtGui.QMainWindow):
"""
Handles the ui e... | 0.582254 | 0.146484 |
import json
import platform
import sys
import tempfile
from os.path import dirname
import bpy
sys.path.insert(0, dirname(dirname(__file__)))
# pylint: disable=wrong-import-position;
from io_scene_vrm.importer.py_model import json_dict_diff # noqa: E402
# pylint: enable=wrong-import-position;
def test() -> None:
... | tests/blender_test_save_human_bone_mappings.py | import json
import platform
import sys
import tempfile
from os.path import dirname
import bpy
sys.path.insert(0, dirname(dirname(__file__)))
# pylint: disable=wrong-import-position;
from io_scene_vrm.importer.py_model import json_dict_diff # noqa: E402
# pylint: enable=wrong-import-position;
def test() -> None:
... | 0.379608 | 0.309089 |
from alembic import op
import sqlalchemy as sa
from app.models import GUID
# revision identifiers, used by Alembic.
revision = "fcd46eadd970"
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
"services",
sa.Column("id", GUID(), nullable=False),
s... | alembic/versions/fcd46eadd970_initial_database_creation.py | from alembic import op
import sqlalchemy as sa
from app.models import GUID
# revision identifiers, used by Alembic.
revision = "fcd46eadd970"
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
op.create_table(
"services",
sa.Column("id", GUID(), nullable=False),
s... | 0.291485 | 0.175185 |
from manimlib.mobject.svg.text_mobject import Text
from manim.utils.color import DARK_BLUE
from manimlib.animation.indication import ShowCreationThenDestruction, ShowCreationThenDestructionAround, ShowCreationThenFadeOut
from manimlib.mobject.svg.tex_mobject import Tex
from manimlib.animation.creation import ShowCreat... | graph_scene.py |
from manimlib.mobject.svg.text_mobject import Text
from manim.utils.color import DARK_BLUE
from manimlib.animation.indication import ShowCreationThenDestruction, ShowCreationThenDestructionAround, ShowCreationThenFadeOut
from manimlib.mobject.svg.tex_mobject import Tex
from manimlib.animation.creation import ShowCreat... | 0.453746 | 0.153422 |
from functools import reduce
class Operator():
@property
def should_eval(self):
return hasattr(self, 'left_operand') and hasattr(self, 'right_operand')
class Or(Operator):
@property
def should_eval(self):
if getattr(self, 'left_operand', False):
# Shortcircuit
... | drf_guard/operators.py | from functools import reduce
class Operator():
@property
def should_eval(self):
return hasattr(self, 'left_operand') and hasattr(self, 'right_operand')
class Or(Operator):
@property
def should_eval(self):
if getattr(self, 'left_operand', False):
# Shortcircuit
... | 0.865707 | 0.331512 |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_in... | arch/api/proto/inference_service_pb2.py |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
# @@protoc_in... | 0.160036 | 0.090977 |
import numpy as np
import autograd.numpy as anp
from autograd import grad
from autograd.tracer import getval
from typing import Tuple, Optional, Dict
from numpy.random import RandomState
from syne_tune.optimizer.schedulers.searchers.bayesopt.gpautograd.kernel import (
KernelFunction,
)
from syne_tune.optimizer.sch... | syne_tune/optimizer/schedulers/searchers/bayesopt/gpautograd/posterior_state.py | import numpy as np
import autograd.numpy as anp
from autograd import grad
from autograd.tracer import getval
from typing import Tuple, Optional, Dict
from numpy.random import RandomState
from syne_tune.optimizer.schedulers.searchers.bayesopt.gpautograd.kernel import (
KernelFunction,
)
from syne_tune.optimizer.sch... | 0.911989 | 0.60679 |
import os
import requests
from django.conf import settings
from django.apps import AppConfig
from constance import config
import tau.twitchevents.webhook_payloads as webhook_payloads
from .utils import refresh_access_token, setup_ngrok
class CoreConfig(AppConfig):
name = 'tau.core'
verbose_name = 'Core'
... | tau/core/apps.py | import os
import requests
from django.conf import settings
from django.apps import AppConfig
from constance import config
import tau.twitchevents.webhook_payloads as webhook_payloads
from .utils import refresh_access_token, setup_ngrok
class CoreConfig(AppConfig):
name = 'tau.core'
verbose_name = 'Core'
... | 0.263315 | 0.041931 |
import unittest
from collections import OrderedDict
from textwrap import dedent
from unittest.mock import Mock
from znake.setupgen import _render_entry_points, _render_install_requirements, \
_render_package_data, _render_setup_py_data
class TestRenderInstallRequires(unittest.TestCase):
def test_render_inst... | znake/test/test_setupgen.py | import unittest
from collections import OrderedDict
from textwrap import dedent
from unittest.mock import Mock
from znake.setupgen import _render_entry_points, _render_install_requirements, \
_render_package_data, _render_setup_py_data
class TestRenderInstallRequires(unittest.TestCase):
def test_render_inst... | 0.424531 | 0.390999 |
# class -------------------------------------------------------------------
# ---------------------------------------------------------------------------
class ArgumentError(Exception):
"""This exception is when a argument's value does not coincide with the items of a predefined list.
"""
def __init__(se... | expmgmt/debug/exceptions.py |
# class -------------------------------------------------------------------
# ---------------------------------------------------------------------------
class ArgumentError(Exception):
"""This exception is when a argument's value does not coincide with the items of a predefined list.
"""
def __init__(se... | 0.708414 | 0.264471 |
"""Utitly functions to help distribution class."""
import numpy as np
from mindspore import context
from mindspore._checkparam import Validator as validator
from mindspore.common.tensor import Tensor
from mindspore.common.parameter import Parameter
from mindspore.common import dtype as mstype
from mindspore.ops import ... | mindspore/nn/probability/distribution/_utils/utils.py | """Utitly functions to help distribution class."""
import numpy as np
from mindspore import context
from mindspore._checkparam import Validator as validator
from mindspore.common.tensor import Tensor
from mindspore.common.parameter import Parameter
from mindspore.common import dtype as mstype
from mindspore.ops import ... | 0.933635 | 0.655736 |
import numpy as np
import tensorflow as tf
from tacotron.models import create_model
from tacotron.utils.text import text_to_sequence
_pad = 0
class AlignmentSynthesizer:
def load(self, checkpoint, hparams, gta=False, model_name='tacotron_pml', locked_alignments=None, cut_lengths=True):
"""
:param... | tacotron/alignment_synthesizer.py | import numpy as np
import tensorflow as tf
from tacotron.models import create_model
from tacotron.utils.text import text_to_sequence
_pad = 0
class AlignmentSynthesizer:
def load(self, checkpoint, hparams, gta=False, model_name='tacotron_pml', locked_alignments=None, cut_lengths=True):
"""
:param... | 0.756987 | 0.39867 |
from pyspark.resultiterable import ResultIterable
def _do_python_join(rdd, other, numPartitions, dispatch):
vs = rdd.mapValues(lambda v: (1, v))
ws = other.mapValues(lambda v: (2, v))
return vs.union(ws).groupByKey(numPartitions).flatMapValues(lambda x: dispatch(x.__iter__()))
def python_join(rdd, other... | python/pyspark/join.py | from pyspark.resultiterable import ResultIterable
def _do_python_join(rdd, other, numPartitions, dispatch):
vs = rdd.mapValues(lambda v: (1, v))
ws = other.mapValues(lambda v: (2, v))
return vs.union(ws).groupByKey(numPartitions).flatMapValues(lambda x: dispatch(x.__iter__()))
def python_join(rdd, other... | 0.485356 | 0.440108 |
import json
import logging
import os
import random
import signal
import socket
import requests
import sys
from flask import Flask, render_template, request, make_response
from paste.translogger import TransLogger
from prometheus_flask_exporter import PrometheusMetrics
from waitress import serve
app = Flask(__name__)
... | v3/src/web/app.py | import json
import logging
import os
import random
import signal
import socket
import requests
import sys
from flask import Flask, render_template, request, make_response
from paste.translogger import TransLogger
from prometheus_flask_exporter import PrometheusMetrics
from waitress import serve
app = Flask(__name__)
... | 0.242744 | 0.119845 |
from helpers import Helpers
import string
import syft as sy
import torch as th
hook = sy.TorchHook(th)
class EncryptedDB():
def __init__(self, *owners, max_key_len=8, max_val_len=8):
self.helpers = Helpers()
self.max_key_len = max_key_len
self.max_val_len = max_val_len
self.keys =... | run.py | from helpers import Helpers
import string
import syft as sy
import torch as th
hook = sy.TorchHook(th)
class EncryptedDB():
def __init__(self, *owners, max_key_len=8, max_val_len=8):
self.helpers = Helpers()
self.max_key_len = max_key_len
self.max_val_len = max_val_len
self.keys =... | 0.424889 | 0.264768 |
import logging
from mock import Mock, patch, call
from netaddr import IPAddress
from calico.felix import frules
from calico.felix.fiptables import IptablesUpdater
from calico.felix.futils import FailedSystemCall, IPV4
from calico.felix.test.base import BaseTestCase, load_config
_log = logging.getLogger(__name__)
EX... | calico/felix/test/test_frules.py | import logging
from mock import Mock, patch, call
from netaddr import IPAddress
from calico.felix import frules
from calico.felix.fiptables import IptablesUpdater
from calico.felix.futils import FailedSystemCall, IPV4
from calico.felix.test.base import BaseTestCase, load_config
_log = logging.getLogger(__name__)
EX... | 0.288669 | 0.063832 |
import json, sys
from PyPDF4 import PdfFileReader, PdfFileWriter
def add_link(pdf_writer, pg_from, pg_to, coords, pg_height, pg_width, draw_border=False):
if draw_border:
border = [0, 0, 1]
else:
border = None
xll1 = coords["x0"]
yll1 = pg_height - coords["y1"]
xur1 = coords["x1"]
... | test-pipeline/merged-PDF.py | import json, sys
from PyPDF4 import PdfFileReader, PdfFileWriter
def add_link(pdf_writer, pg_from, pg_to, coords, pg_height, pg_width, draw_border=False):
if draw_border:
border = [0, 0, 1]
else:
border = None
xll1 = coords["x0"]
yll1 = pg_height - coords["y1"]
xur1 = coords["x1"]
... | 0.219338 | 0.103431 |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.p... | pgoapi/protos/pogoprotos/networking/requests/messages/get_map_objects_message_pb2.py |
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.p... | 0.170819 | 0.111434 |
from collections import OrderedDict
from falcon.uri import parse_query_string
class Singleton(type):
"""
Creates a singleton instance for the parent class.
This way only one instance will be available throughout the application.
"""
_instances = {}
def __call__(cls, *args, **kwargs):
... | AutonomousService/service/utils.py | from collections import OrderedDict
from falcon.uri import parse_query_string
class Singleton(type):
"""
Creates a singleton instance for the parent class.
This way only one instance will be available throughout the application.
"""
_instances = {}
def __call__(cls, *args, **kwargs):
... | 0.864882 | 0.350866 |
import os.path as op
import numpy as np
from joblib import Parallel, delayed
import mne
import config as cfg
from library import preprocessing as pp
from library.preprocessing import (
_run_maxfilter, _get_global_reject_epochs, _get_global_reject_ssp)
def clean_raw(raw, subject, sss, ssp_er, ssp_eog, ssp_ecg, d... | compute_covs_preproc_impact.py | import os.path as op
import numpy as np
from joblib import Parallel, delayed
import mne
import config as cfg
from library import preprocessing as pp
from library.preprocessing import (
_run_maxfilter, _get_global_reject_epochs, _get_global_reject_ssp)
def clean_raw(raw, subject, sss, ssp_er, ssp_eog, ssp_ecg, d... | 0.326057 | 0.157105 |
from . import coins, messages
from .tools import CallException, expect, normalize_nfc, session
@expect(messages.PublicKey)
def get_public_node(
client,
n,
ecdsa_curve_name=None,
show_display=False,
coin_name=None,
script_type=messages.InputScriptType.SPENDADDRESS,
):
return client.call(
... | python/trezorlib/btc.py |
from . import coins, messages
from .tools import CallException, expect, normalize_nfc, session
@expect(messages.PublicKey)
def get_public_node(
client,
n,
ecdsa_curve_name=None,
show_display=False,
coin_name=None,
script_type=messages.InputScriptType.SPENDADDRESS,
):
return client.call(
... | 0.739234 | 0.117117 |
import sqlalchemy
from sqlalchemy.orm import sessionmaker
class Database(object):
"""Gerencia as conexões com o banco de dados"""
def __init__(self, user, password, db, host='localhost', port=5432):
"""TODO: to be defined1.
:user: Usuário de conexeção ao banco de dados
:password: <P... | Database.py | import sqlalchemy
from sqlalchemy.orm import sessionmaker
class Database(object):
"""Gerencia as conexões com o banco de dados"""
def __init__(self, user, password, db, host='localhost', port=5432):
"""TODO: to be defined1.
:user: Usuário de conexeção ao banco de dados
:password: <P... | 0.325092 | 0.158402 |
from __future__ import print_function
import sys
import argparse
import time
import math
import torch
import torch.backends.cudnn as cudnn
import numpy as np
from main_ce import set_loader
from util import AverageMeter
from util import adjust_learning_rate, warmup_learning_rate, accuracy
from util import set_optimiz... | main_linear.py | from __future__ import print_function
import sys
import argparse
import time
import math
import torch
import torch.backends.cudnn as cudnn
import numpy as np
from main_ce import set_loader
from util import AverageMeter
from util import adjust_learning_rate, warmup_learning_rate, accuracy
from util import set_optimiz... | 0.566738 | 0.135403 |
import logging
from abc import ABC
from typing import Tuple, List, Dict, Any
from typing import Union, Type, Hashable, Iterable, Optional
from forte.common.configuration import Config
from forte.data.converter.feature import Feature
from forte.data.data_pack import DataPack
from forte.data.ontology import Annotation
f... | forte/data/extractor/base_extractor.py | import logging
from abc import ABC
from typing import Tuple, List, Dict, Any
from typing import Union, Type, Hashable, Iterable, Optional
from forte.common.configuration import Config
from forte.data.converter.feature import Feature
from forte.data.data_pack import DataPack
from forte.data.ontology import Annotation
f... | 0.935465 | 0.418043 |
from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException
from thrift.protocol.TProtocol import TProtocolException
from thrift.TRecursive import fix_spec
import sys
from thrift.transport import TTransport
all_structs = []
class ParentFog(object):
"""
Attributes:
- n... | docker-testing-environment/preload/cli/gen-py/EdgeServices/ttypes.py |
from thrift.Thrift import TType, TMessageType, TFrozenDict, TException, TApplicationException
from thrift.protocol.TProtocol import TProtocolException
from thrift.TRecursive import fix_spec
import sys
from thrift.transport import TTransport
all_structs = []
class ParentFog(object):
"""
Attributes:
- n... | 0.297164 | 0.097262 |
from datetime import datetime
from pyvirtualdisplay import Display
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from .login_util import login_user
from .print_log_writer import log_follower_num
from .follow_util import follow_from_recommended
from .unfollow_util import unfollow_... | twitpy/twitpy.py | from datetime import datetime
from pyvirtualdisplay import Display
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from .login_util import login_user
from .print_log_writer import log_follower_num
from .follow_util import follow_from_recommended
from .unfollow_util import unfollow_... | 0.429071 | 0.065755 |
import datetime
import pytest
from pytest import param
from h.services.auth_token import (
AuthTokenService,
LongLivedToken,
auth_token_service_factory,
)
class TestAuthTokenService:
def test_validate_returns_database_token(self, svc, factories):
token_model = factories.DeveloperToken(expire... | tests/h/services/auth_token_test.py | import datetime
import pytest
from pytest import param
from h.services.auth_token import (
AuthTokenService,
LongLivedToken,
auth_token_service_factory,
)
class TestAuthTokenService:
def test_validate_returns_database_token(self, svc, factories):
token_model = factories.DeveloperToken(expire... | 0.615319 | 0.477128 |
import numpy as np
from scipy.stats import norm
import logging
from .base import BaseSimulator
from .utils import NumpyDataset
from scipy.special import i0
logger = logging.getLogger(__name__)
class MixtureSphereSimulator(BaseSimulator):
def __init__(self, latent_dim=2, data_dim=3, kappa=6.0, epsilon=0.):
... | experiments/datasets/mixture_on_sphere.py |
import numpy as np
from scipy.stats import norm
import logging
from .base import BaseSimulator
from .utils import NumpyDataset
from scipy.special import i0
logger = logging.getLogger(__name__)
class MixtureSphereSimulator(BaseSimulator):
def __init__(self, latent_dim=2, data_dim=3, kappa=6.0, epsilon=0.):
... | 0.556761 | 0.49292 |
from typing import Tuple
import torch
import torch.nn as nn
from torch.distributions import Normal, OneHotCategorical
from .linear import LinearPolicy
class GaussianPolicy(nn.Module):
"""
A simple gaussian policy.
"""
LOG_STD_MIN = -20
LOG_STD_MAX = 2
def __init__(
self,
... | hlrl/torch/policies/distribution.py | from typing import Tuple
import torch
import torch.nn as nn
from torch.distributions import Normal, OneHotCategorical
from .linear import LinearPolicy
class GaussianPolicy(nn.Module):
"""
A simple gaussian policy.
"""
LOG_STD_MIN = -20
LOG_STD_MAX = 2
def __init__(
self,
... | 0.968426 | 0.689469 |
from __future__ import annotations
from datetime import date, datetime # noqa: F401
import re # noqa: F401
from typing import Any, Dict, List, Optional, Union, Literal # noqa: F401
from pydantic import AnyUrl, BaseModel, EmailStr, validator, Field, Extra # noqa: F401
from aries_cloudcontroller.model.cred_def_va... | aries_cloudcontroller/model/credential_definition.py |
from __future__ import annotations
from datetime import date, datetime # noqa: F401
import re # noqa: F401
from typing import Any, Dict, List, Optional, Union, Literal # noqa: F401
from pydantic import AnyUrl, BaseModel, EmailStr, validator, Field, Extra # noqa: F401
from aries_cloudcontroller.model.cred_def_va... | 0.882124 | 0.168857 |
from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
import os
import pytest
import hcl
from hooks.pre_gen_project import TerragruntGenerator, StackParser
from jinja2.exceptions import UndefinedError, TemplateSyntaxError
from tests.test_render_all import FIXTURE_DIR... | tests/test_make_all.py | from __future__ import absolute_import, division, print_function
from __future__ import unicode_literals
import os
import pytest
import hcl
from hooks.pre_gen_project import TerragruntGenerator, StackParser
from jinja2.exceptions import UndefinedError, TemplateSyntaxError
from tests.test_render_all import FIXTURE_DIR... | 0.257298 | 0.132374 |
import scrapy
import json
from getComment.items import GetcommentItem
import codecs
#需要加入cookie,不然有些页面没有权限
class GetcommentSpider(scrapy.Spider):
name = "getComment"
allowed_domains = ["douban.com"]
cookie={ '__utma':"30149280.901747088.1445074673.1463148044.1463205092.69",
'__utma':"223695111... | Spider/scrapy/getComment/getComment/spiders/getcomment.py | import scrapy
import json
from getComment.items import GetcommentItem
import codecs
#需要加入cookie,不然有些页面没有权限
class GetcommentSpider(scrapy.Spider):
name = "getComment"
allowed_domains = ["douban.com"]
cookie={ '__utma':"30149280.901747088.1445074673.1463148044.1463205092.69",
'__utma':"223695111... | 0.114678 | 0.071754 |
import numpy as np
import pandas as pd
from numpy import std
from numpy import mean
from math import sqrt
import matplotlib.pyplot as plt
from scipy.stats import spearmanr
from sklearn.metrics import r2_score
from sklearn.metrics import max_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics impo... | Regression/Linear Regression/linear_regression.py | import numpy as np
import pandas as pd
from numpy import std
from numpy import mean
from math import sqrt
import matplotlib.pyplot as plt
from scipy.stats import spearmanr
from sklearn.metrics import r2_score
from sklearn.metrics import max_error
from sklearn.metrics import mean_squared_error
from sklearn.metrics impo... | 0.507324 | 0.430327 |
__author__ = "<NAME>"
"""
This file holds the implementation of Ryser method of permanent calculation, as
presented in [Cliffords2020] with using Guan codes to speed it up. I modified it
slightly, so that the permanent can be used for computing permanents for bunched and
not-continuous (like [1, 1, 0, ... | theboss/boson_sampling_utilities/permanent_calculators/ryser_guan_permanent_calculator.py | __author__ = "<NAME>"
"""
This file holds the implementation of Ryser method of permanent calculation, as
presented in [Cliffords2020] with using Guan codes to speed it up. I modified it
slightly, so that the permanent can be used for computing permanents for bunched and
not-continuous (like [1, 1, 0, ... | 0.837852 | 0.706994 |
import asyncio
import time
import numpy as np
import pyrr
from virtualreality import templates
from virtualreality.server import server
from aioconsole import ainput
poser = templates.PoserClient()
START_POS = np.array([-0.124638+(3.3/2), -1.439744, 0.623368+1], dtype=np.float64) # [x, y, z]
ROOM_CENTER = np.array(... | examples/poser_draw_room_boundaries.py | import asyncio
import time
import numpy as np
import pyrr
from virtualreality import templates
from virtualreality.server import server
from aioconsole import ainput
poser = templates.PoserClient()
START_POS = np.array([-0.124638+(3.3/2), -1.439744, 0.623368+1], dtype=np.float64) # [x, y, z]
ROOM_CENTER = np.array(... | 0.149407 | 0.257987 |
from dowhy.causal_refuter import CausalRefuter, CausalRefutation
from dowhy.causal_estimator import CausalEstimator
import numpy as np
import random
from sklearn.utils import resample
import logging
class BootstrapRefuter(CausalRefuter):
"""
Refute an estimate by running it on a random sample of the data conta... | dowhy/causal_refuters/bootstrap_refuter.py | from dowhy.causal_refuter import CausalRefuter, CausalRefutation
from dowhy.causal_estimator import CausalEstimator
import numpy as np
import random
from sklearn.utils import resample
import logging
class BootstrapRefuter(CausalRefuter):
"""
Refute an estimate by running it on a random sample of the data conta... | 0.872565 | 0.680378 |
from plum import convert
import neuralprocesses as nps # This fixes inspection below.
from .util import construct_likelihood, parse_transform
from ..util import register_model
__all__ = ["construct_gnp"]
@register_model
def construct_gnp(
dim_x=1,
dim_y=1,
dim_yc=None,
dim_yt=None,
dim_embeddin... | neuralprocesses/architectures/gnp.py | from plum import convert
import neuralprocesses as nps # This fixes inspection below.
from .util import construct_likelihood, parse_transform
from ..util import register_model
__all__ = ["construct_gnp"]
@register_model
def construct_gnp(
dim_x=1,
dim_y=1,
dim_yc=None,
dim_yt=None,
dim_embeddin... | 0.917263 | 0.5769 |