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 http import HTTPStatus
import json
from django.test import (Client, TestCase)
from citizens.models import Citizen
class CitizensTestCase(TestCase):
def setUp(self):
self.client = Client()
self.url = '/api/v1/citizen/'
self.citizen_fields = ('name', 'last_name', 'email', 'phone',
... | api/citizens/tests_cases/test_citizens_crud.py | from http import HTTPStatus
import json
from django.test import (Client, TestCase)
from citizens.models import Citizen
class CitizensTestCase(TestCase):
def setUp(self):
self.client = Client()
self.url = '/api/v1/citizen/'
self.citizen_fields = ('name', 'last_name', 'email', 'phone',
... | 0.543833 | 0.246874 |
import os,sys
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
from .basic import *
from torch_connectomics.libs.sync import SynchronizedBatchNorm1d, SynchronizedBatchNorm2d, SynchronizedBatchNorm3d
# 1. Residual blocks
class residual_block_2d(nn.Module):
"""
Residual Block 2D
... | torch_connectomics/model/blocks/residual.py | import os,sys
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
from .basic import *
from torch_connectomics.libs.sync import SynchronizedBatchNorm1d, SynchronizedBatchNorm2d, SynchronizedBatchNorm3d
# 1. Residual blocks
class residual_block_2d(nn.Module):
"""
Residual Block 2D
... | 0.933794 | 0.583619 |
era_user = '@@{era_<EMAIL>}@@'
era_pass = '@@{era_creds.secret}@@'
headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
# Set the URL and payload
url = "https://@@{era_ip}@@:8443/era/v0.8/databases/provision"
payload = {
"databaseName": "@@{DB_NAME}@@",
"databaseType": "postgres_databas... | play/EraPostgresProvision/scripts/Substrate_Era_PostgreSQL_DB_Action___pre_create___Task__4ProvisionDB.py | era_user = '@@{era_<EMAIL>}@@'
era_pass = '@@{era_creds.secret}@@'
headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
# Set the URL and payload
url = "https://@@{era_ip}@@:8443/era/v0.8/databases/provision"
payload = {
"databaseName": "@@{DB_NAME}@@",
"databaseType": "postgres_databas... | 0.27338 | 0.233717 |
from collections import namedtuple
Genotype = namedtuple('Genotype', 'normal normal_concat reduce reduce_concat')
# Learning Transferable Architectures for Scalable Image Recognition, CVPR 2018
NASNet = Genotype(
normal=[
(('sep_conv_5x5', 1), ('sep_conv_3x3', 0)),
(('sep_conv_5x5', 0), ('sep_conv... | NAS-Models/lib/models/genotypes.py | from collections import namedtuple
Genotype = namedtuple('Genotype', 'normal normal_concat reduce reduce_concat')
# Learning Transferable Architectures for Scalable Image Recognition, CVPR 2018
NASNet = Genotype(
normal=[
(('sep_conv_5x5', 1), ('sep_conv_3x3', 0)),
(('sep_conv_5x5', 0), ('sep_conv... | 0.733356 | 0.526221 |
import logging
import requests
import ari
logging.basicConfig(level=logging.ERROR)
client = ari.connect('http://localhost:8088', 'asterisk', 'asterisk')
def safe_hangup(channel):
"""Safely hang up the specified channel"""
try:
channel.hangup()
print "Hung up {}".format(channel.json.get('nam... | bridge-dial/example.py |
import logging
import requests
import ari
logging.basicConfig(level=logging.ERROR)
client = ari.connect('http://localhost:8088', 'asterisk', 'asterisk')
def safe_hangup(channel):
"""Safely hang up the specified channel"""
try:
channel.hangup()
print "Hung up {}".format(channel.json.get('nam... | 0.434221 | 0.069321 |
from pymtl3 import *
from pymtl3.stdlib.stream.ifcs import SendIfcRTL, RecvIfcRTL
from pymtl3_net.channel.ChannelRTL import ChannelRTL
from pymtl3_net.ocnlib.ifcs.PhysicalDimension import PhysicalDimension
from .BflyRouterRTL import BflyRouterRTL
class BflyNetworkRTL( Component ):
def construct( s, PacketType, P... | pymtl3_net/bflynet/BflyNetworkRTL.py | from pymtl3 import *
from pymtl3.stdlib.stream.ifcs import SendIfcRTL, RecvIfcRTL
from pymtl3_net.channel.ChannelRTL import ChannelRTL
from pymtl3_net.ocnlib.ifcs.PhysicalDimension import PhysicalDimension
from .BflyRouterRTL import BflyRouterRTL
class BflyNetworkRTL( Component ):
def construct( s, PacketType, P... | 0.38445 | 0.153549 |
import os
import inspect
import json
from cleep.core import CleepModule
from cleep.libs.internals.console import Console, EndlessConsole
from cleep.exception import CommandError, MissingParameter, InvalidParameter
from cleep.libs.internals import __all__ as internals_libs
from cleep.libs.drivers import __all__ as driv... | backend/developer.py |
import os
import inspect
import json
from cleep.core import CleepModule
from cleep.libs.internals.console import Console, EndlessConsole
from cleep.exception import CommandError, MissingParameter, InvalidParameter
from cleep.libs.internals import __all__ as internals_libs
from cleep.libs.drivers import __all__ as driv... | 0.340705 | 0.093844 |
"""Hardware Package Table Model."""
# Standard Library Imports
from typing import Any, Dict, Type
# Third Party Imports
from pubsub import pub
# RAMSTK Package Imports
from ramstk.models import RAMSTKBaseTable, RAMSTKHardwareRecord
class RAMSTKHardwareTable(RAMSTKBaseTable):
"""Contain attributes and methods o... | src/ramstk/models/programdb/hardware/table.py | """Hardware Package Table Model."""
# Standard Library Imports
from typing import Any, Dict, Type
# Third Party Imports
from pubsub import pub
# RAMSTK Package Imports
from ramstk.models import RAMSTKBaseTable, RAMSTKHardwareRecord
class RAMSTKHardwareTable(RAMSTKBaseTable):
"""Contain attributes and methods o... | 0.952187 | 0.294145 |
import configparser
import re
import time
from pathlib import Path
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import pandas as pd
class Moneyforward():
"""
docstring:hogehoge
後で書く
"""
def __init__(self):
self.csv_dir = Path("../csv")
sel... | src/download_history.py | import configparser
import re
import time
from pathlib import Path
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import pandas as pd
class Moneyforward():
"""
docstring:hogehoge
後で書く
"""
def __init__(self):
self.csv_dir = Path("../csv")
sel... | 0.265976 | 0.075687 |
from nose.plugins.attrib import attr
from framework.base_test import teardown_driver, HeadlessRunnerTest
from framework.utils.data_fetcher import fetch_, from_
from mangrove.form_model.project import Project
from pages.loginpage.login_page import login
from tests.projects.customizedreplysmstests.customized_reply_sms_da... | func_tests/tests/questionnairetests/create_blank_questionnaire_on_pro_account_tests.py | from nose.plugins.attrib import attr
from framework.base_test import teardown_driver, HeadlessRunnerTest
from framework.utils.data_fetcher import fetch_, from_
from mangrove.form_model.project import Project
from pages.loginpage.login_page import login
from tests.projects.customizedreplysmstests.customized_reply_sms_da... | 0.434461 | 0.136464 |
import numpy as np
from matplotlib import cm
import torch
from torchvision.utils import make_grid
from tensorboardX import SummaryWriter
from tools.utils import color_transfer
class Logger():
def __init__(self, opt):
self.writer = SummaryWriter(opt.log_path)
self.log_path = opt.log_path... | tools/logger.py | import numpy as np
from matplotlib import cm
import torch
from torchvision.utils import make_grid
from tensorboardX import SummaryWriter
from tools.utils import color_transfer
class Logger():
def __init__(self, opt):
self.writer = SummaryWriter(opt.log_path)
self.log_path = opt.log_path... | 0.759047 | 0.29049 |
from uuid import uuid4
import json
import os
import motor.motor_asyncio
from bson import ObjectId
from mongo_connect import mongo_connect
from decouple import config
class MongoDatabase():
client = None
collectionName = None
model = None
callbacks = {}
def __init__(self, collection_name,... | fastapi_restify/mongo_database.py | from uuid import uuid4
import json
import os
import motor.motor_asyncio
from bson import ObjectId
from mongo_connect import mongo_connect
from decouple import config
class MongoDatabase():
client = None
collectionName = None
model = None
callbacks = {}
def __init__(self, collection_name,... | 0.086661 | 0.077274 |
import os
import sys
import time
import argparse
import json
import tiebaBrowser
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Block Tieba ID', allow_abbrev=False)
parser.add_argument('--BDUSS_key', '-k',
type=str,
default='... | block_cycle.py | import os
import sys
import time
import argparse
import json
import tiebaBrowser
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Block Tieba ID', allow_abbrev=False)
parser.add_argument('--BDUSS_key', '-k',
type=str,
default='... | 0.099012 | 0.044431 |
import networkx as nx
import numpy as np
import scipy.sparse as sp
from scipy import linalg
from scipy.special import iv
from sklearn import preprocessing
from sklearn.utils.extmath import randomized_svd
class ProNE(object):
def __init__(self, dimension, step=5, mu=0.2, theta=0.5, **kwargs):
self.dimensio... | GCC-paddle/gcc/models/emb/prone.py | import networkx as nx
import numpy as np
import scipy.sparse as sp
from scipy import linalg
from scipy.special import iv
from sklearn import preprocessing
from sklearn.utils.extmath import randomized_svd
class ProNE(object):
def __init__(self, dimension, step=5, mu=0.2, theta=0.5, **kwargs):
self.dimensio... | 0.825519 | 0.496094 |
import pickle as pkl
from paho.mqtt import publish, subscribe
from time import sleep, time
from os import system
from pathlib import Path
from random import gauss, randint
from sys import argv
from config import *
from shared import *
def task_generator(n):
timeline = []
for i in range(1, n + 1):
t = -1
z = i... | workers/spawner.py |
import pickle as pkl
from paho.mqtt import publish, subscribe
from time import sleep, time
from os import system
from pathlib import Path
from random import gauss, randint
from sys import argv
from config import *
from shared import *
def task_generator(n):
timeline = []
for i in range(1, n + 1):
t = -1
z = i... | 0.135004 | 0.176494 |
from flask import Flask
from flask import render_template
from flask import request
from flask import url_for
import os
from database import person
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html', info='')
if... | python/samplesite.py | from flask import Flask
from flask import render_template
from flask import request
from flask import url_for
import os
from database import person
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html', info='')
if... | 0.273671 | 0.117167 |
import json
from src.testcase.GN_APP.input_case.GN_APP_Input_Case import *
from src.testcase.GN_APP.page.ReadAPPElement import *
from src.utils.Debug import *
from src.utils.OutputReport import *
from src.utils.WriteXls import *
class ScriptInitError(Exception):
def __init__(self, value=None):
self.value... | src/testcase/GN_APP/WaitCase.py | import json
from src.testcase.GN_APP.input_case.GN_APP_Input_Case import *
from src.testcase.GN_APP.page.ReadAPPElement import *
from src.utils.Debug import *
from src.utils.OutputReport import *
from src.utils.WriteXls import *
class ScriptInitError(Exception):
def __init__(self, value=None):
self.value... | 0.094803 | 0.104889 |
import argparse
import numpy as np
import psyneulink as pnl
all_figures = ['5a', '5b', '5c']
parser = argparse.ArgumentParser()
parser.add_argument('--no-plot', action='store_false', help='Disable plotting', dest='enable_plot')
parser.add_argument('--figure', nargs='+', help='Figure(s) to plot (default=all)', choice... | psyneulink/library/models/MontagueDayanSejnowski96.py | import argparse
import numpy as np
import psyneulink as pnl
all_figures = ['5a', '5b', '5c']
parser = argparse.ArgumentParser()
parser.add_argument('--no-plot', action='store_false', help='Disable plotting', dest='enable_plot')
parser.add_argument('--figure', nargs='+', help='Figure(s) to plot (default=all)', choice... | 0.669745 | 0.39036 |
# Standard library imports
import os.path as osp
# Third party imports
from qtpy.QtGui import QIcon
# Local imports
from spyder.config.base import _
from spyder.utils import icon_manager as ima
from spyder.utils.switcher import shorten_paths, get_file_icon
def get_symbol_list(outlineexplorer_data_list):
"""
... | spyder/plugins/editor/utils/switcher.py | # Standard library imports
import os.path as osp
# Third party imports
from qtpy.QtGui import QIcon
# Local imports
from spyder.config.base import _
from spyder.utils import icon_manager as ima
from spyder.utils.switcher import shorten_paths, get_file_icon
def get_symbol_list(outlineexplorer_data_list):
"""
... | 0.632162 | 0.186169 |
from __future__ import division
import numpy as np
from openmdao.api import ExplicitComponent
class TrueAirspeedComp(ExplicitComponent):
'''
Computes true airspeed from equivalent airspeed and density
Inputs
------
fltcond|rho : float
Density (vector, kg/m3)
fltcond|Ueas : float
... | openconcept/analysis/atmospherics/true_airspeed.py | from __future__ import division
import numpy as np
from openmdao.api import ExplicitComponent
class TrueAirspeedComp(ExplicitComponent):
'''
Computes true airspeed from equivalent airspeed and density
Inputs
------
fltcond|rho : float
Density (vector, kg/m3)
fltcond|Ueas : float
... | 0.772574 | 0.602997 |
from __future__ import unicode_literals
if __name__ == '__main__':
import autopath
import codecs
import sys
from alex.utils.config import as_project_path
from alex.corpustools.wavaskey import save_wavaskey
from alex.components.slu.base import CategoryLabelDatabase
from alex.components.asr.utterance import Utter... | alex/applications/PublicTransportInfoCS/slu/gen_uniq.py |
from __future__ import unicode_literals
if __name__ == '__main__':
import autopath
import codecs
import sys
from alex.utils.config import as_project_path
from alex.corpustools.wavaskey import save_wavaskey
from alex.components.slu.base import CategoryLabelDatabase
from alex.components.asr.utterance import Utter... | 0.424531 | 0.174358 |
from hashlib import sha1
import json
def generate_config(context):
""" Entry point for the deployment resources. """
properties = context.properties
project_id = properties.get('project', context.env['project'])
name = context.env['name']
# Set the common route properties.
res_properties = {... | dm/templates/route/single_route.py | from hashlib import sha1
import json
def generate_config(context):
""" Entry point for the deployment resources. """
properties = context.properties
project_id = properties.get('project', context.env['project'])
name = context.env['name']
# Set the common route properties.
res_properties = {... | 0.754192 | 0.1443 |
from glob import glob
from jug import TaskGenerator, CachedFunction, barrier
from projections import load_gf_projection
def blocks_of(xs, n):
xs = list(xs)
while xs:
yield xs[:n]
xs = xs[n:]
_gfd = None
@TaskGenerator
def project_files(us):
import pandas as pd
global _gfd
if _gfd ... | profiles-all/gene.profiles/abundance.gf.py | from glob import glob
from jug import TaskGenerator, CachedFunction, barrier
from projections import load_gf_projection
def blocks_of(xs, n):
xs = list(xs)
while xs:
yield xs[:n]
xs = xs[n:]
_gfd = None
@TaskGenerator
def project_files(us):
import pandas as pd
global _gfd
if _gfd ... | 0.299822 | 0.235955 |
import socket
import struct
import sys
HOST='192.168.0.212'
PORT=5050
#建立socket对象 定义socket类型,网络通信,TCP
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, e:
print 'Strange error creating socket:%s' % e
sys.exit(1)
#mid 创建连接 connect()连接成功后才返回,否则阻塞,无返回值
try:
s.c... | BasicOperations/17_socket/client_getKDataFromMtServer.py | import socket
import struct
import sys
HOST='192.168.0.212'
PORT=5050
#建立socket对象 定义socket类型,网络通信,TCP
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, e:
print 'Strange error creating socket:%s' % e
sys.exit(1)
#mid 创建连接 connect()连接成功后才返回,否则阻塞,无返回值
try:
s.c... | 0.079175 | 0.109372 |
import logging
import plotly.graph_objects as go
from bots import imps, load_candle
from openbb_terminal.common.technical_analysis import overlap_model
from openbb_terminal.decorators import log_start_end
logger = logging.getLogger(__name__)
# pylint: disable=R0913
@log_start_end(log=logger)
def ma_command(
ti... | bots/stocks/technical_analysis/ma.py | import logging
import plotly.graph_objects as go
from bots import imps, load_candle
from openbb_terminal.common.technical_analysis import overlap_model
from openbb_terminal.decorators import log_start_end
logger = logging.getLogger(__name__)
# pylint: disable=R0913
@log_start_end(log=logger)
def ma_command(
ti... | 0.598312 | 0.241668 |
try:
import rest_framework
except ImportError as exc: # pragma: no cover
raise ImportError("Package 'djangorestframework' is required to use this module.") from exc
import rest_framework.fields
from cl_sii.rut import Rut
class RutField(rest_framework.fields.CharField):
"""
DRF field for RUT.
... | cl_sii/extras/drf_fields.py | try:
import rest_framework
except ImportError as exc: # pragma: no cover
raise ImportError("Package 'djangorestframework' is required to use this module.") from exc
import rest_framework.fields
from cl_sii.rut import Rut
class RutField(rest_framework.fields.CharField):
"""
DRF field for RUT.
... | 0.749271 | 0.299012 |
from __future__ import unicode_literals
from django.contrib.contenttypes.models import ContentType
from django.core.apps.cache import AppCache
from django.db import models
from django.test import TestCase
from .models import Author, Article
class ContentTypesViewsTests(TestCase):
fixtures = ['testdata.json']
... | tests/contenttypes_tests/tests.py | from __future__ import unicode_literals
from django.contrib.contenttypes.models import ContentType
from django.core.apps.cache import AppCache
from django.db import models
from django.test import TestCase
from .models import Author, Article
class ContentTypesViewsTests(TestCase):
fixtures = ['testdata.json']
... | 0.489259 | 0.190065 |
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class MaskedColumnSummary(object):
"""
Summary of a masked column. A masked column is a database column masked by a... | src/oci/data_safe/models/masked_column_summary.py |
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class MaskedColumnSummary(object):
"""
Summary of a masked column. A masked column is a database column masked by a... | 0.854019 | 0.380385 |
import os
import math
import random
import io
import urllib
import re
import ast
import html
import http
import flask
import mwoauth
import mwclient
import yaml
import sqlalchemy
import piexif
import backoff
from PIL import Image
app = flask.Flask(__name__)
DESCRIPTION_TEMPLATE = """== {{{{int:filedesc}}}} ==
{{... | app.py | import os
import math
import random
import io
import urllib
import re
import ast
import html
import http
import flask
import mwoauth
import mwclient
import yaml
import sqlalchemy
import piexif
import backoff
from PIL import Image
app = flask.Flask(__name__)
DESCRIPTION_TEMPLATE = """== {{{{int:filedesc}}}} ==
{{... | 0.347759 | 0.082883 |
import datetime
class dt:
def weekend(n=999):
"""
:return bool:
n = 0, 1, 2, 3, 4, 5, 6
"""
n = datetime.datetime.today().weekday() if n == 999 else n
return True if n in [5, 6] else False
def choose_format(choice="%m/%d/%Y, %H:%M:%S"):
return datetime.... | date_tools.py | import datetime
class dt:
def weekend(n=999):
"""
:return bool:
n = 0, 1, 2, 3, 4, 5, 6
"""
n = datetime.datetime.today().weekday() if n == 999 else n
return True if n in [5, 6] else False
def choose_format(choice="%m/%d/%Y, %H:%M:%S"):
return datetime.... | 0.435421 | 0.512205 |
from flask import Flask, render_template, request, g, flash, redirect, url_for
import openaq
from .models import DB, Record
from .forms import SelectCityForm
def create_app():
"""Create and configure an instance of the Flask application."""
app = Flask(__name__)
app.secret_key = 'super secret key'
app... | aq_dashboard.py | from flask import Flask, render_template, request, g, flash, redirect, url_for
import openaq
from .models import DB, Record
from .forms import SelectCityForm
def create_app():
"""Create and configure an instance of the Flask application."""
app = Flask(__name__)
app.secret_key = 'super secret key'
app... | 0.663233 | 0.129458 |
import logging
from typing import Tuple, Dict
class DialogueManager(object):
"""
| The current control flow of dialogue is:
| 1. A chat comes in and Dialogue manager reads it or the bot triggers a
| dialogue because of memory/perception/task state
| 2. The dialogue manage launches an Interpre... | droidlet/dialog/dialogue_manager.py | import logging
from typing import Tuple, Dict
class DialogueManager(object):
"""
| The current control flow of dialogue is:
| 1. A chat comes in and Dialogue manager reads it or the bot triggers a
| dialogue because of memory/perception/task state
| 2. The dialogue manage launches an Interpre... | 0.457621 | 0.238983 |
from dataclasses import dataclass
from typing import List
import aiohttp
from tastyworks.models.order import Order, OrderPriceEffect
@dataclass
class TradingAccount(object):
account_number: str
external_id: str
is_margin: bool
is_closed: bool
account_type_name: str
nickname: str
opened_a... | tastyworks/models/trading_account.py | from dataclasses import dataclass
from typing import List
import aiohttp
from tastyworks.models.order import Order, OrderPriceEffect
@dataclass
class TradingAccount(object):
account_number: str
external_id: str
is_margin: bool
is_closed: bool
account_type_name: str
nickname: str
opened_a... | 0.864282 | 0.272865 |
from tkinter import Tk, Label, Frame, Button, StringVar, PhotoImage, ttk
from PIL import ImageTk, Image
import pytube.contrib.search
from pytube import YouTube
import os, stat, requests, tkinter as tk
name_image = "video_image.png"
class search:
def __init__(self, words):
self.search_words = str(pytube.con... | main.pyw | from tkinter import Tk, Label, Frame, Button, StringVar, PhotoImage, ttk
from PIL import ImageTk, Image
import pytube.contrib.search
from pytube import YouTube
import os, stat, requests, tkinter as tk
name_image = "video_image.png"
class search:
def __init__(self, words):
self.search_words = str(pytube.con... | 0.438304 | 0.182171 |
import tensorflow as tf
from pathlib import Path
from data.processing.component import DataProcessing, DataProcessingConfig
from data.processing.source import LocalVideoSource, SourceConfig
from data.processing.process import VideoProcessor, ProcessorConfig
from inference import Predictor, PredictorConfig, AnomalyScor... | inference/tests/test_predictor.py | import tensorflow as tf
from pathlib import Path
from data.processing.component import DataProcessing, DataProcessingConfig
from data.processing.source import LocalVideoSource, SourceConfig
from data.processing.process import VideoProcessor, ProcessorConfig
from inference import Predictor, PredictorConfig, AnomalyScor... | 0.652574 | 0.348313 |
from datetime import datetime
from zope.component import getUtilitiesFor, getUtility
from zope.i18n import translate
from zope.interface import implementer
from zope.exceptions.interfaces import UserError
from zope.i18nmessageid import ZopeMessageFactory as _
from zope.security.interfaces import IPermission
from zope... | src/zope/app/authentication/browser/rolepermissionview.py | from datetime import datetime
from zope.component import getUtilitiesFor, getUtility
from zope.i18n import translate
from zope.interface import implementer
from zope.exceptions.interfaces import UserError
from zope.i18nmessageid import ZopeMessageFactory as _
from zope.security.interfaces import IPermission
from zope... | 0.690037 | 0.164449 |
import json
from collections import namedtuple
from pathlib import Path
import torch
from torch.utils.data import Dataset
from PIL import Image
annotations = namedtuple('Annotations',['image_id','sentences'])
class Flickr8k(Dataset):
""" for flickr 8k dataset."""
def __init__(self, img_dir, ann_file, vocab,... | aeye/datasets.py | import json
from collections import namedtuple
from pathlib import Path
import torch
from torch.utils.data import Dataset
from PIL import Image
annotations = namedtuple('Annotations',['image_id','sentences'])
class Flickr8k(Dataset):
""" for flickr 8k dataset."""
def __init__(self, img_dir, ann_file, vocab,... | 0.791539 | 0.356419 |
import pytest
from pywxclient.core.message import TextMessage, ImageMessage, FileMessage
class TestMessage:
@pytest.mark.parametrize(
'from_user, to_user, message', (
('@aaaa', '@bbbbb', 'haahahha'),
('@fwewf', '@swefewfwe', 'heeheheh'),
('@swfewwf', '@wjwejrjwe', '你好... | resources/good/test_message.py | import pytest
from pywxclient.core.message import TextMessage, ImageMessage, FileMessage
class TestMessage:
@pytest.mark.parametrize(
'from_user, to_user, message', (
('@aaaa', '@bbbbb', 'haahahha'),
('@fwewf', '@swefewfwe', 'heeheheh'),
('@swfewwf', '@wjwejrjwe', '你好... | 0.407805 | 0.340979 |
import os
import sys
import argparse
from roblib import message, stream_fastq
__author__ = '<NAME>'
__copyright__ = 'Copyright 2020, <NAME>'
__credits__ = ['<NAME>']
__license__ = 'MIT'
__maintainer__ = '<NAME>'
__email__ = '<EMAIL>'
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=" ")
... | fastq/trim_fastq.py | import os
import sys
import argparse
from roblib import message, stream_fastq
__author__ = '<NAME>'
__copyright__ = 'Copyright 2020, <NAME>'
__credits__ = ['<NAME>']
__license__ = 'MIT'
__maintainer__ = '<NAME>'
__email__ = '<EMAIL>'
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=" ")
... | 0.246715 | 0.058885 |
from typing import NamedTuple
class Setpoints(NamedTuple):
U_Blow: float # Heat blower control
U_Boil: float # Boiler control
U_MechCool: float # Control of the mechanical cooling
U_Fog: float # Control of fogging system
U_Roof: float # Control of the roof ventilators
U_Side: float # Con... | data_models.py | from typing import NamedTuple
class Setpoints(NamedTuple):
U_Blow: float # Heat blower control
U_Boil: float # Boiler control
U_MechCool: float # Control of the mechanical cooling
U_Fog: float # Control of fogging system
U_Roof: float # Control of the roof ventilators
U_Side: float # Con... | 0.891858 | 0.65063 |
from collections.abc import MutableMapping
from typing import Dict, Any
from collections import deque
from copy import deepcopy
from tree import JsonTree
class JSONDict(MutableMapping):
def __init__(self, json_dict):
"""Takes a dictionary with JSON-like data and creates an instance that
be... | python3/flat_json.py | from collections.abc import MutableMapping
from typing import Dict, Any
from collections import deque
from copy import deepcopy
from tree import JsonTree
class JSONDict(MutableMapping):
def __init__(self, json_dict):
"""Takes a dictionary with JSON-like data and creates an instance that
be... | 0.802207 | 0.170957 |
import mpl_finance as mpf # 替换 import matplotlib.finance as mpf
import numpy as np
import matplotlib.pyplot as plt
class DefTypesPool():
def __init__(self):
self.routes = {}
def route_types(self, types_str):
def decorator(f):
self.routes[types_str] = f
return f
... | MplVisualIf.py | import mpl_finance as mpf # 替换 import matplotlib.finance as mpf
import numpy as np
import matplotlib.pyplot as plt
class DefTypesPool():
def __init__(self):
self.routes = {}
def route_types(self, types_str):
def decorator(f):
self.routes[types_str] = f
return f
... | 0.18396 | 0.3694 |
from string import ascii_lowercase as alphabet
import pytest
import cirq
from cirq.contrib.acquaintance.shift import (
CircularShiftGate)
from cirq.contrib.acquaintance.permutation import (
LinearPermutationGate, SwapPermutationGate)
from cirq.contrib.acquaintance.strategy import (
rectify_acquai... | cirq/contrib/acquaintance/strategy_test.py |
from string import ascii_lowercase as alphabet
import pytest
import cirq
from cirq.contrib.acquaintance.shift import (
CircularShiftGate)
from cirq.contrib.acquaintance.permutation import (
LinearPermutationGate, SwapPermutationGate)
from cirq.contrib.acquaintance.strategy import (
rectify_acquai... | 0.623148 | 0.51379 |
def extractBananas(item):
"""
Parser for 'Bananas'
"""
badwords = [
'iya na kao manga chapters',
]
if any([bad in item['tags'] for bad in badwords]):
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
r... | WebMirror/management/rss_parser_funcs/feed_parse_extractBananas.py | def extractBananas(item):
"""
Parser for 'Bananas'
"""
badwords = [
'iya na kao manga chapters',
]
if any([bad in item['tags'] for bad in badwords]):
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
r... | 0.249722 | 0.284974 |
from unittest import TestCase
import json
import operator
import re
from bfs import Bfs
class TestBfsEntities(TestCase):
def setUp(self):
try:
with open('../../config.json') as f:
self.config = json.load(f)
except FileNotFoundError:
print('config.json is n... | bfs/tests/test_bfs_entities.py | from unittest import TestCase
import json
import operator
import re
from bfs import Bfs
class TestBfsEntities(TestCase):
def setUp(self):
try:
with open('../../config.json') as f:
self.config = json.load(f)
except FileNotFoundError:
print('config.json is n... | 0.65202 | 0.407451 |
import datetime
import random
import sys
import bz2
import time
import traceback
import itertools
from functools import partial
from pathlib import Path, PurePosixPath
from typing import Iterable, Union, Optional, Tuple, Callable, Literal, List
from urllib.parse import unquote, urlparse
from dateutil.relativedelta impo... | lsde2021/download.py | import datetime
import random
import sys
import bz2
import time
import traceback
import itertools
from functools import partial
from pathlib import Path, PurePosixPath
from typing import Iterable, Union, Optional, Tuple, Callable, Literal, List
from urllib.parse import unquote, urlparse
from dateutil.relativedelta impo... | 0.527317 | 0.138491 |
import os
import sys
import datetime
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
import pytorch_lightning as pl
# os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
aa_idx = {"X": 0, "A": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6, "H": 7, "I": 8, "K": 9, "L": 10,
... | scripts/process.py | import os
import sys
import datetime
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
import pytorch_lightning as pl
# os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
aa_idx = {"X": 0, "A": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6, "H": 7, "I": 8, "K": 9, "L": 10,
... | 0.711732 | 0.320183 |
from ...ucsmo import ManagedObject
from ...ucscoremeta import MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class OsMiiLinkMonitoringPolicyConsts:
LINK_STATUS_QUERY_TYPE_ETHTOOL = "ethtool"
LINK_STATUS_QUERY_TYPE_NETIF = "netif"
class OsMiiLinkMonitoringPolicy(ManagedObject):
"""This is OsM... | ucsmsdk/mometa/os/OsMiiLinkMonitoringPolicy.py |
from ...ucsmo import ManagedObject
from ...ucscoremeta import MoPropertyMeta, MoMeta
from ...ucsmeta import VersionMeta
class OsMiiLinkMonitoringPolicyConsts:
LINK_STATUS_QUERY_TYPE_ETHTOOL = "ethtool"
LINK_STATUS_QUERY_TYPE_NETIF = "netif"
class OsMiiLinkMonitoringPolicy(ManagedObject):
"""This is OsM... | 0.500244 | 0.127137 |
from casadi import *
import numpy as NP
import matplotlib.pyplot as plt
# Degree of interpolating polynomial
d = 3
# Choose collocation points
tau_root = [0] + collocation_points(d, "radau")
# Coefficients of the collocation equation
C = NP.zeros((d+1,d+1))
# Coefficients of the continuity equation
D = NP.zeros(d+1... | mpc/kmpc_casadi/utility/casadi-example_pack-v3.4.4/python/vdp_collocation.py | from casadi import *
import numpy as NP
import matplotlib.pyplot as plt
# Degree of interpolating polynomial
d = 3
# Choose collocation points
tau_root = [0] + collocation_points(d, "radau")
# Coefficients of the collocation equation
C = NP.zeros((d+1,d+1))
# Coefficients of the continuity equation
D = NP.zeros(d+1... | 0.632276 | 0.657731 |
import numpy as np
import pandas as pd
import pytest
import scipy.stats
from pyextremes.models import Emcee, get_model
@pytest.fixture(scope="function")
def extremes() -> pd.Series:
np.random.seed(0)
return pd.Series(
index=pd.date_range(start="2000-01-01", periods=1000, freq="1H"),
data=scip... | tests/models/test_model_emcee.py | import numpy as np
import pandas as pd
import pytest
import scipy.stats
from pyextremes.models import Emcee, get_model
@pytest.fixture(scope="function")
def extremes() -> pd.Series:
np.random.seed(0)
return pd.Series(
index=pd.date_range(start="2000-01-01", periods=1000, freq="1H"),
data=scip... | 0.748536 | 0.552419 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from config import cfg
def count_trainable_parameters(model):
""" to count trainable parameters """
return sum(p.numel() for p in model.parameters() if p.requires_grad)
class double_conv(nn.Module):
""" implements two Conv-BatchNorm bloc... | model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from config import cfg
def count_trainable_parameters(model):
""" to count trainable parameters """
return sum(p.numel() for p in model.parameters() if p.requires_grad)
class double_conv(nn.Module):
""" implements two Conv-BatchNorm bloc... | 0.93318 | 0.597608 |
from scipy import signal
from PIL import Image
import cv2
import numpy
import math
import imageio
# Locating the image. If the image is not same then change to relative address.
usedImage = '../../Images/test.jpg'
# Opening the image into an array
img = numpy.array(Image.open(usedImage).convert("L"))
imageio.imwrite(... | Codes/Canny-Edge/canny.py | from scipy import signal
from PIL import Image
import cv2
import numpy
import math
import imageio
# Locating the image. If the image is not same then change to relative address.
usedImage = '../../Images/test.jpg'
# Opening the image into an array
img = numpy.array(Image.open(usedImage).convert("L"))
imageio.imwrite(... | 0.540681 | 0.586523 |
# TODO(littlecvr): Implement "without filter mode", which lets OEM encrypts DRM
# keys directly with ODM's public key, and the key server
# merely stores them without knowing anything about them.
import argparse
import hashlib
import imp
import json
import logging
import logging.confi... | py/dkps/dkps.py | # TODO(littlecvr): Implement "without filter mode", which lets OEM encrypts DRM
# keys directly with ODM's public key, and the key server
# merely stores them without knowing anything about them.
import argparse
import hashlib
import imp
import json
import logging
import logging.confi... | 0.468791 | 0.116714 |
from typing import List
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm.exc import NoResultFound
from odp.api.models.institution import Institution
from odp.db import transaction
from odp.db.models import Institution as InstitutionORM, Domain
from odp.lib import exceptions as x
def create_or_update_in... | odp/lib/institutions.py | from typing import List
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm.exc import NoResultFound
from odp.api.models.institution import Institution
from odp.db import transaction
from odp.db.models import Institution as InstitutionORM, Domain
from odp.lib import exceptions as x
def create_or_update_in... | 0.720958 | 0.306942 |
class database:
def __init__ (self):
self.states = {"Massachusetts":"MA"}
self.capitals = {"MA":"Boston"}
def displayStates(self):
for i in self.states:
print("\n",i)
def addState(self):
fullname=input("\nWhat is the state's full name? ")
... | lab13.py | class database:
def __init__ (self):
self.states = {"Massachusetts":"MA"}
self.capitals = {"MA":"Boston"}
def displayStates(self):
for i in self.states:
print("\n",i)
def addState(self):
fullname=input("\nWhat is the state's full name? ")
... | 0.338514 | 0.389488 |
from collections import defaultdict
from django.conf import settings
from drf_model_pusher.providers import PusherProvider
from drf_model_pusher.signals import view_pre_destroy, view_post_save
pusher_backend_registry = defaultdict(list)
class PusherBackendMetaclass(type):
"""
Register PusherBackend's with ... | drf_model_pusher/backends.py | from collections import defaultdict
from django.conf import settings
from drf_model_pusher.providers import PusherProvider
from drf_model_pusher.signals import view_pre_destroy, view_post_save
pusher_backend_registry = defaultdict(list)
class PusherBackendMetaclass(type):
"""
Register PusherBackend's with ... | 0.888457 | 0.213009 |
import math
import pytest
import requests_mock
from rpcq.core_messages import BinaryExecutableResponse
from pyquil import Program
from pyquil.api._base_connection import get_session
from pyquil.api._compiler import QPUCompiler
from pyquil.api._config import PyquilConfig
from pyquil.api._errors import UserMessageError... | pyquil/api/tests/test_compiler.py | import math
import pytest
import requests_mock
from rpcq.core_messages import BinaryExecutableResponse
from pyquil import Program
from pyquil.api._base_connection import get_session
from pyquil.api._compiler import QPUCompiler
from pyquil.api._config import PyquilConfig
from pyquil.api._errors import UserMessageError... | 0.511717 | 0.254011 |
import gatt
import queue
import time
import threading
# Internal Dependencies
from pyroot import RootPhy
class RootGATT(RootPhy):
root_identifier_uuid = '48c5d828-ac2a-442d-97a3-0c9822b04979'
def __init__(self, name = None, dev = 'hci0', wait_for_connect = True):
"""Sets up Bluetooth manager to look ... | pyroot/phy_gatt.py | import gatt
import queue
import time
import threading
# Internal Dependencies
from pyroot import RootPhy
class RootGATT(RootPhy):
root_identifier_uuid = '48c5d828-ac2a-442d-97a3-0c9822b04979'
def __init__(self, name = None, dev = 'hci0', wait_for_connect = True):
"""Sets up Bluetooth manager to look ... | 0.721449 | 0.148479 |
import numpy as np
import os
import scipy.signal
class PitchBihist:
def __init__(self, win2sec=8):
self.win2sec = win2sec
self.hop2sec = 0.5
self.melody_sr = 44100. / 128.
def hz_to_cents(self, freq_Hz, ref_Hz=32.703, n_cents=1200):
""" convert frequency values from Hz to cen... | lib/PitchBihist.py | import numpy as np
import os
import scipy.signal
class PitchBihist:
def __init__(self, win2sec=8):
self.win2sec = win2sec
self.hop2sec = 0.5
self.melody_sr = 44100. / 128.
def hz_to_cents(self, freq_Hz, ref_Hz=32.703, n_cents=1200):
""" convert frequency values from Hz to cen... | 0.466116 | 0.343122 |
import numpy as np
from scipy.stats.mstats import gmean
from dpn.storable import Storable
class SizeDistribution(Storable):
"""Class to store sizedistributions and determine their characterstics."""
def __init__(self, unit):
"""Create and initialize a SizeDistribution object.
:param unit: Ei... | dpn/sizedistribution.py | import numpy as np
from scipy.stats.mstats import gmean
from dpn.storable import Storable
class SizeDistribution(Storable):
"""Class to store sizedistributions and determine their characterstics."""
def __init__(self, unit):
"""Create and initialize a SizeDistribution object.
:param unit: Ei... | 0.936706 | 0.830285 |
import csv
import json
from .portal import Client
class Parser:
def __init__(self, config_filename, csv_filename):
self.csv_filename = csv_filename
self.config = self._load_config(config_filename)
self.client = Client(self.config['access_token'], self.config['enterprise_account'], endpoin... | xmcuserimporter/parser.py | import csv
import json
from .portal import Client
class Parser:
def __init__(self, config_filename, csv_filename):
self.csv_filename = csv_filename
self.config = self._load_config(config_filename)
self.client = Client(self.config['access_token'], self.config['enterprise_account'], endpoin... | 0.186243 | 0.078078 |
from typing import List, Tuple
import pandas as pd
class AgodaCancellationPreprocessor:
SATURDAY = 5
def __init__(self, full_data: pd.DataFrame):
self.number_of_times_customer_canceled = dict()
for id, cancellation in full_data[
["h_customer_id", "cancellation_datetime"]].itertup... | challenge/agoda_cancellation_preprocessor.py | from typing import List, Tuple
import pandas as pd
class AgodaCancellationPreprocessor:
SATURDAY = 5
def __init__(self, full_data: pd.DataFrame):
self.number_of_times_customer_canceled = dict()
for id, cancellation in full_data[
["h_customer_id", "cancellation_datetime"]].itertup... | 0.577495 | 0.243246 |
import os
import vagrant
import click
import yaml
import re
import socket
import time
@click.command()
@click.option("--cluster", "-c", default="none", help="Name of cluster ('app' or 'infra')")
@click.option("--pull", "-p", default=True, help="whether pull images before deployment (True or False)")
def run(cluster, ... | deploy.py | import os
import vagrant
import click
import yaml
import re
import socket
import time
@click.command()
@click.option("--cluster", "-c", default="none", help="Name of cluster ('app' or 'infra')")
@click.option("--pull", "-p", default=True, help="whether pull images before deployment (True or False)")
def run(cluster, ... | 0.171477 | 0.113211 |
import numpy
from copy import deepcopy
from handwriting_features.data.utils.math import derivation
from handwriting_features.data.utils.dsp import LowPassFilter, GaussianFilter
from handwriting_features.features.implementation.conventional.spatial import stroke_length
from handwriting_features.features.implementation.c... | src/handwriting_features/features/implementation/conventional/utils/composite.py | import numpy
from copy import deepcopy
from handwriting_features.data.utils.math import derivation
from handwriting_features.data.utils.dsp import LowPassFilter, GaussianFilter
from handwriting_features.features.implementation.conventional.spatial import stroke_length
from handwriting_features.features.implementation.c... | 0.828696 | 0.515681 |
import argparse
from pathlib import Path
from bc81asmc_ast import *
from bc81asmc_grammar import program
def read_input_file(fname):
with open(fname, 'r', encoding='utf8') as file_handle:
return file_handle.read()
def compile(ast, verbose):
context = CodeContext()
labeladdresses = {}
if verbos... | bc81asmc/bc81asmc.py | import argparse
from pathlib import Path
from bc81asmc_ast import *
from bc81asmc_grammar import program
def read_input_file(fname):
with open(fname, 'r', encoding='utf8') as file_handle:
return file_handle.read()
def compile(ast, verbose):
context = CodeContext()
labeladdresses = {}
if verbos... | 0.277865 | 0.14557 |
from PIL import Image
from load_data_utils import get_transforms
import json
import matplotlib.pyplot as plt
def print_train_config(args):
# Print all properties prior to training
print("=============== Training Configuration =============")
print("Architecture: {}".format(args.arch))
print("Learning R... | helper_utils.py | from PIL import Image
from load_data_utils import get_transforms
import json
import matplotlib.pyplot as plt
def print_train_config(args):
# Print all properties prior to training
print("=============== Training Configuration =============")
print("Architecture: {}".format(args.arch))
print("Learning R... | 0.565659 | 0.394959 |
import unittest
from R_ev3dev.interpreter import Interpreter, Command, Reference
class ExceptionCommand(Command):
class TestError(Exception):
pass
def invoke(self, interpreter_context, args):
return interpreter_context.throw(ExceptionCommand.TestError())
class TestCommandInt(Command):
d... | tests/test_interpreter.py | import unittest
from R_ev3dev.interpreter import Interpreter, Command, Reference
class ExceptionCommand(Command):
class TestError(Exception):
pass
def invoke(self, interpreter_context, args):
return interpreter_context.throw(ExceptionCommand.TestError())
class TestCommandInt(Command):
d... | 0.597256 | 0.50238 |
from __future__ import print_function
import os, json
import tornado.httpserver
import tornado.ioloop
import tornado.web
from opcua import Client
from .info import __version__
class IndexHandler(tornado.web.RequestHandler):
def get(self):
with open(os.path.join(os.path.dirname(__file__), 'index.html')) as... | opcuawebclient/mainserver.py | from __future__ import print_function
import os, json
import tornado.httpserver
import tornado.ioloop
import tornado.web
from opcua import Client
from .info import __version__
class IndexHandler(tornado.web.RequestHandler):
def get(self):
with open(os.path.join(os.path.dirname(__file__), 'index.html')) as... | 0.180829 | 0.078008 |
# адреса ASSIST
TEST_SERVER = 'https://test.paysec.by'
REAL_SERVER = 'https://secure.assist.ru'
MODE1_PATH = '/shops/purchase.cfm'
MODE2_PATH = '/pay/order.cfm'
GET_RESULTS_PATH = '/orderstate/orderstate.cfm'
CHARGE_PATH = "/charge/charge.cfm"
REFUND_PATH = "/rvr/rvr.cfm"
# форматы ответа на запрос
ASSIST_FORMAT_CSV... | assist/constants.py |
# адреса ASSIST
TEST_SERVER = 'https://test.paysec.by'
REAL_SERVER = 'https://secure.assist.ru'
MODE1_PATH = '/shops/purchase.cfm'
MODE2_PATH = '/pay/order.cfm'
GET_RESULTS_PATH = '/orderstate/orderstate.cfm'
CHARGE_PATH = "/charge/charge.cfm"
REFUND_PATH = "/rvr/rvr.cfm"
# форматы ответа на запрос
ASSIST_FORMAT_CSV... | 0.269422 | 0.185467 |
from .common import RWS_DEFAULT_OPTIONS
from tethysext.atcore.models.resource_workflow_steps import SetStatusRWS
from tethysext.atcore.tests.utilities.sqlalchemy_helpers import SqlAlchemyTestCase
from tethysext.atcore.tests.utilities.sqlalchemy_helpers import setup_module_for_sqlalchemy_tests,\
tear_down_module_for... | tethysext/atcore/tests/integrated_tests/models/resource_workflow_steps/set_status_rws_tests.py | from .common import RWS_DEFAULT_OPTIONS
from tethysext.atcore.models.resource_workflow_steps import SetStatusRWS
from tethysext.atcore.tests.utilities.sqlalchemy_helpers import SqlAlchemyTestCase
from tethysext.atcore.tests.utilities.sqlalchemy_helpers import setup_module_for_sqlalchemy_tests,\
tear_down_module_for... | 0.542136 | 0.220007 |
import pandas as pd
import os
from ..._utils.converter import SynoDict
# concrete class
class Biomart():
def __init__(self):
self.__fileprefix = "mart_export_" # hard coding
self.__sp_dict = {"human":"HGNC", # hard coding
"mouse":"MGI", # hard coding
... | geneutil/dwh/dictionary/biomart.py | import pandas as pd
import os
from ..._utils.converter import SynoDict
# concrete class
class Biomart():
def __init__(self):
self.__fileprefix = "mart_export_" # hard coding
self.__sp_dict = {"human":"HGNC", # hard coding
"mouse":"MGI", # hard coding
... | 0.297674 | 0.143098 |
import os
import unittest
import logging
import datetime
import statis
import json
from dateutil.parser import parse
REDIS_HOST = os.environ.get('STATIS_REDIS_HOST','statis-redis')
REDIS_PORT = os.environ.get('STATIS_REDIS_PORT','6379')
class StatisTestCase(unittest.TestCase):
filepath = 'tests/ufos.tsv'
cou... | test.py | import os
import unittest
import logging
import datetime
import statis
import json
from dateutil.parser import parse
REDIS_HOST = os.environ.get('STATIS_REDIS_HOST','statis-redis')
REDIS_PORT = os.environ.get('STATIS_REDIS_PORT','6379')
class StatisTestCase(unittest.TestCase):
filepath = 'tests/ufos.tsv'
cou... | 0.341253 | 0.119897 |
import unittest
from references.domain import Reference
from references.process.merge import arbitrate
class TestArbitrate(unittest.TestCase):
"""Tests for :func:`.process.merge.arbitrate.arbitrate` function."""
def test_arbitrate(self):
"""Successful arbitration with valid data."""
metadata... | references/process/merge/tests/test_arbitrate.py |
import unittest
from references.domain import Reference
from references.process.merge import arbitrate
class TestArbitrate(unittest.TestCase):
"""Tests for :func:`.process.merge.arbitrate.arbitrate` function."""
def test_arbitrate(self):
"""Successful arbitration with valid data."""
metadata... | 0.783782 | 0.671763 |
"""Cleans the LaTeX code of your paper to submit to arXiv."""
import argparse
import collections
import json
import os
import re
import shutil
from PIL import Image
# Fix for Windows: Even if '\' (os.sep) is the standard way of making paths on
# Windows, it interferes with regular expressions. We just change os.sep... | arxiv_latex_cleaner.py |
"""Cleans the LaTeX code of your paper to submit to arXiv."""
import argparse
import collections
import json
import os
import re
import shutil
from PIL import Image
# Fix for Windows: Even if '\' (os.sep) is the standard way of making paths on
# Windows, it interferes with regular expressions. We just change os.sep... | 0.47171 | 0.210523 |
class EmptyDequeError(Exception):
"""
Custom Error for empty Deque.
"""
pass
class Deque:
"""
Deque: Hybrid Data Structure.
Operations:
addFront(item)
addRear(item)
removeFront()
removeRear()
isEmpty()
size(... | python-dsa/Section2/deque.py | class EmptyDequeError(Exception):
"""
Custom Error for empty Deque.
"""
pass
class Deque:
"""
Deque: Hybrid Data Structure.
Operations:
addFront(item)
addRear(item)
removeFront()
removeRear()
isEmpty()
size(... | 0.789396 | 0.589007 |
"""Contains error handling and the help and about commands"""
from datetime import datetime
import discord
from discord.commands import slash_command
from discord.ext import commands
import database
from resources import emojis, logs, settings
class MainCog(commands.Cog):
"""Cog with events and help and about ... | cogs/main.py | """Contains error handling and the help and about commands"""
from datetime import datetime
import discord
from discord.commands import slash_command
from discord.ext import commands
import database
from resources import emojis, logs, settings
class MainCog(commands.Cog):
"""Cog with events and help and about ... | 0.713931 | 0.388676 |
import pprint
import re # noqa: F401
import six
from jamf.configuration import Configuration
class AppleTvDetails(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_type... | jamf/models/apple_tv_details.py | import pprint
import re # noqa: F401
import six
from jamf.configuration import Configuration
class AppleTvDetails(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_type... | 0.651022 | 0.079531 |
import os
import shutil
ogreBinariesPath = os.path.abspath( '../../../build/Android/' )
ogreSourcePath = os.path.abspath( '../../../' )
sampleNames = [ \
"AnimationTagPoint",
"AreaApproxLights",
"CustomRenderable",
"Decals",
"DynamicGeometry",
"Forward3D",
"Hdr",
"HdrSmaa",
"IesProfiles",
"ImportAnimations... | Samples/2.0/AndroidAppTemplate/GenTemplate.py |
import os
import shutil
ogreBinariesPath = os.path.abspath( '../../../build/Android/' )
ogreSourcePath = os.path.abspath( '../../../' )
sampleNames = [ \
"AnimationTagPoint",
"AreaApproxLights",
"CustomRenderable",
"Decals",
"DynamicGeometry",
"Forward3D",
"Hdr",
"HdrSmaa",
"IesProfiles",
"ImportAnimations... | 0.169819 | 0.24416 |
import httplib2
import os
from pprint import pprint
from apiclient import discovery
import datetime
import pandas as pd
import gmail_api_quickstart
from datadog import statsd
label_cypher = None
def get_label_id(label):
global label_cypher
if label_cypher is None:
service = get_service()
res... | gmail_metrics_collector.py | import httplib2
import os
from pprint import pprint
from apiclient import discovery
import datetime
import pandas as pd
import gmail_api_quickstart
from datadog import statsd
label_cypher = None
def get_label_id(label):
global label_cypher
if label_cypher is None:
service = get_service()
res... | 0.192501 | 0.107297 |
__version__ = "0.0.1"
import math
from array import array
from argparse import ArgumentParser
from PIL import Image
RGB_COLOR_COUNT = 256
GRAYSCALE_COLOR_COUNT = 256
def get_int_from_rgb(rgb):
if isinstance(rgb, tuple):
red = rgb[0]
green = rgb[1]
blue = rgb[2]
rgb_int = (red<<16) ... | png2sp1sprite/png2btile.py |
__version__ = "0.0.1"
import math
from array import array
from argparse import ArgumentParser
from PIL import Image
RGB_COLOR_COUNT = 256
GRAYSCALE_COLOR_COUNT = 256
def get_int_from_rgb(rgb):
if isinstance(rgb, tuple):
red = rgb[0]
green = rgb[1]
blue = rgb[2]
rgb_int = (red<<16) ... | 0.371935 | 0.370709 |
import sys
from PyQt5.QtCore import QCoreApplication
from PyQt5.QtGui import QTextCharFormat, QTextCursor, QColor
from PyQt5.QtWidgets import (QApplication, QWidget, QTextEdit)
import reg2nfa
import nfa2dfa
import statemanager
import time
import os
class TextEdit(QWidget):
def __init__(self, regex='a*li', txt="al... | textSearchGui.py | import sys
from PyQt5.QtCore import QCoreApplication
from PyQt5.QtGui import QTextCharFormat, QTextCursor, QColor
from PyQt5.QtWidgets import (QApplication, QWidget, QTextEdit)
import reg2nfa
import nfa2dfa
import statemanager
import time
import os
class TextEdit(QWidget):
def __init__(self, regex='a*li', txt="al... | 0.097923 | 0.082734 |
import json
from dataclasses import asdict, astuple, dataclass, fields
from typing import List
from util import dataclassToJson
presetSubjects = [
['ASC', 'Academic Support Center'],
['AEE', 'Aerospace Engineering'],
['AVF', 'Aviation Flight'],
['AHF', 'Aviation Human Factors'],
['AVM', 'Aviation ... | subject.py | import json
from dataclasses import asdict, astuple, dataclass, fields
from typing import List
from util import dataclassToJson
presetSubjects = [
['ASC', 'Academic Support Center'],
['AEE', 'Aerospace Engineering'],
['AVF', 'Aviation Flight'],
['AHF', 'Aviation Human Factors'],
['AVM', 'Aviation ... | 0.625324 | 0.488222 |
import unittest
import tempfile
import os
from .ParsedArgs import ParsedArgs
from meraki_cli.__main__ import _args_from_file
class TestArgsFromFile(unittest.TestCase):
def setUp(self):
self.parsed_args = ParsedArgs()
def testArgsFromFileExplicitPathNoExist(self):
self.parsed_args.configFile ... | tests/test_args_from_file.py | import unittest
import tempfile
import os
from .ParsedArgs import ParsedArgs
from meraki_cli.__main__ import _args_from_file
class TestArgsFromFile(unittest.TestCase):
def setUp(self):
self.parsed_args = ParsedArgs()
def testArgsFromFileExplicitPathNoExist(self):
self.parsed_args.configFile ... | 0.257672 | 0.232234 |
import sys
import os
import optuna
import wandb
import argparse
import torch
import pytorch_lightning as pl
from torchvision.utils import make_grid
import numpy as np
from functools import partial
import logging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(name)-12s %(levelname)-8s %(mess... | experiments/01_bioconv_convergence.py |
import sys
import os
import optuna
import wandb
import argparse
import torch
import pytorch_lightning as pl
from torchvision.utils import make_grid
import numpy as np
from functools import partial
import logging
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s %(name)-12s %(levelname)-8s %(mess... | 0.585575 | 0.240006 |
import pytest
from slash.utils.function_marker import function_marker, append_function_marker
def test_marked_func_identical_to_original(marker, func):
orig_func = func
new_func = marker(func)
assert orig_func is new_func
def test_is_marked(marker, func):
assert not marker.is_marked(func)
marker(... | tests/test_function_marker.py | import pytest
from slash.utils.function_marker import function_marker, append_function_marker
def test_marked_func_identical_to_original(marker, func):
orig_func = func
new_func = marker(func)
assert orig_func is new_func
def test_is_marked(marker, func):
assert not marker.is_marked(func)
marker(... | 0.432303 | 0.627609 |
import os
import shutil
from traitlets import Bool
from nbgrader.exchange.abc import ExchangeFetchAssignment as ABCExchangeFetchAssignment
from nbgrader.exchange.default import Exchange
from nbgrader.utils import check_mode
class ExchangeFetchAssignment(Exchange, ABCExchangeFetchAssignment):
def _load_config(s... | nbgrader/exchange/default/fetch_assignment.py | import os
import shutil
from traitlets import Bool
from nbgrader.exchange.abc import ExchangeFetchAssignment as ABCExchangeFetchAssignment
from nbgrader.exchange.default import Exchange
from nbgrader.utils import check_mode
class ExchangeFetchAssignment(Exchange, ABCExchangeFetchAssignment):
def _load_config(s... | 0.352759 | 0.150029 |
__author__ = "<NAME>"
import argparse, json, math, os
from tqdm import tqdm
from sys import argv
from itertools import repeat
import multiprocessing as mp
import pandas as pd
from nicu_los.src.utils.utils import get_subject_dirs, istarmap
def parse_cl_args():
"""Parses CL arguments"""
parser = argparse.Ar... | nicu_los/src/preprocessing/impute_values.py | __author__ = "<NAME>"
import argparse, json, math, os
from tqdm import tqdm
from sys import argv
from itertools import repeat
import multiprocessing as mp
import pandas as pd
from nicu_los.src.utils.utils import get_subject_dirs, istarmap
def parse_cl_args():
"""Parses CL arguments"""
parser = argparse.Ar... | 0.427755 | 0.184584 |
import os
import time
import datetime
import shutil
from shared.logger_factory import LoggerFactory
from shared.utils import read_data_from_json, write_data_to_json
ROOT_DIR = os.environ['ROOT_DIR']
class DataManager:
""" Class that collects the enhanced data from the scraping process, manages backups and compos... | etl/data_management/data_manager.py | import os
import time
import datetime
import shutil
from shared.logger_factory import LoggerFactory
from shared.utils import read_data_from_json, write_data_to_json
ROOT_DIR = os.environ['ROOT_DIR']
class DataManager:
""" Class that collects the enhanced data from the scraping process, manages backups and compos... | 0.585338 | 0.396419 |
import subprocess
import time
import psutil
import inspect
import os
import glob
import sys
import re
import random
import getpass
from pathlib import Path
import socket
def decomposePath(path):
"""
:example:
>>> decomposePath(None)
>>> decomposePath("")
>>> decomposePath(1)
... | lib/python3.5/site-packages/systemtools/location.py |
import subprocess
import time
import psutil
import inspect
import os
import glob
import sys
import re
import random
import getpass
from pathlib import Path
import socket
def decomposePath(path):
"""
:example:
>>> decomposePath(None)
>>> decomposePath("")
>>> decomposePath(1)
... | 0.276202 | 0.104021 |
import rospy
import math
import copy
import tf
import actionlib
import termios, sys, select, tty
from geometry_msgs.msg import Pose, Point, PoseWithCovarianceStamped, Twist
from std_msgs.msg import Int32, Header, Float32, Time
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal, MoveBaseActionResult
from acti... | shared_control/src/task_plan.py |
import rospy
import math
import copy
import tf
import actionlib
import termios, sys, select, tty
from geometry_msgs.msg import Pose, Point, PoseWithCovarianceStamped, Twist
from std_msgs.msg import Int32, Header, Float32, Time
from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal, MoveBaseActionResult
from acti... | 0.31944 | 0.116011 |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
import csv
from datetime import datetime, timedelta
import pandas as pd
def get_sectoral_index(index, launch_date, csvfile=None)... | data_collection/get_sectoral_indices.py | from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
import csv
from datetime import datetime, timedelta
import pandas as pd
def get_sectoral_index(index, launch_date, csvfile=None)... | 0.25174 | 0.103477 |
from datetime import datetime
from sqlalchemy import MetaData, create_engine
from api.models import chats, messages
from api.settings import config
DSN = "postgresql://{user}:{password}@{host}:{port}/{database}"
def create_tables(engine):
meta = MetaData()
meta.drop_all(bind=engine)
meta.create_all(bin... | task-9-async-chatrooms/init_db.py | from datetime import datetime
from sqlalchemy import MetaData, create_engine
from api.models import chats, messages
from api.settings import config
DSN = "postgresql://{user}:{password}@{host}:{port}/{database}"
def create_tables(engine):
meta = MetaData()
meta.drop_all(bind=engine)
meta.create_all(bin... | 0.483648 | 0.165998 |
from __future__ import print_function
import numpy as np
import os
import tardis
import astropy.units as units
import matplotlib.pyplot as plt
from tardis_minimal_model import minimal_model
import pandas as pd
elements = pd.read_csv("elements.csv", names=["chem_symbol", "atomic_no"])
inv_elements = pd.Series(
elem... | tardis_line_id.py | from __future__ import print_function
import numpy as np
import os
import tardis
import astropy.units as units
import matplotlib.pyplot as plt
from tardis_minimal_model import minimal_model
import pandas as pd
elements = pd.read_csv("elements.csv", names=["chem_symbol", "atomic_no"])
inv_elements = pd.Series(
elem... | 0.686055 | 0.182644 |
from logging import getLogger
from typing import Dict, List, Optional
from django.db.models import Q
from firebase_admin.messaging import UnregisteredError
from safe_notification_service.firebase.client import (FirebaseProvider,
MessagingClient)
from ..models i... | safe_notification_service/safe/services/notification_service.py | from logging import getLogger
from typing import Dict, List, Optional
from django.db.models import Q
from firebase_admin.messaging import UnregisteredError
from safe_notification_service.firebase.client import (FirebaseProvider,
MessagingClient)
from ..models i... | 0.868743 | 0.070368 |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("app", "0005_column_length")]
operations = [
migrations.AlterField(
model_name="dropboxlocation",
name="address",
field=models.CharField(blank=True, max_length=1024, ... | backend/pollaris/app/migrations/0006_nullable_fields_location.py |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("app", "0005_column_length")]
operations = [
migrations.AlterField(
model_name="dropboxlocation",
name="address",
field=models.CharField(blank=True, max_length=1024, ... | 0.703448 | 0.212906 |
from .branch_permissions import BranchPermissions
from .default_reviewers import DefaultReviewers
from .compat import update_doc
from .errors import ok_or_error, response_or_error
from .helpers import Nested, ResourceBase, IterableResource
from .permissions import ProjectPermissions
from .repos import Repos
from .setti... | stashy/projects.py | from .branch_permissions import BranchPermissions
from .default_reviewers import DefaultReviewers
from .compat import update_doc
from .errors import ok_or_error, response_or_error
from .helpers import Nested, ResourceBase, IterableResource
from .permissions import ProjectPermissions
from .repos import Repos
from .setti... | 0.698227 | 0.131898 |
import os
import numpy as np
import segyio
from ..core import SegyFile, SegyFileAttributes, is_segy_valid
from ..core.file_copy_utils import fast_copy
def add_files(input_filepath_list, output_filepath, average=False,
iline=9, xline=21):
"""
Add two or more SEG-Y files
"""
if all([is... | pysegyutils/ops/addition.py | import os
import numpy as np
import segyio
from ..core import SegyFile, SegyFileAttributes, is_segy_valid
from ..core.file_copy_utils import fast_copy
def add_files(input_filepath_list, output_filepath, average=False,
iline=9, xline=21):
"""
Add two or more SEG-Y files
"""
if all([is... | 0.133302 | 0.183539 |
import os
import sys
from pathlib import Path
from tempfile import mkdtemp
from zipfile import ZipFile, is_zipfile
from zapp.support.manifest import manifest, once
@once
def cache_root() -> Path:
"""Find a root directory for cached behaviors."""
shared_cache = Path(os.path.join(os.path.expanduser("~"))) / ... | zapp/support/unpack.py |
import os
import sys
from pathlib import Path
from tempfile import mkdtemp
from zipfile import ZipFile, is_zipfile
from zapp.support.manifest import manifest, once
@once
def cache_root() -> Path:
"""Find a root directory for cached behaviors."""
shared_cache = Path(os.path.join(os.path.expanduser("~"))) / ... | 0.371707 | 0.173358 |
import time
import copy
import os
from multiprocessing import Pool
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib.animation as animation
import flowrect
from flowrect.simulations.util import calculate_age, calculate_mt, eta_SRM, moving_average
from ... | plots/final/A_inf.py | import time
import copy
import os
from multiprocessing import Pool
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib.animation as animation
import flowrect
from flowrect.simulations.util import calculate_age, calculate_mt, eta_SRM, moving_average
from ... | 0.507324 | 0.341857 |
from os.path import join as pjoin, dirname
from io import StringIO
import re
from hashlib import sha1
from glob import glob
from copy import deepcopy
import numpy as np
from rnbgrader import JupyterKernel
from rnbgrader.grader import (OPTIONAL_PROMPT, MARK_MARKUP_RE, NBRunner,
report, du... | rnbgrader/tests/test_grader.py |
More text
""")
nb_fileobj1 = StringIO("""
Text
More text
""")
with JupyterKernel('ir') as rk:
results0 = runner.run(nb_fileobj0, rk)
results1 = runner.run(nb_fileobj1, rk)
assert (report(results0) ==
' 0: first_var <- 1 - None\n 1: first_var - [1] 1')
assert (report(r... | 0.553264 | 0.504578 |