text
stringlengths
8
6.05M
""" Tests for :mod:`nova_api` and :mod:`nova_objects`. """ from __future__ import absolute_import, division, unicode_literals import json from six import text_type from six.moves.urllib.parse import urlencode, parse_qs from testtools.matchers import ( ContainsDict, Equals, MatchesDict, MatchesListwise, StartsWit...
from _typeshed import Incomplete def bethe_hessian_matrix( G, r: Incomplete | None = None, nodelist: Incomplete | None = None ): ...
from datetime import date atual = date.today() menor = 0 maior = 0 for c in range(1, 8, 1): nasc = int(input(f'Em que ano a {c}ª pessoa nasceu? ')) if (atual.year - nasc) < 18: menor += 1 else: maior += 1 print(f'\nAo todo tivemos {maior} pessoas maiores de idade') print(f'E também tivemos ...
import numpy as np import cv2 as cv import dlib img= cv.imread('pic.jpg') ogimg=img gray= cv.cvtColor(img,cv.COLOR_BGR2GRAY) canny = cv.Canny(gray,125,150) cv.imshow('cannys',canny ) contours,hierarchy=cv.findContours(canny.copy(),cv.RETR_TREE,cv.CHAIN_APPROX_NONE) print(len(contours)) areas=[] for cn...
# -*- coding: utf-8 -*- """ Created on Wed May 6 11:33:29 2020 @author: juanc """ # Import needed functionality import matplotlib.pyplot as plt from collections import Counter def plot_counter(counter, n_most_common=5): # Subset the n_most_common items from the input counter top_items = counter.most_common(...
# Copyright (c) 2012 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'target2', 'type': 'none', 'sources': [ '../touch.py' ], 'rules': [ { ...
""" Testing CSVLogger """ class CSVLogger(BaseLogger): def __init__( self, evaluator, log_dicts=None, train_log_dicts=None, val_log_dicts=None, log_dir="./logs", filename="logs.csv", **kwargs, ): """Initiate a CSV logger. Summar...
import tensorflow as tf from tensorflow.python.ops import math_ops from tensorflow.contrib.cudnn_rnn.python.ops import cudnn_rnn_ops from my.tensorflow.cudnn_recurrent_layers import CudnnLstm, CudnnGru VERY_NEGATIVE_NUMBER = -1e29 def exp_mask(val, mask): mask = tf.cast(tf.sequence_mask(mask, tf.shape(val)[1]), tf...
from arcgis_terrain import get_terrain_map from arcgis.features import FeatureLayer from arcgis.gis import GIS from arcgis_terrain import lat_lon2meters from arcgis_terrain import meters2lat_lon import time from arcgis.geometry.filters import envelope_intersects import arcgis.geometry import numpy as np import plotly....
__author__ = 'Justin' import os import json import matplotlib.pyplot as plt import numpy as np import matplotlib.mlab as mlab from collections import deque # DESCRIPTION: this script will provide a simulation of the gradient ascent/descent method's performance # # Load Characterization from file # Load Data cwd = ...
import datetime import programs import unittest class TestLightProgram(unittest.TestCase): def setUp(self): self.morning_program = programs.LightProgram("weekday", "morning", {"start_at": "08:15", "duration": 3600, "brightness": 100}) self.evening_program = programs.LightProgram("weekday", "evenin...
import sys sys.path.append('.') from django.db import models # Create your models here. class Team(models.Model): name = models.CharField(max_length=100, null=False) description = models.CharField(max_length=250, null=True) class Sport(models.Model): name = models.CharField(max_length=100, null=False) ...
# @Time : 2018-10-24 # @Author : zxh # 测试 import requests r = requests.get('http://192.168.213.51:8899/test1') print(r.json()) r = requests.post('http://192.168.213.51:8899/test1', json={'key': 1}) print(r.json())
import pandas as pd import time import os import multiprocessing as mp import traceback import logging import sys logging.basicConfig(filename='logs.log', filemode='a', format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s', ...
import math def countBits(n): counter = 0 while(n >0): num = n%2 n = math.floor(n/2) if(num==1): counter +=1 return counter #clever solution: return bin(n).count("1") :(
# Write a Python program to replace the last element in a list with another list def replace(list1,list2): list1[-1]= list2 return list1 list1 = [1,2,3] list2 = [4,5] output = replace(list1,list2) print(output)
import tensorflow as tf from tensorflow.keras import datasets, layers, models class CnnModel: def __init__(self): self.train_images = None self.train_labels = None self.test_images = None self.test_labels = None self.model = None def execute(self): self.download...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-04-15 09:01:45 # @Author : Fallen (xdd043@qq.com) # @Link : https://github.com/fallencrasher/python-learning # @Version : $Id$ # random 模块 import random # 左闭右开,获取 [0.0,1.0) 范围内的一个浮点数,不接收参数 # random.random() a = random.random() print(a) # 左闭右开, 获取 [a...
#!/usr/bin/env python """ * asas_catalog.R in Python ** input parameters: - deboss arff fpath - asas arff fpath - features to exclude ** output: - asas_randomForest.Rdat fpath - classifier effeciency metrics ** I want to call the full AL R script, but be able to modify some bits. *** wrap...
import numpy as np from getmem import GetMem from plot_dirSpec import plot_dirSpec data = np.loadtxt('teste_spec.txt') freq = data[:,0] energy = data[:,2] a1 = data[:,4] b1 = data[:,5] a2 = data[:,6] b2 = data[:,7] E = np.tile(energy, (360,1)).T norm_mem= GetMem(a1,b1,a2,b2) dirSpec = E*norm_mem dirSpec = dirSpec...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, with_statement import random import string from revolver.core import sudo from revolver import command, package, file, service from revolver import contextmanager as ctx from revolver import directory as dir def _preseed_server(root_password...
from apps.api.stats.serializers import type as serializers from apps.games.models import Game from django.core.cache import cache from django.db.models import Avg, Max, Min from utils import constants def get_count_per_year(request): key = 'stats_v2_count_per_year' context = cache.get(key) if context is...
"""百度ip地址定位api简单封装 详细请参考文档:http://developer.baidu.com/map/ip-location-api.htm """ import json from urllib.parse import urlencode from urllib.request import urlopen class BaiduIp(): url = 'http://api.map.baidu.com/location/ip?' def __init__(self, ak, ip='', coor='bd09ll'): self.ak = ak self....
from django.urls import path from rest_framework_simplejwt import views as jwt_views from .views import CustomUserCreate, Hello urlpatterns = [ path('user/create/', CustomUserCreate.as_view(), name="create_user"), path('user/hello/', Hello.as_view(), name="hello_user"), path('token/obtain/', jwt_views.Toke...
from person import person class Agent(person): def __init__(self, age: int, sex: chr, receptivity: float, infected_with: dict = dict(), visited_nodes: list = list()): super().__init__(age, sex, receptivity, infected_with) self.visited_nodes = visited_nodes
# -*- coding: utf-8 -*- from plone.dexterity.content import Container from sc.photogallery.interfaces import IPhotoGallery from zope.interface import implementer # BBB: for content created with version 1.0a1 import sys sys.modules['sc.photogallery.content.photogallery'] = sys.modules[__name__] # noqa: I003 @impleme...
''' Created on 01/02/2013 @author: rafael.cunha ''' #from model import from appController import SessionManager def test_check_credentials_ok(): assert(SessionManager.check_credentials('Rafael') <> None) def test_check_credentials_nok(): assert(SessionManager.check_credentials('rafael') is None)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __version__ = '1.0.1' """ This module exports the db meta data.""" from sqlalchemy import MetaData # from sqlalchemy import create_engine # from web_backend.config import DATABASE # engine = create_engine('{0}://{1}:{2}@{3}:{4}/{5}'.format( # DATABASE['type'], # ...
import kivy from kivy.uix.label import Label as lb from kivy.uix.gridlayout import GridLayout as gl from kivy.uix.button import Button as btn from kivy.clock import Clock from kivy.app import App from kivy.uix.image import Image from kivy.uix.floatlayout import FloatLayout as fl import time as dt start=dt.time_ns() c...
import fileModule def main(args): filename = args['fileid'] fm = fileModule.FileManager() data = fm.loadFile(filename) return{"return": data.read()}
DAYS = {'Monday': lambda a: a == 12, 'Tuesday': lambda b: b > 95, 'Wednesday': lambda c: c == 34, 'Thursday': lambda d: d == 34, 'Friday': lambda e: e % 2 == 0, 'Saturday': lambda f: f == 56, 'Sunday': lambda g: abs(g) == 666} def am_I_afraid(day, num): """ am_i_afr...
from behave import * from behave_webdriver.transformers import matcher_mapping try: from urllib.parse import urlparse except ImportError: from urlparse import urlparse if 'transform-parse' not in matcher_mapping: use_step_matcher('re') else: use_step_matcher('transform-re') @given('the element "([^"]...
Objects and Data Structures Assessment Test Test your knowledge. ** Answer the following questions ** Write a brief description of all the following Object Types and Data Structures we've learned about: . Numbers: they represent intergers and floats in python. Integers being whole numbers and floats being decimals. ...
vocales="aeiouAEIOU" cambio=" " result=str.maketrans(vocales,cambio) palabra=str(input("ingresa la palabra:")) sin_espacios=palabra.translate(result) print(sin_espacios.replace(' ',''))
from situation import Situation from evaluate import pivotal, pivotality, criticality, prob_pivotal from draw import draw, highlight_cause_effect import matplotlib.pyplot as plt ''' simulates the case parameters: int case number dict loaded input file return: None ''' def simulate(file, **attr): data = {} if...
import string from itertools import chain def split_text_by_sentences(text): """Split a text by words. Another approach: `[word.strip(string.punctuation) for word in input_text.split() if word not in string.punctuation]` """ sentences = [] for sent in text.split('.'): new_sent = '' ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [("organisations", "0053_auto_20180705_1041")] operations = [ migrations.RunSQL( """ UPDATE organisations_organisationgeograp...
name = input("请输入你的名字:") print("你好" + name + "!")
from sys import argv # 调用kkk.txt好了 script, input_file = argv def print_all(f): print(f.read()) def rewind(f): f.seek(1)#因为read()运行一次将指针放到了末尾,所以后文中调用read()后需要seek(0)将指针 #放到起始位置。而readline()不需要的原因是因为顺序输出,每次指针调用到当行的结尾不会影响 #下一行的读取。 #其实不是很懂seek的用法。#作为指针移动到某一处?所以不改变内容? def print_a_line(line_coun...
# -*- coding: utf-8 -*- import pytest from django.core.management import call_command from django import forms from chloroform.models import ( Configuration, Metadata, ) @pytest.mark.django_db def test_configuration_get_default(): call_command('loaddata', 'chloroform/tests/test_models.yaml') c = C...
def BubbleSort(ara): for i in range(0,len(ara)-1): for j in range(0,len(ara)-1-i): if (ara[j+1]<ara[j]): ara[j],ara[j+1] = ara[j+1],ara[j]#ShortCut Swap Technique '''tem = ara[j] ara[j] = ara[j+1] ara[j+1] = tem''' return ara a...
value_in_meters = int(input('Enter value in meters:')) value_in_kilometers = float(value_in_meters / 1000) print(value_in_kilometers, 'km')
import torch import torch.nn.functional as F class AttenNet(torch.nn.Module): """ Args: """ def __init__(self, dim_embeddings,similarity='inner_product'): super(AttenNet, self).__init__() self.hidden_size = 256 self.lstm1 = torch.n...
from django.db import models # Create your models here. class EnterName(models.Model): first_name = models.CharField(max_length = 120) last_name = models.CharField(max_length = 120) def __unicode__(self): return self.first_name class Profile(models.Model): food = models.CharField(max_length = 120) first_name...
#!/usr/bin/env python # -*- coding:utf-8 -*- print('\n', '-' * 20, ' 格式化字符串 ', '-' * 20) # 1、不指定位置,按默认顺序 print('{} {}!'.format('hello', 'world')) # 2、指定位置,按位置使用,可以重复使用 print('我叫{1}{0},姓{1},名{0}。'.format('令珂', '孟')) # 3、指定名称参数 print('网站名:{name},地址:{url}'.format(name='runnoob', url='www.runnoob.com')) # 4、使用字典设置参数...
# Copyright 2016 Michael Rice <michael@michaelrice.org> # # 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 a...
from selenium import webdriver link = "http://suninjuly.github.io/registration1.html" try: browser = webdriver.Chrome() browser.get(link) input1 = browser.find_element_by_css_selector('.first_block .first') input1.send_keys("Ivan") input2 = browser.find_element_by_css_selector('.first_b...
a,b=[int(x) for x in raw_input().split(":")] c,d=[int(x) for x in raw_input().split(":")] def getA(e): global a if e>=c: a=e-c else: a=24+e-c if b>=d: b = b-d getA(a) else: b=60+b-d a=a-1 getA(a) if a<10 and b<10: print "0"+str(a)+":"+"0"+str(b) if a>10 and b<10...
# Generated by Django 2.2.20 on 2021-07-20 14:38 from django.db import migrations from django.db.models import JSONField class Migration(migrations.Migration): dependencies = [ ("elections", "0059_election_tags"), ] operations = [ migrations.AlterField( model_name="election",...
n = int(input()) for i in range(n): arr = list(map(int,input().strip().split()))[:n] print(arr)
# This is a Testcase for Decred, see https://wiki.decred.org/Block_Header_Specifications # # ocminer - admin AT suprnova.cc 16/02/01 # # Teststart refers to the original block header bytes from the example given on the page # The Hash must return df03ea8cb4a6f201c3e726f2f922a9249b39129bb59fa593ceb172e0f7c14d6e if your ...
# -*- coding: utf-8 -*- """ Created on Mon Jan 23 20:26:06 2017 @author: varar """ print("HelloWorld")
# -*- coding: utf-8 -*- from datetime import datetime from app.database.models import GitHubCommit REPO = 'teradici/deploy' commits = [ GitHubCommit('user1', 'user1@mock,com', 1, datetime.now(), '0001'), GitHubCommit('user1', 'user1@mock,com', 1, datetime.now(), '0002'), GitHubCommit('user2', 'user2@moc...
from .uppercase import uppercase_filter as uppercase from .urlencode import urlencode_filter as urlencode
import os import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch import optim from scipy.misc import imread, imsave,imresize from torchvision import transforms from argparse import ArgumentParser from networks import * from fp16Optimizer import Fp16Optimizer # from apex.fp16_ut...
import matplotlib.pyplot as plt import numpy as np from sklearn.utils import shuffle import math def compute_y(x, W, bias): # dreapta de decizie # [x, y] * [W[0], W[1]] + b = 0 return (-x * W[0] - bias) / (W[1] + 1e-10) def sigmoid(x): return 1 / (1 + math.exp(-x)) def plot_decision(X_, W_1, W_2, ...
from tkinter import * from tkinter import ttk root = Tk() root.title('Jwngdaocrypto') root.resizable(True,True) root.configure(background='blue') root.frame_header = ttk.Frame() ttk.Label(root.frame_header, text = 'CRYPTOGRAPHY', style = 'Header.TLabel').grid(row = 0, column = 1) #########################...
#!/usr/bin/python3 from app import app import os app.debug = True port = int(os.environ.get("PORT", 5000)) app.run(host='0.0.0.0', port=port)
import pytest from unittest import mock import builtins def any_or_all(): n = input('') num=input('') numbers = list(str(num).split()) return all(int(x) >= 0 for x in numbers) and any(int(x) == int(str(x)[::-1]) for x in numbers) def test_any_or_all(): with mock.patch.object(builtins, 'input', l...
from rest_framework import serializers from .models import Movie, ShowingRoom, Showing, Order from django.db.models import Q, F from .models import Status class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = ['id', 'name', 'description'] class ShowingRoomSeriali...
from google.cloud import bigquery import json class BigQueryClient: """ Extracts data from Google BigQuery This class will not function without the json key. """ query = 'SELECT * FROM `fh-bigquery.reddit_comments.2015_01` ' def __init__(self, key_path = None): if key_path is None: ...
''' Fizz Buzz ''' three = False five = False x =0 while x <16: x += 1 three = False five = False if x%3 == 0: three = True if x%5 == 0: five = True if three and five: print "Fizz Buzz" elif three: print "Fizz" eli...
from django.contrib import admin import shop.models admin.site.register(shop.models.Category) admin.site.register(shop.models.Item)
from django.conf.urls import url from .views import * urlpatterns = [ url(r'upload',UploadPhoto.as_view()) ]
# -*- coding: utf-8 -*- from setuptools import setup, find_packages import os version = open(os.path.join("sc", "newsletter", "creator", "version.txt")).read().strip() setup(name='sc.newsletter.creator', version=version, description="Creates HTML for sending newsletter", long_description=open(os.pat...
num_tests = int(raw_input()) for test_index in range(num_tests): array_size = int(raw_input()) array = map(int, raw_input().split()) max_flips = int(raw_input()) stripes = [] gaps = [] total_zeroes = 0 max_stripe = 0 firstOneFound = False curr_gap = 0 curr_stripe = 0 old_bi...
c.tabs.position = "top" c.completion.shrink = True c.url.searchengines = { "DEFAULT": "https://duckduckgo.com/?q={}", "aw": "https://wiki.archlinux.org/?search={}", "red": "https://reddit.com/r/{}" }
"""This program checks for palindrom""" import string original_str = input("Enter string to check: ").lower() #change original case to lower case # modified_str = original_str.lower() bad_chars = string.whitespace + string.punctuation modified_str = '' #check and store good characters for char in original_str: ...
import pandas as pd import numpy as np import sys def parse(infile, outfile): df = pd.read_csv(infile, sep="\t") df = df.dropna(axis='columns', how='all') if len(df.columns) != 22: return names = [ "time", # sec "q1", "q2", "q3", # rad "dq1", "dq...
# Implementation of classic arcade game Pong # works but still needs some changes, run in codeskulptor import simplegui import random # initialize globals - pos and vel encode vertical info for paddles WIDTH = 600 HEIGHT = 400 BALL_RADIUS = 20 PAD_WIDTH = 8 PAD_HEIGHT = 80 HALF_PAD_WIDTH = PAD_WIDTH / 2 HALF_PAD_HEIGH...
#!/usr/bin/python -tt # # Copyright (c) 2009, 2010, 2011 Intel, Inc. # # This program is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License as published by the Free # Software Foundation; version 2 of the License # # This program is distributed in the hope that i...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('neighborhood', '0001_initial'), ] operations = [ migrations.CreateModel( name='Budg...
import asyncio import sys from pathlib import Path from time import perf_counter from urllib.parse import urlsplit import aiofiles import aiohttp from torchvision import models from tqdm.asyncio import tqdm async def main(download_root): download_root.mkdir(parents=True, exist_ok=True) urls = {weight.url for...
class Indicator: def __init__(self, utils, config, logger, timeframe): self.logger = logger self.utils = utils self.cfg = config self.timeframe = timeframe async def analyze(self): raise NotImplementedError("Please implement this method u.u")
from google.appengine.ext import db class Poem(db.Model): title = db.StringProperty(required=True) text = db.TextProperty(required=True) page = db.StringProperty(required=False) written = db.StringProperty(required=False) created = db.DateTimeProperty(auto_now_add = True) class Comment(db.Mo...
name = ['hsj','yrq','zc',['shjd','shgdh'],'lgm','frt'] '''name2 = name print(name) print(name2) name2 = name.copy() name[2] = 'hsk' print(name) print(name2)''' #name2 = name[:] #name2 = name[0:-1] #name[3] = 'hsk' #print(name) #print(name2) import copy name2 = copy.deepcopy(name) name[3][0] = 'hsk' print(name) print(na...
# File : i2c_test.py import time import math import signal import sys from i2c_base import i2c_sensor from i2c_compass import compass from i2c_accel import accel from i2c_fusion import fusion f = None def signal_handler(signal,frame): global f f.reader_stop() sys.exit(0) if __name__=="__main__": p...
import requests import json import os import time class Baidu: def __init__(self): self.path = os.path.abspath(".") self.url = "https://image.baidu.com/search/acjson" self.pages = 0 self.params = { "tn": "resultjson_com", "ipn": "rj", ...
import requests import json import os from datetime import date from requests.exceptions import HTTPError from config import Config def login(config): url = config['url']+config['auth_point'] headers = {"content-type": "application/json"} data = {"username": config['username'], "passwor...
import urllib2 from django.dispatch import receiver, Signal from django.db.models.signals import post_init, post_save, pre_save from prezisb.models import Prezentation from django.core.files import File from django.core.files.temp import NamedTemporaryFile @receiver(post_save, sender=Prezentation) def prezentation_po...
# O(n^2) def genome_sort(seq): i = 0 while i < len(seq): if i == 0 or seq[i - 1] <= seq[i]: i += 1 else: seq[i], seq[i - 1] = seq[i - 1], seq[i] i -= 1 def main(): seq = [1, 5, 3, 4, 6, 2] genome_sort(seq) print("".join(str(seq))) if __name__ =...
from model.group import Group from utils.formatstrings import FormatStrings from model.contact import Contact import allure def test_verify_group_list(app, db): with allure.step("Given list of groups got from home page and list of groups got from db"): ui_list = app.group.get_group_list() db_list =...
import random import itertools as it def point1(parent1, parent2): """Basic 1 point crossover for lists""" if len(parent1) < 2: return [] parent1, parent2 = list(parent1), list(parent2) point = random.randint(1, len(parent1) - 1) return [parent1[:point] + parent2[point:], paren...
import argparse import csv import datetime import json import logging import os import secrets from collections import OrderedDict, defaultdict, deque from functools import lru_cache from bs4 import BeautifulSoup from wta_scrapper.mixins import Mixins from wta_scrapper.models import Query from wta_scrapper.score impo...
import discovery_query import pytest import json def read_json_file(file_path): """Reads and parse a json file. Parameters ---------- file_path : {str} the path to the json file. Returns ------- dict : a dictionary containing the json structure read from the file. """ with open(f...
import random database = {} account = 100 #initialization def init(): print("Welcome to bankPHP") AccountAvailability = int(input("Do you have account in our bank? 1(Yes) 2 (No) \n")) if AccountAvailability == 1 : login() elif AccountAvailability == 2 : print(register()) else: ...
from sqlalchemy import Column, String, Float, Integer from model.Base import Base class Plan(Base): __tablename__ = 'plan' id = Column(Integer, primary_key=True) lp = Column(String, unique=True) easting = Column(Float) northing = Column(Float)
# -*- coding: utf-8 -*- """ Created on Mon May 20 23:01:44 2019 @author: HP """ x="0ABCBDA" y="0BDCABA" def LCS(x,y): m=len(x)-1 n=len(y)-1 c=[[0 for i in range(0,n+1)] for j in range(0,m+1)] b=[[0 for i in range(0,n+1)] for j in range(0,m+1)] for i in range(1,m+1): for j in range(1,n...
import streamlit as st import time st.title('Streamlit 超入門') st.write('プレグレスバーの表示') 'Start!!' latest_iteration = st.empty() bar = st.progress(0) for i in range(100): latest_iteration.text(f'Iteration {i+1}') bar.progress(i + 1) time.sleep(0.1) #st.write('DataFrame') # df = pd.DataFrame( # np.ran...
from eagles_ml.app import db db.create_all()
from flask import Flask, request, redirect, session, json, g, render_template, flash, abort from flask_sqlalchemy import SQLAlchemy from flask_openid import OpenID from flask_sslify import SSLify from wtforms import Form, BooleanField, TextField, PasswordField, validators, SelectField import urllib2 import werkzeug imp...
class Room: def __init__(self,descr): self.__descr = descr self.__north = None self.__south = None self.__east = None self.__west = None def __str__(self): return str(self.__descr) def getNorth(self): return self.__north def getS...
# setup.py from setuptools import setup, find_packages setup( name='appconfig', version='0.0', author='', author_email='lingweb@shh.mpg.de', description='Remote control for DLCE apps', keywords='fabric', license='Apache 2.0', url='https://github.com/shh-dlce/appconfig', packages=f...
from django.db import models class TodoItem(models.Model): # todo_id = models.IntegerField() title = models.CharField(max_length=200) content = models.TextField() due_date = models.DateTimeField() def __str__(self): return self.title
def arr2bin(arr): return False if len([x for x in arr if type(x)==int])!=len(arr) else bin(sum(arr))[2:] ''' Given an array containing only integers, add all the elements and return the binary equivalent of that sum. If the array contains any non-integer element (e.g. an object, a float, a string and so on), re...
#Author: James Nicholson #Date: 6/5/2018 #Ask the user for a string and print out whether this string is a palindrome or not. # (A palindrome is a string that reads the same forwards and backwards.) def reverse(word): x = '' for i in range(len(word)): x += word[len(word)-1-i] return x word = input('give me a w...
import click import datetime from random import randint from math import floor from flask.cli import with_appcontext from .models import Proposal, db from grant.milestone.models import Milestone from grant.comment.models import Comment from grant.utils.enums import ProposalStatus, Category, ProposalStage from grant.us...
import abc class Scheduler(object): """ This class is an abstract class for Schedulers - Actual scheduler implementations need to provide these methods, and should also provide an implementation of the TaskQueue base class. """ __metaclass__ = abc.ABCMeta @abc.abstractmethod def plan_...
# -*- encoding:utf-8 -*- # __author__=='Gan' # Note: This is an extension of House Robber. # After robbing those houses on that street, the thief has found himself a new place for his thievery # so that he will not get too much attention. This time, all houses at this place are arranged in a circle. # That means the f...
__doc__ = """ """ import os import sys import logging from flask import Flask, render_template APP_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__),'..')) CONFIG_PATH = os.path.join(APP_ROOT,'etc','config','config.py') DEFAULT_PORT = 8000 def parse_args(): parser = argparse.ArgumentParser(descripti...