code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function create_char_relation df_bibleTA_distilled begin string each time we save a character or a relation we do have to do expensive operations in I/O a .pkl file. set character_list = list set character_name_list = list set relation_list = list for tuple _ row in call iterrows begin set tuple character_A_name cha...
def create_char_relation(df_bibleTA_distilled): """each time we save a character or a relation we do have to do expensive operations in I/O a .pkl file.""" character_list = [] character_name_list = [] relation_list = [] for _, row in df_bibleTA_distilled.iterrows(): character_A_name, charac...
Python
nomic_cornstack_python_v1
function main begin function get_password begin print string Your password must be between MIN_LENGTH string and MAX_LENGTH string characters, and contain: print string 1 or more uppercase characters print string 1 or more lowercase characters print string 1 or more numbers print string 1 or more special characters set...
def main(): def get_password(): print("Your password must be between", MIN_LENGTH, "and", MAX_LENGTH, "characters, and contain:") print("\t1 or more uppercase characters") print("\t1 or more lowercase characters") print("\t1 or more numbers") print("\t1 or more...
Python
zaydzuhri_stack_edu_python
function parse_profiling_filepath filepath begin set path = split filepath string / set fname = path at - 1 set run = path at - 2 set opt = path at - 3 set benchmark = path at - 4 set cache_size = path at - 5 set func_no = integer split fname string . at - 1 return tuple benchmark func_no opt run cache_size end functio...
def parse_profiling_filepath(filepath): path = filepath.split("/") fname = path[-1] run = path[-2] opt = path[-3] benchmark = path[-4] cache_size = path[-5] func_no = int(fname.split(".")[-1]) return benchmark, func_no, opt, run, cache_size
Python
nomic_cornstack_python_v1
function are_nodes_online nodes begin if is instance nodes str begin set nodes = list nodes end set node_results = dict for node in nodes begin set cmd = string ping %s -c1 % node set tuple ret out err = call run_local cmd if ret begin info string %s is offline % node set node_results at node = false end else begin in...
def are_nodes_online(nodes): if isinstance(nodes, str): nodes = [nodes] node_results = {} for node in nodes: cmd = "ping %s -c1" % node ret, out, err = g.run_local(cmd) if ret: g.log.info("%s is offline" % node) node_results[node] = False els...
Python
nomic_cornstack_python_v1
function evaluate_segmentation weight_dir=string unet_model=none bs=8 save=false model_name=string ifhd=true ifasd=true begin print string start to evaluate...... if save begin print string to save: positive set csv_path = string evaluation_of_models_tf.csv if exists path csv_path begin set df = read csv csv_path end...
def evaluate_segmentation(weight_dir='', unet_model=None, bs=8, save=False, model_name='', ifhd=True, ifasd=True): print("start to evaluate......") if save: print("to save: positive") csv_path = 'evaluation_of_models_tf.csv' if os.path.exists(csv_path): df = pd.read_csv(csv_p...
Python
nomic_cornstack_python_v1
from sklearn.neighbors import KNeighborsClassifier from skimage import exposure from skimage import feature from imutils import paths import imutils import cv2 import os import numpy as np import pickle import joblib function test model_path image_path begin comment load the model from disk set model = load joblib mode...
from sklearn.neighbors import KNeighborsClassifier from skimage import exposure from skimage import feature from imutils import paths import imutils import cv2 import os import numpy as np import pickle import joblib def test(model_path, image_path): # load the model from disk model = joblib.load(model_path) ...
Python
zaydzuhri_stack_edu_python
function getAllOrNone self begin return __allOrNone end function
def getAllOrNone(self): return self.__allOrNone
Python
nomic_cornstack_python_v1
from django.shortcuts import redirect , render from lists.models import Item , List import random function view_list request list_id begin set list_ = get objects id=list_id set comment = call insert_comment list_ return call render request string list.html dict string list list_ ; string comment comment end function f...
from django.shortcuts import redirect, render from lists.models import Item, List import random def view_list(request, list_id): list_ = List.objects.get(id=list_id) comment = insert_comment(list_) return render(request, 'list.html', {'list':list_, 'comment':comment}) def home_page(request): return re...
Python
zaydzuhri_stack_edu_python
function addEdge self vertex1 vertex2 begin call addVertex vertex1 call addVertex vertex2 if vertex2 not in adjList at vertex1 begin append adjList at vertex1 vertex2 end end function
def addEdge(self, vertex1, vertex2): self.addVertex(vertex1) self.addVertex(vertex2) if vertex2 not in self.adjList[vertex1]: self.adjList[vertex1].append(vertex2)
Python
nomic_cornstack_python_v1
import requests function bruteforce username url begin for k in k1 begin set k = strip k print string [!!] trying to bruteforce password + k set data_dictionary = dict string name username ; string password k ; string Login string return false set resp = post url data_dictionary if string Authentication failed: invalid...
import requests def bruteforce(username,url): for k in k1: k = k.strip() print ('[!!] trying to bruteforce password ' + k) data_dictionary = {'name':username, 'password':k, 'Login':'return false'} resp = requests.post(url, data_dictionary) if "Authentication failed: invalid u...
Python
zaydzuhri_stack_edu_python
import sys import json from pyspark.sql import SparkSession function main input_file output_file begin set result = dict set spark = call getOrCreate set text = cache comment A. Find the total number of users set result at string total_users = count text comment B. Find the average number of written reviews of all use...
import sys import json from pyspark.sql import SparkSession def main(input_file, output_file): result = {} spark = SparkSession.builder.master("local[*]").appName("HW1").getOrCreate() text = spark \ .sparkContext \ .textFile(input_f...
Python
zaydzuhri_stack_edu_python
from course import Course from urllib.request import urlopen from urllib.error import URLError from bs4 import BeautifulSoup from appJar import gui class Main begin function __init__ self begin set courses = list set course_codes = list set name_to_course = dict set name_to_file = dict call populate_courses set app...
from course import Course from urllib.request import urlopen from urllib.error import URLError from bs4 import BeautifulSoup from appJar import gui class Main: def __init__(self): self.courses = [] self.course_codes = [] self.name_to_course = {} self.name_to_file = {} self.p...
Python
zaydzuhri_stack_edu_python
string Unit tests for the whole application. from unittest.mock import MagicMock import pytest from falcon import testing import app.factory decorator fixture function mock_model_session begin string Create a mock ONNX session for testing. set mock_model_session = call MagicMock set return_value = tuple none list dict ...
"""Unit tests for the whole application.""" from unittest.mock import MagicMock import pytest from falcon import testing import app.factory @pytest.fixture() def mock_model_session(): """Create a mock ONNX session for testing.""" mock_model_session = MagicMock() mock_model_session.run.return_value = (N...
Python
zaydzuhri_stack_edu_python
function test_publish_populates_store_for_new_kernel self begin set new_activity = hex set value = string some awesome value call publish kernel_id new_activity value assert true get activity at kernel_id is not none string Kernel activity object was not created end function
def test_publish_populates_store_for_new_kernel(self): new_activity = uuid.uuid1().hex value = 'some awesome value' self.activity.publish(self.kernel_id, new_activity, value) self.assertTrue(self.activity.get()[self.kernel_id] is not None, 'Kernel activity object was not created')
Python
nomic_cornstack_python_v1
string What is the largest prime factor of the number 600851475143 set number = integer input string entger any integer set factors = list set largest = list for i in range 1 number + 1 begin if number % i == 0 begin append factors i end end comment print(i) print factors set maximum = max factors print maximum for f...
"""What is the largest prime factor of the number 600851475143""" number = int(input("entger any integer")) factors = [] largest = [] for i in range(1 , number + 1): if number % i == 0: factors.append(i) #print(i) print(factors) maximum = max(factors) print(maximum) for fact in factors: for i i...
Python
zaydzuhri_stack_edu_python
comment 一、导入datetime包 comment import datetime comment print(datetime.date(2019, 3, 20)) # 提供year,month,day属性 comment # print(datetime.date(2019, 3, 20).day) comment print(datetime.time(3,30,10)) #提供hour,minute,second,microsecond等属性 comment print(datetime.time(3,30,10).second) comment from datetime import time comment t...
#一、导入datetime包 # import datetime # print(datetime.date(2019, 3, 20)) # 提供year,month,day属性 # # print(datetime.date(2019, 3, 20).day) # print(datetime.time(3,30,10)) #提供hour,minute,second,microsecond等属性 # print(datetime.time(3,30,10).second) # from datetime import time # t=time(3,30,10) #等于import datetime时 t=datetim...
Python
zaydzuhri_stack_edu_python
import cv2 import numpy as np from copy import copy set alfa_slider = 0 set alfa_slider_max = 100 set top_slider = 0 set top_slider_max = 100 function on_trackbar_blend alfaslider begin global image1 imageTop alfa_slider set alfa_slider = alfaslider set alfa = decimal alfa_slider / alfa_slider_max set blended = call ad...
import cv2 import numpy as np from copy import copy alfa_slider = 0 alfa_slider_max = 100 top_slider = 0 top_slider_max = 100 def on_trackbar_blend(alfaslider): global image1, imageTop, alfa_slider alfa_slider = alfaslider alfa = float(alfa_slider/alfa_slider_max) blended = cv2.addWeighted(image1, al...
Python
zaydzuhri_stack_edu_python
import re set original_text = string life is too short set p = compile string [a-z]+ set m = search original_text print m comment 검색결과는 list로 반환해준다. set match_list = find all original_text print match_list for match_element in match_list begin print match_element end
import re original_text = 'life is too short' p = re.compile('[a-z]+') m = p.search(original_text) print(m) match_list = p.findall(original_text) # 검색결과는 list로 반환해준다. print(match_list) for match_element in match_list: print(match_element)
Python
zaydzuhri_stack_edu_python
string https://leetcode-cn.com/problems/clone-graph comment Definition for a Node. comment Definition for a Node. class Node extends object begin function __init__ self val=0 neighbors=none begin set val = val set neighbors = if expression neighbors is not none then neighbors else list end function function __repr__ s...
""" https://leetcode-cn.com/problems/clone-graph """ # Definition for a Node. # Definition for a Node. class Node(object): def __init__(self, val=0, neighbors=None): self.val = val self.neighbors = neighbors if neighbors is not None else [] def __repr__(self): return 'node[{0}]'.form...
Python
zaydzuhri_stack_edu_python
function pprint obj begin for argname in sorted list comprehension x for x in directory obj if not starts with x string __ begin comment Skip callables if has attribute get attribute obj argname string __call__ begin continue end print format string {} : {} argname get attribute obj argname end end function
def pprint(obj): for argname in sorted([x for x in dir(obj) if not x.startswith('__')]): # Skip callables if hasattr(getattr(obj, argname), '__call__'): continue print("{} : {}".format(argname, getattr(obj, argname)))
Python
nomic_cornstack_python_v1
function save_position self text position ignorable begin set ignore = dict for character in string + ignorable begin set ignore at character = none end set counter = 0 for character in text at slice : position : begin if character in ignore begin set counter = counter + 1 end end set position = position - counter ...
def save_position(self, text, position, ignorable): ignore = {} for character in ' \t\r\n' + ignorable: ignore[character] = None counter = 0 for character in text[:position]: if character in ignore: counter = counter + 1 self.positi...
Python
nomic_cornstack_python_v1
function rigid_body_constraints self begin set phi_1 = call constant_distance symbolic_coordinates - symbolic_coordinates length set phi_2 = call constant_distance symbolic_coordinates 1 set phi_3 = call constant_distance symbolic_coordinates 1 set phi_4 = call perpendicular symbolic_coordinates symbolic_coordinates se...
def rigid_body_constraints(self): phi_1 = constant_distance(self.r_i.symbolic_coordinates - self.r_j.symbolic_coordinates, self.length) phi_2 = constant_distance(self.u.symbolic_coordinates, 1) phi_3 = constant_distance(self.v.symbolic_coordinates, 1) ph...
Python
nomic_cornstack_python_v1
function __contains__ self key begin set tuple pred_not_ok prob = call contains_offensive_language key return pred_not_ok end function
def __contains__(self, key): pred_not_ok, prob = self.contains_offensive_language(key) return pred_not_ok
Python
nomic_cornstack_python_v1
comment def validate_pin(pin): comment return len(pin) in (4,6) and pin.isdigit() comment print(validate_pin(4565)) comment print(len(pin)) comment Global mutable state set current_number = 1 set accumulated_sum = 0 function sum_recursive begin global current_number global accumulated_sum comment Base case if current_n...
# def validate_pin(pin): # return len(pin) in (4,6) and pin.isdigit() # print(validate_pin(4565)) # print(len(pin)) # Global mutable state current_number = 1 accumulated_sum = 0 def sum_recursive(): global current_number global accumulated_sum # Base case if current_number == 11: return ac...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import sys , re comment xyz.coll set IN1 = open argv at 1 string r comment xyz.tandem set IN2 = open argv at 2 string r set OUT1 = open argv at 3 string w set OUT2 = open argv at 4 string w set dict1 = set set dict2 = set for eachline in IN1 begin if not starts with eachline string # begin ...
#!/usr/bin/env python import sys,re IN1=open(sys.argv[1],'r')#xyz.coll IN2=open(sys.argv[2],'r')#xyz.tandem OUT1=open(sys.argv[3],'w') OUT2=open(sys.argv[4],'w') dict1=set() dict2=set() for eachline in IN1: if not eachline.startswith("#"): split=eachline.strip().split() if split[2].startswith("Potri"): dic...
Python
zaydzuhri_stack_edu_python
comment cannot find CLR method function __init__ self *args begin pass end function
def __init__(self, *args): #cannot find CLR method pass
Python
nomic_cornstack_python_v1
function get_today begin from datetime import date return string today end function
def get_today(): from datetime import date return str(date.today())
Python
nomic_cornstack_python_v1
function colorplot2d ax x y z plotType=image axLabels=tuple string string string **kw begin set cmap = pop kw string cmap rcParams at string image.cmap comment first we need to check if our grid can be plotted nicely. if plotType in list image colormesh begin set x = as type x float set y = as type y float set z = a...
def colorplot2d(ax: Axes, x: Union[np.ndarray, np.ma.MaskedArray], y: Union[np.ndarray, np.ma.MaskedArray], z: Union[np.ndarray, np.ma.MaskedArray], plotType: PlotType = PlotType.image, axLabels: Tuple[Optional[str], Optional[str], Optional...
Python
nomic_cornstack_python_v1
function add x y begin string Return the sum of x and y. return x + y end function
def add(x, y): """Return the sum of x and y.""" return x + y
Python
jtatman_500k
from tkinter import * set window = call Tk title window string 예제 call geometry string 500x500+1200+300 set listBox = call Listbox window selectmode=string extended height=0 comment extended(다중선택) , single(한개만 선택) insert listBox 0 string 대한민국 insert listBox END string 만만세!! insert listBox END string 동해물과 insert listBox...
from tkinter import * window = Tk() window.title("예제") window.geometry("500x500+1200+300") listBox = Listbox(window, selectmode="extended", # extended(다중선택) , single(한개만 선택) height=0) listBox.insert(0, "대한민국") listBox.insert(END, "만만세!!") listBox.insert(END, "동해물과") listBox.insert...
Python
zaydzuhri_stack_edu_python
function load self file begin set parser = call PentasolParser set tuple reference move_list = parse parser file save string initial.png set reference = call pos_from_coords x y set history = list comment Replay game call reset for move in move_list begin call make_move move call pos_from_coords x y dir end end functi...
def load(self, file): parser = PentasolParser() reference, move_list = parser.parse(file) self.get_grid().get_PILImage(800, 800).save('initial.png') self.reference = self.pos_from_coords(reference.x, reference.y) self.history = [] # Replay game self.reset() ...
Python
nomic_cornstack_python_v1
import umap import feather import pandas as pd import matplotlib.pyplot as plt comment data = feather.read_dataframe("features/DAE.feather").values set train = call read_dataframe string data/input/tr_best.feather set test = call read_dataframe string data/input/te_best.feather del train at string Score train at string...
import umap import feather import pandas as pd import matplotlib.pyplot as plt #data = feather.read_dataframe("features/DAE.feather").values train = feather.read_dataframe("data/input/tr_best.feather") test = feather.read_dataframe("data/input/te_best.feather") del train["Score"],train["index"],test["index"],test["ID"]...
Python
zaydzuhri_stack_edu_python
function rmf_score flu_space access_variables begin comment access cols set prox_rmf = string res_units_rmf_from_within15_OpAuto set prox_vac_rmf = string vac_res_units_rmf_from_within15_OpAuto set prox_new_rmf = string rmf_res_units_in_last5_from_within15_OpAuto set prox_pers = string persons_to_within20_OpAuto commen...
def rmf_score(flu_space, access_variables): # access cols prox_rmf = 'res_units_rmf_from_within15_OpAuto' prox_vac_rmf = 'vac_res_units_rmf_from_within15_OpAuto' prox_new_rmf = 'rmf_res_units_in_last5_from_within15_OpAuto' prox_pers = 'persons_to_within20_OpAuto' # get projects projs = flu_...
Python
nomic_cornstack_python_v1
while is_running begin set value = input if value == string . begin break end set number = number + integer value set counter = counter + 1 end print number / counter
while is_running: value = input() if value == '.': break number += int(value) counter += 1 print(number / counter)
Python
zaydzuhri_stack_edu_python
import os import numpy as np from PIL import Image class HTML begin function __init__ self web_dir title begin set title = title set web_dir = web_dir set img_dir = join path web_dir string images if not exists path web_dir begin make directories web_dir end if not exists path img_dir begin make directories img_dir end...
import os import numpy as np from PIL import Image class HTML: def __init__(self, web_dir, title): self.title = title self.web_dir = web_dir self.img_dir = os.path.join(self.web_dir, 'images') if not os.path.exists(self.web_dir): os.makedirs(self.web_dir) if no...
Python
zaydzuhri_stack_edu_python
function load self filename offset begin string Loads HFS+ volume information try begin set offset = offset set fd = open filename string rb comment 1024 - temporary, need to find out actual volume header size seek fd offset + VOLUME_HEADER_OFFSET set data = read fd 1024 set vol_header = call VolumeHeader data close fd...
def load(self, filename, offset): """Loads HFS+ volume information""" try: self.offset = offset self.fd = open(filename, 'rb') # 1024 - temporary, need to find out actual volume header size self.fd.seek(self.offset + VOLUME_HEADER_OFFSET) data ...
Python
jtatman_500k
function get_htdocs_dirs self begin return list end function
def get_htdocs_dirs(self): return []
Python
nomic_cornstack_python_v1
function Qsasp self s a sp S=1 begin set s = to s device=device dtype=dtype set a = to a device=device dtype=dtype set T = shape at 0 assert shape at 0 == shape at 0 set ssp = call cat list s sp 0 set tuple Qssp logpq _ = call _Qs ssp S=S if device == device string cpu begin comment gather on cpu wants 64 bit integers ...
def Qsasp(self, s, a, sp, S=1): s = s.to(device=self.device, dtype=self.dtype) a = a.to(device=self.device, dtype=self.dtype) T = s.shape[0] assert s.shape[0] == sp.shape[0] ssp = t.cat([s, sp], 0) Qssp, logpq, _ = self._Qs(ssp, S=S) if a.device == t.device('cpu'...
Python
nomic_cornstack_python_v1
comment PROYECTO DE LA SEMANA 3 comment por > Leonardo Enrique Castillo comment castillo.leo@gmail.com comment Disposicion de leds comment 0a-----0b comment | | comment | | comment 0c--0d-0e comment | | comment | | comment 0f-----0g set num = list list 0 0 0 1 0 0 0 list 0 0 1 0 1 0 0 list 0 1 0 1 0 1 0 list 1 1 0 0 0 ...
# PROYECTO DE LA SEMANA 3 # por > Leonardo Enrique Castillo # castillo.leo@gmail.com # Disposicion de leds # 0a-----0b # | | # | | # 0c--0d-0e # | | # | | # 0f-----0g num = [ #a b c d e f g Leds [0, 0, 0, 1, 0, 0, 0], # 1 [0, 0, 1, 0, 1, 0, 0], # 2 [0, 1, 0, 1, 0, 1, 0], # 3 ...
Python
zaydzuhri_stack_edu_python
function grep self pattern prune=false field=none begin string Return all strings matching 'pattern' (a regex or callable) This is case-insensitive. If prune is true, return all items NOT matching the pattern. If field is specified, the match must occur in the specified whitespace-separated field. Examples:: a.grep( la...
def grep(self, pattern, prune = False, field = None): """ Return all strings matching 'pattern' (a regex or callable) This is case-insensitive. If prune is true, return all items NOT matching the pattern. If field is specified, the match must occur in the specified whitespace-s...
Python
jtatman_500k
import random print string This Is Dice Simulator By Python set x = string y while x == string y begin set Num = random integer 1 6 if Num == 1 begin print string ------- print string | | print string | O | print string | | print string ------- end if Num == 2 begin print string ------- print string | | print string |O...
import random print("This Is Dice Simulator By Python") x ="y" while x=="y": Num= random.randint(1,6) if Num==1: print("-------") print("| |") print("| O |") print("| |") print("-------") if Num==2: print("-------") print("| ...
Python
zaydzuhri_stack_edu_python
import logging warning string 警告!!! info string 确认信息!!
import logging logging.warning("警告!!!") logging.info("确认信息!!")
Python
zaydzuhri_stack_edu_python
comment Actividad 1 comment Escribamos un programa que nos permita crear con una lista de 6 números aleatorios entre 1 y 20, comment y luego creemos tres funciones que reciban la lista como parámetro de la siguiente forma: comment mayor(x) - Una función que imprima el número mayor valor de una lista x comment primos(x)...
#Actividad 1 #Escribamos un programa que nos permita crear con una lista de 6 números aleatorios entre 1 y 20, #y luego creemos tres funciones que reciban la lista como parámetro de la siguiente forma: # # mayor(x) - Una función que imprima el número mayor valor de una lista x # primos(x) - Una función que impr...
Python
zaydzuhri_stack_edu_python
from collections import defaultdict function main begin set N = integer input set A = list comprehension integer i for i in split input set S = 0 set Bl = list dictionary for a in A begin set S = S + 1 if get Bl at - 1 a begin if Bl at - 1 at a == a - 1 begin set S = S - a del Bl at slice - a + 1 : : end else begin a...
from collections import defaultdict def main(): N = int(input()) A = [ int(i) for i in input().split() ] S = 0 Bl = [dict()] for a in A: S += 1 if Bl[-1].get(a): if Bl[-1][a] == a-1: S -= a del Bl[-a+1:] else: ...
Python
zaydzuhri_stack_edu_python
function test_team_builder_config_product_size_materials_id_pdf_color_profile_get self begin pass end function
def test_team_builder_config_product_size_materials_id_pdf_color_profile_get(self): pass
Python
nomic_cornstack_python_v1
function convert_to_dataset obj group=string posterior coords=none dims=none begin string Convert a supported object to an xarray dataset. This function is idempotent, in that it will return xarray.Dataset functions unchanged. Raises `ValueError` if the desired group can not be extracted. Note this goes through a DataI...
def convert_to_dataset(obj, *, group="posterior", coords=None, dims=None): """Convert a supported object to an xarray dataset. This function is idempotent, in that it will return xarray.Dataset functions unchanged. Raises `ValueError` if the desired group can not be extracted. Note this goes through a...
Python
jtatman_500k
function testMonthlyPayrollTotals self begin call _setupMonthlyTotals set totals = rows at - 1 set work_total = call Decimal string 110.00 call assertEquals totals at string work_total work_total call assertEquals length totals at string billable 1 + 1 for entry in totals at string billable begin call assertEquals entr...
def testMonthlyPayrollTotals(self): self._setupMonthlyTotals() totals = self.rows[-1] work_total = Decimal('110.00') self.assertEquals(totals['work_total'], work_total) self.assertEquals(len(totals['billable']), 1 + 1) for entry in totals['billable']: self.a...
Python
nomic_cornstack_python_v1
comment Teste seu codigo aos poucos. comment Nao teste tudo no final, pois fica mais dificil de identificar erros. comment Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo. set num = integer input set num2 = integer input print num print num2 set quociente = num // num2 set resto = num % num2...
# Teste seu codigo aos poucos. # Nao teste tudo no final, pois fica mais dificil de identificar erros. # Nao se intimide com as mensagens de erro. Elas ajudam a corrigir seu codigo. num= int(input()) num2= int(input()) print(num) print(num2) quociente= num//num2 resto= num%num2 print(quociente) print(resto)
Python
zaydzuhri_stack_edu_python
from datetime import datetime as dt , time as ti import time as t function get_midnight begin set midnight = call combine today min set e = timestamp midnight set e = integer e return e end function function get_current_time begin set ts = time set ts = integer ts return ts end function function get_top_of_hour begin s...
from datetime import datetime as dt, time as ti import time as t def get_midnight(): midnight = dt.combine(dt.today(), ti.min) e = midnight.timestamp() e = int(e) return e def get_current_time(): ts = t.time() ts = int(ts) return ts def get_top_of_hour(): m = get_midnight() e = g...
Python
zaydzuhri_stack_edu_python
function decrPartyHealth self num begin for person in call generatePerson begin if not call deadPerson begin call decrHealth num end end end function
def decrPartyHealth (self, num) : for person in self.generatePerson () : if not person.deadPerson () : person.decrHealth (num)
Python
nomic_cornstack_python_v1
async function read self cached=none begin return dict name await call get_reading end function
async def read(self, cached: Optional[bool] = None) -> Dict[str, Reading]: return {self.name: await self._backend_or_cache(cached).get_reading()}
Python
nomic_cornstack_python_v1
class Account begin function __init__ self balance begin set balance = balance end function function getbalance self begin return balance end function function deposit self amt begin if amt < 0 begin return false end else begin set balance = balance + amt return true end end function function withdraw self amt begin if...
class Account(): def __init__(self,balance): self.balance = balance def getbalance(self): return self.balance def deposit(self,amt): if amt < 0: return False else: self.balance += amt return True def withdraw(self,amt): if s...
Python
zaydzuhri_stack_edu_python
comment This tallies bits in their significant digits class Solution begin function countBits self num begin set skip = 0 set prev_bit = 0 set bit = 1 set arr = list set numzeroes = 0 for i in range 32 begin set c = 0 set skip = skip + prev_bit set n = num - skip set r = n % bit * 2 if r >= bit begin set c = c + bit e...
# This tallies bits in their significant digits class Solution: def countBits(self, num: int) -> List[int]: skip = 0 prev_bit = 0 bit = 1 arr = [] numzeroes = 0 for i in range(32): c = 0 skip += prev_bit n = num - skip ...
Python
zaydzuhri_stack_edu_python
input string What's your name? print string Hello + input string What's your name?
input("What's your name?") print("Hello"+input("What's your name?"))
Python
zaydzuhri_stack_edu_python
class TreeNode begin function __init__ self x begin set val = x set left = none set right = none end function end class function minDepth self root begin if not root begin return 0 end set children = list left right comment if we're at leaf node if not any children begin return 1 end set min_depth = decimal string inf ...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def minDepth(self, root): if not root: return 0 children = [root.left, root.right] # if we're at leaf node if not any(children): return 1 min_depth = float('inf') ...
Python
zaydzuhri_stack_edu_python
function todb table dbo tablename schema=none commit=true create=false drop=false constraints=true metadata=none dialect=none sample=1000 begin string Load data into an existing database table via a DB-API 2.0 connection or cursor. Note that the database table will be truncated, i.e., all existing rows will be deleted ...
def todb(table, dbo, tablename, schema=None, commit=True, create=False, drop=False, constraints=True, metadata=None, dialect=None, sample=1000): """ Load data into an existing database table via a DB-API 2.0 connection or cursor. Note that the database table will be truncated, i.e., al...
Python
jtatman_500k
function ret z y begin return tuple z * y z + y / 2 end function set tot = call ret 10 5 print tot function primo x begin set div = 0 for i in range 1 x + 1 begin if x % i == 0 begin set div = div + 1 end end if div > 2 begin print x string não é primo! end else begin print x string é primo! end end function call primo...
def ret(z,y): return(z*y),(z+y)/2 tot=ret(10,5) print(tot) ######################################## def primo(x): div=0 for i in range(1,x+1): if x%i==0: div=div+1 if div>2: print(x,"não é primo!") else: print(x,"é primo!") primo(15) ############################...
Python
zaydzuhri_stack_edu_python
function normalizer tracks begin set result = list for track in tracks begin append result string %s - %s % tuple get track string Artist string get track string Name string end return result end function
def normalizer(tracks): result = [] for track in tracks: result.append('%s - %s' % (track.get('Artist', ''), track.get('Name', ''))) return result
Python
nomic_cornstack_python_v1
class DataTypeConverter begin function convert_str_to_int self input_str begin try begin return integer input_str end except ValueError begin return none end end function function convert_int_to_str self input_int begin return string input_int end function function convert_float_to_int self input_float begin return int...
class DataTypeConverter: def convert_str_to_int(self, input_str: str) -> int: try: return int(input_str) except ValueError: return None def convert_int_to_str(self, input_int: int) -> str: return str(input_int) def convert_float_to_int(self, input_float: flo...
Python
jtatman_500k
from django.test import TestCase from django.contrib.auth.models import User from derisk_app.models import Formula class FormulaTestCase extends TestCase begin function setUp self begin set test_user = call create email=string test@test.com comment formula with no functions call create created_by=test_user name=string ...
from django.test import TestCase from django.contrib.auth.models import User from derisk_app.models import Formula class FormulaTestCase(TestCase): def setUp(self): test_user = User.objects.create(email='test@test.com') # formula with no functions Formula.objects.create(created_by=test_u...
Python
zaydzuhri_stack_edu_python
from tree import tree_node as node from tree import tree_node from tree import tree_edge as egde from tree import tree from copy import deepcopy class specie extends tree_node begin function __init__ self r=none name=none theta=none begin call __init__ self set R = set set name = name set theta = theta if r begin set r...
from tree import tree_node as node from tree import tree_node from tree import tree_edge as egde from tree import tree from copy import deepcopy class specie(tree_node): def __init__(self, r = None, name = None, theta = None): node.__init__(self) self.R = set() self.name = name self.theta = theta if...
Python
zaydzuhri_stack_edu_python
function close_socket self begin close socket_listen end function
def close_socket(self): self.socket_listen.close()
Python
nomic_cornstack_python_v1
from pandas_datareader import data import pandas as pd import matplotlib.pyplot as plt import numpy as np import talib as ta import warnings simple filter string ignore function company_stock start end company_code begin comment select a datasorce properly. set df = call DataReader company_code string yahoo set df = df...
from pandas_datareader import data import pandas as pd import matplotlib.pyplot as plt import numpy as np import talib as ta import warnings warnings.simplefilter('ignore') def company_stock(start, end, company_code): #select a datasorce properly. df = data.DataReader(company_code, 'yahoo') df = df[(df.ind...
Python
zaydzuhri_stack_edu_python
comment Iterate through the list in reverse order for i in range length _list - 1 - 1 - 1 begin print _list at i end comment Output: comment 5 comment 4 comment 3 comment 2 comment 1
# Iterate through the list in reverse order for i in range(len(_list) - 1, -1, -1): print(_list[i]) # Output: # 5 # 4 # 3 # 2 # 1
Python
jtatman_500k
function test_background_colour self begin set expected = list 1 2 3 set actual = _background_colour assert equal expected actual end function
def test_background_colour(self): expected = [1, 2, 3] actual = self.n._background_colour self.assertEqual(expected, actual)
Python
nomic_cornstack_python_v1
comment 训练&保存模型 import gym import numpy as np comment 清理内存的 import gc import train import buffer comment 'CartPole-v0', 'MountainCar-v0', 'BipedalWalker-v2' set ENV = string CartPole-v0 set env = call make ENV comment 还原env的原始设置,env外包了一层防作弊层 set env = unwrapped set MAX_EPISODES = 401 set MAX_BUFFER = 10000 set S_DIM = ...
# 训练&保存模型 import gym import numpy as np import gc # 清理内存的 import train import buffer ENV = 'CartPole-v0' # 'CartPole-v0', 'MountainCar-v0', 'BipedalWalker-v2' env = gym.make(ENV) env = env.unwrapped # 还原env的原始设置,env外包了一层防作弊层 MAX_EPISODES = 401 MAX_BUFFER = 10000 S_DIM = env.observation_space.shape[0...
Python
zaydzuhri_stack_edu_python
function BatchGenerator iterator batch_size begin set batch = list for i in iterator begin append batch i if length batch >= batch_size begin yield batch set batch = list end end if batch begin comment if there was anything left in the final batch, yield it. yield batch end end function
def BatchGenerator(iterator, batch_size): batch = [] for i in iterator: batch.append(i) if len(batch) >= batch_size: yield batch batch = [] if batch: # if there was anything left in the final batch, yield it. yield batch
Python
nomic_cornstack_python_v1
function _filter_by_version self mapping parse_metadata version_checker begin set result = dictionary comprehension run : dict for run in mapping for tuple run tag_to_content in items mapping begin for tuple tag metadatum in items tag_to_content begin set md = call parse_metadata plugin_content if not call ok version ...
def _filter_by_version(self, mapping, parse_metadata, version_checker): result = {run: {} for run in mapping} for (run, tag_to_content) in mapping.items(): for (tag, metadatum) in tag_to_content.items(): md = parse_metadata(metadatum.plugin_content) if not ver...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Mon May 4 20:55:48 2020 import sys comment import numpy as np call setrecursionlimit 10 ^ 9 comment def input(): comment return sys.stdin.readline()[:-1] set mod = 10 ^ 9 + 7 comment N = int(input()) set tuple A B = map int split input if B % A == 0 begin print A + B end ...
# -*- coding: utf-8 -*- """ Created on Mon May 4 20:55:48 2020 """ import sys #import numpy as np sys.setrecursionlimit(10 ** 9) #def input(): # return sys.stdin.readline()[:-1] mod = 10**9+7 #N = int(input()) A, B = map(int,input().split()) if B % A == 0: print(A+B) else: print(B-A)
Python
zaydzuhri_stack_edu_python
from Reader import Reader from Greed.Algorithm import Algorithm from Profiler import Profiler class Process begin function __init__ self begin set reader = reader set profiler = call Profiler end function function execute self begin set source = call read_source while source begin call start_tracking set alg = call Alg...
from Reader import Reader from Greed.Algorithm import Algorithm from Profiler import Profiler class Process: def __init__(self): self.reader = Reader() self.profiler = Profiler() def execute(self): source = self.reader.read_source() while source: self.profiler.star...
Python
zaydzuhri_stack_edu_python
function do_target self target expr_form=string glob begin set target = target set expr_form = expr_form call update_prompt end function
def do_target(self, target, expr_form='glob'): self.target = target self.expr_form = expr_form self.update_prompt()
Python
nomic_cornstack_python_v1
function draw self axes fcolor ecolor alph begin set poly = call Polygon _V facecolor=fcolor edgecolor=ecolor alpha=alph call add_patch poly if _safety_region begin set poly_safe = call Polygon _V_safe facecolor=string none edgecolor=fcolor call add_patch poly_safe end end function
def draw(self, axes, fcolor, ecolor, alph): poly = matplotlib.patches.Polygon(self._V, facecolor=fcolor, edgecolor=ecolor, alpha=alph) axes.add_patch(poly) if self._safety_region: poly_safe = matplotlib.patches.Polygon(self._V_safe, facecolor='none', edgecolor=fcolor) axe...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment set working directory to current folder import os change directory directory name path absolute path path string sentiment-analysis.py import pandas as pd from nltk.stem.snowball import SnowballStemmer from nltk import word_tokenize function clean_lyrics_add_wordcounts artist_df be...
# -*- coding: utf-8 -*- # set working directory to current folder import os os.chdir(os.path.dirname(os.path.abspath('sentiment-analysis.py'))) import pandas as pd from nltk.stem.snowball import SnowballStemmer from nltk import word_tokenize def clean_lyrics_add_wordcounts(artist_df): # clean up lyrics. Remove ...
Python
zaydzuhri_stack_edu_python
function confirm text default=false abort=false prompt_suffix=string : show_default=true err=false begin string Prompts for confirmation (yes/no question). If the user aborts the input by sending a interrupt signal this function will catch it and raise a :exc:`Abort` exception. .. versionadded:: 4.0 Added the `err` par...
def confirm(text, default=False, abort=False, prompt_suffix=': ', show_default=True, err=False): """Prompts for confirmation (yes/no question). If the user aborts the input by sending a interrupt signal this function will catch it and raise a :exc:`Abort` exception. .. versionadded:: 4.0 ...
Python
jtatman_500k
from tkinter import * set w = call Tk comment advantage of text variable comment set variable is easier to remember comment easier to modify multiple labels at once set text = call StringVar master=w set label_1 = call Label w bd=1 relief=string solid padx=10 pady=10 font=tuple string Times 22 string bold textvariable=...
from tkinter import * w = Tk() # advantage of text variable ######################################### # set variable is easier to remember # easier to modify multiple labels at once text = StringVar(master=w) label_1 = Label(w, bd=1, relief='solid', padx=10, ...
Python
zaydzuhri_stack_edu_python
function add x y begin return tuple x + y x - y end function print add 2 1 set tuple add_result subtract_result = add 5 3 print add_result print subtract_result
def add(x, y): return x + y, x - y print (add(2, 1)) add_result, subtract_result = add(5, 3) print (add_result) print (subtract_result)
Python
zaydzuhri_stack_edu_python
function get_highlight_mask im threshold=0.99 dtype=float32 begin set binary_mask = call reduce_mean im axis=- 1 keepdims=true > threshold set mask = call cast binary_mask dtype return mask end function
def get_highlight_mask(im, threshold = 0.99, dtype = tf.float32): binary_mask = tf.reduce_mean(im, axis=-1, keepdims=True) > threshold mask = tf.cast(binary_mask, dtype) return mask
Python
nomic_cornstack_python_v1
function invert_r r begin set r_inv = zeros length r dtype=int set r_inv at r = array range length r return r_inv end function
def invert_r(r): r_inv = np.zeros(len(r), dtype=int) r_inv[r] = np.arange(len(r)) return r_inv
Python
nomic_cornstack_python_v1
async function stop_bridges self begin string Stop all sleep tasks to allow bridges to end. for task in sleep_tasks begin call cancel end for bridge in bridges begin call stop end end function
async def stop_bridges(self): """Stop all sleep tasks to allow bridges to end.""" for task in self.sleep_tasks: task.cancel() for bridge in self.bridges: bridge.stop()
Python
jtatman_500k
function solve board begin debug format string Called solve on board: {} board call propagate board if call is_solved begin return true end if not call is_consistent begin return false end info string Invoking back-track search comment There must be at least one tile with value UNKNOWN comment and multiple candidate va...
def solve(board: Board) -> bool: log.debug("Called solve on board:\n{}".format(board)) propagate(board) if board.is_solved(): return True if not board.is_consistent(): return False log.info("Invoking back-track search") # There must be at least one tile with value UNKNOWN # ...
Python
nomic_cornstack_python_v1
function _resolve_name name package level begin if not has attribute package string rindex begin raise call ValueError string 'package' not set to a string end set dot = length package for x in call xrange level 1 - 1 begin try begin set dot = call rindex string . 0 dot end except ValueError begin raise call ValueError...
def _resolve_name(name, package, level): if not hasattr(package, 'rindex'): raise ValueError("'package' not set to a string") dot = len(package) for x in xrange(level, 1, -1): try: dot = package.rindex('.', 0, dot) except ValueError: ...
Python
nomic_cornstack_python_v1
comment prolog compile command: comment swipl.exe -o myapp.exe -c load.pl --goal=main set fail_if_not_atom = true set print_sudoku_if_found = false set startletter = string A set endletter = string I set samebox = list list string A string B string C list string D string E string F list string G string H string I set i...
# prolog compile command: # swipl.exe -o myapp.exe -c load.pl --goal=main fail_if_not_atom = True print_sudoku_if_found = False startletter = 'A' endletter = 'I' samebox = [ ['A','B','C'], ['D','E','F'], ['G','H','I'] ] init = "%% init anfang\n" code = "%% code anfang\n" bound = "%% bound anfang\n" endcod...
Python
zaydzuhri_stack_edu_python
function _create_examples self lines set_type begin set examples = list set label_to_ids = dictionary comprehension k : v for tuple v k in enumerate call get_labels for tuple i line in enumerate lines begin if length line != 2 begin comment print(line) continue end comment if i == 0: comment continue set guid = string...
def _create_examples(self, lines, set_type): examples = [] label_to_ids = {k: v for v, k in enumerate(self.get_labels())} for (i, line) in enumerate(lines): if len(line) != 2: # print(line) continue # if i == 0: # co...
Python
nomic_cornstack_python_v1
comment coding:shift-jis import gzip import json import re set fname = string jawiki-country.json.gz function ext_UK begin with open fname string rt encoding=string utf-8 as data_file begin for line in data_file begin set data_json = loads line if data_json at string title == string CMX begin return data_json at string...
#coding:shift-jis import gzip import json import re fname = 'jawiki-country.json.gz' def ext_UK(): with gzip.open(fname, 'rt',encoding='utf-8') as data_file: for line in data_file: data_json = json.loads(line) if data_json['title'] == 'CMX': return d...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Tue Dec 17 15:07:00 2019 @author: Eirik Nordgård import numpy as np from matplotlib import cm from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import axes3d import seaborn as sns import time set call set_style string whitegrid call set_palette string Set2 ca...
# -*- coding: utf-8 -*- """ Created on Tue Dec 17 15:07:00 2019 @author: Eirik Nordgård """ import numpy as np from matplotlib import cm from matplotlib import pyplot as plt from mpl_toolkits.mplot3d import axes3d import seaborn as sns import time sns.set() sns.set_style("whitegrid") sns.set_palette("Set2") plt.rc('...
Python
zaydzuhri_stack_edu_python
string Name: Peter Solimine Course: CMPS 1500 Lab Section: Thursday 3:30 - 4:45pm Assignment: Lab 9 pr 0 Date: 04/17/2018 class Node begin function __init__ self data next=none begin set data = data set next = next end function end class function join head1 head2 begin if head1 == none and head2 == none begin return no...
''' Name: Peter Solimine Course: CMPS 1500 Lab Section: Thursday 3:30 - 4:45pm Assignment: Lab 9 pr 0 Date: 04/17/2018 ''' class Node: def __init__(self, data, next=None): self.data = data self.next = next def join(head1, head2): if head1 == None and head2 ...
Python
zaydzuhri_stack_edu_python
function parametertype self parameter begin comment split the paramter block line, and strip whitespace set tuple pname param = split parameter string : set pname = strip pname string set param = strip param string if pname in __listtype begin set param = call list_param pname param end else if pname in __strtype begin...
def parametertype(self, parameter): # split the paramter block line, and strip whitespace pname, param = parameter.split(':') pname = pname.strip(' ') param = param.strip(' ') if pname in self.__listtype: param = self.list_param(pname, param) elif pn...
Python
nomic_cornstack_python_v1
comment Diferença set a = integer input set b = integer input set c = integer input set d = integer input set dif = a * b - c * d print string DIFERENCA = %d % dif
#Diferença a = int(input()) b = int(input()) c = int(input()) d = int(input()) dif = a*b - c*d print("DIFERENCA = %d"%dif)
Python
zaydzuhri_stack_edu_python
function selectionSort alist begin string 选择排序 for fillslot in range length alist - 1 0 - 1 begin print alist set positionOfMax = 0 for location in range 1 fillslot + 1 begin if alist at location > alist at positionOfMax begin set positionOfMax = location end end set temp = alist at fillslot set alist at fillslot = ali...
def selectionSort(alist): """选择排序""" for fillslot in range(len(alist)-1, 0, -1): print(alist) positionOfMax = 0 for location in range(1, fillslot+1): if alist[location] > alist[positionOfMax]: positionOfMax = location temp = alist[f...
Python
zaydzuhri_stack_edu_python
function _log_decade_ticks ax min_log max_log ax_set_func num=none **kw_ticks begin if num is none begin set num = max_log - min_log + 1 end call ax_set_func call logspace min_log max_log base=10 num=num return call tickAxisFont ax=ax keyword kw_ticks end function
def _log_decade_ticks(ax,min_log,max_log,ax_set_func,num=None,**kw_ticks): if (num is None): num = max_log - min_log + 1 ax_set_func(np.logspace(min_log, max_log, base=10, num=num)) return tickAxisFont(ax=ax,**kw_ticks)
Python
nomic_cornstack_python_v1
function connect_subproc begin return call connect_subproc list executable string -u SERVER_FILE string -q string -m string stdio SlaveService end function
def connect_subproc(): return factory.connect_subproc([sys.executable, "-u", SERVER_FILE, "-q", "-m", "stdio"], SlaveService)
Python
nomic_cornstack_python_v1
for i in range 1 11 1 begin set NUM = integer input string Introduce un numero if NUM != 0 begin if - 1 ^ NUM > 0 begin set SUMPAR = SUMPAR + NUM set CUEPAR = CUEPAR + 1 set i = i + 1 end else begin set SUMIMP = SUMIMP + NUM set i = i + 1 end end end set PROPAR = SUMPAR / CUEPAR print string El promedio de numeros pare...
for i in range(1,11,1): NUM = int(input("Introduce un numero")) if NUM != 0: if ((-1) ** NUM)>0: SUMPAR+= NUM CUEPAR+= 1 i+= 1 else: SUMIMP+= NUM i+= 1 PROPAR = SUMPAR / CUEPAR print (f"El promedio de numeros pares {PROPAR} y la su...
Python
zaydzuhri_stack_edu_python
comment Daily Coding Problem # 14 comment The area of a circle is defined as πr^2. comment Estimate π to 3 decimal places using a Monte Carlo method. comment Hint: The basic equation of a circle is x2 + y2 = r2. comment Generate a bunch of number pairs from 0 - 1 (x, y coordinates) comment For each generated point, det...
# Daily Coding Problem # 14 # # The area of a circle is defined as πr^2. # Estimate π to 3 decimal places using a Monte Carlo method. # Hint: The basic equation of a circle is x2 + y2 = r2. # # Generate a bunch of number pairs from 0 - 1 (x, y coordinates) # For each generated point, determine if the point lies in the...
Python
zaydzuhri_stack_edu_python
import sys import pygame from alien import Alien from bullet import Bullet function checkAllEdge settings aliens begin for alien in aliens begin if call checkEdge begin call changeDirection settings aliens break end end end function function changeDirection settings aliens begin for alien in aliens begin set y = y + al...
import sys import pygame from alien import Alien from bullet import Bullet def checkAllEdge(settings, aliens): for alien in aliens: if alien.checkEdge(): changeDirection(settings, aliens) break def changeDirection(settings, aliens): for alien in aliens: alien.rect.y += ...
Python
zaydzuhri_stack_edu_python
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import emoji import string import csv import os function getFileSize nameFile begin return st_size end function set browser = call Chrome function loginInstagram url username password begin comment Masuk ke url. get browser url c...
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import emoji import string import csv import os def getFileSize(nameFile): return os.stat(nameFile).st_size browser = webdriver.Chrome() def loginInstagram(url, username, password): browser.get(url) #Masu...
Python
zaydzuhri_stack_edu_python
function create_mouse_grid self begin set grid = call QTableWidget call setRowCount grid_dim call setColumnCount grid_dim call setSizeAdjustPolicy AdjustToContents call hide call hide call connect on_click_grid_cell for y_index in range grid_dim begin for x_index in range grid_dim begin set blank_widget = call QTableWi...
def create_mouse_grid(self): grid = QTableWidget() grid.setRowCount(self.grid_dim) grid.setColumnCount(self.grid_dim) grid.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents) grid.horizontalHeader().hide() grid.verticalHeader().hide() grid.clicked.connect(se...
Python
nomic_cornstack_python_v1
function rk4 f x0 t **kwargs begin comment Pass in the function for dx/dt, the initial value, x0, and an array comment of times and return an array of x values for those times. comment track the current value of x set x = x0 comment Create an array of x values at all times set xlist = x set lasttime = t at 0 for time i...
def rk4(f, x0, t, **kwargs): # Pass in the function for dx/dt, the initial value, x0, and an array # of times and return an array of x values for those times. x = x0 # track the current value of x xlist = x # Create an array of x values at all times lasttime = t[0] for time in t[...
Python
nomic_cornstack_python_v1
function index_num_to_grid_loc index spatial_cols begin set tuple row_num col_num = call get_row_col_number index spatial_cols set image_num_str = string row_num + string col_num return image_num_str end function
def index_num_to_grid_loc(index, spatial_cols): row_num, col_num = get_row_col_number(index, spatial_cols) image_num_str = str(row_num) + str(col_num) return image_num_str
Python
nomic_cornstack_python_v1
function test_missing_project self begin set task = call Task dict string name string test ; string id 1 ; string stage_id list 1 string name ; string date_deadline false ; string date_start false ; string date_end false ; string partial_messages list dict string date string 2018-10-21 12:00:00 ; string kanban_state st...
def test_missing_project(self): task = Task({ 'name': 'test', 'id': 1, 'stage_id' : [1, 'name'], 'date_deadline': False, 'date_start': False, 'date_end': False, 'partial_messages': [{'date':'2018-10-21 12:00:00'}], '...
Python
nomic_cornstack_python_v1
import unittest from non_terminal import NonTerminal class TestNonTerminal extends TestCase begin function test_init self begin set non_terminal = call NonTerminal string TEST assert equal name string TEST end function function test_equals self begin set non_terminal1 = call NonTerminal string TEST set non_terminal2 = ...
import unittest from non_terminal import NonTerminal class TestNonTerminal(unittest.TestCase): def test_init(self): non_terminal = NonTerminal("TEST") self.assertEqual(non_terminal.name, "TEST") def test_equals(self): non_terminal1 = NonTerminal("TEST") non_terminal2 = NonTerm...
Python
zaydzuhri_stack_edu_python