text stringlengths 8 6.05M |
|---|
import numpy as np
import utils.audio_dataset_generator
import settings
import model_handler_lstm
import tensorflow as tf
import tflearn
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import audio_handler
import librosa
from dataset_handler import Dataset
class TrainingMonitorCallback(tflearn.cal... |
# Generated by Django 3.0.7 on 2020-07-24 22:34
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),
('Inventario', '0004_auto_... |
"""
Contains code for unittesting of the Questions class.
"""
import unittest
from questions import Question
class QuestionTest(unittest.TestCase):
"""
Tests the Question class.
"""
def test_create_question(self):
"""
Test to create a new question and answer.
"""
quest ... |
from .lexer import VueLexer # noqa
__all__ = ['VueLexer']
|
import pandas as pd
from sklearn import svm, metrics
# nand 연산 아닌게 하나라도 있으면 1
xor_input = [
[0,0,0,0,1],
[0,1,1,0,1],
[0,1,0,0,1],
[1,0,0,0,1],
[1,1,0,0,1],
[1,0,1,0,1],
[1,1,1,0,1],
[0,0,0,1,1],
[0,1,1,1,1],
[0,1,0,1,1],
[1,0,0,1,1],
[1,1,0,1,1],
[1,0,1,1,1],
[1,... |
from model import AliasMapping
# return map from alias -> Player
# We choose the Player whose alias matches, or if none match exactly,
# the player with the shortest name
def get_top_suggestion_for_aliases(dao, aliases):
suggestions_map = get_player_or_suggestions_from_player_aliases(
dao, aliases)
r... |
from gtnlplib.tagger_base import apply_tagger
def kaggle_output(testfile, tagger_func, features, weights, all_tags, output_file):
tagger = lambda words, all_tags : tagger_func(words, features, weights, all_tags)[0]
apply_tagger(tagger, output_file, testfile=testfile, all_tags=all_tags, kaggle=True)
|
#_*_utf-8_*_
import simpleguitk as simplegui
'''
message = "Welcome"
def click():
global message
message = "Good job!"
def draw(canvas):
canvas.draw_text(message, (50,112), 36, "Red")
frame = simplegui.create_frame("Home", 300, 200)
frame.add_button("Click me", click)
frame.set_draw_handler(draw)
frame.start(... |
#!/usr/bin/python
import sys
import subprocess
import pipes
argv = sys.argv[1:]
quoted = [pipes.quote(arg) for arg in argv]
quoted.insert(0,"/home/eb4890/sparkles/sparkles.py")
#argv.insert(len(argv), "&")
#print argv
subprocess.Popen(" ".join(quoted) + "&", shell=True)
|
#!/usr/bin/env python
import aiohttp
import asyncio
import json
import logging
import pandas as pd
import time
from typing import (
Any,
AsyncIterable,
Dict,
List,
Optional,
)
from decimal import Decimal
import requests
import cachetools.func
import websockets
from websockets.exceptions import Con... |
'''
Created on 03.10.2018
@author: FM
'''
import unittest
import unittest.mock as mock
import CLI
from CLI import determine_and_perform_action, TerminateProgram
from test.testing_tools import mock_assert_msg
from FileSet import FileSet
mock_add = mock.MagicMock(name='add')
mock_remove = mock.MagicMock(... |
import pickle
f = open('/run/media/rvolpi/data/renvision_data/P38_06_03_14_ret1/experiments/t0_modSmall_single_pca_cond/crbm_tmp.pkl')
data = pickle.load(f)
print data
|
"""
User queries
"""
from typing import Generator, List, Optional, Union
import warnings
from typeguard import typechecked
from ...helpers import Compatible, format_result, fragment_builder
from .queries import gql_users, GQL_USERS_COUNT
from ...types import User
from ...utils import row_generator_from_paginated_ca... |
import scrapy
class DucanhSpider(scrapy.Spider):
name = 'ducanh'
allowed_domains = ['https://www.thegioididong.com/dtdd']
start_urls = ['https://www.thegioididong.com/dtdd/']
def parse(self, response):
name = response.css('.listproduct h3::text').extract()
price = response.css('.listp... |
#!/usr/bin/env python3
from .greet import *
|
#!/usr/bin/python
# TypeDungeon by Andrew Barry
# script for feeding text to type to the game client
import cgi, cgitb
import textwrap
import random
import time
cgitb.enable()
text_files = ['frankenstein.txt', 'alice.txt', 'ulysses.txt', 'modest.txt', 'traps.txt', 'wood.txt', 'scarlet.txt', 'spacedoor.txt', 'bulgar... |
from django.urls import path
from catalogo import views
urlpatterns = [
path('', views.index, name='index'),
path('fontes/', views.ListaFontes.as_view(), name='fontes'),
path('papeis/', views.papeis, name='papeis'),
#path('papeis/', views.CreatePapel.as_view(), name='papeis'),
# path('papel/<int:p... |
import urllib.request
from bs4 import BeautifulSoup
import datetime
import newspaper
import json
import os.path
import os
import io
import langdetect
import time
import articleDateExtractor
### Download functions
def Achriv_data_Download(URL_List, Date_List, site = 'Handelsblatt',
URL_Filter =... |
import uuid
from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
def jwt_get_secret_key(user_model):
return user_model.jwt_secret
class UserManager(BaseUserManager):
def create_user(self, email, first... |
class Solution:
def beg(self, cap, N, wt, val):
dp = [[0 for j in range(cap + 1)] for i in range(N+1)]
# 在第i个包处,包总容量w个容量情况下可以装的最多的价值
for i in range(1, N+1):
for j in range(1, cap+1):
if j >= wt[i-1]:
dp[i][j] = max(dp[i-1][j], val[i-1] + dp[i-1... |
class A:
classvar1="a is student studing in class A"
def __init__(self):
self.var1="i am in class A"
self.subjects="we have sankrit optional"
self.team="cricket"
class B(A):
classvar1 = "b is students studing in class B"
def __init__(self):
self.var1 = "i am in class B"
... |
from django.db import models
from django.utils import timezone
class ClubTeam(models.Model):
author = models.ForeignKey('auth.User')
name = models.CharField(max_length=100)
location = models.CharField(max_length=100, null=True)
created_date = models.DateTimeField(default=timezone.now)
def __str__(self):
retur... |
#!/usr/bin/python
#\file regression1b.py
#\brief Chainer example: train a multi-layer perceptron on diabetes dataset
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Aug.04, 2015
"""
src: https://gist.github.com/mottodora/a9c46754cf555a68edb7
"""
#Float version of range
def FRange1(x1,x2,nu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File : CBOW.py
# @Author: harry
# @Date : 18-8-1 下午10:52
# @Desc : Yet another CBOW Model written in pytorch
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import numpy as np
CONTEXT_SIZE = 2 # 2 words to th... |
#!/usr/bin/env
############################################
# exercise_12.py
# Author: Paul Yang
# Date: June, 2016
# Brief:
############################################
############################################
# time_each([])
# time each element in the list
# inputs: a list that contains number only
# return... |
#!/usr/bin/env python
"""Script introducing basic 'for' loops in Python"""
__author__ = 'Saul Moore (sm5911@imperial.ac.uk)'
__version__ = '0.0.1'
# for loops in Python
for i in range(5): # For input variable 0-4
print i
my_list = [0, 2, "geronimo!", 3.0, True, False] # [int, int, str, float, bool, bool]
for k in ... |
#!/usr/bin/python
## -*- coding: utf-8 -*-
#
import json
import cgi
import sys
import sqlite3
import percentile
qform = cgi.FieldStorage()
inparam = "MEIS2" #CTD-3080P12.3" #MEIS1"#
inparam = qform.getvalue('inparameter')
session = percentile.loaddict("./_all_session_genestain.dict")[inparam]
conn = sqlite3.connect('... |
from init_env import init_environment
sources = Split("""
textProgressBar.cc
""")
env = init_environment("")
lib = env.Library(source = sources, target = "../lib/textProgressBar")
|
from django.db import models
class Users(models.Model):
username = models.CharField(max_length=32)
password = models.CharField(max_length=128)
active = models.BooleanField()
ctime = models.DateTimeField(auto_now_add=True)
mtime = models.DateTimeField(auto_now=True)
email = models.EmailField(max... |
import pandas as pd
import json
import sys
from casos import casos_positivos, casos_fallecidos
poblacion_tumbes = 256423
positivos_tumbes = list(casos_positivos[casos_positivos['DEPARTAMENTO'] == "TUMBES"].shape)[0]
positivos_hombres_tumbes = list(casos_positivos[(casos_positivos['DEPARTAMENTO'] == "TUMBES") &(casos_... |
class Solution(object):
def canCompleteCircuit(self, gas, cost):
n = len(gas)
start, total, tank = 0, 0, 0
for i in xrange(n):
tank += gas[i] - cost[i]
if tank < 0:
start = i+1
total += tank
tank = 0
if total + t... |
with open("hightemp.txt") as f:
lines = f.readlines()
d = {}
for idx, l in enumerate(lines):
l = l.split("\t")
key = l[0]
if key in d:
d[key] += 1
else:
d[key] = 1
for k, v in sorted(d.items(), key=lambda x: x[1])[::-1]:
print(k, v)
# cut... |
""" Compatibility support for Python 2 and 3 """
import sys
PY2 = sys.version_info[0] == 2
if PY2:
text_type = unicode
from StringIO import StringIO
else:
text_type = str
from io import StringIO
|
import csv
import shutil
import os
import split_folders
def sort_images():
target_path = 'data/image_sort'
original_path = 'data/Image_ori'
with open('data/csv_convert1.csv', "rt") as csv_file:
reader = csv.reader(csv_file)
next(reader) # loop over first line
print(reader)
... |
# Generated by Django 2.1.7 on 2019-08-18 18:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('frame', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='framemodel',
name='imagetype',
... |
class Area:
objects = []
name = "DEFAULT AREA"
light = 1
smell_description = ""
noise_description = ""
temperature = 0
|
from tkinter import*
root = Tk()
root.title("Restaurant Management System")
root.geometry("1350x750")
root.configure(bg= "powder blue")
Title_frame = Frame(root,bd=20,bg="powder blue",relief= RIDGE,pady=5)
Title_frame.pack(side=TOP)
Title = Label(Title_frame ,text = "Restaurant Management System",font=("aerial",... |
# -----------------------------------------------------------------------------
# Copyright (c) 2014--, The Qiita Development Team.
#
# Distributed under the terms of the BSD 3-clause License.
#
# The full license is in the file LICENSE, distributed with this software.
# ------------------------------------------------... |
from tkinter import *
import sqlite3
from tkinter import messagebox
con=sqlite3.connect('database.db')
cur=con.cursor()
class UPdatePerson(Toplevel):
def __init__(self,person_id):
Toplevel.__init__(self)
self.person_id=person_id
self.geometry("650x550+500+120")
self.title("... |
#!/usr/bin/env python
from Constants import *
import pygame
class Length(object):
def __init__(self, up, down, left, right, speed):
self.up = up
self.down = down
self.left = left
self.right = right
self.speed = speed
def setLength(self, up, down, left, right, speed):
self.up = up
self.down = down
s... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import pickle
from PRW import ProjectedRobustWasserstein
from Optimization.RiemannianBCD import RiemannianBlockCoordinateDescent
from Optimization.RiemannianGAS import RiemannianGradientAscentSinkhorn
def T(x,d,dim=2):... |
from django.db import models
from django.utils.translation import ugettext as _
from django.utils.encoding import python_2_unicode_compatible
from extuser.models import ExtUser
from helpers.model_fields import IntegerRangeField
@python_2_unicode_compatible
class Skill(models.Model):
skill_type = models.CharField(... |
from numbers import Integral
def fib(n):
"""Return the n-th Fibonacci number."""
if n == 0:
return 0
elif n == 1:
return 1
else:
return fib(n-2) + fib(n-1)
def typesafe_fib(n):
"""Return the n-th Fibonacci number, raising an exception if a
non-integer is passed as n."... |
import random, GUI, Node, pygame, numpy, time
class Player:
def __init__(self, name_in):
self.name = name_in
self.at_node = 1
def move_player(self, node_in): #move the player
self.at_node = node_in #add options to move later also allow back or forward movement
class Board:
def __ini... |
import sys
from gui import GUI
from PyQt5.QtWidgets import QApplication
from breadth import BreadthSearch
from map import Map
from enemy import Enemy
from tower import Tower
from projectile import Projectile
from custombutton import CustomButton
from square import Square
from wave import Wave
from PyQt5.QtGu... |
#!/usr/bin/env python
#
# generate a Draine dust grain size distribution
# from Weingartner & Draine (2001)
#
# Started: Jul 2016 (KDG)
from scipy.special import erf
import numpy as np
def WGsizedist_graphite(a, bC_input, Cg, a_tg, a_cg, alpha_g, beta_g):
# a in Angstrom and assumed to always be > 3.5 A
#... |
class Solution:
def isToeplitzMatrix(self, matrix):
M, N = len(matrix[0]), len(matrix)
if M == 1 or N == 1:
return True
for i in range(M):
for j in range(min(N, M - i)):
if j == 0:
tmp = matrix[j][i + j]
els... |
# 装饰器:本质就是函数,为其他函数添加附加功能
# 原则:1 不修改被修饰函数的源代码,
# 2 不修改被修饰函数的调用方式
# 装饰器 = 高阶函数 + 函数嵌套 + 闭包
# 高阶函数:函数接受的参数是一个函数名,函数的返回值是一个函数值,满足其中任意一个条件即为高阶函数
import time
# def foo():
# print("来自foo")
# 高阶函数
# def test(func):
# print(func)
# return func
# # func()
# foo = test(foo)
# foo()
# 不修改foo 源代码,不修改foo调用方式
#... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 25 07:41:27 2017
@author: 29907
"""
#lucky.py - Open several google search results.
import sys,requests,webbrowser,bs4
if len(sys.argv)<2: #判断输入是否正确
print('Input error')
print('Gooling') #在下载goole页面时显示文本
res=requests.get... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('doctor', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='bookingstatus',
name=... |
from time import sleep
from github import Github
from consts import GITHUB_API_KEY
class ProjectsFinder:
def __init__(self):
self.should_run = False
def start(self):
self.should_run = True
while self.should_run:
self._run()
def stop(self):
self.should_run =... |
#dangdang
#coding:utf8
from bs4 import BeautifulSoup
import re
import urllib
from urllib.request import urlopen
from urllib.error import HTTPError
from distutils.filelist import findall
import pymysql
from text9.dbcon import *
import sys
import re
import decimal
import time
j = 0
class dangdang():
def __init__(se... |
'''
Extract Map Predictions.
Extract values from a raster corresponding to X,Y coordinates from input CSV.
INPUTS (command line):
-inputPath [CSV with X,Y columns]
-predictionMap [path to raster of predictions]
-outputPath
OUTPUT:
-new CSV with 'MAP_PREDICTION' column added
EXAMPLE:
python exractMapPred... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'database_UI.ui'
#
# Created by: PyQt5 UI code generator 5.7
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import db_manager, sys, network, key_actor_UI, key_term_U... |
"""
注释为程序中必不可少的一个组成部分
注释为程序的灵魂
没有注释的程序不是一个好的程序
没有注释相当于程序没有灵魂
"""
'''
注释虽然与程序运行无关,但是注释和程序的维护和结构有关
在大型项目中会经常出现注释 其主要用于解释模块的功能以及应用的位置 以及用于测试的代码会被注释掉
'''
# 在python中我们可以用以下三种方式来对我们的程序进行注释
# 1.# 单行注释
# 2.'''_____'''多行注释
# 3."""——————""" 多行注释 常用于大型的项目中
|
DEBUG=True
PORT=5000
HOST="0.0.0.0"
|
CATE_ID = '1'
classes_dict = {'1': 'visible body', '2': 'full body', '3': 'head', '4': 'vehicle'}
json_pre_dict = {'1': 'person_visible', '2': 'person_full', '3': 'person_head', '4':'vehicle'}
data_root = '/lustre/home/acct-eedxw/eedxw-user3/tianchi_PANDA/PANDA-Toolkit/PANDA_COCO_TYPE_DATA/split_' + json_pre_dict[CAT... |
# This file is only intended for development purposes
from kubeflow.kubeflow.ci import base_runner
base_runner.main(component_name="common_ui_tests",
workflow_name="common-ui-tests")
|
import socket, subprocess, re
import smtplib
def get_ipv4_address():
"""
Returns IP address(es) of current machine.
:return:
"""
fromaddr = 'FROM@gmail.com'
toaddrs = 'TO@gmail.com'
p = subprocess.Popen(["ifconfig"], stdout=subprocess.PIPE)
ifc_resp = p.communicate()
patt = re.compi... |
#cria um dicionario
#cada chave possui em valores 1 ou mais elementos
#depois imprimi chaves e valores
lugares_favoritos = {
'alan' : ['copacabana','fernando noronha'],
'lucas' : ['rio grande do norte'],
'monica': ['rio de janeiro','porto seguro','ilha bela'],
}
for name, lugares in lugares_favoritos.i... |
#!/usr/bin/python
#\file var_arg2.py
#\brief certain python script
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Jun.28, 2018
def Run(ct,*args):
print 'type of args:', type(args)
print 'length of args:', len(args)
print 'content of args:', args
ct= None
Run(ct, 'aaa')
Run(ct, 1, 2.... |
import socket,select
import struct,binascii,hashlib
import time,os,sys,platform
from collections import deque
import random
timeoutTime = 0.55
fileSize = 4719551306
serverIp = ['155.138.174.74',]
baseNum = 20000
portNum = 20700
bigNum = 21000
packSize = 1400
salt = b'salt'
gotNumThr = 100
selIpLen = ... |
from django.urls import path
from .views import loginUser, index, crearMascota, borrarMascota,calendario
from .views import crearPropietario, borrarPropietario, verMascota
from .views import expediente, expediente_mascota, crearCita, borrarCita, pagoServicio, borrarPago
from .views import producto, borrarProducto, pago... |
from rv.modules import Behavior as B
from rv.modules import Module
from rv.modules.base.flanger import BaseFlanger
class Flanger(BaseFlanger, Module):
behaviors = {B.receives_audio, B.sends_audio}
|
def jaccard_similarity(src, sink, following_dict, followers_dict):
src_neighbor_set = set(following_dict[src]) | set(followers_dict[src])
sink_neighbor_set = set(following_dict[sink]) if sink in following_dict else set() | set(followers_dict[sink])
intersection = src_neighbor_set & sink_neighbor_set
u... |
def fib(n):
a = 0
b = 1
if n == 0:
return a
elif n == 1:
return b
else:
for i in range(2,n):
c = a + b
a = b
b = c
return b
def productFib(prod):
for i in range(0,prod+2):
if fib(i)*fib(i+1)>=prod:
... |
from compimpl.compos import generateId
PATTERN = """//Start:Declarations
int branch_%ID%(%ARGS%);
//Stop:Declarations
//Start:Definitions
int branch_%ID%(%ARGS%) {
if(%PRED%(%AR%)) return %YES%(%AR%);
else return %NO%(%AR%);
}
//Stop:Definitions
"""
def generate(*args):
identification = generateId()
... |
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Users)
admin.site.register(Products_photos)
admin.site.register(Products)
admin.site.register(Messages)
admin.site.register(Basket)
|
# Definition for a undirected graph node
class UndirectedGraphNode:
def __init__(self, x):
self.label = x
self.neighbors = []
import copy
class Solution:
# @param node, a undirected graph node
# @return a undirected graph node
def cloneGraph(self, node):
return copy.deepcopy(nod... |
import cv2 as c
import numpy as np
import tkinter as tk
from sklearn.neighbors import KNeighborsClassifier
from tkinter import filedialog
from PIL import ImageTk, Image
l = tk.Tk()
l.geometry('300x300')
def select():
global name
name = filedialog.askopenfilename(initialdir = "/Users/Dariush/Deskt... |
from viola.core.stream import TCPStream
from viola.exception import ViolaEventException
from viola.core.event_loop import EventLoop
from viola.http.parser import Parser
from viola.http.wrapper import Wrapper
import logging
class WSGIStream(TCPStream):
def __init__(self, c_socket, event_loop, wsgi_handler, start_r... |
def norm(vector):
total = 0
for i in range(len(vector)):
total += vector[i] ** 2
total = total**(1/2)
return total
def normalize(vector):
new = []
for i in range(len(vector)):
total = 0
total += vector[i] * (1 / norm(vector))
new.append(total)
return new
def dot(vector01, vector02):
to... |
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Nombre: botonRedondo.py
# Autor: Miguel Andres Garcia Niño
# Creado: 10 de Mayo 2018
# Modificado: 10 de Mayo 2018
# Copyright: (c) 2018 by Miguel Andres Garcia Niño, 2018
# License: Apa... |
# !/usr/bin/python
# coding=utf-8
#
# @Author: LiXiaoYu
# @Time: 2013-10-17
# @Info: Config.
import sys
from Configs.ParseConfig import ParseConfig
class Config():
#配置字典
__config_dict = {}
#创建解析器
def __init__(self, app_name=""):
#惯例配置
c = ParseConfig()
default_dict = c.getVal... |
#!/usr/bin/python
from pwn import *
def exploit():
global io
system_addr = 0x08048320
binsh_addr = 0x0804A024
payload = 'A' * 0x88
payload += 'A' * 0x4
payload += p32(system_addr) # ret addr
payload += 'A' * 0x4 # ebp --> push ebp
payload += p32(binsh_addr) # bins... |
"""BIDS Interface for MOABB.
========================
This module contains the BIDS interface for MOABB, which allows to convert
any MOABB dataset to BIDS with Cache.
We can convert at the Raw, Epochs or Array level.
"""
# Authors: Pierre Guetschel <pierre.guetschel@gmail.com>
#
# License: BSD (3-clause)
import abc... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
def main():
logging.warning('warning!')
logging.info('info')
if __name__ == '__main__':
main()
|
"""Unit testsing for ConstGaussian
"""
import pytest
import numpy as np
from firecrown.likelihood.gauss_family.gaussian import ConstGaussian
from firecrown.modeling_tools import ModelingTools
from firecrown.parameters import (
RequiredParameters,
DerivedParameterCollection,
)
def test_require_nonempty_stati... |
from osgeo import gdal
raster =gdal.Open("raster_intersects_recortado.tif")
band = raster.GetRasterBand(1)
sec_gye = band.ReadAsArray()
|
# Generated by Django 3.0.7 on 2020-11-27 17:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cl_table', '0085_auto_20201116_0823'),
]
operations = [
migrations.AlterField(
model_name='prepaidaccount',
name='sa... |
#! ./env/bin/python
import pendulum
import sys
import logging
import logging.config
logger = logging.getLogger()
from etm.__version__ import version
import etm.view as view
# from etm.view import check_output
import etm.options as options
setup_logging = options.setup_logging
setup_logging(1, '~/etm-mv')
view.logge... |
import numpy as np
import csv
from scipy import optimize
import math
"""This code takes a .csv file containing the coordinates, and normal angle (in radians) of a set planar contacts. It
returns whether or not the set is in form closure. If closed it returns the solution to the linear problem.
Example usage log:
In... |
from math import ceil, floor
def displayMoves(moves):
spacing = [' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ',' ','']
chanceSpace = [' ',' ','']
print(' | Move Name | Chance | Damage')
print('-------------------... |
#!/usr/bin/python3
"""My string module performs operations on strings
"""
def text_indentation(text):
"""Prints 2 new lines after each . ? or : character in a string
Args:
text (str): The text to perform operation on
"""
if not isinstance(text, str):
raise TypeError("text must be a st... |
import tensorflow as tf
from tensorflow.python.framework.ops import convert_to_tensor
from utils import save_images, get_image
import numpy as np
class Dataloader():
def __init__(self, repeat_num, batch_size, output_size):
self.repeat_num = repeat_num
self.batch_size = batch_size
self.outpu... |
"""Author Arianna Delgado
Created on June 14, 2020
"""
#Defines a function to calculate average.
#Values a and b are by default 20 and 10.
def average(a = 20 ,b = 10):
print(a)
print(b)
return (a+b)/2
#Changes the default value, add arguments to the function.
print(average(a = 50)) |
from flask import render_template,request
from flask import redirect,url_for
import os
from PIL import Image
from app1.ml_model import pipeline_model
upload_folder='static/uploads'
def base():
return render_template("base.html")
def index():
return render_template("index.html")
def faceapp():
... |
in_file = open('input_15.txt', 'r')
# in_file = open('test_15.txt', 'r')
def pushTill2020(l):
while len(l) < 2020:
if l[0] not in l[1:]:
l.insert(0, 0)
else:
l.insert(0, l[1:].index(l[0]) + 1)
return l[0]
start = list(map(lambda x: x.rstrip(), in_file.readlines()))[0].split(',')
start = list(map(int, star... |
# Generated by Django 2.2.6 on 2019-10-19 17:07
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('techei', '0005_auto_20191019_2232'),
]
operations = [
migrations.RemoveField(
model_name='person',
name='country',
)... |
from django import forms
from .models import BlogData
class PostForm(forms.ModelForm):
class Meta:
model = BlogData
fields = ('title', 'link',) |
from common import eprint
CORRECT_PASS = "pass"
print("cde job list --vcluster-endpoint https://d94tftqj.cde-64m2285t.dex-priv.xcu2-8y8x.dev.cldr.work/dex/api/v1")
# Simulate no line break at end of the line
print("WARN: Plaintext or insecure TLS connection requested, take care before continuing. Continue? yes/no [no... |
#!/bin/env python
from flask import Flask, jsonify, request, send_from_directory, abort
from embedding_sharedmem import Embedding
import json, os, ast, pickle, sys
from pathlib import Path
import numpy as np
data = None
embeddings = {}
wordlists = {}
data_path = Path(__file__).resolve().parent.parent / '... |
import os
from datetime import timedelta
from icalendar import Calendar, Event, Todo, Journal
from icalendar.caselessdict import CaselessDict
from icalendar.prop import vDate, vDatetime
import pytz
import pendulum
import dateutil
# from dateutil.parser import parse
from pendulum import parse as pendulum_parse
def p... |
# -*- coding: utf-8 -*-
from django.shortcuts import render_to_response, redirect
from django.template import RequestContext
from vasite import settings
import requests
from django.http import HttpResponse
def page(request):
return render_to_response("auth.html", {},context_instance=RequestContext(request))
def ... |
"""
game module
"""
class Game(object):
"""
Game
"""
def __init__(self):
self._parser = None
self._hero = None
self._people = []
self._rooms = []
self._things = []
def play(self):
"""
Entrypoint for starting a game. This method should loop ... |
import os
import cv2
import numpy as np
def skin_detector_train(imageFolder="./Images/SkinTraining"):
# creating a 2d histogram. got maximum dimensions from cv2 change color space documentation.
histogram = np.zeros((180,256))
for imageName in os.listdir(imageFolder):
# reads... |
from fabric.api import local
def prepare_deploy():
local("dir")
|
'''
author: juzicode
address: www.juzicode.com
公众号: 桔子code/juzicode
date: 2020.10.20
'''
print('\n')
print('-----欢迎来到www.juzicode.com')
print('-----公众号: 桔子code/juzicode \n')
import time, threading
def func1():
thread_name = threading.current_thread().name
print('进入线程: ', thread_name)
print(thread_nam... |
import sys
# Class for individual Congkak holes
class CongkakHole:
def __init__(self, player, type):
self.player = player
self.type = type
# Initialising marble count for score and house
if type == "score":
self.marbles = 0
elif type == "house":
... |
import math
import string
import random
import re
import datetime
def generate_password(length: int) -> str:
"""
generate password with given length
Homework
функция должна возвращать строку из случайных символов заданной длины.
"""
alphabet = string.digits + string.ascii_uppercase + string.asc... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.