text
stringlengths
8
6.05M
#!/usr/bin/env python3 import sys def usage(): print("Usage") print(" tohex.py 0x123") print(" tohex.py 0b101") print(" tohex.py 12345") print("") exit(0) def printDEC(parsed): print("DEC %i" % parsed) def printHEX(parsed): print('HEX 0x%x' % parsed) def printBIN(parsed...
vo=['a','e','i','o','u'] n=input() if n in vo: print("vowel") else: print("consonant")
# pylint: disable=protected-access """ Test the wrappers for the C API. """ import os import pytest from ..clib.core import load_libgmt, _check_libgmt, create_session, \ destroy_session, call_module, get_constant from ..clib.context_manager import LibGMT from ..clib.utils import clib_extension from ..exceptions i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __version__ = '1.0.1' from sanic.log import logger from sanic.request import Request from .specification.create_hw_command_specification import ( create_hw_command_element_query, create_hw_command_element_rent_query ) from .specification.get_hw_command_specification ...
from direct.distributed.DistributedObjectAI import DistributedObjectAI from direct.directnotify import DirectNotifyGlobal class DistributedJollyRogerAI(DistributedObjectAI): notify = DirectNotifyGlobal.directNotify.newCategory('DistributedJollyRogerAI') def __init__(self, air): DistributedObjectAI.__i...
import unittest from katas.kyu_7.descending_order import Descending_Order class DescendingOrderTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(Descending_Order(0), 0) def test_equals_2(self): self.assertEqual(Descending_Order(15), 51) def test_equals_3(self): ...
#!usr/bin/python # -*- coding: utf-8 -*- from __future__ import print_function, division import torch import torch.nn as nn import torch.nn.functional as F from torch.nn import Parameter from torch.autograd import Variable """ Desc: compute MarginCosineProduct Date: 2019/05/13 Author: Jesse Contact: ...
from direct.showbase.DirectObject import DirectObject from bsp.leveleditor.ui.HistoryPanel import HistoryPanel class ActionEntry: def __init__(self, desc, action): self.desc = desc self.action = action def do(self): self.action.do() def undo(self): self.action.undo() ...
from flask import request from sqlalchemy import desc from flask_restful import Resource, marshal_with from ..fields import Fields from app.models.models import SaleGroup, db sale_group_fields = Fields().sale_group_fields() class SaleGroupListAPI(Resource): @marshal_with(sale_group_fields) def get(self): ...
from datetime import datetime, timedelta from django import forms from django.http import HttpResponseRedirect from django.urls import reverse, reverse_lazy from django.shortcuts import get_object_or_404, render from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteV...
import numpy as np sigmoid_range = 34.538776394910684 def sigmoid(x): return 1.0 / (1.0 + np.exp(-np.clip(x, -sigmoid_range, sigmoid_range))) def derivative_sigmoid(o): return o * (1.0 - o) # 3層ニューラルネットワーク class ThreeLayerNetwork: # コンストラクタ def __init__(self, inodes, hnodes, onodes, lr): ...
n = int(input("Enter the length of the sequence: ")) # Do not change this line num1 = 0 num2 = 0 num3 = 1 for i in range(n): temp3 = num3 num3 = num1 + num2 + num3 if i > 1: num1 = num2 num2 = temp3 print(num3) 1 - 1+0+0 2 - 1+1+0 3 - 2+1+0 4 - 3+2+1
from django.db.models import Manager from django.core.exceptions import ObjectDoesNotExist from django.apps import apps from rest_framework.exceptions import ValidationError, NotFound from ..common.utils import on_time class OrderManager(Manager): @on_time def place_order(self, **model_attributes): "...
from threading import Thread import random, time class Producer(Thread): def __init__(self, queue, condition): super(Producer, self).__init__() self.queue = queue self.condition = condition def run(self): nums = range(5) while True: self.condition.acquire()...
"""Factories for core application.""" import factory from django.contrib.auth.models import Group from . import models class PermissionFactory(factory.django.DjangoModelFactory): """A base factory to handle permissions.""" class Meta(object): abstract = True @factory.post_generation def ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 24 15:58:02 2017 @author: dgratz """ import numpy as np from glob import glob from readFile import readFile import re from ParameterSensitivity import ParamSensetivity import matplotlib.pyplot as plt from calcSync import calcTimeSync, calcSyncVarLen...
import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Rectangle from skimage import io def load_image(fname): return io.imread(fname) / 256. class Dataset: def __init__(self, X, Y): self.X = X self.Y = Y self._epochs_completed = 0 self._index_in_e...
class Dagger(): damage = 3 def __init__(self, damage): self.damage = damage def get_damage(self): return self.damage class Longsword(): damage = 5 def __init__(self, damage): self.damage = damage def get_damage(self): return self.damage class Scimitar()...
#!/usr/bin/env python # Python script created by Lucas Hale # Standard Python libraries from __future__ import (absolute_import, print_function, division, unicode_literals) import os import sys import glob import uuid import shutil from copy import deepcopy # http://www.numpy.org/ import nump...
#!/usr/bin/env python import argparse import yaml import os import io import sys import shutil current_dir = os.path.dirname(os.path.realpath(__file__)) os.chdir(current_dir) # consts NEW_LINE = "\n" NEW_LINE_1 = "\n " CMD_CONJUCTION_1 = " && \\\n " def generateImageDir(name, image, config): ...
def mean(mylist): the_mean=sum(mylist)/len(mylist) return the_mean # print(mean([2,4,6,8])) print(type(mean), type(sum))
# Scratch doc import pandas as pd import numpy as np import geopandas as gpd from shapely.geometry import Point, LineString from geopy.distance import geodesic from sodapy import Socrata # Function to calculate distance between from_location and to_location def get_dist(row): # Get point tuples. from_loc = ...
import os import time import logging import threading import paho.mqtt.client as mqtt from queue import Queue class mqttwrapper(threading.Thread): def __init__(self,config,logger): threading.Thread.__init__(self) print(logger) self._rootLogger = logger _libName = str(__name__....
import os import sys import asyncio import string import random import time import fnmatch class random_creation(): def __init__(self, path,): self.path = path def string_generator(self, size,): chars = string.ascii_uppercase + string.ascii_lowercase return ''.j...
#!/usr/bin/python # -*- coding: cp936 -*- import sqlite3 from SQLiteQuery.capitalQuery import * from SQLiteDataProcessing.userDayATradeUtility import * ''' prerequisite: run getsheet2() ''' class accountCapital: def generateAccountCapitalExcelFromSQLite(self): with sqlite3.connect('C:\sqlite\db\hxdat...
from random import shuffle def start_situation(number_of_players, include_multicolor): # check if given input is an integer and value 2-5 try: number = int(number_of_players) except ValueError: print("error: please enter an integer for number of players") return else: i...
import argparse import os from tensorflow.contrib.learn.python.learn.utils import ( saved_model_export_utils) from tensorflow.contrib.training.python.training import hparam # --------------------------------------------------- # Library used for loading a file from Google Storage # --------------------------------...
import math x = math.pi/4 val = math.sin(x)**2 + math.cos(x)**2 print val v = 3 #m/s t = 1 #sec a = 2 #m/s**2 s = ((v * t) + ((1.0/2.0) * a * (t**2))) print s, "meters" a = float(input("Enter the first number")) b = float(input("Enter the second number")) e1 = ((a+b)**2) e2 = (a**2)+(2*a*b)+(b**2) if e1 == e2: pr...
from torch import gt from backpack.core.derivatives.elementwise import ElementwiseDerivatives class ReLUDerivatives(ElementwiseDerivatives): def hessian_is_zero(self): """`ReLU''(x) = 0`.""" return True def df(self, module, g_inp, g_out): """First ReLU derivative: `ReLU'(x) = 0 if x ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import os from absl import flags import numpy as np import cv2 from tqdm import tqdm import skimage.io as io import tensorflow as tf from src.util import renderer as vis_util from src.util import i...
class JobRegistry(set): @property def classes(self): return self JobRegistry = JobRegistry() from .cleanup import * from .comment import * from .commit import * from .event import * from .general import * from .githubuser import * from .issue import * from .label import * from .milestone import * fr...
# To change this license header, choose License Headers in Project Properties. # To change this template file, choose Tools | Templates # and open the template in the editor. import itertools #libreria de python para poder usar iteradores import timeit #libreria python para poder utilizar el timer import sys #libreria...
from django.db import models from core.models import UserProfile from django.contrib.auth.models import User from tastypie.models import ApiKey import datetime #class PhotoUrl(models.Model): # url = models.CharField(max_length=128) # uploaded = models.DateTimeField() # # def save(self): ...
import json class InsightsEndpointsMixin(object): """For endpoints in related to insights functionality.""" def insights(self): """ Get insights :param day: :return: """ params = { 'locale': 'en_US', 'vc_policy': 'insights_policy', ...
'''Finding Numbers in a Haystack In this assignment you will read through and parse a file with text and numbers. You will extract all the numbers in the file and compute the sum of the numbers. Data Files We provide two files for this assignment. One is a sample file where we give you the sum for your testing and th...
import pika import sys, os import time import uuid class RpcServer(object): def __init__(self): self.conn = pika.BlockingConnection(pika.ConnectionParameters(host='localhost')) self.channel = self.conn.channel() def fib(self, n): # 定义一个主逻辑:斐波那契数列.===>程序的处理逻辑在这里写. if n == 0: ...
import time, unittest, os, sys from selenium import webdriver from main.page.desktop_v3.login.pe_login import * from main.page.desktop_v3.product.pe_product import * from main.activity.desktop_v3.activity_login import * from main.activity.desktop_v3.activity_product import * from utils.function.setup import * from util...
from graphics import * import time win=GraphWin("A STRAIGHT LINE USING DDA LINE DRAWING ALGORITHM",900,900) def main(): xc=int(input()) yc=int(input()) rx=int(input()) ry=int(input()) ellipse(xc,yc,rx,ry) win.getMouse() win.close() def ellipse(xc,yc,rx,ry): p=ry*ry-rx*rx*ry+rx*rx/4 x...
from gym_connect_four import RandomPlayer class Vlada(RandomPlayer): """ Clone of RandomPlayer for runner.py illustration purpose """ pass
from node import Node import threading f = open("input", 'r') lines = f.readlines() n = int(lines[0]) nodes = {} for i in range(1, n+1): nodes[i] = Node(uid=i, network_size=n) uid = -1 for i in range((n * n) + 1): if len(lines[i].split()) == 4: tokens = lines[i].split() uid = int(tokens[0...
import requests class YunPian(object): def __init__(self, api_key): self.api_key = api_key self.single_send_url = 'https://sms.yunpian.com/v2/sms/single_send.json' def send_sms(self,code ,mobile): parmas = { "apikey": self.api_key, "mobile": mobile, ...
import socketserver import os import sys import time import threading ip_port=("172.18.0.3",19984) class MyServer(socketserver.BaseRequestHandler): def handle(self): print("conn is :",self.request) # conn print("addr is :",self.client_address) # addr while True: ...
import numpy as np import matplotlib.pyplot as plt from stuckpy.image.text import string_to_array def append_scale_bar(image, scale): rows, cols = image.shape white = np.max(image) # Add a blank region at the bottom for the meta data res_factor = int(rows/1000) # 1 per 1000 pixels of resolution sc...
from math import sin,cos import pymunk import pyglet from pyglet.gl import * class Jelly: def __init__ (self, space, position, radius, bounciness, shape_group, color, batch, order_group): self.space = space self.radius = radius #self.color = color #self.group = group self.bo...
#!/usr/bin/python import sys, pickle from os import listdir, path from icepy import * from icecube.dataio import I3File from icecube import simclasses, recclasses from icecube.phys_services import I3Calculator #############################################################################################################...
#This problem was asked by Snapchat. #Given an array of time intervals (start, end) #for classroom lectures (possibly overlapping), #find the minimum number of rooms required. #For example, given [(30, 75), (0, 50), (60, 150)], you should return 2. def min_intervals(intervals): intervals.sort(key=lambda i:i[0]) ...
""" Plot Receiver Operating Characteristic (ROC) curve. The ROC curve, a caracteristic of a binary classifier, is obtained by plotting the *true positive rate* (TPR, also known as *sensitivity* or *recall*) .. math:: \\text{TPR} = \\frac{\\text{TP}}{\\text{TP} + \\text{FN}} versus the *false positive rate* ...
from application import app from flask_sqlalchemy import SQLAlchemy from flask import request app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost/book' db=SQLAlchemy(app) class Login(db.Model): sno = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(20), unique=False, nullable=Fals...
from PyQt5.QtWidgets import QWidget, QLabel, QTextEdit, QGridLayout from PyQt5.QtGui import QPixmap import configparser import requests import time import random import hmac, hashlib, base64, json, binascii class AnalysisWindow(QWidget): def __init__(self, filename, x, y): super().__init__() self....
import ROOT import numpy as np import matplotlib.pyplot as plt #from plotter import Plotter def scatter(file_1, file_2, name, run): print "Creating scatter plot." print "First file: {0}".format(file_1) print "Second file: {0}".format(file_2) # XKCD Colors pinkish_red = "#f10c45" azure = "#069a...
import datetime import time from datetime import timedelta class GetTime: @staticmethod def get_current_time(): current_now = datetime.datetime.now() current_time = current_now.strftime("%Y-%m-%d %H:%M:%S") current_time_num = int(time.time() * 1000) return {"current_time": curr...
''' forms.py ------------------- Define form in _CensusImputeForm, create instances using CensusImputeForm ''' from flask_wtf import FlaskForm from wtforms import SelectField, DecimalField, BooleanField class CensusImputeForm(): def __init__(self, data_dict, numeric_fields, recordname2description): self....
from lib.imageExtractor import ImageExtractor from bs4 import BeautifulSoup import urllib.parse, urllib.request import requests import requests.exceptions import re import os import shutil class WebsiteExtractor(ImageExtractor): """ This class allows to download all the images from a given website. """ ...
#! /usr/bin/env python3 """ collection_interface.py - Collect stats in database and display it on a webpage Author: - Pablo Caruana (pablo dot caruana at gmail dot com) Date: 12/3/2016 """ from database_manager import DatabaseManager from flask import Flask, jsonify, request, render_template app =...
import datetime import simplejson from django.db.models import Q from django.http import HttpResponse from fts3.models import Job, File def uniqueSources(httpRequest): query = Job.objects.values('source_se').distinct('source_se') if 'term' in httpRequest.GET and str(httpRequest.GET['term']) != '': qu...
# -*-coding=utf-8-*- __author__ = 'Rocky' ''' http://30daydo.com Contact: weigesysu@qq.com ''' import requests from lxml import etree session = requests.Session() from scrapy.selector import Selector get_crsl = 'https://passport.zujuan.com/login' first_header = {'Host': 'passport.zujuan.com', 'Connection': 'keep-al...
import tensorflow as tf import numpy as np class Classifier: def __init__(self, chromosome, x_train, x_test, y_train, y_test, batch_size, epochs, seed, lamarckian): self.train_g = tf.Graph() self.sess = tf.Session(graph = self.train_g) # self.test_g = tf.Graph() s...
import pandas as pd # import dataset data = pd.read_csv('seeds_dataset.csv') # pisakhan data dan label X = data.iloc[:, :-1].values y = data.iloc[:, len(data.columns)-1].values # split trining and test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_spl...
from jinja2 import Template import random import base64 from flask import Flask, render_template_string, request, render_template, current_app, url_for app = Flask(__name__) @app.route("/", methods=["GET"]) def index(): strings = ['Uniandes', 'UNIANDES', 'Mario Laserna', 'Carlos Pacheco Devia', 'Sala Turing', 'Sa...
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import threading import pytest from pants.pantsd.service.pants_service import PantsService class RunnableTestService(PantsService): def run(self): pass @pytest.fixture de...
from info.info import TestData from pages.BasePage import BasePage from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys class MainPage(BasePage): """Locators""" START_FOR_FREE_BUTTON = (By.XPATH, '/html/body/div[1]/div/div[2]/div[3]/div/a') LOGIN_BUTTON = (By.XPATH, ...
import requests import urllib.request import json # Chien Json CHIEN_URL = 'https://rti-giken.jp/fhc/api/train_tetsudo/delay.json' # Get Chien JSON def get_chien(keyword): req = urllib.request.Request(CHIEN_URL) with urllib.request.urlopen(req) as res: #res = urllib2.urlopen(CHIEN_URL) datas= js...
import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib.colors import SymLogNorm from matplotlib.colors import LogNorm from mpl_toolkits.mplot3d import Axes3D import scipy.stats as stats import numpy as np import pandas as pd import h5py import os import subprocess import time from collections import C...
"""The simplest way to create bit-flags. Basic usage ----------- >>> import intflags >>> x, y, z = intflags.get(3) >>> flags = x | y >>> y in flags True >>> z in flags False >>> int(y) 2 In a class ---------- >>> class MyFlags: ... A, B, C, D = intflags.get(4) ......
# pylint: disable=missing-docstring from ._version import __version__ from .application import Application, WebApplication from .page import WebPage from .element import WebElement
from graphics import * import time win=GraphWin("A STRAIGHT LINE USING DDA LINE DRAWING ALGORITHM",900,900) def main(): line(100,100,200,300) win.getMouse() win.close() def line(x1,y1,x2,y2): dx=x2-x1 dy=y2-y1 x=x1 y=y1 p=2*(dy-dx) while(x<x2): if(p>=0): put_pixel...
from django.db import models from django.conf import settings from datetime import datetime from django.contrib.postgres.fields import ArrayField class Log(models.Model): subject = models.CharField(max_length=100) created_at = models.DateTimeField(auto_now_add=True) last_update = models.DateTimeField(au...
import re # Email validation checker email_pattern = re.compile(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)") s = 'andy.mtv12@gmail.com' email = email_pattern.search(s).group() if email_pattern.search(s) else 'incorrect email' print(email) # at least 8 characters length, lowercase and uppercase, symbols $%#...
import random from time import time def quicksort(alist,start,end): if start < end: pivot = partition(alist,start,end) quicksort(alist,start,pivot-1) quicksort(alist,pivot+1,end) def partition(alist,first,last): pivot = alist[first] leftmark = first + 1 rightmark = last ...
from queries import UPDATE_USER_EXPERIENCE from queries import DELETE_USER from app import experience from queries import READ_USER_EXPERIENCE from queries import INSERT_INTO_DATABASE_EXPERIENCE from flask import Flask,render_template,request,redirect from decouple import config from flask_mysqldb import MySQL ...
def is_rotation(s1, s2): return s1 in s2 + s2 and len(s1) == len(s2)
# Generated by Django 2.2.13 on 2020-07-16 17:26 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('product', '0022_auto_20200712_1630'), ] operations = [ migrations.AddField( model_name='product', name='amount', ...
#!/usr/bin/env python3.8 import sys,os,getopt from lxml import etree def extractInterrupts(mplabXDir:str,chipName:str): root:lxml.etree._ElementTree=etree.parse(os.path.join(mplabXDir, chipName + ".atdf")) family=str(root.xpath("devices/device/@family")[0]) interrupts = root.xpath("devices/device/interrupts/inte...
#!/usr/bin/python import nltk from nltk.corpus import stopwords import re import json pythonDictionary = {'name':'Bob', 'age':44, 'isEmployed':True} dictionaryToJson = json.dumps(pythonDictionary) class InputReadAndProcess(object): def __init__(self): #print("hello") self.inp = "" self.content...
from django.contrib.auth.models import User from rest_framework.test import APITestCase from rest_framework.status import HTTP_401_UNAUTHORIZED, HTTP_200_OK from pycont.apps.users.serializers import UserSerializer class AuthTest(APITestCase): def setUp(self): User.objects.create_user('sieira', password=...
from django.apps import AppConfig class ExpoCmsConfig(AppConfig): name = 'expo_cms'
from pathlib import Path import xml.etree.ElementTree as ET import re from nltk import Tree from collections import deque from typing import List, Any from babybertsrl.srl_utils import make_srl_string from babybertsrl import configs NAME = 'human-based-2018' XML_PATH = Path(f'data/srl_{NAME}/xml') VERBOSE = False EXC...
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- # File: osc4py3/oscchannel.py # <pep8 compliant> """Base classe for OSC data transmission. TransportChannel provides basic options common to communication. TransportChannel subclasses are used for communication with peer OSC systems. They wrap transmission of OSC packe...
from game import * from model import * #Create places to lay out the foundation of the world places = { "tgh" : Place(name="The Great Hall", description="It's a hall and it's great"), "tsh" : Place(name="The Small Hall", description="It's a hall and it's small"), "td" : Place(name="The Dungeon...
#Code to find the lowest common ancestor between two nodes class Node: def __init__(self,key): self.key=key self.left=None self.right=None def findPath(root,path,k): if(root is None): return False path.append(k) if(root.key==k): ...
from Deck_creation import draw, listed, deck, game l = listed() game_deck = deck(1) total_players = game(3) player_1_hand = total_players[0]; player_2_hand = total_players[1] # Turn base stop1 = True stop2 = True result1 = 0 result2 = 0 active_player = 1 def winner(): print("Player 1 had a tot...
import asyncio from math import ceil from shared.utils import get_time class Housekeeping(): # ------------------------------------------------------------------ async def cleanup_loop(self, loop_info): self.log.info([ ['y', ' - starting '], ['b', 'cleanup_loop'], ...
first_list = [int(i) for i in input("Enter numbers separated by spaces and press Enter:").split()] second_list = [int(j) for j in input("Enter numbers separated by spaces and press Enter:").split()] same = "" first_uniq = "" second_uniq = "" for k in range(len(first_list)): if first_list[k] in second_list: ...
def result(ns): for i in range(9): for j in range(i+1, 9): if sum(ns) - ns[i] - ns[j] == 100: return i, j ns = list() for _ in range(9): ns.append(int(input())) ns = sorted(ns) i, j = result(ns) for idx, n in enumerate(ns): if idx != i and idx != j: print(n)
#knAudio.py """ Programmer: Keith G. Nemitz E-mail: keithn@mousechief.com Version 0.0.1 Development """ import pyglet import knTimers daSong = None daSinger = None; faderTimer = None; #------------------------------------------- def LoadSFX(name): return pyglet.resource.media(name,streaming=False); def...
# LEVEL 5 # http://www.pythonchallenge.com/pc/def/peak.html import pickle test = {'a': 2, 'b': 4, 'c': 6, 'alongstring0': 'averylongstringindeed0', 'alongstring1': 'averylongstringindeed1', 'alongstring2': 'averylongstringindeed2', 'alongstring3': 'averylongstringindeed3', 'alo...
import pyttsx k = pyttsx.init() def say(text): k.say(text) k.runAndWait() say('Hello')
import numpy as np import scipy.signal as scs def todo_specification_separate_channels(u,v): nrowu,ncolu,nchu = u.shape w = np.zeros(u.shape) for i in range(3): uch = u[:,:,i] vch = v[:,:,i] u_sort,index_u=np.sort(uch,axis=None),np.argsort(uch,axis=None) v_sort,index_v=np.so...
# @Time :2019/7/21 13:48 # @Author :jinbiao from Python_0719_job import match_count from Python_0719_job.operation_excel import OperationExcel import unittest from ddt import ddt, data oe = OperationExcel(excel_name="test_data.xlsx", sheet_name="divide") test_data = oe.get_data() @ddt class Testoperation(unittest.Te...
# -*- coding: utf-8 -*- """ Created on Sun Oct 28 18:25:33 2018 @author: PPAGACZ """ import abc from packets import * class IPipe(abc.ABC): @abc.abstractmethod def runFilter(self): pass @abc.abstractmethod def checkConditions(data): pass
# coding=utf-8 import ConfigParser import os import sys sys.path.append(os.getenv('PY_DEV_HOME')) from webTest_pro.common.logger import logger from webTest_pro.common.os_sqlfile_read import getSqlPath reload(sys) sys.setdefaultencoding("utf-8") home_path = os.environ.get('PY_DEV_HOME') def getCfgPath(): tmpEn...
from django.shortcuts import render, redirect from .models import Food from .form import FoodForm def food(request): foods = Food.objects.all() return render(request, 'food.html', {"foods": foods}) def create_food(request): form = FoodForm(request.POST or None) if form.is_valid(): form.save(...
import unittest from TemplateConverter import TemplateConverter class TestConverter(unittest.TestCase): def test_multiplePlaceHolders(self): lines = ["$from_res&#8212;$to_res records out of $nrows.\n"] converter = TemplateConverter(lines, "test_notPlaceholder") convertedLines = converter....
#!/usr/bin/python A="10" def func(A): A = 2 func(2) print("A is now",A) def func1(A): A = 5 return A A=func1(5) print("A is now",A)
import requests from datetime import datetime, timedelta import plotly.graph_objects as go import plotly.express as px import numpy as np import os, shutil import json API_KEY = os.environ.get('API_KEY') if API_KEY: print(f'API_KEY of length {len(API_KEY)} retrieved.') else: print('Retrieving API KEY locally....
#LISTAS ''' numeros = [1, 2, 3, 4, 5, 6] print(numeros) print(numeros[0]) print(numeros[3]) print(len(numeros)) text = ["A", "B", "C"] print(text) print(text[2]) print(text[len(text) - 1]) # NOS DEVUELVE LA ÚLTIMA POSICIÓN variada = [1, 2, 3, 4.2, False, "Hey"] print(variada) ''' #BUCLE FOR ''' #NORMAL for variable...
### Laura Buchanan ### lcb402 import unittest from grade_funcs import * import os.path class test_grade_funcs(unittest.Testcare): test load_restaurant_data(self): self.assertTrue(os.path.isfile('../clean_data.csv') self.assertFalse(os.path.isfile('./clean_data.csv') test_year(self): self.assertTrue(len(ye...
# coint_bollinger_strategy.py from __future__ import print_function from collections import deque from math import floor import numpy as np from qstrader.price_parser import PriceParser from qstrader.event import (SignalEvent, EventType) from qstrader.strategy.base import AbstractStrategy class CointegrationBolli...
from django.shortcuts import render from django.views.generic.edit import CreateView from django.contrib.auth.views import LoginView from django.contrib.auth import login, authenticate from .utility import SIGNIN_TEMPLATE, SIGNUP_TEMPLATE, SIGNUP_SUCCESS_URL, SIGNIN_TITLE, SIGNUP_TITLE from login.forms import UserSignI...
def hello(a): """ string a parameter printed """ return f"Hello {a}"