text
stringlengths
38
1.54M
import pytest from fcm_django.models import FCMDeviceQuerySet from tests.factories import ReviewFactory from jobadvisor.notifications.models import Message @pytest.mark.django_db def test_review_signal_create(mocker, company) -> None: mocker.spy(Message.objects, "bulk_create") ReviewFactory(company=company) ...
# -*- coding: utf-8 -*- """ Updated Jan 21, 2018 The primary goal of this file is to demonstrate a simple unittest implementation @author: jrr @author: rk """ import unittest from Triangle import classifyTriangle # This code implements the unit test functionality # https://docs.python.org/3/library/unit...
from z3 import * s = Solver() x = Int('x') s.add(16*x*x+145*x+9==0) print s.check() print s.model() y = BitVec('y', 8) s.add( y ^ 0x77 == 0 ) print s.model()
import logging from interfaces.LTS import LTS from module_generation.lts_to_verilog import lts_to_verilog from module_generation.verilog_to_aiger_via_yosys import verilog_to_aiger def lts_to_aiger(lts:LTS) -> str: module_name = 'model' v = lts_to_verilog(lts, module_name) logging.debug('verilog output is...
# -*- coding: utf-8 -*- import django from django.http import HttpResponseRedirect from django.utils.http import urlencode from allauth.account.adapter import get_adapter from allauth.account.utils import get_next_redirect_url from allauth.socialaccount import providers from allauth.socialaccount.helpers import ( ...
import json import uuid from bson.objectid import ObjectId from lib.custom_except import duplicateError from models import db def get_all(): item_result = list( db.TYPE_COLLECTION.aggregate( [ {"$match": {"category": "item"}}, { "$lookup":...
def solution(phone_book): answer = True phone_book.sort() for i in range(0, len(phone_book)-1): k = len(phone_book[i]) print(k , phone_book[i]) for j in range(i+1, len(phone_book)): if len(phone_book[j]) < k: pass else: print(ph...
import os import re import sys import io sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8') #根据文件扩展名判断文件类型 def endWith(s,*endstring): array = map(s.endswith,endstring) if True in array: return True else: return False #将全部已搜索到的关键字列表中的内容保存到result.log文件中 def writeResultLog(dir...
__author__ = 'wing2048' import time import math import serial from constants import * class Servo(): def __init__(self, servo_id): self.id = servo_id self.angle = 0 self.velocity = 0 def set_angle(self, angle): self.angle = angle class Tool(): def __init__(self): ...
from django.db import models import datetime as dt # Create your models here. class Category(models.Model): CATEGORIES =(("SpaceX","SpaceX"),("Blue Origin","Blue Origin"),("Virgin Atlantic","Virgin Atlantic")) image_category = models.CharField(max_length=40,choices=CATEGORIES,) def save_category(self): ...
import numpy as np import torch from torch.utils.data import TensorDataset from torch.utils.data import DataLoader import logging from datetime import datetime import time import utils_.helpers as helpers def get_loss(model, loss_func, data_loader): losses, nums = zip(*[loss_batch(model, loss_func, None, batch[-1]...
import tkinter as tk from tkinter.scrolledtext import ScrolledText from Ciphers.Nomenclator import nomenclator, PrintCodes from Ciphers.UtilityFunctions import preptext import webbrowser # Create the window root = tk.Tk() # Don't let the user change the window size root.maxsize(800,800) root.minsize(800,800) # Titl...
import json import math class Agent: """docstring for Agent""" def say_hello(sef, first_name): return "Bien le bonjour"+first_name+" !" def __init__(self, **agent_attributes): for attr_name, attr_value in agent_attributes.items(): # set attribute setattr(self, attr_name,attr_name) class Possition: """do...
from tests.integration.integration_test_case import IntegrationTestCase from tests.integration.it_utils import submit_transaction_async, test_async_and_sync from tests.integration.reusable_values import WALLET from xrpl.models.response import ResponseStatus from xrpl.models.transactions import EscrowCancel ACCOUNT = W...
1. Assert: _O_ is an Object that has a [[ViewedArrayBuffer]] internal slot. 1. Assert: The [[ViewedArrayBuffer]] internal slot of _O_ is *undefined*. 1. Assert: _length_ ≥ 0. 1. Let _constructorName_ be the String value of _O_'s [[TypedArrayName]] internal slot. ...
# -*- coding: utf-8 -*- from Tkinter import * CANVAS_WIDTH = 600 CANVAS_HEIGHT = 600 CELL_X = CELL_Y = 35 def paint_grid(canvas): for x in range(CELL_X, CANVAS_WIDTH, CELL_Y): canvas.create_line(x, 0, x, CANVAS_HEIGHT, fill="black") for y in range(CELL_X, CANVAS_HEIGHT, CELL_Y): canvas.create_line(0, y, CANVAS_...
from django.db import models from phonenumber_field.modelfields import PhoneNumberField # Create your models here. class Cliente(models.Model): nombre = models.CharField(max_length=250) telefono = PhoneNumberField(unique=True) notas = models.TextField(blank=True) def ultima_visita_con_reserva(self): ...
import os import numpy as np import torch import torch.nn as nn import torch.utils.data as Data import torch.optim as optim import torch.nn.functional as F data_csv_path = ["SM_HighBP","SM_Normal","SM_pneumonia","SM_SARS"] def data_preprocessing(data_path,num_feature=23): path = os.path.join("sars-cov-1") d...
''' command for zim custom tool: python path/to/zim_to_textile.py -T %T -f %f * textile format: http://www.redmine.org/projects/redmine/wiki/RedmineTextFormattingTextile#External-links ''' import argparse import pyperclip from zim.formats import get_parser from zim.formats import UNCHECKED_BOX, XCHECKED_BOX, CHECKED...
# -*- coding: utf-8 -*- """ Created on Fri Jun 18 17:55:33 2021 @author: Osvaldo """ class nodoSimple: def __init__(self, d = None): self.dato = d self.liga = None def asignarDato(self, d): self.dato = d def asignarLiga(self, x): self.liga = x def retornarDato(self): retur...
# a="MISSISSIPPI" # b={} # for i in a: # count=0 # if i not in b.keys(): # for j in a: # if i==j: # count+=1 # b[i]=count # print(b) # for i in a: # if i in b: # b[i]+=1 # else: # b[i]=1 # print(b) count = {"M":0,"I":0,"S":0,"P":0} word...
import pygame class Bullet1(pygame.sprite.Sprite): # 继承 pygame.sprite.Sprite 类 def __init__(self, position): # 构造函数,传入对象和背景大小 pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load("images/bullet1.png").convert_alpha() # 创建图像 self.rect = self.image.get_rect() # 获取具有图像...
import modutil # will need the function modinv() which returns the inverse of an integer def blocksize(n): """returns the size of a block in an RSA encrypted string""" twofive = "25" while int(twofive) < n: twofive += "25" return len(twofive) - 2 def RSAletters2digits(letters): """con...
import pytest from hypothesis import given, assume from unittest import TestCase from stylo.testing.strategies import real from stylo.utils import bounded_property @pytest.mark.utils class TestBoundedProperty(TestCase): """Tests to ensure the :code:`bounded_property` factory function produces properties as e...
# encoding=utf8 from flask import Flask, request, jsonify, session, render_template from flask_pymongo import PyMongo from gevent import pywsgi from flask_cors import CORS import random import time app = Flask(__name__) app.debug = True app.config['JSON_AS_ASCII'] = False CORS(app, supports_credentials=True) app.confi...
""" Django settings for project {{ project_name }}. Generated by 'django-admin startproject' using Django {{ django_version }}. For more information on this file, see https://docs.djangoproject.com/en/{{ docs_version }}/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.c...
from django.conf.urls import url from views import * from django.contrib.sitemaps.views import sitemap urlpatterns = [ url(r'^newsletter', newsletter,name='newsletter'), url(r'^aboutus',AboutUs.as_view(),{'template_name':'aboutus.html'},name="aboutus"), url(r'^contactus',ContactUs.as_view(),{'template_name...
# -------------- # Import Libraries import os import pandas as pd import numpy as np import warnings warnings.filterwarnings('ignore') # Code starts here df = pd.read_csv(path) print(df.head()) df.columns = df.columns.str.lower() df.columns = df.columns.str.replace(' ','_') df = df.replace('NaN','np.nan') df.isna(...
#!/usr/bin/env python # # this node subscribes to the /enu and /magnetic topics # # as soon as a sensor reading is received on both, an initial guess # of the robot pose and orientation is computed and the parameter # /roamfree/initialPose is set accordingly in the parameter server # # once done, the node terminates. ...
import os from google.cloud import datastore PROJECT_ID = os.environ.get('PROJECT_ID', 'ccblender') def list_instances_of_word(word): client = datastore.Client(PROJECT_ID) query = client.query(kind='Captioned Word') query.add_filter('word', '=', word) word_instances = list(query.fetch()) if len(...
# -*- coding: utf-8 -*- import logging import os import sys import json import requests import random import datetime from flask import Flask from flask import request from flask import Response from mattermost_giphy.settings import * logging.basicConfig( level=logging.INFO, format='[%(asctime)s] [%(levelname)s...
import unittest from operator import attrgetter import obonet from pyobo import SynonymTypeDef, get from pyobo.struct import Reference from pyobo.struct.struct import ( iterate_graph_synonym_typedefs, iterate_graph_typedefs, iterate_node_parents, iterate_node_properties, iterate_node_relationships, iterate_no...
#!/usr/bin/python3 """ Base module """ import json class Base: """ Base class Attributes: __nb_objects: private class attribute """ __nb_objects = 0 def __init__(self, id=None): """ Initialization method Args: id """ if id is not No...
#print("Yo what's yo name") #name=input() #if name == "Leo" or name== "Mikael": # print("Group 2") #elif name == "Justis" or name == "David": # print("Group 3") #elif name == "Kayla" or name == "Gen": # print("Group 4") #else: # print("IDK") print("whats yo age") age = float (input()) if age <4: print...
############################################################################ # # # Copyright (c) 2017 eBay Inc. # # # # Licensed u...
from . import views from django.urls import path urlpatterns =[ path('/',views.BookListView.as_view(),name='book.all'), path('/index',views.index,name='book.all.index'), path('/<int:pk>',views.BookDetailView.as_view(),name='book.show'), path('/book/<int:id>',views.show,name='book.show.index'), pat...
from unittest.mock import MagicMock import pytest from riotwatcher._apis.legends_of_runeterra import MatchApi @pytest.fixture(params=["match_id_001122"]) def match_id(request): return request.param @pytest.mark.lor @pytest.mark.unit class TestMatchApi: def test_by_puuid(self, region, puuid): mock_...
from functools import reduce # 匿名函数 stm = lambda x, y: x + y print(stm(1, 2)) # 高阶函数:把函数作为参数使用 def printC(n): return n* 3 def mul(n,f): return printC(n) * 100 print(mul(3,3)) # map # 映射,把集合里的每个元素按照一定规则进行操作,生成一个新的列表 l1 = [i for i in range(0, 10)] def mulTen(n): return n * 10 l3 = [] l2 = map(mulTen, l1)...
# Copyright 2018 Adrien Guinet <adrien@guinet.me> # # 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 o...
import cv2 import numpy as np import os import time from tqdm import tqdm import shutil import argparse from glob import glob import torchvision.transforms as transforms import torchvision.models as models import torch.nn as nn import torch import torch.backends.cudnn as cudnn from test_spatial_dataloader import * from...
""" Copy this file to local_settings.py and edit the values. Make sure you set the DJANGO_SETTINGS_MODULE environment variable to local_settings as well. """ # Local environment? # from totemag.settings.local import * # Production environment? # from totemag.settings.production import * # Override database settin...
from mininet.node import OVSSwitch class OVSSwitchSTP(OVSSwitch): prio = 1000 def start(self, *args, **kwargs): OVSSwitch.start(self, *args, **kwargs) OVSSwitchSTP.prio += 1 self.cmd('ovs-vsctl set-fail-mode', self, 'standalone') self.cmd('ovs-vsctl set-controller', self) ...
import math from random import random from scipy.stats.distributions import chi2 values = [86,133,75,22,11,144,78,122,8,146,33,41,99] values.sort() def func_distro_expo(x, media): return 1 - math.e**(-x/float(media)) def func_distro_exp_values(n, media): values_f = [] for i in values: values_f.append(func_dist...
numb = 3 floatt = 3.14 print(type(numb)) #returns type of variable print(type(floatt)) #this'll be a float instead of an integer #Arithmetic Operators: # Addition: + Subtraction: - #Multiplication: * Division: / Floor Division: // #Exponent: ** Modulus: % (get the remainder of division) numb *= 1...
class Loc: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return '{} {}'.format(self.x, self.y) # ========== Key Map ========== # BTN QUEST = Loc(359, 1035) SORT = Loc(359, 1120) MAKE_EQUIP = Loc(359, 1220) # SKILL SKILL1 = Loc(664, 796) SKILL2 = Loc(664, 898) SKI...
import pandas as pd import numpy as np import glob import os class functionals: # instance attributes def __init__(self, path, indir, outdir): self.path = path self.fig_id = fig_id self.orig_headers = [ 'CREDIT SCORE', 'FIRST PAYMENT DATE', 'FIRST TIME HOMEBUYER FLAG', 'MATUR...
def add(x, y): z = float ( x ) + float ( y ) print "The required Sum is: {}".format ( z ) return z def add(x, y): z = float ( x ) + float ( y ) print "The required Sum is: {}".format ( z ) return z print add ( 5, 8 ) # If a & b are strings def add(x, y): ...
from django.contrib import admin from .models import attachment class AttachmentAdmin(admin.ModelAdmin): menu_title = "Attachment" menu_group = "Attachment" list_display = ['begin_date', 'end_date', 'name', 'cycle','format', 'description', 'file', 'content_type', 'objid'] admin.site.register(attachment.Attach...
# Python3 module: compactSchemes """Python module that reads the alpha-coefs from db files""" import sqlite3 as db def get_alphas(db_filename,nbs_id): """Return the list of alpha coeficients in table nbs(nbs_id)""" conn = db.connect(db_filename) conn.row_factory = db.Row cur = conn.cursor() ...
#!/user/bin/env python # coding=utf-8 """ @file: tf基础.py @author: zwt @time: 2020/10/20 16:44 @desc: """ import tensorflow as tf # 定义一个随机数标量 random_float = tf.random.uniform(shape=()) print(random_float) # 定义一个有两个元素的零向量 zero_vector = tf.zeros(shape=(2)) print(zero_vector) # 定已两个2*2的常量矩阵 A = tf.constant([[1., 2.], [...
#!/bin/python3 import sys #sys.path.append("./secret") import grid_mdp import random grid = grid_mdp.Grid_Mdp(); states = grid.getStates(); actions = grid.getActions(); gamma = grid.getGamma(); def mc(gamma, state_sample, action_sample, reward_sample): vfunc = dict(); nfunc = dict(); for s in states: ...
import os cmd = 'ps | grep -c exchange-xiaozhi-express' cnt = os.popen(cmd).read().replace('\n',''); print cnt if cnt == '2': cmd = '/etc/init.d/nodejs restart' print cmd os.system(cmd)
#!/usr/bin/env python3 from scipy.fftpack import dct from random import randint, sample from numpy import eye, zeros from numpy.random import randn, permutation def cs_data(m, n, s): """ BE SUPER CAREFUL THAT YOU ARE PASSING THE RIGHT VALUES HERE. it seems that matlab is inclusive ranges and python is not...
from matplotlib import pyplot as plt import numpy as np y_1, y_2 = np.meshgrid(np.arange(-7, 7, .1), np.arange(-7, 7, .1)) y_1_dot = -y_1 + y_2 y_2_dot = -y_1 - y_2 start = [ [4, 4], [4, -4], [0, 4], [4, 0], [-4, -4], [-4, 4], [0, -4], [-4, 0], [np.sqrt(3), 1], [1, np.sqrt(3)]...
import os from fabric.decorators import task from fabric.tasks import execute from fabric.api import env, cd, settings, sudo, run, put, hide, show from fabric.contrib.files import append from cStringIO import StringIO from mercantile.config import config, required, string_list, contents_of_path, default_file, default ...
print("Let's make a band name!") name_1 = input("What is your first name? ") name_2 = input("What is your home state's name? ") print(f'Your band name is {name_1} {name_2}')
import random miss = 0 hits = 0 battleshipps = [] let = ['a','b','c','d','e','f','g','h','i','j'] ch = [] ps = input('input ship position') missed = [] def guess(): pdd = random.choice(let) pd = random.randint(1,10) ks = (pdd+str(pd)) class botship(): def carrier(): go = True ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #返回函数 #高阶函数除了可以接受函数参数外,还可以将函数作为结果值返回 def lazy_sum(*args): def sum(): ax = 0 for n in args: ax += n return ax return sum f = lazy_sum(1,2,3,4,5,6,7,8,9) print(f) print(f()) print(lazy_sum(1,3,5,7,9) == lazy_sum(1,3,5,7,9)) #每次调用都返回一个新的函数,即使传入相同的参数 #闭包 def co...
""" Tests for the coupling estimators implemented in cassiopeia/tools/coupling.py """ import unittest import networkx as nx import numpy as np import pandas as pd import cassiopeia as cas from cassiopeia.data import CassiopeiaTree from cassiopeia.data import utilities as data_utilities from cassiopeia.mixins import C...
from rest_framework import serializers from . models import Users class UsersSerializer(serializers.ModelSerializer): class Meta: model = Users fields='__all__' extra_kwargs = {'avartar': {'required': False}}
#!/usr/bin/python3 def is_same_class(obj, a_class): """ 1.returns TRUE if the object is exactly an instance of the specified class. 2.otherwise FALSE. """ return(type(obj) == a_class)
import sys from os.path import abspath, dirname, join path = join(dirname(dirname(abspath(__file__))), 'src') sys.path.append(path)
# _*_ coding:utf_8 -*_ from selenium import webdriver from selenium.webdriver.common.action_chains import ActionChains import time import os driver = webdriver.Chrome() driver.maximize_window() driver.find_element_by_css_selector('#agr_pop > div.pop_footer > a.reg_btn.reg_agree').click() time.sleep(2) source = driver...
from service_manager import ServiceManager from series_service import SeriesService from cv_service import CVService from edit_service import EditService from export_service import ExportService # need to explicitly import these for pyinstaller import pymysql import pyodbc #import psycopg2 __all__ = [ 'EditServic...
# encoding=utf-8 # Author: Yu-Lun Chiang # Description: Test NewsCrawler import logging import pytest from collections import namedtuple from Sanga.media import udn from Sanga.struct import NewsStruct logger = logging.getLogger(__name__) TEST_DATA = namedtuple( typename="TEST_DATA", field_names=[ "n...
#!/usr/bin/python """ Copyright (C) 2011 Konstantin Andrusenko See the documentation for further information on copyrights, or contact the author. All Rights Reserved. @package blik.nodesManager.nodesMonitor @author Konstantin Andrusenko @date July 9, 2011 This module contains the implementation of NodesMonit...
class Order: def __init__(self, value): self.value = value def __repr__(self): return str(self.value) def __add__(self, other): return Order(self.value * other.value) def __radd__(self, other): return self.value + other def __mul__(self, other): return Ord...
from django.urls import path from rest_framework_jwt.views import ( obtain_jwt_token, verify_jwt_token, refresh_jwt_token, ) from . import views from config.views import validate_jwt_token, CustomObtainJSONWebToken app_name = "users" # 회원, 로그인 관련 EndPoint(URL) 생성 urlpatterns = [ path("", views.UserLis...
from g3 import Parser s = '' with open('programs/success.txt') as f: s = f.read() print(s) p = Parser(s) print(p.run())
from __future__ import division from Graph import PolledGraph import gtk, os class HScrollGraph(PolledGraph): """A graph that shows time on the horizontal axis, multiple channels of data on the Y axis, and scrolls horizontally so current data is always on the right edge of the graph. grid...
""" From page 263 Write a program that, given the URL of a web page will attempt to down- load every linked page on the page. The program should flag any pages that have a 404 "Not Found" status code and print them out as broken links. """ import bs4 import logging import os import requests URL = r'http://www.warnerb...
# Generated by Django 2.2.4 on 2021-05-04 03:46 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('login_registration_app', '0019_auto_20210503_2344'), ] operations = [ migrations.AlterField( model_name='user', ...
import matplotlib.pyplot as plt # generates bar graph for output by title analysis file # This bar graph is based on dictrionary of POS, TAG, DEP POS = {'compound': 22698, 'ROOT': 15556, 'punct': 14358, 'nsubj': 8148, 'aux': 3406, 'neg': 588, 'advmod': 2908, 'dobj': 6091, 'mark': 691, 'advcl': 803, 'det': 5584, 'cc...
import numpy as np epsilon = 1e-5 class Triangle: def __init__(self, a, b, c): self.a, self.b, self.c = np.array(a), np.array(b), np.array(c) def closest_point_to(self, x): if self.is_inside(x): return None min_pt, min_dist = None, np.inf for s in ...
## This program is a bulk entry tool. It uses the Student class, which holds: name, student ID #, ## GPA, expected grade for course, and full/part-time (as name, ID, GPA, grade, and time). It ## asks for input to create size instances of the student object, then pickles them in a file chosen ## by the user. The list_t...
y import time import multiprocessing as mp from multiprocessing import Pool print(mp.cpu_count()) def f(a_list): out = 0 for n in a_list: out += n*n time.sleep(0.1) return out def f_mp(a_list): chunks = [a_list[i::5] for i in range(5)] pool = Pool(processes=5) result =...
from selenium import webdriver import time browser = webdriver.Chrome() # еявное ожидание, каждого элемента до 5 секунд browser.implicitly_wait(5) browser.get("http://suninjuly.github.io/wait1.html") #time.sleep(1) button = browser.find_element_by_id("check") button.click() message = brow...
import random import sys import copy from .board_manager import BoardManager from .evaluation_manager import EvaluationManager class AIManager: def __init__(self, game_manager): self.game_manager = game_manager self.evaluation_manager = EvaluationManager() self.lookup_table = {} ...
# tuodaan tarvittavat osat from flask import render_template, request, redirect, url_for, flash from flask_login import login_user, logout_user, current_user, login_required from application import app, db, login_required from application.auth.models import User from application.teams.models import Team from applicati...
# from .component import Component from .shellscript import ShellScript from ._version import __version__ def reactopya_templates_directory(): import os dirname = os.path.dirname(os.path.realpath(__file__)) return os.path.join(dirname, 'templates') def reactopya_server_directory(): import os dirna...
first = None second = None n1 = None n2 = None def get_two_numbers(): numbers = [ ['first', None], ['second', None], ] for number in numbers: n = None while n is None: s = raw_input("What is the " + number[0] + " number? ") try: n = ...
import requests from lxml import etree # url = "http://www.dytt8.net/html/gndy/dyzz/list_23_1.html" #请求头定义为全局变量 HEADERS = { 'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36' } #设置全局变量,拼接完整的url链接 BASE_DOMAIN = 'http://www.dytt8.net' #定义为函数 ...
from shared.settings import * SERVER_IP = '' SERVER = SERVER if DEBUG else SERVER_IP ADDR = (SERVER, PORT)
# Copyright 2021 The Magenta Authors. # # 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 ...
from werkzeug.security import generate_password_hash from application import db class User(db.Model): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(80), unique=True) password = db.Column(db.String(120), unique=True) is_valid = db.Column(db.Boolean, default=True) def ...
from docx import Document import xlwings as xw def get_paragraph_text(path, n): """ 获取指定段落的文本 :param path: word路径 :param n: 第几段落,从0开始计数 :return: word文本 """ document = Document(path) all_paragraphs = len(document.paragraphs) if all_paragraphs > n: paragraph_text = document.p...
from requests import get, post, put, delete print('Проверяем GET запрос для RequestResource') print(get('http://localhost:8080/api/request/2').json()) # обработка несуществующего запроса print(get('http://localhost:8080/api/request/1000').json()) print('Проверяем GET запрос для RequestListResource') print(get('http...
#!/usr/bin/env python import sys def main(input, output): with file(input, "r") as i, file(output, "w") as o: write = False for line in iter(i.readline, ''): if line.startswith("\\begin{document"): write=True continue if line.startswith("\\end...
# -*- coding:utf-8 -*- """ Taken from: https://github.com/zhuang-hao-ming/c4.5-python """ import operator import math def get_majority_class(class_list): class_count = {} for item in class_list: if item in class_count: class_count[item] += 1 else: class_count[item] = 1...
import numpy as np from datetime import datetime import os import ROOT import LORAparameters as LORA import os.path from datetime import date nTraceV1=4000 nDetV1=20 dtV1=2.5 timesV1=np.arange(0,4000*dtV1,dtV1) avg_threshold=np.asarray([ 27.24867982, 27.08347496, 21.3469044, 22.45092564, 16.96505311, 16.62127466...
import pygame as py import random as rn py.init() class gm: clk=py.time.Clock() scr=py.display.set_mode((512,512)) run=True class sn: x = rn.randint(0,32) y = rn.randint(0,32) def rec(s,x,y,w,h,c): py.draw.rect(s,c,py.Rect(x,y,w,h)) def draw(): gm.rec(gm.scr,gm.sn...
""" Factorial and Fibonacci Recursive vs iterative Recursive: DRY (helps not to repeat yourself) Readability Maintains state at different levels of recursion But extra memory footprint (space complexity): larger stack because of additional function calls, adding functions to the call stack, potentially stack ove...
import telnetlib,getpass host = 'tis-sw-acc-1lab-1' username = input('Username: ') username = bytes(username + '\n', 'UTF8') password = getpass.getpass() password = bytes(password + '\n', 'UTF8') enablepw = getpass.getpass() enablepw = bytes(enablepw + '\n', 'UTF8') session = telnetlib.Telnet() session.open(host) o...
import numpy as np import pandas as pd purchase_1 = pd.Series({'Name': 'Chris', 'Item Purchased': 'Dog Food', 'Cost': 22.50}) purchase_2 = pd.Series({'Name': 'Kevyn', 'Item Purchased': 'Kitty Litter', 'Cost': 2.50}) purchas...
import mechanicalSoup from bs4 import BeautifulSoup """ AURTHOR: BHARATH SUNDAR VERSION: 1.0 INFO: Web Scrapper to get live cricket score and live sports news. """ news_url = "" scores_url = ""
#!/usr/bin/env python3 # # Based on examples from minikerberos by skelsec # Parts of this code was inspired by the following project by @rubin_mor # https://github.com/morRubin/AzureADJoinedMachinePTC # # Author: # Tamas Jos (@skelsec) # Dirk-jan Mollema (@_dirkjan) # import argparse import logging import binascii im...
#! /usr/bin/env python3 # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope tha...
import numpy as np import pandas as pd from sklearn.metrics import r2_score as r2 from sklearn.metrics import mean_squared_error as mse def r2_for_last_n_cycles(y_act , y_hat, last_n=50): ypred_n = [] y_act_n = [] for idx, cycle in enumerate(y_act): # print(cycle) if cycle <= last_n: ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import numpy as np import scipy.constants as const import matplotlib.pyplot as plt def sat( vgs, vds, w, l, kp, vth, lamb): vdsat = vgs - vth return ( ( kp / 2) * ( w / l) * (vgs - vth) ** 2) * \ ( 1 + lamb * ( vds - vdsat))...
# coding: utf-8 # #WebClient のプロキシ設定確認用サンプル from System import * from System.Net import * wc = WebClient() wc.BaseAddress = "http://www.google.co.jp/" print wc.Proxy.GetProxy(Uri("http://www.google.co.jp/")) print wc.DownloadString("")