content stringlengths 5 1.05M |
|---|
""" Class to control the lights """
from platform import system
from colour import Color
import random, copy
import k24.binding_winbond as binding_winbond
class Keylights:
"""
see: Keylights.setall() and Keylights.setkey() for practical uses
"""
vid=0
pid=0
def __init__(self):
self.ada... |
"""
Not every sitemap needs to be as complex as
the post sitmap. Django anticipates that in
most cases, we will simply override the
items() method of the Sitemap subclass and
nothing else. To make this easy the sitemaps
app supplies the GenericSitemap class, which
can be passed a dictionary of items to
automatically ge... |
# Refer: https://arxiv.org/pdf/1308.4008.pdf (Momin, J. A. M. I. L., & Yang, X. S. (2013). A literature survey of benchmark functions for global optimization problems. Journal of Mathematical Modelling and Numerical Optimisation, 4(2), 150-194.)
import numpy as np
import matplotlib.pyplot as plt
import pso_solver
pso... |
import numpy
import os
numpy.seterr('ignore')
luz = int(300000000)
while True:
inicio = input("¿que deseas?(entrar, salir o limpiar): \n>")
print ("")
if inicio == "entrar" or inicio == "enter":
opcion = input("elige la magnitud(energia, fuerza o recorrido): \n>")
if opcion == "energia" or opcion == ... |
import logging
import os
import jenga.compile
import jenga.crossreference
import jenga.interpret
import jenga.lex
import jenga.preprocess
from jenga.types import Word
def gen_ir(fn: str, include_paths: list[str]) -> list[Word]:
"""Generate the intermediate representation (list of Words) from a program"""
log... |
"""Payment forwarder."""
import pytest
import datetime
from eth_tester.exceptions import TransactionFailed
from web3.contract import Contract
@pytest.fixture
def issuer_token(chain, team_multisig) -> Contract:
"""Create the token contract."""
args = [team_multisig, "Foobar", "FOOB", 1000000, 0, int((datetim... |
# -*- encoding: utf-8 -*-
'''
Filename :lib_circuit_base.py
Description :This document is used for fundamental class of quantum circuit
Time :2021/09/26 13:58:23
Author :Weiwen Jiang & Zhirui Hu
Version :1.0
'''
import sys
import numpy as np
import numpy as np
from qiskit.t... |
import numpy as np
import os
from wafl_interface import WAflInterface
from util import fast_hash
import json
import shutil
from collections import Counter,defaultdict
COV_MAX_SIZE = 65536
# CONSTANTS to depict change in coverage
COV_NO_CHANGE = -1
COV_CHANGE = 0
COV_INCREASE = 1
COV_SOFT_INCREASE = 2
COV_SOFT_DECREA... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 20 09:43:34 2020
@author: Nikki
"""
#referencing https://github.com/aqeelanwar/SocialDistancingAI
import cv2
import sys
import csv
import transform as tform
import numpy as np
import os.path
# Goal Input: csv file with ip address, length, width
# Output: csv file... |
import os,fortnitepy,datetime,requests,json,asyncio,time,random,threading
from threading import Thread
from Fortnite import Variants,API,Extras,colored,apiwrapper
fnapi = apiwrapper.FortniteAPI()
async def Command(self, message):
HasFullAccess = False
TimeInUTC = datetime.datetime.utcnow().strftim... |
import numpy as np
#LaxFriedrichs算法,二阶精度。只有当a = 1时才完全准确。其它时候数值耗散很大
nmax = 510
tmax = 1005
U = np.zeros((tmax,nmax))
f = np.zeros((tmax,nmax+1))
F = np.zeros((tmax,nmax))
a = 0.5#速度
b = np.zeros((2,nmax+1))
dt = 1
dx = 1
for i in range(0,nmax+1):
b[0,i] = -i*i/2 + i*10
b[1,i] = -i*i*i*i/6 + i*i*5
j = i + 0... |
from invoke import task
CONTAINER_NAME = 'jupyter_datascience_pyspark'
IMAGE_NAME = f"tuteco/{CONTAINER_NAME}"
CONTAINER_INSTANCE = 'default'
@task
def build_local(context):
"""
build an image from a Dockerfile with tag 'latest-dev'
"""
context.run(f"docker build -t {IMAGE_NAME}:latest-dev . -f D... |
'''Kiosk main functions and classes'''
class Channels():
"""
Holds dict of channels
Channels have a uuid name
Channels contain a list of urls
"""
def __init__(self):
self.channels = {
'_standby': ['https://dutchsec.com']
}
def add(self, name, pages):
"... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mezcal-widget.ui'
#
# Created by: PyQt5 UI code generator 5.8.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MezcalPicker(object):
def setupUi(self, MezcalPicker):
... |
#!/usr/bin/env python
##
#
# hiroshima.py
# This is the main front-end that pulls all network attacks into one interface. Enjoy.
# Samuel Steele (cryptoc1)
#
##
import networks, sys
_usage = "hiroshima help: \
\n\tAttackable Networks: \
\n\t\t+ Twitter \
\n\t\t+ Instagram... |
"""
Helpers for accessing C++ STL containers in GDB.
"""
# @lint-avoid-python-3-compatibility-imports
import gdb
import re
from gdbutils import *
from hashes import hash_of
#------------------------------------------------------------------------------
# STL accessors.
#
# These are only designed to work for gcc-4.8... |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
# Copyright (C) Canux CHENG <canuxcheng@gmail.com>
#
# 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 li... |
from functools import lru_cache
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
from sanic_routing import BaseRouter # type: ignore
from sanic_routing.exceptions import NoMethod # type: ignore
from sanic_routing.exceptions import (
NotFound as RoutingNotFound, # type: ignore
)
from sanic_ro... |
from django.urls import path
from . import views
urlpatterns = [
path('add/<str:codigo>/', views.pedido_add_item, name='pedido_add_item'),
path('add/atacado/<str:codigo>/<int:quantidade>/', views.pedido_add_item_atacado, name='pedido_add_item_atacado'),
path('aberto/', views.pedido_aberto, name='pedido_ab... |
from typing import Any, Dict
from django.db.models import Count
from django.db.models.functions import TruncDay
from django.http import HttpRequest, HttpResponse
from django.shortcuts import redirect
from django.urls import reverse, reverse_lazy
from django.utils import timezone
from django.views import View
from djan... |
#!/usr/bin/env python
import sys
import argparse
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument('--noan', action='store_true', help='Not to run make psql-analyze')
TOTAL_SIZE_SQL = """SELECT
pg_size_pretty(sum(size)) AS size
FROM (
SELECT
relname as "Table",
pg_total_relation_siz... |
from django.contrib import admin
from django.contrib.auth.hashers import make_password
from ..models.authorModel import Author
# DJANGO ADMIN PANEL
# Allows you to view pending request to action on
def pendingRequest(ModelAdmin, request, result):
for request in result:
admin = Author(displayName=request.di... |
# -*- coding: utf-8 -*-
# !/usr/bin/env python
# @Time : 2021/8/26 11:38
# @Author : NoWords
# @FileName: comment_view.py
from core.common.common_view import CommonAPIView
from ..serializers import CommentSerializer
from ..models import Comment
class CommentAPIView(CommonAPIView):
"""
评论管理
"""
mod... |
# Copyright (c) 2017 Sony Corporation. 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.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... |
#!/usr/bin/env python
# encoding: utf-8
"""
pilatus.py - connect to and control the pilatus100
NB: cam_server and EPICS GUI must be on for this to work.
If something looks wrong, debug by watching the output on the
cam_server and GUI windows
Created by Dave Williams on 2014-12-04
"""
import os
import time
import ep... |
import os
import glob
import sys
import time
import numpy as np
from collections import defaultdict
from tensorflow.keras.layers import Dense
from tensorflow.keras.layers import Dropout
from tensorflow.keras.layers import Input
from tensorflow.keras.layers import Add
from tensorflow.keras.layers import Dot
from tenso... |
from PyQt5 import QtWidgets
from PyQt5 import uic
from PyQt5.QtGui import QIcon, QPixmap, QClipboard
from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog, QPushButton, QHBoxLayout, QDialog, QBoxLayout, QMainWindow
from PyQt5.QtWebEngineWidgets import QWebEnginePage
from PyQt5.QtWebEng... |
from recviz.rec import recviz
|
from context import Meta
meta = Meta()
merge_dictionaries = meta.load("http://www.meta-lang.org/snippets/56ee468ac0cb8f7470fbb338")
print(merge_dictionaries.get_dynamic_type_sig())
|
import sys
import os.path
import datetime
import re
from urlparse import urljoin
from urllib import urlopen
import nltk
from base_source import BaseSource
from shared import common
from shared.config import ConfigReader
class Ford(BaseSource):
def __init__(self):
self._ptn_date = re.compile('^(\d\d) (\w\w... |
from flask import Blueprint
bp = Blueprint('topic', __name__, url_prefix='/topics')
|
#coding: utf-8
import requests
from AdvancedHTMLParser import AdvancedHTMLParser
import collections
from unidecode import unidecode
import modules.utils
import json
import re
def pprint(txt="",e="\n"):
if False:
print(txt, end=e)
"""
www_parser - module for parsing timetable from vulcan.
"""
class www_parser:
de... |
import ontotextapi as onto
import utils
import json
from os.path import isfile, join, split
import joblib as jl
import cohortanalysis as cohort
from ann_post_rules import AnnRuleExecutor
import sys
import xml.etree.ElementTree as ET
import concept_mapping
import urllib3
import logging
class StudyConcept(object):
... |
# coding=utf-8
"""
© 2014 LinkedIn Corp. 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.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed ... |
import tkinter as tk
import random
class Controller(object):
"""
A class to control the movement of the snake in the game
"""
def __init__(self, screen):
"""
Binds the arrow keys to the game canvas.
Parameters:
screen (Canvas): The canvas for the Snake game.
... |
"""Copyright © 2020-present, Swisscom (Schweiz) AG.
All rights reserved.
This class is used for training models and is the core of the framework.
With the help of this class, the user of the framework is able to train and
develop models. The framework gets all the relevant objects as an input, and
all the parameters ... |
from src.flaskbasic.functions import Functions
import pytest
fun = Functions
def test_student_name():
assert fun.readName('Lwando',1) == 'Lwando'
assert fun.readName('Zukisa',2) == 'Zukisa'
assert fun.readName('ludwe',3) == 'ludwe'
def delete(student_id):
student_results = Student.query.get_o... |
# -*- coding: utf-8 -*-
# vispy: gallery 30
# -----------------------------------------------------------------------------
# Copyright (c) Vispy Development Team. All Rights Reserved.
# Distributed under the (new) BSD License. See LICENSE.txt for more info.
# -----------------------------------------------------------... |
import logging
from mopidy import backend
logger = logging.getLogger(__name__)
BITRATES = {
128: "low",
160: "med",
320: "hi",
}
class GMusicPlaybackProvider(backend.PlaybackProvider):
def translate_uri(self, uri):
track_id = uri.rsplit(":")[-1]
quality = BITRATES[self.backend.con... |
from discovery_imaging_utils.reports.qc import ind_functional_qc
from discovery_imaging_utils.reports.qc import ind_group_functional_qc
from discovery_imaging_utils.reports.qc import ind_group_structural_qc
from discovery_imaging_utils.reports.qc import ind_structural_qc
from discovery_imaging_utils.reports.qc import s... |
from abc import abstractmethod, ABC
class AnsatzGenerator(ABC):
"""
Abstract class to be inherited by iPOPO bundles to generate quantum circuit ansatz for quantum computation
Subclasses must inherit and implement the generate() method to return an XACC Intermediate Representation (IR) Function in... |
"""Module for handling internationalisation in URL patterns."""
from django.urls import LocalePrefixPattern, URLResolver
from django.conf import settings
from django.utils.translation import activate, get_language
class ActiveLocalePrefixPattern(LocalePrefixPattern):
"""Patched version of LocalePrefixPattern for... |
import os
import re
import traceback
from abc import abstractmethod
from pydoc import locate
from config.Config import Config
from engine.component.TemplateModuleComponent import TemplateModuleComponent
from enums.Architectures import Arch
from enums.Language import Language
class ModuleNotCompatibleException(Except... |
import setuptools
# Pypi doesn't seem to like .rst
#with open("README.rst", "r") as file:
# long_description = file.read()
long_description = "Easily protect your serialized class objects with secure encryption. Kosher Pickles provides a Mixin you can use in any classes you wish to protect."
setuptools.setup(
... |
nome= input("Olá, qual o seu nome?\n")
if nome== "Lucas":
print("Olá, %s"% nome)
elif nome== "Mário":
print("Oi, Mário!")
elif nome== "José":
print("Oi, José!")
else:
print("Olá, visitante!")
|
from enum import Enum
import basicTypes
class MainOp(Enum):
J = 2
JAL = 3
BEQ = 4
BNE = 5
BLEZ = 6
BGTZ = 7
ADDI = 8
ADDIU = 9
SLTI = 10
SLTIU = 11
ANDI = 12
ORI = 13
XORI = 14
LUI = 15
BEQL = 20
BNEL = 21
BLEZL = 22
BGTZL = ... |
import pathlib
import jsonlines as jl
import progressbar as pb
import typing as t
import utils as u
from typeguard import typechecked
@typechecked
def list_documents(jsonl_in: pathlib.Path) -> t.Iterator[dict]:
"""
Lists all the documents in the `JSONL` file
Parameters
----------
jsonl_in : pathli... |
# encoding: utf-8
# Copyright 2011 Tree.io Limited
# This file is part of Treeio.
# License www.tree.io/license
#-*- coding: utf-8 -*-
import handlers
from django.conf.urls.defaults import *
from treeio.core.api.auth import auth_engine
from treeio.core.api.doc import documentation_view
from treeio.core.api.resource i... |
# Copyright 2019 The SQLNet Company GmbH
# 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, ... |
#coding=utf-8
# coding=utf-8
'''
Created on 2014-2-17
@author: ETHAN
'''
from doraemon.home.models import DicType,DicData
class DAL_DictValue(object):
'''
data access for dictionary table
'''
@staticmethod
def getdatavaluebytype(datatypename):
dicType=DicType.objects.all().filter(DicType... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
LONG_DESCRIPTION = "Package to handle scientific experiments easily"
setup(name='uib_experiments',
version='1.0.0',
description='Handle the experiments.',
long_description=LONG_DESCRIPTION,
url='https://github.com/miquelmn/uib... |
# apis_v1/documentation_source/friend_invitation_by_email_send_doc.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
def friend_invitation_by_email_send_doc_template_values(url_root):
"""
Show documentation about friendInvitationByEmailSend
"""
required_query_parameter_list = [
... |
# Copyright 2014 - Mirantis, Inc.
#
# 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 ag... |
# Django settings for testsite project.
from os import path
import sys
import socket
hostname = socket.gethostname()
# Try and import pycairo or fallback to cairocffi and install as cairo
try:
import cairo
except ImportError:
import cairocffi
cairocffi.install_as_pycairo()
from django.core.urlresolvers i... |
from liquer import *
import pandas as pd
import io
from urllib.request import urlopen
from matplotlib.figure import Figure
from matplotlib import pyplot as plt
import numpy as np
@command
def MPL(state, command, *series):
"""Matplotlib chart
"""
fig = plt.figure(figsize=(8, 6), dpi=300)
axis = fig.add... |
#Author-Hyunyoung Kim
#Description-MorpheesPlug script for Fusion 360
#Basic unit: cm, rad
import adsk.core, adsk.fusion, adsk.cam, traceback, math
_app = adsk.core.Application.cast(None)
_ui = adsk.core.UserInterface.cast(None)
_handlers = []
_inputs = adsk.core.CommandInputs.cast(None)
def run(context):
try:
... |
# Transcibed from original Visual Basic scripts by Clayton Lewis and Lawrence Hipps
import pandas as pd
import scipy
import numpy as np
import dask as dd
#Public Module EC
import numba
# https://stackoverflow.com/questions/47594932/row-wise-interpolation-in-dataframe-using-interp1d
# https://krstn.eu/fast-linear-1D-... |
import json
import os
import shutil
import tempfile
import logging
from debpackager.utils.pom import Pom
from sh import mkdir
import pytest
from debpackager.main import get_project_type, add_missing_params
logging.basicConfig(level=logging.WARNING)
@pytest.mark.unit
class TestMain(object):
def setup_method(se... |
from util import loader
from wrappers.update import Update
from games.base_class import Game
class PathOfExile(Game):
def __init__(self):
self.alert_level = 3
self.ignore_terms = 'sale, showcase, interview'
super().__init__('Path of Exile', homepage='https://pathofexile.com')
def scan(self):
forums = [
... |
from Modularity.predict import predict
from seq2seq.helpers import sequence_accuracy
from Modularity.nn import get_exact_match
import torch
import torch.nn as nn
from typing import Iterator
from typing import Dict
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
def evaluate(data_iterator: Ite... |
import glob
import os.path as path
import subprocess
import sys
import tempfile
from shlex import quote
import yaml
def main():
repos = _buildRepoMap()
for arg in sys.argv[1:]:
_validateFile(arg, repos)
def _buildRepoMap():
repos = {}
for file in glob.glob("./**/*.yaml", recursive=True):
... |
import os
import subprocess
import sys
_PYTHON_VERSIONS_ = ["3.6", "3.7", "3.8"]
_TAGS = [
("Dockerfile", "basecuda"),
("Dockerfile.cuda", "cuda"),
("Dockerfile.nightly", "rustnightly"),
("Dockerfile.stable", "rust"),
("Dockerfile.cuda.stable", "cudarust")
]
cwd = os.path.abspath(os.path.dirname(... |
"""Tests for STRIPS operator learning."""
from gym.spaces import Box
import numpy as np
from predicators.src.nsrt_learning.strips_learning import segment_trajectory, \
learn_strips_operators
from predicators.src.structs import Type, Predicate, State, Action, \
ParameterizedOption, LowLevelTrajectory
from predi... |
from axiom.test.historic import stubloader
from xmantissa.people import EmailAddress, Person
class EmailAddressTestCase(stubloader.StubbedTest):
def testUpgrade(self):
ea = self.store.findUnique(EmailAddress)
person = self.store.findUnique(Person)
self.assertIdentical(ea.person, person)
... |
from google.cloud.datastore_v1 import types
from typing import NamedTuple
class _StoredObject(NamedTuple):
version: int
entity: types.Entity
|
#!/usr/bin/env python
# encoding: utf-8
"""
untitled.py
Created by Olivier Huin on 2010-03-22.
Copyright (c) 2010 Flarebyte.com Limited. All rights reserved.
"""
import sys
import os
import S3
import time
import csv, uuid
import simplejson as json
import mondriancss
import datautils, devutils, datasource
from collect... |
#!/usr/bin/env python3
# coding: utf-8
"""Plotting and analysis tools for the ARTIS 3D supernova radiative transfer code."""
import datetime
import sys
from pathlib import Path
from setuptools import find_packages, setup
from setuptools.command.test import test as TestCommand
sys.path.append('artistools/')
from com... |
'''
This Module contain a collection of decorator to manage maya selection.
The goal is to externalize all selection checks during procedure like:
def generic_method_creating_a_deformer_from_selection():
selection = cmds.ls(selection=True)
if len(selection) == 0:
return cmds.warning('Please select at le... |
'''
模拟处理机调度算法
create by Ian in 2017-11-9 19:28:46
'''
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import sys
import time
class MultiInPutDialog(QDialog):
'''新建作业弹窗,自定义对话框'''
def __init__(self):
super(MultiInPutDialog, self).__init__()
self.initUI()
def i... |
#!/usr/bin/python3 -OO
# Copyright 2007-2021 The SABnzbd-Team <team@sabnzbd.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any late... |
from mara.storage.dict import DictStore
async def test_flat_store():
store = DictStore(a=1, foo="bar")
data = await store.store()
assert data == '{"a": 1, "foo": "bar"}'
async def test_flat_restore():
store = await DictStore.restore('{"a": 1, "foo": "bar"}')
assert store.a == 1
assert store.... |
class medidas:
π = 3.14159265359
def coordenadas_hipotenusa(self, x1: float, y1: float, x2: float, y2: float)->float:
'''Função que calcula os catetos e retorna a hipotenusa
Parameters:
x1 (float): Primeira posição X
y1 (float): Primeira posição Y
x2 (float): Segunda posição X
y2 (float): Segunda po... |
# Copyright 2021 InterDigital R&D and Télécom Paris.
# Author: Giorgia Cantisani
# License: Apache 2.0
"""Code to generate the dataset and set sources to zero manually.
"""
import os
import argparse
import random
import numpy as np
import librosa
import musdb
import soundfile as sf
from copy import deepcopy as cp
from... |
import pymongo
# 데이터베이스와 컬렉션을 생성하는 코드입니다. 수정하지 마세요!
connection = pymongo.MongoClient("mongodb://localhost:27017/")
db = connection["library"]
col = db["books"]
# 사라진 책을 데이터베이스에서 삭제하세요.
query = { "title": {"$regex": "^Alice's Adventures in Wonderland"} }
col.delete_many(query)
# 책이 잘 삭제되었는지 확인하는 코드입니다. 수정하지 마세요!
fo... |
#importing tkinter which comes already installed with python
from tkinter import *
from tkinter import messagebox
#main_window is the parent or the main window
window=Tk()
#giving our gui a title
window.title("Fun GUI")
#size of minimized GUI
window.geometry('350x250')
lb=Label(window,text="Hello to my site!! Wa... |
import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.setpoint_managers import SetpointManagerOutdoorAirReset
log = logging.getLogger(__name__)
class TestSetpointManagerOutdoorAirReset(unittest.TestCase):
def setUp(self):
... |
# Further clean occupation data from 1847 census data
# Alice Huang, 7/18/19
import csv
def main():
# init vars
listM = []
listF = []
male = []
male2 = []
female = []
female2 = []
matches = []
with open('testdata2.csv') as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
... |
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
def __init__(self, *args, **kwargs):
super(UserRegisterForm, self).__init__(*args, **kwargs)
for fiel... |
from pgmpy.models import BayesianModel
from pgmpy.sampling import BayesianModelSampling
from pgmpy.factors.discrete import State
import numpy as np
import helpers
#all_slots = ['area', 'customer rating', 'eatType', 'familyFriendly', 'food', 'near', 'priceRange']
def sample_slots(model_info_file, mr_slot_names):
m... |
from random import randint
from typing import Optional
from sqlalchemy.orm import Session
from app import crud, schemas
from app.constants.state import TaskType, TaskState
from tests.utils.utils import random_lower_string
from tests.utils.datasets import create_dataset_record
def create_task(
db: Session,
u... |
import dolfin as df
import math
class RadialBasisFunction(df.UserExpression):
# slow and old
def __init__(self, r0, l, **kwargs):
self.r0 = r0
self.l = l
super().__init__(**kwargs)
def eval_cell(self, values, x, ufc_cell):
raise NotImplementedError
def eval(self, va... |
import os
from fastapi import File, UploadFile, Depends, HTTPException
from fastapi.encoders import jsonable_encoder
from sqlalchemy.orm import Session
from common.constant import Message
from model.user_profile_model import UserProfile
from router import router
from utils.database import get_db
from utils.jwt_utils i... |
''' Operadores Aritimeticos
+ : Adição ** : Potência (o comando 'pow' tbm serve)
- : Subtração % : Resto da divisão
* : Multiplicação // : Divisão inteira
/ : Divisão == : Igual (tem que usar os dois mesmo.)
**(1/2) : Para fazer raiz qu... |
#!/usr/bin/python
#
# Copyright 2018-2020 Polyaxon, Inc.
#
# 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 ... |
#おまじない
from tkinter import Tk, Button, X, Frame, GROOVE, W, E, Label, Entry, END
import numpy as np
import os
from matplotlib import pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
# プロットする関数
def graph(data):
# 大きさ(6,3)のグラフを生成する
fig = plt.Figure(figsize=(6,3... |
from random import randint
from random import choice
from redbot.core import commands
from redbot.core import Config
from redbot.core.data_manager import cog_data_path
import dateutil.parser
import discord
class Gacha(commands.Cog):
"""
Plays a game of gachapon.
"""
def __init__(self, bot... |
celsius = int(raw_input('Informe a temperatura em Celsius: '))
farenheit = ((celsius / 5.0) * 9.0) + 32.0
print "A temperatura em Farenheit eh", farenheit
|
# A train script using just pytroch and torchvision
# test to get training loop right
# main detection script for now
### TODO
# add checkpoint saving
# try again on FP16
# validation loop
# model watching for wandb
# argparse?
# different models
import torch
import torchvision
import torchvision.models.detection as ... |
import json
import config
import time
from datetime import date, timedelta, datetime
from utils import setup_client, save_homework
from discord_webhook import DiscordWebhook
def log(message):
ts = time.time()
print("[" + datetime.fromtimestamp(ts).strftime('%H:%M %d/%m/%Y') + "]" + " " + message)
def send_web... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Responsible file to start the application.
"""
from os.path import join, dirname
from tornado.ioloop import IOLoop
from tornado.httpserver import HTTPServer
from tornado.web import Application, StaticFileHandler
from tornado.options import define, options, parse_... |
import collections
from germanium.impl._load_script import load_script
from .DeferredLocator import DeferredLocator
class StaticElementLocator(DeferredLocator):
def __init__(self, germanium, element):
""" Just holds a static reference to the elements. """
super(StaticElementLocator, self).__init_... |
# James Clarke
# 25/09/2019
from . import serialize
from . import protocol
from threading import Thread
import socket, logging, os
DEFAULT_PORT = 3141
USE_MULTITHREADING = True
BLOCK_SIZE = 128
SIZE_INFO = 10
logging.basicConfig(level=os.environ.get("LOGLEVEL", "NOTSET"))
# Format a message for sending by adding si... |
from LAUG.util.dataloader.dataset_dataloader import *
from LAUG.util.dataloader.module_dataloader import *
|
import sys
import os.path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__),
os.path.pardir)))
from htmlfactory.TagFactory import TagFactory
from htmlfactory.SingletonTag import SingletonTag
def setup_function(function):
print("Setting up", functi... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import abc
from .basic import *
__all__ = ["IIC"]
class IIC(BaseModule):
def __init__(self, in_channels: int = 3, num_classes: int = 10, num_classes_over: int = 100, z_dim=512, num_heads=10):
super().__init__()
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import math
from PIL import Image, ImageFont, ImageDraw, ImageEnhance, ImageChops
def add_mark(imagePath, mark, out, quality):
'''
添加水印,然后保存图片
'''
im = Image.open(imagePath)
image = mark(im)
name = os.path.basename(imagePath)
if image:... |
import os
import sys
import shutil
PIVY_HEADER = """\
#ifdef __PIVY__
%%include %s
#endif
"""
def copy_and_swigify_headers(includedir, dirname, files):
"""Copy the header files to the local include directories. Add an
#include line at the beginning for the SWIG interface files..."""
for fil... |
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
import os
import numpy as np
import collections
from ipu_sparse_ops import host_utils
import tensorflow.compat.v1 as tf
from tensorflow.python import ipu
from logging import getLogger
tf.disable_eager_execution()
tf.disable_v2_behavior()
def get_lib_path(lib_na... |
from pyopteryx.factories.usage_action_factories.abstract_usage_action_factory import AbstractUsageActionFactory
from pyopteryx.utils.utils import string_int_to_string_float
from pyopteryx.utils.builder_utils import add_activity_to_task, add_synch_call_to_activity
class LoopUsageActionFactory(AbstractUsageActionFactor... |
import os
file_path = os.path.join(os.path.dirname(__file__), 'GUI_QT.ui')
dest_path = os.path.join(os.path.dirname(__file__), 'gui.py')
out = os.system(f'pyuic5 -x {file_path} -o {dest_path}')
if out:
print('Error:', out)
exit(1)
else:
print('Its ok.')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.