text stringlengths 8 6.05M |
|---|
MOD = 1000000009
def AlternateSum(n,a,b,k,s):
res = 0
inv = lambda x: pow(x, MOD-2, MOD)
q = pow(b, k, MOD) * inv(pow(a, k, MOD)) % MOD
max_pow = pow(a, n, MOD)
c = b * inv(a) % MOD
for i in range(k):
if s[i] == '+':
res += max_pow
else:
res -= max_pow
... |
from Container import Container
import Variables
from Variables import datasetVars
from Selection import Selection, filter_tree
import ROOT
from Utils import rgetattr
XcWmassE = '(({pmass}^2 + p_P^2)^.5 + ({kmass}^2 + K_P^2)^.5 + ({pimass}^2 + pi_P^2)^.5)'
XcWmass = '(' + XcWmassE + '^2 - X_c_P^2)^.5'
pimass = 139.570... |
f = open("kanji.txt", encoding="utf-8")
kanji_list = f.readline()
f.close()
f = open("era.txt", "wb")
for i in kanji_list:
for j in kanji_list:
print("{}{}".format(i, j))
f.write("{}{}".format(i, j).encode())
f.close()
|
#!/usr/bin/env python3
#
# Copyright (C) 2019 Tejun Heo <tj@kernel.org>
# Copyright (C) 2019 Andy Newell <newella@fb.com>
# Copyright (C) 2019 Facebook
desc = """
Generate linear IO cost model coefficients used by the blk-iocost
controller. If the target raw testdev is specified, destructive tests
are performed again... |
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.9.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Rallyview Charts
#
# Make a... |
from translationstring import TranslationStringFactory
_ = TranslationStringFactory('onegov.swissvotes')
|
# hero's inventory
# demonstrates tuple creation
# create an empty table
inventory = ()
# treat tuple as a condition
if not inventory:
print("you are emppty handed")
input("\nPress the enter key to continue, fill your inventory.")
# create a tuple with some items
inventory = ("sword","armor","shields","healing ... |
D, N = map( int, input().split())
T = [ int(input()) for _ in range(D)]
mM = []
C = []
for _ in range(N):
a, b, c = map( int, input().split())
mM.append([a,b])
C.append(c)
t = T[0]
Cminnow = 100
Cmaxnow = 0
dp = [ [ -1 for _ in range(N)] for _ in range(D)]
for i in range(N):
if mM[i][0] <= t and t <= mM... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import time
import cv2
import numpy as np
import math
def set_state3(pre_pointx, road_found, cross_num):
nonzero_count = 0
weight_total = [0, 0, 0,0]
x_total = [0, 0, 0,0]
x_final = [0, 0, 0,0]
for i in range(len(pre_pointx)):
if pre_pointx[i] != 0:... |
import random
from itertools import islice
import numpy as np
from louter.core.criteria import english_criteria
from louter.core.keyboard import ANSI
from louter.core.keycaps import generate_new_random_ansi_english
from louter.util.softmax import soft_random_generator
POOL_SIZE = 100
ITERATIONS = 40
MEAN_MUTATIONS =... |
from django.views.generic import View, UpdateView
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.urls import reverse_lazy
from .models import Address
from .forms import AddressForm
@method_decorator(login_... |
import random
from itertools import islice
from math import e
from functools import partial
import sys
import numpy as np
from louter.core.criteria import pauleikis_criteria
from louter.core.keyboard import Planck
from louter.core.keycaps import RandomKeyCaps, KeyCaps
from louter.util.softmax import soft_random_gener... |
school = [{'school_class':'4a', 'scores': [3,4,4,5,2]},
{'school_class':'4b', 'scores': [5,4,3,3,2]},
{'school_class':'4c', 'scores': [5,5,3,5,2]},
{'school_class':'4d', 'scores': [5,4,5,5,4]}
]
'''
average_class_score = []
for s in school:
average_score = sum(s['scores'])/len(s['scores'])
average_cl... |
class Character(object):
def __init__(self, size, sprite):
self.size = 2
self.sprite = 'image file'
def __repr__(self):
return 'Nerf is drunk and %s big and his image file is at %p' (self.size, self.sprite)
@property
def movement(self):
return 'run'
|
'''
Script to run drifters from river inputs forward for 4 months
'''
import matplotlib as mpl
mpl.use("Agg") # set matplotlib to use the backend that does not require a windowing system
import numpy as np
import os
import netCDF4 as netCDF
import pdb
import matplotlib.pyplot as plt
import tracpy
import init
from date... |
def abbreviate(palabra):
palabras = palabra.replace('_', ' ').replace('-', ' ')
vecPalabra = palabras.split()
acronimo = ''
for i in vecPalabra:
acronimo += i[0].upper()
return acronimo
|
#!/usr/bin/env python
"""
Stopwatch program that tracks elapsed time, creates laps
and returns output to clipboard
"""
import time
import pyperclip
def track_time():
print('Press ENTER to begin. Afterwards, press ENTER to start stopwatch.')
print('Press Ctrl-C to quit.')
input() ... |
s = input().split()
nums = []
for i in s:
nums.append(int(i))
cnt = 0
for i in range(1,len(nums)-1):
if nums[i] > nums[i-1] and nums[i] > nums[i+1]:
cnt += 1
print(cnt)
# print(s)
# print(nums)
|
# We use our own custom json implementation. In the libres library we made this
# configurable. Since onegov.core is a framework we don't do that though, we
# want all onegov.core applications with the same framework version to be able
# to read each others json.
#
# Therefore we use a common denominator kind of json e... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/6/30 15:23
# @Author : TheTAO
# @Site :
# @File : data_process.py.py
# @Software: PyCharm
import os
import re
def get_entities(dir):
# 实体字典
entities = {}
files_list = os.listdir(dir)
# 获取所有的文件名列表
files = list(set([file.split('.')[0] for... |
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import torch.optim as optim
from dataset import SST2 as Dataset
from model import RNN
import os
BATCH_SIZE = 128
INIT_LR = 1e-1
MOMENTUM = 0.9
L2_REG = 1e-5
class Learner():
def __init__(self, dataset_path, network):
# set device & build dataset
... |
# ----------------------------------------------------------------------------
# Copyright 2014 Nervana Systems 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.o... |
from URL_Lib import descargarResultadoData
from File_Lib import saveFile, saveFileExc, loadFile
import re
#
#
# ********************************** Programa principal **********************************
#
#
def descargarCategorias(codigo):
payload = "lang=E&codi="+codigo
headers = { 'content-type': "application/x-w... |
from onegov.page import Page
from onegov.form import FormDefinition
from onegov.reservation import Resource
class PersonMove:
""" Represents a single move of a linked person. """
def __init__(self, session, obj, subject, target, direction):
self.session = session
self.obj = obj
# rem... |
#-*- coding: utf-8 -*-
from random import randint
from math import e
from random import choice
LINEAR = 1
SIGMOIDE = 2
class Neuronio():
def __init__(self,seq,peso=randint(1,10),entrada=1):
self.peso=peso
self.seq = seq
self.entrada=entrada
def calcular(se... |
# XOR Crypto Programming Assignment
# Group 1 - Macedonians
import sys, os
# DEBUG activator
DEBUG = 1
def XOR():
# collect the text to be encoded/decoded and what key we will be using
# the input to be coded is given through stdin
input_text = sys.stdin.read().rstrip('\n')
# the key is from a file
try:
# ope... |
# -*- coding: utf-8 -*-
# @Author : 赵永健
# @Time : 2019/12/31 10:57
class baseProc(object):
def basePr(self, driver, list=[]):
for i in list:
self.switch(driver, i)
def switch(self, driver, num):
pass
|
import pandas as pd
import yfinance as yf
class Stock:
"""
Class to store stock data for each symbol, easier accesibility for post processing funcs and data
...
Attributes
-----
symbol: str
Stock symbol
name: str
Stock name
sentiment: pd.DataFrame
... |
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from landing.views import landing
urlpatterns = [
url(r'^', landing, name='landing'),
] |
#!/usr/bin/python
#
# This file is part of the AffBio package for clustering of
# biomolecular structures.
#
# Copyright (c) 2015-2016, by Arthur Zalevsky <aozalevsky@fbb.msu.ru>
#
# AffBio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by t... |
import time
import random
import math
import asyncio
import ewcfg
import ewutils
import ewitem
import ewrolemgr
import ewstats
import ewwep
from ew import EwUser
from ewitem import EwItem
from ewmarket import EwMarket
from ewplayer import EwPlayer
from ewdistrict import EwDistrict
from ewslimeoid import EwSlimeoid
fr... |
import math, itertools
balls = [0, 1, 2, 3, 4, 5, 6] * 10
#print(balls)
totalExpected = 0
for comb in itertools.combinations(balls, 20):
totalExpected += len(set(comb))
print(totalExpected/(math.factorial(70)//math.factorial(20)//math.factorial(50)))
|
import pygame, sys, random
from tkinter import *
from tkinter import messagebox
pygame.init()
clock = pygame.time.Clock()
screen_width = 520
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Sudoku Solver")
bg_color = pygame.Color('white')
black_color = p... |
import shelve
'''f=shelve.open('usernames.txt',writeback=True)
f['usernames']=[]
f.close()'''
def fun(x):
f=shelve.open('usernames.txt',writeback=True)
f['usernames'].append(x)
f.sync()
f.close()
def funsearch(username):
f=shelve.open('usernames.txt')
if username in f['usernames']:
ret... |
from rest_framework import permissions
class IsOwner(permissions.BasePermission):
"""
Only the owner can view and edit images
"""
def has_object_permission(self, request, view, obj):
"""
Check if the object owner is the same as the requester
"""
# Only allow the owner ... |
import tkinter as tk
def decide(*args):
if entry == "ego":
output.insert("Noun")
if entry == "docet":
output.insert("Verb")
root = tk.Tk()
root.Title = "Switch GUIs"
title = tk.Label()
title.config(bg = "#243c6a", fg = "#FFFFFF", text = "Input Word Below")
title.grid(row = 0)
entry = tk.Entry()
entry.config(... |
# -*- coding: utf-8 -*-
# See github page to report issues or to contribute:
# https://github.com/hssm/advanced-browser
# Built-in columns which are not sortable by default are made sortable here.
#
# Question/Answer columns are too slow so they are not handled.
# Note: the onData function of the columns is None as th... |
from onegov.core.converters import extended_date_converter
from onegov.core.converters import uuid_converter
from onegov.file.integration import get_file
from onegov.gazette import GazetteApp
from onegov.gazette.collections import CategoryCollection
from onegov.gazette.collections import GazetteNoticeCollection
from on... |
import requests
from bs4 import BeautifulSoup as BS
import json
# разобрав get-запросы сайта, нашел это чудо, джекпот!
URL = 'https://apigate.tui.ru/api/office/list?cityId=1&subwayId=&hoursFrom=&hoursTo=&serviceIds=all&toBeOpenOnHolidays=false'
HOST = 'https://www.tui.ru/'
HEADERS = {
'accept': 'text/html,applicat... |
from django.contrib.auth.models import User, Group
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import serializers
from rest_framework.authtoken.models import Token
from authentication.models import UserProfile
from Crypto.PublicKey import RSA
class UserSerializer(serializers.ModelSeria... |
class Arbol:
def __init__(self,raiz):
self.raiz = raiz
self.hijo1 = None
self.hijo2 = None
def Agregahijo1(self,padre,dato):
if self.raiz != padre:
if self.hijo1 !=None:
self.hijo1.Agregahijo1(padre,dato) ... |
import os,re,sys,math
from experiments import configs
from collections import OrderedDict
#from experiments import config_names
import glob
import pprint
import latency_stats as ls
import itertools
CONFIG_PARAMS = [
# "DEBUG_DISTR",
"CC_ALG",
"MODE",
"WORKLOAD",
"PRIORITY",
"TWOPL_LITE",
"IS... |
import os
import json
import numpy as np
import matplotlib.pyplot as plt
JSON_FILES = ['', '', '']
def subcategorybar(ax, X, vals, labels, colors, width=0.4):
import numpy as np
n = len(vals)
_X = np.arange(len(X))
for i in range(n):
ax.bar(_X - width/2. + i/float(n)*widt... |
import time
import requests
import json
import os
import argparse
import glob
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from dotenv import load_dotenv
load_dotenv()
host = os.getenv('API_HOST')
secret = os.getenv('API_SECRET')
class LogManifest(object):
def __ini... |
"""
Home page application db models.
"""
#from django.db import models
# Create your models here.
|
import math, time
def prime(n):
for d in range(2, math.floor(math.sqrt(n))+1):
if not n % d: return False
return True
def stmtTrue(a,n):
return a*(a-1) % n == 0
def M(n):
if prime(n): return 1 # This seems to be a very slight optimization
# Something is broken here!
#print(n)
for a ... |
# Generated by Django 3.0.7 on 2020-06-21 14:49
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0004_auto_20200619_1245'),
]
operations = [
migrations.AlterField(
model_name='card',
name='product_id',
... |
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name... |
#!/usr/bin/env python
# coding: utf-8
from pprint import pprint as p
from flask import Flask, jsonify, render_template, request, redirect, url_for, session
import json
app = Flask(__name__)
@app.route('/', methods=['GET','POST'])
def index():
return 'Hello world'
|
# encoding:utf-8
'''
Created on 2015-6-8
@author: jianfeizhang
'''
class Target:
def show(self):
print 'I am normal'
class Adaptee:
def specific_show(self):
print 'I am specific'
#class adapter
class Adapter(Target, Adaptee):
def show(self):
self.specific_show()
#object adapter
# class Adapter(Target): ... |
print( int( input())*2)
|
#!/usr/bin/env python3
# Copyright 2017 Google 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... |
import os
import time
import bcrypt
import socket
import sys
import tqdm
BCRYPT_PASSWORD = '@X1&u2#6Zjwsx&bl'
HASHCAT = 'hashcat'
FILES_PATH = './archivos'
DICCIONARIO_1 = FILES_PATH + '/diccionarios/diccionario_1.dict'
DICCIONARIO_2 = FILES_PATH + '/diccionarios/diccionario_2.dict'
FILE_1 = {'path': FILES_PATH + '/... |
import requests
TOKEN = '2619421814940190'
def get_thanos_info():
url = 'https://superheroapi.com/api/2619421814940190/search/thanos'
response = requests.get(url, timeout=5)
return response.json()
def get_hulk_info():
url = 'https://superheroapi.com/api/2619421814940190/search/hulk'
response = ... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import os, sys, math
#from itertools import izip
from sys_info import SysInfo
from file_managers import frames, parse_time
def printa_nonaffine_header(sys_info, out):
if out == None:
out = sys.stdout
out.write(sys_info.one_liner() + "\n")
def printa_nonaffin... |
#Grading system with try and except to validate
score = input('Enter score: ')
try :
iscore = float(score)
except :
iscore = -1
quit ()
if iscore >= 0.9 :
print('A')
elif iscore >= 0.8 :
print('B')
elif iscore >= 0.7 :
print('C')
elif iscore >= 0.6 :
print ('D')
elif iscore <... |
import argparse
from os import makedirs
from os.path import join, exists
from allennlp.commands.elmo import ElmoEmbedder
parser = argparse.ArgumentParser()
parser.add_argument('--data_dir', default='data/balanced',
help='Directory containing the dataset')
parser.add_argument('--elmo_params_dir',
help='Directory conta... |
from django.contrib.auth import authenticate
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User, Permission
from django.contrib import messages
from django.contrib.auth.views import LoginView, LogoutView
from dj... |
# -*- coding: utf-8 -*-
import argparse
import json
import sqlite3
import sys
DB_SCHEMA = """
PRAGMA foreign_keys = 1;
CREATE TABLE domains (
id INTEGER PRIMARY KEY,
name VARCHAR(255) NOT NULL COLLATE NOCASE,
master VARCHAR(128) DEFAULT NULL,
last_check ... |
def get_cronjob_by_name(app, name):
for cronjob in app.config.cronjob_registry.cronjobs.values():
if name in cronjob.name:
return cronjob
def get_cronjob_url(cronjob):
return '/cronjobs/{}'.format(cronjob.id)
def edit_bar_links(page, attrib=None):
links = page.pyquery('.edit-bar a')
... |
'''
A googol (10^100) is a massive number: one followed by one-hundred zeros;
100^100 is almost unimaginably large: one followed by two-hundred zeros.
Despite their size, the sum of the digits in each number is only 1.
Considering natural numbers of the form, a^b, where a, b < 100, what is the maximum digital sum?
'... |
# Generated by Django 3.0.3 on 2020-02-15 11:57
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Billet',
fields=[
('id', models.AutoField(a... |
# Bagging and Random Forests
# Bagging is an ensemble method involving training the same algorithm many times using different subsets sampled from the training data. In this chapter, you'll understand how bagging can be used to create a tree ensemble. You'll also learn how the random forests algorithm can lead to furth... |
import os, tarfile
import numpy as np
import healpy as hp
import qcinv
import simcache
basedir = os.environ.get('SIMCACHE_DATA', os.path.dirname(simcache.__file__)) + "/wmap/"
def y2r(year):
return {7 : 4, 9 : 5}[year]
def n2r(nside):
return {512 : 9}[nside]
#
wmap_das = ['K1', 'Ka1', 'Q1', 'Q2', 'V1'... |
# -*- coding: utf-8 -*-
# ! /usr/bin/env python
"""
@author:LiWei
@license:LiWei
@contact:877129310@qq.com
@version:V1.0
@var:加载数据库配置信息
@note:加载数据库爬虫配置信息等
"""
import MySQLdb
import MySQLdb.cursors
import logging
import platform
import sys
import json
reload(sys)
if platform.system().lower() in "windows":
sys.se... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
'''
It was proposed by Christian Goldbach that every odd composite number
can be written as the sum of a prime and twice a square.
9 = 7 + 2×12
15 = 7 + 2×22
21 = 3 + 2×32
25 = 7 + 2×32
27 = 19 + 2×22
33 = 31 + 2×12
It turns out that the conjecture was false.
What is the sma... |
# Paul Glenn
# MTH 437 Numerical Analysis
# Homework 9
# Differentiation arithmetic/ Automatic Differentiation
import math
class valnder:
def __init__(self, val = 0.0, der = 0.0 ): #Constructor
self.val = val
self.der = der
def __add__( self, g): #Addition
return valnder( self.val + g... |
#!/bin/python3
s = ''
memory = []
for n in range(int(input().strip())):
query = [x for x in input().strip().split(' ')]
if int(query[0]) == 1:
memory.append(s)
s += query[1]
elif int(query[0]) == 2:
memory.append(s)
s = s[:-int(query[1])]
elif int(query[0]) == 3:
... |
import sys
import os, re
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense, Lambda, Layer, Activation
from tensorflow.keras.layers import Dropout, BatchNormalization
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.losses import... |
a = int(input())
b = int(input())
c = int(input())
mx = 0
mn = 0
if a >= b and a >= c:
mx = a
elif b >= a and b >= c:
mx = b
else:
mx = c
if a <= b and a <= c:
mn = a
elif b <= a and b <= c:
mn = b
else:
mn = c
print(mx - mn) |
# kullanıcı adı şifre uyumu
kullanıcıadım = "beyzi"
kullanıcışifrem = "123456789"
KA = input("kullanıcı adı:")
KS = input("kullanıcı şifresi:")
if(kullanıcıadım == KA and kullanıcışifrem != KS):
print("kullanıcı adınız doğru fakat şifreniz yanlış")
elif(kullanıcıadım != KA and kullanıcışifrem == KS):
pri... |
""" aux.py -- companion functions to the main utility """
from .errors import *
from .connection import *
import datetime
import time
import json
import math
def get_baseline(granularity):
""" Returns the baseline for a given granularity """
bls = {'MINUTE': 3600,\
'EIGHT_MINUTE': 3600,\
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import numpy as np
class Individual:
def __init__(self):
self.rank = 0
self.crowding_distance = None
self.dominated_solutions = []
self.domination_count = 0
self.adj = None
self.model_parameter = None
self.compress... |
# A palindromic number reads the same both ways.
# The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
# Find the largest palindrome made from the product of two 3-digit numbers.
import time
t = time.time()
palindrome_appendix = []
def is_palindrome(num):
num = str(num)
r... |
names = ['panda', 'tiger', 'bear']
message = 'Welcome '
names.insert(0, 'cattle')
names.insert(2, 'sheep')
names.append('pig')
print(message + names[0])
print(message + names[1])
print(message + names[2])
print(message + names[3])
print(message + names[4])
print(message + names[5]) |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 2 19:12:53 2019
@author: gustavo.fonseca
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Tarefa 13
'''Nesta tarefa, criaremos um histograma do público para um time específico do
Campeonato Brasileiro de Futebol de 2018, basea... |
num_ant = 0
num = 1
print(num_ant, num)
cont = 1
while cont <= 18:
prox = num_ant + num
num_ant = num
num = prox
print(prox)
cont = cont + 1 |
from django.shortcuts import render
from .models import (
Utilisateur
)
#from rest_framework import viewsets
from .models import *
#from .serializers import *
from .forms import(
Form_ajout_utilisateur
)
# Create your views here.
formulaire = Form_ajout_utilisateur(None)
def addUti(requete):
context... |
#!/usr/bin/python
# -*- coding: utf-8 -*
class Fish():
def __init__(self, name, location):
self.name = name
self.location = location
def jump(self):
print ' 来自 %s 的鱼 %s 开始跳起来了 ' %(self.location, self.name)
class Rabit():
def __init__(self, name,location):
self.name = name
self.location=loc... |
'''
2.
첫 번째 숫자를 두 번째 숫자부터 마지막 숫자까지 차례대로 비교하여
가장 작은 값을 찾아 첫 번째에 놓고, 두번째 숫자를 세 번째 숫자부터
마지막 숫자까지 차례대로 비교하여그 중 가장 작은 값을 찾아
두 번째 위치에 놓는 과정을 반복하며 정렬하는것을 선택정렬이라고 합니다.
주어진 리스트를 선택정렬함수(select_sort)를 생성하여 오름차순으로 정렬하시오
list=[6,2,3,7,8,10,21,1]
<입력>
print(select_sort(list))
<출력>
[1, 2, 3, 6, 7, 8, 10, 21]
'''
def select_sort... |
with open("hightemp.txt") as f:
lines = f.readlines()
print(len(lines))
|
import sys
import argparse
import fileinput
import config
import data
import transformer
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.data
class Config(dict):
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
def exec_model(config, vocab_enc, vocab_dec... |
#code
t = int(input())
for _ in range(t):
s = input()
flag = False
for i in range(len(s)):
for j in range(i+1,len(s)):
if s[i]==s[j]:
print(s[i])
flag = True
break
if flag:
break
if not flag:
print(-1) |
import os
from os import scandir
import torch
import torch.nn as nn
import nibabel as nib
import numpy as np
from PIL import Image
from torchvision.transforms import transforms
from mypath import Path
from torch.utils.data.sampler import SubsetRandomSampler
import random
NANNOTATOR = {
'brain-tu... |
import my_module
print(my_module.random_rsp())
import datetime
now = datetime.datetime.now()
print(now) |
from sqlalchemy.orm import Session
from typing import List
from db import models, schemas
def get_organization_by_id(db: Session, org_id: int) -> schemas.Organization:
return db.query(models.Organization).filter_by(id=org_id).first()
def get_organization_by_name(db: Session, name: str) -> schemas.Organization... |
#Turtle Draw
# By Jaylen Johnson
#Credit to Prof. Pogue & Dr. Klump
import turtle
import math
Answer = input('Please Enter, turtle-draw.txt, to begin program.\n ')
TEXTFILENAME = 'turtle-draw.txt'
turtleBoarder = turtle.Screen()
turtleBoarder.setup(450, 450)
print('TurtleDraw')
TEXTCODE = Answer
turtleDraw = ... |
import numpy as np
import tabulate
from pyrealm.param_classes import HygroParams
from pyrealm.bounds_checker import bounds_checker
# from pandas.core.series import Series
"""
This module provides utility functions shared by modules or providing
extra functions such as conversions for common forcing variable inputs,
s... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
import json
class SpidersPipeline:
def process_item(self, item, spider):
return item
class DoubanMovieTop250Pi... |
# -*- coding: utf-8 -*-
from django.shortcuts import render
from category.models import Category,Subcategory
from products.models import Product
def category(request):
query = Subcategory.objects.all().values('id','name','slug')
context = {'data':query}
return context
def about(request):
context... |
# vim:fileencoding=utf-8:noet
from __future__ import (unicode_literals, division, absolute_import, print_function)
import ctypes
from collections import namedtuple
from powerline.lib.unicode import unicode, unichr, tointiter
Dimensions = namedtuple('Dimensions', ('rows', 'cols'))
class CTypesFunction(object):
d... |
from pwn import *
pchar = ''
r = remote("ecb.utctf.live", 9003)
flag = ''
def init_pchar():
global pchar
for i in range(26):
pchar += chr(ord('a') + i)
for i in range(10):
pchar += chr(ord('0') + i)
pchar += '_'
pchar += '{}'
for i in range(26):
pchar += chr(ord('A') + i)
pchar += '\0'
def bf():
global... |
N = int(input('Enter a number to create a pattern: '))
for i in range(1, N + 1):
print('*'*i)
for i in range(N, 0, -1):
print('*'*i)
|
#!/usr/bin/env python3
from distutils.version import LooseVersion, StrictVersion
import sys, os, subprocess
NEW_NAUTILUS_VERSION = LooseVersion('3.10')
NEWEST_NAUTILUS_VERSION = LooseVersion('3.32')
def get_nautilus_version():
output = subprocess.run(['nautilus', '--version'], stdout=subprocess.PIPE, check=False... |
import os
import pygame
import kezmenu
from main import Game
class Team(object):
running = True
def main(self, screen):
clock = pygame.time.Clock()
background = pygame.image.load(os.path.join('img', 'background.png'))
teammate = pygame.image.load(os.path.join('img', 'teammate1.png')... |
# -*- coding: utf-8 -*-
"""The entry point for mtriage.
Orchestrates selectors and analysers via CLI parameters.
Modules:
Each module corresponds to a web platform API, or some equivalent method
of programmatic retrieval.
TODO: document where to find selector and analyser design docs.
Attributes:
mod... |
from gopigo import *
for x in range (5):
stop()
disable_servo() |
foods = ('pizza', 'meat', 'beef', 'vegetable', 'rice')
for food in foods:
print(food)
# Python禁止如此修改元组
# foods[0] = 'noodles'
print()
foods = ('pizza', 'milk', 'beef', 'vegetable', 'cookie')
for food in foods:
print(food) |
import runStatus
runStatus.preloadDicts = False
# import Levenshtein as lv
import markdown
import logging
import settings
import abc
import threading
import urllib.parse
import functools
import operator as opclass
import sql
# import sql.operators as sqlo
import hashlib
import psycopg2
import os
import tracebac... |
import pygame
from random import choice
class AbstractParticle:
def __init__(self, x, y):
self.cords = {
'x': x,
'y': y
}
self.beforeDestroy = 60 # frames
class Bubble(AbstractParticle):
def __init__(self, radius, x, y):
super().__init_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.