code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function export_grid obj colormap=none order=none xlim=none ylim=none filename=none begin comment colormap if colormap is none begin set colormap = dictionary end comment a list to align layered objects in order if order is none begin set order = list end set fig = figure set pypobjs = list set ax = call add_subplot ...
def export_grid( obj, colormap=None, order=None, xlim=None, ylim=None, filename=None, ): # colormap if colormap is None: colormap = dict() # a list to align layered objects in order if order is None: order = [] fig = plt.figure() pypobjs = [] ax = fi...
Python
nomic_cornstack_python_v1
import os import datetime from ravenpackapi import RPApi comment Or PRODUCT = "edge" set PRODUCT = string rpa set api = call RPApi product=PRODUCT function download_or_read_reference_file reference_filename=string reference.csv begin if is file path reference_filename begin comment use the locally saved reference file ...
import os import datetime from ravenpackapi import RPApi PRODUCT = "rpa" # Or PRODUCT = "edge" api = RPApi(product=PRODUCT) def download_or_read_reference_file(reference_filename="reference.csv"): if os.path.isfile(reference_filename): # use the locally saved reference file if it exists referen...
Python
zaydzuhri_stack_edu_python
import sys , string , math , itertools set n = integer input set L = list for i in range 2 n + 1 2 begin if n % i == 0 begin append L i end end print *L
import sys,string, math,itertools n = int(input()) L = [] for i in range(2,n+1,2) : if n%i == 0 : L.append(i) print(*L)
Python
zaydzuhri_stack_edu_python
from enum import Enum import numpy as np import robot_arm from util import * from math import pi from matplotlib import pyplot as plt import screen import logging set log = call getLogger __name__ from operator import itemgetter comment ==========================# comment Useful numbers# set tuple a b c = tuple 1 2 4 c...
from enum import Enum import numpy as np import robot_arm from util import * from math import pi from matplotlib import pyplot as plt import screen import logging log = logging.getLogger(__name__) from operator import itemgetter #==========================# #Useful numbers# a, b, c = (1, 2, 4) #cuts to make. cuts["red"...
Python
zaydzuhri_stack_edu_python
import os import re import uuid import sqlite3 set SQLITE_PATH = join path directory name path __file__ string msol.db function rand_uuid begin return string uuid 4 end function class Database begin function __init__ self begin set conn = call connect SQLITE_PATH call init_db end function function select self sql param...
import os import re import uuid import sqlite3 SQLITE_PATH = os.path.join(os.path.dirname(__file__), 'msol.db') def rand_uuid(): return str(uuid.uuid4()) class Database: def __init__(self): self.conn = sqlite3.connect(SQLITE_PATH) self.init_db() def select(self, sql, parameters=[]): ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment Copyright 2013 Amit Wolfus string Defines the models for the sociopark application set __author__ = string amitwolfus@gmail.com (Amit Wolfus from google.appengine.ext import db from geo.geomodel import GeoModel class ParkingState begin string Represents an enum for the available sta...
#!/usr/bin/env python # # Copyright 2013 Amit Wolfus """Defines the models for the sociopark application""" __author__= 'amitwolfus@gmail.com (Amit Wolfus' from google.appengine.ext import db from geo.geomodel import GeoModel class ParkingState: """Represents an enum for the available states of a parki...
Python
zaydzuhri_stack_edu_python
function main begin set stub = call Stub console=true call makeStubs return 0 end function
def main(): stub = Stub(console=True) stub.makeStubs() return 0
Python
nomic_cornstack_python_v1
string First created payroll database and employee table, in table created column name in sequence like (id,name,designation,basic_salary,da,hra,gross_salary,tax,net_salary print string ------Project Title------ print string ------Payroll Management System------ comment to hold the output screen input print string ****...
'''First created payroll database and employee table, in table created column name in sequence like (id,name,designation,basic_salary,da,hra,gross_salary,tax,net_salary ''' print(" ------Project Title------ ") print("------Payroll Management System------") input() #to hold the output screen print(" *****C...
Python
zaydzuhri_stack_edu_python
function read_by_lines path encoding=string utf-8 begin set result = list with open path string r as infile begin for line in infile begin append result decode strip line encoding end end return result end function
def read_by_lines(path, encoding="utf-8"): result = list() with open(path, "r") as infile: for line in infile: result.append(line.strip().decode(encoding)) return result
Python
nomic_cornstack_python_v1
function reload_lv2_plugins_data self begin set plugins_data = call lv2_plugins_data save plugins_data end function
def reload_lv2_plugins_data(self): plugins_data = self.lv2_builder.lv2_plugins_data() self._dao.save(plugins_data)
Python
nomic_cornstack_python_v1
function bokeh_shot_chart data x=string LOC_X y=string LOC_Y fill_color=string #1f77b4 scatter_size=10 fill_alpha=0.4 line_alpha=0.4 court_line_color=string gray court_line_width=1 hover_tool=false tooltips=none **kwargs begin comment TODO: Settings for hover tooltip string Returns a figure with both FGA and basketball...
def bokeh_shot_chart(data, x="LOC_X", y="LOC_Y", fill_color="#1f77b4", scatter_size=10, fill_alpha=0.4, line_alpha=0.4, court_line_color='gray', court_line_width=1, hover_tool=False, tooltips=None, **kwargs): # TODO: Settings for hover tooltip """ ...
Python
jtatman_500k
function getvehiclesstats self game personaid begin set params = dict string game game ; string personaId personaid set r = call jsonRPC string Progression.getVehiclesByPersonaId params=params return r end function
def getvehiclesstats(self, game, personaid): params = { "game": game, "personaId": personaid } r = self.jsonRPC("Progression.getVehiclesByPersonaId", params=params) return r
Python
nomic_cornstack_python_v1
function get_pull_requests_count self begin set repo_details = split strip repo_url string / at slice - 2 : : set pull_requests = 0 set i = 1 while true begin set args = dict string state string open ; string page i ; string per_page 100 set api_url = format string https://api.github.com/repos/{}/{}/pulls?{} repo_det...
def get_pull_requests_count(self): repo_details = self.repo_url.strip().split('/')[-2:] pull_requests = 0 i = 1 while True: args = {'state': 'open', 'page': i, 'per_page': 100} api_url = "https://api.github.com/repos/{}/{}/pulls?{}".format(repo_details[0], repo_de...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python import os from ast import literal_eval function filter_output begin set input_file = open string output.txt string r set output_file = open string filtered_output.txt string w write output_file string [ for line in input_file begin set line = strip line if line at slice : 4 : == string or li...
#!/usr/bin/python import os from ast import literal_eval def filter_output() : input_file = open('output.txt', 'r') output_file = open('filtered_output.txt', 'w') output_file.write('[') for line in input_file : line = line.strip() if line[:4] == "" or line[:4] == "http" : pass else : output_file.write(line ...
Python
zaydzuhri_stack_edu_python
function summarize_grim_checks self begin if _grim_results is none begin set _grim_results = call _apply_grim_to_test_sets end set values = reshape _grim_results - 1 set ns = reshape call tile _test_set tuple 1 _k - 1 set sample = repeat list comprehension join string - list comprehension string i for i in t for t in _...
def summarize_grim_checks(self): if self._grim_results is None: self._grim_results = self._apply_grim_to_test_sets() values = self._grim_results.reshape(-1) ns = np.tile(self._test_set, (1, self._k)).reshape(-1) sample = np.repeat(["-".join([str(i) for i in t]) for t in self....
Python
nomic_cornstack_python_v1
comment Debugging Active Learning Session - CSCI101 comment Bugged File #3 comment User will enter a binary string that will be a 2's complement number set num = input string Enter a binary string to convert: comment Initial variables set placevalue = 1 comment Loop to convert to decimal number for i in range length nu...
# Debugging Active Learning Session - CSCI101 # Bugged File #3 #User will enter a binary string that will be a 2's complement number num = input("Enter a binary string to convert: ") #Initial variables placevalue = 1 #Loop to convert to decimal number for i in range(len(num)): #Go backwards to start with lowest ...
Python
zaydzuhri_stack_edu_python
set string = string hello set n = integer input string Enter a num: print string at n
string="hello" n=int(input("Enter a num:")) print(string[n])
Python
zaydzuhri_stack_edu_python
import os import re class ParseError extends Exception begin pass end class class SubStyler extends object begin set HEX_COLORS = dict string red string #FF0000 ; string white string #FFFFFF ; string cyan string #00FFFF ; string silver string #C0C0C0 ; string blue string #0000FF ; string gray string #808080 ; string gr...
import os import re class ParseError(Exception): pass class SubStyler(object): HEX_COLORS = { "red":"#FF0000", "white":"#FFFFFF", "cyan":"#00FFFF", "silver":"#C0C0C0", "blue": "#0000FF", "gray":"#808080", "grey...
Python
zaydzuhri_stack_edu_python
function compute_pg_cascaded_loss asv_predictions cm_predictions targets is_spoof args begin comment Sample actions if deterministic begin comment Threshold at 0.5 set asv_actions = asv_predictions > 0.5 set cm_actions = cm_predictions > 0.5 end else begin comment Stochastic actions set asv_actions = call rand_like asv...
def compute_pg_cascaded_loss(asv_predictions, cm_predictions, targets, is_spoof, args): # Sample actions if args.deterministic: # Threshold at 0.5 asv_actions = asv_predictions > 0.5 cm_actions = cm_predictions > 0.5 else: # Stochastic actions asv_actions = torch.ran...
Python
nomic_cornstack_python_v1
comment 类方法 comment @classmethod comment def lalala(cls): comment pass class Tool begin set count = 0 decorator classmethod function tool_count cls begin print format string 工具数量: {} count end function function __init__ self name begin set count = count + 1 end function end class set tool1 = call Tool string 斧头 set too...
#类方法 #@classmethod #def lalala(cls): # pass class Tool: count = 0 @classmethod def tool_count(cls): print("工具数量: {}".format(cls.count)) def __init__(self, name): Tool.count += 1 tool1 = Tool("斧头") tool2 = Tool("榔头") Tool.tool_count()
Python
zaydzuhri_stack_edu_python
function fileno self begin return call fileno end function
def fileno(self): return self.sock.fileno()
Python
nomic_cornstack_python_v1
function test_update_complex_name begin comment Standard name update set fn = string sub-X_ses-Y_task-Z_run-01_sbref set metadata = dict string ImageType list string ORIGINAL string PRIMARY string P string MB string TE3 string ND string MOSAIC set suffix = 3 set out_fn_true = string sub-X_ses-Y_task-Z_run-01_part-phase...
def test_update_complex_name(): # Standard name update fn = 'sub-X_ses-Y_task-Z_run-01_sbref' metadata = {'ImageType': ['ORIGINAL', 'PRIMARY', 'P', 'MB', 'TE3', 'ND', 'MOSAIC']} suffix = 3 out_fn_true = 'sub-X_ses-Y_task-Z_run-01_part-phase_sbref' out_fn_test = update_complex_name(metadata, fn, ...
Python
nomic_cornstack_python_v1
function factorial n begin if n == 1 begin return 1 end else begin return n * call factorial n - 1 end end function
def factorial(n): if n == 1: return 1 else: return n * factorial(n - 1)
Python
nomic_cornstack_python_v1
function setup_platform hass config add_devices discovery_info=none begin call add_devices list call AtlasSensor name=get config CONF_NAME port=get config CONF_PORT offset=get config CONF_OFFSET scale=get config CONF_SCALE end function
def setup_platform(hass, config, add_devices, discovery_info=None): add_devices([AtlasSensor( name=config.get(CONF_NAME), port=config.get(CONF_PORT), offset=config.get(CONF_OFFSET), scale=config.get(CONF_SCALE) )])
Python
nomic_cornstack_python_v1
function start_postgres begin set docker_client = call from_env try begin set postgres = get containers string postgres end except NotFound begin return strip decode check output list string docker string run string --name string postgres string -e string POSTGRES_PASSWORD=notsecretpassword string -d string postgres:9....
def start_postgres(): docker_client = docker.from_env() try: postgres = docker_client.containers.get('postgres') except docker.errors.NotFound: return subprocess.check_output( ['docker', 'run', '--name', 'postgres', '-e', 'POSTGRES_PASSWORD=notsecretpass...
Python
nomic_cornstack_python_v1
function New *args **kargs begin set obj = call __New_orig__ import itkTemplate call New obj *args keyword kargs return obj end function
def New(*args, **kargs): obj = itkShotNoiseImageFilterIUC3IUC3.__New_orig__() import itkTemplate itkTemplate.New(obj, *args, **kargs) return obj
Python
nomic_cornstack_python_v1
from __future__ import annotations from enum import IntEnum from typing import Tuple , List , TypeVar , Iterable , Sequence , Generic , List , Callable , Set , Deque , Dict , Any , Optional from typing_extensions import Protocol from heapq import heappush , heappop set Nucleotide : IntEnum = call IntEnum string Nucleot...
from __future__ import annotations from enum import IntEnum from typing import Tuple, List, TypeVar, Iterable, Sequence, Generic, List, Callable, Set, Deque, Dict, Any, Optional from typing_extensions import Protocol from heapq import heappush, heappop Nucleotide: IntEnum = IntEnum('Nucleotide', ('A', 'C', 'G', 'T')) ...
Python
zaydzuhri_stack_edu_python
function TrueFalse a b begin if a == true and b == true begin print string a 和 b 同時成立 end if a == true and b == false begin print string a 成立,b 不成立 end if a == false and b == true begin print string a 不成立,b 成立 end if a == false and b == false begin print string a 不成立,b 不成立 end if a == true or b == true begin print stri...
def TrueFalse(a, b): if a == True and b == True: print("a 和 b 同時成立") if a == True and b == False: print("a 成立,b 不成立") if a == False and b == True: print("a 不成立,b 成立") if a == False and b == False: print("a 不成立,b 不成立") if a == True or b == True: print("a 或 b 成立...
Python
zaydzuhri_stack_edu_python
import re import numpy as np class Moon begin set position = list 0 0 0 set velocity = list 0 0 0 function __init__ self position begin set position = position set velocity = list 0 0 0 end function function ApplyGravity self otherMoon begin for i in range 3 begin call ApplyGravityAxis otherMoon i end end function func...
import re import numpy as np class Moon: position = [0, 0, 0] velocity = [0, 0, 0] def __init__(self, position): self.position = position self.velocity = [0, 0, 0] def ApplyGravity(self, otherMoon): for i in range(3): ApplyGravityAxis(otherMoon, i) def ApplyGr...
Python
zaydzuhri_stack_edu_python
function getUserId begin set ID = input string 아이디를 입력하세요: return ID end function
def getUserId(): ID = input("아이디를 입력하세요: ") return ID
Python
zaydzuhri_stack_edu_python
function parse_options begin set parser = call OptionParser description=string PySpark WordCount. call add_option string -i string --input action=string store nargs=1 default=string s3://dimajix-training/data/alice/ help=string Input file or directory call add_option string -o string --output action=string store nargs=...
def parse_options(): parser = optparse.OptionParser(description='PySpark WordCount.') parser.add_option('-i', '--input', action='store', nargs=1, default='s3://dimajix-training/data/alice/', help='Input file or directory') parser.add_option('-o', '--output', acti...
Python
nomic_cornstack_python_v1
comment _*_ coding.utf-8 _*_ comment 开发人员 : leehm comment 开发时间 : 2020/6/24 22:24 comment 文件名称 : 27.py comment 开发工具 : PyCharm set a = input set b = input set c = input set yours = input set a1 = a + b + c set a2 = a + c + b set a3 = b + c + a set a4 = b + a + c set a5 = c + a + b set a6 = c + b + a if yours == a1 or you...
# _*_ coding.utf-8 _*_ # 开发人员 : leehm # 开发时间 : 2020/6/24 22:24 # 文件名称 : 27.py # 开发工具 : PyCharm a = input() b = input() c = input() yours = input() a1 = a + b + c a2 = a + c + b a3 = b + c + a a4 = b + a + c a5 = c + a + b a6 = c + b + a if yours == a1 or yours == a2 or yours == a3 or yours == a4 or yours == a5 or yours...
Python
zaydzuhri_stack_edu_python
comment copy和deepcopy set aa = dict string username string admin ; string machines list string foo string bar string baz comment shallow copy set bb = copy aa set bb at string username = string mlh comment 原地修改浅复制的内容,原文也会改变 remove bb at string machines string bar print aa string bb comment 使用deepcopy可以解决问题 comment 参数是...
#copy和deepcopy aa = {'username':'admin','machines':['foo','bar','baz']} bb = aa.copy()#shallow copy bb['username'] = 'mlh' bb['machines'].remove('bar')#原地修改浅复制的内容,原文也会改变 print(aa,'\n',bb) #使用deepcopy可以解决问题 print({}.fromkeys(['a', 'bb']))#参数是一个list print(dict.fromkeys(['f','g'],'Hello'))#可以添加一个缺省的参数 print(d.get('name'...
Python
zaydzuhri_stack_edu_python
function route_video_languages begin set result = call retrieve_languages return call jsonify dict string languages result end function
def route_video_languages(): result = video_dal_retriever.retrieve_languages() return jsonify({'languages' : result})
Python
nomic_cornstack_python_v1
function test_device_wireless_api self begin set url = reverse string api_device_wireless args=list 1 set response = get client url assert equal status_code 200 assert equal length data 1 set url = reverse string api_device_wireless args=list 99 set response = get client url assert equal status_code 404 end function
def test_device_wireless_api(self): url = reverse('api_device_wireless', args=[1]) response = self.client.get(url) self.assertEqual(response.status_code, 200) self.assertEqual(len(response.data), 1) url = reverse('api_device_wireless', args=[99]) ...
Python
nomic_cornstack_python_v1
string Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. Example 1: Input: [3,2,3] Output: 3 Example 2: Input: [2,2,1,1,1,2,2] Output: 2 from typing...
""" Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times. You may assume that the array is non-empty and the majority element always exist in the array. Example 1: Input: [3,2,3] Output: 3 Example 2: Input: [2,2,1,1,1,2,2] Output: 2 """ from...
Python
zaydzuhri_stack_edu_python
function scan self **kwargs begin assert get kwargs string text msg string scan: text attribute must be supplied return call _biblia_get form=string scan args=kwargs end function
def scan(self, **kwargs): assert kwargs.get('text'), f'scan: text attribute must be supplied' return self._biblia_get(form='scan', args=kwargs)
Python
nomic_cornstack_python_v1
while x > 0 begin set x = x // k set ans = ans + 1 end print ans
while x > 0: x = x // k ans += 1 print(ans)
Python
zaydzuhri_stack_edu_python
function __call__ self code user_id begin set activation = call q_activation_by_code code if not activation begin raise call MalbonaRezulto status_int=404 title=activation_code_not_found_title plain=activation_code_not_found end set user = call q_user_by_id user_id if not user begin raise call MalbonaRezulto status_int...
def __call__(self, code: str, user_id: int) -> Rezulto: activation = self.repo.q_activation_by_code(code) if not activation: raise MalbonaRezulto( status_int=404, title=self._strings.activation_code_not_found_title, plain=self._strings.activati...
Python
nomic_cornstack_python_v1
function LucasKanade self img1 img2 window begin set tuple fx fy ft = call get_derivatives img1 img2 set denom = call filter2D fx ^ 2 - 1 window * call filter2D fy ^ 2 - 1 window - call filter2D fx * fy - 1 window ^ 2 set denom at denom == 0 = inf set u = - call filter2D fy ^ 2 - 1 window * call filter2D fx * ft - 1 wi...
def LucasKanade(self, img1, img2, window): fx, fy, ft = self.get_derivatives(img1, img2) denom = cv2.filter2D(fx**2, -1, window)*cv2.filter2D(fy**2, -1, window) - \ cv2.filter2D((fx*fy), -1, window)**2 denom[denom == 0] = np.inf u = (-cv2.filter2D(fy**2, -1, window)*cv2.fi...
Python
nomic_cornstack_python_v1
function get_hits self vsid begin import re if not match string ^\w{2}\*\d+$ vsid begin raise call ValueError format string {0} is not a valid Vidispine library ID vsid end if _cache is not none begin set _document = get _cache format string portal.plugins.gnmlibrarytool:{0}:document vsid end if _document is none begin...
def get_hits(self, vsid): import re if not re.match(r'^\w{2}\*\d+$',vsid): raise ValueError("{0} is not a valid Vidispine library ID".format(vsid)) if self._cache is not None: self._document = self._cache.get("portal.plugins.gnmlibrarytool:{0}:document".format(vsid)) ...
Python
nomic_cornstack_python_v1
function stop self begin call terminate_job job_id_string end function
def stop(self): QueueAdapter.terminate_job(self.job_id_string)
Python
nomic_cornstack_python_v1
function _render_vertical self gc lx ly rx ry mx my begin set mx = lx + rx - lx / 2.0 with gc begin call set_line_width 20 call set_stroke_color call _get_border_color call tee_v gc lx ly rx mx my end call set_line_width 10 call set_fill_color gc call tee_v gc lx ly rx mx my end function
def _render_vertical(self, gc, lx, ly, rx, ry, mx, my): mx = lx + (rx - lx) / 2. with gc: gc.set_line_width(20) gc.set_stroke_color(self._get_border_color()) tee_v(gc, lx, ly, rx, mx, my) gc.set_line_width(10) self.set_fill_color(gc) tee_v(gc,...
Python
nomic_cornstack_python_v1
function root config begin set response = call generate_response text=text spans=spans return response end function
def root(config: EntityConfig): response = handler.generate_response(text=config.text, spans=config.spans) return response
Python
nomic_cornstack_python_v1
function prime_fact n begin set primes = list set i = 2 while i * i <= n begin set cnt = 0 while n % i == 0 begin set n = n // i set cnt = cnt + 1 end if cnt begin append primes list i cnt end set i = i + 1 end if n != 1 begin append primes list n 1 end return primes end function set n = integer input set primes = cal...
def prime_fact(n): primes = [] i = 2 while i * i <= n: cnt = 0 while n % i == 0: n //= i cnt += 1 if cnt: primes.append([i, cnt]) i += 1 if n != 1: primes.append([n, 1]) return primes n = int(input()) primes = prime_fact(...
Python
zaydzuhri_stack_edu_python
function get_ytm_dict self begin set ytm = ytm for term in keys Rmn begin set ytm = call bisection self 0.001 0.1 1e-10 2 * term Rmn ytm end return ytm end function
def get_ytm_dict(self): ytm=self.ytm for term in self.Rmn.keys(): ytm = Bootstrapping.bisection(self,0.001, 0.1, 1e-10, 2 * term, self.Rmn, ytm) return ytm
Python
nomic_cornstack_python_v1
function backtest_chart1 backtest_timeseries start_date end_date figsize=tuple 15 9 save=false show=true yscale=string linear begin set backtest_timeseries = loc at slice start_date : end_date : set backtest_timeseries = backtest_timeseries / iloc at 0 set x_values = index set y_values = iloc at tuple slice : : sli...
def backtest_chart1(backtest_timeseries, start_date, end_date, figsize=(15, 9), save=False, show=True, yscale='linear'): backtest_timeseries = backtest_timeseries.loc[start_date: end_date] backtest_timeseries = backtest_timeseries / backtest_timeseries.iloc[0] x_values = backtest_timeseries.index y_valu...
Python
nomic_cornstack_python_v1
import sys class KakaoAnalyzer begin function __init__ self fileName begin set fileName = fileName end function function talkSpliter self begin set textFile = open fileName string r encoding=string utf8 set text = read textFile set text = split text string set newList = list for i in text begin if length i != 0 begin ...
import sys class KakaoAnalyzer: def __init__(self, fileName): self.fileName = fileName def talkSpliter(self): textFile = open(self.fileName, "r", encoding="utf8") text = textFile.read() text = text.split("\n") newList = [] for i in text: if len(...
Python
zaydzuhri_stack_edu_python
class BetterSolution begin function removeElement self nums val begin set length_range = range length nums set length = 0 for i in length_range begin if nums at i != val begin set nums at length = nums at i set length = length + 1 end end return length end function end class class Solution begin function removeElement ...
class BetterSolution: def removeElement(self, nums, val: int) -> int: length_range = range(len(nums)) length = 0 for i in length_range: if nums[i] != val: nums[length] = nums[i] length += 1 return length class Solution: def removeEl...
Python
zaydzuhri_stack_edu_python
import argparse import random import requests import serial import subprocess import threading import time set PINS = list string 2 string 4 string 5 string 6 string 7 set POURING = dictionary comprehension p : false for p in PINS set BUTTON = string 3 set VALVES = list string 2 string 4 string 5 set PUMPS = list strin...
import argparse import random import requests import serial import subprocess import threading import time PINS = ['2', '4', '5', '6', '7'] POURING = {p: False for p in PINS} BUTTON = '3' VALVES = ['2', '4', '5'] PUMPS = ['6', '7'] # Shots take 6 secs to pour from pumps, 7 from valves. SHOT_DURATION = {p: 6 for p i...
Python
zaydzuhri_stack_edu_python
if x < 0 begin print string The Number is Negative end else if x > 0 begin print string The number is Positive end else begin print string The Number is Zero end
if (x<0): print ("The Number is Negative") elif (x>0): print ("The number is Positive") else: print ("The Number is Zero")
Python
zaydzuhri_stack_edu_python
function is_full self begin return length list >= limit end function
def is_full(self): return len(self.list) >= self.limit
Python
nomic_cornstack_python_v1
function ws050 self value=none begin string Corresponds to IDD Field `ws050` Wind speed corresponding 5.0% annual cumulative frequency of occurrence Args: value (float): value for IDD Field `ws050` Unit: m/s if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises:...
def ws050(self, value=None): """ Corresponds to IDD Field `ws050` Wind speed corresponding 5.0% annual cumulative frequency of occurrence Args: value (float): value for IDD Field `ws050` Unit: m/s if `value` is None it will not be checked against the...
Python
jtatman_500k
function add_occupant sender instance created **kwargs begin set room = room if created begin if checked_in == true begin set occupied = true end save end if checked_out == true begin set occupied = false save end end function
def add_occupant(sender, instance, created, **kwargs): room = instance.room if created: if instance.checked_in == True: room.occupied = True room.save() if instance.checked_out == True: room.occupied = False room.save()
Python
nomic_cornstack_python_v1
function __init__ self pin begin comment Numero del pin gpio al que esta conectado el encoder set pin = pin set pi = call pi call set_mode pin INPUT set posPass = 0 end function
def __init__(self, pin): self.pin = pin #Numero del pin gpio al que esta conectado el encoder self.pi = pigpio.pi() self.pi.set_mode(self.pin, pigpio.INPUT) self.posPass = 0
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment coding: utf-8 import matplotlib.pyplot as plt import numpy as np import sys set fileName = string argv at 1 set threshold = string argv at 2 set colors = list string red string blue string brown string orange string teal string grey string pink string yellow string green string ligh...
#!/usr/bin/env python # coding: utf-8 import matplotlib.pyplot as plt import numpy as np import sys fileName = str(sys.argv[1]) threshold = str(sys.argv[2]) colors = ["red", "blue", "brown", "orange", "teal", "grey", "pink", "yellow", "green", "lightblue"] xLabel = "X" yLabel = "Y" f = open(fileName) title = "Graph...
Python
zaydzuhri_stack_edu_python
comment Python Object Oriented Programming class Employee begin set num_of_emps = 0 set raise_amount = 1.04 function __init__ self first last pay begin set first = first set last = last set pay = pay set num_of_emps = num_of_emps + 1 end function decorator property function email self begin return format string {}.{}@e...
# Python Object Oriented Programming class Employee: num_of_emps = 0 raise_amount = 1.04 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay Employee.num_of_emps += 1 @property def email(self): ...
Python
zaydzuhri_stack_edu_python
comment Question string Make a script that prints out numbers from 1 to 10. Hint: Simply iterate through a range object. comment Answer: string for i in range(1,11): print(i) Explanation: A for loop is used to repeat an action (i.e. print ) until the iterating sequence (i.e. range ) is consumed. In our case it would pr...
#Question ''' Make a script that prints out numbers from 1 to 10. Hint: Simply iterate through a range object. ''' #Answer: ''' for i in range(1,11): print(i) Explanation: A for loop is used to repeat an action (i.e. print ) until the iterating sequence (i.e. range ) is consumed. In our case it would print all ...
Python
zaydzuhri_stack_edu_python
function get_permissions self grp_name resource begin string Get permissions associated the group has with the given resource. Args: grp_name (string): Name of group. resource (intern.resource.boss.Resource): Identifies which data model object to operate on. Returns: (list): List of permissions. Raises: requests.HTTPEr...
def get_permissions(self, grp_name, resource): """ Get permissions associated the group has with the given resource. Args: grp_name (string): Name of group. resource (intern.resource.boss.Resource): Identifies which data model object to operate on. ...
Python
jtatman_500k
comment !/usr/bin/env python comment Mabel Zhang comment 3 Mar 2015 comment During manual exploration of an object (i.e. using human hand to guide the comment ReFlex Hand on the object surface), plots: comment - a marker at anywhere a pressure sensor exceeds a threshold. Per iteration comment - a point cloud of all suc...
#!/usr/bin/env python # Mabel Zhang # 3 Mar 2015 # # During manual exploration of an object (i.e. using human hand to guide the # ReFlex Hand on the object surface), plots: # - a marker at anywhere a pressure sensor exceeds a threshold. Per iteration # - a point cloud of all such sensor positions. Cumulative. # ...
Python
zaydzuhri_stack_edu_python
comment get data from user and store it in a list, then comment display the most recent three entries nicely comment Set up empty list set all_calculations = list comment Get five items of Data if __name__ == string __main__ begin for item in range 0 5 begin set get_item = input string Enter and item: append all_calcu...
# get data from user and store it in a list, then # display the most recent three entries nicely # Set up empty list all_calculations = [] # Get five items of Data if __name__ == '__main__': for item in range(0, 5): get_item = input("Enter and item: ") all_calculations.append(get_item) # Show th...
Python
zaydzuhri_stack_edu_python
function __init__ self price_process liquidity_process trade_cost begin set price_process = price_process set liquidity_process = liquidity_process set trade_cost = trade_cost end function
def __init__(self, price_process, liquidity_process, trade_cost): self.price_process = price_process self.liquidity_process = liquidity_process self.trade_cost = trade_cost
Python
nomic_cornstack_python_v1
function get_query_url self begin set url = server_url set url = url + paths at query_type + string ? debug string The url to query is %s % url set params = dict FILTER_KEY dict ; QUERY_FILTER_KEY dict comment add passed params call __add_query_param query_params params comment add default params if they have been pa...
def get_query_url(self): url = self.__config.server_url url = url + self.__config.paths[self.query_type] + '?' logging.debug('The url to query is %s' % url) params = { self.FILTER_KEY: {}, self.QUERY_FILTER_KEY: {} } # add passed params s...
Python
nomic_cornstack_python_v1
function request_continuation_token self request_continuation_token begin set _request_continuation_token = request_continuation_token end function
def request_continuation_token(self, request_continuation_token): self._request_continuation_token = request_continuation_token
Python
nomic_cornstack_python_v1
function normalized_words cls text begin comment XXX split on punctuation as well return list comprehension word for word in list comprehension call normalize_word word for word in split text if word end function
def normalized_words(cls, text): # XXX split on punctuation as well return [word for word in [cls.normalize_word(word) for word in text.split()] if word]
Python
nomic_cornstack_python_v1
function compute_descriptor img begin set rects = call detector img 1 set shape = call sp68 img rects at 0 set comp = call compute_face_descriptor img shape set a = list for i in comp begin append a i end return a end function
def compute_descriptor(img): rects = detector(img,1) shape = sp68(img,rects[0]) comp = facerec.compute_face_descriptor(img,shape) a = [] for i in comp: a.append(i) return a
Python
nomic_cornstack_python_v1
comment coding=utf8 import ply.yacc as yacc from mlex import lexer , tokens set start = string program class Statement extends object begin set content = none end class function p_value p begin string value : STRING | INTEGER | FLOAT end function function p_setexpression p begin string end function function p_setstate...
#coding=utf8 import ply.yacc as yacc from mlex import lexer, tokens start = 'program' class Statement(object): content = None def p_value(p): ''' value : STRING | INTEGER | FLOAT ''' def p_setexpression(p): ''' ''' def p_setstatement(p): ''' setstatement...
Python
zaydzuhri_stack_edu_python
comment Author: Patrick Blanchard comment Date: 10-26-17 comment Description: Scrapes CNN for news articles from bs4 import BeautifulSoup import urllib comment collects links from page and adds them to a queue comment max_size determines how large the queue can get before exiting comment returns a list of articles func...
# Author: Patrick Blanchard # Date: 10-26-17 # Description: Scrapes CNN for news articles from bs4 import BeautifulSoup import urllib # collects links from page and adds them to a queue # max_size determines how large the queue can get before exiting # returns a list of articles def crawl(domain, max_size): queue =...
Python
zaydzuhri_stack_edu_python
function put self key item begin if key and item is not none begin set cache_data at key = item call move_to_end key if length cache_data > MAX_ITEMS begin set remove = pop item cache_data last=false print string DISCARD: + string remove at 0 end end end function
def put(self, key, item): if key and item is not None: self.cache_data[key] = item self.cache_data.move_to_end(key) if len(self.cache_data) > BaseCaching.MAX_ITEMS: remove = self.cache_data.popitem(last=False) print('DISCARD: ' + str(remove[0])...
Python
nomic_cornstack_python_v1
function createExampleProject begin set project = call makeBasicProject comment Create sprite sheet for the player sprite set player_sprite_sheet = call addSpriteSheet project string actor_animated.png string actor_animated string actor_animated set settings at string playerSpriteSheetId = player_sprite_sheet at string...
def createExampleProject(): project = generator.makeBasicProject() # Create sprite sheet for the player sprite player_sprite_sheet = generator.addSpriteSheet(project, "actor_animated.png", "actor_animated", "actor_animated") project.settings["playerSpriteSheetId"] = player_sprite_sheet["id"] ...
Python
nomic_cornstack_python_v1
function get_copy_var_ops dest_scope_name src_scope_name begin comment Copy variables src_scope to dest_scope set op_holder = list set src_vars = call get_collection TRAINABLE_VARIABLES scope=src_scope_name set dest_vars = call get_collection TRAINABLE_VARIABLES scope=dest_scope_name for tuple src_var dest_var in zip ...
def get_copy_var_ops(*, dest_scope_name: str, src_scope_name: str) -> List[tf.Operation]: # Copy variables src_scope to dest_scope op_holder = [] src_vars = tf.get_collection( tf.GraphKeys.TRAINABLE_VARIABLES, scope=src_scope_name) dest_vars = tf.get_collection( tf.GraphKeys.TRAINABLE_V...
Python
nomic_cornstack_python_v1
comment The training data file name has to be provided in line 172, validation data in 176 comment Dependent variable should be named "binary".Text data, when present, should be the last column, and named "text" comment The confusion matrix will be in the output file nn_validation_confusion.png and validation data prob...
# The training data file name has to be provided in line 172, validation data in 176 # Dependent variable should be named "binary".Text data, when present, should be the last column, and named "text" # The confusion matrix will be in the output file nn_validation_confusion.png and validation data probabilities in Valid...
Python
zaydzuhri_stack_edu_python
function bacon_number self start target=string Bacon, Kevin begin set my_list = call path_to_bacon start return length my_list - 1 / 2 end function
def bacon_number(self, start, target="Bacon, Kevin"): my_list = self.path_to_bacon(start) return (len(my_list)-1)/2
Python
nomic_cornstack_python_v1
function track_capsules ParameterClass begin import timeit set start_time = call default_timer set start_time = call default_timer print string Printing Arguments print string path : + string path print string d0 : + string d0 print string pPmm : + string pPmm print string background : + string backgroundImage print st...
def track_capsules(ParameterClass): import timeit start_time = start_time = timeit.default_timer() print('Printing Arguments') print(' path : ' + str( ParameterClass.path)) print('d0 : ' + str(ParameterClass.d0)) print('pPmm : ' + str(ParameterClass.pPmm)) print('background : ' + str(Pa...
Python
nomic_cornstack_python_v1
function count_words string begin set words = dict for word in split string begin if word in words begin set words at word = words at word + 1 end else begin set words at word = 1 end end return words end function
def count_words(string): words = {} for word in string.split(): if word in words: words[word] += 1 else: words[word] = 1 return words
Python
jtatman_500k
import cv2 import numpy as np import os comment from https://stackoverflow.com/questions/28717054/calculating-sharpness-of-an-image function getBlurValue image begin set canny = call Canny image 50 250 return mean np canny end function function getSimilarity img1 img2 begin return call matchTemplate frame last_image TM...
import cv2 import numpy as np import os ########################################################################## # from https://stackoverflow.com/questions/28717054/calculating-sharpness-of-an-image def getBlurValue(image): canny = cv2.Canny(image, 50,250) return np.mean(canny) ##############################...
Python
zaydzuhri_stack_edu_python
comment https://stackoverflow.com/questions/19201290/how-to-save-a-dictionary-to-a-file/32216025 import pickle import os.path import pandas as pd from datetime import datetime set MODEL_OBJ_RELATIVE_PATH = string ./trained_vectors/py_obj/ set PROCESSED_LOG_RELATIVE_PATH = string ./logs/processed/ function is_file_exist...
# https://stackoverflow.com/questions/19201290/how-to-save-a-dictionary-to-a-file/32216025 import pickle import os.path import pandas as pd from datetime import datetime MODEL_OBJ_RELATIVE_PATH = './trained_vectors/py_obj/' PROCESSED_LOG_RELATIVE_PATH = './logs/processed/' def is_file_exist(path): return os.pat...
Python
zaydzuhri_stack_edu_python
from pprint import pprint function check_passwd username password min_len=8 check_numbers=false check_spec_sym=true begin string Функция проверяет пароль, возвращает True/False print string username= { username } password= { password } min_len= { min_len } if length password < min_len begin comment print("Пароль слишко...
from pprint import pprint def check_passwd( username, password, *, min_len=8, check_numbers=False, check_spec_sym=True ): """ Функция проверяет пароль, возвращает True/False """ print(f"{username=} {password=} {min_len=}") if len(password) < min_len: # print("Пароль слишком...
Python
zaydzuhri_stack_edu_python
function from_hdulist cls hdulist hdu_bands=none begin try begin set sed_type = header at string SED_TYPE end except KeyError begin raise call ValueError string Cannot determine SED type of flux map from primary header. end set maps = dict for map_type in REQUIRED_MAPS at sed_type begin set maps at map_type = call fro...
def from_hdulist(cls, hdulist, hdu_bands=None): try: sed_type = hdulist[0].header["SED_TYPE"] except KeyError: raise ValueError( f"Cannot determine SED type of flux map from primary header." ) maps = {} for map_type in REQUIRED_MAPS[s...
Python
nomic_cornstack_python_v1
if f == v begin print string é um palíndromo end else begin print string não é um palíndromo end
if f == v: print("é um palíndromo") else: print("não é um palíndromo")
Python
zaydzuhri_stack_edu_python
import unittest from helper.map40 import Map40 from single_source_shortest_path import SingleSourceShortestPath , Graph class TestAStar extends TestCase begin function test_map_with_40_nodes_start_5_end_34 self begin set start_node_id = 5 set dest_node_id = 34 set paths = call find_path set shortest_path = list while ...
import unittest from helper.map40 import Map40 from single_source_shortest_path import SingleSourceShortestPath, Graph class TestAStar(unittest.TestCase): def test_map_with_40_nodes_start_5_end_34(self): start_node_id = 5 dest_node_id = 34 paths = SingleSourceShortestPath(Graph(Map40.inters...
Python
zaydzuhri_stack_edu_python
from builtins import range import numpy as np from loss_capabilities.softmax_loss import SoftMax class NeuralNet begin function __init__ self hidden_dims=list 50 50 input_dims=40 num_classes=5 reg=0.0 weight_dev=0.01 dtype=float32 loss_type=none function=string sigmoid begin comment function='sigmoid' set num_layers = ...
from builtins import range import numpy as np from loss_capabilities.softmax_loss import SoftMax class NeuralNet: def __init__(self, hidden_dims=[50, 50], input_dims=40, num_classes=5, reg=0.0, weight_dev=1e-2, dtype=np.float32, loss_type=None, function='sigmoid'): # function='sigmoid' ...
Python
zaydzuhri_stack_edu_python
function validate_response response begin if type response != Response begin raise call AttributeError string 'response' variable type is not a requests.Response type. end set high_level_schema = call Schema dict string data object ; string meta object set response_data = json response return call is_valid response_dat...
def validate_response(response): if type(response) != requests.models.Response: raise AttributeError("'response' variable type is not a requests.Response type.") high_level_schema = schema.Schema({'data': object, 'meta': object}) response_data = response.json() return high_level_schema.is_vali...
Python
nomic_cornstack_python_v1
function render self **kwargs begin if not _vis_component begin warn string No visualization component has set return end set cpcolor = get kwargs string cpcolor string blue set curvecolor = get kwargs string curvecolor string black comment Check all parameters are set call _check_variables comment Check if the surface...
def render(self, **kwargs): if not self._vis_component: warn("No visualization component has set") return cpcolor = kwargs.get('cpcolor', 'blue') curvecolor = kwargs.get('curvecolor', 'black') # Check all parameters are set self._check_variables() ...
Python
nomic_cornstack_python_v1
function read_lines filename=string nb_lines=0 begin set linecount = 0 with open filename string r encoding=string utf-8 as my_file begin if nb_lines <= 0 begin print read my_file end=string end else begin for line in my_file begin if linecount < nb_lines begin print line end=string set linecount = linecount + 1 end e...
def read_lines(filename="", nb_lines=0): linecount = 0 with open(filename, "r", encoding='utf-8') as my_file: if nb_lines <= 0: print(my_file.read(), end="") else: for line in my_file: if linecount < nb_lines: print(line, end="") ...
Python
nomic_cornstack_python_v1
function test_GBSA_params_by_type self begin from peleffy.forcefield.parameters import OPLS2005ParameterWrapper comment 1st test set OPLS_params = call OPLS2005ParameterWrapper comment Create mock molecule containing just one customized atom set OPLS_params at string atom_names = list string C1 set OPLS_params at strin...
def test_GBSA_params_by_type(self): from peleffy.forcefield.parameters import OPLS2005ParameterWrapper # 1st test OPLS_params = OPLS2005ParameterWrapper() # Create mock molecule containing just one customized atom OPLS_params['atom_names'] = [' C1 '] OPLS_params['atom_...
Python
nomic_cornstack_python_v1
function get_char self begin for i in range length bars begin set left = i * step set right = i + 1 * step if left <= value < right begin return bars at i end end return bars at - 1 end function
def get_char(self): for i in range(len(HBar.bars)): left = i * self.step right = (i + 1) * self.step if left <= self.value < right: return self.bars[i] return self.bars[-1]
Python
nomic_cornstack_python_v1
import pandas as pd set data = list tuple string John 24 string Male tuple string Sarah 32 string Female comment Create the pandas DataFrame set df = call DataFrame data columns=list string Name string Age string Gender print df
import pandas as pd data = [('John', 24, 'Male'), ('Sarah', 32, 'Female')] # Create the pandas DataFrame df = pd.DataFrame(data, columns = ['Name', 'Age', 'Gender']) print(df)
Python
jtatman_500k
function get_coloring self begin set colors = dictionary set colors at - 1 = 0 comment Don't want any normal colors on the last frame if not sorting_active begin set new_list = list comprehension integer i for i in lst comment The list is sorted, color it green if sorted_lst == new_list begin set colors at - 1 = 1 retu...
def get_coloring(self): colors = dict() colors[-1] = 0 if not self.sorting_active: # Don't want any normal colors on the last frame new_list = [int(i) for i in self.lst] if self.sorted_lst == new_list: # The list is sorted, color it green colors[-1] = 1 ...
Python
nomic_cornstack_python_v1
function _get_serialized_challenge_lines self cr uid challenge user_id=false restrict_goal_ids=false restrict_top=false context=none begin set goal_obj = get pool string gamification.goal set tuple start_date end_date = call start_end_date_for_period period set res_lines = list set all_reached = true for line in line_...
def _get_serialized_challenge_lines(self, cr, uid, challenge, user_id=False, restrict_goal_ids=False, restrict_top=False, context=None): goal_obj = self.pool.get('gamification.goal') (start_date, end_date) = start_end_date_for_period(challenge.period) res_lines = [] all_reached = True ...
Python
nomic_cornstack_python_v1
function build_vocabulary image_paths vocab_size begin comment Load images from the training set. To save computation time, you don't comment necessarily need to sample from all images, although it would be better comment to do so. You can randomly sample the descriptors from each image to save comment memory and speed...
def build_vocabulary(image_paths, vocab_size): # Load images from the training set. To save computation time, you don't # necessarily need to sample from all images, although it would be better # to do so. You can randomly sample the descriptors from each image to save # memory and speed up the clusteri...
Python
nomic_cornstack_python_v1
import numpy as np import cv2 , random , sys , math , cProfile comment check it has loaded function clip val minimum maximum begin return sorted tuple minimum val maximum at 1 end function function problem1 img bright_factor=2 blend_factor=0.8 rainbow=false begin if not img is none begin set windowName = string Light L...
import numpy as np import cv2, random, sys, math, cProfile # check it has loaded def clip(val, minimum, maximum): return sorted((minimum, val, maximum))[1] def problem1(img, bright_factor = 2, blend_factor = 0.8, rainbow = False): if not img is None: windowName = "Light Leak Filter" # Now w...
Python
zaydzuhri_stack_edu_python
string Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 comment 整体思路 comment 递归 comment 问题: return l1 or l2 有什么具体功能?还能一直循环返回? import list comment Definition for singly-l...
""" Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 """ # 整体思路 # 递归 # 问题: return l1 or l2 有什么具体功能?还能一直循环返回? import list # Definition for singly-linked list. # class...
Python
zaydzuhri_stack_edu_python
comment import inspect from StandartTypes import Number from StandartTypes import String from StandartTypes import Boolean from StandartTypes import Array from CodeStructures import Types if __name__ == string __main__ begin set GLOBAL_PARAMETERS = dict string Number Number ; string Boolean Boolean ; string String Stri...
#import inspect from StandartTypes import Number from StandartTypes import String from StandartTypes import Boolean from StandartTypes import Array from CodeStructures import Types if __name__ == '__main__': GLOBAL_PARAMETERS = {'Number':Number.Number, 'Boolean':Boolean.Boolean, ...
Python
zaydzuhri_stack_edu_python
function set self option_id value priority=1 source=string unknown entity=none begin call assert_type option_id value entity=entity set key = call _option_key option_id entity add _config at key value priority source end function
def set(self, option_id, value, priority=1, source='unknown', entity=None): self._type_checker.assert_type(option_id, value, entity=entity) key = self._option_key(option_id, entity) self._config[key].add(value, priority, source)
Python
nomic_cornstack_python_v1
function reset self begin comment initial snake starts at center of screen set body = list list integer x_pos / 2 integer y_pos / 2 set direction = string UP set length = 1 set alive = true set speed = 10 end function
def reset(self): self.body = [[int(self.x_pos/2), int(self.y_pos/2)]] # initial snake starts at center of screen self.direction = "UP" self.length = 1 self.alive = True self.speed = 10
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 string Unit tests for BaseModel from unittest import TestCase from models.base_model import BaseModel class TestBaseModel extends TestCase begin string Tests BaseModel function test_init self begin string tests init set base = call BaseModel assert is instance base BaseModel assert in string i...
#!/usr/bin/python3 '''Unit tests for BaseModel''' from unittest import TestCase from models.base_model import BaseModel class TestBaseModel(TestCase): '''Tests BaseModel''' def test_init(self): '''tests init''' base = BaseModel() self.assertIsInstance(base, BaseModel) self.asse...
Python
zaydzuhri_stack_edu_python
function create_report self output_filename=none output_format=string html offline_js=false begin comment extra code to put in the <head> part of HTML set extra_head_code = string if output_format == string html begin comment embed plotly.js in HTML (makes it bigger, but then doesn't require web connection) if offline...
def create_report(self, output_filename=None, output_format='html', offline_js=False): # extra code to put in the <head> part of HTML extra_head_code = '' if output_format == 'html': # embed plotly.js in HTML (makes it bigger, but then doesn't require web connection) i...
Python
nomic_cornstack_python_v1
import boto3 set ec2 = call resource string ec2 # Cloud resource management logic here
import boto3 ec2 = boto3.resource('ec2\n# Cloud resource management logic here')
Python
flytech_python_25k
import unittest import unittest.mock as mock import store.checkout as checkout class TestCaseUnderTen extends TestCase begin function test_price_as_five_dollars self begin assert equal call calculate_order 5 5 0.1 5.95 end function function test_price_as_seven_with_ten_percent_off self begin assert equal call calculate...
import unittest import unittest.mock as mock import store.checkout as checkout class TestCaseUnderTen(unittest.TestCase): def test_price_as_five_dollars(self): self.assertEqual(checkout.calculate_order(5, 5, .10), 5.95) def test_price_as_seven_with_ten_percent_off(self): self.assertEqual(checkout.ca...
Python
zaydzuhri_stack_edu_python