text
stringlengths
38
1.54M
"""Test cases for lane.py.""" import os import unittest from typing import Dict import numpy as np from ..common.utils import list_files from .lane import ( eval_lane_per_threshold, evaluate_lane_marking, get_foreground, get_lane_class, sub_task_funcs, ) class TestGetLaneClass(unittest.TestCase)...
import cv2 name = 'ball' \ filenameSource = '../' + name + '.bmp' filenameOutput = '../' + name + '.hex' img = cv2.imread(filenameSource, cv2.IMREAD_COLOR) if img is not None: img = (img >> 4) << 4 cv2.imshow('Image', img) cv2.waitKey(0) cv2.destroyAllWindows() with open(filenameOutput, 'wb'...
#!/usr/bin/env python3 # tools/callstack.py # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. The # ASF licenses this file to you under the Apache License, ...
# -*- coding: utf-8 -*- """ Created on Tue Feb 4 10:16:14 2020 GUI for battery demonstartion using real-time data from OPC UA @author: hube """ # %% Import libraries import pandas as pd import matplotlib.pyplot as plt import matplotlib.animation as animation from matplotlib import style from time import sleep from...
#!/usr/bin/env python # encoding: utf-8 """ setup.py Copyright (c) 2011 Indie Energy Systems Company, LLC.. All rights reserved. """ import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name="python-geopod", version="...
import serial import time ser = serial.Serial('COM7',9600) time.sleep(5) data = [] for i in range(50): a = ser.readline() b = a.decode() c = b.rstrip() d = float(c) print(d) data.append(d) time.sleep(1) ser.close()
import sys from PyQt5.QtWidgets import * from PyQt5.QtGui import QPixmap class Window(QWidget): def __init__(self): super().__init__() self.setWindowTitle("PyQt_04") self.setGeometry(50,50,350,350) self.UI() def UI(self): # all your code is here : self...
def contar_vocales(): frase = input("Dame una frase: ") frase1 = frase.lower() a = frase1.count("a") e = frase1.count("e") i = frase1.count("i") o = frase1.count("o") u = frase1.count("u") totalvoc = a + e + i + o + u print ("Total de vocales: ", totalvoc) print ("Hay un total de a:", a) print ("H...
""" reverse only the vowels in a string """ def reverseVowels(s: str) -> str: vset = set(["a", "e", "i", "o", "u"]) n = len(s) right = n - 1 left = 0 s = list(s) print(s) while left < right: if s[left] in vset and s[right] in vset: s[left], s[right] = s[right], s[left]...
import os import argparse import sys import meshlabxml as mlx import platform from tqdm import tqdm from shutil import copyfile # based off https://github.com/HusseinBakri/3DMeshBulkSimplification # returns a boolean if the mesh was simplified (if false, means mesh already had few enough faces and a simply co...
"""Coindix model""" __docformat__ = "numpy" import logging from typing import Optional import pandas as pd import urllib3 from openbb_terminal import rich_config from openbb_terminal.core.session.current_user import get_current_user from openbb_terminal.decorators import log_start_end from openbb_terminal.helper_fun...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os from status_dock.bar import Bar CONFIG_FILE = f"{os.environ['HOME']}/.i3/status.conf.json" if __name__ == "__main__": import sys try: layout = sys.argv[1] except IndexError: raise ValueError("Please supply the layout as the only ...
from selenium import webdriver from junit_xml import TestSuite, TestCase from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.support.ui import WebDriverWait import time, unittest class OnInternetExplorer (unittest.TestCase): def setUp(self) : self.driver =...
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def hasPathSum(self, root, target): if root is None: return False nodes = [root] sum...
import numpy as np import tushare as ts code = '002771' data_5 = ts.get_k_data(code, ktype='5') data_15 = ts.get_k_data(code, ktype='15') data_30 = ts.get_k_data(code, ktype='30') data_60 = ts.get_k_data(code, ktype='60') data_d = ts.get_k_data(code, ktype='D') data_w = ts.get_k_data(code, ktype='W')
#!/usr/bin/env python from __future__ import print_function import yaml import argparse import sys def main(): parser = argparse.ArgumentParser(description='Convert old poses to new motion format.') parser.add_argument('infile', nargs='?', help='input poses parameter file [default: std...
import unittest, sys sys.path.append("..") from server import app class FlaskTests(unittest.TestCase): def setUp(self): """Stuff to do before every test.""" self.client = app.test_client() app.config['TESTING'] = True def tearDown(self): """Stuff to do after every test.""" ...
from math import sin, cos, asin, sqrt, degrees, radians RADIUS = 6371.0 def calculateDeltas(lat, lng, distance): dlat = distance / RADIUS dlng = asin(sin(dlat) / cos(radians(lat))) return degrees(dlat), degrees(dlng) def bounding_box(lat, lng, distance): dlat, dlng = calculateDeltas(lat, lng, distanc...
from nltk.corpus import gutenberg from word_segmentation.brown_cmu_unigram_provider import BrownCmuUnigramProvider from word_segmentation.brown_bigram_provider import BrownBigramProvider from word_segmentation.cmu_dictionary import CmuDictionary from word_segmentation.bigram_word_segmenter import BigramWordSegmenter f...
from django.apps import AppConfig class DraftKitAppConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'draft_kit_app'
import sklearn.model_selection import sklearn.datasets as datasets import sklearn.metrics import autosklearn.classification import warnings warnings.simplefilter(action='ignore', category=FutureWarning) warnings.simplefilter(action='ignore', category=DeprecationWarning) def example1(): X, y = sklearn.datasets.lo...
from pprint import pprint from checkpoint import * from game import * from snapshot import * checkpoints = [Checkpoint("A1", "Alpha 1", Area()), Checkpoint("B1", "Bravo 1", Area()), Checkpoint("C1", "Charlie 1", Area())] players = [Player("P01", "Amy", "S1L1"), Player("P02", ...
from flask import Flask, render_template, redirect, url_for, request, session, flash, Blueprint import requests import json import boto3 from botocore.exceptions import ClientError from . import routes @routes.route('/register', methods = ['GET', 'POST']) def register(): if request.method == 'POST': mobil...
import sys def nestPrint(the_list): for each_item in the_list: if isinstance(each_item, list): nestPrint(each_item) else: print(each_item) def print_lol(the_list, indent=False , level=0, outfile=sys.stdout): for each_item in the_list: if isinstance(each_item, ...
#!/usr/bin/env python class MessageEnum(object): MOVE = 1 SUGGEST = 2 ACCUSE = 3 LOBBY_ADD = 4 LOBBY_READY = 5 LOBBY_UNREADY = 6 LOBBY_CHANGE_PLAYER = 7 GAME_STATE_CHANGE = 8 TURN_OVER = 9 TURN_BEGIN = 10 ERROR = 11
""" This file provide wrappers and abstract implementation of the following spec: https://docs.google.com/document/d/1qztk6n6_OYubDKynQL05G0H9Yuwf7CX8K-SFJyeE4z0/edit# To set or use any additional parameters in your functions of the Vectorization, Tokenization, Clusterization classes, use the self.ctx dict. """ from...
import re; def cCrashInfo_fsGetModuleISA(oCrashInfo, sCdbModuleId): # returns "x86" or "AMD64" asModuleOutput = oCrashInfo._fasSendCommandAndReadOutput("lm m %s" % sCdbModuleId); if not oCrashInfo._bCdbRunning: return; oModuleDetailsMatch = ( len(asModuleOutput) == 2 and re.match(r"^start\s+end\s+modul...
import mobula from mobula.const import req import os import numpy as np @mobula.op.register class RetinaNetTargetGenerator: def __init__(self, number_of_classes, stride=16, base_size=(32, 32), negative_iou_threshold=.4, positive_iou_threshold=.5, ...
# Generated by Django 3.0 on 2021-03-12 04:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('myapp', '0003_user_usertype'), ] operations = [ migrations.CreateModel( name='Product', fields=[ ('id'...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Feb 26 13:46:55 2021 @author: romainboudet Version 2 of the NBA props model for Sports Interaction This model differs from previous ones by using individual player weights that are trained on past data to minimize the difference between the actual va...
#Given a binary array, find the maximum number of consecutive 1s in this array. from typing import List class MaxOnesArray: def findMaxConsecutiveOnes(nums: List[int]) -> int: max_length = 0 counter = 0 for i in nums: if i == 1: counter += 1 else: ...
#!/usr/bin/env python import rospy import smach import numpy as np from geometry_msgs.msg import Twist from sensor_msgs.msg import LaserScan from math import pi from random import choice class RunBitchRun(smach.State): def __init__(self, simulator): smach.State.__init__( self, out...
i = 1 j = 7 while i <= 9: print('I={} J={}'.format(i,j)) print('I={} J={}'.format(i,j-1)) print('I={} J={}'.format(i,j-2)) i += 2 j += 2
import urllib.request, urllib.parse, urllib.error #用 urllib 创建socket连接 fhanld = urllib.request.urlopen('http://data.pr4e.org/intro-short.txt') print(fhanld) counts = dict() for line in fhanld: words = line.decode().strip().split() for word in words: counts[word] = counts.get(word,0)+1 print(counts)
import pickle class people: def __init__(self): self.name=None self.dob=None def open_file(): with open("people.dat",mode="rb") as people_file: people = pickle.load(people_file) return people def get_max_len(people): max_len = 0 for person in people: ...
# file that give each business and user id integers import pickle import random user_ind_dict = {} business_ind_dict = {} user_ind = 1 business_ind = 1 # read the rating list for restaurants rating_list = pickle.load(open('rating_list_pickle', 'rb')) sample_rating_list = random.sample(rating_list,100000) # tuple...
# Generated by Django 2.2 on 2020-10-01 11:40 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('MerchantManagement', '0008...
from datetime import datetime, timedelta import pandas as pd import pytest from openbb_terminal.stocks.tradinghours import bursa_model TRADING_HOURS_DF = pd.read_csv( "tests/openbb_terminal/stocks/tradinghours/csv/test_bursa_model/trading_hours_df.csv", index_col=0, ) DAYS_TILL_NEXT_MONDAY = (0 - datetime.u...
from typing import Union from numpy import ndarray import random import numpy from typing import List from typing import Tuple from typing import Sequence import random from collections.abc import Generator def seed_global(seed: int, offset: int = 0) -> None: ... def shuffle( items: Union[list, ndarray], ...
import numpy as np from abc import ABC from abc import abstractmethod class Layer(ABC): def __init__(self, trainable, name=None): self.name = name self.trainable = trainable @abstractmethod def forward(self, inputs): raise NotImplementedError() @abstractmethod def backwa...
import json import SimpleBO def test1(): result = SimpleBO.find_people_by_primary_key('willite01') print("Result = ", json.dumps(result)) test1()
#!/usr/bin/env python ## # This script is a collection of utility function to be used for extracting PGEN # products from EDEX and to store PGEN activities to EDEX. # # Users can override the default EDEX server and port name by specifying them # in the $DEFAULT_HOST and $DEFAULT_PORT shell environment variables. # ...
import Pyro4 @Pyro4.expose @Pyro4.behavior(instance_mode="single") class ChatServer(object): def __init__(self): self.users = [] self.nicknames = [] self.count = 0 def join(self, nickname, callback): self.valid_nickname(nickname) self.users.append((nickname, callback)) ...
import sys, os import pickle import numpy as np import pandas as pd import glob import shutil import gc if len(sys.argv) > 1: job_df = pd.read_pickle(sys.argv[1]) job_index = int(sys.argv[2]) job_row = job_df.iloc[job_index].copy() else: job_row = None # Import pymask sys.path.append('/afs/cern.ch/en...
import pandas as pd def double_tweet(tweet): for index, row in trumpdf2.iterrows(): if tweet == row['content']: return True return False trumpdf = pd.read_csv('realdonaldtrump.csv') trumpdf2 = pd.read_csv('trumptweets.csv') counter = 0 for index, row in trumpdf.iterrows(): if double_...
'''Tests for the second coursework Q1''' import pytest import numpy as np import q1 CID = 1357062 # Test the solution for Ax = b produced by LUsolveA for random float 1D arrays @pytest.mark.parametrize('m', [5, 11, 53, 100, 501, 1000]) def test_LUsolveA(m): np.random.seed(CID+m) rand = np.random.random(2+...
# -*- coding: utf-8 -*- # @Date : 2020/5/23 # @Author: Luokun # @Email : olooook@outlook.com import matplotlib.pyplot as plt import numpy as np class SVM: """ Support Vector Machines(支持向量机) """ def __init__(self, C=1.0, tol=1e-3, iterations=100, kernel='linear', **kwargs): """ :para...
class player_reg(db.Model): player_id = db.Column(db.Integer, primary_key=True) first_name = db.Column(db.String(15), nullable=False) last_name = db.Column(db.String(15), nullable=False) age = db.Column(db.String(15), nullable=False) class prize(db.Model): id = db.Column(db.Integer, primary_key=Tru...
from os import getenv class Config(object): SECRET_KEY = 'M<JZ7]6P-r_C0C3hNzY#gbOjY' SQLALCHEMY_DATABASE_URI = f'mysql+pymysql://root:{getenv("DATABASE_PW")}@localhost:3306/qtodo' SQLALCHEMY_TRACK_MODIFICATIONS = False GLOBAL_ERROR_CODE = '400 401 403 404 500'
# data analysis and wrangling import bisect import re import warnings warnings.simplefilter(action='ignore', category=FutureWarning) import pandas as pd import numpy as np # machine learning from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble.gradient_boosting import GradientBoostingClassifier fr...
import statistics stat_fields=open('stat_fields','r').read().replace('\r\n','\n').split('\n') stat_fields.remove('') print(str(stat_fields)) data =open('DataFreezeDataFrame_10022015_VERSION2.txt','r').read().replace('\r','\n').split('\n') if '' in data: data.remove('') header=data[0].split('\t') value_dict=dict()...
import FWCore.ParameterSet.Config as cms # AlCaReco for Bad Component Identification OutALCARECOSiPixelCalZeroBias_noDrop = cms.PSet( SelectEvents = cms.untracked.PSet( SelectEvents = cms.vstring('pathALCARECOSiPixelCalZeroBias') ), outputCommands=cms.untracked.vstring( 'keep *_ALCARECOS...
import urllib2 import base64 username = 'akos' password = '9ff85ba6e0beb00208ee84b998650cf8' # only a local api key, no harm url = 'http://localhost:8080/job/packjob/4/api/json' request = urllib2.Request(url) request.add_header('Authorization', b'Basic ' + base64.b64encode(username + b':' + password)) result = urllib...
#!/usr/bin/env python from optparse import OptionParser parser = OptionParser() parser.add_option('--infile', type='string', action='store', dest='infile', default = "/data/EXOVV/QCDTree/JetHT_Run2015D_B2GAnaFW_v74x_V8p4_25ns_Nov13silverJSON.root", help='Input fil...
# Copyright (c) 2015 # # All rights reserved. # # This file is distributed under the Clear BSD license. # The full text can be found in LICENSE in the root directory. from boardfarm import lib from boardfarm.devices import prompt from boardfarm.lib import installers from boardfarm.tests import ipv6_setup, rootfs_boot ...
#!/usr/bin/python # -*- coding : utf-8 -*- __author__ = 'ash' import MySQLdb as mdb con = mdb.connect('localhost', 'ash', '5188', 'bestbuy') with con: cur = con.cursor() cur.execute('SELECT * FROM Writers') rows = cur.fetchall() desc = cur.description print desc for row in rows: ...
class A: def f(self,*args): print('f:', type(self), args) print(A) a = A() print(type(a)) a.f(3,4,5) g = a.f print(type(g)) a.f(6,7,8) g(6,7,8) A.f(11,22,33)
# 문제 # 한 개의 회의실이 있는데 이를 사용하고자 하는 N개의 회의들에 대하여 회의실 사용표를 만들려고 한다. # 각 회의 I에 대해 시작시간과 끝나는 시간이 주어져 있고, 각 회의가 겹치지 않게 하면서 회의실을 사용할 수 있는 최대수의 회의를 찾아라. # 단, 회의는 한번 시작하면 중간에 중단될 수 없으며 한 회의가 끝나는 것과 동시에 다음 회의가 시작될 수 있다. # 회의의 시작시간과 끝나는 시간이 같을 수도 있다. 이 경우에는 시작하자마자 끝나는 것으로 생각하면 된다. # # 입력 # 첫째 줄에 회의의 수 N(1 ≤ N ≤ 100,000)이 주어진다. # 둘...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved """ A sweeper that operates on generational batches of jobs """ from abc import abstractmethod from . import Sweeper class StepSweeper(Sweeper): """ A sweeper that support base implementation for sweepers that operates on batches of j...
import re from functools import reduce from basic.bupt_2017_10_19.Vec import Vec from basic.bupt_2017_10_24 import egi class Mat: def __init__(self,filepath="",mat=None,ndarray=None): if filepath != "": self.init_by_file(filepath) elif mat != None: self.init_by_mat(mat) ...
import collections import util import copy class Gomuku: def _init__(self): self.board = [['.' for i in range(7)] for i in range(7)] ##self.np = 1 ##slef.lm = (-1, -1) self.pOne = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','x','y','z'] self.pTwo = ['A','B','C',...
import tkinter as tk #建立主視窗 win = tk.Tk() #設定視窗名稱(標題) win.title("視窗名稱測試") #設定視窗大小 win.geometry("400x300+800+400") #(寬x高 +X +Y) (用字串表示,後面的 + 前者數字為X軸,後者為Y)---(設定開啟視窗大小預設值及位置) win.minsize(width=400, height=200) #設定視窗最小值 win.maxsize(width=1024, height=768) #設定視窗最大值 #設定視窗背景顏色 win.config(background="skyblue") #建立拉桿...
import pandas as pd import csv df = pd.read_csv("2019_verkehrszaehlungen_werte_fussgaenger_velo_bereinigt.csv", sep =";") #setting the categories of the counting stations df.loc[df['FK_ZAEHLER'] == "U15G3104443", "KATEGORIE"] = "fussgaenger" df.loc[df['FK_ZAEHLER'] == "U15G3104446", "KATEGORIE"] = "fussgaenger" df.lo...
#!/usr/bin/env python # -*- coding: utf-8 -*- from . import _utils, _query_nodeping_api, config API_URL = "{0}results".format(config.API_URL) def get_results(token, check_id, customerid=None, span=None, limit=300, start=None, ...
from django import forms class NameForm(forms.Form): faculty_id = forms.CharField(label='',widget=forms.TextInput(attrs={'placeholder': 'Faculty ID','class': 'login-input'}),max_length=20,initial="") password = forms.CharField(label='',widget=forms.PasswordInput(attrs={'placeholder': 'Password','class': 'login...
from sklearn.datasets import load_breast_cancer from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split import matplotlib.pyplot as py from sklearn import tree from sklearn.metrics import accuracy_score from sklearn.svm import SVC cancer=load_breast_cancer() prin...
import os, sys sys.path.append(os.path.pardir) from common.n_gram import NGram if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('-t', '--train-file') parser.add_argument('-o', '--output-file') arg = parser.parse_args() model = NGram(1) with...
from sklearn.cluster import KMeans import numpy as np from numpy import array NUM_CLASS = 16 train_X = [] read_feature = open("train_feature.txt", "r") lines = read_feature.readlines() print(len(lines)) for line in lines: line_split = line.split(" ") line_split = [float(i) for i in line_split] train_X.append(l...
from office365.runtime.client_value import ClientValue from office365.sharepoint.base_entity import BaseEntity from office365.sharepoint.base_entity_collection import BaseEntityCollection class EventReceiverDefinitionCreationInformation(ClientValue): """Represents the properties that can be set when creating a cl...
#!/usr/bin/python import os print"___________________________________________________________________" print"| SELECT WHAT KIND OF OPTIONS TO RUN: |" print"|-----------------------------------------------------------------|" print"|1. Start Nginx ...
from django.shortcuts import render from django.http import HttpResponse from . models import Product from math import ceil def index(request): products= Product.objects.all() n= len(products) nSlides= n//4 + ceil((n/4) + (n//4)) params={'no_of_slides':nSlides, 'range':range(1,nSlides), 'product': prod...
#!/usr/bin/env python3 import attr from wrdscli.lib.base import WRDSEntity @attr.s(auto_attribs=True) class IdxFdmtAnn(WRDSEntity): schema = 'comp' table = 'idx_ann' gvkeyx : str = None # Global Index Key - Index Annual aco : int = None # Current Assets - Other - Index Fundamental act : int = None # Curr...
import bcrypt from cryptography.fernet import Fernet import sqlite3 from sqlite3 import OperationalError import mysql.connector import time import random import string from getpass import getpass from env import secret_keys # Sqlite connection conn = sqlite3.connect('UserAccounts.db') cur = conn.cursor() # MySQL con...
import unittest # from MakingChange import ChangeMaker import MakingChange class MakingChangeTest(unittest.TestCase): def testMakeChangeIterative1(self): expected = 2 changeToMake = 1.25 changeMaker = MakingChange.ChangeMaker() actual = changeMaker.makeChange(changeToMake) ...
#!/usr/bin/python import cgi import commands import cgitb cgitb.enable() print "content-type:text/html" print "\n" s=cgi.FieldStorage() name=s.getvalue('name') size=s.getvalue('size') #print "lvcreate --name {} --size {} vg".format(name,size) a=commands.getstatusoutput("sudo lvcreate --name "+name+" --size...
import parser import ast import sys import getopt import os from subprocess import call from Exceptions import DefinitionError from Templates import HTMLTemplate class FiniteAutomaton: def __init__(self, states, alphabet, transitions, initial, final): self.states = set(states) self.alphabet = set(a...
# !/usr/bin/env python # -*- coding:utf-8 -*- import json def is_date(date): lst = date.split('/') if len(lst) == 2: if len(lst[0]) <= 2 & len(lst[1]) <= 2: return lst[0].isdigit() & lst[1].isdigit() def get_arg(message): lst = message.split(' ') if len(lst) == 2: return l...
from utilities import * class PathPasser(object): def __init__(self): """ Constructor """ self.validate_arg_parse() def validate_arg_parse(self): """ Validates arg parser """ parser = argparse.ArgumentParser() # Parser to parse arguments passed parser.add_argument('...
from functools import wraps from time import time def timing(f): @wraps(f) def wrap(*args, **kw): ts = time() result = f(*args, **kw) te = time() delta = round(te - ts, 2) print(f"function {f.__name__} took {delta} sec") return result retu...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `lexicalrichness` package.""" import unittest import matplotlib import numpy as np import pytest from lexicalrichness.lexicalrichness import ( LexicalRichness, frequency_wordfrequency_table, list_sliding_window, preprocess, segment_gene...
#CS7641: Machine Learning #Fall 2018 #aelkugia3 #Boosting import pandas as pd import numpy as np import matplotlib.pyplot as plt from xgboost import XGBClassifier from sklearn.model_selection import GridSearchCV from sklearn.svm import SVC import time dataset = pd.read_csv("/Users/aelkugia/Documents/GeorgiaTec...
--- third_party/protobuf/protobuf.gyp.orig 2017-06-08 22:22:39 UTC +++ third_party/protobuf/protobuf.gyp @@ -518,6 +518,7 @@ { 'target_name': 'protobuf_lite', 'type': 'none', + 'toolsets': ['host','target'], 'direct_dependent_settings': { 'cflags': [ ...
# Copyright 2014: Mirantis Inc. # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required b...
""" Напишите функцию f(x), которая возвращает значение следующей функции, определённой на всей числовой прямой: f(x)= 1 - (x + 2)^2,при x <=-2 f(x)= -(x/2), при -2 < x <= 2 f(x)= (x-2)^2 + 1, при 2 < x Требуется реализовать только функцию, решение не должно осуществлять операций ввода-вывода. """ def f(x): if x...
# Copyright 2018 Twilio, Inc. # # 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,...
# # This is test file for git edication. def First(): a = 1 b = 2 def Second(): c = 3 d = 4 # Second branch addition e = 5
# -*- coding: utf-8 -*- """ Turbine Flicker tests """ from click.testing import CliRunner import json import numpy as np import os import pytest import shutil import tempfile import traceback from rex.utilities.loggers import LOGGERS from reV.handlers.exclusions import ExclusionLayers from reVX import TESTDATADIR fro...
from typing import List ### YESSSSS. Sucessfull refactor. Accepted on third attemtp ### Interesting that the OPTIMAL APPROACH is just to divide by 2 or subtract one until you reach 0 ### I'm sure there is an elegant theorem to prove this mathematical fact, but I abused it as if ### I know it was a fact. class con...
from math import pi import numpy as np import openmc from tests.testing_harness import PyAPITestHarness class SourceTestHarness(PyAPITestHarness): def _build_inputs(self): mat = openmc.Material() mat.set_density('g/cm3', 0.998207) mat.add_element('H', 0.111894) mat.add_element('O...
"""Problema 2: Considere a empresa de telefonia Tchau. Abaixo de 200 minutos, a empresa cobra R$ 0,20 por minuto. Entre 200 e 400 minutos, o preço é R$0,18. Acima de 400 minutos o preço por minuto é R$0,15. Calcule sua conta de telefone.""" minutos = int(input('Minutos: ')) conta = 0 if minutos <= 200: ...
# -*- coding: utf-8 -*- """ Created on Fri Oct 18 09:58:28 2019 @author: ki10m """ color_list=("赤","緑","白","黒") print(color_list[0]) print(color_list[-1])
def tokenizing(string): lst = [] index = -1 for i in range(len(string)): if i == len(string) - 1: if index == -1: lst.append(string[i]) else: lst.append(string[index:i+1]) elif '0' <= string[i] <= '9' and i != len(string): ...
import string import re def check_letter_number(letter): return bool(re.match('^[1-9]\d*$', letter)) def get_text(): text = input("Введіть строку - ") separator = input("Введіть роздільник - ") return str(text), separator def get_letters(prompt): number = input(prompt) while not check_letter_...
from typing import List from random import choice def always_cheat(id:int, games:List[tuple]): return 0 def always_coop(id:int, games:List[tuple]): return 1 def always_rdm(id:int, games:List[tuple]): return choice([0, 1]) def always_copy(id:int, games:List[tuple]): last_game = games[-1] if id in...
""" 1. Проанализировать скорость и сложность одного любого алгоритма, разработанных в рамках домашнего задания первых трех уроков. Примечание: попробуйте написать несколько реализаций алгоритма и сравнить их. Подсказка: 1) возьмите 2-3 задачи, реализованные ранее, сделайте замеры на разных входных данных 2) сделайте д...
from django.http import HttpResponse from django.template.loader import get_template from django.template import Context # Create your views here. def hello(request, message = "HeXA"): return HttpResponse("hello, World! Your message is " + message) def me(request, name, group, role): t = get_template('index.htm...
# coding: utf8 #!/usr/bin/env python # -*- coding: utf-8 -*- import random import string import allure import pytest from selene.conditions import text from selene.api import * import time from General_pages.order_steps import random_mail @allure.step('Нажимаем на главной странице кнопку Order') def proceed_to_order(...
def percentFun(marks): p = ((marks[0] + marks[1] + marks[2] + marks[3])/400)*100 return p marks1 = [78, 58, 85, 65] percentage1 = percentFun(marks1) marks2 = [98, 96, 74, 85] percentage2 = percentFun(marks2) print(percentage1, percentage2) # def addition(a,b): # return a+b # print(addition(5,6))
# Python program to demonstrate # higher order functions def shout(text): return text.upper() def whisper(text): return text.lower() def greet(func): # storing the function in a variable greeting = func("Hi, I am created by a function passed as an argument.") print(greeting) #HI, I AM CREATED BY...
#!python3 import time import os, sys import argparse import tempfile import datetime import FaceWarperClient as fwc class Timer: def __init__(self): self._start_time = None self.restart() def restart(self): self._start_time = time.perf_counter() def time(self): return ti...