text
string
size
int64
token_count
int64
import sys print(sys.version_info[:2])
39
15
"""This module is designed to build timestrings from file metadata. Everything is done in seconds since the unix epoch or UTC. Author: Brian Lindsay Author Email: tekemperor@gmail.com """ import sys import os import datetime def filetime(file_path): """Returns formatted time string from file metadata. Uses mo...
2,467
661
from __future__ import print_function from tqdm import * import sys import argparse import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from torch.utils.data import DataLoader from torch.optim import lr_scheduler import torch.utils.data.distributed import torchvision.tran...
9,750
3,188
import argparse import json import os from datetime import datetime from settings import annotation_predictor_metadata_dir def concat_detection_record(record1: str, record2: str): """ Concatenates two detection records and saves them in a new file. Args: record1: Path to first record, saved in a ...
1,355
445
""" Generic Device class for manipulators. To make a new device, one must implement at least: * position * absolute_move """ from numpy import array import time __all__ = ['Device'] class Device(object): def __init__(self): pass def position(self, axis): ''' Current position along an...
2,579
698
# PHOTOMETRY CODE (TEST) FOR PYTHON 3.X # 2019.03.09 # GREGORY S.H. PAEK #============================================================ import os, glob import numpy as np import matplotlib.pyplot as plt from astropy.io import ascii from astropy.io import fits #from imsng import zpcal #===================================...
9,068
4,364
from django.db import transaction from django.shortcuts import render, redirect from django.urls import reverse_lazy, reverse from django.views.generic import CreateView, ListView, DeleteView, UpdateView, DetailView from django.contrib.auth.mixins import LoginRequiredMixin from LetsCook.common.forms import CommentForm...
5,440
1,579
from . models import Profile, Business,Myhood, PolicePosts, HealthFacilities, UserPost from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.forms import widgets class UserRegistrationForm(UserCreationForm): class Meta: mo...
4,540
1,332
""" Author: Alexandra Lee Date Created: 11 March 2020 Scripts related to training the VAE including 1. Normalizing gene expression data 2. Wrapper function to input training parameters and run vae training in `vae.tybalt_2layer_model` """ from ponyo import vae, utils import os import pickle import pandas as pd from s...
4,599
1,420
"""Provides other helper functions for factors""" from typing import Any, Iterable import numpy from pandas import Categorical, DataFrame from pipda import register_verb from pipda.utils import CallingEnvs from ..core.types import ForcatsRegType, ForcatsType, is_null, is_scalar from ..core.utils import Array from ..co...
3,096
1,088
from . import utils from . import models __all__ = ['utils', 'models']
71
23
# Copyright 2018 PIQuIL - All Rights Reserved # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache Licens...
6,585
2,206
cond = True while cond: x = int(input("Input X Value :")) y = 10 if (x > 10) else 5 if (x < 5) else x print("{} is the Y value".format(y)) cond = True if input("continue? y/n :") == "y" else False
214
85
import copy def next10(i): # start condition board = [3, 7] elves = [0, 1] found = False # while (len(board) < i + 10): while (not found): to_add = board[elves[0]] + board[elves[1]] if (to_add < 10): board.append(to_add) if (board[-1*len(i):] == i): ...
1,433
666
import xmlrpclib from SimpleXMLRPCServer import SimpleXMLRPCServer from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler import numpy as np from io import StringIO from numpy.linalg import inv from scipy.linalg import * # Restrict to a particular path. class RequestHandler(SimpleXMLRPCRequestHandler): ...
892
302
# put your python code here print(10)
38
14
#!/usr/bin/env python # coding=utf-8 from smtplib import SMTPException from django.conf import settings from django.core.management import BaseCommand from django.core.mail import send_mail class Command(BaseCommand): def _log(self, tag, result): label = self.style.ERROR("XXX") if result: ...
1,524
449
"""Manages the lifecycle of a docker container. Use via the with statement: with Container(some_image) as c: for line in c.run("some_command"): print line """ import docker import click, os # sets the docker host from your environment variables client = docker.Client( **docker.utils.kwargs_from_env(a...
4,113
1,212
import networkx as nx import numpy as np from sklearn import covariance import torch def convertToTorch(data, req_grad=False, use_cuda=False): """Convert data from numpy to torch variable, if the req_grad flag is on then the gradient calculation is turned on. """ if not torch.is_tensor(data): d...
4,321
1,444
def multiplica_matrizes(m1, m2): '''Minha solução para multiplicação de matrizes''' matriz = [] cont = 0 b1 = 0 for t in range(len(m1)): # números de linhas mat1 linhanova = [] for t1 in range(len(m2[0])): #números de colunas mat2 while cont < len(m2): #a1...
1,475
644
# Generated by Django 2.2.2 on 2019-06-10 03:37 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('zoo_checks', '0015_auto_20190609_2303'), ] operations = [ migrations.RenameField( model_name='enclosure', old_name='user', ...
366
139
""" Tests of the view factors module """ import pytest import numpy as np from bifacialvf.vf import getSkyConfigurationFactors from bifacialvf.tests import ( SKY_BETA160_C05_D1, SKY_BETA20_C05_D1, SKY_BETA20_C0_D1, SKY_BETA160_C0_D1, SKY_BETA160_C1_D1, SKY_BETA20_C1_D1, SKY_BETA20_C1_D0, SKY_BETA160_C1_D0, ...
996
604
# Databricks notebook source import horovod.tensorflow.keras as hvd def run_training_horovod(): # Horovod: initialize Horovod. hvd.init() import os print(os.environ.get('PYTHONPATH')) print(os.environ.get('PYTHONHOME')) print(f"Rank is: {hvd.rank()}") print(f"Size is: {hvd.size()}") # COMM...
732
269
#!/usr/bin/env python3 import boto3 import os import base64 """ Uploads pre-generated certificates to SSM for the ci to consume example WORKSPACE=dev-next ENVIRONMENT=sandbox aws-vault exec sandbox-shared -- make upload-certificates """ class UploadCertificates(object): ssm_client = None environment = None...
1,973
612
import multiprocessing from multiprocessing import Queue from OpenPersonDetector import OpenPersonDetector from newgen.GenerativeDetector import AbstractDetectorGenerator class ManagedOPDetector: def __init__(self, input_queue, output_queue): self.input_queue = input_queue self.output_queue = ou...
1,709
497
# -*- coding: utf-8 -*- """ Created on Thu Mar 12 10:11:09 2020 @author: NAT """ import torch from torch.utils.data import Dataset import json import os from PIL import Image from utils import transform class VOCDataset(Dataset): def __init__(self, DataFolder, split): """ DataFol...
1,832
573
#!/usr/bin/python DOCUMENTATION = ''' --- module: to_toml, from_toml version_added: "2.8" short_description: Converts Python data to TOML and TOML to Python data. author: - "Samy Coenen (contact@samycoenen.be)" ''' import datetime import sys from collections import OrderedDict #pip3 install python-toml def to_to...
7,564
2,730
def divisor(n: int): divisors = [] for integer in range(1, int(n**0.5)+1): if not n % integer: divisors.append(integer) divisors.append(n//integer) divisors.sort() return divisors n = int(input()) divisors = divisor(2*n) answer = 0 for integer in divisors: pair = 2*...
414
151
from mongoengine import Document, IntField, StringField, FloatField, connect from pymongo import UpdateOne class Episode(Document): title = StringField(required=True) show = StringField(required=True) rating = FloatField(required=True) votes = IntField(required=True) def bulk_upsert(episodes): bu...
862
238
import json import os from contextlib import AbstractContextManager from tools import settings def is_subset_dict(subset, superset): return subset.items() <= superset.items() def read(basename): with open(os.path.join("tests", "fixtures", f"{basename}.json")) as f: return json.load(f) class overr...
5,702
1,472
#!/usr/bin/env python from setuptools import setup setup( # The package name along with all the other metadata is specified in setup.cfg # However, GitHub's dependency graph can't see the package unless we put this here. name="sgkit", use_scm_version=True, )
276
80
# Mod Divmod "https://www.hackerrank.com/challenges/python-mod-divmod/problem" # Enter your code here. Read input from STDIN. Print output to STDOUT a, b = (int(input()) for _ in range(2)) print(a // b) print(a % b) print(divmod(a, b))
238
93
import subprocess import docx.table import pandas as pd from docx import Document from docx.enum.text import WD_PARAGRAPH_ALIGNMENT from docx.oxml import OxmlElement from docx.oxml import ns from docx.oxml.ns import qn from docx.shared import Inches, Pt from docx.table import _Cell from docx2pdf import convert class...
4,161
1,283
# -*- coding: utf-8 -*- """Test the import statement.""" import pytest def test_relative_missing_import(): """Test that a relative missing import doesn't crash. Some modules use this to check if a package is installed. Relative import in the site-packages folder""" with pytest.raises(ImportError): ...
357
103
"""精度評価指標を計算するモジュール y_trueと、y_pred_probaから精度評価指標を計算するための関数群 """ import sklearn.metrics as skm import numpy as np def auc(y_true, y_pred_proba): """AUCを計算する関数 Args: y_true(1-D array-like shape of [n_samples, ]): 2値の目的ラベルの配列(ラベルは0または1) y_pred_proba(1-D array-like shape of [n_samples, ]): 陽性(ラ...
2,879
1,760
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/ads/googleads_v2/proto/services/campaign_criterion_service.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.pr...
19,759
7,382
from network import WLAN import urequests as requests # from ubidots tutorial https://help.ubidots.com/en/articles/961994-connect-any-pycom-board-to-ubidots-using-wi-fi-over-http from machine import I2C import adafruit_sgp30 # from https://github.com/alexmrqt/micropython-sgp30 from machine import Pin from dht import DH...
4,568
1,697
# coding:UTF-8 import queue import serial import time import threading ACCData = [0.0] * 8 GYROData = [0.0] * 8 AngleData = [0.0] * 8 FrameState = 0 # 通过0x后面的值判断属于哪一种情况 Bytenum = 0 # 读取到这一段的第几位 CheckSum = 0 # 求和校验位 a = [0.0] * 3 w = [0.0] * 3 Angle = [0.0] * 3 count=0 start_time = time.time() interval=0.01 def ...
5,278
2,256
import os import unittest from torchtext.data import Field, Iterator from project.utils.utils_metrics import AverageMeter from project.utils.utils_logging import Logger from project.utils.datasets import Seq2SeqDataset data_dir = os.path.join(".", "test", "test_data") class TestIOUtils(unittest.TestCase): def ...
3,082
1,048
# Load in test framework from sublime_plugin_tests import framework class TestExample(framework.TestCase): def sampleTest(): pass
144
38
import torch import torch.nn as nn import numpy as np class Net(nn.Module): def __init__(self, num_classes=10): super().__init__() self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding=1) s = compute_conv_output_size(32, 3, padding=1) # 32 self.conv2 = nn.Conv2d(32, 32, kernel_siz...
2,156
919
# __init__.py # Version of the cab-dynamic-pricing package __version__ = "1.0.0"
82
32
# -*- coding: utf-8 -*- """ 654. Maximum Binary Tree Given an integer array with no duplicates. A maximum tree building on this array is defined as follow: The root is the maximum number in the array. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number. The right sub...
1,207
349
import asyncio import traceback from configuration_manager import ConfigurationManager from data_parser import * parse_map = { 0: ProtocolRequest, 1: ProtocolResponse, 2: ServerDisconnect, 3: ConnectSuccess, 4: ConnectFailure, 5: HandshakeChallenge, 6: ChatReceived, 7: None, 8: Non...
5,189
1,627
# Import Selenium Module from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # Import Path from pathlib import Path # Import Base Module for Code import os import datetime #...
4,224
1,449
import sys import os import mxnet as mx import argparse sys.path.append(os.path.join(os.getcwd(), "../src/common")) sys.path.append(os.path.join(os.getcwd(), "../src/eval")) import verification def argParser(): parser = argparse.ArgumentParser(description='test network') parser.add_argument('--model', default=...
3,032
1,124
# -*- coding: utf-8 -*- # # Copyright (C) 2021 Chris Caron <lead2gold@gmail.com> # All rights reserved. # # This code is licensed under the MIT License. # # 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 th...
4,482
1,603
#! /usr/bin/env python3 import argparse import textwrap import math from PIL import Image parser = argparse.ArgumentParser( prog='img_striper.py', formatter_class=argparse.RawDescriptionHelpFormatter, description=textwrap.dedent('''\ Image striper This is a simple program to make stripes ...
2,751
1,007
import datetime from aiohttp import web from aiohttp_jinja2 import template import sqlalchemy as sa from sqlalchemy.dialects import postgresql as pg import psycopg2 from ds import db from . import forms @template('index.jinja2') async def index(request): return {} @template('profile_list.jinja2') async def pr...
7,590
2,332
# Generated by Django 3.2.9 on 2021-11-19 15:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0007_alter_login_owner'), ] operations = [ migrations.CreateModel( name='Test1', fields=[ ('t...
488
159
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: tb_paddle/proto/api.proto from google.protobuf.internal import enum_type_wrapper from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _...
47,110
18,379
import six import json import logging import requests from requests_oauthlib import OAuth1 if six.PY3: from urllib.parse import parse_qs from urllib.parse import urlencode else: from urlparse import parse_qs from urllib import urlencode log = logging.getLogger(__name__) class EtsyError(Exception): ...
6,123
1,751
import datetime import os import re import sys import urllib from SatTrack.superclasses import FileDirectory ############################################################################### # CONSTANTS TLE_URL = f"https://celestrak.com/NORAD/elements/supplemental" ######################################################...
2,996
866
import os import h5py import torch import torch.nn as nn from torch.utils.data import Dataset, IterableDataset, DataLoader import Levenshtein as levenshtein from tqdm import tqdm from yaml import YAMLObject from transformers import AutoTokenizer, AutoModel from allennlp.modules.elmo import batch_to_ids from utils im...
21,970
7,287
# Copyright (c) 2021 AccelByte Inc. All Rights Reserved. # This is licensed software from AccelByte Inc, for limitations # and restrictions contact your company contract manager. # # Code generated. DO NOT EDIT! # template file: justice_py_sdk_codegen/__main__.py # justice-basic-service (1.36.3) # pylint: disable=d...
7,012
2,034
""" Copyright 2019 Samsung SDS 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 ...
2,505
957
# -*- coding: utf-8 -*- import logging from .__version__ import __version__ logging.getLogger(__name__).addHandler(logging.NullHandler()) __author__ = "Rajaram Kaliyaperumal, Arnold Kuzniar, Cunliang Geng, Carlos Martinez-Ortiz" __email__ = 'c.martinez@esciencecenter.nl' __status__ = 'beta' __license__ = 'Apache Li...
340
129
from django.contrib import admin from .models import Post,Author,Tag # Register your models here. class PostAdmin(admin.ModelAdmin): list_display=('title','date','author') list_filter=('author','tags','date') prepopulated_fields={'slug':('title',)} admin.site.register(Post,PostAdmin) admin.site.regi...
358
111
def main(): print('This is the very beginning of pyrallest')
67
23
# -*- coding: utf-8 -*- '''Chemical Engineering Design Library (ChEDL). Utilities for process modeling. Copyright (C) 2018 Caleb Bell <Caleb.Andrew.Bell@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 ...
60,795
23,653
# Generated by Django 3.1.14 on 2022-01-24 11:20 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("iaso", "0114_auto_20220117_1609"), ] operations = [ migrations.RenameField( model_name="entity", old_name="instance...
532
179
"""Delete command Author: Rory Byrne <rory@rory.bio> """ from typing import Any from git_plan.cli.commands.command import Command from git_plan.service.plan import PlanService from git_plan.util.decorators import requires_initialized, requires_git_repository @requires_initialized @requires_git_repository class Dele...
1,370
404
from django.contrib import admin from newspaper2.news.models import News, Event class NewsAdmin(admin.ModelAdmin): list_display = ('title', 'publish_date') list_filter = ('publish_date',) search_fields = ['title'] class EventAdmin(admin.ModelAdmin): pass admin.site.register(News, NewsAdmin) admin.site....
347
106
import numpy as np import cv2 CLASSES = ["background", "aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "train", "tvmonitor"] net = cv2.dnn.readNetFromCaffe( ...
1,926
764
""" Name: Lewis Papapetrou References: Ernst, Phys. Rev., v167, p1175, (1968) Coordinates: Cartesian """ from sympy import Function, Rational, exp, symbols, zeros coords = symbols("t x y z", real=True) variables = () functions = symbols("k r s w", cls=Function) t, x, y, z = coords k, r, s, w = functions metric = zeros...
618
304
from django.contrib import admin from modeltranslation.admin import TranslationAdmin from product.models import (Category, Discount, Review, Product, Properity, ProperityOption, Image, ShoppingCart, Tag,Wishlist,Color) class ReviewAdmin(admin.ModelAdmin): list_display = ('name', 'product', 'creat...
2,591
812
#!/usr/bin/env python3.6 # vim: ts=4 sw=4 import requests, lxml.html, json, sys, os, configparser, re from datetime import datetime from mastodon import * ## Initializing host = 'https://bpnavi.jp' ua = 'Mozilla/5.0 (iPhone; CPU iPhone OS 12_1_4 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko...
3,009
1,121
import numpy as np import matplotlib.pyplot as plt from scipy import optimize # Lecture 11 2-user water allocation example # First approach: scipy.optimize.linprog # need matrix form: minimize c^T * x, subject to Ax <= b c = [-5, -3] # negative to maximize A = [[10,5], [1,1.5], [2,2], [-1,0], [0,-1]] b = [20, 3, 4.5...
1,091
454
## This file used to be programmatically generated for converging to best fit Activity Dependent Inhibition curve. ## But that doesn't give decent result, so set by hand. import sys sys.path.extend(["../networks"]) ## do not import networkConstants as that imports this file, and it's circular then!!! from networkConst...
1,471
534
from .utils import defaults_f DEFAULTS = defaults_f({ 'ARTIFACTS_ROOT': '~/agoge/artifacts', 'TQDM_DISABLED': False, 'TRIAL_ROOT': 'Worker', 'BUCKET': 'nintorac_model_serving', 'BASE_URL': 'https://github.com/Nintorac/NeuralDX7-weights/raw/master' }) from .data_handler import DataHandler from .mod...
499
172
def do_loop(): print('Being Invoked.') # * 表示参数为 元组 def fun1(*args): # 相当于 def fun1(1,2,3) ==> args 就相当于(1,2,3) for a in args: print(a) # ** 表示参数为 字典 def fun2(**args): # 相当于 def fun2({a:1,b:2,c:3}) ==>args 就相当于{a:1,b:2,c:3} for k, v in args: print(k, ":", v) # Python3 的六个标准数据类型 def...
1,206
655
# -*- coding: utf-8 -*- import logging from scrapystsytem.misc.commonspider import CommonSpider from scrapy.spiders import Rule from scrapy.linkextractors import LinkExtractor as sle logger = logging.getLogger(__name__) class DoubanMovieSpider(CommonSpider): name = "doubanmovie" allowed_domains = ["douban...
951
321
import uuid class Message(object): def __init__(self, kind, timestamp, raw_data): self.kind = kind self.timestamp = timestamp self.raw_data = raw_data self.uuid = str(uuid.uuid4()) def _asdict(self): return { 'kind': self.kind, 'timestamp': self...
560
177
from nbexchange.handlers.assignment import Assignment, Assignments from nbexchange.handlers.collection import Collection, Collections from nbexchange.handlers.feedback import FeedbackHandler from nbexchange.handlers.pages import HomeHandler from nbexchange.handlers.submission import Submission, Submissions default_han...
469
134
#!/bin/env python3 import operator from _operator import attrgetter, itemgetter from collections import defaultdict, Counter from functools import reduce, partial from itertools import chain from aocd import get_data EMPTY = type('EMPTY', (int,), dict(__repr__=(f := lambda s: 'EMPTY'), __str__=f))(10) def windowed(...
2,476
855
from detectron2.engine import DefaultPredictor from detectron2.data import MetadataCatalog from detectron2.config import get_cfg from detectron2.utils.visualizer import ColorMode, Visualizer from detectron2 import model_zoo import cv2 import numpy as np import requests # Load an image res = requests.get("h...
1,343
539
import os import yaml import json import click import hydra.utils.constants as const from hydra.utils.git import check_repo from hydra.utils.utils import dict_to_string, inflate_options from hydra.cloud.local_platform import LocalPlatform from hydra.cloud.fast_local_platform import FastLocalPlatform from hydra.cloud.go...
9,920
2,919
'''requests biblioteca beaultiful solp para páginas web. ''' from builtins import print import requests '''compartilhando o cabeçario http, vem junto com requesição cabecalho = {'User-agent': 'Windows 12', 'Referer': 'https://google.com.br'} meus_cookies = {'Ultima-visita': '10-10-2020'} meus_...
773
298
import pygame import random import sys Xfactor = 1.35 Yfactor = 3.2 CELLS = 9 PLAYERS = 2 CORNERS = [1, 3, 7, 9] NON_CORNERS = [2, 4, 6, 8] board = {} for i in range(9): board[i + 1] = 0 signs = {0: " ", 1: "X", 2: "O"} winner = None boardX = 10 boardY = 464 icon = pygame.image.load("ttticon2.png"...
23,738
7,885
# -*- coding: utf-8 -*- # @Time : 2021/9/18 下午11:23 # @Author : DaiPuWei # @Email : 771830171@qq.com # @File : dataset_utils.py # @Software: PyCharm """ 这是YOLO模型数据集 """ import cv2 import numpy as np from PIL import Image from matplotlib.colors import rgb_to_hsv, hsv_to_rgb from utils.model_utils import...
25,458
9,680
import string def caesar_cipher(text, shift, decrypt=False): if not text.isascii() or not text.isalpha(): raise ValueError("Text must be ASCII and contain no numbers.") lowercase = string.ascii_lowercase uppercase = string.ascii_uppercase result = "" if decrypt: shift = shift * -1...
750
252
import json import logging from app.abc import StartError from app.device import DeviceApp, DeviceMessage from app.device.models import Device from app.hint import HintApp from app.hint.defs import HintMessage from util.storage import DataStore LOGGER = logging.getLogger(__name__) class Hume: def __init__(self...
6,953
1,852
# # Author: Michał Borzęcki # # This script creates empty files with study and data object metadata in # specified space and Oneprovider. It uses JSON files located in directories # `studies_dir` (= studies) and `data_object_dir` (= data_objects). Positional # arguments: # 1. Oneprovider location (IP address or domain...
3,281
1,132
from flask import jsonify, request import backend.services.user as user_services from . import bp @bp.route('/user', methods=['POST', 'GET']) def create_user(): if request.method == "POST": data_json = request.json body, status = user_services.create_user(data_json) elif request.method == "G...
1,925
626
# flake8: noqa from mot.motion_models.base_motion_model import MotionModel from mot.motion_models.CT_motion_model import CoordinateTurnMotionModel from mot.motion_models.CV_motion_model import ConstantVelocityMotionModel
222
74
# modu # Copyright (c) 2006-2010 Phil Christensen # http://modu.bubblehouse.org # # # See LICENSE for details """ Datatypes for managing stringlike data. """ import time, datetime from zope.interface import implements from modu.editable import IDatatype, define from modu.util import form, tags, date from modu.persi...
7,205
2,970
from functions.summation import summation from functions.subtraction import subtraction from functions.multiplication import multiplication from functions.division import division from functions.exponential import exponential from functions.root import root num1 = float(input('número 1: ')) num2 = float(input('número ...
829
269
! pip install -q librosa nltk import torch import numpy as np import librosa import librosa.display import IPython from IPython.display import Audio # need this for English text processing frontend import nltk ! python -m nltk.downloader cmudict preset = "20180505_deepvoice3_ljspeech.json" checkpoint_path = "20180505...
2,949
1,020
from discord.ext import commands from lib import exceptions import os import json configFile = os.path.join(os.getcwd(), "data", "config.json") with open(configFile, "rb") as f: config = json.load(f) def is_owner(): async def predicate(ctx): if ctx.author.id in config['owners']: return ...
405
124
import gym import numpy as np from torchvision.utils import save_image from .fixobj import FixedObjectGoalEnv class IntervalGoalEnv(FixedObjectGoalEnv): def __init__(self, args): self.img_size = args.img_size FixedObjectGoalEnv.__init__(self, args) def generate_goal(self): if self.target_goal_center is not ...
1,649
689
"""Alias command.""" from . import Command from ...packets import MessagePacket class Alias(Command): """Alias command.""" COMMAND = "alias" @Command.command(role="moderator") async def add(self, alias: "?command", command: "?command", *_: False, raw: "packet"): """Add a n...
1,908
547
import numpy as np def combine(signal_x, signal_y): return np.stack((signal_x, signal_y), axis=-1) def normalize(signal, minimum=None, maximum=None): """Normalize a signal to the range 0, 1. Uses the minimum and maximum observed in the data unless explicitly passed.""" signal = np.array(signal).astype('fl...
2,828
844
import os import sys import hashlib import importlib def is_available_boto3(): return importlib.util.find_spec("boto3") if is_available_boto3(): import boto3 from botocore import UNSIGNED from botocore.client import Config else: raise ModuleNotFoundError("Please install boto3 with: `pip install ...
2,839
936
def factorial(num): if num == 0: return 1 else: return num * factorial(num - 1) def main(): print("0! =", factorial(0)) print("1! =", factorial(1)) print("2! =", factorial(2)) print("3! =", factorial(3)) print("4! =", factorial(4)) print("5! =", factorial(5)) if __name_...
348
137
#!/usr/bin/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 ag...
1,565
536
from sqlalchemy import * from sqlalchemy.orm import relationship from db import db class Fleet(db.Model): __tablename__ = "fleet" id = Column(String, primary_key=True) deployment_target_id = Column(String, ForeignKey('deployment_target.id')) fleet_type_id = Column(String, ForeignKey('fleet_type.id'))...
1,054
370
from django.contrib import admin from .models import HypertriviationUser class HypertriviationUserAdmin(admin.ModelAdmin): model = HypertriviationUser # Register your models here. admin.site.register(HypertriviationUser, HypertriviationUserAdmin)
254
71
################################################################### ######## Follow up email ############# ################################################################### """ followup_email.py This is special use case code written to assist bot developers. It consolidates to...
1,568
476
from marshmallow import validate, fields, Schema class AuthorizationVal(Schema): id_auth = fields.Str(required=True, validator=validate.Length(max=10)) id_o = fields.Str(required=True, validator=validate.Length(max=10)) file_a = fields.Raw(required=True)
269
90
#!/usr/bin/env python # -*- coding: iso-8859-15 -*- # # Copyright 2003-2015 CORE Security Technologies # # 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/LIC...
1,213
409