text stringlengths 2 999k |
|---|
import time
from collections import Counter, defaultdict
import warnings; warnings.filterwarnings('ignore')
import glob
import re
import ast
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from algorithms import ShapeletTransformer
from extractors.extractor import MultiGeneticExtractor
from dat... |
class SolutionTLE:
def shortestDistance(self, grid: List[List[int]]) -> int:
buildings = []
rows, cols = len(grid), len(grid[0])
for row in range(rows):
for col in range(cols):
if grid[row][col] == 1:
buildings.append((row, col))
def... |
from torch.distributed.rpc import RRef
from hearthstone.simulator.agent import AnnotatingAgent, Annotation, DiscoverChoiceAction, StandardAction, \
RearrangeCardsAction, HeroChoiceAction
class RemoteAgent(AnnotatingAgent):
def __init__(self, remote_agent: RRef):
self.remote_agent = remote_agent
... |
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 30, transform = "RelativeDifference", sigma = 0.0, exog_count = 100, ar_order = 0); |
"""
Base class for modular abelian varieties
AUTHORS:
- William Stein (2007-03)
TESTS::
sage: A = J0(33)
sage: D = A.decomposition(); D
[
Simple abelian subvariety 11a(1,33) of dimension 1 of J0(33),
Simple abelian subvariety 11a(3,33) of dimension 1 of J0(33),
Simple abelian subvariety 33a(... |
#!/usr/bin/env python3
# Author: Volodymyr Shymanskyy
# Usage:
# ./run-spec-test.py
# ./run-spec-test.py ./core/i32.json
# ./run-spec-test.py ./core/float_exprs.json --line 2070
# ./run-spec-test.py ./proposals/tail-call/*.json
# ./run-spec-test.py --exec ../build-custom/wasm3
# ./run-spec-test.py --engine... |
# Copyright 2019 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, ... |
from lektor.constants import PRIMARY_ALT
from lektor.i18n import get_i18n_block
from lektor.types.base import Type
class FakeType(Type):
def value_from_raw(self, raw):
return None
def to_json(self, pad, record=None, alt=PRIMARY_ALT):
rv = Type.to_json(self, pad, record, alt)
rv["is_fa... |
"""Module implémentant des classes en relations avec le menu."""
from typing import Callable, Dict, List, Tuple, AnyStr
class Trafficlight:
"""Modélise un feu de circulation présentant un état lumineux donné.
wrarn : la couleur affectée par défaut n'est pas validée par l'init
autrement dit on pe... |
''' clip.py:
Implement's the clip ONNX node as a flexnode (for use with any accelerator)
'''
import uuid
import numpy as np
from operators.flexnode import FlexNode
from core.defines import Operator
from core.messaging import Message
class Clip(FlexNode):
def __init__(self, onnx_node, inputs, outputs):
... |
"""
SQLite3 backend for django.
Works with either the pysqlite2 module or the sqlite3 module in the
standard library.
"""
from __future__ import unicode_literals
import datetime
import decimal
import warnings
import re
from django.db import utils
from django.db.backends import *
from django.db.backends.sqlite3.clien... |
titulo = 'Cadastro de Pessoas'
print(titulo.center(50, '='))
print('')
idade = total = homens = mulheres = 0
sexo = ''
while True:
idade = int(input('Idade: '))
sexo = input('Sexo: [M] ou [F]? ').upper().strip()[0]
while sexo not in 'MF':
sexo = input('Sexo: [M] ou [F]? ').upper().strip()[0]
res... |
import os
# Finds path of any file in the assets folder #
def findPath(folders, file, extension):
# Checks if it's an array (or other type of list idk, basically this should do the job) #
if(isinstance(folders, list)):
# Default folder path, being nothing #
folderPath = ""
# Loops thro... |
#!/usr/bin/env python
# Copyright (c) 2017 The sqlalchemy-bigquery Authors
#
# 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
# ... |
#!/usr/bin/env python
"""APOGEE cold shutter control and status
History:
2011-08-30 ROwen
2011-09-01 ROwen Added support for cancelling commands.
2012-11-14 ROwen Stop using Checkbutton indicatoron=False; it is no longer supported on MacOS X.
2015-11-03 ROwen Replace "== None" with "is None" and "!= None" wit... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# nnutil2 - Tensorflow utilities for training neural networks
# Copyright (c) 2019, Abdó Roig-Maranges <abdo.roig@gmail.com>
#
# This file is part of 'nnutil2'.
#
# This file may be modified and distributed under the terms of the 3-clause BSD
# license. See the LICENSE fi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Setup script for twodolib."""
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.re... |
from PySide2.QtWidgets import QPushButton, QMainWindow, QLabel, QLineEdit, QGroupBox
from math import ceil
import source
class MainWindow(QMainWindow):
def __init__(self, screen_width, screen_height):
self.screen_width = screen_width
self.screen_height = screen_height
self.screen_ratio = s... |
import graphene
from graphene import relay
from ....product import models
from ...core.connection import CountableDjangoObjectType
from ...core.scalars import UUID
from ...meta.types import ObjectWithMetadata
class DigitalContentUrl(CountableDjangoObjectType):
url = graphene.String(description="URL for digital c... |
#!/usr/bin/env python
# Copyright (c) YugaByte, 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... |
CARDS = (
(('Gr', 'Mu', 'Pe', 'Pl', 'Sc', 'Wh')),
(('Ca', 'Kn', 'Pi', 'Re', 'Ro', 'Wr')),
(('Ba', 'Bi', 'Co', 'Di', 'Ha', 'Ki', 'Li', 'Lo', 'St')),
)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, print_function, absolute_import,
unicode_literals)
from .sampler import *
from .mh import *
from .ensemble import *
from .ptsampler import *
from . import utils
from . import autocorr
__version__ = "2.1.0"
def t... |
"""
byceps.services.seating.area_service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2014-2022 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from __future__ import annotations
from typing import Optional
from sqlalchemy import select
from sqlalchemy.sql import Select
from ...d... |
"""
Unit test for multiple modules
This module illustrates what a proper unit test should look like.
Each function being tested has its own test procedure.
It also has a segment of "script code" that invokes the test
procedure when this module is run as an script.
Author: Walker M. White
Date: February 14, 2019
""... |
import glob, struct, random, csv
from tensorflow.core.example import example_pb2
# <s> and </s> are used in the data files to segment the abstracts into sentences. They don't receive vocab ids.
SENTENCE_START = '<s>'
SENTENCE_END = '</s>'
PAD_TOKEN = '[PAD]' # This has a vocab id, which is used to pad the encoder in... |
import os
import re
from sys import argv
from mod_pbxproj import XcodeProject
path = argv[1]
print path
project = XcodeProject.Load(path +'/Unity-iPhone.xcodeproj/project.pbxproj')
project.add_file_if_doesnt_exist('System/Library/Frameworks/Security.framework', tree='SDKROOT')
project.add_file_if_doesnt_exist('usr/l... |
'''
Created on Nov 9, 2017
@author: khoi.ngo
'''
def generate_random_string(prefix="", suffix="", size=20):
"""
Generate random string .
:param prefix: (optional) Prefix of a string.
:param suffix: (optional) Suffix of a string.
:param length: (optional) Max length of a string (include prefix an... |
import speech_recognition as sr
import pyttsx3
import pywhatkit
import datetime
import wikipedia
import pyjokes
import webbrowser
import os
#import pyaudio
listenner = sr.Recognizer()
engine = pyttsx3.init()
voices = engine.getProperty("voices")
engine.setProperty('voice', voices[1].id)
def talk(text):... |
# Generated by Django 3.1.1 on 2020-09-27 18:26
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),
('restaurants', '0006_auto... |
# Generated by Django 2.2.23 on 2021-07-07 13:18
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='BigModel',
fields=[
('id', models.AutoFiel... |
# coding: utf-8
"""
Lightly API
Lightly.ai enables you to do self-supervised learning in an easy and intuitive way. The lightly.ai OpenAPI spec defines how one can interact with our REST API to unleash the full potential of lightly.ai # noqa: E501
OpenAPI spec version: 1.0.0
Contact: support@lightly... |
from flask import render_template
from .import main
@main.app_errorhandler(404) #if error handlers used instead app_errorhandler the instnace is available only for errors originate in blueprint
def page_not_found(e):
return render_template(''), 404
@main.app_errorhandler(500)
def internal_server_error(e):
re... |
from setuptools import setup
setup(name='orinoco',
version='0.1',
description='Sweet data integration',
author='Quartic Technologies',
author_email='alex@quartic.io',
license='MIT',
packages=['orinoco'],
install_requires=[
'aiohttp',
'pyformance'
],
... |
#!/usr/bin/env python3
"""
Project title: CollembolAI
Authors: Stephan Weißbach, Stanislav Sys, Clément Schneider
Original repository: https://github.com/stasys-hub/Collembola_AI.git
Module title: output_inference_images
.py
Purpose: draws bounding boxes from annotation on pictures.... |
def is_even(n):
if n%2 is 0:
return True
return False
|
"""Provides the repository macro to import LLVM."""
load("//third_party:repo.bzl", "tf_http_archive")
def repo(name):
"""Imports LLVM."""
LLVM_COMMIT = "5020e104a1349a0ae6532b007b48c68b8f64c049"
LLVM_SHA256 = "3113dbc5f7b3e6405375eedfe95e220268bcc4818c8d8453a23ef00f82d4b172"
tf_http_archive(
... |
import pytest
from salesman.orders.models import Order
from salesman.orders.signals import status_changed
_signal_called = False
def on_status_changed(sender, order, new_status, old_status, **kwargs):
global _signal_called
_signal_called = True
@pytest.mark.django_db
def test_order_changed_signal(rf):
... |
import sys
sys.path.append('model/') |
'''
Created on Feb 26, 2021
@author: laurentmichel
'''
import os
class FileUtils(object):
file_path = os.path.dirname(os.path.realpath(__file__))
@staticmethod
def get_datadir():
return os.path.realpath(os.path.join(FileUtils.file_path, "../client/tests/", "data"))
@staticmethod
def... |
import os
import numpy as np
from models import ALOCC_Model
from utils import pp, visualize, to_json, show_all_variables
import tensorflow as tf
flags = tf.app.flags
flags.DEFINE_integer("epoch", 40, "Epoch to train [25]")
flags.DEFINE_float("learning_rate", 0.002, "Learning rate of for adam [0.0002]")
flags.DEFINE_fl... |
# Copyright 2020-present NAVER Corp. Under BSD 3-clause license
import sys
import os.path as path
# when developing, prefer local kapture to the one installed on the system
HERE_PATH = path.abspath(path.normpath(path.dirname(__file__)))
KATURE_LOCALIZATION_REPO_PATH = path.normpath(path.join(HERE_PATH, '../'))
# che... |
from dataclasses import dataclass
from apischema import serialize
@dataclass
class Foo:
bar: int = 0
baz: str | None = None
assert serialize(Foo, Foo(), exclude_defaults=True) == {}
assert serialize(Foo, Foo(), exclude_none=True) == {"bar": 0}
|
# coding=utf-8
"""
@Time: 2020/11/14 2:15 下午
@Author: Aopolin
@File: MolweniConfig.py
@Contact: aopolin.ii@gmail.com
@Description:
"""
class Config(object):
def __init__(self):
self.SQUAD_DIR = "../../Dataset/squad2.0"
self.MOLWENI_DIR = "../../Dataset/Molweni"
... |
# -*- coding: utf-8 -*-
# Copyright 2022 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... |
"""
:mod:`pyformlang.regular_expression`
====================================
This module deals with regular expression.
By default, this module does not use the standard way to write regular
expressions. Please read the documentation of Regex for more information.
Available Classes
-----------------
Regex
A re... |
from pkg_resources import parse_version
from configparser import ConfigParser
import setuptools
assert parse_version(setuptools.__version__)>=parse_version('36.2')
# note: all settings are in settings.ini; edit there, not here
config = ConfigParser(delimiters=['='])
config.read('settings.ini')
cfg = config['DEFAULT']
... |
# -*- coding: utf-8 -*-
"""
train bert
python tagging/train.py --train ../../data/v6/corpus.wordbiased.tag.train --test ../../data/v6/corpus.wordbiased.tag.test --working_dir TEST --train_batch_size 3 --test_batch_size 10 --hidden_size 32 --debug_skip
"""
from pytorch_pretrained_bert.tokenization import BertTokenize... |
from re import X
from tkinter import Y
import cv2
cap = cv2.VideoCapture("demo2.mp4")
ret, img = cap.read()
roibb = cv2.selectROI("image", img, fromCenter=False, showCrosshair=True)
print('X', roibb[0])
print('Y', roibb[1])
print('Width', roibb[2])
print('Height', roibb[3])
with open('roi.cfg', 'w+') as rf:
rf.w... |
from distutils.version import LooseVersion
from ... import logging
from .base import HAVE_DIPY, dipy_version, dipy_to_nipype_interface, get_dipy_workflows
IFLOGGER = logging.getLogger("nipype.interface")
if HAVE_DIPY and LooseVersion(dipy_version()) >= LooseVersion("0.15"):
from dipy.workflows import align
... |
from approaches.abstract_approach import AbstractApproach
from approaches.simple import SimpleApproach
from approaches.tfidf import TfIdfApproach
from approaches.intersection import IntersectionApproach
|
import dash
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.express as px
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
df = pd.read_csv('https://plotly.github.io/data... |
import pytest
from poetry.core.semver import Version
from poetry.core.semver import VersionRange
from poetry.core.semver import VersionUnion
from poetry.core.semver import parse_constraint
@pytest.mark.parametrize(
"constraint,version",
[
("~=3.8", VersionRange(min=Version(3, 8), max=Version(4, 0), i... |
#!/usr/bin/env python3
"""Using repeat() and map()
"""
#end_pymotw_header
from itertools import *
for i in map(lambda x, y: (x, y, x * y), repeat(2), range(5)):
print('{:d} * {:d} = {:d}'.format(*i))
|
import numpy as np
import pandas as pd
from scipy.stats.mstats import gmean
import random
import math
from randomdict import RandomDict
# from chest import *
import shelve
from Patch import *
from AgentBranch import *
import gc
from memory_profiler import memory_usage
#Model.py
class Model():
def __init__(self, gu... |
# coding=utf-8
import time
import os
class CreateID:
def __init__(self, rpapp):
self.rpapp = rpapp
def create_docs(self):
driver = self.rpapp.driver
driver.find_element_by_xpath(
"(.//*[normalize-space(text()) and normalize-space(.)='ti'])[1]/following::button[6]").click(... |
import datetime
from moto.core import BaseBackend
from moto.core.utils import iso_8601_datetime
class Token(object):
def __init__(self, duration, name=None, policy=None):
now = datetime.datetime.now()
self.expiration = now + datetime.timedelta(seconds=duration)
self.name = name
sel... |
def holaTodos(nombre1, nombre2):
print("Hola,", nombre2)
print("Hola,", nombre1)
holaTodos("Sebastián", "Felipe") |
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from collections import defaultdict, OrderedDict
from io import StringIO
import io
import os
import sys
import datetime
import argparse
import nump... |
"""
Test for the SmartThings sensors platform.
The only mocking required is of the underlying SmartThings API object so
real HTTP calls are not initiated during testing.
"""
from pysmartthings import ATTRIBUTES, CAPABILITIES, Attribute, Capability
from homeassistant.components.sensor import DEVICE_CLASSES, DOMAIN as ... |
#!/usr/bin/env python3
# pvoutput.py
#
# Simple library for uploading data to PVOutput.
import urllib.request
import urllib.parse
import urllib.error
import logging
import sys
logger = logging.getLogger(__name__)
class System:
"""Provides methods for direct uploading to PVOutput for set system."""
def ... |
from django.conf.urls import include, url # pragma: no cover
from django.contrib import admin # pragma: no cover
from weddingServices import views as ws_views # pragma: no cover
from django.contrib.auth import views as auth_views # pragma: no cover
urlpatterns = [ # pragma: no cover
# Examples:
# url(r'^$', '... |
# -*- coding: utf-8 -*-
""" Sahana Eden Guided Tour Model
@copyright: 2009-2015 (c) Sahana Software Foundation
@license: MIT
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 w... |
import asyncio
import inspect
import json
import logging
from asyncio import Queue, CancelledError
from sanic import Blueprint, response
from sanic.request import Request
from sanic.response import HTTPResponse, ResponseStream
from typing import Text, Dict, Any, Optional, Callable, Awaitable, NoReturn, Union
import ra... |
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Michael A.G. Aivazis
# California Institute of Technology
# (C) 1998-2003 All Rights Reserved
#
# <LicenseText>
#
# ~~~~~~~~~~~~~~~~... |
import os
import os.path
import json
import pathlib
from types import prepare_class
from ulauncher.api.client.Extension import Extension
from ulauncher.api.client.EventListener import EventListener
from ulauncher.api.shared.event import (
KeywordQueryEvent,
ItemEnterEvent,
PreferencesEvent,
PreferencesUpdateEvent,
... |
"""
Copyright (c) 2019 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 writing,... |
from gensim.models import KeyedVectors
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.font_manager as fm
import pandas as pd
glove_vector_file = "vectors.txt"
gensim_glove_vector_file = "gensim_glove_vectors.txt"
top_k = 10
words_triple_file = 'similarity_words.ttl'
# G... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Leonardo Arcari @leonardoarcari"
from networkx.relabel import convert_node_labels_to_integers
import networkx as nx
from pathlib import Path
from osgeo import ogr
from osgeo import osr
from math import cos, sin, asin, sqrt, radians
import random
## Modules
... |
import re
import sys
def walk(m, n, x, y):
c = 0
while n > y:
c, m, n, x, y = c + m, n - 1, m, n - y, x
return c + x
with open(sys.argv[1], 'r') as test_cases:
for test in test_cases:
print(walk(*map(int, re.findall(r'\d+', test))))
|
# JoyStick
#
# Copyright (c) 2021 Hajime Saito
#
# Released under the MIT license.
# see https://opensource.org/licenses/MIT
import pygame
from pygame.locals import *
import Repeater
JOY_MAX_TRIGGER = 16
JOY_NOINPUT = 0
JOY_UP = 0x1 << JOY_MAX_TRIGGER
JOY_RIGHT = 0x2 << JOY_MAX_TRIGGER
JOY_DOWN = 0x4 <<... |
from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework.generics import CreateAPIView
User = get_user_model()
class SignupSerializer(serializers.Serializer):
error_message = "'{value}' is a registered {field}. Contact admin if you forgets password."
username... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
import jwt
from flask import render_template, Flask, request, session, send_file
import secrets
from datetime import datetime
import io
from jwt import PyJWTError
from werkzeug.exceptions import BadRequest
from werkzeug.utils import redirect
import pandas as pd
from microsetta_admin import metadata_util, upload_util
... |
from bz2 import BZ2File
from collections import Counter, Sequence, Iterable, \
Mapping
from functools import partial
import gc
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email import encoders
from inspect import signature, getattr_... |
'''
common usage:
1. put this script in ckpt folder
2. python print_tensor_in_ckpt.py > tensors.txt
'''
# ref: https://stackoverflow.com/questions/38218174/how-do-i-find-the-variable-names-and-values-that-are-saved-in-a-checkpoint
import tensorflow as tf
from tensorflow.python.tools.inspect_checkpoint import print... |
#!/usr/bin/env python3
# Copyright (c) 2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test segwit transactions and blocks on P2P network."""
from test_framework.mininode import *
from test_fram... |
import inspect
import json
import logging
import threading
from datetime import datetime, timezone
from time import time
import pytz
import requests
from notion.block import TextBlock
from notion.client import NotionClient
from notion.collection import NotionDate
from tqdm import tqdm
from tzlocal import get_localzone... |
import shutil
import sys
import os
for (root,dirs,files) in os.walk(os.path.abspath('.'),topdown=True):
for d in dirs:
path = os.path.join(root,d)
if '__pycache__' in path:
shutil.rmtree(path)
for f in files:
path = os.path.join(root,f)
if '.DS_Store' in path:
os.remove(path)
|
class messageEntity:
isBotMention = False
start: int
end: int
def __repr__(self):
return "<class 'messageEntity' ({})>".format(type(self))
class formatEntity(messageEntity):
pass
class mention(messageEntity): #(@username)
text: str
user: str
def __init__(self, text, user = N... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# 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 importlib import import_module
from os import path
import re
from setuptools import find_packages, setup
def get_version():
text = open(path.join(path.dirname(__file__), "markdown_it", "__init__.py")).read()
match = re.compile(r"^__version__\s*\=\s*[\"\']([^\s\'\"]+)", re.M).search(text)
return mat... |
""" A BlogController Module """
from masonite.controllers import Controller
from masonite.request import Request
from app.Blog import Blog
class BlogController(Controller):
def __init__(self, request: Request):
self.request = request
def show(self):
id = self.request.param("id")
retur... |
import uuid
import datetime
from sqlalchemy import Float
from sqlalchemy import Column
from sqlalchemy import String
from sqlalchemy import Integer
from sqlalchemy import Boolean
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy import UniqueConstraint
from sqlalchemy.orm import backref... |
import os
import csv
from django.core.management.base import BaseCommand
from django.db import transaction
from api.models import Action, Country, DisasterType, SituationReportType
from api.logger import logger
class Command(BaseCommand):
help = 'Import translated strings from a CSV. Either use the --table and --... |
from ctre import WPI_TalonSRX
class Shooter:
motor: WPI_TalonSRX
def __init__(self):
self.ref_velocity = 0
def enable(self):
self.ref_velocity = 1
def disable(self):
self.ref_velocity = 0
def ready(self):
return self.motor.getQuadratureVelocity() > 4500
def e... |
"""fasterRCNN训练的损失函数与数据生成器"""
from keras.applications.imagenet_utils import preprocess_input
from keras import backend as K
import keras
import tensorflow as tf
import numpy as np
from random import shuffle
import random
from PIL import Image
from keras.objectives import categorical_crossentropy
from matplotlib.colors ... |
import os
from setuptools import setup
#data_files = []
#directories = glob.glob('src/share')
setup(
name = "bmk",
packages=['bmk'],
package_dir = {'' : 'src'},
package_data = {'bmk' : ['share/*']},
author = "Matthew Ballance",
author_email = "matt.ballance@gmail.com",
description = ("Provides a core c... |
# -*- coding: utf-8 -*-
# Copyright 2016 OpenMarket Ltd
#
# 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 la... |
# Copyright 2014 Google 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.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agre... |
#!/usr/bin/python
# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
# 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
... |
from django.db import models
class Person(models.Model):
age = models.IntegerField()
name = models.CharField(max_length=100)
class Document(models.Model):
myfile = models.FileField(upload_to="uploads")
|
from Simulation.calculation_status import CalculationStatus
from Simulation.sign_function import SignFunction
from Simulation.mcad import Mcad
from Simulation.market_snapshot import MarketSnapshot
from Simulation.stock_snapshot_helper import StockSnapshotHelper
from Simulation.visualization_data import VisualizationDat... |
_base_ = [
'../../_base_/models/tsm_r50.py', '../../_base_/schedules/sgd_tsm_100e.py',
'../../_base_/default_runtime.py'
]
# model settings
model = dict(backbone=dict(pretrained='weight/resnet50-19c8e357.pth'),cls_head=dict(num_classes=2))
log_config = dict(
interval=1,
hooks=[
dict(type='TextL... |
import matplotlib.pyplot as plt
import nnfs
from nnfs.datasets import vertical_data
nnfs.init()
X, y = vertical_data(samples=100, classes=3)
plt.scatter(X[:, 0], X[:, 1], c=y, s=40, cmap='brg')
plt.show()
import numpy as np
import nnfs
import matplotlib.pyplot as plt
nnfs.init()
class Layer_Dense:
def __init_... |
import ldb
# console based do not edit
while True:
cmd = str(input("LDB > "))
cmd = cmd.split(" ")
if cmd[0].lower() == "exit":
break
elif cmd[0].lower() == "init":
ldb.init()
elif cmd[0].lower() == "create":
ldb.create(list(cmd[1:]))
elif cmd[0].lower() == "view":
... |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# Copyright 2017 The TensorFlow Authors. 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 applica... |
# -*- coding: utf-8 -*-
#
# dataflake.fakeldap documentation build configuration file, created by
# sphinx-quickstart on Sat May 27 10:35:35 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 15 10:14:35 2018
@author: alexissoto
"""
'''
Music Production Kit
'''
import librosa as lb
song = "Fantasia_Impromptu.m4a" #Input file
def TempoChange():
y, sr = lb.load(song, duration = 30)
tempo, beat_frames = lb.beat.beat_trac... |
import scipy.signal as signal
import torch
import torch.nn as nn
import numpy as np
import models
import gym
import wandb
def create_feedforward(sizes, activation=nn.ReLU):
layers = []
for i in range(len(sizes) - 1):
layers.append(nn.Linear(sizes[i], sizes[i+1]))
if i < len(sizes) - 2:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.