text
stringlengths
8
6.05M
import data dataList = data.result resultCount = 0 w, h = 1008, 1008 matrix = [[0 for x in range(w)] for y in range(h)] # iterate over dataList [#][x, y][w, h] for dataArr in dataList: x = dataArr[0][0] y = dataArr[0][1] w = dataArr[1][0] h = dataArr[1][1] # iterating over how many rows for rows in ran...
from django.shortcuts import render from datetime import datetime # Create your views here. def Wish_django(request): date=datetime.now() msg='i am proud to be an indian' my_dict={'date':date,'msg':msg} return render('request'sixthapp/display.html',context=my_dict)
import argparse import json import logging import os import random from builtins import ValueError from collections import defaultdict from io import open import numpy as np import torch import yaml from easydict import EasyDict as edict from tqdm import tqdm from evaluator import final_evaluate from mmt.metrics impo...
import calendar from datetime import date import requests import json from configparser import ConfigParser import keyboard hotkey = "ctrl + x" remind = open("reminders.txt") today = date.today() month = today.month year = today.year calendar = calendar.month(year,month) ascii_art = open("ascii_art") print(ascii_art...
# Generated by Django 2.2.2 on 2019-07-23 07:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('teachingtask', '0007_remove_teachingtask_level'), ('student', '0002_student_nick_name'), ('attendance', '0001_initial'), ] operation...
#!/usr/bin/env python3 """ Converts Satisfactory save games (.sav) into a Python dict """ import struct import sys def to_py(file_path): f = open(file_path, 'rb') # determine the file size so that we can f.seek(0, 2) file_size = f.tell() f.seek(0, 0) bytesRead = 0 def assert_fail(messag...
# -*- coding: utf-8 -*- """ =============================================================================== Cube_and_Cuboid -- A standard Cubic pore and Cuboic throat model =============================================================================== """ from OpenPNM.Geometry import models as gm from OpenPNM.Geomet...
from django.conf.urls import url from states import views from django.urls import path urlpatterns = [ url(r'^countries/(?P<country_code>[A-z]+)/states/', views.state_list), #url('^<state>', views.state_delete), url(r'^countries/(?P<country_code>[A-z]+)/(?P<state>[A-z]+)', views.state_detail), ]
from django.db import models # Create your models here. from django.contrib.auth.models import User class Company(models.Model): class Meta: db_table = 'tb_companies' name = models.CharField(max_length=100, unique=True) ceo = models.CharField(max_length=50, blank=True, null=True) phone = mod...
""" File: pydaq.py Author: Allen Sanford (ras9841@rit.edu) Description: Module of python classes and functions build to aide in data acquisition. Fitting relies on scipy's odr module. """ # Imports import matplotlib.pyplot as plt from numpy import linspace from scipy.stats import chi2 from scipy.odr import * #from...
#!/usr/bin/env python3 """ Send a result to RabbitMQ. """ import amqp import datetime import pscheduler import sys import time import urllib.parse MAX_SCHEMA = 2 log_prefix="archiver-rabbitmq" log = pscheduler.Log(prefix=log_prefix, quiet=True) class AMQPExpiringConnection(object): """ Maintains an expi...
from django.db import models from django.contrib.auth.models import User # Create your models here. class Mois(models.Model): titre = models.CharField(max_length=255) description = models.TextField() image = models.ImageField(upload_to='img', blank=True) statut = models.BooleanField(default=True) ...
import random class jobscheduling(): """this class is to handle various functions of the scheduling algorithms""" process_list = [] #a list of list to store the processes total_processes = 0 #variable to keep track of total number of processes total_time = 0 #variable to keep track o...
import random tabela = ('Santos','Palmeiras','Flamengo','Atlético-MG','Corinthians','São Paulo','Internacional','Athletico-PR','Botafogo','Bahia','Ceará SC','Goiás','Grêmio','Fortaleza','Vasco da Gama','Fluminense','Chapecoense','Cruzeiro','CSA','Avaí') print(f'Os 5 primeiros colocados são {tabela[:5]}') print(f'Os 4 ú...
import numpy as np import pytest import pyqtgraph as pg app = pg.mkQApp() @pytest.mark.parametrize('orientation', ['left', 'right', 'top', 'bottom']) def test_PlotItem_shared_axis_items(orientation): """Adding an AxisItem to multiple plots raises RuntimeError""" ax1 = pg.AxisItem(orientation) ax2 = pg.A...
import numpy as np import plotly.graph_objects as go import plotly.express as px import plotly.io as pio import plotly import seaborn as sns import matplotlib.pyplot as plt pio.renderers.default = "browser" # https://habr.com/ru/post/468295/ def generate_data(start_x, end_x, step=0.1, spread=10, bias=0): x = np...
# vim:fileencoding=utf-8:noet from __future__ import (unicode_literals, division, absolute_import, print_function) import os import re import logging from collections import defaultdict from powerline.lib.threaded import ThreadedSegment from powerline.lib.unicode import unicode from powerline.lint.markedjson.markedv...
from django.test import TestCase from django.urls import reverse from waffle.models import Switch from . import forms from .models import Registrant, Location, EmailConfirmation from .utils import generate_random_key from django.contrib.messages import get_messages from portal.services import NotifyService from porta...
#!/usr/bin/python3 import os import time import sys from binance.client import Client #init api_key = os.environ.get('binance_api') api_secret = os.environ.get('binance_secret') pair_coin_symbol=sys.argv[1] client = Client(api_key, api_secret) coin_price = client.get_symbol_ticker(symbol=pair_coin_symbol) print(co...
from onegov.core.orm.abstract import AdjacencyListCollection from onegov.gazette.models import Organization class OrganizationCollection(AdjacencyListCollection): """ Manage a list of organizations. The list is ordered manually (through migration and/or backend). """ __listclass__ = Organization ...
#!env python3 # -*- coding: utf-8 -*- import unittest from unittest import mock from unittest_mock_target import add_time, get_this_month from datetime import datetime def get_username(user): return user.username class TestMock(unittest.TestCase): def test_mock(self): dummy_object = mock.Mock() ...
from plotly.graph_objs import Bar, Layout from plotly import offline from die import Die # Create two D6 dice. die_1 = Die() die_2 = Die() # Make some rolls, and store results in a list. results = [] roll_times = 10000 for roll_num in range(roll_times): result = die_1.roll() + die_2.roll() results.append(resu...
def likes(names): if len(names) == 0: return "No one like this" elif len(names) == 1: return names[0] + " likes this" elif len(names) == 2: return names[0] + " and "+ names[1] +" like this" elif len(names) == 3: return names[0] + ", "+ names[1] + " and "+ names[2] +" like this" elif len(names...
from django.test import TestCase, SimpleTestCase from django.urls import reverse, resolve from django.contrib.auth.views import ( LogoutView, LoginView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView, ) from users.views...
im = open('006993_photoA.tif', 'rb') ord(im.read(1)) chr(ord(im.read(1)))
# add path to the src and test directory import os import sys PARENT_PATH = os.getenv('PYMCTS_ROOT') SRC_PATH = PARENT_PATH +"src/" sys.path.append(SRC_PATH+"algorithm") import mcts import connectfour_model import heuristic_model # Clear the shell os.system("clear") # Setup for MCTS model = heuristic_model.ConnectFo...
# coding: utf-8 import csv import os import numpy as np import unicodecsv # check type of values in each coulumn def checkType(data): newData=list(data) valueTypeArray=newData.pop(0) valueTypeArray=[0 for i in range (0,len(valueTypeArray))] for row in newData: for i in range (0,len(row)): ...
from enum import Enum, unique @unique class Term(Enum): FALL = 'F' WINTER = 'W' SPRING = 'SP' INDETERMINATE = 'TBD' @staticmethod def from_str(string: str): for term in Term: if term.value == string: return term assert False, 'Cannot initialize term...
from sqlalchemy.orm import Session # Local modules from data.models import users_model from data.schemas import schema_users def create_user(db: Session, user: schema_users.UserCreate): fake_hashed_password = user.password + "notreallyhashed" db_user = users_model.UserModel(email=user.email, ...
# Generated by Django 3.2 on 2021-04-21 18:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pie', '0005_alter_showchart_customer_id'), ] operations = [ migrations.AlterField( model_name='showchart', name='custo...
file_name = 'pi_digits.txt' with open(file_name) as file_object: contents = file_object.read() print(contents) with open(file_name) as file_object: for line in file_object: print(line.rstrip()) with open(file_name) as file_object: lines = file_object.readlines() for line in lines: print(...
#Circular array rotation inp = input().split(' ') n , k , q = [int(x) for x in inp] m = [] #print(n , k , q) #n -- > num of ints in arrays #k - num of rotations #q - num of queries arr = list(map(int , (input().split(' ')))) result = [] for i in range(q): m = int(input()) k = k % n...
#!/usr/bin/python import sys import os if len(sys.argv) != 2: print 'error ** usage: %s data predictions' % sys.argv[0] print 'error ** please try: majority|even_odd|logistic_regression' sys.exit() algorithm = sys.argv[1] match = 0 if algorithm == 'majority': match = 1 elif algorithm == 'even_odd': ...
import enum from datetime import datetime from api.app import db class MessageStatus(enum.Enum): RECEIVED = 'received' CONFIRMED = 'confirmed' REVOKED = 'revoked' UNDELIVERABLE = 'undeliverable' class Message(db.Model): created_at = db.Column(db.DateTime, nullable=False, default=lambda: datetim...
from math import pi, sqrt import numpy as np # This is used by other modules importing * from here # ----------physical constants---------- a0 = 5.2917721092e-11 GEVperHartree = 27.21138505e-9 # GeV per Hartree eVperHartree = 27.21138505 # eV per Hartree secPerAU = 2.41888e-17 # seconds per au time c = 137.0359990...
class Solution: def backspaceCompare(self, S: str, T: str) -> bool: sList=[] for item in S: if(item=='#'): if(len(sList)>0): sList.pop() else: sList.append(item) S="".join(sList) tList=[] for item in...
from python_helper import Constant as c from python_helper import ObjectHelper, log from python_framework import Service, ServiceMethod from domain import BrowserConstants, LoginConstants from dto import QRCodeDto @Service() class QRCodeService: browser = None booting = BrowserConstants.DEFAULT_BROWSER_BOTT...
# Generated by Django 2.2 on 2019-04-25 02:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('assets', '0009_content'), ] operations = [ migrations.AddField( model_name='content', name='file_remark'...
import dash from dash.dependencies import Input, Output, State import dash_html_components as html import dash_core_components as dcc from dash.exceptions import PreventUpdate import dash_table from dash_table.Format import Format import plotly.graph_objs as go import numpy as np from skimage import io, filters, meas...
a=1 #I went back to change 1 #changed in dev #editted in master and dev
from sklearn.feature_selection import VarianceThreshold X = [[0, 0, 1], [0, 1, 0], [1, 0, 0], [0, 1, 1], [0, 1, 0], [0, 1, 1]] sel = VarianceThreshold(threshold=(.8 * (1 - .8))) X_sel = sel.fit_transform(X) print (X) print(X_sel)
import pytest from lis import * program = '(begin (define r 10) (* pi (* r r)))' def test_tokenize(): result = ['(', 'begin', '(', 'define', 'r', '10', ')', '(', '*', 'pi', '(', '*', 'r', 'r', ')', ')', ')'] assert tokenize(program) == result def test_parse(): result = ['begin', ['define', 'r', 10], ['...
#coding:utf-8 #! /usr/bin/env python3 """ Contains the function to get the size map(map_size) and map generator(map_initialize) """ from fonction.get_file import get_file_path from config import * def map_size(file_to_open, folder_file): """ Get the size of the map for pygame windows size""" # loading of ...
# Create packed tuple. pair = ("dog", "cat", "horse") # Unpack tuple. (key, value, key2, value2) = pair # Display unpacked variables. print(key) print(value)
# 用生成器模拟多任务系统 def music(duration): index = 1 while index <= duration: print("音乐进行到第%d分钟" % index) index += 1 yield None def movie(duration): index = 1 while index <= duration: print("电影进行到第%d分钟" % index) index += 1 yield None def main(): music_iter...
# -*- coding: utf-8 -*- """ Created on Wed Aug 11 16:58:04 2021 @author: Gustavo @mail: gustavogodoy85@gmail.com """ # ============================================================================= # # 2.2 manejo de archivos # ============================================================================= # %% with ope...
import re import spacy from tqdm import tqdm # Compiled regex for tokenizer HTML_TAGS = re.compile(r"</*\w+>", re.IGNORECASE) PUNCT_START_END = re.compile(r"^\W+|\W+$") PUNCT_ANYWHERE = re.compile(r"\W") NON_ALPHANUMERIC = re.compile(r"[^a-zA-Z0-9\-\'\.]") ONLY_NUMBERS = re.compile(r"^(\d\W*)+$") # spacy English mod...
""" Probability Calculator by Sofia Zavala 04/14/2021 """ import random import copy class Hat: def __init__(self, **kwargs): """ Define the sample space. Keyword args: keys -- types of balls values -- quantity of each type """ self.contents = [key for key, value in...
#!/bin/python import sys import copy import re import math infile = open(sys.argv[1], "r") instructions = [] for line in infile: line = line.rstrip() lineM = re.match(r"(N|S|E|W|L|R|F)(\d+)", line) if not lineM: print("poop") instructions.append((lineM.group(1), int(lineM.group(2)))) #pri...
''' Title : sWAP cASE Subdomain : Strings Domain : Python Author : Darpan Zope Created : Problem : https://www.hackerrank.com/challenges/swap-case/problem ''' def swap_case(s): newstring = "" for item in s: if item.isupper(): newstring += item.lower() else: ...
import logging import threading import flask from .requests import Request __all__ = ['Skill'] class Skill(flask.Flask): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._sessions = {} self._session_lock = threading.RLock() def script(self, generator): ...
# 61. Rotate List # # Given a linked list, rotate the list to the right by k places, where k is non-negative. # # Example 1: # # Input: 1->2->3->4->5->NULL, k = 2 # Output: 4->5->1->2->3->NULL # Explanation: # rotate 1 steps to the right: 5->1->2->3->4->NULL # rotate 2 steps to the right: 4->5->1->2->3->NULL # Examp...
# def get_power_of3(x): # ''' # purpose is to do this # :param x: input character # :return: a list # :type x: integer # ''' # import itertools as it # '''itertools is a very powerful module # ''' # assert isinstance(x,int) # assert x>=1 and x<=40 # # try: #...
import globals import numpy import scipy from scipy.optimize import minimize def chisquared(vars, alignm, data, eps_data = None): if not eps_data: eps_data = len(data)*[1.0] hit = numpy.array([vars[0],vars[1]]) sum_array = [ ((data[i] - numpy.sqrt((hit - alignm[i]).dot(hit-alignm[i])) + vars[2])/ep...
import nltk from nltk import word_tokenize import json states = [] observations = [] transition_probability = {'<S>' : {"<E>" : 0}} emission_probability = {} previousObservations = [] previousTags = [] def train(data="data.txt"): file = open("data.txt", "r") for line in file: text = word_tok...
#!/usr/bin/env python # By Jacek Zienkiewicz and Andrew Davison, Imperial College London, 2014 # Based on original C code by Adrien Angeli, 2009 import random import os import time import math import brickpi interface=brickpi.Interface() interface.initialize() #Sonar Motor motor = 2 #Wheel motors motors = [3,1] in...
"""Author Arianna Delgado Created on May 28, 2020 """ """Display numbers from 50 t0 70""" for i in range(50,71): print(i)
import os import sys cur_path = os.getcwd() sys.path.insert(0, '/'.join(cur_path.split('/')[:-1])) import unittest from parser.course import Course from parser.coursecode import CourseCode from parser.term import Term from parser.unitrange import UnitRange from storage.DBProxy import DBProxy from storage.preprocesso...
# wrapper script around py.test so coverage can run py.test from inside tox import sys import pytest sys.exit(pytest.main())
from flask import Flask, request, jsonify, render_template from flask.globals import request from flask.json import jsonify from clarifai_grpc.channel.clarifai_channel import ClarifaiChannel from clarifai_grpc.grpc.api import service_pb2_grpc import fs stub = service_pb2_grpc.V2Stub(ClarifaiChannel.get_grpc_channel()) ...
from sqlobject import * from sqlobject.sqlbuilder import * from ceo import conf from ceo import members from ceo import terms import time from datetime import datetime, timedelta CONFIG_FILE = "/etc/csc/library.cf" cfg = {} def configure(): """ Load configuration """ cfg_fields = [ "library_connect_s...
from ED6ScenarioHelper import * def main(): # 调试地图 CreateScenaFile( FileName = 'T0034 ._SN', MapName = 'map1', Location = 'T0030.x', MapIndex = 1, MapDefaultBGM = "ed60010", Flags = 0, E...
def quicksort(lista): quicksort_aux(lista,0,len(lista)-1) def quicksort_aux(lista, inicio, fin): if inicio < fin: pivote = particion(lista, inicio, fin) quicksort_aux(lista, inicio, pivote-1) quicksort_aux(lista, pivote+1, fin) def particion(lista, inic...
from tkinter import * from tkinter import messagebox import listfile as fileloc import module_addword as modAddword import module_checkfile as modCheckfile import module_find as modFind import module_history as modHist main = Tk() main.bind("<Escape>", exit) main.geometry("700x700") main.resizable(width =...
__author__ = 'gjbelang' import pickle from athlete_list import AthleteList def get_coach_data(filename): try: with open(filename) as f: data= f.readline() templ = data.strip().split(',') return AthleteList(templ.pop(0), templ.pop(0), templ) except IOError as ioerr: ...
from django.urls import path from rest_framework.urlpatterns import format_suffix_patterns from gen import views urlpatterns = [ path('gen/', views.generate) ] urlpatterns = format_suffix_patterns(urlpatterns)
from django.contrib import admin from simple_history.admin import SimpleHistoryAdmin from .models import Practice from contacts.models import Contact from core.actions.export_to_csv import export_to_csv class ContactInline(admin.StackedInline): model = Contact extra = 1 class PracticeAdmin(SimpleHistoryAdmi...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import torch.optim as optim from utils.helpers import Experience class Agent(object): def __init__(self, args, env_prototype, circuit_prototype): # logging self.mode = args.mo...
# Python Do-While loop to catch upper and lower boundaries levels while True: N = int(input("Type the number of competitors: ")) if 2 <= N <= 10000: break # create an list lst = [] # append the values into the list by iterating with the range of the numbers of competitors for i in range(N): number...
<<<<<<< HEAD # -*- coding: utf-8 -*- from django.shortcuts import render from django.views.generic.base import View from pure_pagination import Paginator, PageNotAnInteger from django.shortcuts import redirect from itertools import chain import docker import socket import urllib3 import time import random from .model...
import sys input = sys.stdin.readline from collections import defaultdict def main(): N, M = map( int, input().split()) X = list( map( int, input().split())) d = defaultdict( int) Same = [0]*M Mod = [0]*M for x in X: Mod[x%M] += 1 if d[x] > 0: d[x] = 0 Sam...
from flask import Flask from flask_ask import Ask, statement, question, session from bs4 import BeautifulSoup import json import requests import time import unidecode # import urllib2 # import ssl # This restores the same behavior as before. # context = ssl._create_unverified_context() # urllib.urlopen("https://no-va...
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) switch_pin = 23 GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) while True: if GPIO.input(switch_pin) == False: print("Button Pressed") time.sleep(0.2)
import tensorflow as tf from tensorflow.contrib import slim from graph_lm.models.networks.utils.dag_utils import message_passing from ...stats import get_bias def vae_decoder_dag_supervised(latent, dag, dag_bw, vocab_size, params, tags, tag_size, weights_regularizer=None, is_training=True): # latent (N, L, D) ...
from django.contrib import admin from .models import Post # Register your models here. class PostAdmin(admin.ModelAdmin): list_display=('id','title','created','author') admin.site.register(Post,PostAdmin)
from .S2Identified import S2Identified from .terms import Prov from .terms import SBOL2 from rdflib import URIRef from rdflib.namespace import RDF class S2ProvAssociation(S2Identified): def __init__(self, g, uri): super(S2ProvAssociation, self).__init__(g, uri) @property def agent(self): ...
"""discreteplot Make plots from data for discrete distributions. Usage: plot.py [-v] [-q] infect <filename1> <filename2> plot.py [-v] [-q] detect <filename1> plot.py [-v] [-q] quarantine <filename1> plot.py [-v] [-q] locations <filename1> [--cutoff=CUTOFF] plot.py [-v] [-q] disease <filename1> <fi...
import sys import time from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait # Login credentials login = { 'userName': '<inputUserName>', 'password': '<inputPassword>' }...
from rest_framework import permissions class UpdateOwnProfile(permissions.BasePermission): """ Allow users to edit their own profiles """ def has_object_permission(self, request, view, obj): """ Check user has permissions to edit their own profiles """ #checks if the action falls under SAFE...
"""Abstract base classes for GaussianFamily statistics. """ from __future__ import annotations from typing import Optional, Sequence, final from abc import abstractmethod import sacc import pyccl import pyccl.nl_pt from .....modeling_tools import ModelingTools from .....parameters import ParamsMap from .....updatab...
#!/usr/bin/env python # coding: utf-8 # In[11]: import math import re import sys import matplotlib.pyplot as plt import os import numpy as np # In[12]: train_data_directory = "train/" # ### Word Count # In[13]: ham_dictionary = {} # stores words in ham files and their frequencies spam_dictionary = {} ...
import pygame from inputManager import InputManager from gameObject import game_objects, GameObject, add from map.canvas import Background from map.matrixMap import generate_map from point import Point from boxes import Boxes from createPlayer import createplayer,playerL from createBoxes import createBoxes, bs from c...
from django import forms from django.contrib.auth.models import Group from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import UserProfile, City, Post from django.contrib.auth.models import User class RegistrationForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInp...
participant = ["iksu", "ingyu", "inan", "iksu"] completion = ["iksu"] d = {} for x in participant: d[x] = d.get(x, 0) + 1 for x in completion: d[x]-=1 dnf = [k for k,v in d.items() if v > 0] # keys in dict, if v > 0 append to array print(dnf)
from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.models import Group, User from .forms import CreateUserForm from .decorators import unauth...
import pandas as pd import yfinance as yf import csv import requests import numpy as np from pathlib import Path import sqlalchemy as sql # Pulling S&P Data from wiki and outputing html url = 'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies' # Read html sp500_html = pd.read_html(url) # Obtain first table s...
from datetime import datetime from auth import jwt import json import psycopg2 def authenticate(cursor, unique_id, token, secret): valid, data = jwt.verifyJWT(token, secret) if valid: #fetch token from database query = 'SELECT token FROM tokens WHERE owner_unique=\'{}\';'.format(unique_id) ...
#!/usr/bin/python3 def weight_average(my_list=[]): if not my_list: return 0 else: numerator = float(sum(x[0]*x[1] for x in my_list)) denominator = float(sum(y[1] for y in my_list)) return numerator / denominator
# -*- coding: utf-8 -*- """ Created on Tue May 15 11:05:38 2018 @author: fahad @contributor: Lianxin Zhang """ import time import xlsxwriter import random from collections import deque import globalvar as gl from ina219 import INA219 from ina219 import DeviceRangeError def sensor(): ...
def print_frames(audio_frames): print(audio_frames)
from collections import OrderedDict import json import os import matplotlib.pyplot import matplotlib.pyplot import numpy as np import sklearn.cluster import distance from nltk.stem.wordnet import WordNetLemmatizer class HelperFunctions(object): ASC = 1 DESC = 0 KEY = 0 VALUE = 1 @staticmethod ...
import requests import json import random VK_API = 'https://api.vk.com/method/{0}?{1}' class VkApi: def __init__(self, domain, method_name): self.domain = domain self.method_name = method_name self.count = '10' if domain.startswith('-') == False: self.paramaters = 'd...
# (c) 2012 Urban Airship and Contributors from django.test import TestCase from mithril.decorators import exempt, resettable import random class TestOfMithrilDecorators(TestCase): def test_exempt_attaches_appropriate_flag(self): anything = lambda *a: a expected = random.randint(0, 10) ...
n = int(input("Enter number n: ")) m = int(input("Enter number m: ")) if n % 10 > m % 10: print(n) elif n % 10 < m % 10: print(m) else: if n > m: print(n) elif n < m: print(m) else: print("n is equal to m")
# encoding:utf-8 __author__ = 'hanzhao' import sys def run(msg): print '[info] 魔方小工具模块载入中。。' if '<br/>' in msg: #为群聊消息时候 [FromUser,msg] = msg.split('<br/>') else: #为个人消息时候 pass if msg in ['打开计时器','.计时器']: print '[tool]自动回答' return 'http://zht...
from Flask import Flask, render_template, request, session, redirect, url_for ##import utils app = Flask(__name__) @app.route("/") @app.route("/home") @app.route("/home/") def home(): if "logged_in" in session and session["logged_in"]: return render_template("home.html") else: return redirect(...
for a in range(1,10): for b in range(1,10): for c in range(a+1,10): if (10*a+b)/(10*b+c) == a/c: print(10*a + b, 10*b + c)
from django.shortcuts import render, render_to_response from django.http import HttpResponse, HttpResponseRedirect from django.template import RequestContext from .models import * from .forms import * from django.views.generic import TemplateView, CreateView, DetailView, UpdateView, DeleteView # Create your views here....
# if temperature is greater than 30, it's a hot day other wise if it's less than 10; # it's a cold day;otherwise,it's neither hot nor cold. temperature=int(input("enter the number: ")) if temperature>30: print("it's hot day") elif temperature<10: print("it's cold day") else: print("it's neither hot nor col...
from OOP.PlanetSystem_VV import solarsystem, planet import numpy as np n = 10000 h = 0.01 Earth_mass = 6.0E24/2.0E30 Sun_mass = 1 Earth_posx = 1.0 Earth_posy = 0 Sun_posx = 0 Sun_posy = 0 Earth_velx = 0 velocitys = np.linspace(8.5, 9.5, num=100) #Grid search over posible velocities for Earth_vely in velocitys: ...