text stringlengths 8 6.05M |
|---|
import sys
import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
import maya.OpenMayaRender as OpenMayaRender
nodeTypeName = "RG_Part"
# Gve an ID (identifier) to our type of node
nodeTypeId = OpenMaya.MTypeId(0x00000004)
# A pointer to hardware render class
glRenderer = OpenMayaRender.MHardwareRend... |
from random import randint
from datetime import datetime, timedelta
from Utility import Utility
import uuid
from decorators import run_time_decorator
device_list = {'billing': ['ICam007', 'ICam008', 'ICam009', 'ICam012'], 'sha': ['ICam001', 'ICam002', 'ICam003'],
'footfall': ['ICam004', 'ICam005', 'ICam... |
from os import environ
# if you set a property in SESSION_CONFIG_DEFAULTS, it will be inherited by all configs
# in SESSION_CONFIGS, except those that explicitly override it.
# the session config can be accessed from methods in your apps as self.session.config,
# e.g. self.session.config['participation_fee']
SESSION_... |
from typing import Optional
from pydantic import BaseModel
from enum import Enum
from datetime import datetime
class Sex(str, Enum):
"""发送者的性别枚举
"""
male = "male"
female = "female"
unknown = "unknown"
class PostType(str, Enum):
"""事件类型枚举
"""
message = "message"
notice = "notice"
... |
import time
import sys
import numpy as np
import random
from random import choice
import multiprocessing
import time
# Set Global Variables:
# numberrr = 0
start = 0
run_time = 0
termination = 0
random_seed = 0
vertices = 0
depot = 0
required_edges = 0 # task number!!!
# non_required_edges = 0
# vehicles = 0
capacity... |
# Generated by Django 3.0.6 on 2020-05-20 22:56
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('bookflixapp', '0007_auto_20200520_1930'),
]
operations = [
migrations.DeleteModel(
name='PerfilCust',
),
]
|
# convert to R - doing
# do analysis -> t.test or anova? ANOVA
from csep.loglikelihood import calcLogLikelihood as loglikelihood
import gaModel.etasGaModelNP as etasGaModelNP
import models.model as model
import models.modelEtasGa as etasGa
"""
This file needs to be undestood -> what does it do?
"""
def loadModelSC(... |
from smtplib import SMTP_SSL
from email.message import EmailMessage
from getpass import getpass
from collections import defaultdict
def get_user_input(message, category=str):
while True:
try:
return category(input(message))
except ValueError:
print(f"Please input a {categor... |
# -*- coding: utf-8 -*-
# See github page to report issues or to contribute:
# https://github.com/hssm/advanced-browser
class InternalFields:
def __init__(self):
self.noteColumns = []
self.cardColumns = []
def onBuildContextMenu(self, contextMenu):
nGroup = contextMenu.newSubMenu("- ... |
import re
import error as e
data_type = {'int': r'^[0-9]+$',
'float': r'^[0-9].?[0-9]*',
'string': r'^(\").*(\")$'}
def type_check(words, values):
word_list = []
for i in words:
word_list.append(words[i])
for i in range(len(word_list)):
for type in data_type:
... |
import os
from environment import environment
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.%s" % environment)
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
"""
Python module to read from the PurpleCrane GrowApp database, and write to CROP database.
There is not quite a 1:1 mapping between the CROP tables/columns and the GrowApp tables/columns.
The philosophy in this module is to perform all the necessary logic to do the transformation in the
get_xyz functions, that then... |
from typing import Tuple, Callable, Optional
from computegraph.types import Function
from summer2.parameters import Time, Data
from summer2.experimental.model_builder import ModelBuilder
from .parameters import TestingToDetection, Population
from autumn.core.inputs import get_population_by_agegroup
from autumn.settin... |
# Skal kode etter programkartet vi laget i stad:
# Beregning av bruttolønn, skattetrekk og netto utbetalt.
# Først trenger vi inpt/inndata fra brukeren.
timelonn = float(input('Hva er din timelønn? '))
antall_timer = float(input('Hvor mange timer har du arbeidet? '))
# Beregner bruttolønn.
bruttolonn = timel... |
/home/miaojian/miniconda3/lib/python3.7/_dummy_thread.py |
from django.test import TestCase
from django.urls import reverse
from .models import Post
from bs4 import BeautifulSoup
import requests
class ParserTests(TestCase):
url = "https://news.ycombinator.com/"
def test_fetch_posts(self):
response = requests.get(self.url)
self.assertEqual(response.st... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#pylint: disable=
"""
File : WorkflowManager.py
Author : Valentin Kuznetsov <vkuznet AT gmail dot com>
Description: Workflow management tools
"""
from __future__ import print_function
# system modules
import os
import re
import json
import httplib
# ReqMgr module... |
import os
import numpy as np
import tensorflow as tf
import tensorlayer as tl
from config import FLAGS_CMNIST, FLAGS_CIFAR
from train import args
flags = FLAGS_CMNIST()
if args.dataset == 'CMNIST':
flags = FLAGS_CMNIST()
elif args.dataset == 'CIFAR_10':
flags = FLAGS_CIFAR_10()
else:
print('da... |
"""
Class module defining the Project class and its Qt interface class ProjectView (derived from QTreeview).
"""
import yaml
import application.lib.objectmodel as objectmodel
class Project(object):
"""
Class implementing the concept of user project in a similar waya as in other integrated development enviro... |
H, W = map( int, input().split())
N = int( input())
A = list( map( int, input().split()))
reverse = 0
ANS = [ [] for _ in range(H)]
gyou = 0
cnt = 0
for i in range(N):
for j in range(A[i]):
cnt += 1
if reverse == 0:
ANS[gyou].append(i+1)
else:
ANS[gyou].insert(0, i+1)... |
import re
def main():
with open('Fayek.bib', 'r') as f:
lines = f.read()
bibs = lines.split('@')[1:]
for bib in bibs:
# bib = re.sub(r'\n(?=[^{}]*})', '', bib) # remove new lines
# bib = re.sub(r' +(?=[^{}]*})', ' ', bib) # remove multiple space
bib = bib.replace(',\n', '<>').replace(', \n', '<>').repl... |
import time
from playwright import sync_playwright
# 以下コマンドラインでレコード機能
# python -m playwright codegen
def test_run(playwright):
browser = playwright.chromium.launch(headless=True)
context = browser.newContext()
page = context.newPage()
# Go to
page.goto("https://next.rikunabi.com/")
# Scree... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# author: cg错过
# time : 2017-12-12
class AllModuleRunAll:
# 为实现在规定之间内只执行一次,
# 例如在小时数为9的时候,这个小时内只执行一次检测
# 这个类只是提供一个判断条件
# 当然也可以利用此条件来执行几次,就看后面调用时的代码怎么写了
# 2017-12-14添加intOverAllCheckPicArrivals,intOverAllCheckPm2
# 2018-04-25添加intO... |
"""
distutilazy.util
----------------
utility functions
:license: MIT. For more details see LICENSE file or
https://opensource.org/licenses/MIT
"""
import os
import fnmatch
def find_files(root, pattern):
"""Find all files matching the glob pattern recursively
:param root: string
:param pattern: string
... |
from db_models.models.base.abstract_uploaded_media import AbstractUploadedMedia
class UploadedPhoto(AbstractUploadedMedia):
s3_bucket = 'gymapplife-uploaded-photo'
|
from app import cmx
variaveis = {
'usuario': f"INSERT INTO usuario (user, nome, senha, email, status_user) VALUES ('%s', '%s', '%s', '%s', 'false')",
'administrador': f"INSERT INTO administrador (user, nome, senha, email, chave) VALUES ('%s', '%s', '%s', '%s', '%s')",
'seleciona_um' :f"SELECT %s FROM %s WH... |
from django.shortcuts import render
from django.views import generic
from blog.models import Post
# Create your views here.
#
# def home(request):
# return render(request,'index.html',{})
#
class Index(generic.ListView):
template_name = 'index.html'
context_object_name = "posts"
def get_queryset(self... |
#!/usr/bin/env python
#################################################################
#
# Copyright (c) 2012
# Fraunhofer Institute for Manufacturing Engineering
# and Automation (IPA)
#
#################################################################
#
# Project name: care-o-bot
# ROS stack name: cob_driver
# ROS ... |
import numpy as np
# fix the random seed for reproducibility
seed = 1337
np.random.seed(seed)
import convnet_models
import matplotlib.pyplot as plt
from keras.preprocessing.image import ImageDataGenerator
from keras.utils import np_utils, plot_model
from keras.models import load_model
from keras import backend as K
K.... |
import pandas as pd
import matplotlib.pyplot as plt
dataframe = pd.read_csv('data/problem1data.txt', header=None)
datasetClass0 = # Put your code here (hint: see https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.loc.html)
datasetClass1 = # Put your code here
figure = plt.figure()
axis = figure.... |
import sqlite3
conn = sqlite3.connect('./resource/db_task.db',isolation_level=None)
cur = conn.cursor()
cur.execute('CREATE TABLE IF NOT EXISTS student_info( \
student_id INTEGER PRIMARY KEY, \
name TEXT, \
tel TEXT, \
region TEXT)')
cur.execute('CREATE TABL... |
# run in CMSSW_9_3_1
from WMCore.Configuration import Configuration
config = Configuration()
config.section_("General")
config.General.requestName = "tmp"
config.General.workArea = 'crab_dim6top_18Mai18'
config.General.transferLogs = True
config.section_("JobType")
config.JobType.pluginName = 'PrivateMC'
config.JobTy... |
from requests import get, post
from io import BytesIO
from json import loads, dumps
import base64
import api
from tools import get_secret_key, check_file, decode_image, mkdir, isExist, getFile, createFile
from api import detect_faces, compare_photos, extract_descriptor, get_landmarks, swap_face, swap_video
from flask ... |
# create tuples
coordinates = (4, 5)
print(coordinates[1])
coordinates2 = [(4, 5), (1, 2), (5, 7)]
print(coordinates2)
# can not change the value in tuples
coordinates[1] = 2
print(coordinates[1])
|
#!/usr/bin/env python3
#ensure the "mut_files" directory exists in the working directory.
import pysam
import vcf
import sys
import argparse
import pybedtools
from pybedtools import BedTool
def load_muts():
sample_files = ["mut_files/mut_M" + str(k) + ".txt" for k in range(1,9)] #get every file
muts = []
f... |
from datetime import date
import boundaries
boundaries.register('Guelph wards',
domain='Guelph, ON',
last_updated=date(2012, 5, 15),
name_func=lambda f: 'Ward %s' % f.get('WARD'),
id_func=boundaries.attr('WARD'),
authority='City of Guelph',
encoding='iso-8859-1',
metadata={'geographic_code... |
import itertools
import string
import ast
import random
from beatriz import *
from mimi import *
#Parametros: [lista cromosoma, int n, arreglo 2D matrizA, arreglo 2D matrizB]
def calcularAptitud(cromosoma, n, matrizA, matrizB):
#Definicion del diccionario que usare para saber las posiciones de la permutacion
alfab... |
import sys
if len(sys.argv) > 1:
print ("Hello, " + sys.argv[1] + "!")
else:
print ("Hello World!") |
from machine import Pin,DAC,PWM
from time import sleep
buzzer = PWM(Pin(25))
i=0
while(1):
buzzer.freq(10)
sleep(0.5)
buzzer.deinit()
|
f = open('cars.info', 'w+')
fbg = open('bg.txt', 'w+')
for i in range(550):
f.write('pos/pos-' + str(i) + '.pgm 1 0 0 100 40\n')
for i in range(500):
fbg.write('neg/neg-' + str(i) + '.pgm\n')
for i in range(500, 512):
fbg.write('neg/neg-' + str(i) + '.pgm\n')
|
#!/usr/bin/env python3
##
## EPITECH PROJECT, 2020
## 107transfer_2019
## File description:
## unit_test
##
import unittest
import error
import function
class TestStringMethods(unittest.TestCase):
def setUp(self):
self.var = "USAGE\n" \
"\t./107transfer [num den]*\n" \
... |
from math import *
def in_p():
w = input("------Introduzca p: ")
return w
def in_q():
w = input("------Introduzca q: ")
return w
def in_s():
w = input("------Introduzca s: ")
return w
def in_it():
w = input("------Introduzca el numero de it: ")
return w
def in_x():
w = input... |
import machine, oled_ssd1306
from utime import sleep_ms
from menus import *
line_y = {1: 3, 2: 12, 3: 21, 4: 30, 5: 39, 6: 48, 7: 57}
cursor_pos = 1
b1 = machine.Pin(4, machine.Pin.IN, machine.Pin.PULL_UP)
b2 = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_UP)
options = ('1', '2', '3', '4', '5', '6', '7')... |
import os
import csv
# ======================================================================================================================
# Name:
# get_dictionaries()
# Purpose:
# Returns a list of strings that represent paths
# where files were found with file names with... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 21 13:34:17 2016
@author: JO21372
"""
from setuptools import setup, find_packages
setup(
name="pyslgr",
packages=['pyslgr'],
version="0.7.2",
description="Python tools for speech, language, and gender recognition (SLGR)",
author='Human Language Techno... |
archivo = open('doc.mp3', 'a')
contador = 1
while True:
contador = contador + 1
archivo.write(str(contador * contador))
archivo.close() |
# import dash_bootstrap_components as dbc
# import dash_html_components as html
# import dash
# import pandas as pd
# import dash_core_components as dcc
# from dash.dependencies import Input, Output
# import plotly.graph_objs as go
# import plotly.express as px
# from math import log10
import... |
from django.db import models
class Coupon(models.Model):
coupon_id = models.AutoField(primary_key=True)
coupon_name = models.CharField(max_length=60)
image = models.ImageField(db_column='image', upload_to="voucher/coupons/", null=True, blank=True)
discount = models.IntegerField()
created = models.... |
from copy import deepcopy
from functools import reduce
from itertools import starmap
from typing import List, Tuple, Iterable, Set
def read_block() -> str:
n = int(input())
text = str()
for _ in range(n):
line = input()
text += line
text = text.replace('\n', '')
text = text.replace... |
from django.test import Client
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User
from rest_framework import status
from rest_framework.test import APITestCase, APIClient
from rest_framework.authtoken.models import Token
from authentication.models import UserProfile
from... |
from rest_framework import filters, viewsets
from .models import Todo, TodoList
from .serializers import TodoSerializer, TodoListSerializer
class TodoViewSet(viewsets.ModelViewSet):
queryset = Todo.objects.all().order_by('-id')
serializer_class = TodoSerializer
filter_backends = (filters.SearchF... |
# -*- coding: utf-8 -*-
#廣義歐幾里德除法
#返回100,000內任意兩整數的最大公因數
def GCD(a=1, b=1):
if a < 0: a = -1 * a #將a轉為正整數進行計算
if b < 0: b = -1 * b #將b轉為正整數進行計算
if a < b: c = a; a = b; b = c #交換a與b的次序,使得a≥b
if b == 0: return a #(r,0) = r
r = a % b
return... |
import csv
import pandas as pd
from pandas import DataFrame
'''
전공과목 수정
'''
# column 이름은 ['학년']['전공']['교과코드-구분']['과목명']['학점']['담당교수']['시간']['강의실']로 설정
# []안의 이름 변경시 구분되는 col 이름 변경
# dataset은 csv파일 , 단위로 읽어서 저장되어 있습니다.
# .drop등 명령어로 특정부분 삭제 가능
f_major = open('computer.csv','r',encoding='utf-8') ... |
# Default arguments, variable-length arguments and scope
# In this chapter, you'll learn to write functions with default arguments so that the user doesn't always need to specify them, and variable-length arguments so they can pass an arbitrary number of arguments on to your functions. You'll also learn about the esse... |
"""Object to keep track of which widget class should be used for each BfObject or FbxObject
This can be subclassed for DCC implementations to add more custom widgets.
"""
import fbx
from brenfbx.core import bfCore
from brenpy.core import bpDebug
from brenfbx.qt import bfQtCore
# bf object imports
from brenfbx.fbxsdk... |
# Plotter that gets passed a series of moves in a csv file
# Written to be called from mods.cba.mit.edu
# After the "toMoves.js" module
# Nadya Peek 2016
#------IMPORTS-------
from pygestalt import nodes
from pygestalt import interfaces
from pygestalt import machines
from pygestalt import functions
from pygestalt.mach... |
import feedparser
from settings import get_config
from models import JobOffer
def parse_stackoverflow():
""" Parses the results of the stackoverflow remote jobs search into a list of JobOffer objects """
config = get_config()
url = config.get('rss').get('stackoverflow')
feed = feedparser.parse(url)
... |
from rest_framework.views import APIView
import logging
from rest_framework.response import Response
from user.models import *
from user.serializers import StudentSerializers, TeacherSerializers
from .login_token import *
from django.contrib.auth.hashers import check_password
from django.contrib.auth.hashers import mak... |
#!/usr/bin/env python
# Funtion:
# Filename:
# name = [1,2,3]
# try:
# day = 1
# except IndexError as e:
# print(e)
# except KeyError as e:
# print(e)
# except (IOError , ImportError) as e:
# print(e)
# except Exception as e:
# print(e)
# else:
# print("No Error")
# finally:
# print("... |
"""
@File: time_task.py
@CreateTime: 2020/1/6 上午11:05
@Desc: 定时任务schedule
"""
import schedule
import time
def one_job(message="stuff"):
print("I'm working on:", message)
def two_job(message='working'):
print("The Worker Status is:", message)
if __name__ == '__main__':
schedule.every(10).minutes.do(one... |
Gstart = int(input('Input start gauge '))
Gend = int(input('Input final gauge '))
Tm = Gstart - Gend
print('You loaded',Tm,'m3')
if (Tm > 0 and Tm <= 24 ):
print('This is small load')
elif (Tm < 0):
print('Start gauge cant be smaller than end gauge')
elif (Tm > 24 and Tm < 30):
print('This is big... |
import os
import pandas as pd
import seaborn as sns; sns.set_theme(color_codes=True)
file_name=os.path.join('folder_path','similarity_res.csv')
df=pd.read_csv(file_name,index_col='ligand') #
df=df.drop(columns=df.columns[df.isna().all()].tolist()) # removing columns with all na values
df=df.dropna() # removing rows wi... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 29 10:01:28 2017
@author: 29907
"""
#2048_game.py -- Auto play 2048 game
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
#Open 2048 game website
browser=webdriver.Opera()
browser.get('http://gabrielecirulli.github.io/2048/')
html_ele=bro... |
words = []
word = str(input("Enter string: "))
while word != "":
words.append(word)
word = str(input("Enter string: "))
repeats = []
for x in range(0, len(words), 1):
if words[x] in words[:x] and not repeats:
repeats.append(words[x])
if len(repeats)>0:
print("Strings repeated: ", "... |
ngram = 4
from keras.datasets import imdb
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers.embeddings import Embedding
from keras.preprocessing import sequence
from keras.callbacks import ModelCheckpoint
import json
import word_table a... |
import numpy as np
class epsilon(object):
def __init__(self, eps_start = 1.0, eps_decay = 0.999, eps_min = 0.0):
self.eps_start = eps_start
self.eps = self.eps_start
self.eps_decay = eps_decay
self.eps_min = eps_min
def update(self):
self.eps = max(self.eps*self... |
#!/usr/bin/env python3
import numpy as np
from glob import iglob
from collections import defaultdict
from functools import partial
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab
import pickle
#set up tex
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
#hatch
# plt.rcParams['hatch.linewid... |
from flask import *
from utiles import todict
empresa = Blueprint('empresa', __name__, url_prefix='/empresa', template_folder='empresa_templates')
@empresa.route('/')
def home():
return render_template('empresa.home.html')
@empresa.route('/api', methods=['GET', 'POST', 'DELETE'])
def api():
if request.met... |
class AbstractDataset():
def __init__(self, csvpath, config, batchsize, accbatchsize):
raise Exception("Abstract class used")
|
import sys
import os
import enum
import socket
import struct
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ("127.0.0.1", 69)
class TftpProcessor(object):
class TftpPacketType(enum.Enum):
RRQ = 1
WRQ = 2
DATA = 3
ACK = 4
E... |
from flask import request
from requirementmanager.app import app
from requirementmanager.mongodb import (
requirement_tree_collection
)
from requirementmanager.dao.requirement_tree import (
RequirementTreeMongoDBDao
)
from requirementmanager.utils.handle_api import handle_response, verify_request
from requirem... |
from flask import Flask
# from flask_appconfig import AppConfig
from flask_bootstrap import Bootstrap
from .session_setup import sess
from .frontend import frontend
from .nav import nav
from .model.base import db
def create_app(configfile=None):
app = Flask(__name__)
app.config['SECRET_KEY'] = 'toto-lea'
... |
import pymysql
import requests
from bs4 import BeautifulSoup
from abc import *
import crawling
class AppstoreGameCrawling(crawling.Crawling, ABC):
def __init__(self, main_url, db_host, db_port, db_user, db_pw, db_name, db_charset):
super().__init__(main_url, db_host, db_port, db_user, db_pw, db_name, db_... |
###
# Copyright (c) 2015, Michael Daniel Telatynski <postmaster@webdevguru.co.uk>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyr... |
class Solution:
def countElements(self, arr) -> int:
count = 0
for number in arr:
if(number + 1 in arr):
count += 1
return count |
class Character(object):
def __init__(self, type, name, bonus, condition):
self.type = type
self.name = name
self.bonus = bonus
self.condition = condition
def create(self):
pass |
""" Renders and handles defined forms, turning them into submissions. """
import morepath
from onegov.core.security import Public, Private
from onegov.org.cli import close_ticket
from onegov.ticket import TicketCollection
from onegov.form import (
FormCollection,
PendingFormSubmission,
CompleteFormSubmiss... |
from __future__ import division
from warnings import warn
import numpy as np
from scipy import special
from dipy.data import get_sphere
def density(points, Lambda):
"""Density function of the Angular Central Gaussian Distribution"""
q = Lambda.shape[0]
a_inv = special.gamma(q / 2.) / (2. * np.pi ** (q / ... |
# encoding: utf-8
"""
Helper module for example applications. Mimics ZeroMQ Guide's zhelpers.h.
"""
from __future__ import print_function
import binascii
import os
from random import randint
import zmq
IDENTITY_PREFIX = 'id\x00'
RAW_MSG_FLAG = '\x00\x00'
def socket_set_hwm(socket, hwm=-1):
"""libzmq 2/3/4 comp... |
import numpy as np
import copy
import pdb
import random as rdm
import time
import scipy.special as scp
import scipy.stats as scs
import scipy.optimize as scopt
import matplotlib.pyplot as plt
from scipy import optimize as scipyopt
import datetime
import utilities as utils
from loggedopt import Log
class InformationR... |
import socket
import json
import time
from termios import tcflush, TCIFLUSH
import sys
import Adafruit_BBIO.PWM as PWM
import Adafruit_BBIO.ADC as ADC
import Adafruit_BBIO.GPIO as GPIO
PWM.cleanup()
#set pins
frontright_pin = "P9_14" #PWM pin working
frontleft_pin = "P9_21" #PWM pin working
rearright_... |
from modulos.Hand import Hand
from modulos.Gamer import Gamer
from modulos.Deck import Deck
from modulos import Helpers
import os
class Table:
dealer: Hand
gamer: Gamer
split: Gamer
deck: Deck
screen = 60
bet_max = 300
second_card_is_hidden = True
split_active = False
dealer_active... |
import sys
from distutils import sysconfig
s = "using python : {version} : {prefix} : {inc} ;\n".format(
version=sysconfig.get_python_version(),
prefix=sysconfig.get_config_var("prefix"),
inc=sysconfig.get_python_inc())
sys.stdout.write(s)
|
#oef3
import math
def maximum(a,b,c):
if (a>b):
if (a>c):
print("{} is het grootste getal.".format(a))
else:
print("{} is het grootste getal.".format(c))
elif (b>c):
print("{} is het grootste getal.".format(b))
else:
print("{} is het grootste getal.".f... |
from flask import Flask, request
from MonsterGen import Monster, CR, random_trap, Npc, monster_loot, horde_loot
app = Flask(__name__)
@app.route('/monster')
def monster():
level = int(request.args['avg-level'])
players = int(request.args['num-players'])
difficulty = int(request.args['difficulty'])
re... |
from calendar import monthrange
from datetime import timedelta
from enum import IntEnum
class TimeFreq(IntEnum):
Hourly = 0
ThreeHourly = 1
Daily = 2
Monthly = 3
Yearly = 4
def time_freq_factory(name_or_abbr):
if name_or_abbr in ('HH', 'Hourly'):
return TimeFreq.Hourly
elif name_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 11May 14 20:17:23 2020
@author: bfemenia
"""
# %% IMPORT SECTION
#-------------------
import pandas as pd
from astropy import units as u
from astropy.coordinates import Angle, Distance, Latitude, Longitude, SkyCoord
from reducerTFM import DiasCat... |
# Generated by Django 2.0.3 on 2018-12-01 16:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('deckShare', '0004_auto_20181201_1653'),
]
operations = [
migrations.RemoveField(
model_name='profile',
name='awaitin... |
from django.db import models
from django.utils import timezone
from django.urls import reverse
from django.contrib.auth.models import User
from django.db.models import Sum, Case, When, IntegerField
from django.db.models.functions import TruncDay, TruncMonth, TruncYear
today = timezone.now()
class Profile(models.Model... |
class Space():
def __init__(self, location, id, type):
self.location=location
self.id=id
self.occupied=False
self.assigned_vehicle=None
self.space_type=type
def park(self, vehicle):
self.assigned_vehicle=vehicle
self.occupied=True
def unp... |
from utils import annihilate, read_input
if __name__ == '__main__':
print(len(annihilate(read_input())))
|
from botSession import kuma
from localDb import welcome_chat
from botInfo import creator
from threading import Timer
def welcome(update, context):
chat_id = update.message.chat_id
alert_id = update.message.message_id
new_member = update.message.new_chat_members[0]
bot_status = new_member.is_bot
if... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
"""
===========
Annotation extraction tool
Takes filename as argument.
Extracts the annotations in json format
and stores them into the same directory.
===========
"""
import os.path
import json
imp... |
import torch
from torch.nn import functional as F
def binary_clf_curve(
preds: torch.Tensor,
target: torch.Tensor,
sample_weights = None,
pos_label: int = 1.,
):
"""
adapted from https://github.com/scikit-learn/scikit-learn/blob/master/sklearn/metrics/_ranking.py
"""
if sample_weights ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
ref:
- PY2: https://docs.python.org/2/library/functions.html#hex
- PY3: https://docs.python.org/3/library/functions.html#hex
"""
assert hex(255) == "0xff"
assert hex(-42) == "-0x2a"
assert float.hex(3.14) == "0x1.91eb851eb851fp+1"
assert float.hex(-0.618) == "-0x1.3c... |
import arcade
import movement_2
import settings
SPRITE_SCALING = 0.25
SCREEN_HEIGHT = 880
SCREEN_WIDTH = 1080
MOVEMENT_SPEED = 10
class Ball:
def __init__(self, position_x, position_y, change_x, change_y, radius, color):
# Take the parameters of the init function above, and create instance variables out ... |
"""admin URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based v... |
class Person:
def __init__(self, firstname, lastname, age):
self.firstname = firstname
self.lastname = lastname
self.age = age
def display(self):
print("\n--- x --- X --- x ---")
print("First name: %s\nLast name: %s\nAge: %s" % self.firstname, self.lastname, self.age)
... |
__author__ = 'ejullap'
import re
from _datetime import datetime
class SpeedingDetector:
camera_logs = []
speed_limit = float()
camera_positions = []
speeding_cars = dict()
def parse_speed_log(self, log_name):
speed_log = open(log_name, 'r')
camera_logs = {}
f... |
from math import tanh, cosh
def f_and_fprime(x):
return tanh(x), (1./cosh(x))**2
#print f_and_fprime(2.)
#quit()
x=1.08
err = 10.**-15.
for i in range(10):
print i,x
f,fprime = f_and_fprime(x)
step = -f/fprime
x += step
if abs(f) > err: print False
else: print True
print x
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.