text stringlengths 8 6.05M |
|---|
from django.contrib import admin
# Register your models here.
from .models import Book
"""Minimal registration of Models.
admin.site.register(Book)
"""
admin.site.register(Book)
class BooksInline(admin.TabularInline):
"""Defines format of inline book insertion (used in AuthorAdmin)"""
model = Book
class B... |
#!/usr/bin/env pybricks-micropython
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,
InfraredSensor, UltrasonicSensor, GyroSensor)
from pybricks.parameters import Port, Stop, Direction, Button, Color
from pybricks.tools impor... |
from aiogram import types
from aiogram.dispatcher import FSMContext
from bot.loader import dp
@dp.message_handler(state=None)
async def bot_echo(message: types.Message):
await message.answer(f"{message.text}"
f"Вы были зарегестрированы {None}")
@dp.message_handler(state="*", content_ty... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'addEditCoffeeForm.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Form(object):
def setupUi(self, Form):
Form.set... |
from django.test import TestCase
from rest_framework.test import APITestCase
from authentication.models import User
class TestModel(APITestCase):
def test_test(self):
self.assertEqual(1,1-0)
def test_creates_user(self):
user=User.objects.create_user('hi','hi@gmail.com', 'test123')
... |
from .object import Object
# namespace
class Ns(Object):
pass
# global namespace
glob = Ns('global')
glob << glob
glob >> glob
|
# MLP
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
get_ipython().magic('matplotlib inline')
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop
# set parameters
ba... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Operation',
fields=[
... |
import time
TABLE_SIZE = 64
HASHING = 7
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
def the_print(info):
print "[CACHE]", info
table = [[] for i in range(TABLE_SIZE)]
def insert(incident_list, from_value, to_value):
if to_value ... |
a=list(input().split())
for i in range(len(a)):
b = a[i][::-1]
print(b,end=" ")
|
from pico2d import *
import game_framework
import game_world
import time
class Player:
image = None
RUN_SPEED_PPS = 300
FIELD_MARGIN = 50
PADDLE_Y = 100
def __init__(self):
self.field_width, self.field_height = get_canvas_width(), get_canvas_height()
self.size = 60
self.mouse_control = False
self.angle = ... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from dataclasses import dataclass
from pants.backend.python.lint.add_trailing_comma.skip_field import SkipAddTrailingCommaField
from pants.backend.python.lint.add_trailing_comma.subsystem... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 10 10:08:15 2020
@author: TOP Artes
"""
# Importa a biblioteca para estruturação dos dados
import numpy as np
# Importa as classes necessárias
from model.regressor import Regressor
from model.validator import Validator
from control.control_validator impor... |
# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import user_passes_test
from Aluno.models import Aluno
def check_aluno_exist(user):
if not user.is_authenticated():
return False
try:
aluno = user.aluno_set.get()
return True
except Aluno.DoesNotExist:
return ... |
from classes.github.client import Client
from classes.yaml_parser import YamlParser
from classes.yaml_replacer.result import Result
from classes.model.package import Package
from typing import Any, List, Optional
class YamlReplacer:
def __init__(self, client: Client, yaml_parser: YamlParser):
self.client... |
""" Core views
:Author: Jonathan Karr <karr@mssm.edu>
:Date: 2017-10-26
:Copyright: 2017, Karr Lab
:License: MIT
"""
from datetime import datetime
from django.contrib.auth import login as auth_login, logout as auth_logout
from django.contrib.auth.forms import AuthenticationForm
from django.http import HttpRe... |
a=input("檢測的字串(end結束):")
while a!="end":
b=list(a)
two=input("檢測的單一字元:")
if a!="end":
a=b.count(two)
print("字元",two,"出現次數為:",a)
a=input("檢測的字串(end結束):")
if a=="end":
print("檢測結束") |
class Info:
__name = None
__age = None
def __init__(self):
pass
def setName(self,name):
self.__name
def setAge(self,age):
if age < 1 :
self.__age = 1
return
def disp(self):
print("이름 : {}".format(self.__name))
print("나이 ... |
from tastypie.resources import ModelResource
from background.models import Picture
class PictureResource(ModelResource):
class Meta:
queryset = Picture.objects.all()
resource_name = 'pic' |
from tkinter import *
from tkinter import ttk
win = Tk()
win.geometry('700x500')
win.title("Priyanshi")
combo_var = StringVar()
Label(text='Binary To All Number System Converter', font=('arial bold', 20)).grid(column=0, row=1, padx=50)
Label(text="").grid(column=0, row=2)
Label(text="Enter Binary Number:"... |
#
# Copyright (c) 2020 Carsten Igel.
#
# This file is part of pip-licenses-reader
# (see https://github.com/carstencodes/pip-licenses-reader).
#
# License: 3-clause BSD, see https://opensource.org/licenses/BSD-3-Clause
#
import unittest
import tempfile
import os
from pathlib import Path
from typing import FrozenSet, L... |
#!/usr/bin/env python3
import rospy
import numpy as np
import cv2 as cv
from yolo2_utils import infer_image
from std_msgs.msg import Float32MultiArray
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Image
from std_msgs.msg import String
from vision_msgs.msg import Detection2D, Detection2DA... |
import os
from bsm.util import safe_rmdir
from bsm.util import safe_mkdir
from bsm.util import call_and_log
def run(param):
version = param['version']
tar_filename = param['config_package']['source']['file'].format(version=version)
tar_file = os.path.join(param['package_path']['misc_dir'], 'download', ta... |
HORIZONTAL = 0
VERTICAL = 1
|
from uszipcode import ZipcodeSearchEngine
import psycopg2, pprint, sys
debug = True
zipSearch = ZipcodeSearchEngine()
zipNumber = 600
conString = "dbname=yourDBname user=postgres"
con = psycopg2.connect(conString)
con.autocommit = True
sqlString = """INSERT INTO zipcode(city, density, houseofunits, landarea, latitude... |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from config import config
import time
import pytz
from pytz import timezone
from dateutil import parser
from datetime import datetime, timedelta
from common_cachefetcher import fetcher
from requests_oauthlib import OAuth1
CONSUMER_KEY = config['linked... |
# 5 - Camisetas
n = int(input())
pedidos = {}
for i in range(n):
nome = input()
if nome == "0":
break
camisa = input()
x, y = camisa.split(" ")
pedidos[nome] = (x,y)
x = sorted(pedidos.items(), reverse=True, key=lambda i : i[0])
dict(x)
y = sorted(x, key=lambda i : i[1])
dict... |
#!/usr/bin/env
# encoding: utf-8
"""
Created by John DiBaggio on 2018-09-04
Implement NumberToPattern
Implement NumberToPattern
Convert an integer to its corresponding DNA string.
Given: Integers index and k.
Return: NumberToPattern(index, k).
Sample Dataset
45
4
Sample Output
AGTC
Extra Dataset
Input
5353
7
Outp... |
import io
from test.util import ClangTest
from ctypeslib.codegen import clangparser
from ctypeslib.codegen.handler import InvalidTranslationUnitException
class TestClang_Parser(ClangTest):
def setUp(self) -> None:
# Create a clang parser instance, no flags
self.parser = clangparser.Clang_Parser([... |
# coding:utf8
from db import mongo_util
'''
获取app models
'''
from bson.objectid import ObjectId
from db.page import Page, DEFAULT_PAGE_SIZE
import pymongo
def find_collections(appid):
schemes=mongo_util.get_mongo_collection("scheme")
appScheme=schemes.find_one({"app_id":appid})
... |
import heapq
def kthLargest(iterable, k):
largest = []
sortedArray = []
for value in iterable:
heapq.heappush(largest, value)
if len(largest) > k:
sortedArray.append(heapq.heappop(largest))
if (len(largest) < k):
return None
return largest
print(kthLargest([8,... |
from TH_Repository import *
#this line generates a list of Hindu daily urls like : 'http://www.thehindu.com/archive/print/2017/01/01/'
dayUrls= TH_DayUrl_Generator()
#this line takes in Database password
PWD = raw_input( "Please Enter Database Password: ")
#this line extracts article urls (ending in .ece) from each... |
from django.http import HttpResponse
from django.shortcuts import render
import operator
def home(request):
return render(request, 'home.html', {'HITHERE': 'This is me'})
def count(request):
# fulltext pass from home.html
fulltext = request.GET['fulltext']
wordlist = fulltext.split()
worddictionary = {}
for... |
import pandas as pd
import numpy as np
import torch
from metrics import get_metrics
from torch.autograd import Variable
from tensorboardX import SummaryWriter
import itertools
import os
import pprint
# static constants
HYPERPARAMS = ['learning_rate', 'num_iters', 'n_h', 'n_h_adv', 'dropout_rate', 'alpha']
intermediate... |
#!/usr/bin/python3
# Filename : json-csv_3.py
# Author by : Lily
"""
版本三
将多条json写入csv,其中几条缺少了部分键值对
"""
json_data = [{"id":"216","city":"\u4e1c\u839e\u5e02","county":"\u5e02\u3001\u53bf\u7ea7\u5e02","detail":"\u4e1c\u839e\u5e02\u5858\u53a6\u9547\u4e07\u79d1\u751f\u6d3b\u5e7f\u573aB7\u3001B8\u53f7","time":"2015-09-23"},
... |
import sys
filename=sys.argv[1]
prefectures=set()
with open(filename) as f:
line=f.readline()
while line:
prefectures.add(line.split()[0])
line=f.readline()
for pref.in prefctures:
print (pref)
|
import app_main.main as m
m.main()
|
import requests
# script for testing
def req_loc(action, body):
resp = requests.post("http://localhost:8080/mail2", json={
"action": action,
"body": body
})
if resp.status_code == 200:
return resp.json()
raise ValueError(resp.text)
def req_rem(action, body):
resp = request... |
from django.http import JsonResponse
from django.contrib.auth.models import User
import django.contrib.auth as auth
from django.views.decorators.csrf import csrf_exempt
from .utils import users_session_data
from .forms import UserForm
import json
@csrf_exempt
def users(request):
user = json.loads(request.body)['... |
# app/serializers.py
from rest_framework import serializers
from .models import Post, ViewTestModel
class UserSerializer(serializers.Serializer):
email = serializers.EmailField()
username = serializers.CharField(max_length=100)
class PostSerializer(serializers.HyperlinkedModelSerializer):
# user = Use... |
# Challenges proposed at https://www.codementor.io/@ilyaas97/6-python-projects-for-beginners-yn3va03fs
import random
import numpy as np
# Guess the Number
if __name__ == '__main__':
num = np.random.randint(0,20) # random integer drawn from (0,20)
# function to decide whether you have won or not
# this fu... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 1 12:18:31 2015
@author: bolaka
submission1.csv - first pass @ 1.25643166239
submission2.csv - first pass
"""
import os
os.chdir('/home/bolaka/python-workspace/CVX-timelines/')
# imports
#import math
import time
import datetime
from cvxtextproject import *
from mlclas... |
class India:
def states(self):
print(29)
def currency(self):
print("Rupee")
class Usa:
def states(self):
print(15)
def currency(self):
print("Dollar")
def main():
ind_obj = India()
usa_obj = Usa()
for obj in (ind_obj, usa_obj):
obj.states()
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(verbos... |
# JTSK-350112
# rqballsim.py
# Taiyr Begeyev
# t.begeyev@jacobs-university.de
from random import random
def printIntro():
"""Prints an introduction to the program"""
print("This program simulates a game of racquetball \
between two players called \"A\" and \"B\". \
The abilities of each player is indicated by... |
import unittest, random, string
from main.activity.activity_login import *
from main.activity.activity_logout import *
from main.activity.activity_myshop_editor import *
from main.lib.user_data import *
from main.function.setup import *
class Test_add_etalase(unittest.TestCase):
_site = "live"
def setUp(se... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'MainForm.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
... |
from datatypes import nil, true, false, mksym, cons, from_list, to_list, LispSymbol, LispLambda, LispPair, first, rest, LispInteger, LispClass, class_base, Environment, LispString, get_stack
from lex import tokenize
from parse import parse
# ----------------------------------------------------------------------------... |
## Enter tile info here
bList = ['Jason','Hercules','Theseus','Odesseus','e','90','80']
iList = ['753 B.C.','509 B.C.','27 B.C.','476 A.D.','264 B.C.','146 B.C.','60 B.C.','43 B.C.','72 B.C.', '44 B.C.']
nList = ['k','l','m','n','o','90','80']
gList = ['p','q','r','s','t','90','80']
oList = ['u','v','w','x','y','90','8... |
# -*- coding: utf-8 -*-
"""
qr_code helper utils
"""
import platform
import qrcode # type: ignore
def qr_terminal(data: str, version=None):
"""
create qr_code
:param data: qrcode data
:param version:1-40 or None
:return:
"""
if platform.system() == 'Windows':
white_block = '▇'
... |
# Create a file
myFile = open('myFiles.txt', 'w')
# Write to a file
myFile.write("I love python \n")
myFile.write("I love javascript \n")
myFile.close()
# Append to file
myFile = open('myFiles.txt', 'a')
myFile.write("I kinda like php")
# Read a file
myFile = open('myFiles.txt', 'r+')
text = myFile.read()
print(tex... |
def doit():
print("MMMMMMMMMMM")
return 999
|
def solve(arr):
arr.sort()
n = len(arr)
odds = arr[0:(len(arr)//2)+(len(arr)%2)]
evens = arr[len(odds):]
odds.sort(reverse = True)
i , j = 0 ,0
while i<n and j<len(odds):
arr[i] = odds[j]
i+=2
j+=1
i , j = 1,0
while i<n and j<len(evens):
arr[i] =... |
from django.conf.urls import url, include
from django.urls import path
from .views import *
import madadkar.views
urlpatterns = [
path('', madadkar.views.madadkarhome, name='madadkar-home'),
path('goals/', madadkar.views.madadkargoal, name='madadkar-goals'),
path('history/', madadkar.views.madadkarhistory,... |
from application import app
@app.template_filter('reverse')
def reverse_filter(s):
return s[::-1]
# app.jinja_env.filters['reverse'] = reverse_filte
|
import urllib
class KatSearch:
def __init__(self):
self.protocol = "http"
self.katDomain = "kat.cr"
self.includedWords = []
self.excludedWords = []
self.category = None
self.minSeeds = None
self.orderByField = None
def include(self, words):
self.includedWords += words.split()
... |
#python imports
import sys
import os
import subprocess
import json
import requests
from requests.auth import HTTPBasicAuth
from termcolor import colored
#third-party imports
#No third-party imports
#programmer generated imports
from logger import logger
from fileio import fileio
'''
***BEGIN DESCRIP... |
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QDial, QSpinBox
from PyQt5.QtGui import QFont
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.resize(400,300)
f = QFont('',16)
dial = QDial(self)
dial.resize(175,175)
dial.move(30,3... |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Company(models.Model):
name = models.TextField(max_length=300)
description = models.TextField(max_length=500, null=True)
def __str__(self):
return self.name
@staticmethod
def get_c... |
from rest_framework_jwt import authentication
from project.serializers import UserSerializer
from project.utils import LogUtilMixin
class JSONWebTokenAuthentication(authentication.JSONWebTokenAuthentication, LogUtilMixin):
def authenticate(self, request):
"""
Returns a two-tuple of `User` and to... |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import WebDriverException
from django.test import LiveServerTestCase
import time
MAX_WAIT = 3
class NewVisitorTest(LiveServerTestCase):
options = Opt... |
'''some functions required to calculate the co-ordinates of the key points.'''
import numpy as np
def padRightDownCorner(img, stride, padValue):
h = img.shape[0]
w = img.shape[1]
pad = 4 * [None]
pad[0] = 0 # up
pad[1] = 0 # left
pad[2] = 0 if (h%stride==0) else stride - (h % stride) # down
... |
# Expected Output
# Download
# Age is not valid, setting age to 0.
# You are young.
# You are young.
# You are young.
# You are a teenager.
# You are a teenager.
# You are old.
# You are old.
# You are old. |
print('kjshd')
print('ksjdhfkjhd') |
from pynmea.streamer import NMEAStream
from fractions import Fraction
from itertools import groupby
from math import modf
from common import *
try:
import ogr
except ImportError:
from osgeo import ogr
def fraction_to_rational(fra):
"""
Take a fraction and return a stupid Rational to make stupid dam... |
### lists
#lists are iterable (can return items one at a time)
#lists are mutable (can be changed)
#lists can be indexed
print("\nlists:")
emptylist = []
numlist = [1,2,3]
print(numlist)
#index
print("first item: ", end="")
print(numlist[0])
# len
print("lenght: ", end="")
print(len(numlist))
# add
emptylist.append... |
# -*- coding: utf-8 -*-
import unittest
from . import UnitTestBase
from moviesnotifier import TntvillageWebpage
class TntvillageWebpageTest(UnitTestBase):
def setUp(self):
html = self._read_file('tntvillage_example1.html')
self.page = TntvillageWebpage(html)
def test_recognizeCorrectlyNumberOfMovies(sel... |
# -*- coding: utf-8 -*-
"""
******************************************************************************
* @author : Jabed-Akhtar (github)
* @Created on : Fri Apr 1 03:18:48 2022
******************************************************************************
* @file : ml_DecisionTreeClassifier_Music.py... |
from classes.console.console import Console
from classes.option.fetch import OptionFetch
from classes.option.option_interface import OptionInterface
from classes.option.replace import OptionReplace
from classes.option.search import OptionSearch
from classes.yaml_parser import YamlParser
import sys
from typing import An... |
"""
virtualenv
图形界面
网络编程
TCP/IP简介
TCP编程
UDP编程
"""
# 在开发Python应用程序的时候,系统安装的Python3只有一个版本:3.4。所有第三方的包都会被pip安装到Python3的site-packages目录下。
# 如果我们要同时开发多个应用程序,那这些应用程序都会共用一个Python,就是安装在系统的Python 3。如果应用A需要jinja 2.7,而应用B需要jinja 2.6怎么办?
# 这种情况下,每个应用可能需要各自拥有一套“独立”的Python运行环境。virtualenv就是用来为一个应用创建一套“隔离”的Python运行环境。
# 首先,我们用pip安装vi... |
from progressbar import ProgressBar
from tqdm import tqdm
import numpy as np
class ClassicDE:
def __init__(self, bounds, mutation, cross_probability, normalized_population, denorm_population, population_size, iterations, clip, exp_cross, cost_function):
self.bounds = bounds
self.mutation = mutati... |
__author__ = 'Sanjarbek Hudaiberdiev'
import sys
sys.path.append('/users/hudaiber/Projects/SystemFiles/')
sys.path.append('/users/hudaiber/Projects/lib/BioPy')
from BioClasses import Gene
import globalVariables as gv
import os
from CogClasses import *
import cPickle as pickle
#Global variables
arGOGDataPath = os... |
# import re
# n = int(input())
# for i in range(n):
# print(re.sub(r'(?<= )(&&|\|\|)(?= )', lambda x: 'and' if x.group() == '&&' else 'or', input()))
import re
for _ in range(int(input())):
s = input()
s = re.sub(r" &&(?= )", " and", s)
s = re.sub(r" ||(?= )", ' or', s)
... |
import matplotlib.pyplot as plt
def main():
left_edges = [0 ,10, 20, 30, 40]
heights = [100, 200, 300, 400, 500]
plt.bar(left_edges, heights)
plt.show()
main() |
#!/usr/bin/python
from __future__ import division
import numpy as np
import pandas as pd
import sys
from sklearn import svm
from sklearn.ensemble import RandomForestClassifier
import csv
#train_file = sys.argv[1]
train_frame0 = pd.read_csv("train200_200_new1.csv")
train_frame1 = pd.read_csv("train250_250_new1.csv")
#... |
import pyspark.sql.functions as F
from pyspark.sql import DataFrame
def sample_transform(input_df: DataFrame) -> DataFrame:
inter_df = input_df.where(input_df['race'] == \
F.lit('hobbit')).groupBy('name').agg(F.sum('coins').alias('total_coins'))
output_df = inter_df.select('name'... |
import numpy as np
import math
import time
from epics import caget, caput, PV
from bokeh.driving import count
from bokeh.io import curdoc
from bokeh.models import ColumnDataSource, Slider
from bokeh.plotting import figure
from bokeh.layouts import column, row
from bokeh.models.glyphs import MultiLine
from bokeh.model... |
def Age(x):
class AGE(int): pass
v = float(x)
if v > 0 and v < 160:
return AGE(v)
exit()
def Height(x):
class HEIGHT(int): pass
v = float(x)
if v > 0 and v < 300:
return HEIGHT(v)
exit()
def Weight(x):
class WEIGHT(int): pass
v = float(x)
if v > 0 and v < 600:
return WEIGHT(v)
exit()
def Fat(x):
... |
import uuid
from django.core.cache import cache
from django.shortcuts import render
from rest_framework.exceptions import APIException
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from Admin.models import AdminUser
from Admin.serializers import AdminUserSerializer
from... |
#manipulacao de dados
num_inteira = 5
num_decimal = 7.3
val_string = "qualquer texto"
#formas de concatenacao para printagem danada de decimais
print ("Concatenando decimal: ", num_decimal)
print ("Concatenando decimal: %.42f" %num_decimal)
print ("Concatenando decimal: " + str(num_decimal))
#formas de concatenacao p... |
import unittest
from katas.kyu_7.reversed_strings import solution
class ReversedStringsTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(solution('world'), 'dlrow')
def test_equals_2(self):
self.assertEqual(solution('hello'), 'olleh')
def test_equals_3(self):
... |
import sys
import os
import time
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QPushButton, QHBoxLayout, QMainWindow, QWidget
from PyQt5.QtCore import QCoreApplication, Qt
if hasattr(Qt, 'AA_EnableHighDpiScaling'):
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
if hasattr(... |
sya = int(input("借金>"))
riritu = int(input("年利率(%)>"))
hennsai = int(input("返済額>"))
count = 0
while True:
count += 1
if sya <= hennsai:
sya = int(((sya*riritu/100)/12 + sya))
sumhen = hennsai*(count-1)+sya
print(count,"月: 返済額",sya,"円 これで完済。 返済総額:",sumhen,"円")
break
sya = in... |
print("Special prime numbers")
from math import sqrt
#Given two numbers n and k, find whether there exist at least k Special prime numbers or not from 2 to n inclusively.
#A prime number is said to be Special prime number if it can be expressed as the sum of three integer numbers: two neighboring prime numbers and 1... |
from django.db import models
from wagtail.wagtailcore.models import Page
from wagtail.wagtailadmin.edit_handlers import FieldPanel
class BlogIndexPage(Page):
intro = models.TextField()
content_panels = Page.content_panels + [
FieldPanel('intro', classname="full")
]
subpage_types = ['BlogPage... |
# Django bootstrap, sigh.
from django.conf import settings; settings.configure()
import mock
import djpjax
from django.template.response import TemplateResponse
from django.test.client import RequestFactory
# A couple of request objects - one PJAX, one not.
rf = RequestFactory()
regular_request = rf.get('/')
pjax_req... |
# _*_ coding:UTF-8 _*_
#! /usr/bin/env python
from test import *
print "是否更新控件坐标: Y or N "
updateflag = raw_input("Enter your choice: ")
if updateflag == 'Y' or 'y':
print "鼠标放到用户名框保持1S"
user_x, user_y = set_cursor_po()
time.sleep(1)
print "鼠标放到password框保持1S"
pas_x, pas_y = set_cursor_po()
time.sleep(1)
... |
from django.contrib import admin
from .models import Post, PostImage, Comment, Like
admin.site.register(Post)
admin.site.register(PostImage)
admin.site.register(Comment)
admin.site.register(Like) |
v = float(input('Salário atual: R$'))
p = v*15 / 100
n = v + p
print('Novo sálario: R${:.2f}'.format(n)) |
# 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... |
from game import Hangman
def main():
h = Hangman()
h.play_game()
if __name__ == "__main__":
main()
|
companies = [
"3m",
"american express",
"apple",
"boeing",
"caterpillar",
"chevron",
"cisco systems",
"coca-cola",
"dowdupont",
"exxonmobil",
"goldman sachs",
"the home depot",
"ibm",
"intel",
"johnson & johnson",
"jpmorgan chase",
"mcdonald's",
"merck & company",
"microsoft",
"nike",
"pfizer",
"procter & gamble",
"tra... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import math
from PyQt5.QtCore import (qAbs, QLineF, QPointF, qrand, QRectF, QSizeF, qsrand,
Qt, QTime)
from PyQt5.QtGui import (QBrush, QColor, QLinearGradient, QPainter,
QPainterPath, QPen, QPolygonF, QRadialGradient)... |
"""QtChunkReceiver and QtGuiEvent classes.
"""
from qtpy.QtCore import QObject, Signal
from napari.components.experimental.chunk import chunk_loader
from napari.utils.events import EmitterGroup, Event, EventEmitter
class QtGuiEvent(QObject):
"""Fires an event in the GUI thread.
Listens to an event in any th... |
l = [1,2,3,4]
def rec(l):
if len(l) == 0:return []
else:return [l.pop()] + rec(l)
print(rec(l)) |
#! /usr/bin/python3
import sys
import os
sys.path.insert(0, os.path.abspath('../models'))
import numpy as np
import matplotlib.pyplot as plt
import matplotlib .animation as animation
from network import Network
# x is a vector of length n*n
def plot_neurons(x, n=8):
assert x.shape == (n**2,)
X = x.reshape(... |
"""
Configuration module.
"""
import logging
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple, Union
import pytz
from gitdb.exc import BadName
from pydriller.domain.commit import Commit
logger = logging.getLogger(__name__)
class Conf:
"""
Configuration class. This class ho... |
#Import core packages
import matplotlib.pyplot as plt
import seaborn as sns; sns.set(color_codes=True)
import numpy as np
#Drop column not perceived to be features
drop_cols = ['company_permalink','company_category_code','company_country_code','company_state_code','company_city','company_region',
'... |
from aiohttp import web
from .geocoder import geocode
async def geocode_address(request):
query = request.match_info.get('query')
response = geocode(query)
return web.json_response(response)
|
###########################
# Fichier projet.py #
# 16/05/18 #
# La communauté de l'info #
###########################
from classe import *
import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as opt
import random
def chaine_to_tuple(mot):
w = ()
for i in range(len(mo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.