text
stringlengths
38
1.54M
# -*- coding: utf-8 -*- from __future__ import unicode_literals from .forms import PendingWorkForm from Employee.models import Employee from django.shortcuts import render from django.shortcuts import render,get_object_or_404,render_to_response,redirect from .models import PendingWork from Inward.models import Inward f...
#!python #cython: boundscheck=False #cython: wraparound=False #cython: cdivision=True # By Jake Vanderplas (2013) <jakevdp@cs.washington.edu> # written for the scikit-learn project # License: BSD import numpy as np cimport numpy as np np.import_array() # required in order to use C-API #############################...
'''Define a class named American which has a static method called printNationality.''' class American: @staticmethod def printNationality(nacionalidade): print(f"A nacionalidade é {nacionalidade}") American.printNationality("Brasileira")
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-12-15 11:28 from __future__ import unicode_literals from django.db import migrations, models def give_editor_access(apps, schema_editor): Users = apps.get_model("auth", "User") Group = apps.get_model('auth', 'Group') org_contributor, created = Gr...
import math # 计算距离 def lp(x, y, p): sum = 0 for i in range(len(x)): sum += math.pow(abs(x[i] - y[i]), p) return math.pow(sum, 1.0 / p) x1 = [1, 1] x2 = [5, 1] x3 = [4, 4] for i in range(1, 5): l = { 'l{}([1, 1], {})'.format(i, each): lp(x1, each, i) for each in [x2, x3] ...
import sqlite3 class linkedin: def __init__(self): self.connection = sqlite3.connect("./myDB.db") self.cursor = self.connection.cursor() self.username = "" def set_myusername(self, username): self.username = username def create_user_table(self): sel...
# 실습, 모델구성하고 완료 # 회귀 데이터를 Classifier로 만들었을 경우에 에러 확인! from sklearn.svm import LinearSVC, SVC # 애네가 먹히는지 확인 from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor from sklearn.linear_model import LogisticRegression, LinearRegression # LogisticRegression 면접질문에서 많이나옴 (분류모델이라고 외우면됨) from sklearn.tree...
from django.http import HttpResponse,JsonResponse import json import time from house.models import LianJiaTenementHouse import pymysql # Create your views here. def house_views(request): """ 处理前端请求 返回符合条件数据 :param request: :return: """ db = pymysql.connect('localhost', 'root', '123456', 'House_d...
from selenium import webdriver from time import sleep from secrets import pw from random import randint class Bot(): links = [] comments = [ 'Great post!', 'Awesome!' ] def __init__(self): self.login('your_username', pw) self.like_comment_by_hashtag('programme...
import cv import cv2 import numpy as np import tictoc def main(): N = 50 print "OPENING VIDEO" vid = cv2.VideoCapture() vid.open("write.avi") print "LOADING VIDEO" imgs = np.asarray([ vid.read()[1] for i in range(N+2) ]) print "CONCATENATING VIDEO" imgs = np.concatenate( ( np.repeat( imgs[:1], N, axis = 0 )...
from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from django import forms from django.forms import PasswordInput, ModelForm from django.contrib.auth.forms import UserCreationForm, UserChangeForm # Register your models here. from .models im...
import string import sys ALPHABET = string.ascii_lowercase def l2n(l): if l in ALPHABET: return ALPHABET.index(l) print(l, " not in alphabet. Usage: l2n(letter)", file=sys.stderr) def n2l(n): if n >= len(ALPHABET): print(n, " is greater that the alphabet size. Usage n2l(number)", file=sy...
# http://codecombat.com/play/level/extra-extrapolation shellAirTime = 3.4 ogre = hero.getNearestEnemy() if (ogre): hero.attackXY(ogre.pos.x, ogre.pos.y)
""" """ import os import sys sys.path.append(os.getcwd()) import _init_paths import json import math from parse_args import parse_args from PCN import * from Folding import * from TopNet import * from train_utils import train, test, metrics, samples, set_seed, \ tf_resume, cache_pred, model_at, parse_e...
import random class Account: account_count=0 def __init__(self, name, balance): self.deposit_count =0 self.deposit_list = [] self.withdraw_list = [] self.bank = 'sc은행' self.name = name self.balance = balance # acount number num1 = r...
import mido def read_midi(filename): ''' returns params, data with contents of filename. data has shape (-1, channel count). ''' file = mido.MidiFile(filename) return extract_notes(file) def extract_notes(midifile): notes = [] for trk in midifile.tracks: note_stack = {} time ...
inputyear=int(input("enter the year:")) print(inputyear) if ((inputyear % 4 == 0 ) and (inputyear % 100 != 0)) or ((inputyear % 400 ==0)): # if ((inputyear % 400) == 0): print("leap year") else: print("not a leap year")
# coding: utf8 #!/usr/bin/env python # -*- coding: utf-8 -*- import random import string import allure import pytest from selene.conditions import text from selene.api import * import time from General_pages import modals from General_pages.order_steps import random_mail @allure.step('Нажимаем на главной странице кно...
""" Get information from: dr_product_info Version information is used for logics Different SRM version might have different logics against each work-flow. We don't care about schema change between SRM version, since we are inspecting the DB dynamically. """ from srm_db_tool.orm.gentable import GenTable ...
from django.urls import path from . import views urlpatterns = [ path('', views.index.as_view(), name='index'), path('dashboard/', views.dash.as_view(), name='dashboard'), path('profile/', views.profile.as_view(), name='profile'), path('logout/', views.logout_view, name='logout'), path('about/', v...
import os, os.path import sys import editFrame #Edit and SVGify frames. If arguments are provided, we will use them. If not, we will use the defaults #Note: the first argument is always the name of the python script (editAllFrames.py), so ignore it baseFolder = '' baseImageName = 'out-' if (len(sys.argv) > 1): #...
from selenium.webdriver.common.by import By from .AdminProductsPage import AdminProductsPage from .BasePage import BasePage class AdminPage(BasePage): LOGOUT_LINK = (By.XPATH, "//header[@id='header']//a[contains(@href, 'logout')]") MENU_CATALOG_LINK = (By.XPATH, "//ul[@id='menu']/li[@id='menu-catalog']/a[text...
stringA = "I am going home" print("Given String: \n",stringA) vowels = "AaEeIiOoUu" res = set([each for each in stringA if each in vowels]) print("The vowels present in the string:\n ",res)
def is_valid_subsequence(array, subarray): if len(subarray) > len(array): return False index = 0 for number in subarray: while (index < len(array)) and (array[index] != number): index += 1 # Incrementing index once outside of the while loop so next iteration # ch...
""" ================ Date tick labels ================ Matplotlib date plotting is done by converting date instances into days since an epoch (by default 1970-01-01T00:00:00). The :mod:`matplotlib.dates` module provides the converter functions `.date2num` and `.num2date` that convert `datetime.datetime` and `numpy.dat...
import sys import argparse import os from ROOT import TCanvas, TColor, TGaxis, TH1F, TPad, TString, TFile, TH1, THStack, gROOT, TStyle, TAttFill, TLegend, TGraphAsymmErrors, TLine from ROOT import kBlack, kBlue, kRed, kCyan, kViolet, kGreen, kOrange, kGray, kPink, kTRUE gROOT.SetBatch(1) ######### to run ######### ##...
import copy from django import forms from django.forms.utils import pretty_name from django.core.exceptions import ValidationError, ImproperlyConfigured from django.db.models import Q from collections import OrderedDict from functools import reduce from django.utils.http import urlencode from .forms import BetterForm...
# test 003 import os import tensorflow as tf os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' var1 = tf.constant(3.0, dtype=tf.float32) # 定义32位浮点数常量 var2 = tf.constant(4.3, dtype=tf.float32) var3 = tf.constant(5.2, dtype=tf.float32) print(var1) # 直接打印变量属性,由于tensorflow需运行才能找到变量内容,直接打印则显示变量属性内容 sess = tf.Session() node ...
from django.contrib import admin from .models import( AssetRequest ) # Register your models here. class AssetRequestAdmin(admin.ModelAdmin): list_display = [ 'email','role', 'asset_name','quantity_required', 'expected_date', 'status', 'last_updated_by_role'] list_per_page = 10 class Meta: ...
import re import os import django django.setup() from sefaria.model import * from sefaria.helper.normalization import RegexNormalizer, NormalizerComposer failed = [] for file in os.listdir('txt'): print(file) mas, ch = re.findall('(.*?) (.?.) פירוש', file)[0] mas = mas.replace('תעניות', 'תענית') with o...
import math ''' | | | | |---x---| | | | | ''' def drawHTree(x,y,length,depth): if depth < 1: return 0 x0 = x-length/2.0 y0 = y-length/2.0 x1 = x+length/2.0 y1 = y+length/2.0 drawLine(x0, y0, x0, y1) #L drawLine(x1, y0, y1, y1) #R drawLine(x0, y , x1, y) #Line dra...
# 练习: # 定义技能类(技能名称,攻击比例,持续时间) # 创建技能对象,直接print. # 克隆技能对象,体会改变其中一个,不影响另外一个. # 15:10 class Skill: def __init__(self, name="", atk_ratio=0.1, duration=0.1): self.name = name self.atk_ratio = atk_ratio self.duration = duration def __str__(self): return "%s---%d---%d" % (self.name, ...
import re import sys import os import time class GamePlay: def __init__(self, input_file): self.input_file = input_file self.boardSize = 0 self.mode = None self.player = None self.depth = 0 self.cell_val = [] self.boardState = [] def parse_input(self): try: with open(self.input_file, 'r') as f: ...
# ''' # 소요시간 2020/10/18/22:50 # 기둥을 순서대로 재배열하고 제일 첫기둥을 기준으로 # 다음 기둥으로 갈수록 커지면 높이, 위치 갱신하고 지붕 너비 더함 # 만약 다음 기둥이 작다면 이후 모든 기둥들을 훑어보면서 자기보다 더 높은것이 있는지 찾고 있다면 위 과정 반복 # 없다면 그다음으로 가장높은 곳을 기준으로 지붕 너비를 더함 그리고 또 반복 # ''' import sys sys.stdin = open('input.txt','r') # # def check(r): # global roof,now,p_height # #다음 기둥까...
import math def getTerms(triangleNumber): tSqrt = round(math.sqrt(triangleNumber)) + 1 terms = [] for i in range(1, tSqrt): div = triangleNumber / i if triangleNumber % i == 0: terms.append(i) terms.append(round(div)) terms.append(triangleNumber) return t...
class Cargo: def __init__(self): self.codigo=99 self.descripcion="Sin cargo" cargo1 = Cargo() print(cargo1.codigo,cargo1.descripcion) cargo2 =Cargo() cargo2.codigo=1 cargo2.descripcion="Docente" print(cargo2.codigo,cargo2.descripcion) cargo3=Cargo() cargo3.descripcion="Conserje" print(cargo3.codigo...
# Generated by Django 2.2.5 on 2019-09-14 13:57 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('product', '0001_initial'), ('community', '0001_initial'), ('media', '0001_initial'), ...
''' @author: rjs10 ''' import numpy as np import PyMPC.ssdiscrete as ssdiscrete A = np.array([[-1.2822, 0.0, 0.98, 0.0], [ 0.0, 0.0, 1.0, 0.0], [-5.4293, 0.0, -1.8366, 0.0], [ -128.2, 128.2, 0.0, 0.0]]) # 1 ...
import numpy as np import matplotlib.pyplot as plt class FuzzySystem: """ Fuzzy system contains all information gathered from the expert and the user """ def __init__(self, rule_list=None, fuzzy_universe_list=None): """ Initialise the FuzzySystem with rule array and universes array""" if fuzzy...
import logging from time import sleep from selenium.webdriver.support.wait import WebDriverWait from ocs_ci.ocs.ui.page_objects.page_navigator import PageNavigator from ocs_ci.ocs.ui.page_objects.object_service import ObjectService from ocs_ci.ocs.ui.helpers_ui import get_element_by_text logger = logging.getLogger(__...
# -*- coding:utf-8 -*- """ ------------------------------------------------- File Name: 3.11 Description : Author : huang wei date: 2019/2/23 ------------------------------------------------- Change Activity: 2019/2/23: -------------------------------------...
"""Experiment Configuration""" import os import re import glob import itertools import sacred from sacred import Experiment from sacred.observers import FileStorageObserver from sacred.utils import apply_backspaces_and_linefeeds sacred.SETTINGS['CONFIG']['READ_ONLY_CONFIG'] = False sacred.SETTINGS.CAPTURE_MODE = 'no'...
import sklearn.svm import sklearn.decomposition import sklearn.ensemble import numpy def trainSVM(features, Cparam): ''' Train a multi-class probabilitistic SVM classifier. Note: This function is simply a wrapper to the sklearn functionality for SVM training See function trainSVM_feature(...
# Copyright 2015 Google Inc. 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 applicable law or ag...
# # ------------------------------------------------------------------------- # Copyright (C) 2019 IBM. # # 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...
import table as t import csv class DrinksRound: order = [] def update_order(self, name, drink): self.name = name self.drink = drink self.order.append([self.name, self.drink]) return self.order def print_order(self): t.p...
import random from typing import Dict, List, NamedTuple, Optional, Tuple, Union import numpy as np from numpy import typing as npt from scipy import sparse as sps from tqdm import tqdm from typing_extensions import Literal from ._lda import LDATrainer from ._lda import Predictor as CorePredictor from ._lda import lea...
import numpy as np ############ #world params a=30 b=30 world=np.zeros((a,b)) world[:,0]=1 world[0,:]=1 world[:,a-1]=1 world[b-1,:]=1 world[10,0:10]=1 world[5:10,10]=1 world[25:30,25]=1 world[15:18,15:18]=1 world[3:7,21:24]=1 targ=np.array([28.,28.]) thresh=3 nfeatsx=100 nfeatsy=100 v=6. dt=0.2 ################ #Q lea...
from rest_framework import serializers from .models import Curso, Avaliacao from django.db.models import Avg class AvaliacaoSerializer(serializers.ModelSerializer): class Meta: extra_kwargs = { 'email': {'write_only': True} } model = Avaliacao fields = '__all__' de...
import setuptools import typing as t import os import shutil import importlib _HERE = os.path.abspath(os.path.dirname(os.path.realpath(__file__))) classifiers = [ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Console', 'License :: OSI Approved :: Apache Software License', 'Natural Language :...
# coding: utf-8 # from aoikregistryeditor.registry_editor import FilteredFieldEditor # def semicolon_to_newline(text): """ Convert semicolons in given text to newlines. @param text: Text to convert. @return: Converted text. """ # Convert semicolons to newlines. # Return converted text....
# -*- coding: utf-8 -*- ''' @project: PY_project @Time : 2019/8/4 9:23 @month : 八月 @Author : mhm @FileName: __no_applist_lg.py @Software: PyCharm ''' import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn import metric...
from bs4 import BeautifulSoup import requests import smtplib #the mail id which will be used to send message my_email="redwan.ahmed1512039@gmail.com" password="Redwan(1)" #the product page which i'm interested in url="https://www.amazon.com/AMD-Ryzen-3700X-16-Thread-Processor/dp/B07SXMZLPK/ref=sr_1_6?dchil...
import email, smtplib, ssl import sys from email import encoders from email.mime.base import MIMEBase from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText import os.path import pandas as pd from time import sleep import util class bcolors: OKBLUE = '\033[94m' FAIL = '\033[91m' ...
from datetime import datetime import logging import os import prometheus_client import shutil import string import tempfile from tornado.web import authenticated from .. import convert from .. import database from .. import export from .base import BaseHandler logger = logging.getLogger(__name__) class WriteAdapte...
from pyramid.config import Configurator from notify.resources import Root from pyramid.mako_templating import renderer_factory as mako_factory def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(root_factory=Root, settings=settings) confi...
class UserMention: def __init__(self, id, name=None, tag=None): self.__id = id self.__name = name self.__tag = tag def as_dict(self): user = {'id': self.__id} if self.__name: user['name'] = self.__name if self.__tag: user['tag'] = self....
def bmi_result(num): if num < 18.5: print('Underweight') if 18.5 >= num <= 25: print('Normal') if num > 25: return 'Overweight' class KgException: pass class CmException: pass def bmi_calculator(): while True: try: height = int(input('What is you...
import pygame as pg from . import constants as c def getMapIndex(x, y): #devuelve el indice del mouse en la matrix x -= 238 y -= 11 return (x // 65, y // 65) def getMapGridPos(map_x, map_y): #devuelve la posicion de las cuadriculas de la matrix return (map_x * 65 + 65//2 + c.OFFSET_...
import numpy as np import pickle import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim torch.manual_seed(988) class Net(nn.Module): def __init__(self, nInput): super().__init__() self.fc1 = nn.Linear(nInput,64) self.fc2 = nn.Linear(64, 64) s...
class UserProjectsResults: def __init__(self, projects: [], contributed_projects: []): self.projects = projects self.contributed_projects = contributed_projects def to_response(self, user_id): return { "projects": [pj.to_created_project_response() for pj in self.projects], ...
def isana(word, item): newword = word for l in word: if l in item: print(l) newword = item.replace(l,"") print(item) list = ["code", "doce", "code"] isana("one", "two")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @File : postmanAi.py # @Author : CHIN # @Time : 2020-12-23 23:47 import json import requests class Requests: def request(self,method='get',url=None,**kwargs): if method=='get': requests.request(method='get',url=url,**kwargs) elif method=='post': req...
from PyObjCTools.TestSupport import TestCase import CallKit class TestCXError(TestCase): def test_constants(self): self.assertIsInstance(CallKit.CXErrorDomain, str) self.assertIsInstance(CallKit.CXErrorDomainIncomingCall, str) self.assertIsInstance(CallKit.CXErrorDomainRequestTransaction, ...
#!/bin/env python from pyrapp import * from optparse import OptionParser, make_option from copy import copy from pprint import pprint import csv,os from math import sqrt import array # ------------------------------------------------------------------------------------------ class TrgEffPlots(PlotApp): def __...
from optimade.models import ( ReferenceResource, StructureResponseMany, StructureResponseOne, ) from ..utils import RegularEndpointTests class TestStructuresEndpoint(RegularEndpointTests): """Tests for /structures""" request_str = "/structures" response_cls = StructureResponseMany def t...
import os import numpy as np from keras.preprocessing.image import img_to_array, load_img from sklearn.model_selection import train_test_split class DataSet: def __init__(self, path): self.path = path self.img_list = os.listdir(self.path) try: self.img_list.remove('.DS_Store') ...
from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) username = serializers.CharField() password = serializers.CharField(write_only=True) is_staff = serializers.BooleanField(requir...
import numpy as np from tensorflow.keras.layers import Embedding def convert_to_one_hot(Y, C): Y = np.eye(C)[Y.reshape(-1)] return Y def sentences_to_indices(X, word_to_index: np.array, max_len: int)->np.array: """ Converts an array of tokenized and cleaned sentences into an array of indices correspo...
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2015,2018 Contributor # # 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 #...
from socket import * #import hashlib Server_host = '51.158.165.206' Server_port = 9091 socket_object = socket(AF_INET, SOCK_STREAM) socket_object.connect((Server_host, Server_port)) while True: data = socket_object.recv(1024).strip() if 'KHCTF' in data: print (data) break else: data1...
# SERVENT # """ Nome: Ana Luiza de Avelar Cabral Matricula: 2013007080 Nome: Matheus Paiva Costa Matricula: 2012055170 Nome: Ramiro Costa Lopes Matricula: 2013007722 """ TAM_MAX = 54 #tam max eh 54, mais folga? por isso 60. 52=2+2+(4+2)+4+40, msg entre servents, a maior possivel. import socket i...
# coding:utf-8 import sys from django import template from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User from django.db.models import Q from django.template.loader ...
import sqlite3 as sq import os from myBasic import order,CDF import pylab as pl import numpy as num from eventD import eventDetection from recur import recPlot from tsTransform import * import math def bina(ts,val,h): a=min(ts) b=max(ts) bl=int(num.ceil(float((b-a))/h)) unused,he=num.histogram(ts,bl) xax=[.5*(he[...
""" Port of gdb_uefi.py to LLDB. Refer to gdb_uefi.py for more details. """ import array import binascii import getopt import lldb import os import re import shlex import subprocess import sys from collections import OrderedDict from common_uefi import * class ReloadUefi: """Reload UEFI symbols""" # # V...
import logging import numpy as np import pandas as pd import scipy.special import scipy.stats def encode_array(vals, sep=',', fmt='{:.6g}'): return sep.join(map(fmt.format, vals)) def decode_array(vals, sep=','): return np.asarray(list(map(float, vals.split(',')))) def encode_matrix(vals, sep1=',', sep2=';'...
everything = ['dongjing', 'beijing', 'shanghai', 'qingdao', 'shenzhen', 'changjiang', 'huanghe'] print(everything) print(everything[0]) print("\nThis is last " + everything[-1].title() + ".") one = "\nThis is three word " + everything[2].title() + "." print(one) everything[0] = "xizang" print("\nThe f...
########################################################################################## ### LICENSE ########################################################################################## # # This code is part of findmyhash v 2.0 # # This code is under GPL v3 License (http://www.gnu.org/licenses/gpl-3.0.html). # ...
import socket import sys s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 建立连接: s.connect(('127.0.0.1', 9000)) # 接收欢迎消息: print(s.recv(1024).decode('utf-8')) while True: data=input("send data:") if data == 'exit': break else: s.send(bytes(data,'utf-8')) print(s.recv(1024).d...
import numpy as np import utils from data.datasets import BaseDataset from .base_dl import BaseDataLoader class DataLoaderNoAugmentations(BaseDataLoader): """ Data loader that yields images from Dataset as is. Use this loader if augmentations are performed in Dataset class itself to avoid performing ...
from flask_restful import fields class ResourceFields(object): def __init__(self): pass @staticmethod def put_schema(): return { 'id': fields.Integer, 'country': fields.String, 'commodity': fields.String, 'fixed_overhead': fields.Float, ...
#!/usr/bin/python3m # -*- coding: utf8 -*- import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), 'src')) from optparse import OptionParser from db2bkp.DB2Backup import DB2Backup if __name__ == '__main__': parser = OptionParser() parser.add_option("-c", "--config", dest="config", ...
import json import logging from autobahn.twisted.wamp import ApplicationSession from django.conf import settings from django.db import models from django.db.models.signals import post_save from django.utils.timezone import now from .plugin import Plugin logger = logging.getLogger(__name__) class LogManager(models....
import unittest import os from test.aiml_tests.client import TestClient from programy.config.brain import BrainFileConfiguration class LearnfTestClient(TestClient): def __init__(self): TestClient.__init__(self) def load_configuration(self, arguments): super(LearnfTestClient, self).load_config...
my_list = [3, 8, 1, 6, 0, 8, 4] target = 8 num = 0 for i in range(len(my_list)): if my_list[i] == target: if num == 0: num = 1 else: print(i) # for i in range(len(my_list)): if my_list[i] == target: print(my_list.index(target, i+1)) break # indexPosList...
from kafka import KafkaProducer from time import sleep import json, sys import requests import time def getData(url): jsonData = requests.get(url).json() data = [] labels = {} index = 0 for i in range(len(jsonData["response"]['results'])): headline = jsonData["response"]['results'][i]['fi...
# Space Spice __author__ = 'Tim Polizzi' __email__ = 'Timothy.Polizzi1@marist.edu' class Melange(object): def __init__(self, name: str, price: float, qty: int): self.name = name self.price = price self.qty = qty
from django.shortcuts import render def activity(request): context = { 'nav_items': [{'path': 'activities', 'text': '活动'}], 'registered': False, 'candidates': [ {"photo": "main/images/baqizhao.jpg", "code_desc": "经过评委合议,2016年Q4最佳代码评选结果新鲜出炉,最佳代码获得者为Moon(刘轶材)和Nero(刘雍琪),恭喜两位!同时,...
# Wrong Answer import math t = int(raw_input()) for i in xrange(1, t + 1): area = float(raw_input()) a2 = area * area sin = math.sqrt((a2 - 1) / a2) cos = 1 / area print 'Case #{}:'.format(i) print sin / 2, cos / 2, 0 print -cos / 2, sin / 2, 0 print 0, 0, 0.5
#!/usr/bin/env python # coding: utf-8 import getpass user = getpass.getuser() passwd = getpass.getpass() if svc_login(user, passwd): # You must write svc_login() print('Yay!') else: print('Boo!') user = input('Enter your username: ')
# Generated by Django 3.1.8 on 2021-06-05 06:22 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ("contenttypes", "0002_remove_content_type_name"), migrations.swa...
# Generated by Django 3.1.8 on 2021-04-18 10:32 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('store', '0005_auto_20210406_2259'), ] operations = [ migrations.AddField( model_name='order', name='payment_id', ...
# -*- coding: utf-8 -*- from django.shortcuts import render_to_response from django.template import RequestContext from django.core.urlresolvers import reverse from clientes.models import Cliente from django.contrib.auth.decorators import login_required from django.http import HttpResponseRedirect from clientes.forms i...
# -*- coding: utf-8 -*- """ Created on Fri Jun 24 11:23:19 2016 @author: sicarbonnell """ import numpy as np #np.random.seed(172) import matplotlib.pyplot as plt import pandas as pd import cv2 from keras.models import model_from_json import Utils.data_management as dm # model = model_from_json(open('Saved/segment_m...
# Binary heap is a complete binary tree where the parent node is alaways # smaller or greater than the child node. # Binary heaps can be implemented using arrays and it is very space # efficient. # If the parent node is stored in at index i, the left child # can be stored in the array as 2*i + 1 and the right chil...
from django.forms import ( CharField, Form, ) from gbe_forms_text import ( participant_form_help_texts, participant_labels, ) class BasicBidForm(Form): use_required_attribute = False required_css_class = 'required' error_css_class = 'error' phone = CharField(required=True, ...
# 2.1 Math # Addition # Addition works just as you would expect it torepresented by + # print(5 + 5) # Subtraction # Subtraction works the same as you would expect it torepresented by - # print(20 - 10) # Multiplication # Multiplication works the same as you would expect it torepresented by * ...
from typing import Final FPS: Final = 60 BACKGROUND_MENU_LOBBY: Final = "../../static/menu/background.png" DEFAULT_PATH_FONT: Final = "../../static/fonts/main_font.otf"
import unittest from unittest.mock import MagicMock, call from ortools_linearization.linearization import PieceWiseLinearization class LinearizationTest(unittest.TestCase): def setUp(self) -> None: self.linearization = PieceWiseLinearization() self.solver_mock = MagicMock() self.objectiv...
#!/usr/bin/python3 # -*- coding: utf-8 -*- file = open("vcards.txt", "r") dic = {} lis = [] def dicGehRein(d, dTmp): if list(d.keys())[0] == "__": dTmp["__"] = d["__"] else: key = list(d.keys())[0] if key in dTmp: dicGehRein(d[key], dTmp[key]) else: dT...