text
stringlengths
38
1.54M
""" 3 # @File : scenario_reduction.py 4 # @Author: Chen Zhen 5 # @Date : 2019/9/17 6 # @Desc : reduce the number of scenarios based on the paper: A two stage stochastic programming model for lot-sizing and scheduling under uncertainty (2016) in CIE. """ import numpy as np i...
import time # webdriver это и есть набор команд для управления браузером from selenium import webdriver from selenium.webdriver.support.ui import Select # инициализируем драйвер браузера. После этой команды вы должны увидеть новое открытое окно браузера driver = webdriver.Chrome("C:/chromedriver/chromedriver.exe") ...
import webbrowser class Movie(): # Initialize the movie class with multiple fields def __init__(self, title, year, description, rating, poster, trailer): self.title = title self.year = year self.description = description self.rating = rating self.poster_image_url = post...
#http://coderbyte.com/CodingArea/GuestEditor.php?ct=Letter%20Capitalize&lan=Python ''' Using the Python language, have the function LetterCapitalize(str) take the str parameter being passed and capitalize the first letter of each word. Words will be separated by only one space. Input = "hello world"Output = "Hello Worl...
from django.contrib import admin from .models import Choice, Question from .models import Choice admin.site.register(Question) admin.site.register(Choice) #class QuestionAdmin(admin.ModelAdmin): # fieldsets = ['pub_date' ,'Question_text']
def leftrotation(the_array, times): i=0 while i < times: array_var = the_array[0] the_array.append(array_var) the_array.remove(array_var) i += 1 print(the_array) array_1 = [1,2,3,4,5] leftrotation(array_1, 3)
import torch import torch.nn as nn import numpy as np from scipy import sparse from scipy.sparse.linalg import svds import matplotlib.pyplot as plt from math import isnan import csv zeros = np.zeros pinv = np.linalg.pinv DATA_PATH = "./data/ml-100k/u.data" def MoiveAvgRating(sparseDataMatrix:sparse.c...
import lang import flect class ComponentDefinition(object): __slots__ = [ "name", "language", "interpreter" ] def __init__(self, name, language): self.name = name self.language = language def create_component(self): return None def initilize_interpreter(self, interpreter): ...
# our prime list is empty here primes = [] def is_prime(x): a = True for i in primes: if x % i == 0: a = False break if i > int(x ** 0.5): break if a: primes.append(x) return a # this loop simply runs the fxn to add newer primes for i in ra...
from datetime import datetime from googleads import adwords, oauth2 import random, time, uuid, ast import urllib.request as urllib2 MAX_POLL_ATTEMPS = 5 PENDING_STATUSES = ("ACTIVE", "AWAITING_FILE", "CANCELING") API_VERSION = "v201702" class BatchJob(object): def __init__(self, client): self.batchJobHelper = ...
from tornado.web import Application from handlers.employees import EmployeesHandler, EmployeeHandler def make_app(): return Application([(r'/api/employees', EmployeesHandler), (r'/api/employees/([^/]+)', EmployeeHandler)])
''' copy the whole directory to dpm ''' # Standard imports import os # default locations from StopsDilepton.samples.default_locations import default_locations # Arguments import argparse argParser = argparse.ArgumentParser(description = "Argument parser for cmgPostProcessing") #argParser.add_argument('--logLevel', ...
# -*- coding: utf-8 -*- """ Created on Thu May 03 15:56:31 2018 @author: MATTEK6 grp 2 """ from path_import import _gaincalculation from wmn_main import _interferencelimit from main import main import numpy as np import scipy as sc import matplotlib.pyplot as plt import warnings warnings.filterwarnings("ignore") de...
number = int(raw_input("give me a number: ")) if (number%3 == 0) and (number%5 == 0): print("Fizz Buzz") elif (number%3) == 0: print("Fizz") elif (number%5) == 0: print("Buzz") else: print("Please enter another number.")
#!/usr/bin/python """ ============================================================================== Author: Tao Li (taoli@ucsd.edu) Date: Jul 10, 2015 Question: 150-Evaluate-Reverse-Polish-Notation Link: https://leetcode.com/problems/evaluate-reverse-polish-notation/ =========================================...
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' @Author : xueqiang.liu @contact : xqliu@dragondropinn.com @Date : 2019/6/24 @Description :fastq文件质控 ''' import os import time import sys import functools from profile import Profile var_path = Profile() def timefly(func): @functools.wraps(func) ...
''' Tests for WMT extract file parser''' import os import pytest from xlrd import XLRDError import wmt_etl.extract_parser as parser THIS_DIR = os.path.dirname(os.path.abspath(__file__)) TEST_DATA_FILE_PATH = os.path.join(THIS_DIR, 'data/WMT_Extract_sample.xlsx') INVALID_DATA_FILE_PATH = os.path.join(THIS_DIR, 'data/In...
# TODO: add name recognition, check for word combinations in handler2, thread handler2 with a separate dict from bs4 import BeautifulSoup from PIL import Image import urllib import unidecode import pyscreenshot import sys, os import socket as cv2 #FIX NO NEED SOCKET #import pytesseract import argparse import webbrow...
""" This file contains tools to facilitate the use of the system. """ def generate_connection_string(type_database: str = "", user: str = "", password: str = "", host: str = "localhost", port: str = "", database: str = "") -> str: """ Returns the configuration string for SQLAlch...
from setuptools import Extension, find_packages, setup from codecs import open from os import path from distutils.command.install import INSTALL_SCHEMES import os here = path.abspath(path.dirname(__file__)) def file_content(fpath): with open(path.join(here, fpath), encoding='utf-8') as f: return f.read()...
from abc import abstractmethod import numpy as np from macaw.models import LinearModel, LogisticModel, QuadraticModel from .optimizers import GradientDescent, CoordinateDescent, MajorizationMinimization __all__ = ['L1Norm', 'L2Norm', 'BernoulliLikelihood', 'Lasso', 'RidgeRegression', 'LogisticRegression', ...
''' Name: Sidharth Banerjee ID : 1001622703 ''' import numpy as np import matplotlib.pyplot as plt import soundfile as sf def Gamma(mu, theta): num = 1 - (4/(1+mu))*np.tan(theta/2) den = 1 + (4/(1+mu))*np.tan(theta/2) return num/den def u_n (x, a, g): u = [] u.append(a*x[0]) for n in range (...
from aoc2019.day06.part1 import build_orbits def test_checksum(): orbit_map = build_orbits( ['COM)B', 'B)C', 'C)D', 'D)E', 'E)F', 'B)G', 'G)H', 'D)I', 'E)J', 'J)K', 'K)L', 'K)YOU', 'I)SAN']) orbit_map['YOU'].search(-1) assert(orbit_map['SAN'].dist == 4)
from django.db import models from django.urls import reverse from django.utils.translation import gettext_lazy as _ from club.models import Club from mahjong_portal.models import BaseModel from player.models import Player from rating.calculation.hardcoded_coefficients import AGARI_TOURNAMENT_ID from settings.models im...
#!/usr/bin/python text = " CREATE tabLe MyTable ( country varchar(45),ID integer ,XYI double ) ; " def parseCreateTable(sql): sql = sql.strip() sql = sql[sql.find(" "):].strip() keyWord = str(sql[:sql.find(" ")]).upper() if keyWord != "TABLE": print "error: expected keyword \"Table\...
def base10int(value, base): if (int(value // base)): return base10int(int(value // base), base) + str(value % base) return str(value % base) def b8to10(s): mid = 0 for i in range(len(s)): mid += int(s[len(s)-1-i])*(8 ** i) return mid n, k = map(str, input().split(" ")) ...
import requests import config url = "https://api.yelp.com/v3/businesses/search" headers = { "Authorization" : "Bearer " + config.yelp_api_key } params = { "location": "NYC", "term": "Barber" } response = requests.get(url, headers=headers, params=params) businesses = response.json()["businesses"] names = [...
# -*- coding: utf-8 -*- import re import os from botminer.util.picture import drawBar from botminer.util.ip_statistic import ip_statistic os.chdir('../log/') def analys(): files = os.listdir('../log/') os.chdir('../log/') co = re.compile('Time:.*?event.*?0\n(.*?) ->.*?Port/Proto Range',re.S) ips = set...
def random(): from random import randint x=randint(0,50) return x def obtenerInt(): y = int(input("Ingrese su adivinanza: ")) return y def respuesta(respuesta,intento): if respuesta==intento: print("Ha adivinado el numero. ") exit() elif respuesta > intento: print("El numero ingresado es menor que la re...
"""" Given an array nums. We define a running sum of an array as runningSum[i] = sum(nums[0]…nums[i]). Return the running sum of nums. """ # import List from typing to support hinting in function definition from typing import List class Solution: nums = [1,2,3,4] def runningSum(self, nums: List[int]) -> Li...
""" The restaurant application factory """ import os from flask import Flask, render_template, request, redirect, url_for, flash, jsonify from database import db_session from models import Restaurant, MenuItem def create_app(test_config=None): """ A application factory to create, set and return the restauran...
# Generated by Django 2.0.7 on 2018-08-29 18:38 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('GuildPosts', '0007_auto_20180829_1835'), ] operations = [ migrations.RemoveField( model_name='postmodel', name='PostLink', ...
''' import pdb s = '0' n = int(s) pdb.set_trace() #运行到这里会暂停 print(10 / n) ''' import logging logging.basicConfig(level=logging.INFO) #设置记录信息级别,输出信息 s = '0' n = int(s) logging.info('n = {}'.format(n)) print(10 / n)
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-02 11:10 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('complaint', '0001_initial'), ] operations = [ ...
#!/usr/bin/env python import os import sys low = int(sys.argv[1]) high = int(sys.argv[2]) cmdPrefix = '~/spark-1.4.0/bin/spark-submit --master spark://spark4-master:7077 --driver-memory 20g --executor-memory 14g msg_spark_opt.py ' msgPathIn = 'hdfs://spark4-master:9000/user/yong/msg_analysis/msg_0616/' msgPathOut ...
import re import time import requests class Scraper(object): api_url = None default_headers = () default_params = () default_data = () cache_attrs = () def __init__(self, ratelimit=1): self.ratelimit = ratelimit self._last_request = 0 self.cookies = None self...
def maximum(): for x in range(100): for y in range(100): if((x|y) >= max(x,y))==False: print x,y, (x|y), max(x,y) return False return True print maximum()
# 알파코드(DFS) import sys sys.stdin=open("C:\Python-lecture\Python_lecture\section_7\input.txt", "rt") def DFS(L, P): global cnt if L==n: cnt+=1 for j in range(P): print(chr(res[j]+64), end=' ') print() else: for i in range(1, 27): if code[L]==i: ...
a=list(map(int,input().split())) b=list(map(int,input().split())) yo=0 for i in range(len(b)): if b[i]==0: yo +=1 flag=0 for c in range (len(b)): if yo!=len(b): if b[a[1]-1]!=0: if b[c]>=b[a[1]-1]: flag+=1 else: continue else: if b[c]>b[a[1]-1]: flag+=1 else: continue els...
# target = "https://ticket2.usj.co.jp/t/tkt/ei.do?t=3743|4157|3823|3840|3760|4182|3902|3913|3814&p=20|20|20|20|20|20|20|20|20&m=2" target = "https://ticket2.usj.co.jp/t/tkt/ei.do?t=3743|4157|3823|3840|3760|4182|3902|3913&p=20|20|20|20|20|20|20|20&m=2" new_target = "https://ticket2.usj.co.jp/t/tkt/ei.do?t=4648|4663|4655...
from celery import Celery import sys import os from keras.preprocessing.image import ImageDataGenerator from keras.models import Sequential from keras.callbacks import ModelCheckpoint from keras.layers import Conv2D, MaxPooling2D from keras.layers import Activation, Dropout, Flatten, Dense from keras import bac...
import fileinput def main(): # entrada de dados por arquivo indata = [] for line in fileinput.input(files='in.txt'): indata.append(line.rstrip('\n')) interval = indata[2].split(' ') del indata[-1] Amin, Amax = interval Kmax, R = indata # casting Kmax = int(Kmax) R = in...
# Copyright Contributors to the Amundsen project. # SPDX-License-Identifier: Apache-2.0 import unittest from typing import Any, Dict from mock import patch from pyhocon import ConfigFactory from databuilder import Scoped from databuilder.extractor.sql_alchemy_extractor import SQLAlchemyExtractor class TestSqlAlche...
import tornado.web import json import config class Send_task(tornado.web.RequestHandler): """Provide API for frontend to perform task creation and result visualization """ def get(self, *arg, **kwargs): prob_dict = { 'type' : 'ping', 'url': 'www.baidu.com' ...
#Q: Double the given number using lambda function def double(a): x=lambda a: 2*a print(x(a)) double(25)
from typing import List from models.chat_state import ChatState from models.event_pattern import EventPattern from constants.mattermost_status import MattermostStatus class User: """ Represents a single user, identified by its Mattermost username. """ _mattermost_login = '' _gcal_token_file = '' ...
import torch import torch.nn.modules as nn from torch.utils.data import DataLoader from torchvision import transforms, datasets class RNNNet(nn.Module): def __init__(self): super(RNNNet, self).__init__() self.rnn_layer = nn.RNN(input_size=28, hidden_size=28, num_layers=1, batch_first=True) ...
# Generated by Django 2.1 on 2018-08-29 07:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('shop', '0004_auto_20180828_2309'), ] operations = [ migrations.CreateModel( name='OrderModel', fields=[ ...
from django.contrib import admin from django.urls import path from Main import views urlpatterns = [ path('music/', views.music_search), ]
""" Given an array of numbers, find the length of the longest increasing subsequence in the array. The subsequence does not necessarily have to be contiguous. For example, given the array [0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15], the longest increasing subsequence has length 6: it is 0, 2, 6, 9, 11, ...
#Tatiana Borta #10023231 #CA5 part_a def add(first, second):#add numbers return map(lambda x, y: x+y, first, second) def substract(values):#substract two numbers return reduce(lambda x, y: x-y, values) def devide(first, second):#devide two numbers return map(lambda x, y: x/float(y) if y != 0 else 'nan',fir...
import hashlib with open("min.jpg","rb") as file: string = (file.read()) m = hashlib.md5() m.update(string) result = m.digest() print(result)
import pystan import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import numpy as np import sys import time import arviz as az import xarray as xr #Modify system pathway to ensure import works sys.path.insert(1,'/Users/laurence/Desktop/Neuroscience/kevin_projects/code/mousetask/models/mouse_task_...
import datetime from django.contrib.auth.hashers import make_password from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse from engineers.models import Engineer from engineers.forms import EngineerAddForm from engineers.views import EngineerEditView class Enginee...
import SimpleITK as sitk import numpy as np import csv import os from PIL import Image # perskaitom originalu komp. tomografijos paveiksla ir grazinam ji kaip numpy image def load_itk_image(filename): itk_image = sitk.ReadImage(filename) numpy_image = sitk.GetArrayFromImage(itk_image) numpy_origin = np.a...
import numpy as np # import tensorflow as tf # import keras import random import time import pygame import sys LEFT, UP, RIGHT, DOWN = 0, 1, 2, 3 gridSize = (8, 8) class Game(): def __init__(self): self.direction = LEFT self.length = 1 self.segments = [ (gridSize[0]//2, gridSize[1]//2) ] ...
import os import json import jieba import scipy import random import pickle import numpy as np import pandas as pd from tqdm import tqdm from multiprocessing import Pool from sklearn.metrics.pairwise import cosine_similarity import torch import torch.nn as nn TEST_FLAG = 'test_b' class LoadDataset: def __init__(...
# Generated by Django 2.1 on 2018-08-20 12:31 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Proposed_law', fields=[ ('id'...
import pandas as pd import numpy as np import itertools import os import logging import datetime base_path = os.path.dirname(os.path.abspath(__file__)) today_file = str(datetime.date.today()) work_file = '..\\logs\\' + today_file + '.log' log_path = os.path.join(base_path, work_file) logging.basicConfig(lev...
import numpy as np import imutils import cv2 def order_points(pts): # initialzie a list of coordinates that will be ordered # such that the first entry in the list is the top-left, # the second entry is the top-right, the third is the # bottom-right, and the fourth is the bottom-left rect ...
# 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 # d...
# coding: utf-8 # In[13]: import pywrapfst as ofst import easygui FST_PATH='Lexicon/FSTs/' categories =['Verbs','Nouns','Pronouns','Adjectives','Adverbs','Propositions','Auxillary Verbs'] # In[40]: def set_input_fsm(input_string,ifst,isys): i=0 while input_string[i]!='+': #print(str(i)+ " " + ...
from kafka import KafkaConsumer import yolo import mongoDB import storage_helper import json import os consumer = KafkaConsumer('demo', bootstrap_servers="13.233.230.133:9092") for msg in consumer: print(msg) data = json.loads(msg.value) key = data["blob_id"] storage_helper.download_file(...
from django.urls import path, include from . import views urlpatterns = [ path('', views.index), path('slider/', views.slider) ]
import sys import arguments import numpy as np import time from Instance import Instance def main(args): # Reading file and creating instance problem kwargs = {"maxiters": args.maxiters, "pop_size": args.size} file = "./data/" + args.file instance = Instance.from_file(file, **kwargs) t1 = time.tim...
# -*- coding: utf-8 -*- """ Created on Thu Feb 27 20:03:57 2020 @author: WELCOME """ """ Time Complexity - O(N) Space - O(N) """ class Solution: def maxSumAfterPartitioning(self, A: List[int], K: int) -> int: totalMax=0 h={} def helper(index,total): nonlocal h if ind...
from kafka import KafkaProducer import json class MyKafka(object): def __init__(self, kafka_brokers): self.producer = KafkaProducer( value_serializer=lambda v: json.dumps(v).encode('utf-8'), bootstrap_servers=kafka_brokers ) def send_page_data(self, json_data): ...
"""Tests for the plot module.""" import numpy as np from app.demo.plot import ( model, get_perp, prepare_data, generate_plot_image_string ) from app.demo.plot import offset as plot_offset def test_model(): """Test the class prediction based on the highest score.""" params = np.array([[1, 1, ...
import asyncio import pytest import ucp @pytest.mark.parametrize("server_guarantee_msg_order", [True, False]) def test_mismatch(server_guarantee_msg_order): # We use an exception handle to catch errors raised by the server def handle_exception(loop, context): msg = str(context.get("exception", cont...
# coding: utf8 import wx_spider if __name__ == '__main__': gongzhonghao = input(u'input weixin gongzhonghao:') if not gongzhonghao: gongzhonghao = 'spider' text = " ".join(wx_spider.run(gongzhonghao)) print(text)
from downloader import download from collections import defaultdict import operator download(2017, 8) with open('aoc2017_8input.txt') as inputfile: data = inputfile.read() print(data) operations = {'inc': operator.add, 'dec': operator.sub} registers = defaultdict(int) highest = 0 for line in data.splitlines(): ...
"""Handles how much health bullets and entities have""" import pygame from sprite.sprite_library import RectangleSprite class Health: """A normal health object that keeps track of maximum and remaining HP""" def __init__(self, hp=1, regen=0): """Creates the Health object""" self.max_hp = hp ...
#-*- coding:utf-8 -*- import urllib from bs4 import BeautifulSoup import os import csv from collections import deque import time #//////////////////////////////get data per hour//////////////////////////////# def getRealTimeData(url): # ------------------------------beautifulsoup------------------------------# ope...
# -*- coding: utf-8 -*- # Generated by Django 1.11.8 on 2018-10-11 08:48 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('incubator', '0001_initial'), ] operations = [ migrations.AlterModelOptions( ...
# svg_parser.py # Copyright Max Kolosov 2009 maxkolosov@inbox.ru # http://saxi.nm.ru/ # BSD license import sys from StringIO import StringIO from xml.etree import cElementTree from svg_path_regex import svg_path_parser def print_error(): exc, err, traceback = sys.exc_info() print exc, traceback.tb_frame...
from multiprocessing import TimeoutError from .pool import Pool __all__ = ["Pool", "TimeoutError"]
def pick2(arr): list = [] list.append((arr[0], arr[1])) # tuple list.append((arr[0], arr[2])) list.append((arr[0], arr[3])) list.append((arr[0], arr[3])) for i in range(len(arr)-1): for j in range(i+1, len(arr)): list.append((arr[i], arr[j])) return list # arr = [1, 2, 3...
# !/usr/bin/env python # -*- coding: utf-8 -*- import json import logging import os import time from datetime import datetime import tweepy import requests auth = tweepy.OAuthHandler(os.environ['CONSUMER_KEY'], os.environ['CONSUMER_SECRET']) auth.set_access_token(os.environ['ACCESS_KEY'], os.environ['ACCESS_SECRE...
import SocketServer import socket import math host = 'localhost' port_client = 8557 port_server_sum = '8560' port_server_sub = '8561' port_server_mul = '8562' port_server_div = '8563' port_server_pow = '8564' port_server_sqr = '8565' port_server_log = '8566' class myHandler(SocketServer.BaseRequestHandler): def h...
from django.conf.urls import url from . import views urlpatterns=[ url(r'post_todo_item$', views.add_todo_item,), url(r'add_todo_items$', views.add_todo_items,), url(r'get_todo_items$', views.get_todo_items), url(r'put_todo_item$',views.put_todo_item), url(r'delete_todo_item$',views.delete_todo_ite...
#!/usr/bin/env python """Script used for performing a forward pass on a previously trained model and visualizing the predicted primitives. """ import argparse import os import sys import numpy as np import torch import trimesh from simple_3dviz import Mesh, Spherecloud from simple_3dviz.behaviours import SceneInit fr...
def gcd(a,b): while b != 0: a, b = b, a%b return a def coprime(a,b): r=0. if gcd(a,b) == 1: r=1. return r for N in range(4,51): t=4*(N-2)*(N-1)+4*(N-4)*(N-2) for y in range(3,N/2+1): for x in range(1,y/2+1): t=t+8*coprime(x,y)*(N-2*y)*(N-y) print...
# coding: utf-8 from django.db import models # Create your models here. class User(models.Model): """ユーザー""" nfc_id = models.CharField('NFCID', max_length=64,primary_key=True) employee_no = models.CharField('社員番号', max_length=64) name = models.CharField('氏名', max_length=256) def __unicode__(self):...
from django.http import HttpResponse from django.shortcuts import render_to_response from subprocess import check_call, CalledProcessError from django.template import RequestContext import json, httplib def contact(req): return HttpResponse('Not Implemented Yet', status=501) def about(req): context = RequestC...
from plotly.offline import plot, iplot import plotly.graph_objs as go import numpy as np import matplotlib as mpl import plotly.plotly as py from plotly.offline import init_notebook_mode init_notebook_mode(connected=True) x_negative = ["X8","X7","X6","X5"] x_positive = ["X4","X3","X2","X1"] y_negative = [1...
#RPG Dice system #by Fábio Pinto import random def rollDice(): dice = input(f'\nChoose a dice to roll.(d2, d4, d6, d8, d10, d12, d20, d100)\n') if str(dice.lower())[0].isalpha(): rollSingleDie(dice) elif str(dice.lower())[0].isnumeric(): rollMultiDice(dice) else: print('To rol...
from sqlalchemy import * from migrate import * from migrate.changeset import schema pre_meta = MetaData() post_meta = MetaData() options = Table('options', post_meta, Column('id', Integer, primary_key=True, nullable=False), Column('opt', String(length=140)), ) question = Table('question', post_meta, Colu...
# -*- coding: utf-8 -*- from ._TIC_Tools import * from datetime import datetime from datetime import timedelta from io import BytesIO, StringIO def _read_stream2(stream, length): # if not isinstance(length, int): # raise TypeError("expected length to be int") if length < 0: raise ValueError("length must be >= 0...
from django.urls import path from . import views from django.contrib.auth import views as auth_views urlpatterns = [ path('register/', views.registerPage, name='register_page'), path('login/', views.logInPage, name='log_in_page'), path('logout/', views.logOutPage, name='log_out_page'), path('password-r...
class User(): def __init__(self, id_, name, setting): self.id = id_ self.name = name self.setting = setting def __str__(self): user_str = f'id::{self.id}, name::{self.name}' # noqa return user_str + str(self.setting)
import numpy as np import scipy.sparse as sparse import time class richards: def __init__(self,nhru,nsoil): self.theta = np.zeros((nhru,nsoil)) self.thetar = np.zeros(nhru) self.thetas = np.zeros(nhru) self.b = np.zeros(nhru) self.satpsi = np.zeros(nhru) self.ksat = np.zeros(nhru) self.dem = np.zeros(...
from tastypie import fields class UserResource(ModelResource): class Meta: queryset = User.objects.all() resource_name = 'user' authorization= Authorization() class ClientResource(ModelResource): class Meta: queryset = Client.objects.all() resource_name = "client" authorization= Authorization() class ...
from __future__ import print_function import ROOT import pytest import re PDG_PARTICLES = [ 1, 2, 3, 4, -313, -213, 221, 323, 21, 310, 313, 223, -323, 213 ] KNOWN_PARTICLES = { "Xi", "Sigma", "Lambda", "Delta", "rho", "omega", "eta", "phi", "pi" } def pdg2name(x): return ROOT.TParticle(x, *[0] ...
import os import csv import statistics csvpath = os.path.join("..","Resources","budget_data.csv") with open(csvpath, newline='', encoding= 'utf-8') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') csv_header = next(csvreader) Month =[] Total=[] Profit=[] for row in csvreader: ...
import numpy as np STUDENT = {'name': 'sam mordoch ,dvir ben abu', 'ID': '313295396 204675235'} from loglinear import softmax def classifier_output(x, params): # YOUR CODE HERE. # z is the layer before activate the activation function. z_layers = [] # h is the layer after activation functi...
import torch def initialze_cuda(SEED): """Initialize the GPU if available Arguments: SEED : The value of seed to have amplost same distribution of data everytime we run the model Returns: cuda: True if GPU is available else False device: 'cuda' or 'cpu' """ cuda = torch.cud...
from .scanLog import scanLog from .antfits import ANTFITS from .dcrfits import DCRFITS #import argparse import numpy import pylab as plt from scipy import signal from numpy import random from scipy.optimize import curve_fit #import pyfits def gauss(x, height, width, center, offset): return height * numpy.exp(-(x...
''' 给你一个大小为 m x n 的网格和一个球。球的起始坐标为 [startRow, startColumn] 。你可以将球移到在四个方向上相邻的单元格内(可以穿过网格边界到达网格之外)。你 最多 可以移动 maxMove 次球。 给你五个整数 m、n、maxMove、startRow 以及 startColumn ,找出并返回可以将球移出边界的路径数量。因为答案可能非常大,返回对 109 + 7 取余 后的结果。 示例 1: 输入:m = 2, n = 2, maxMove = 2, startRow = 0, startColumn = 0 输出:6 示例 2: 输入:m = 1, n ...
""" HTML web scratching """ from lxml import html import requests from bs4 import BeautifulSoup import time import pandas as pd import xml.etree.ElementTree as ET with open('GPL11154.txt') as f: ff = f.readlines() GSE = [] GSE_number = [] for item in ff: if "GSE" in item: a = item.strip() b = a[a.find('GSE'):...
import enum from typing import ( List, Tuple, ) from slacktools.block_kit.base import BaseBlock from slacktools.block_kit.types import ( ConfirmationDialogType, DispatchActionType, OptionGroupType, OptionType, ) class DispatchActions(enum.Enum): on_enter_pressed = 0 on_character_enter...