text
stringlengths
38
1.54M
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (c) 2018 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # from collections import OrderedDict import yaml from cgtsclient.common import utils from cgtsclient import exc from cgtsclient.v1 import app as app_utils def _print_helm_chart(chart)...
import Bio.PDB from Bio.PDB import PDBParser from Bio.PDB.PDBIO import PDBIO from Bio.PDB import Superimposer from Bio.PDB import NeighborSearch import sys import os import argparse from functions import * parser = argparse.ArgumentParser(description="The function of this program is to reconstruct biological...
import cv2 import numpy as np; import math # read the image throught an window frame #imports for that from tkinter import * from tkinter import filedialog from matplotlib import pyplot as plt from matplotlib import path from sideOfPieces import sideOfPieces from pieces import pieces from PIL import Image from colorma...
from datetime import datetime, timedelta import json from time import mktime from django.db import models from model_utils import Choices from training.core.dailymile import api_get class DailyMileProfile(models.Model): user = models.OneToOneField('auth.User') dailymile_url = models.TextField() access_t...
__author__ = 'kole0114' class OperationStatus(object): def __init__(self,token,**extra): self.token=token if 'redirect' in extra: self.redirect=extra['redirect'] else: self.redirect=None if 'status' in extra: self.status=extra['status'] ...
#! /usr/bin/env python # -*- coding: utf-8 -*- import sys import codecs import re from optparse import OptionParser from xml2vrt.rule_parse import ElemRuleParser from xml2vrt.util import WrappedXMLFileReader from xml2vrt.converter import Converter, _test_rules # This is needed only as long as we need to be able to ...
# -*- coding: utf-8 -*- def combine(residual, data, combine): if combine == 'add': return residual + data elif combine == 'concat': return mx.sym.concat(residual, data, dim=1) return None def channel_shuffle(data, groups): data = mx.sym.reshape(data, shape=(0, -4, groups, -1, -2)) data = mx.sym.swapaxes(data...
from collections import OrderedDict import numpy as np from copy import copy import load_gals class InvalidGalColorError(Exception): pass class CroppingError(Exception): pass class GalsAndStarsDoNotContainTheSameWavebandsError(Exception): pass class Galaxy: def __init__(self, gal_dict, stars_d...
from sheepdog import utils from sheepdog.transactions.transaction_base import TransactionBase class ReviewTransactionBase(TransactionBase): role = None def __init__(self, **kwargs): super(ReviewTransactionBase, self).__init__(role=self.role, **kwargs) @property def to_state(self): "...
import tweepy from tweepy.streaming import StreamListener CONSUMER_KEY = '62DQSnyyPSVYv9TU9UKe8gqPw' CONSUMER_SECRET = 'l85LOdo3UNDO7EFOXgPGDMw4DyKlhL4UV5VUicsi0AGrbUs2up' ACCESS_TOKEN = '204483920-qaUDsIVnGqRmMhpw4ZQcrw0JzndIgugIZymobYkQ' ACCESS_TOKEN_SECRET = 'sEwtMlXcZUkgcpq85bYEpUcwZMrxuwqLAwIUyZ8yWvYwa' auth = t...
N, M = map(int, input().split()) result = 0 for n in range(N): data = list(map(int, input().split())) min_value = min(data) result = max(result, min_value) # 2중 반복문 구조 이용 # result = 0 # # for n in range(N): # 한 줄씩 입력받기 # data = list(map(int, input().split())) # # 현재 줄에서 '가장 작은 수' 찾기 # m...
from typing import Dict, Optional, Union from autoPyTorch.datasets.base_dataset import BaseDatasetPropertiesType from autoPyTorch.pipeline.components.training.trainer.StandardTrainer import StandardTrainer from autoPyTorch.pipeline.components.training.trainer.forecasting_trainer.forecasting_base_trainer import \ F...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tag genes for hotels based on stored rules""" __author__ = "Kingshuk Dasgupta (rextrebat/kdasgupta)" __version__ = "0.0pre0" import logging #import celery import urllib2 import urllib import json from celery.signals import worker_init from bin.celeryapp import celery...
""" Copyright 2015 Rackspace 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 agreed to in writing, software dist...
import cv2 import numpy as np # Reading the Image image = cv2.imread("1.JPG") # Finding the Edges of Image gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray = cv2.medianBlur(gray, 7) edges = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 9, 10) # Making a Cartoon of the image color =...
from django.shortcuts import render from django.views.generic import UpdateView, FormView, DetailView, ListView, DeleteView from userprofile.forms import UserProfileForm, ContactForm from userprofile.models import UserProfiles from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse_laz...
# -*- coding: utf-8 -*- # Generated by Django 1.11.16 on 2018-12-31 07:08 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('job', '0001_initial'), ] operations = [ migrations.RenameField( ...
# Generated by Django 2.1.5 on 2019-01-26 17:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('newsfeed', '0002_auto_20190126_1616'), ] operations = [ migrations.AlterField( model_name='article', name='author', ...
import re import socket from edc.device.sync.exceptions import ProducerError def getproducerbyaddr(producer): try: hostname, aliases, ips = socket.gethostbyaddr(producer.producer_ip) except AttributeError: raise AttributeError(('Expected a producer instance. Got producer=\'{}\'.').format(prod...
"""AutoBridge""" from setuptools import find_packages, setup with open('README.md', encoding='utf-8') as f: long_description = f.read() setup( name='autobridge', version='0.0.20220512.dev1', description='AutoBridge', long_description=long_description, long_description_content_type='text/markdow...
""" Given an array of integers nums, calculate the pivot index of this array. The pivot index is the index where the sum of all the numbers strictly to the left of the index is equal to the sum of all the numbers strictly to the index's right. If the index is on the left edge of the array, then the left sum is 0 bec...
s = input() k = int(input()) if k <= len(s): s_k = [] for i in range(len(s)-k+1): s_k.append(s[i:i+k]) print(len(set(s_k))) else: print(0)
#!/usr/bin/env python3 import subprocess, os initialCommit = "HEAD~" if "INITIAL_COMMIT" in os.environ: initialCommit = os.environ["INITIAL_COMMIT"] filterPaths = [ "test_dir", "contrib/filter-commits.py", ".gitignore" ] subprocess.run(["git", "reset", "--soft", initialCommit]) subprocess.run(["git"...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'app/template/lab5.ui' # # Created by: PyQt5 UI code generator 5.5.1 # # 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.setObj...
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import absolute_import, division, print_function, unicode_literals import sys from astropy.units import Quantity from astropy.table import Table from ..utils.time import time_ref_from_dict from ..utils.scripts import make_path __all__ = [ ...
#! python3 import csv import setup example_file = open('example.csv') # reader is iterative example_reader = csv.reader(example_file) for row in example_reader: print('Row#{} {}'.format(example_reader.line_num, str(row))) # writer delimiter = {'csv': ',', 'tsv': '\t'} for k, v in delimiter.items(): outp...
""" Turner, Mann, Clandinin: Figure generation script: Fig. 3. https://github.com/mhturner/SC-FC """ import matplotlib.pyplot as plt import numpy as np import networkx as nx import os import glob from scfc import bridge, anatomical_connectivity, functional_connectivity, plotting from matplotlib import rcParams rcPar...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @version: python2.7 @author: @contact: @software: RoboWareStudio @file: modular_robot_control_func.py @biref:上位机主窗口,包含关节控制,路径离线控制 """ import rospy import sys from rospkg import RosPack from ui.msg import robot_feedback from modular_robot_control import Ui_MainWindow_...
# -*- coding: utf-8 -*- from PIL import Image import os import numpy as np import matplotlib.pyplot as plt images = [] im_list = [] x = np.zeros((877,4096,3)) os.chdir("van_gogh") len_van_gogh = os.listdir() for i in range (1,len(len_van_gogh)+1): im = Image.open('Vincent_van_Gogh_' + str(i) +'.jpg') if np.a...
from functools import wraps import conjur from flask import request, jsonify from util import send_audit_event def check_auth(username, password): """ This function is called to check if a username/password combination is valid. """ request.user = username api = conjur.new_from_key(username, pa...
from datetime import datetime from django import forms from captcha.fields import CaptchaField from .models import Info MONTH = {i: i for i in range(1, 13)} YEAR = {i: i for i in range(datetime.now().year-19, datetime.now().year+1)} class LoginForm(forms.Form): username = forms.CharField(label=u'用户名', requi...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='AdoptionDay', fields=[ ('id', models.AutoField(...
from md_loops_debug import main_debug_loop __author__ = "nikos.daniilidis" if __name__ == '__main__': main_debug_loop( note='shared-x', readme='''n streams sharing x values, all gauss, different balances, same weights''', event_types=3 * ['gauss'], # distribution of the hidde...
# create a function with defaults def keyword_function(a=1, b=2): return a+b # call it with keyword arguments keyword_function(b=4, a=5) # call the function without arguments (i.e. use the defaults) keyword_function()
import collections import re from sklearn.feature_extraction.text import TfidfVectorizer import numpy as np from sklearn.preprocessing import LabelEncoder from sklearn import svm import wordcloud import matplotlib.pyplot as plt from newsiness_modules import feature_extraction as nm_fe from newsiness_modules import text...
from logging import log from PIL import Image, ImageFont, ImageDraw from telethon import events from .. import jdbot, chat_id, _LogDir, _JdbotDir, logger, mybot, chname from prettytable import PrettyTable import subprocess from .beandata import get_bean_data from .utils import V4 IN = _LogDir + '/bean_income.csv' OUT ...
# -*- coding: utf-8 -*- from odoo import api, fields, models, _ class Material(models.Model): _name = 'hs.eas.material' _description = 'Material' _order = 'number' name = fields.Char('Name', required=True) base_unit = fields.Many2one('hs.eas.measure.unit', string='Base Unit', required=True) ...
def capitalize(s): output11 = "" output2 = "" c = [] for x in range(0, len(s)): if (x % 2 == 0): output11 += s[x].upper() else: output11 += s[x].lower() if (x % 2 == 1): output2 += s[x].upper() else: output2 += s[x].lower...
import numpy as np from scipy import ndimage from scipy import signal from scipy import misc from scipy.ndimage import filters def notch_filter_2d(size, sigma): x, y = np.mgrid[-size//2 + 1:size//2 + 1, -size//2 + 1:size//2 + 1] g = np.exp(-((x**2 + y**2)/(2.0*sigma**2))) g /= g.sum() g -= (np.max(g) +...
import random import evemy.ude as ude from evemy.evemy_sis.si1 import si1 from evemy.evemy_sis.si2 import si2 class mob1: def __init__(self,canvas,ife=1,sk=30,uf=100,rk=1): self.canvas=canvas self.items=[] self.sk=sk self.uf=uf self.rk=rk if ife==1: self....
import numpy as np from scipy.misc import lena import OpenGL.GL as gl class Canvas(): done_init_texture = False def initTexture(self): """ init the texture - this has to happen after an OpenGL context has been created """ # make the OpenGL context associated with this ...
def checkList(food): count = 0 for item in food: count += 1 x = "Your list contains {} food items!" print(x.format(count))
import sys from bs4 import BeautifulSoup import os import re TITLE_TAG = "h3" PARSER_TYPE = "lxml" class Listing(object): def __init__(self, attr_dict, content): self.attr_dict = attr_dict self.content = content def __str__(self): st = "---" for attr in self.attr_dict: ...
import numpy as np import pandas as pd import itertools as it filename = 'input.txt' with open(filename) as f: content = f.read().splitlines() x0,y0,vx,vy = [],[],[],[] for i in content: x0.append(int(i[10:16])) y0.append(int(i[18:24])) vx.append(int(i[36:38])) vy.append(int(i[40:42])) from o...
import requests #topics covered : requests,api (application programming interface) #taking json value from website api.fixer.ip(used to get currency exchenge rates) def main(): base = input("First Currency: ") other = input("Second Currency: ") #taking inputs for the currencies res = requests.get("htt...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'untitled.ui' # # Created by: PyQt5 UI code generator 5.15.2 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtG...
from torch import nn import torch.nn.functional as F class NNHeuristic(nn.Module): """ Define a neural network for use in DQN with a heuristic input. """ def __init__(self, input_dims: int=6): super(NNHeuristic, self).__init__() self.conv1 = nn.Sequential(nn.Linear(input_dims, 64)) ...
from ebpub.db.models import NewsItem, Schema from django.contrib.gis.geos import Point import datetime from ksublock.scrapers.yelp import YelpApi schema = Schema.objects.get(slug='campus-event') yelpAxes = YelpApi('nRv6gPdCwEopk82FK_cwcA','g8VQ_wr3wgWspFEYFaW-S0Z4dBI','rS-u-TkmWViYGmblyi7M4pmCwIpLbdwD','H4xrxatP9OCuGt2...
__author__ = 'grant' c = dict(name='bill', age=21, occupation='student') print(c) e = dict([('name', 'jim'), ('age', 21), ('occupation', 'student')]) print(e) d = dict(zip([1, 2, 3, 4], ['first', 'second', 'third', 'fourth'])) print(e.keys()) print(e.values()) print(d) keys = {1: 1, 2: 2, 3: 3, 4: 4} values = ...
from flask_restful import Resource, reqparse from models.user import UserModel from flask_jwt_extended import create_access_token, jwt_required, get_raw_jwt from werkzeug.security import safe_str_cmp from blacklist import BLACKLIST args = reqparse.RequestParser() args.add_argument('name', type=str, required=True, help...
#!/usr/bin/python # -*-coding:utf-8-*- import os import yaml # dirpath = os.path.dirname(os.path.realpath(__file__)) # f = open("mypage.yaml", "r", encoding="utf-8") # a = f.read() # f.close() # d = yaml.load(a) # print(d) # print(d["Mypage"]['desc']) # for i in d["Mypage"]['locators']: # print(i) dirpath = os.p...
import requests import os from datetime import datetime import pytz link = 'https://www.toggl.com/api/v8/time_entries/current' script_dir = os.path.dirname(__file__) file = open(os.path.join(script_dir, 'token.txt')) token = file.read().replace('/n', '') file.close() r = requests.get(link, auth=(token.strip(), 'api_t...
#EASY, MEDIUM AND HARD LEVEL PARAGRAPHS easy= """An immense mausoleum of white marble, built in ____1____ between 1631 and 1648 by order of the Mughal emperor ____2____ in memory of his favourite wife ____3____ , the Taj Mahal is the jewel of Muslim art in ____4____ and one of the universally admired masterpieces of...
import twitter api = twitter.Api(consumer_key='vX4zFZ2O5EvB2dvVmHKIrZX9f', consumer_secret='wuh6s2tU5PCbr9XYv1s9gIb6WnykUbnuEbDSpQ9cia919NvOor', access_token_key='328006955-eX4tQxmAl67Eau2EJvH11shUZzoo8Z06qKMcHgmZ', access_token_secret='P2zpEcnRXjLq65Xe...
import integration def f(x): return x/(1+x) res = 1.30685281944 # anlaytical result #for n=5 n = 5 m1 = integration.midpoint(1, 3, n, f) t1 = integration.trapezoidal(1, 3, n, f) s1 = integration.simpson(1, 3, n, f) # for n=10 n = 10 m2 = integration.midpoint(1, 3, n, f) t2 = integration.trapezoidal(...
# TODO import cs50 from csv import reader from sys import argv # open the database to be used later db = cs50.SQL("sqlite:///students.db") # check whether there is an input if len(argv) < 2: print("usage error, import.py characters.csv") exit() # open csv and copy into a list with open(argv[1], newline='') as...
"""A video playlist class.""" from .video import Video from .video_library import VideoLibrary class Playlist: """A class used to represent a Playlist.""" def __init__(self, name): self._video_library = VideoLibrary() self._original_name = name self._internal_name = name.lower(...
""" Tests of wc_env_manager command line interface :Author: Jonathan Karr <jonrkarr@gmail.com> :Date: 2018-08-29 :Copyright: 2018, Karr Lab :License: MIT """ from wc_env_manager import __main__ import mock import unittest import whichcraft @unittest.skipIf(whichcraft.which('docker') is None, 'Test requires Docker a...
"""Routes Tourism Serializers. """ # Django REST from rest_framework import serializers # Models from core.commerce.models import Route, DayNumber, ElementDay class RouteModelSerializer(serializers.ModelSerializer): days = serializers.SerializerMethodField('get_day_for_route') def get_day_for_route(self, ro...
import threading import glib import dbus from dbus.mainloop.glib import DBusGMainLoop def printin(bus, message): print("New message!") print(message['member']) print("\n\n\n") def printout(bus, message): print("Message seen") #args = message.get_args_list() print(message['member']) print("...
#!/usr/bin/env python from easygui import * import glob import os import re import sys import pyfits def pick_dir(msg=None, title="Choose Directory", default=None): if msg != None: msgbox(msg) while 1: dirname = diropenbox(title, default=default) if dirname == None or not os.path.isdir...
import pyautogui import mymodule1 import pyperclip a = mymodule1.user2["user"] b = mymodule1.user2["contactnumber"] c = mymodule1.user2["desklocation"] d = mymodule1.user2["username"] #click cherwell pyautogui.click(x=320, y=1056) pyautogui.PAUSE = 2 #click my que pyautogui.click(x=1102, y=469) pyautogui.PAUSE = 2...
from pymongo import * import sys import argparse usage = 'cleandb -c "client"' parser = argparse.ArgumentParser(description="Delete Database from mongo",epilog=usage) parser.add_argument("-c","--client",help="clientdb",type=str,required=True) opt = parser.parse_args() if len(sys.argv) < 1: parser.print_help() ...
""" sphinx_c_autodoc is a package which provide c source file parsing for sphinx. It is composed of multiple directives and settings: .. rst:directive:: .. c:module:: filename A directive to document a c file. This is similar to :rst:dir:`py:module` except it's for the C domain. This can be used for both c...
# -*- coding: utf-8 -*- """ Created on 2017-10-10 @author: cheng.li """ from math import pi, cos, sin, copysign, trunc, sqrt import numpy as np from scipy.ndimage import convolve from scipy.misc import imread from matplotlib import pyplot as plt length = 20 theta = 45. def motion_blur(length, theta): length =...
from typing import List from pydantic import BaseModel class FidesopsSchema(BaseModel): """ A base template for all other FidesOps Schemas to inherit from. """ @classmethod def get_field_names(cls) -> List[str]: """Return a list of all field names specified on this schema""" retu...
import random monsters = {"Red Eye Wolf", "Blightfang", "The Painted Terror Monkey"} randomMonster = random.choice(list(monsters)) health = 100 print(f"You have stummbled upon a {randomMonster} which has {health} health") class Player: def __init__(self): #Initialize here def attack(self): ...
import mysql.connector import csv from tkinter.filedialog import askopenfilename from functools import partial from matplotlib.figure import Figure from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg import tkinter as tk import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from apyori i...
# Time: O(m * n), m is the number of nodes of s, n is the number of nodes of t # Space: O(h), h is the height of s # Given two non-empty binary trees s and t, # check whether tree t has exactly the same structure and # node values with a subtree of s. # A subtree of s is a tree consists of a node in s and all of this...
try: degrees_in_fahrenheit = float(input("What is the temperature in Fahrenheit?: ")) def F2C_Converter(): degrees_in_celcius = (degrees_in_fahrenheit - 32) * 5/9 return degrees_in_celcius print(F2C_Converter(),"C") except ValueError: print("This is not a num...
from django.urls import path from .views import all_proms from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', all_proms ) ]
x = [0.0, 3.0, 5.0, 2.5, 3.7] #define array print(type(x)) #remove third element x.pop(2) print(x) #will print without third element #remove 2.5 x.remove(2.5) print(x) #add an element to the end x.append(1.2) print(x) #copy y = x.copy() print(y) #how many elements are 0.0 print (y.count(0.0)) #print the index wit...
import numpy as np from math import * ecuacion = input("Ingrese la función a resolver: ") aValor = float(input("Ingrese el extremo inferior del intervalo: ")) bValor = float(input("Ingrese el extremo superior del intervalo: ")) tolerancia = float(input("Ingrese la tolerancia del método: ")) maximoIteraciones = int(inp...
#SCOPE TERM #Has 2 types # 1. Local variable: Defined in function # 2. Global variable: defined outside function #Attempt 1st a=10 #GLobal def something(): a=9 #Local print("fun",a) something() print("Global",a) #Attempt 2nd #if you want to change the global variable by change varibale inside function a=10 d...
import sys def findpal(n): pals,i = 0,999 while i > 99: j = 999 while j >= i: prod = i*j j = j-1 if prod < pals: break if str(prod)==(str(prod)[::-1]) and prod < n: if prod > pals: pals = prod ...
# -*- coding: utf-8 -*- """ Created on Tue Apr 16 14:11:50 2019 @author: 77 """ import pandas as pd import numpy as np import os for name in os.listdir('E:/the_data/new_data'): domain = os.path.abspath(r'E:/the_data/new_data') #获取文件夹的路径 info = os.path.join(domain,name) #将路径与文件名结合起来就是每个...
''' Reads in IntensityList from a .csv @author: Mason ''' #Import required modules import pandas as pd import numpy as np import matplotlib.pyplot as plt def read_intensity(filename="../Raw_Data/intensity.csv"): ''' Inputs: filename: path of the .csv you want to parse Outputs: resize...
from rest_framework import serializers from .models import Class class ClassViewSetSerializer(serializers.ModelSerializer): class Meta: model = Class exclude = [ "is_active", "location_code", ] read_only_fields = [ "somm", "pk", ...
import numpy as np import torch import torch.nn as nn from scipy.sparse import csr_matrix from beta_rec.models.torch_engine import ModelEngine class VAE(nn.Module): def __init__(self, z_dim, ae_structure, config): super(VAE, self).__init__() self.config = config act_fn = self.config["acti...
import serial import time import struct class STM32_Message(object): x_vel =0 y_vel =0 ang_vel =0 wind_left =0 wind_right =0 unwind_left =0 unwind_right=0 left_prop =0 right_prop =0 roller =0 def __init__(self,port,baudrate): ...
#!/usr/bin/env python3 # coding: utf-8 import contextlib import json import logging import os import random import pymongo import requests import zhconv from tqdm import tqdm from common.utils import hide_phone, ts_date from databases.base import Mongo, Redis, SearchEngine from databases.comment import CommentSearch ...
#!/usr/bin/env python # -*- coding: utf-8 -*- ########################################################### # WARNING: Generated code! # # ************************** # # Manual changes may get lost if file is generated again. # # Only code inside the [MANUAL] ta...
#!/usr/bin/env python3 import os import datetime import time import subprocess import psutil from pathlib import Path from create_rrdfiles import create_Network from createLogFile import createLog def get_Network(): network_interface = psutil.net_io_counters(pernic=True) ifaces = psutil.net_if_addrs() netwo...
import sys, os import pyshark import json from pathlib import Path from optparse import OptionParser from gen_parser import parse as gp from dur_parser import parse as dp from rate_parser import parse as rp # This program takes as input a directory path # It will fork off a thread and parse every file capture locat...
from django.test import TestCase from .models import Customer, Contact # Create your tests here. class ContactTests(TestCase): def setUp(self): Customer.objects.create(name='Sample Customer') self.company = Customer.objects.get(name='Sample Customer') def test_name(self): """ last name should be ...
from PIL import Image from PIL import ImageStat class TakenPicture: def __init__(self, shutter_speed, img, config): self.img = img self.shutter_speed = shutter_speed self.brightness = self.calculate_brightness(img, config) self.delta = abs(config.ideal_brightness - self.brightness)...
def shoot(i,j): global direction, game, H, W direction = game[i][j] if direction == "<": dj = j print("<") if 0 <= dj - 1<W: dj -= 1 if game[i][dj] == "." or game[i][dj] == "-": shoot(i,dj) elif game[i][dj]=="*": gam...
__all__ = [ 'base_model', 'address', 'criteria', 'notification', 'offer', 'product', 'price', 'tax', 'order', 'payer', 'response', 'update', 'shipping', 'task_complete_params', 'task_data', 'task_followup', 'transaction', 'sort_dir...
from app.models import Log, Comment from flask import url_for from flask_restful import fields from . import default_per_page user_fields = { 'id': fields.Integer, 'email': fields.String, 'name': fields.String, 'major': fields.String, 'headline': fields.String, 'about_me': fields.String, 'a...
class Calculator: def add(a,b): return a + b def sub(a,b): return a - b def mul(a,b): return a * b def div(a,b): return a / b c = Calculator print(c.add(10,3)) print(c.sub(23,8)) print(c.mul(4,6)) print(c.div(6,3))
from common.mixin import DynamicLoadMixin class ProviderFactory(DynamicLoadMixin): provider_map = { # "aws": AWSProvider, # "azure": AzureProvider, "gcp": "gcp.GCPProvider", "onprem": "onprem.OnPremProvider" } @classmethod def get_provider(cls, provider_name, *args, *...
import pandas as pd import flightanalysis2015 as fa def test_flighttimes(): flights_df = pd.DataFrame({ "AIRLINE" : [ "UA", "B6", "DL", "FAIL" ], "ORIGIN_AIRPORT" : [ "IAD", "IAD", "IAD", "FAIL" ], "DESTINATION_A...
class Solution: def killProcess(self, pid, ppid, kill): """ :type pid: List[int] :type ppid: List[int] :type kill: int :rtype: List[int] """ dic = {} visited = {} for p in pid: dic.setdefault(p, []) visited[p] = 0 ...
__all__ = ['Comment', 'dump', 'Element', 'ElementTree', 'fromstring', 'fromstringlist', 'iselement', 'iterparse', 'parse', 'ParseError', 'PI', 'ProcessingInstruction', 'QName', 'SubElement', 'tostring', 'tostringlist', 'TreeBuilder', 'VERSION', 'XML', 'XMLID', 'XMLParser', 'XMLPullParser', 'register_namespace'] VERSION...
import torch from torchvision.datasets.vision import VisionDataset import transforms as T import glob from PIL import Image import random import os import xml.etree.ElementTree as ET # Car (승용차), Truck (트럭), Bus (버스), Etc vehicle (기타 차량-덤프트럭, 레미콘 등 건설용차량), Bike( 이륜 차) License(번호판) class ConvertCarPlateto...
from random import shuffle num1 = str(input('Primeiro aluno: -> ')) num2 = str(input('Segundo Aluno: -> ')) num3 = str(input('Terceiro aluno: -> ')) num4 = str(input('Quarto aluno: -> ')) num5 = str(input('Quinto aluno: -> ')) lista = [num1, num2, num3, num4, num5] shuffle(lista) print('A ordem de apresentação sera? ')...
import collections import torch from torch import optim import torchvision from torchvision import datasets from torchvision.transforms import ToTensor import torch.nn as nn import torch.nn.functional as F from torch.nn.utils import spectral_norm from torch.utils.data import DataLoader from torch.autograd import Vari...
import sqlite3 conn = sqlite3.connect('notes.db') c = conn.cursor() c.execute("CREATE TABLE `messages` (`id` INTEGER PRIMARY KEY, `from` TEXT, `to` TEXT, `timestamp` INTEGER, `message` TEXT, `received` INTEGER)") c.execute("INSERT INTO `messages` VALUES (NULL, 'mader', 'darnek', 0, 'test', 0)") conn.commit() conn.close...
from energyMinimization import * import colorsys import csv from collections import Counter import itertools import colorsys import math square_grid = 16 input_image_file = "input/room1.jpg" output_weight_filename = "room_weight" def min_max_scale(arr): arr[:, :, 1] = (arr[:, :, 1] - arr[:, :, 1].min()) / (arr[...
from .serializers import DiveSiteSerializer from .models import DiveSite from rest_framework import generics class DiveSiteList(generics.ListCreateAPIView): queryset = DiveSite.objects.all() serializer_class = DiveSiteSerializer class DiveSiteDetails(generics.RetrieveUpdateDestroyAPIView): queryset = Dive...