code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function __getitem__ self item begin return get self sighash=item end function
def __getitem__(self, item): return self.get(sighash=item)
Python
nomic_cornstack_python_v1
with open filename string w as file_object begin write file_object f_name + string end with open filename string a as file_object begin write file_object l_name + string end
with open(filename, 'w') as file_object: file_object.write (f_name + ' ') with open(filename,'a') as file_object: file_object.write (l_name + ' ')
Python
zaydzuhri_stack_edu_python
function d_ff request begin return param end function
def d_ff(request) -> int: return request.param
Python
nomic_cornstack_python_v1
function __init__ self parent begin call __init__ self parent set editors = list set filenames = list set tabwidget = none set menu_actions = none set layout = call QVBoxLayout set tabwidget = call Tabs self menu_actions call connect refresh call connect move_tab if platform == string darwin begin set tab_container =...
def __init__(self, parent): QWidget.__init__(self, parent) self.editors = [] self.filenames = [] self.tabwidget = None self.menu_actions = None layout = QVBoxLayout() self.tabwidget = Tabs(self, self.menu_actions) self.tabwidget.currentChanged.connect(s...
Python
nomic_cornstack_python_v1
function DeviceFirstOccurrence self **kwargs begin return call api_request call _get_method_fullname string DeviceFirstOccurrence kwargs end function
def DeviceFirstOccurrence(self, **kwargs): return self.api_request(self._get_method_fullname("DeviceFirstOccurrence"), kwargs)
Python
nomic_cornstack_python_v1
function __init__ self *args **kwds begin if args or kwds begin call __init__ *args keyword kwds comment message fields cannot be None, assign default values for those that are if mirror is none begin set mirror = false end if dynamical is none begin set dynamical = false end if ballSpecial is none begin set ballSpecia...
def __init__(self, *args, **kwds): if args or kwds: super(BikeRequest, self).__init__(*args, **kwds) #message fields cannot be None, assign default values for those that are if self.mirror is None: self.mirror = False if self.dynamical is None: self.dynamical = False if...
Python
nomic_cornstack_python_v1
function update_parties self *parties begin for party in parties begin set _route_table at string route_table at call get_id = call to_entry_point end end function
def update_parties(self, *parties) -> None: for party in parties: self._route_table['route_table'][party.get_id()] = party.to_entry_point( )
Python
nomic_cornstack_python_v1
import numpy as np from sklearn.feature_extraction.text import CountVectorizer function similarity_score sentence1 sentence2 begin string Computes the similarity between two sentences using cosine similarity. comment Vectorize the sentences set vectorizer = call CountVectorizer stop_words=string english fit transform v...
import numpy as np from sklearn.feature_extraction.text import CountVectorizer def similarity_score(sentence1, sentence2): """Computes the similarity between two sentences using cosine similarity.""" # Vectorize the sentences vectorizer = CountVectorizer(stop_words='english') vectorizer.fit_transform([...
Python
iamtarun_python_18k_alpaca
function add_word_count word word_counts begin try begin set word_counts at word = word_counts at word + 1 end except KeyError begin set word_counts at word = 1 end end function
def add_word_count(word, word_counts): try: word_counts[word] += 1 except KeyError: word_counts[word] = 1
Python
nomic_cornstack_python_v1
function __insert_partial_model_in_model_queus self address partial_model begin with __aggregation_model_queues_lock begin if aggregation_id not in __previous_aggregation_ids begin if __aggregation_model_queues is none begin append __partial_model_queue_waiting_list tuple address partial_model end else if __aggregation...
def __insert_partial_model_in_model_queus(self, address, partial_model): with self.__aggregation_model_queues_lock: if partial_model.aggregation_id not in self.__previous_aggregation_ids: if self.__aggregation_model_queues is None: self.__partial_model_queue_waiti...
Python
nomic_cornstack_python_v1
import uuid import tempfile import os import torch import math from tqdm import tqdm from import plots set temp = call gettempdir class GanTrainer begin string Trains a WGAN with different discriminator regularization strategies Args: batch_size (int): batch size data (callable): real data distribution. noise (callabl...
import uuid import tempfile import os import torch import math from tqdm import tqdm from . import plots temp = tempfile.gettempdir() class GanTrainer(): """ Trains a WGAN with different discriminator regularization strategies Args: batch_size (int): batch size data (callable): real dat...
Python
zaydzuhri_stack_edu_python
from keras.models import Model , load_model from keras.layers import Dense , LSTM , Concatenate , Input , Dropout from countercoup.shared.structure import Structure class EnhancedBasic extends Structure begin string Basic enhanced structure, same as Enhanced structure but without LSTM cells decorator staticmethod funct...
from keras.models import Model, load_model from keras.layers import Dense, LSTM, Concatenate, Input, Dropout from countercoup.shared.structure import Structure class EnhancedBasic(Structure): """Basic enhanced structure, same as Enhanced structure but without LSTM cells""" @staticmethod def define_struct...
Python
zaydzuhri_stack_edu_python
function on_epoch_start self begin for callback in callbacks begin call on_epoch_start self call get_model end end function
def on_epoch_start(self): for callback in self.callbacks: callback.on_epoch_start(self, self.get_model())
Python
nomic_cornstack_python_v1
function set_crc self begin set str_hkey = string { nom } _ { dateOrigine } _ { dateUpdate } set crc = hex digest sha1 encode str_hkey end function
def set_crc(self): str_hkey=f"{self.nom}_{self.dateOrigine}_{self.dateUpdate}" self.crc=hashlib.sha1(str_hkey.encode()).hexdigest()
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment @Time : 2019/4/17 15:52 comment @Author : Lwq comment @File : 2-2.py comment @Software: PyCharm string 如何统计列表中的元素频度 from collections import Counter from random import randint string 先把列表转换为字典(k是数据,V是频次),然后排序 set data = list comprehension random integer 0 10 for _ in range 30 print ...
# -*- coding: utf-8 -*- # @Time : 2019/4/17 15:52 # @Author : Lwq # @File : 2-2.py # @Software: PyCharm """ 如何统计列表中的元素频度 """ from collections import Counter from random import randint ''' 先把列表转换为字典(k是数据,V是频次),然后排序 ''' data = [randint(0, 10) for _ in range(30)] print('data:', data) l = dict.fromkeys(data, 0) for...
Python
zaydzuhri_stack_edu_python
function all_webhooks self trans **kwd begin return list comprehension call to_dict for webhook in webhooks end function
def all_webhooks(self, trans, **kwd): return [ webhook.to_dict() for webhook in self.app.webhooks_registry.webhooks ]
Python
nomic_cornstack_python_v1
function item_pubdate self item begin return submit_date end function
def item_pubdate(self, item): return item.submit_date
Python
nomic_cornstack_python_v1
function approx_standard_normal_cdf x begin return 0.5 * 1.0 + tanh square root 2.0 / pi * x + 0.044715 * power x 3 end function
def approx_standard_normal_cdf(x): return 0.5 * (1.0 + torch.tanh(np.sqrt(2.0 / np.pi) * (x + 0.044715 * torch.pow(x, 3))))
Python
nomic_cornstack_python_v1
for i in range n begin if i % 2 == 0 begin set ans = ans + A at i end else begin set ans = ans - A at i end end print ans
for i in range(n): if i % 2 == 0: ans += A[i] else: ans -= A[i] print(ans)
Python
zaydzuhri_stack_edu_python
function create_oracle_connection begin try begin set property_file_contents = call collect_property_file_contents string config.ini string ORACLE set conn = call open_oracle_connection property_file_contents return conn end except Exception as e begin print string ERROR: Unable to connect to ORACLE account. Will be un...
def create_oracle_connection(): try: property_file_contents = collect_property_file_contents('config.ini', 'ORACLE') conn = open_oracle_connection(property_file_contents) return conn except Exception as e: print('ERROR: Unable to connect to ORACLE account. Will be unable ...
Python
nomic_cornstack_python_v1
function breadth_first_search start_state begin comment list of paths through the state space, represented as (move, state) pairs. set frontier = list list tuple string start start_state comment set of states we've already visited set visited = set set i = 0 while frontier begin comment consider the first path in the f...
def breadth_first_search(start_state): frontier = [[('start', start_state)]] # list of paths through the state space, represented as (move, state) pairs. visited = set() # set of states we've already visited i = 0 while frontier: path = frontier.pop(0) # consider the first path in the frontier,...
Python
nomic_cornstack_python_v1
function gen_indices_with_replacement self dataset dataset_size min max number_of_subsets begin set indices = list for i in range number_of_subsets begin set subset_size = random integer min max append indices list comprehension random integer 0 dataset_size for j in range subset_size end return indices end function
def gen_indices_with_replacement(self, dataset, dataset_size: int, min: int, max: int, number_of_subsets: int): indices = [] for i in range(number_of_subsets): subset_size = random.randint(min, max) indices.append([random.randint(0,dataset_size) for j in range(subset_size)]) return indices
Python
nomic_cornstack_python_v1
from random import randrange set count = 0 while true begin set x = call randrange - 100 100 if expression x is 50 then print x else print x end=string , set count = count + 1 if x == 50 begin break end end print string Count = count
from random import randrange count = 0 while True: x = randrange(-100, 100) print(x) if x is 50 else print(x, end=',') count += 1 if x == 50: break print('Count =', count)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- from inspect import signature from functools import wraps function typeassert *ty_args **ty_kwargs begin function decorate func begin if not __debug__ begin return func end set sig = signature func set bound_tyes = arguments decorator wraps func function wrappe...
#!/usr/bin/env python # -*- coding: utf-8 -*- from inspect import signature from functools import wraps def typeassert(*ty_args, **ty_kwargs): def decorate(func): if not __debug__: return func sig = signature(func) bound_tyes = sig.bind_partial(*ty_args, **ty_kwargs).arguments ...
Python
zaydzuhri_stack_edu_python
function split_bucket_university_course current_bucket_university_course begin set course_separator_delimiter = list string computer string artificial string cyber string network string data string machine for delimiter in course_separator_delimiter begin set separated_list = split current_bucket_university_course deli...
def split_bucket_university_course(current_bucket_university_course): course_separator_delimiter = ['computer', 'artificial', 'cyber', 'network', 'data', 'machine'] for delimiter in course_separator_delimiter: separated_list = current_bucket_university_course.split(delimiter,1) if len(se...
Python
nomic_cornstack_python_v1
string Solution to https://leetcode.com/problems/product-of-array-except-self/ This problem was asked by Uber. Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, ...
""" Solution to https://leetcode.com/problems/product-of-array-except-self/ This problem was asked by Uber. Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. For example, if our input was [1, 2, ...
Python
zaydzuhri_stack_edu_python
function strip_foxid_attribute content begin return sub FOXID_REGEX string content end function
def strip_foxid_attribute(content: str) -> str: return re.sub(FOXID_REGEX, "", content)
Python
nomic_cornstack_python_v1
function InfoString self message begin return HEADER + string [ -INFO-] + ENDC + message end function
def InfoString(self, message): return self.HEADER + "[ -INFO-]" + self.ENDC + message
Python
nomic_cornstack_python_v1
function finalize self begin comment type: () -> bytes if finished begin raise call RuntimeError string pmac: already finished end if position == SIZE begin call xor_in_place buffer call xor_in_place l_inv end else begin for i in range position begin set data at i = data at i ? data at i end set data at position = data...
def finalize(self): # type: () -> bytes if self.finished: raise RuntimeError("pmac: already finished") if self.position == block.SIZE: self.digest.xor_in_place(self.buffer) self.digest.xor_in_place(self.l_inv) else: for i in range(self.pos...
Python
nomic_cornstack_python_v1
function sizeOver self begin return _size + 1 >= _capacity * _limit end function
def sizeOver(self): return (self._size+1) >= self._capacity * self._limit
Python
nomic_cornstack_python_v1
import nltk import os from nltk.collocations import * import plotly.graph_objects as go import tqdm function bi_grams token_list begin set bgrams = call bigrams token_list comment compute frequency distribution for all the bigrams in the text set fdist = call FreqDist bgrams set bigram_fq = call most_common set bigram_...
import nltk import os from nltk.collocations import * import plotly.graph_objects as go import tqdm def bi_grams(token_list): bgrams = nltk.bigrams(token_list) # compute frequency distribution for all the bigrams in the text fdist = nltk.FreqDist(bgrams) bigram_fq = fdist.most_common() bigram_fre...
Python
zaydzuhri_stack_edu_python
function acl_list consul_url=none token=none **kwargs begin string List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list set ret = dict set data = dict if not consul_url begin set consul_url = call _get_config if not consul_url ...
def acl_list(consul_url=None, token=None, **kwargs): ''' List the ACL tokens. :param consul_url: The Consul server URL. :return: List of ACLs CLI Example: .. code-block:: bash salt '*' consul.acl_list ''' ret = {} data = {} if not consul_url: consul_url = _ge...
Python
jtatman_500k
function getMicroAODHLTFilter datasetName options begin for tuple dset analysisType in items options at string TriggerPaths begin set hlt_paths = list for an in analysisType begin extend hlt_paths list comprehension string trg for trg in options at string TriggerPaths at dset at an end set triggerConditions = call vst...
def getMicroAODHLTFilter(datasetName, options): for dset, analysisType in options["TriggerPaths"].items(): hlt_paths = [] for an in analysisType: hlt_paths.extend( [str(trg) for trg in options["TriggerPaths"][dset][an]] ) triggerConditions = cms.vstring(hlt_paths)
Python
nomic_cornstack_python_v1
function run_touch self begin comment Alle zukünftigen Tageskategorien touchen set day = time delta days=1 set start = now for _ in range 14 begin set c = call Category site format string Kategorie:Wikipedia:Dateiüberprüfung ({}) string format time start string %Y-%m-%d call touch c set start = start - day end end func...
def run_touch(self): # Alle zukünftigen Tageskategorien touchen day = timedelta(days=1) start = datetime.now() for _ in range(14): c = pywikibot.Category(self.site, 'Kategorie:Wikipedia:Dateiüberprüfung ({})' ...
Python
nomic_cornstack_python_v1
import torch.nn as nn import torch import torch.optim as optim import time import math import numpy as np from torch.utils.data import Dataset , DataLoader comment Ignore warnings import warnings filter warnings string ignore import sys comment insert at 1, 0 is the script path (or '' in REPL) insert path 1 string /Use...
import torch.nn as nn import torch import torch.optim as optim import time import math import numpy as np from torch.utils.data import Dataset, DataLoader # Ignore warnings import warnings warnings.filterwarnings("ignore") import sys # insert at 1, 0 is the script path (or '' in REPL) sys.path.insert(1, '/Users/kehuiy...
Python
zaydzuhri_stack_edu_python
function add_image_contrast username image time begin set user = first call raw dict string _id username append image_contrast image append contrast_time time set contrast_times = contrast_times + 1 save return contrast_times end function
def add_image_contrast(username, image, time): user = models.User.objects.raw({"_id": username}).first() user.image_contrast.append(image) user.contrast_time.append(time) user.contrast_times += 1 user.save() return user.contrast_times
Python
nomic_cornstack_python_v1
function gensalt log_rounds=12 begin return call _encode_salt call urandom 16 min max log_rounds 4 31 end function
def gensalt(log_rounds=12): return _encode_salt(os.urandom(16), min(max(log_rounds, 4), 31))
Python
nomic_cornstack_python_v1
comment Given comment an comment array comment A comment of comment N comment integers.Your comment task is to comment write comment a comment program comment to comment find comment the comment maximum comment value comment of ∑arr[i] * i, where comment i = 0, 1, 2,…., n – 1. comment You comment are comment allowed co...
# Given # an # array # A # of # N # integers.Your # task is to # write # a # program # to # find # the # maximum # value # of ∑arr[i] * i, where # i = 0, 1, 2,…., n – 1. # You # are # allowed # to # rearrange # the # elements # of # the # array. # Note: Since # output # could # be # larg...
Python
zaydzuhri_stack_edu_python
function render slug=string begin if slug begin call _render_graphics list string %s/%s % tuple GRAPHICS_PATH slug end else begin comment save_fallback_image(slug) # TODO call _render_graphics glob string %s/* % GRAPHICS_PATH end end function
def render(slug=''): if slug: _render_graphics(['%s/%s' % (app_config.GRAPHICS_PATH, slug)]) # save_fallback_image(slug) # TODO else: _render_graphics(glob('%s/*' % app_config.GRAPHICS_PATH))
Python
nomic_cornstack_python_v1
comment pragma: no cover function shutdown signum frame begin info string Shutting down exit 0 end function
def shutdown(signum, frame): # pragma: no cover logging.info("Shutting down") sys.exit(0)
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sun Oct 29 20:11:03 2017 @author: PeaceDove comment monitor.py import urllib from xml.etree.cElementTree import parse set candidates = list string 1866 string 1383 string 4367 set daves_lat = 41.980262 function distance lat1 lat2 begin string Return distance in miles betw...
# -*- coding: utf-8 -*- """ Created on Sun Oct 29 20:11:03 2017 @author: PeaceDove """ # monitor.py import urllib from xml.etree.cElementTree import parse candidates = ['1866', '1383', '4367'] daves_lat =41.980262 def distance(lat1, lat2): 'Return distance in miles between two lats' return 69 * abs(lat1 -...
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import numpy as np import seaborn as sns import pandas as pd comment Dataset: set MATLAB = call DataFrame dict string Linguagem de Programação repeat string MATLAB 13 ; string Quantidade de Palavras tuple 463 698 39 446 688 443 446 446 450 363 448 443 461 set Julia = call DataFrame dict ...
import matplotlib.pyplot as plt import numpy as np import seaborn as sns import pandas as pd # Dataset: MATLAB = pd.DataFrame({ 'Linguagem de Programação' : np.repeat('MATLAB', 13), 'Quantidade de Palavras': (463, 698, 39, 446, 688, 443, 446, 446, 450, 363, 448, 443, 461) }) Julia = pd.DataFrame({ 'Linguagem de Progr...
Python
zaydzuhri_stack_edu_python
import numpy as np import cv2 as cv import matplotlib.pyplot as plt function center_crop img new_h new_w begin set tuple old_h old_w = shape at slice : 2 : set off_w = old_w - new_w // 2 set off_h = old_h - new_h // 2 return img at tuple slice off_h : off_h + new_h : slice off_w : off_w + new_w : slice : : end f...
import numpy as np import cv2 as cv import matplotlib.pyplot as plt def center_crop(img, new_h, new_w): old_h, old_w = img.shape[:2] off_w = (old_w - new_w) // 2 off_h = (old_h - new_h) // 2 return img[off_h:off_h+new_h, off_w:off_w+new_w, :] def find_edges(img): if len(img.shape) >...
Python
zaydzuhri_stack_edu_python
comment Entrada set real = decimal input string Digite o valor em real: comment Processamento set desconto = real * 70 / 100 comment Saída print format string 70% de R${:.2f} é: R${:.2f} real desconto
#Entrada real = float(input("Digite o valor em real: ")) #Processamento desconto = real*70/100 #Saída print("70% de R${:.2f} é: R${:.2f}".format(real,desconto))
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment template.py comment ----------------------------------------------------------------------------- comment template comment ----------------------------------------------------------------------------- function template input_data begin set output = input_data return output end funct...
#!/usr/bin/env python # template.py # ----------------------------------------------------------------------------- # template # ----------------------------------------------------------------------------- def template(input_data): output = input_data return output if __name__ == "__main__": ...
Python
zaydzuhri_stack_edu_python
import requests comment UA 伪装:将对应的User-Agent封装到一个字典里 set headers = dict string User-agent string Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36 set url = string http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword comment 处理url携带的参数:封装到...
import requests # UA 伪装:将对应的User-Agent封装到一个字典里 headers={ 'User-agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36' } url='http://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx?op=keyword' #处理url携带的参数:封装到字典中 kw=input('enter a word:') param={...
Python
zaydzuhri_stack_edu_python
function crier_ordres self personnage begin set direction = direction if direction < 23 or direction > 337 begin set nom_dir = string l'est end else if direction < 67 begin set nom_dir = string le sud-est end else if direction < 112 begin set nom_dir = string le sud end else if direction < 157 begin set nom_dir = strin...
def crier_ordres(self, personnage): direction = self.direction if direction < 23 or direction > 337: nom_dir = "l'est" elif direction < 67: nom_dir = "le sud-est" elif direction < 112: nom_dir = "le sud" elif direction < 157: nom_di...
Python
nomic_cornstack_python_v1
import serial set lora = call Serial string /dev/ttyACM1 115200 timeout=2.0 set Arduino = call Serial string /dev/ttyACM2 9600 timeout=2.0 print string Start while true begin set comando = read line Arduino set mensaje = string AT+SEND + comando + string print mensaje write lora encode mensaje end set lora = close con...
import serial lora = serial.Serial('/dev/ttyACM1',115200,timeout=2.0) Arduino = serial.Serial ('/dev/ttyACM2',9600,timeout=2.0) print ("Start") while True: comando = Arduino.readline() mensaje = "AT+SEND "+comando+"\r" print (mensaje) lora.write(mensaje.encode()) lora = connection.close() Arduino = connection.c...
Python
zaydzuhri_stack_edu_python
function Evaluator *args begin function helper holding begin set points = 0 for tuple rank value in zip RANKS list args + list 0 * length RANKS - length args begin set points = points + count holding rank * value end return points end function return helper end function
def Evaluator(*args): def helper(holding): points = 0 for (rank, value) in zip(RANKS, list(args) + [0]*(len(RANKS)-len(args))): points += holding.count(rank)*value return points return helper
Python
nomic_cornstack_python_v1
import RPi.GPIO as GPIO import time set servoPIN = 17 call setmode BCM setup GPIO servoPIN OUT set p = call PWM servoPIN 50 start p 2.5
import RPi.GPIO as GPIO import time servoPIN=17 GPIO.setmode(GPIO.BCM) GPIO.setup(servoPIN, GPIO.OUT) p = GPIO.PWM(servoPIN, 50) p.start(2.5)
Python
zaydzuhri_stack_edu_python
import socket function Main begin set host = string 127.0.0.1 set port = 5000 set s = call socket call connect tuple host port set filename = call raw_input string Masukkan nama file = if filename != string q begin call send filename set data = call recv 1024 if data at slice : 6 : == string EXISTS begin set size = c...
import socket def Main(): host = '127.0.0.1' port = 5000 s = socket.socket() s.connect((host, port)) filename = raw_input("Masukkan nama file = ") if filename != 'q': s.send(filename) data = s.recv(1024) if data[:6] == 'EXISTS': size = long(data[6:]) ...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt from Task3_HelperFunctions import featureFunction function computeRMSE yPred y begin string Returns the RMSE between the target calculated with input x and weights and the true value of y. The used formulas are shown as comments in the code set RMSE = 0 for tuple i yi ...
import numpy as np import matplotlib.pyplot as plt from Task3_HelperFunctions import featureFunction def computeRMSE(yPred: np.ndarray, y: np.ndarray) -> float: """Returns the RMSE between the target calculated with input x and weights and the true value of y. The used formulas are shown as comments in the co...
Python
zaydzuhri_stack_edu_python
function categorize_as_vendor_payment self transaction_id vendor_payment begin set url = base_url + string uncategorized/ + transaction_id + string /categorize/vendorpayments set json_object = dumps to json vendor_payment set data = dict string JSONString json_object set resp = post url details headers data return call...
def categorize_as_vendor_payment(self, transaction_id, vendor_payment): url = base_url + 'uncategorized/' + transaction_id + \ '/categorize/vendorpayments' json_object = dumps(vendor_payment.to_json()) data = { 'JSONString': json_object } resp = zo...
Python
nomic_cornstack_python_v1
import json from urllib.request import urlopen with url open string https://jsonplaceholder.typicode.com/posts as response begin set source = read response end set data = loads source for d in data begin print d at string userId print d at string id print d at string title print d at string body print end comment print...
import json from urllib.request import urlopen with urlopen("https://jsonplaceholder.typicode.com/posts") as response: source = response.read() data = json.loads(source) for d in data: print(d['userId']) print(d['id']) print(d['title']) print(d['body']) print() # print(json.dumps(data, inden...
Python
zaydzuhri_stack_edu_python
from collections import deque set T = integer input function calc x op begin if op == string D begin return x * 2 % 10000 end else if op == string S begin if x == 0 begin return 9999 end return x - 1 end else if op == string L begin return x % 1000 * 10 + x // 1000 end else begin return x % 10 * 1000 + x // 10 end end ...
from collections import deque T = int(input()) def calc(x, op): if op == 'D': return (x*2)%10000 elif op =='S': if x == 0: return 9999 return x-1 elif op == 'L': return (x%1000)*10+x//1000 else: return (x%10)*1000+x//10 for _ in range(T): a, b = map(int, inpu...
Python
zaydzuhri_stack_edu_python
function claim_device self user_id device_id begin if user_id is none begin call log_error __name__ + string Unexpected empty object: user_id return false end if device_id is none begin call log_error __name__ + string Unexpected empty object: device_id return false end try begin set user_id_obj = call ObjectId user_id...
def claim_device(self, user_id, device_id): if user_id is None: self.log_error(MongoDatabase.claim_device.__name__ + "Unexpected empty object: user_id") return False if device_id is None: self.log_error(MongoDatabase.claim_device.__name__ + "Unexpected empty object: d...
Python
nomic_cornstack_python_v1
function load_yaml_config self begin comment LOG.info('Loading _Config - Version:{}'.format(__version__)) try begin set l_node = call read_yaml CONFIG_FILE_NAME end except any begin set Buttons = none return none end try begin set l_yaml = Yaml at string Buttons end except any begin warn string The buttons.yaml file do...
def load_yaml_config(self): # LOG.info('Loading _Config - Version:{}'.format(__version__)) try: l_node = config_tools.Yaml(self.m_pyhouse_obj).read_yaml(CONFIG_FILE_NAME) except: self.m_pyhouse_obj.House.Lighting.Buttons = None return None try: ...
Python
nomic_cornstack_python_v1
function get_intent data begin global name global mailto global mailcontent set m = lower data at string message comment If the intent is about name i.e the first input by the user. if data at string key == string name begin set name = m return string next end else comment If the user answered to the question ( enter t...
def get_intent(data): global name global mailto global mailcontent m=data['message'].lower() ## If the intent is about name i.e the first input by the user. if data['key'] =="name": name=m return "next" ## If the user answered to the question ( enter the mail ID ) ...
Python
zaydzuhri_stack_edu_python
function transformer_prepare_encoder inputs hparams features=none begin set ishape_static = call as_list set encoder_input = inputs comment Usual case - not a packed dataset. set encoder_padding = call embedding_to_padding encoder_input set ignore_padding = call attention_bias_ignore_padding encoder_padding set encoder...
def transformer_prepare_encoder(inputs, hparams, features=None): ishape_static = inputs.shape.as_list() encoder_input = inputs # Usual case - not a packed dataset. encoder_padding = common_attention.embedding_to_padding(encoder_input) ignore_padding = common_attention.attention_bias_ignore_padding(...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment -*-coding:utf-8 -*- from sklearn import neighbors import numpy as np import matplotlib.pyplot as plt function draw_training_points figure begin clear figure title plt string k-NN (k = + string k + string ) x label string X Axis y label string Y Axis scatter call gca x1 y1 c=string b mar...
#!/usr/bin/python # -*-coding:utf-8 -*- from sklearn import neighbors import numpy as np import matplotlib.pyplot as plt def draw_training_points(figure): figure.clear() plt.title('k-NN (k = ' + str(k) + ')') plt.xlabel('X Axis') plt.ylabel('Y Axis') figure.gca().scatter(x1, y1, c='b', marker='s...
Python
zaydzuhri_stack_edu_python
function cu_qoo10_product self result begin set order_lines = list set order_line = result at string data at string Order comment for order_line in product_list: if order_line begin set name = order_line at string itemTitle set name = strip encode name string utf8 set name = replace string name string \ string set nam...
def cu_qoo10_product(self, result): order_lines = [] order_line = result['data']['Order'] # for order_line in product_list: if order_line: name = order_line['itemTitle'] name = name.encode('utf8').strip() name = str(name).replace("\\", '') ...
Python
nomic_cornstack_python_v1
function function begin set a = split input if a at 0 == string stop begin print string Работа программы прекращена end else begin set product = 1 set i = 0 while i < length a begin set product = integer a at i * product set i = i + 1 end print product end end function
def function(): a = input().split() if a[0] == "stop": print("Работа программы прекращена") else: product = 1 i = 0 while i < len(a): product = int(a[i]) * product i+=1 print(product)
Python
zaydzuhri_stack_edu_python
function run self *args **kwargs begin raise call NotImplementedError string Tasks must define a run method. end function
def run(self, *args, **kwargs): raise NotImplementedError("Tasks must define a run method.")
Python
nomic_cornstack_python_v1
function get_all_possible_masks prev nxt begin comment Base case: finished parsing whole string if length nxt == 0 begin return list string end comment Base case: no more Xs if find nxt string X == - 1 begin return list nxt end comment Recursive case: set all_masks = list comment X here, so we need to replace with 0 ...
def get_all_possible_masks(prev, nxt): # Base case: finished parsing whole string if len(nxt) == 0: return [''] # Base case: no more Xs if nxt.find('X') == -1: return [nxt] # Recursive case: all_masks = [] if nxt[0] == 'X': # X here, so we need to replace with 0 or 1 ...
Python
nomic_cornstack_python_v1
function read_metadata cls data index begin set metadata = dict while true begin if not data at index begin pass end else if data at index and data at index at 0 == string Impact category begin return tuple metadata index end else if data at index and data at index + 1 and data at index at 0 begin set metadata at data...
def read_metadata(cls, data, index): metadata = {} while True: if not data[index]: pass elif data[index] and data[index][0] == "Impact category": return metadata, index elif data[index] and data[index + 1] and data[index][0]: ...
Python
nomic_cornstack_python_v1
function _gather_rdr_queries project_id dataset_id begin set query_list = list extend query_list call get_id_deduplicate_queries project_id dataset_id extend query_list call get_year_of_birth_queries project_id dataset_id extend query_list call get_negative_ages_queries project_id dataset_id extend query_list call get...
def _gather_rdr_queries(project_id, dataset_id): query_list = [] query_list.extend(id_dedup.get_id_deduplicate_queries(project_id, dataset_id)) query_list.extend(clean_years.get_year_of_birth_queries(project_id, dataset_id)) query_list.extend(neg_ages.get_negative_ages_queries(project_id, dataset_id)) ...
Python
nomic_cornstack_python_v1
function add_fivec_express_group subparser begin call add_argument string -e string --express-iterations dest=string expiter required=false type=int default=1000 action=string store help=string The number of iterations to run the express learning phase for. [default: %(default)s] call add_argument string -d string --re...
def add_fivec_express_group(subparser): subparser.add_argument("-e", "--express-iterations", dest="expiter", required=False, type=int, default=1000, action='store', help="The number of iterations to run the express learning phase for. [default: %(default)s]") subparser.add_argument("-d", "--remove-dista...
Python
nomic_cornstack_python_v1
comment Problem 378 comment Medium comment Asked by Coinbase comment Write a function that takes in a number, string, list, or dictionary and returns comment its JSON encoding. It should also handle nulls. comment For example, given the following input: comment [None, 123, ["a", "b"], {"c":"d"}] comment You should retu...
# Problem 378 # Medium # Asked by Coinbase # # Write a function that takes in a number, string, list, or dictionary and returns # its JSON encoding. It should also handle nulls. # # For example, given the following input: # # [None, 123, ["a", "b"], {"c":"d"}] # # You should return the following, as a string: ...
Python
zaydzuhri_stack_edu_python
function replace_multiGT_with_bialleleGT id_format_dict alt_allele_gt line_dict begin comment loop over proband (gt_id) and genotype from FORMAT field (gt_value) for tuple ft_id ft_field_dict in items id_format_dict begin try begin set gt_split_list = split re string [|/] ft_field_dict at string GT set alt_allele_gt_st...
def replace_multiGT_with_bialleleGT(id_format_dict, alt_allele_gt, line_dict): # loop over proband (gt_id) and genotype from FORMAT field (gt_value) for ft_id, ft_field_dict in id_format_dict.items(): try: gt_split_list = re.split("[|/]", ft_field_dict["GT"]) alt_allele_gt_str = ...
Python
nomic_cornstack_python_v1
function bagURLLinks request identifier begin comment assign the proxy url set proxyRoot = call build_absolute_uri string / comment attempt to grab a bag, call get_object_or_404 Bag name__exact=identifier try begin set transList = call generateBagFiles identifier proxyRoot CODA_PROXY_MODE end except FileHandleError beg...
def bagURLLinks(request, identifier): # assign the proxy url proxyRoot = request.build_absolute_uri('/') # attempt to grab a bag, get_object_or_404(Bag, name__exact=identifier) try: transList = generateBagFiles(identifier, proxyRoot, settings.CODA_PROXY_MODE) except FileHandleError: ...
Python
nomic_cornstack_python_v1
function set_up_repo clone_url repo_dir begin info string Cloning repo... set local_repo = call clone_from url=clone_url to_path=repo_dir return local_repo end function
def set_up_repo(clone_url, repo_dir): LOG.info("Cloning repo...") local_repo = git.Repo.clone_from(url=clone_url, to_path=repo_dir) return local_repo
Python
nomic_cornstack_python_v1
import copy import heapq as hp comment A class contains all the information and statistic for processes class Process extends object begin function __init__ self proc_id initial_arrival_time cpu_burst_time num_bursts io_time begin set proc_id = proc_id set arrival_time = integer initial_arrival_time set initial_arrival...
import copy import heapq as hp # A class contains all the information and statistic for processes class Process(object): def __init__(self, proc_id, initial_arrival_time, cpu_burst_time, num_bursts, io_time): self.proc_id = proc_id self.arrival_time = int(initial_arri...
Python
zaydzuhri_stack_edu_python
function c_to_f temp begin if type temp is list or type temp is tuple begin return list comprehension c * 1.8 + 32 for c in temp end else begin return temp * 1.8 + 32.0 end end function
def c_to_f(temp): if type(temp) is list or type(temp) is tuple: return [c * 1.8 + 32 for c in temp] else: return temp * 1.8 + 32.0
Python
nomic_cornstack_python_v1
function search_json self r **attr begin set xml = xml set output = none set request = request set response = response set resource = resource set table = table comment Query comes in pre-filtered to accessible & deletion_status comment Respect response.s3.filter call add_filter filter comment should be request.get_var...
def search_json(self, r, **attr): xml = self.manager.xml output = None request = self.request response = self.response resource = self.resource table = self.table # Query comes in pre-filtered to accessible & deletion_status # Respect response.s3.f...
Python
nomic_cornstack_python_v1
import math class MinHeap begin function __init__ self begin set heap = list set size = 0 end function function getParentIndex self i begin return floor i - 1 / 2 end function function getLeftChildIndex self i begin return 2 * i + 1 end function function getRightChildIndex self i begin return 2 * i + 2 end function fu...
import math class MinHeap: def __init__(self): self.heap = [] self.size = 0 def getParentIndex(self, i): return math.floor((i-1)/2) def getLeftChildIndex(self, i): return 2*i + 1 def getRightChildIndex(self, i): return 2*i + 2 ...
Python
zaydzuhri_stack_edu_python
import keras import numpy as np from datetime import datetime from keras import optimizers from keras.models import Model , load_model from keras.layers import Dense from keras.applications.resnet50 import ResNet50 from sklearn.metrics import roc_auc_score from utils import img_dims set batch_size = 64 set num_epochs =...
import keras import numpy as np from datetime import datetime from keras import optimizers from keras.models import Model, load_model from keras.layers import Dense from keras.applications.resnet50 import ResNet50 from sklearn.metrics import roc_auc_score from utils import img_dims batch_size = 64 num_epochs = 15 lr...
Python
zaydzuhri_stack_edu_python
function get_texts book begin set content = read book set chars_limit = 970 set texts = list comprehension content at slice i : i + chars_limit : for i in range 0 length content chars_limit return list comprehension if expression t != texts at 0 then string ... + t + string ... else t + string ... for t in texts end f...
def get_texts(book: TextIO) -> list: content = book.read() chars_limit = 970 texts = [content[i:i + chars_limit] for i in range(0, len(content), chars_limit)] return ["..." + t + "..." if t != texts[0] else t + "..." for t in texts]
Python
nomic_cornstack_python_v1
function predict model samples begin set tuple probabilities t = call forward_propagate model at string weights model at string biases samples return argument maximum probabilities axis=1 end function
def predict(model, samples): probabilities, t = forward_propagate( model['weights'], model['biases'], samples ) return np.argmax(probabilities, axis=1)
Python
nomic_cornstack_python_v1
function playerWins self begin raise NotImplementedError end function
def playerWins(self): raise NotImplementedError
Python
nomic_cornstack_python_v1
comment coding:utf-8 from selenium import webdriver import time import unittest from case.login import login class LoginTest extends TestCase begin decorator classmethod function setUpClass cls begin set driver = call Chrome end function function setUp self begin get driver string https://sop.linlinyi.cn/manage/toLogin...
# coding:utf-8 from selenium import webdriver import time import unittest from case.login import login class LoginTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = webdriver.Chrome() def setUp(self): self.driver.get("https://sop.linlinyi.cn/manage/toLogin.jhtml?retu...
Python
zaydzuhri_stack_edu_python
function set_contrast self brightness begin comment First write the brightness if brightness not in range 0 256 begin raise call ValueError string Valid brightness is between 0 and 255. end call write_mailbox 0 brightness comment Then write the command call write_blocking_command SET_CONTRAST_LEVEL end function
def set_contrast(self, brightness): # First write the brightness if brightness not in range(0, 256): raise ValueError("Valid brightness is between 0 and 255.") self.microblaze.write_mailbox(0, brightness) # Then write the command self.microblaze.write_blocking_comman...
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import collections import matplotlib.pyplot as plt import networkx as nx import progressbar import itertools comment from nxviz import CircosPlot string G = nx.Graph() orgs = [] #for letter1, letter2 in itertools.combinations("abcdefgh", 2): # G.add_edge(letter1, letter2) #G.add_n...
import pandas as pd import numpy as np import collections import matplotlib.pyplot as plt import networkx as nx import progressbar import itertools #from nxviz import CircosPlot ''' G = nx.Graph() orgs = [] #for letter1, letter2 in itertools.combinations("abcdefgh", 2): # G.add_edge(letter1, letter2) #G.add_node("...
Python
zaydzuhri_stack_edu_python
import pandas as pd import requests import bs4 from datetime import date set df = read csv string c:/pyprojects/dm/data/rm_links_to_brands2021-08-17.csv set links = list links set links = list comprehension string x + string ?isLayerAjax=1&limit=36 for x in links print links set df_total = call DataFrame for category_l...
import pandas as pd import requests import bs4 from datetime import date df = pd.read_csv('c:/pyprojects/dm/data/rm_links_to_brands2021-08-17.csv') links = list(df.links) links = [str(x) + '?isLayerAjax=1&limit=36' for x in links] print(links) df_total = pd.DataFrame() for category_link in links: print('#####...
Python
zaydzuhri_stack_edu_python
function home request begin assert is instance request HttpRequest return call render request string app/index.html dict string title string Home Page ; string year year end function
def home(request): assert isinstance(request, HttpRequest) return render( request, 'app/index.html', { 'title':'Home Page', 'year':datetime.now().year, } )
Python
nomic_cornstack_python_v1
function ISetMin InterfaceItemPath MinValue begin pass end function
def ISetMin(InterfaceItemPath, MinValue): pass
Python
nomic_cornstack_python_v1
from typing import List class Solution begin function maxSumAfterPartitioning self A K begin comment N = len(A) comment dp = [0] * (N + 1) comment for i in range(N): comment curMax = 0 comment # 1, 2, 3 comment # dp=[1,30,45,...] comment for k in range(1, min(K, i + 1) + 1): comment # i = 3 comment # A[i-k+1] => A[3-1+...
from typing import List class Solution: def maxSumAfterPartitioning(self, A: List[int], K: int) -> int: # N = len(A) # dp = [0] * (N + 1) # for i in range(N): # curMax = 0 # # 1, 2, 3 # # dp=[1,30,45,...] # for k in range(1, min(K,...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding=utf-8 from multiprocessing import Process from multiprocessing import Pool import os import time import random comment Only works on Unix/Linux/Mac: print string Process (%s) start... % call getpid set pid = call fork if pid == 0 begin print string I am child process (%s) and...
#!/usr/bin/env python # coding=utf-8 from multiprocessing import Process from multiprocessing import Pool import os import time import random # Only works on Unix/Linux/Mac: print('Process (%s) start...' % os.getpid()) pid = os.fork() if pid == 0: print('I am child process (%s) and my parent is %s.' % (os.getpid()...
Python
zaydzuhri_stack_edu_python
function test_check_metadata_nameid_full_name begin set check = call CheckTester googlefonts_profile string com.google.fonts/check/metadata/nameid/full_name set font = call TEST_FILE string merriweather/Merriweather-Regular.ttf call assert_PASS call check font string with a good font... comment here we change the font....
def test_check_metadata_nameid_full_name(): check = CheckTester(googlefonts_profile, "com.google.fonts/check/metadata/nameid/full_name") font = TEST_FILE("merriweather/Merriweather-Regular.ttf") assert_PASS(check(font), 'with a good font...') # here we change t...
Python
nomic_cornstack_python_v1
function __init__ self file begin comment default params set lonlat = none set name = none set map_zoom_level = none set tags = list set buildings = list comment osm-based geometry is based on explicit lat, lon coordinates, comment while geometry rendered from 3D creation software(i.e. blender) is based on relative [...
def __init__(self, file): # default params self.lonlat = None self.name = None self.map_zoom_level = None self.tags = [] self.buildings = [] # osm-based geometry is based on explicit lat, lon coordinates, # while geometry rendered...
Python
nomic_cornstack_python_v1
function test_04_verify_guest_lspci self begin if hypervisorNotSupported begin call skipTest string Hypervisor not supported end call verifyGuestState 3 end function
def test_04_verify_guest_lspci(self): if self.hypervisorNotSupported: self.skipTest("Hypervisor not supported") self.verifyGuestState(3)
Python
nomic_cornstack_python_v1
function diff_lineMode self text1 text2 deadline begin string Do a quick line-level diff on both strings, then rediff the parts for greater accuracy. This speedup can produce non-minimal diffs. Args: text1: Old string to be diffed. text2: New string to be diffed. deadline: Time when the diff should be complete by. Retu...
def diff_lineMode(self, text1, text2, deadline): """Do a quick line-level diff on both strings, then rediff the parts for greater accuracy. This speedup can produce non-minimal diffs. Args: text1: Old string to be diffed. text2: New string to be diffed. deadline: Time when the dif...
Python
jtatman_500k
function kptproj_prepare_vectors pt_locs pt_sizes pt_orientations begin comment project 3 pts: comment center, center + (cos, sin), center + (sin, -cos) comment measure angle and size set pt_locs = reshape pt_locs tuple - 1 2 set pt_sizes = reshape pt_sizes tuple - 1 1 set pt_orientations = reshape pt_orientations tupl...
def kptproj_prepare_vectors(pt_locs, pt_sizes, pt_orientations): # project 3 pts: # center, center + (cos, sin), center + (sin, -cos) # measure angle and size pt_locs = pt_locs.reshape((-1, 2)) pt_sizes = pt_sizes.reshape((-1, 1)) pt_orientations = pt_orientations.reshape((-1, 1)) pt_count = pt_locs.shape[0] ...
Python
nomic_cornstack_python_v1
function set_primary_parameters self **kwargs begin string Set all primary parameters at once. set given = sorted keys kwargs set required = sorted _PRIMARY_PARAMETERS if given == required begin for tuple key value in items kwargs begin set attribute self key value end end else begin raise call ValueError string When p...
def set_primary_parameters(self, **kwargs): """Set all primary parameters at once.""" given = sorted(kwargs.keys()) required = sorted(self._PRIMARY_PARAMETERS) if given == required: for (key, value) in kwargs.items(): setattr(self, key, value) else: ...
Python
jtatman_500k
string Negatives, Zeros and Positives На вход программе подается натуральное число nn, а затем nn целых чисел. Напишите программу, которая сначала выводит все отрицательные числа, затем нули, а затем все положительные числа, каждое на отдельной строке. Числа должны быть выведены в том же порядке, в котором они были вве...
""" Negatives, Zeros and Positives На вход программе подается натуральное число nn, а затем nn целых чисел. Напишите программу, которая сначала выводит все отрицательные числа, затем нули, а затем все положительные числа, каждое на отдельной строке. Числа должны быть выведены в том же порядке, в котором они были введен...
Python
zaydzuhri_stack_edu_python
import datetime import numpy as np import pandas as pd import scipy.optimize as optimize import matplotlib.pyplot as plt set returns_sheet = drop call read_excel string data_Ass1_G2.xlsx sheet_name=string Returns string month 1 set BM_sheet = drop call read_excel string data_Ass1_G2.xlsx sheet_name=string BM string mon...
import datetime import numpy as np import pandas as pd import scipy.optimize as optimize import matplotlib.pyplot as plt returns_sheet = pd.read_excel('data_Ass1_G2.xlsx', sheet_name='Returns').drop('month', 1) BM_sheet = pd.read_excel('data_Ass1_G2.xlsx', sheet_name='BM').drop('month', 1) # start is the first peri...
Python
zaydzuhri_stack_edu_python
async function Pulse_Lights begin call apply_effect_to_light ALL_LIGHTS pulse return dict string action string effect ; string name string pulse ; string light_id string all ; string color string red end function
async def Pulse_Lights(): busylightapi.manager.apply_effect_to_light(ALL_LIGHTS, pulse) return { "action": "effect", "name": "pulse", "light_id": "all", "color": "red", }
Python
nomic_cornstack_python_v1
import torch import torch.nn as nn class LayeredLSTM extends Module begin function __init__ self input_size hidden_size num_layers=1 norm_lstm=true begin call __init__ set i_s = input_size set h_s = hidden_size set n_layers = num_layers set hidden_states = list comprehension none for _ in range n_layers set cell_states...
import torch import torch.nn as nn class LayeredLSTM(nn.Module): def __init__(self, input_size, hidden_size, num_layers=1, norm_lstm=True): super(LayeredLSTM, self).__init__() self.i_s = input_size self.h_s = hidden_size self.n_layers = num_layers self.hidden_states = [No...
Python
zaydzuhri_stack_edu_python
function test_get_pages self begin comment We'll ask for the last page of single-entry pages. set expected_rows = count filter hidden=false if expected_rows > 10 begin set expected_rows = 10 end set expected_prev = expected_rows - 1 set token = call create_and_login set response = get client SEARCH_URL + string ?page_s...
def test_get_pages(self): # We'll ask for the last page of single-entry pages. expected_rows = SavedSearch.objects.filter(hidden=False).count() if expected_rows > 10: expected_rows = 10 expected_prev = expected_rows - 1 token = create_and_login() response ...
Python
nomic_cornstack_python_v1
string Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for...
""" Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it is able to trap after raining. The above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for co...
Python
zaydzuhri_stack_edu_python
from set import card , third_card_in_game_set , third_property , game_sets_on_table from nose.tools import assert_equal , assert_raises function test_card_works begin call assert_equal call card string 1GDE tuple string 1 string G string D string E end function function test_card_ordering begin call assert_equal call c...
from set import ( card, third_card_in_game_set, third_property, game_sets_on_table ) from nose.tools import assert_equal, assert_raises def test_card_works(): assert_equal(card('1GDE'), ('1', 'G', 'D', 'E')) def test_card_ordering(): assert_equal(card('EDG1'), ('1', 'G', 'D', 'E')) def tes...
Python
zaydzuhri_stack_edu_python