text stringlengths 8 6.05M |
|---|
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String, DateTime, UnicodeText, Sequence
from sqlalchemy.orm import relationship, backref
from datetime import datetime
from app.db.database import Base
class Project(Base):
__tablename__ = "projects"
id = Column(Integer, Sequence('projects_id_seq'),... |
from node import Operator_node, Float_node, Variable_node, Print_node, If_node, Endif_node, While_node, Endwhile_node, Node
from token_types import Token_types
from operations import Operations
from token import Token
from typing import List
def parse(tokens: List[List[Token]]) -> List[List[Node]]:
'''
This f... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:hua
from . import goods_blue
@goods_blue.route("/index")
def user_info():
return "goods_blue" |
from sklearn.cluster import KMeans
import numpy as np
import pandas as pd
class AlgoritmoDeKMeans:
def __init__(self, dataset):
self.model = KMeans(n_clusters=14) # escolhido 14 devido a análise dos valores de inertia em 30 grupos diferentes
self.model.fit(dataset)
# insere coluna gru... |
#!/usr/bin/env python
import socket
import time
from envirophat import weather, leds , light
HOST, PORT = '', 8888
listen_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((HOST, PORT))
listen_socket.listen(1)
print 'Ser... |
#####################
from spyre import server
class SimpleApp(server.App):
title = "Simple App"
inputs = [{ "type":"text",
"key":"words",
"label": "write here",
"value":"hello world"}]
outputs = [{"type":"html",
"id":"some_html",
... |
""" lets make some dominos and some functions to access them"""
"""creates a domino with a left and a right value"""
def create(left, right):
domino = (left, right)
return domino
"""gets left domino value"""
def get_left(domino):
return domino[0]
"""gets right domino value"""
def get_right(domino):
re... |
# coding: utf-8
import random
import json
import asyncio
import itchat
from threading import Thread
from .config import (STICKERS_FOR_SPAM, EVERY_REPLY_SEND_COUNT, REPLY_TEMPLATE_SPAM,
ANIMATED_QUERY_TYPE, GIFT_MONEY_KEYWORD, GIFT_MONEY_STICKER_QUERY)
from .logger import logger
from .chatroom impor... |
n , v = map(int,input().split())
arr = list(map(int,input().strip().split()))[:n]
brr = list(map(int,input().strip().split()))[:n]
mn = 10000000000000
for i in range(n):
mn = min(mn,brr[i]/arr[i])
sum = 0
for i in range(n):
sum = sum + arr[i] * mn
if sum > v:
print(v)
else:
print(sum)
... |
# -*- coding: utf-8 -*-
__author__ = 'Konrad'
import threading
import time
class myThread(threading.Thread):
threadCounter = 0
barrierCounter = 0
exitCounter = 0
lock = threading.Lock()
cv = threading.Condition(lock)
def __enter__(self):
return self
def __init__(self, threadID, ... |
class TimeDiff:
"""Helper class to handle a duration in various units.
Attributes:
time_diff (int): duration to manage (in seconds).
"""
def __init__(self, time1, time2):
"""Initialize the duration.
Args:
time1 (int): first timestamp in second.
... |
class Inside(): pass
class Outside(): pass
def switch(s):
if isinstance(s, Outside):
return Inside()
elif isinstance(s, Inside):
return Outside()
def separate(line, separator, escape_char):
assert(type(separator) == str)
assert(type(escape_char) == str)
assert(separator != escape_char)
state = Outside()
t... |
# *_* coding=utf8 *_*
#!/usr/bin/env python
from unreal.utils import ipv4
from unreal.handler import base
class Link(base.BaseHandler):
def get(self, uuid):
url = self.db.get("SELECT * FROM url WHERE uuid=%s", uuid)
remote_ip_v4 = ipv4.to_int(self.request.remote_ip)
referer = self.reques... |
import matplotlib.pyplot as plt
import numpy as np
import math
#Core Visualization Function for generated .csv files & Overall Performance file
def Visualize(version_array, measure_array, nrWorkers=0, nrCycles=0, promFile=''):
plt.rcdefaults()
fig, ax = plt.subplots()
y_pos = np.arange(len(version_array))
#N... |
class Jeu(object):
def __init__(self):
self.Village = {}
self.nbrGentils = 0
self.nbrLoups = 0
self.tours = []
self.listeMortsPotentielles = [] # Liste des morts potentielle avant le vote du matin |||| A effacer CHAQUE matin
self.listeProteges = [] # Li... |
# -*- coding: utf-8 -*-
"""A plugin to migrate mailboxes using IMAP."""
from __future__ import unicode_literals
from pkg_resources import get_distribution, DistributionNotFound
try:
__version__ = get_distribution(__name__).version
except DistributionNotFound:
# package is not installed
pass
default_ap... |
import os, sys, math
import pygame as pg
from player import Player
from enemy import EnemySpawner
from utils import DamageBar, MenuSystem, media_path
TITLE = "Bubble Shoot"
SIZE = (0, 0)
FPS = 60
BACKGROUND = (80, 80, 80)
MENU_BACKGROUND = (55, 37, 92)
class Game:
def __init__(self):
p... |
from location import *
import csv
import os
def readData():
locdict = {}
if os.name == 'nt':
with open("LocationLatLong.csv", newline='', encoding='utf-8') as csvfile:
locreader = csv.reader(csvfile, dialect='excel', delimiter=',')
for row in locreader:
locdict[s... |
import os;
import time;
import math;
import sys;
f = [ [] , [] ]
filename = '../runBodies0.bat'
f[0] = open(filename,'w')
filename = '../runBodies1.bat'
f[1] = open(filename,'w')
for i in range(300,399+1):
filename = '../runBodies' + str(i%2) + '.bat';
writeString = './Modularity ' + str(i) + '\n';
f[i%2].wri... |
#!/usr/bin/env python3
from functions_script import binomial
import matplotlib.pyplot as plt
from math import sqrt
def mean(n, p):
return n*p
def variance(n, p):
return n*p*(1-p)
def std_dev(var):
return sqrt(var)
def pr(p, total, choose, verbose=False):
if verbose:
print(f'{total} choos... |
#!/usr/bin/python3
''' Classes partake of the dynamic nature of Python: they are created at runtime and can be modified after creation. '''
class MyClass():
name = "Wukong"
def __init__(self, name): # constructor
self.name = name
def show(self):
print "Welcome to here, my friend: ", s... |
# test 1
# 嵌套
# 创建30个外星人字典:列表中嵌套字典
aliens = []
for alien_num in range(1,31):
alien = {'color':'green', 'age':'14', 'point':'5', 'number':alien_num}
aliens.append(alien)
# 修改前3个,用到切片
for alien in aliens[:3]:
if alien['color'] == 'green':
alien['color'] = 'blue'
alien['age'] = '20'
a... |
# 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 License, Version 2.0
# (the 'License'); you may not use ... |
from abc import ABCMeta, abstractmethod
from SignalGenerationPackage.SignalData import SignalData
import numpy as np
from LoggersConfig import loggers
from SignalGenerationPackage.Point import Point
class Signal(metaclass=ABCMeta):
# Model in MVC, abstract class
# Aggregates the class SignalData - also part ... |
#!/usr/bin/python
def run(filename):
f = open(filename, "r")
case_count = int(f.readline())
for i in range(case_count):
line = f.readline()
result = process_case(parse_case(line))
print('Case #%d: %s' % (i+1, result))
def parse_case(line):
pieces = line.split()
return ... |
import sys
import urllib2
import json
import ipdb as pdb
def get_results(ddg):
results = []
for ret in ddg.get("RelatedTopics"):
if ret.has_key("Topics"):
for rett in ret.get("Topics"):
result_inf = {"description":rett["Text"], "url":rett["FirstURL"]}
el... |
from torch.utils.data import DataLoader, Dataset
from PIL import Image
import cv2
import torch
import numpy as np
from torch.utils.data import Dataset
from torchvision import transforms
class InferDataset(Dataset):
def __init__(self, annotations_list, mode='train', transform=None):
self.annotations_list ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys, pygame
from pygame.locals import *
chessplate =(
('L','C','C','R','6','R','I','E'),
('E','E','L','S','S','P','9','E'),
('E','E','E','1','U','E','D','U'),
('S','L','U','E','M','9','V','R'),
('D','L','1','S','T','E','A','S'),
('L','O','C','P','5','O','T','D'),
('A','U... |
import numpy as np
# -------------------------------INPUT-------------------------------------------------------
number_of_river_patches = 44
id_file = 'id_mesh_refined_acuna.dat'
outputfile = 'dzg_2007_acuna_option_1.dat'
schwelle_id = 999
schwelle_value = 0
value_bed = 3
value_banks = 0
# ---------------------------... |
def unscramble_eggs(word):
return word.replace('egg','')
'''
Unscramble the eggs.
The string given to your function has had an "egg" inserted directly after
each consonant. You need to return the string before it became eggcoded.
Example
unscrambleEggs("Beggegeggineggneggeregg"); => "Beginner"
// "B... |
import sys
import os
import errno
from datetime import datetime
name = "{query}"
sys.stdout.write(name)
title = name.title()
file_name = "{}-{}.md".format(
datetime.today().strftime('%Y-%m-%d'),
name.replace(' ', '-').lower()
)
folder = os.environ.get('noteable_folder')
home = os.getenv("HOME")
if folder:
... |
def main():
"""
Visualize the outputs of the train dataset analyses.
"""
import matplotlib.pyplot as plt
import pandas as pd
# The original data set
df_0 = pd.DataFrame.from_csv('arr_dep.csv')
# The data set with the multiplication interaction feature.
df_times = pd.DataFrame.from_... |
# Generated by Django 2.2.1 on 2019-05-25 05:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0011_auto_20190519_2047'),
]
operations = [
migrations.AddField(
model_name='post',
name='custom_css',
... |
# Copyright 2017 The Forseti Security Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ap... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2021/1/7 16:33
__author__ = 'the king of north'
from django.shortcuts import render
from django.core.paginator import Paginator
def carlists(request):
clists = [{"Id": 1, "brand": "11", "name": "ll", "price": 1, "type": 1},
{"Id": 1, "brand": ... |
import speech_recognition
robot_ear=speech_recognition.Recognizer()
with speech_recognition.Microphone()as mic:
print("Robot: i'm listening ")
audio=robot_ear.listen(mic)
try:
you= robot_ear.recognize_google(audio)
except:
you== ""
print("you :"+you) |
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 30 09:57:02 2020
@author: hua'wei
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import pandas as pd
import sklearn.preprocessing as prep
import tensorflow as tf
from Autoenc... |
import pygame
import random
pygame.init()
display_width = 800
display_height = 600
yellow_color = (255, 253, 208)
black_color_1 = (100, 100, 100)
black_color_2 = (0, 0, 0)
red_color = (255, 0, 0)
green_color = (0, 255, 0)
display = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption(... |
import datetime as dt
birthday = dt.datetime(2001, 1, 23)
time_alive = dt.datetime.today() - birthday
print(time_alive.days) |
#!/usr/bin/env python
from setuptools import setup
setup(name='igtdetect',
version='1.1.1',
description='Line-level classifier for IGT instances, part of RiPLEs pipeline.',
author='Ryan Georgi',
author_email='rgeorgi@uw.edu',
url='https://github.com/xigt/igtdetect',
scripts=['detect... |
from math import *
from decimal import *
def methoda(a):
n = 0
getcontext().prec = 1000
total = Decimal(0)
for i in range(1):
for a in range(a):
total = Decimal(total) + Decimal(1/Decimal(factorial(n)))
n = n + 1
print(Decimal(total))
a = 5000
methoda(a)
|
from typing import Dict
from graph_db.engine.types import *
from .graph_storage import NodeStorage, RelationshipStorage, PropertyStorage, LabelStorage, DynamicStorage
from .record import Record
import rpyc
from rpyc.utils.server import ThreadedServer
class WorkerService(rpyc.SlaveService):
class exposed_Worker(... |
# Generated by Django 3.0.3 on 2021-03-21 22:39
from django.db import migrations
import multiselectfield.db.fields
class Migration(migrations.Migration):
dependencies = [
('api', '0006_auto_20210321_2239'),
]
operations = [
migrations.AlterField(
model_name='resource',
... |
# coding: utf-8
# Standard Python libraries
from io import IOBase
from pathlib import Path
from typing import Optional, Union
# https://github.com/usnistgov/atomman
import atomman.unitconvert as uc
# https://github.com/usnistgov/DataModelDict
from DataModelDict import DataModelDict as DM
# iprPy imports
from .. imp... |
import numpy as np
import pdb
from gym import utils
from . import mujoco_env
from . import geom_utils
class BaseAntEnv(mujoco_env.MujocoEnv, utils.EzPickle):
# Initialize Mujoco environment
def __init__(self, xml_file='my_ant.xml'):
mujoco_env.MujocoEnv.__init__(self, xml_file, 5)
utils.EzPickl... |
for i in range(1, 11):
with open('resources/asap_prompt_'+str(i)+'.txt', 'r', encoding='utf-8') as file:
max_length = 0
sum_length = 0
count_line = 0
min_length = 1024
for line in file:
token_list = line.split(" ")
if len(token_list) > max_length:
... |
from queue import LifoQueue
class StackUnderflowError(Exception):
def __init__(self, message):
super().__init__(message)
def check_size(stack, size):
if stack.qsize() < size:
raise StackUnderflowError("Stack does not contain enough values for required pop")
def dup(stack):
check_size(stac... |
from spack import *
import sys,os
sys.path.append(os.path.join(os.path.dirname(__file__), '../../common'))
from scrampackage import write_scram_toolfile
class LibtiffToolfile(Package):
url = 'file://' + os.path.dirname(__file__) + '/../../common/junk.xml'
version('1.0', '68841b7dcbd130afd7d236afe8fd5b949f0176... |
import boto3
import json
def get_aws_mesh_info():
"""
A function that gets the mesh information
"""
conn = boto3.client('ec2')
regions = [region['RegionName'] for region in conn.describe_regions()['Regions']]
appmeshes = []
route_info = []
for region in regions:
if region == '... |
import pandas as pd
from PIL import Image
import numpy as np
import csv
def main():
csv_data = pd.read_csv("./challenge_test/test.csv").values
image_array = csv_data[:,1:]
image_id = csv_data[:,0]
image_num = image_array.shape[0]
print(image_array.shape)
image_array = image_array.reshape((image_... |
# -*- coding: utf-8 -*-
class Solution:
def countEven(self, num: int) -> int:
digit_sum, original_num = 0, num
while num:
num, remainder = divmod(num, 10)
digit_sum += remainder
return original_num // 2 if digit_sum % 2 == 0 else (original_num - 1) // 2
if __name... |
import pandas as pd
data frame
data frame2
|
try:
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO.setup(17, GPIO.OUT)
def blink(pin):
GPIO.output(pin, True)
time.sleep(0.1)
GPIO.output(pin, False)
except:
def blink(pin):
print('blinking pin %s' % pin)
|
"""
权限视图模块
"""
# pylint: disable=invalid-name, too-few-public-methods
from flask import render_template, redirect, url_for, flash
from flask_login import login_required, current_user
from flask_moment import Moment
from datetime import datetime
import pytz
from .. import mydb
from .forms import LabelDict, PayapplyForm,... |
def get_city(city,country,population=''):
if population:
name=city.title()+","+country.title()+" - population "+str(population)
else:
name=city.title()+","+country.title()
return name
|
# Depth-first search
def dfs(node, explored):
pass
# Breadth-first search
def bfs(start, goal):
pass
|
import tensorflow as tf
import numpy as np
tf.enable_eager_execution()
tf.set_random_seed(777) # for reproducibility
tfe = tf.contrib.eager
x_data = [[1, 2, 1, 1], [2, 1, 3, 2],[3, 1, 3, 4],[4, 1, 5, 5],
[1, 7, 5, 5],[1, 2, 5, 6],[1, 6, 6, 6], [1, 7, 7, 7]]
y_data = [[0, 0, 1],[0, 0, 1],[0, 0, 1],[0, 1, 0],... |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 26 19:24:02 2020
@author: shaun
"""
import numpy as np
from scipy.optimize import brentq
def eulerstep(yn,tn,f,h):
yn1=yn+h*f(yn,tn)
return yn1
def eIlinstep(yn,tn,f,df,h):
top=yn+h*f(yn,tn+h)-h*yn*df(yn,tn+h)
bot=1-h*df(yn,tn+h)
yn1=top/bot
return... |
import pytest
def test_cadastro():
dado1 = {"nome": "YURI"}
dado2 = {"nome": "YURI"}
assert dado1 == dado2
|
import random
import string
import pyperclip
class User:
user_list = []
def __init__(self, user_name, password):
self.user_name = user_name
self.password = password
def save_user(self):
User.user_list.append(self)
@classmethod
def display_user(cls):
return cls... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Filename: step02_download_world_bank_indicator_in_my_mac
# @Date: 2020/3/11
# @Author: Mark Wang
# @Email: wangyouan@gamil.com
"""
python -m CollectData.step02_download_world_bank_indicator_in_my_mac
"""
import os
import time
import random
import pandas as pd
from tq... |
# importing matplotlib module for the plot
import matplotlib.pyplot as plot
# importing random module to generate random integers for the plot
import random
# initialising the lists
x = [0]
y = [0]
# initialising a variable to zero to track position
current = 0
for i in range(1, 100000):
# generating a random intege... |
class Solution(object):
def deleteNode(self, node):
"""
https://leetcode.com/problems/delete-node-in-a-linked-list/
just replace the next node data with current node.
"""
next_node = node.next
node.val = next_node.val
node.next = next_node.next |
import pandas as pd
from nipype.pipeline.engine import Node, Workflow, MapNode
import nipype.interfaces.utility as util
import nipype.interfaces.io as nio
import nipype.interfaces.fsl as fsl
import nipype.interfaces.freesurfer as fs
import nipype.interfaces.afni as afni
import nipype.interfaces.nipy as nipy
import nipy... |
import unittest
from katas.kyu_5.sum_of_pairs import sum_pairs
class SumOfPairsTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(sum_pairs([11, 3, 7, 5], 10), [3, 7])
def test_equal_2(self):
self.assertEqual(sum_pairs([4, 3, 2, 3, 4], 6), [4, 2])
def test_equal_3(sel... |
import socketserver
import socket, threading
import sys
class MyTCPHandler(socketserver.BaseRequestHandler):
BUFFER_SIZE = 4096
def handle(self):
global address
add = address
global destPort
dst = destPort
s = socket.socket()
s.connect((add,dst))
while 1... |
import logging
import operator
from datetime import datetime
from functools import reduce
import matplotlib.pyplot as plt
import numpy as np
from sympy import Symbol
from sympy.functions.elementary.exponential import log
from scipy.special import gamma
from common.gen import LinearCongruentialGenerator
from common.lo... |
"""
cYnfクラスのテスト
"""
import os
import sys
from unittest import TestCase
# srcの下をパスに追加
sys.path.append(os.path.join(os.getcwd(), 'src'))
from fig_package.format.ynf import cYnf, cYnfLine
class TestCYnf(TestCase):
"""
cYnfクラスのテスト
"""
def setUp(self):
"""
テスト前処理
"""
self.de... |
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, ... |
n_kg = int(input())
bongzi = [5, 3]
geasu = 0
i = 0
if n_kg % 5 == 0:
geasu = n_kg // bongzi[0]
n_kg -= geasu * bongzi[0]
else:
while i*bongzi[0] < n_kg:
if n_kg - (i*bongzi[0]) == 3:
geasu += 1 + i
if n_kg - (i * bongzi[0]) == 6:
geasu += 2+ i
if n_kg - (i ... |
from django.conf.urls import url
from . import views
from .views import AccountView
urlpatterns = [
#127.0.0.1:8000/v1/users
url(r'^$', views.user_view),
#获取验证码
url(r'/code$',views.code_view),
url(r'/reset$',views.password_view),
#http://127.0.0.1:8000/v1/users/activation?code=xxxx
url(r'^/... |
from kivy.lang import Builder
from kivy.properties import ObjectProperty
from kivymd.app import MDApp
from kivymd.uix.floatlayout import MDFloatLayout
from kivymd.uix.tab import MDTabsBase
from kivymd.icon_definitions import md_icons
colors = {
"Teal": {
"50": "e4f8f9",
"100": "bdedf0",
"2... |
try:
from urllib import request
from urllib.request import urlopen
import threading # import threadding
import json # import json
import random # import random
import requests # import requests
import ssl
ex... |
from setuptools import setup, find_packages
setup(
name='zeit.care',
version='0.3.dev0',
author='gocept, Zeit Online',
author_email='zon-backend@zeit.de',
url='http://www.zeit.de/',
description="Helper scripts for managing DAV content",
packages=find_packages('src'),
package_dir={'': '... |
from connection import db, Required
class Logservice(db.Entity):
_table_ = 'logservice'
uri = Required(str)
method = Required(str)
params = Required(str)
ip_address = Required(str)
request_time = Required(str)
response = Required(str, 65535)
status = Required(str)
|
PERF_VAL = [
'0 - Fully active, able to carry on all predisease activities without restrictions.',
'1 - No physically strenuous activity, but ambulatory and able to carry out light or sedentary work.',
'2 - Ambulatory/capable of self-care, unable to perform work activities. Up & about more than 50% of the ... |
class Tablero:
tab = []
max_p = 0
def __init__(self, Tablero, Palabra_max):
self.tab = Tablero
self.max_p = Palabra_max
|
В приведенном ниже примере, несколько регистров и числовых значений загружаются в стек. В каком порядке они будут извлекаться из стека с помощью команды pop? Расположите в верном порядке.
push edi
push ecx
push ebp
push 3
push eax
|
'''
Mirror Sequence
Print numbers in sequence is a relatively simple task.
But, and when it is a sequence mirror? This is a sequence
having a number of start and an end number and all numbers
therebetween, including these, are arranged in an increasing
sequence without spaces, and then this sequence is designed
i... |
print("*** ASSIGNMENT 1 ***")
print(" ")
print("Ex1")
def fun():
print("Hello from fun")
fun()
print(" ")
print("Ex2")
def no():
n = int(input("Any no:"))
if (n%2==0):
print("EVEN")
else:
print("Odd")
no()
print(" ")
print("Ex3")
def Add():
a = int(inpu... |
#!/usr/bin/env python3
import subprocess
import time
import yaml
with open('en.yml', 'r') as handle:
data = yaml.load(handle)
out = {}
for k, v in data.items():
print(k, v)
transv = subprocess.check_output(['trans', 'en:es', '-b', v])
print(k, transv)
out[k] = transv
time.sleep(5)
with open('e... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from textwrap import dedent
import pytest
from pants.backend.codegen.protobuf.target_types import ProtobufSourceTarget
from pants.backend.python.goals... |
default_app_config = 'eshop_products.apps.EshopProductsConfig' |
# -*- coding: utf-8 -*-
from django import forms
from django.db import models
from django.template.loader import render_to_string
class TokenWidget(forms.Widget):
class Media:
js = ['random_field/token.js']
css = {
'all': ['random_field/token.css']
}
def __init__(self, max... |
import fool
fool.load_userdict(path)
text = "我在北京天安门看你难受香菇"
print(fool.cut(text)) |
from django.shortcuts import render
from django.shortcuts import render
from django.db.models import Q
from django.shortcuts import render
from User.models import UserExtended
from django.contrib.auth import (authenticate,
login)
from rest_framework.response import Response
from res... |
name = "kindling"
__all__ = [
"FireActorCritic",
"FireQActorCritic",
"FireDDPGActorCritic",
"FireTD3ActorCritic",
"FireSACActorCritic",
"TensorBoardWriter",
"utils",
"ReplayBuffer",
"PGBuffer",
"Saver",
"Logger",
"EpochLogger",
]
from flare.kindling.neuralnets import (
... |
from django.test import RequestFactory
from api.models import AndelaUserProfile, UserProxy
from graphene.test import Client
from snapshottest.django import TestCase
from graphql_schemas.schema import schema
class BaseUserTestCase(TestCase):
def setUp(self):
self.user1 = UserProxy.create_user({
... |
print("\n*********************************************************\n")
data1 = [1,2,3,4,5,6,7,8]
print("Here is the original data:",data1)
evens_for = []
for num in data1:
if not num%2:
evens_for.append(num)
print("Here is the even numbers using for loop: ",evens_for)
evens_comp = [num for num in data1 if not num... |
from sql_kit import SQL_kit
import lyricsgenius
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import mysql.connector
import getpass
import pathlib
from pathlib import Path
class Lyrics_Tool:
def __init__(self):
# genius API key
self.genius_api_key = getpass.... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 25 15:56:45 2019
@author: HP
"""
import random
def power(a,n,p):
res=1
while n>0:
if n%2==1:
res=(res*a)%p
n=n/2
res=(res*res)%p
return res
def euclidean_gcd(a,b):
if b==0:
return a
else:
return eu... |
import os
import xml.etree.ElementTree as et
import cv2
object_name_dict = {
'rice': '1',
'soup': '2',
'rect': '3',
'lcir': '4',
'ssquare': '5',
'msquare': '6',
'lsquare': '7',
'bsquare': '8',
'ellipse': '9'
}
def data_transfer(xml_path, img_... |
from PyQt5.QtGui import QPixmap
from ui_msgbox import *
class RecordingBoxWindow(QtWidgets.QWidget, Ui_msgbox):
message = []
def __init__(self, type, msg,parent=None):
super(RecordingBoxWindow, self).__init__(parent)
self.setupUi(self)
init_f={"buy":self.init_buy,
"sol... |
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.core import validators
from .forms import *
from models import CustomUser as MyUser
from models import SocialNetworks as sn
from django.template import *
# Create your ... |
class Solution(object):
def deleteDuplicates(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head is None:
return None
tmp = head
while tmp is not None:
if tmp.next is not None and tmp.val == tmp.next.val:
... |
from rply import LexerGenerator
class Lexer():
def __init__(self):
self.lexer = LexerGenerator()
def _add_tokens(self):
# Parentheses
self.lexer.add('OPEN_PAREN', r'\(')
self.lexer.add('CLOSE_PAREN', r'\)')
# definitions
self.lexer.add('DEF_NOT', r'def \~')
... |
# definiere eine Person-Klasse
class Person():
# Initialisiere die Klasse mit Daten
def __init__(self, first_name, last_name, year_of_birth):
# speichere die uebergebenen parameter ab
# (self ist das aktuelle Objekt - also das Objekt, das
# gerade initialisiert wird)
self.first_... |
import sys
import random
import signal
import argparse
from functools import partial, reduce
from itertools import chain
import blessed
from .. import save
from ..grid import Direction, Actions
from .grid import Grid
from .tile import Tile
up, left = ('w', 'k', 'KEY_UP'), ('a', 'h', 'KEY_LEFT')
down, right = ('s', '... |
#! C:\bin\Python35\python.exe
# -*- coding: utf-8 -*-
'''
Modified for python3 on 2012/04/29
original python2 version is Created on 2011/10/30
@author: tyama
'''
import poplib
import email.header
import string
import re
import urllib.request
import urllib.error
import urllib.parse
import http.cookiejar
import socket
... |
import requests as http
from lib.mouse import Mouse
from lib.GPIOInteraction import GPIOInteractor
from lib.SoundPlayer import SoundPlayer
import os
import time
os.environ['PLAYING'] = 'False'
playing = False
pause_time = 0
paused_at = time.time()
pressed_at = time.time()
skip = False
playback_url = 'http://127.0.0.1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.