content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
__author__ = 'Irina.Chegodaeva'
| python |
from django.shortcuts import render, get_object_or_404
from .models import BlogPost
def blogIndex(request):
blogposts = BlogPost.objects.order_by('-pub_date')
context = {
'heading':'The Blog',
'subheading':'',
'title':'Blog',
'copyright':'Pending',
'blogposts':blogposts,
}
return render(request,'blog-hom... | python |
"""Module test_listwrapper.
The MIT License
Copyright 2022 Thomas Lehmann.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, co... | python |
import cv2
import dlib
import imutils
from imutils import face_utils
import winsound
from scipy.spatial import distance
detector=dlib.get_frontal_face_detector()
predict=dlib.shape_predictor("C:/Users/kushal asn/Downloads/shape_predictor_68_face_landmarks.dat")
def eye_aspect_ratio(Eye):
A=distance.eucli... | python |
import re
import cltk.corpus.persian.alphabet as alphabet
from cltk.corpus.arabic.alphabet import *
to_reform = [
{
"characters": [
HAMZA,
HAMZA_BELOW,
HAMZA_ABOVE,
HAMZA_ISOLATED,
MINI_ALEF,
SMALL_ALEF,
SMAL... | python |
from __future__ import absolute_import, division, print_function
VERSION = '1.4.0'
def get_version():
return VERSION
__version__ = get_version()
def get_changelist():
# Legacy from the perforce era, but keeping this. It's not worth breaking
return "UnknownChangelist"
| python |
"""
* Copyright 2019 TIBCO Software Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); You may not use this file except
* in compliance with the License.
* A copy of the License is included in the distribution package with this file.
* You also may obtain a copy of the L... | python |
import base64
import requests
import uuid
import time
class MGTV:
def __init__(self, url):
self.url = url
def get_video_id(self):
return self.url.split("/", 5)[-1].split(".")[0]
def get_pm2(self):
did = "e6e13014-393b-43e7-b6be-2323e4960939"
suuid = uuid.uuid4()
p... | python |
import copy
import pickle
import torch
import types
from . import layers
from . import rules
Rules = rules.Rules
def flatten_model(module):
'''
flatten modul to base operation like Conv2, Linear, ...
'''
modules_list = []
for m_1 in module.children():
if len(list(m_1.children())) == 0:
... | python |
import pytest
import os
from tddc import common
def test_get_base_filename():
assert common.get_base_filename('/Users/foo/bar.txt') == 'bar'
assert common.get_base_filename('bar.txt') == 'bar'
assert common.get_base_filename('bar') == 'bar'
assert common.get_base_filename('bar.txt.gz') == 'bar.txt'
... | python |
# compare gene numbers in different samples
import pandas as pd
import scanpy as sc
import matplotlib.pyplot as plt
import seaborn as sns
from pathlib import Path
from scipy.stats import ttest_ind
import scipy.stats as stats
import scikit_posthocs as sp
#-------------------variable--------------------------------
fmt... | python |
#
# Este arquivo é parte do programa multi_agenda
#
# Esta obra está licenciada com uma
# Licença Creative Commons Atribuição 4.0 Internacional.
# (CC BY 4.0 Internacional)
#
# Para ver uma cópia da licença, visite
# https://creativecommons.org/licenses/by/4.0/legalcode
#
# WELLINGTON SAMPAIO - wsampaio@yahoo.com
#... | python |
# Generated by Django 2.2.16 on 2020-09-21 16:18
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('contest', '0001_initial'),
('lecture', '0001_initial'),
]
operations = [
migrations.AddField(
... | python |
import torch.nn as nn
import torch.nn.functional as F
from torch import cat, stack, sqrt
class MLPNetwork(nn.Module):
"""
MLP network (can be used as value or policy)
"""
def __init__(self, input_dim, out_dim, hidden_dim=64, nonlin=F.relu,
constrain_out=False, norm_in=True, discrete_ac... | python |
import re
from datetime import date, datetime, timezone
from urllib.parse import urljoin, urlparse
import pytest
from swpt_debtors import procedures as p
from swpt_debtors import models as m
@pytest.fixture(scope='function')
def client(app, db_session):
return app.test_client()
@pytest.fixture(scope='function')... | python |
from lxml import etree
from defusedxml.lxml import fromstring
import uuid
from django.db import models
from django.http import HttpResponse
from django.urls import reverse
from django.core.exceptions import ObjectDoesNotExist
from acs.response import get_soap_envelope
from acs.models import AcsHttpBaseModel
from acs.... | python |
from typing import List
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Product(BaseModel):
id: str
class Review(BaseModel):
body: str
product: Product
class User(BaseModel):
reviews: List[Review]
USER_DATA = {
"1": User(reviews=[Review(body="Great!", produ... | python |
import bpy
from bpy.props import *
PROP_TYPE_ICONS = {
"String": "SORTALPHA",
"Int": "CHECKBOX_DEHLT",
"Float": "RADIOBUT_OFF",
"Bool": "CHECKMARK",
"Vec2": "ORIENTATION_VIEW",
"Vec3": "ORIENTATION_GLOBAL",
"Vec4": "MESH_ICOSPHERE",
"Object": "OBJECT_DATA",
"CameraObject": "CAMERA_D... | python |
import numpy as np
import pandas as pd
import sklearn
from typing import Dict, Tuple
from sklearn.base import BaseEstimator
class RuleAugmentedEstimator(BaseEstimator):
"""Augments sklearn estimators with rule-based logic.
This class is a wrapper class for sklearn estimators with the additional
possibilit... | python |
# jay mahakal
import Resources.Work_By_Raj.Google_Calender_api.Resources.Setup
import Resources.Work_By_Raj.Google_Calender_api.Resources.Return_events_info
# below function [Setup.setup_calendar_credentials_return_service()] should run only once
# service = Setup.setup_calendar_credentials_return_service()
# pri... | python |
print "Ejercicio de ciclos -Granizada-"
def par(n):
n=n/2
def impar(n):
n=n*3+1
n=int(raw_input("digite numero "))
while n>=1:
if n%2==0:
par(n)
print n
else:
impar(n)
print n
| python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 1 15:39:06 2020
@author: jireh.park
"""
import pandas as pd
import os
from tqdm import tqdm
from google.cloud import storage
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))+ '/key/level-... | python |
#!/usr/bin/env python2.7
import os
import codecs
import json
import random
with codecs.open(os.path.join(os.path.dirname(os.path.realpath(__file__)), "apps.txt"), encoding="utf-8") as f:
apps = f.read().splitlines()
with codecs.open(os.path.join(os.path.dirname(os.path.realpath(__file__)), "networks.txt"), encodin... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""user表测试"""
from executor.database.models.user import Users
from executor.tests.database.base import DatabaseTestCase
from executor.exceptions import UserAlreadyExistException, \
IncorrectPasswordException
class TestOperatorUser(DatabaseTestCase):
data_file_path... | python |
# Copyright 2020 Google LLC
#
# 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, ... | python |
# OBS
# Imagem celular original do vírus recentemente descoberto SARS-CoV-2,
# popularmente chamado de COVID-19 ou Coronavirus.
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
!wget "https://raw.githubusercontent.com/PedroHaupenthal/Image-Processing/master/watershed/covid_19.jpg" -O "covid_19.jpg... | python |
import math
import threading
from django.core.cache import caches
from .settings import CACHE_HELPERS_ALIAS
CACHE_HELPERS_KEY = 'cache_helpers_key'
def set_cache_bust_status(bust_key=None):
cache = caches[CACHE_HELPERS_ALIAS]
cache.set(CACHE_HELPERS_KEY, bust_key)
def get_bust_key():
cache = caches[... | python |
"""
Provides the functionality to feed TF templates with Jerakia lookups
"""
import sys
import os
from jerakia import Jerakia
from terraform_external_data import terraform_external_data
def retrieveLookupInfo(query,item):
lookitem = query[item]
lookuppath =lookitem.split('/')
key = lookuppath.pop()
na... | python |
"""Internal helpers for dataset validation."""
from pathlib import Path
from typing import Any, Iterable, List, Optional, Sequence, Tuple, Union
import numpy as np
import pandas as pd
from biopsykit.utils._types import _Hashable, path_t
from biopsykit.utils.exceptions import FileExtensionError, ValidationError, Value... | python |
from terminaltables import SingleTable
import requests
import os
from dotenv import load_dotenv
def predict_salary(min_salary, max_salary):
if min_salary == None or min_salary == 0:
average_salary = max_salary*0.8
elif max_salary == None or max_salary == 0:
average_salary = min_salary*1.2
... | python |
import numpy as np
import matplotlib.pyplot as plt
teilnehmer = int(input("Teilnehmer: "))
a = list()
x = np.arange(1, teilnehmer+1)
y = np.zeros(teilnehmer)
a.append(float(input("Geheimnis: ")))
for i in range(teilnehmer-1):
a.append(float(input(f"Koeffizient a{i+1}: ")))
for i in range(teilnehmer):
for j in ... | python |
#/usr/bin/env python
from __future__ import absolute_import
# Charge transfer efficiency by EPER, now as a pipe task!
import lsst.pex.config as pexConfig
import lsst.pipe.base as pipeBase
import sys
import numpy as np
import argparse
from .MaskedCCD import MaskedCCD
import lsst.geom as lsstGeom
import lsst.afw.math ... | python |
from datetime import datetime
from sqlalchemy import create_engine, Column, Integer, DateTime
from sqlalchemy.ext.declarative import as_declarative, declared_attr
from sqlalchemy.orm import sessionmaker, scoped_session
from config.config import SQLALCHEMY_DATABASE_URI
engine = create_engine(SQLALCHEMY_DATABASE_URI)
... | python |
from typing import List
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
N = len(digits)
for i in reversed(range(N)):
digit = digits[i]
if digit == 9:
digits[i] = 0
else:
digits[i] += 1
return di... | python |
import timeit
import CoolProp.CoolProp as CP
def time_check(N, h, p, TTSE = False, mode = 'TTSE'):
if TTSE:
if mode =='TTSE':
setup = "import CoolProp; import CoolProp.CoolProp as CP; CP.enable_TTSE_LUT('Water'); CP.set_TTSE_mode('Water','TTSE'); CP.Props('T','H',500,'P',10000,'Water'); IWate... | python |
import numpy as np
import pandas as pd
import logging
logger = logging.getLogger(__name__)
def approximate_curve(data, bin_number):
binned = pd.cut(data.capacity_factor, bin_number)
# bins = np.arange(1, len(data.datetime) / bin_number + 1)
# logger.debug("bins: {}".format(bins))
# digitized = np.... | python |
"""There is a vehicle obscuring a pedestrian that conflicts with your path."""
from flow.envs.multiagent import Bayesian0NoGridEnv
from flow.networks import Bayesian1Network
from flow.core.params import SumoParams, EnvParams, InitialConfig, NetParams
from flow.core.params import SumoCarFollowingParams, VehicleParams
f... | python |
from datetime import datetime, timedelta
from typing import Optional
from utils.utils import format_date
class Event:
"""Event object to store data about a Google Calendar event"""
def __init__(
self,
event_id: str,
link: str,
title: str,
location: Optional[str],
description: Optional[str],
all_day: ... | python |
from __future__ import absolute_import, division, print_function
from cctbx.array_family.flex import ( # noqa: F401; lgtm
abs,
acos,
arg,
asin,
atan,
atan2,
bool,
ceil,
compare_derivatives,
complex_double,
condense_as_ranges,
conj,
cos,
cosh,
cost_of_m_handl... | python |
# @Author: BingWu Yang <detailyang>
# @Date: 2016-03-29T17:47:44+08:00
# @Email: detailyang@gmail.com
# @Last modified by: detailyang
# @Last modified time: 2016-04-10T16:54:56+08:00
# @License: The MIT License (MIT)
import ply.yacc as yacc
import eslast as ast
from esllexer import ESLLexer
tokens = ESLLexer.... | python |
from discord.ext import commands
import config
class Bot(commands.Bot):
async def invoke(self, ctx):
if self.user.mentioned_in(ctx.message):
# Mention was processed in on_message.
return
if ctx.invoked_with:
await ctx.send(config.response)
async def on_mes... | python |
#!/usr/bin/env python3
import altair as alt
import pandas
import selenium
def vegaGraphics(
cmdTag,
id1,
id2,
parameters,
sql,
transformedData,
verbose,):
"""Create interactive charts for specified data"""
# making function more explicit
cmdTag = cmd... | python |
from ark.thread_handler import ThreadHandler
from factory import Factory
import time
class GuiTasks(object):
@classmethod
def loop(cls):
time.sleep(1)
GuiTasks.get_active_threads()
@classmethod
def get_active_threads(cls):
GUI = Factory.get('GUI')
max_threads = len(Thr... | python |
import inject
from flask import Flask, Response, send_from_directory, send_file
class StaticRoute:
@staticmethod
@inject.autoparams()
def init(flask: Flask) -> None:
@flask.route("/static/<path:path>")
def send_static(path: str) -> Response:
return send_from_directory(f"static"... | python |
# Exercise 31: Making Decisions
print "You enter a dark room with two doors. Do you go through door #1 or door #2?"
door = raw_input("> ")
if door == "1":
print "There's a giant bear here eating a cheese cake. What do you do?"
print "1. Take the cake."
print "2. Scream at the bear."
print "3. Turn back quietly"
... | python |
# Generated by Django 3.1.1 on 2020-10-08 02:15
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('rameniaapp', '0009_auto_... | python |
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015, 2016, 2017 Daniel Rodriguez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Li... | python |
#!/usr/bin/env python
#Creates an instance in /home/pi/.config/lxsession/LXDE-pi/autostart which will autolaunch the server on the pi user account.
import time
print "Copy the path of the shortcut file by right clicking it and clicking 'copy path(s)'."
print "Paste the path when prompted by right clicking in the term... | python |
class Book():
'''
Creates a book object that can be used to populate a web page
Inputs:
- title: the title of the book [str]
- author: the author of the book [str]
- series: the series the book belongs to or None [str]
- review_text: a short blurb about the book [str]
- image_url: a plac... | python |
# -*- coding: utf-8 -*-
from .base import Smoother
__all__ = ['Smoother']
| python |
from os.path import join, dirname
from textx import metamodel_for_language
def test_example():
mm = metamodel_for_language('questionnaire')
questionnaire = mm.model_from_file(join(dirname(__file__), 'example.que'))
assert len(questionnaire.questions) == 6
assert questionnaire.questions[3].text == 'Au... | python |
# -*- coding: UTF-8 -*-
import threading
import json
import re
from datetime import datetime
from flask import current_app
from flask_jwt import current_identity, jwt_required
from flask_restful import Resource, request
from marshmallow import EXCLUDE, ValidationError
from sqlalchemy.exc import SQLAlchemyError
from c... | python |
"""
Discovering structure in heatmap data
=====================================
_thumb: .4, .2
"""
import pandas as pd
import seaborn as sns
sns.set(font="monospace")
# Load the brain networks example dataset
df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0)
# Select a subset of the networks
use... | python |
from django.db import models
class Position(models.Model):
w = models.CharField(max_length=128, null=True, blank=True)
x = models.CharField(max_length=128, null=True, blank=True)
y = models.CharField(max_length=128, null=True, blank=True)
z = models.CharField(max_length=128, null=True, blank=True)
... | python |
# -*- coding: UTF-8 -*-
# Copyright 2016-2018 Rumma & Ko Ltd
# License: BSD, see LICENSE for more details.
"""
A library of `invoke
<http://docs.pyinvoke.org/en/latest/index.html>`__ tasks. See
:doc:`/invlib`.
.. autosummary::
:toctree:
tasks
utils
"""
from __future__ import print_function
from __future__ ... | python |
from flask import request, jsonify, current_app, make_response, session
import random
from info.libs.yuntongxun import sms
from . import passport_blue
from info.utils.response_code import RET
from info.utils.captcha.captcha import captcha
from info import redis_store,constants,db
# 导入模型类
from info.models import User
im... | python |
from mpf.tests.MpfGameTestCase import MpfGameTestCase
from mpf.core.rgb_color import RGBColor
class TestBlinkenlight(MpfGameTestCase):
def get_config_file(self):
return 'config.yaml'
def get_platform(self):
return 'smart_virtual'
def get_machine_path(self):
return 'tests/machine... | python |
import mysql.connector
mydb = mysql.connector.connect(
host = 'localhost',
user = "root",
#passwd = "ant904",
database = "spl"
#auth_plugin='mysql_native_password'
)
myCursor = mydb.cursor()
qusTimeList=list()
qusTimeList.append("0:00:03")
qusTimeList.append("0:00:02")
qusTimeList.append("0:00:... | python |
from toee import *
def OnBeginSpellCast( spell ):
print "Vampiric Touch OnBeginSpellCast"
print "spell.target_list=", spell.target_list
print "spell.caster=", spell.caster, " caster.level= ", spell.caster_level
game.particles( "sp-necromancy-conjure", spell.caster )
def OnSpellEffect( spell ):
print "Vampiric T... | python |
from django.contrib import admin
from .models import District, Quarter, Community
admin.site.register(District)
admin.site.register(Quarter)
admin.site.register(Community) | python |
# Copyright (C) 2020 Intel Corporation
#
# 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 wri... | python |
import os
import codecs
from io import StringIO
from pytest import fixture
from rave import filesystem
class DummyProvider:
def __init__(self, files):
self.files = files;
def list(self):
return self.files
def has(self, filename):
return filename in self.list()
def open(self,... | python |
"""Forward measurements from Xiaomi Mi plant sensor via MQTT.
See https://github.com/ChristianKuehnel/plantgateway for more details.
"""
##############################################
#
# This is open source software licensed under the Apache License 2.0
# http://www.apache.org/licenses/LICENSE-2.0
#
################... | python |
#
# This file contains the Python code from Program 6.2 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm06_02.txt
#
class StackAsArray(... | python |
print('----->DESAFIO 48<-----')
print('Vou te mostrar a soma de todos os números impares múltiplos de 3 que estão no intervalo de 1 a 500!')
soma = 0
for c in range(0, 501):
if c > 0 and c % 2 != 0 and c % 3 == 0:
soma += c
print(soma)
| python |
#################################################################
# Name: randDLA.py #
# Authors: Michael Battaglia #
# Function: Program simulates diffusion limited aggregation #
# using Monte Carlo Methods. ... | python |
#import
import random
import os
import numpy
dic = {}
with open("points3D.txt","r") as n:
for line in n:
a = line.split(" ")
temp = []
temp.append(float(a[1]))
temp.append(float(a[2]))
temp.append(float(a[3]))
dic[a[0]] = temp[:]
print(dic["1"])
... | python |
def getone(coll, key, default=None):
try:
value = coll[key]
except [IndexError, KeyError, TypeError]:
return default;
else:
return value;
| python |
#!/usr/bin/env python2.7
# Copyright 2019 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import print_function
import argparse
import itertools
import json
import os
import sys
SCRIPT_DIR = os.path.dirna... | python |
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# Create renderer stuff
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renW... | python |
from collections import defaultdict
with open('day10/input.txt', 'r') as file:
data = sorted([int(x.strip()) for x in file.readlines()])
data = [0] + data
data.append(data[-1] + 3)
jolt_1, jolt_3 = 0, 0
for i in range(len(data)):
current = data[i - 1]
if (data[i] - current) == 1:
jolt_1 += 1
... | python |
from django.contrib.auth.hashers import make_password
from rest_framework import serializers
from .models import User
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework import response, status
class RegisterSerializer(serializers.ModelSerializer):
class Meta:
mo... | python |
import tensorflow as tf
# GPU版Tensor Flowを、特定のGPUで実行する
GPU_INDEX = 2
tf.config.set_soft_device_placement(True)
tf.debugging.set_log_device_placement(True)
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
try:
logical_gpus = tf.config.experimental.list_logical_devices('GPU')
pr... | python |
import pytest
from package_one.module_one import IntegerAdder
@pytest.fixture
def adder():
print("Test set-up!")
yield IntegerAdder()
print("Test tear-down")
def test_integer_adder(adder):
assert adder.add(1, 2) == 3
"""
In case you'd like to declare a fixture that executes only once per module, then... | python |
def snail(array):
results = []
while len(array) > 0:
results += array[0]
del array[0]
if len(array) > 0:
for i in array:
results += [i[-1]]
del i[-1]
if array[-1]:
results += arra... | python |
import os
from google.appengine.ext.webapp import template
from base_controller import CacheableHandler
from models.event import Event
class EventWizardHandler(CacheableHandler):
CACHE_VERSION = 1
CACHE_KEY_FORMAT = "event_wizard"
def __init__(self, *args, **kw):
super(EventWizardHandler, self).... | python |
"""
MIT License
Copyright (c) 2021 martinpflaum
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, ... | python |
__author__ = "Jeremy Nelson"
import csv
import datetime
import json
import urllib2
from json_ld.utilities.creator import JSONLinkedDataCreator
class JohnPeabodyHarringtonJSONLinkedDataCreator(JSONLinkedDataCreator):
CC_URI = 'http://id.loc.gov/authorities/names/n84168445'
LOC_URI = 'http://id.loc.gov/autho... | python |
from .algo.algo_endpoints import AlgoEndpoints
from .graph.graph_endpoints import GraphEndpoints
from .query_runner.query_runner import QueryRunner
class IndirectEndpoints(AlgoEndpoints, GraphEndpoints):
def __init__(self, query_runner: QueryRunner, namespace: str):
super().__init__(query_runner, namespac... | python |
#-*- coding:utf-8 -*-
import generate_chat
import seq2seq_model
import tensorflow as tf
import numpy as np
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
if __name__ == '__main__':
_, _, source_vocab_size = generate_chat.get_vocabs(generate_chat.vocab_encode_file... | python |
import tkinter as tk
from src.ui.core import SortableTable
from src.library.model import PlaylistModel
class Table(SortableTable):
def __init__(self, parent, logger, library):
SortableTable.__init__(self, parent, logger)
self.library = library
self.add_column('Playlist Name', sortable=True)
self.init_treevie... | python |
from slicegan import preprocessing, util
import torch
import torch.nn as nn
import torch.backends.cudnn as cudnn
import torch.optim as optim
import time
import matplotlib
import wandb
# 1. Start a new run
wandb.init(project='SuperRes', name='SliceGAN train', entity='tldr-group')
def train(pth, imtype, datatype, real_... | python |
from typing import List
from ..error import GraphQLError
from ..language import DocumentNode
from ..type import GraphQLSchema
__all__ = ["find_deprecated_usages"]
def find_deprecated_usages(
schema: GraphQLSchema, ast: DocumentNode
) -> List[GraphQLError]: # pragma: no cover
"""Get a list of GraphQLError i... | python |
from .target_generators import HeatmapGenerator
from .target_generators import ScaleAwareHeatmapGenerator
from .target_generators import JointsGenerator
__all__ = ['HeatmapGenerator', 'ScaleAwareHeatmapGenerator', 'JointsGenerator']
| python |
import re
from typing import Annotated, Any, Optional
import pytest
from arti import (
Annotation,
Artifact,
Fingerprint,
PartitionDependencies,
Producer,
StoragePartitions,
)
from arti import producer as producer_decorator # Avoid shadowing
from arti.internal.models import Model
from arti.in... | python |
from pathlib import Path
from fhir.resources.valueset import ValueSet as _ValueSet
from oops_fhir.utils import ValueSet
from oops_fhir.r4.code_system.feeding_device_codes import (
FeedingDeviceCodes as FeedingDeviceCodes_,
)
from oops_fhir.r4.code_system.snomed_ct import SNOMEDCT
__all__ = ["FeedingDeviceCod... | python |
import time
import os
import numpy as np
from perform.constants import REAL_TYPE
class RomSpaceMapping:
"""Base class for mapping to/from the state/latent space."""
def __init__(self, sol_domain, rom_domain, rom_model):
rom_dict = rom_domain.rom_dict
model_idx = rom_model.model_idx
... | python |
from dl.nn.Module import Module
import dl.graph.op as OP
from dl.graph import variable
class DropoutLayer(Module):
"""
Dropout layer object.
"""
def __init__(self, rate: float):
"""
Dropout layer object.
Parameters
----------
rate:
Dropout rate.
... | python |
import torch.distributed as dist
from .trainer import Trainer
from ..util import DDP
def average_gradients(model):
""" Gradient averaging. """
size = float(dist.get_world_size())
for param in model.parameters():
if param.grad is not None:
dist.all_reduce(param.grad.data, op=dist.Reduce... | python |
from .answer import Answer, CalculatedAnswer, DragText, NumericalAnswer
from .enums import *
from .questions import (QCalculated, QCalculatedMultichoice, QCalculatedSimple,
QCloze, QDescription, QDragAndDropImage,
QDragAndDropMarker, QDragAndDropText, QEssay,
... | python |
import warnings
from collections import OrderedDict
import pandas as pd
from . import dtypes, utils
from .alignment import align
from .variable import IndexVariable, Variable, as_variable
from .variable import concat as concat_vars
def concat(
objs,
dim=None,
data_vars="all",
coords="different",
... | python |
import re
import os
try:
from urlparse import urlparse
except:
from urllib.parse import urlparse
from .exceptions import FieldValidationException
from .universal_forwarder_compatiblity import UF_MODE, make_splunkhome_path
from .contrib.ipaddress import ip_network
try:
from .server_info import ServerInfo... | python |
import os
import pandas as pd
import pytest
from probatus.feature_elimination import EarlyStoppingShapRFECV, ShapRFECV
from probatus.utils import preprocess_labels
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import get_scorer
from sklearn.model_selection import RandomizedSearchCV, Stratifi... | python |
# -*- coding: utf8 -*-
from base import Stock
class Uzmanpara(Stock):
stockURL = "http://uzmanpara.milliyet.com.tr/borsa/hisse-senetleri/{0}/"
priceQuery = '.realTime > .price-arrow-down, .realTime > .price-arrow-up'
volumeQuery = '.realTime table tr td'
timezone = "Europe/Istanbul"
@classmethod
... | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import sys
from pkg_resources import load_entry_point
from subprocess import check_call
def main():
check_call([sys.executable, 'setup.py', 'build_ext', '--inplace'])
if '--with-coverage' not in sys.argv:
sys.argv.extend(('--with-co... | python |
"""Tests for ht.events.manager module."""
# =============================================================================
# IMPORTS
# =============================================================================
# Third Party
import pytest
# Houdini Toolbox
import ht.events.manager
from ht.events.event import Houdin... | python |
from .. cupy_utils import to_numpy, trapz, xp
from ..utils import powerlaw
import numpy as np
from astropy.cosmology import Planck15
class PowerLawRedshift(object):
"""
Redshift model from Fishbach+ https://arxiv.org/abs/1805.10270
Note that this is deliberately off by a factor of dVc/dz
"""
de... | python |
from flask import Flask
from flask_bootstrap import Bootstrap
app = Flask(__name__)
Bootstrap(app)
with app.app_context():
import routes
import stats
if __name__ == "__main__":
app.config['DEBUG'] = True
app.run()
| python |
from receptor_affinity.mesh import Mesh
from wait_for import TimedOutError
import time
import pytest
@pytest.yield_fixture(
scope="function",
params=[
"test/perf/flat-mesh.yaml",
"test/perf/tree-mesh.yaml",
"test/perf/random-mesh.yaml",
],
ids=["flat", "tree", "random"],
)
def ... | python |
# Copyright 2021 Gakuto Furuya
#
# 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 writ... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.