code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment format a number in IEEE float format comment only normal form supported comment exp returned without offsetting with a bias function IEEE_float f begin set f = decimal f set sign = 0 set exp = 0 if f < 0 begin set sign = 1 set f = - f end while f >= 2 begin set exp = exp + 1 set f = f / 2 end while f < 1 begin ...
#format a number in IEEE float format #only normal form supported #exp returned without offsetting with a bias def IEEE_float(f): f = float(f) sign = 0 exp = 0 if f < 0: sign = 1 f = -f while f >= 2: exp += 1 f /= 2 while f < 1 : exp -= 1 f *= 2 mantisa = int((f-1)* 2 ** 23) mantisa = "{0:b}".f...
Python
zaydzuhri_stack_edu_python
import unittest import data_io.db as db import sqlite3 class TestDB extends TestCase begin function test_db_ok_sqlite self begin set b = call DataBaseIO string SQLite string ./trash/test.db assert is instance b DataBaseIO end function function test_db_file_not_found self begin set b = call DataBaseIO string SQLite stri...
import unittest import data_io.db as db import sqlite3 class TestDB(unittest.TestCase): def test_db_ok_sqlite(self): b = db.DataBaseIO('SQLite', './trash/test.db') self.assertIsInstance(b, db.DataBaseIO) def test_db_file_not_found(self): b = db.DataBaseIO('SQLite', './non_existing_fo...
Python
zaydzuhri_stack_edu_python
function cmd_daemon opts begin if data_dir is none begin raise call BlockadeError string You must supply a data directory for the daemon end start rest data_dir=data_dir port=port debug=debug host_exec=call get_host_exec end function
def cmd_daemon(opts): if opts.data_dir is None: raise BlockadeError("You must supply a data directory for the daemon") rest.start(data_dir=opts.data_dir, port=opts.port, debug=opts.debug, host_exec=get_host_exec())
Python
nomic_cornstack_python_v1
import numpy as np import cv2 as cv comment Create a black image set img = zeros tuple 512 512 3 uint8 comment Draw a diagonal blue line with thickness of 5 px call line img tuple 0 0 tuple 511 511 tuple 255 0 0 5 call rectangle img tuple 384 0 tuple 510 128 tuple 0 255 0 3 call circle img tuple 447 63 63 tuple 0 0 255...
import numpy as np import cv2 as cv # Create a black image img = np.zeros((512,512,3), np.uint8) # Draw a diagonal blue line with thickness of 5 px cv.line(img,(0,0),(511,511),(255,0,0),5) cv.rectangle(img,(384,0),(510,128),(0,255,0),3) cv.circle(img,(447,63), 63, (0,0,255), -1) cv.ellipse(img,(256,256),(100,50),0,0,...
Python
zaydzuhri_stack_edu_python
comment -*- coding:utf-8 -*- import os import sys from PIL import Image import threading import time import logging comment Dir if length argv > 1 begin set fileDir = argv at 1 end else begin set fileDir = string top end comment config set _NEW_PREFIX = string new set _ENABLE_LOGGING = true set _IGNORE = list string .d...
# -*- coding:utf-8 -*- import os import sys from PIL import Image import threading import time import logging # Dir if len(sys.argv) > 1: fileDir = sys.argv[1] else: fileDir = 'top' # config _NEW_PREFIX = "new" _ENABLE_LOGGING = True _IGNORE = ['.db', '.txt', '.rar', '.zip'] def configLogging(): if not...
Python
zaydzuhri_stack_edu_python
function test_generate_batches_from_1d_array_with_incomplete_batch array batch_size expected begin set gen = call BatchGenerator array batch_size=batch_size set actual = call drain assert actual == expected end function
def test_generate_batches_from_1d_array_with_incomplete_batch( array, batch_size, expected): gen = BatchGenerator(array, batch_size=batch_size) actual = gen.drain() assert actual == expected
Python
nomic_cornstack_python_v1
comment class Node(object): comment def __init__(self, value, nextnode=None): comment self.value = value comment self._nextnode = nextnode comment def append(self, n): comment if not isinstance(n, Node): comment n = Node(n) comment self._nextnode, n = n, self._nextnode comment self._nextnode._nextnode = n comment n=Nod...
# class Node(object): # def __init__(self, value, nextnode=None): # self.value = value # self._nextnode = nextnode # def append(self, n): # if not isinstance(n, Node): # n = Node(n) # self._nextnode, n = n, self._nextnode # self._nextnode._nextnode = n # n=N...
Python
zaydzuhri_stack_edu_python
function pop self begin if stack == list and maxx == list begin return none end if stack at - 1 == maxx at - 1 begin pop maxx - 1 end return pop stack - 1 end function
def pop(self): if self.stack == [] and self.maxx == []: return None if self.stack[-1] == self.maxx[-1]: self.maxx.pop(-1) return self.stack.pop(-1)
Python
nomic_cornstack_python_v1
function get_all_volumes volume_ids=none filters=none return_objs=false region=none key=none keyid=none profile=none begin set conn = call _get_conn region=region key=key keyid=keyid profile=profile try begin set ret = call get_all_volumes volume_ids=volume_ids filters=filters return if expression return_objs then ret ...
def get_all_volumes( volume_ids=None, filters=None, return_objs=False, region=None, key=None, keyid=None, profile=None, ): conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) try: ret = conn.get_all_volumes(volume_ids=volume_ids, filters=filters) r...
Python
nomic_cornstack_python_v1
function type_address self address begin set locator = ADDRESS_INPUT set element = call create_web_element locator write element address return none end function
def type_address(self, address: str): locator = self._locator.ADDRESS_INPUT element = self.create_web_element(locator) element.write(address) return None
Python
nomic_cornstack_python_v1
function create_manual_barrage_initial_state spy_locations_list scout_locations_list miner_locations_list sergeant_locations_list lieutenant_locations_list captain_locations_list major_locations_list colonel_locations_list general_locations_list marshall_locations_list flag_locations_list bomb_locations_list specify_pi...
def create_manual_barrage_initial_state( spy_locations_list, scout_locations_list, miner_locations_list, sergeant_locations_list, lieutenant_locations_list, captain_locations_list, major_locations_list, colonel_locations_list, general_locations_lis...
Python
nomic_cornstack_python_v1
function _getGlobal self n begin return _setglobals at n end function
def _getGlobal(self, n): return self._setglobals[n]
Python
nomic_cornstack_python_v1
function find N M begin global board for i in range N - 1 - 1 - 1 begin for j in range M - 1 - 1 - 1 begin if board at i at j == string 1 begin return join string board at i at slice j - 55 : j + 1 : end end end end function function decoding code begin global decodingcode set tempcode = list for i in range 0 56 7 be...
def find(N, M): global board for i in range(N - 1, -1, -1): for j in range(M - 1, -1, -1): if board[i][j] == '1': return ''.join(board[i][j - 55:j+1]) def decoding(code): global decodingcode tempcode = [] for i in range(0, 56, 7): tempcode.append(decodin...
Python
zaydzuhri_stack_edu_python
function _split_tca_request_into_list self tca_request begin set ticker = ticker if not is instance ticker list begin set ticker = list ticker end set tca_request_list = list comment go through every ticker (and also split into list) for tick in ticker begin set tca_request_temp = call TCARequest tca_request=tca_reque...
def _split_tca_request_into_list(self, tca_request): ticker = tca_request.ticker if not (isinstance(ticker, list)): ticker = [ticker] tca_request_list = [] # go through every ticker (and also split into list) for tick in ticker: tca_request_temp = TCAR...
Python
nomic_cornstack_python_v1
function set_embedding_id_by_name self embedding_name=none begin set embeddings : List at DatasetEmbeddingData = call get_embeddings_by_dataset_id dataset_id=dataset_id if embedding_name is none begin set embedding_id = id return end try begin set embedding_id = next generator expression id for embedding in embeddings ...
def set_embedding_id_by_name(self, embedding_name: str = None): embeddings: List[DatasetEmbeddingData] = \ self.embeddings_api.get_embeddings_by_dataset_id(dataset_id=self.dataset_id) if embedding_name is None: self.embedding_id = embeddings[-1].id return tr...
Python
nomic_cornstack_python_v1
import unittest from sorting import e_6_5_9 class TestE659 extends TestCase begin function test_merge_two self begin set l1 = list 1 4 10 set l2 = list 5 8 15 set merged = call merge_sorted list l1 l2 assert equal list 1 4 5 8 10 15 merged end function function test_merge_three self begin set l1 = list 1 4 10 30 set l2...
import unittest from sorting import e_6_5_9 class TestE659(unittest.TestCase): def test_merge_two(self): l1 = [1, 4, 10] l2 = [5, 8, 15] merged = e_6_5_9.merge_sorted([l1, l2]) self.assertEqual([1, 4, 5, 8, 10, 15], merged) def test_merge_three(self):...
Python
zaydzuhri_stack_edu_python
comment 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 comment 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? comment 注意:给定 n 是一个正整数。 comment 示例 1: comment 输入: 2 comment 输出: 2 comment 解释: 有两种方法可以爬到楼顶。 comment 1. 1 阶 + 1 阶 comment 2. 2 阶 comment 示例 2: comment 输入: 3 comment 输出: 3 comment 解释: 有三种方法可以爬到楼顶。 comment 1. 1 阶 + 1 阶 + 1 阶 comment 2. 1 阶 + 2 阶 co...
# 假设你正在爬楼梯。需要 n 阶你才能到达楼顶。 # # 每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢? # # 注意:给定 n 是一个正整数。 # # 示例 1: # # 输入: 2 # 输出: 2 # 解释: 有两种方法可以爬到楼顶。 # 1. 1 阶 + 1 阶 # 2. 2 阶 # # 示例 2: # # 输入: 3 # 输出: 3 # 解释: 有三种方法可以爬到楼顶。 # 1. 1 阶 + 1 阶 + 1 阶 # 2. 1 阶 + 2 阶 # 3. 2 阶 + 1 阶 # # Related Topics 动态规划 # leetcode submit region begin(Pro...
Python
zaydzuhri_stack_edu_python
comment !/bin/python3 from datetime import datetime set time = strip input set time = string parse time time string %I:%M:%S%p print string format time time string %H:%M:%S
#!/bin/python3 from datetime import datetime time = input().strip() time = datetime.strptime(time, '%I:%M:%S%p') print(time.strftime('%H:%M:%S'))
Python
zaydzuhri_stack_edu_python
function ebt ticker begin return end function
def ebt(ticker): return
Python
nomic_cornstack_python_v1
function test_get_css_hide_submit self count_attempts max_attempts result begin set count_attempts = count_attempts set max_attempts = max_attempts set test_result = call get_css_hide_submit call assertEquals result test_result end function
def test_get_css_hide_submit( self, count_attempts, max_attempts, result, ): self.xblock.count_attempts = count_attempts self.xblock.max_attempts = max_attempts test_result = self.xblock.get_css_hide_submit() self.assertEquals(result, t...
Python
nomic_cornstack_python_v1
function get_all_subclasses cls begin for sub_cls in call __subclasses__ begin yield sub_cls yield from call get_all_subclasses sub_cls end end function
def get_all_subclasses(cls): for sub_cls in cls.__subclasses__(): yield sub_cls yield from get_all_subclasses(sub_cls)
Python
nomic_cornstack_python_v1
function metadata_options self begin return get pulumi self string metadata_options end function
def metadata_options(self) -> Optional[pulumi.Input['LaunchConfigurationMetadataOptionsArgs']]: return pulumi.get(self, "metadata_options")
Python
nomic_cornstack_python_v1
while i < b begin set c = b - i - 1 append reverse word at c set i = i + 1 end print word print reverse while j < b begin if word at j == reverse at j begin set palindrome = true set j = j + 1 continue end else begin set palindrome = false break end end if palindrome == true begin print string Palindrome ! end else beg...
while i < b: c = b - i -1 reverse.append(word[c]) i += 1 print(word) print(reverse) while j < b: if word[j] == reverse[j]: palindrome = True j += 1 continue else: palindrome = False break if palindrome == True: print("Palindrome !") els...
Python
zaydzuhri_stack_edu_python
function test_fenced_code_blocks_extra_10x begin comment Arrange set source_markdown = string 1. abc ```yaml def: > ghi ``` set expected_tokens = list string [olist(1,1):.:1:3:: ] string [para(1,4):] string [text(1,4):abc:] string [end-para:::False] string [fcode-block(2,4):`:3:yaml:::::] string [text(3,4):def: >&gt;...
def test_fenced_code_blocks_extra_10x(): # Arrange source_markdown = """1. abc ```yaml def: > ghi ```""" expected_tokens = [ "[olist(1,1):.:1:3:: \n \n \n ]", "[para(1,4):]", "[text(1,4):abc:]", "[end-para:::False]", "[fcode-block(2,4):`:3:yaml:::...
Python
nomic_cornstack_python_v1
comment Average Test Scores comment 06/27/2017 comment CTI-110 M5HW1 - Test Average and Grade comment Andrae Hernandez-Diaz function calc_Average score1 score2 score3 score4 score5 begin set average = score1 + score2 + score3 + score4 + score5 / 5 print string Your average score is: average end function function determ...
# Average Test Scores # 06/27/2017 # CTI-110 M5HW1 - Test Average and Grade # Andrae Hernandez-Diaz # def calc_Average(score1, score2, score3, score4, score5): average = (score1 + score2 + score3 + score4 + score5) / 5 print ("Your average score is:", average) def determine_grade(score): ...
Python
zaydzuhri_stack_edu_python
function _update_color self color begin set color = color end function
def _update_color(self, color): self.color = color
Python
nomic_cornstack_python_v1
function _get_table self begin return _table end function
def _get_table(self): return self._table
Python
nomic_cornstack_python_v1
function dissociate_mac_from_port_profile self mgr name mac_address begin pass end function
def dissociate_mac_from_port_profile(self, mgr, name, mac_address): pass
Python
nomic_cornstack_python_v1
class Solution begin function smallestpositive self array n begin comment Your code goes here sort array set ans = 1 for i in range n begin if array at i <= ans begin set ans = array at i + ans end end return ans end function end class
class Solution: def smallestpositive(self, array, n): # Your code goes here array.sort() ans =1 for i in range(n): if(array[i] <= ans): ans = array[i] + ans return ans
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 from typing import Dict , List , Optional comment INPUT_FILE_NAME: str = "test-input" comment STEP_COUNT: int = 100 comment CUP_COUNT: int = 9 set INPUT_FILE_NAME : str = string input set STEP_COUNT : int = 10000000 set CUP_COUNT : int = 1000000 class Cup begin function __init__ self label...
#!/usr/bin/env python3 from typing import Dict, List, Optional # INPUT_FILE_NAME: str = "test-input" # STEP_COUNT: int = 100 # CUP_COUNT: int = 9 INPUT_FILE_NAME: str = "input" STEP_COUNT: int = 10000000 CUP_COUNT: int = 1000000 class Cup: def __init__(self, label: int) -> None: self.label = label ...
Python
zaydzuhri_stack_edu_python
from PySimpleGUI import PySimpleGUI as sg comment Layout call theme string DarkBlue9 set layout = list list call Text string Usuário input key=string usuario size=tuple 25 1 list call Text string Senha input key=string senha password_char=string * size=tuple 25 1 list call Checkbox string Salvar o Login? list call Butt...
from PySimpleGUI import PySimpleGUI as sg # Layout sg.theme('DarkBlue9') layout = [ [sg.Text ('Usuário'), sg.Input(key= 'usuario', size=(25,1))], [sg.Text('Senha '), sg.Input(key='senha', password_char='*', size=(25,1))], [sg.Checkbox('Salvar o Login?')], [sg.Button('Entrar')] ] # Janela janela = sg...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python string Problem 14 05 April 2002 The following iterative sequence is defined for the set of positive integers: n --> n / 2 (n is even) n --> 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 It...
#!/usr/bin/env python """ Problem 14 05 April 2002 The following iterative sequence is defined for the set of positive integers: n --> n / 2 (n is even) n --> 3n + 1 (n is odd) Using the rule above and starting with 13, we generate the following sequence: 13 -> 40 -> 20 -> 10 -> 5 -> 16 -> 8 -> 4 -> 2 -> 1 It can ...
Python
zaydzuhri_stack_edu_python
comment pylint: disable=W0621 function test_open_csv_file src_pnts begin assert shape == tuple 12 2 end function
def test_open_csv_file(src_pnts): # pylint: disable=W0621 assert src_pnts.shape == (12, 2)
Python
nomic_cornstack_python_v1
import warnings from load_ressources import load_ressources from robot_actions import get_final_position filter warnings string ignore class GetFinalPosition begin function __init__ self begin set universe_file = string universe.txt set instructions_file = string instrucion_list.txt set initial_position = tuple 0 0 set...
import warnings from load_ressources import load_ressources from robot_actions import get_final_position warnings.filterwarnings("ignore") class GetFinalPosition: def __init__(self): self.universe_file = 'universe.txt' self.instructions_file = 'instrucion_list.txt' self.initial_position ...
Python
zaydzuhri_stack_edu_python
function view_note note_id begin set user_id = get session string user_id if user_id begin set notes = all set user_info = first filter user_id == user_id set image = images at 0 set user_note = get query note_id return call render_template string view_note.html user_note=user_note user_info=user_info image=image notes...
def view_note(note_id): user_id = session.get("user_id") if user_id: notes = Note.query.filter_by(user_id = user_id).all() user_info = User.query.filter(User.user_id == user_id).first() image = user_info.images[0] user_note = Note.query.get(note_id) return render...
Python
nomic_cornstack_python_v1
function bearing lat_from lng_from lat_to lng_to begin comment Convert from degrees to radians set lat1 = call radians lat_from set lng1 = call radians lng_from set lat2 = call radians lat_to set lng2 = call radians lng_to comment Longitudinal difference set dlng = lng2 - lng1 comment https://stackoverflow.com/a/155169...
def bearing(lat_from, lng_from, lat_to, lng_to): # Convert from degrees to radians lat1 = radians(lat_from) lng1 = radians(lng_from) lat2 = radians(lat_to) lng2 = radians(lng_to) # Longitudinal difference dlng = lng2 - lng1 # https://stackoverflow.com/a/15516993/549471 y = sin(dln...
Python
nomic_cornstack_python_v1
function calculate_tilt lead follow begin set y_change = lead at 1 - follow at 1 if y_change < 0 begin set angle = call calculate_angle absolute y_change absolute lead at 0 - follow at 0 end else if y_change > 0 begin set angle = 0 - call calculate_angle absolute y_change absolute lead at 0 - follow at 0 end else begin...
def calculate_tilt(lead, follow): y_change = lead[1] - follow[1] if y_change < 0: angle = calculate_angle(abs(y_change), abs(lead[0] - follow[0])) elif y_change > 0: angle = 0 - calculate_angle(abs(y_change), abs(lead[0] - follow[0])) else: angle = 0 return angle
Python
nomic_cornstack_python_v1
comment import required Libraries import requests from tkinter import * from tkinter import ttk comment define currency convertor object class Currency_Convertor begin set rates = dict function __init__ self url begin set data = json get requests url set rates = data at string rates end function function convert self ...
#import required Libraries import requests from tkinter import * from tkinter import ttk #define currency convertor object class Currency_Convertor: rates = {} def __init__(self, url): data = requests.get(url).json() self.rates = data["rates"] def convert(self, from_currency, to_currency, am...
Python
zaydzuhri_stack_edu_python
function push_all self iterable begin try begin assert is instance iterable tuple list tuple end except AssertionError begin string Histogram must be composed of finite list raise AssertionError end for item in iterable begin try begin set self at item = self at item + 1 end except KeyError begin set self at item = 1 e...
def push_all(self,iterable): try: assert isinstance(iterable, (list, tuple)) except AssertionError: "Histogram must be composed of finite list" raise AssertionError for item in iterable: try: self[item] += ...
Python
nomic_cornstack_python_v1
function __init__ self dset slices stride begin set volume = volume set label = label set sample = iterate range 0 length volume - slices stride set slices = slices end function
def __init__(self, dset, slices, stride): self.volume = dset.volume self.label = dset.label self.sample = iter(range(0, len(self.volume) - slices, stride)) self.slices = slices
Python
nomic_cornstack_python_v1
comment find node in a binary tree class BT extends object begin function __init__ self data left=none right=none begin set data = data set right = right set left = left end function function find_node self root data begin if root is none begin return none end if data == data begin return data end set left = call find_...
#find node in a binary tree class BT(object): def __init__(self, data, left=None, right=None): self.data = data self.right = right self.left = left def find_node(self, root, data): if root is None: return None if root.data == data: return root...
Python
zaydzuhri_stack_edu_python
comment real signature unknown; restored from __doc__ function rowHeight self QModelIndex begin return 0 end function
def rowHeight(self, QModelIndex): # real signature unknown; restored from __doc__ return 0
Python
nomic_cornstack_python_v1
function test_em_nested_list self begin set z_matrix = list list 0.0 0.0 0.333 list 0.033 0.05 0.267 list 0.067 0.1 0.2 list 0.1 0.175 0.1 list 0.2 0.2 0.067 list 0.267 0.225 0.033 list 0.333 0.25 0.0 set obtained_w_vector = call weigh z_matrix string EM set expected_w_vector = array list 0.37406776 0.25186448 0.374067...
def test_em_nested_list(self): z_matrix = [ [0.000, 0.000, 0.333], [0.033, 0.050, 0.267], [0.067, 0.100, 0.200], [0.100, 0.175, 0.100], [0.200, 0.200, 0.067], [0.267, 0.225, 0.033], [0.333, 0.250, 0.000], ] obtai...
Python
nomic_cornstack_python_v1
function test_extend_path_existing_pythonpath self begin set env = dict string PYTHONPATH string hello call extend_python_path env list string test string .pth assert env at string PYTHONPATH == join pathsep list string hello string test string .pth end function
def test_extend_path_existing_pythonpath(self): env = {"PYTHONPATH": "hello"} extend_python_path(env, ["test", ".pth"]) assert env["PYTHONPATH"] == os.pathsep.join(["hello", "test", ".pth"])
Python
nomic_cornstack_python_v1
function create_folders conf year begin set path = call get_conf_path conf year try begin make directories path end comment Python >2.5 except OSError as exc begin if errno == EEXIST and is directory path path begin pass end else begin raise end end end function
def create_folders(conf,year): path = get_conf_path(conf,year) try: os.makedirs(path) except OSError as exc: # Python >2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise
Python
nomic_cornstack_python_v1
function add_group_user self group_id **kwargs begin set kwargs at string _return_http_data_only = true if get kwargs string callback begin return call add_group_user_with_http_info group_id keyword kwargs end else begin set data = call add_group_user_with_http_info group_id keyword kwargs return data end end function
def add_group_user(self, group_id, **kwargs): kwargs['_return_http_data_only'] = True if kwargs.get('callback'): return self.add_group_user_with_http_info(group_id, **kwargs) else: (data) = self.add_group_user_with_http_info(group_id, **kwargs) return data
Python
nomic_cornstack_python_v1
string Vodstok server HTTP/S client Manage communications between Vodstok's client and remote servers import re import os import socket import urllib import httplib import urllib2 import urlparse from base64 import b64encode from core.exception import ServerIOError from core.helpers import normalize class Server begin ...
""" Vodstok server HTTP/S client Manage communications between Vodstok's client and remote servers """ import re import os import socket import urllib import httplib import urllib2 import urlparse from base64 import b64encode from core.exception import ServerIOError from core.helpers import normalize class Server: ...
Python
zaydzuhri_stack_edu_python
function plot_roll_pitch_vs_time dat start stop pitch_max=135 plot_errs=false suptitle=none outfile=none begin set start = call CxoTime start set stop = call CxoTime stop info string start.date= { date } stop.date= { date } pitch_max= { pitch_max } plot_errs= { plot_errs } suptitle= { suptitle } outfile= { outfile } se...
def plot_roll_pitch_vs_time( dat, start, stop, pitch_max=135, plot_errs=False, suptitle=None, outfile=None ): start = CxoTime(start) stop = CxoTime(stop) logger.info( f"{start.date=} {stop.date=} {pitch_max=} {plot_errs=} {suptitle=} {outfile=!s}" ) i0, i1 = np.searchsorted(dat["times"],...
Python
nomic_cornstack_python_v1
from sqlalchemy import select , inspect from adidas.adapters.orm import metadata function test_database_populate_inspect_table_names database_engine begin comment Get table information set inspector = call inspect database_engine assert call get_table_names == list string product_brands string products string comments ...
from sqlalchemy import select, inspect from adidas.adapters.orm import metadata def test_database_populate_inspect_table_names(database_engine): # Get table information inspector = inspect(database_engine) assert inspector.get_table_names() == ['product_brands', 'products', 'comments', 'brands', 'users']...
Python
zaydzuhri_stack_edu_python
import Project class TypeBucketFactory extends IFactory begin string A bucket factory that creates buckets based on a function or type that takes one argument, the key map. function __init__ self Type begin string Creates a new bucket factory based on the given function or type. set type = Type end function function cr...
import Project class TypeBucketFactory(Project.IFactory): """ A bucket factory that creates buckets based on a function or type that takes one argument, the key map. """ def __init__(self, Type): """ Creates a new bucket factory based on the given function or type. """ self.type = Type de...
Python
zaydzuhri_stack_edu_python
string Create a wallet app for learning about pytest. class InsufficientAmount extends Exception begin pass end class class Wallet extends object begin string Wallet object to handle add cash and spend cash. function __init__ self initialamount=0 begin string Set up the initial amount in the wallet set balance = initia...
"""Create a wallet app for learning about pytest.""" class InsufficientAmount(Exception): pass class Wallet(object): """Wallet object to handle add cash and spend cash.""" def __init__(self,initialamount=0): """Set up the initial amount in the wallet""" self.balance = initialamount ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import numpy as np set mutations = list with open string list string r as flist begin for line in read lines flist begin set fn = strip line append mutations fn end end set database = dict for mut in mutations begin set mutation = mut at slice 0 : - 4 : set data = dict comment mono WT s...
#!/usr/bin/env python import numpy as np mutations = [] with open( "list", 'r' ) as flist: for line in flist.readlines(): fn = line.strip() mutations.append(fn) database = {} for mut in mutations: mutation = mut[0:-4] data = {} data["WT"] = [] #mono WT data["MUT"] = [] #mono MUT...
Python
zaydzuhri_stack_edu_python
function findBeltSerialPort begin set _PY3 = version_info > tuple 3 set ports = call comports for comm_port in ports begin set port_valid = false try begin print string Testing port: + string comm_port at 0 comment Connect to port with call Serial comm_port at 0 SERIAL_BAUDRATE timeout=SERIAL_READ_TIMEOUT write_timeout...
def findBeltSerialPort(): _PY3 = sys.version_info > (3,) ports = serial.tools.list_ports.comports() for comm_port in ports: port_valid = False try: print("Testing port: "+str(comm_port[0])) # Connect to port with serial.Serial(comm_port[0], ...
Python
nomic_cornstack_python_v1
function run_sim self rtol=1e-12 begin call run_sim set result = 0 if comp_bench begin set result = call compare_to_benchmark rtol end if make_bench or result != 0 and reset_bench_on_fail begin call store_as_benchmark end if comp_bench begin return result end return sim end function
def run_sim(self, rtol=1.e-12): super().run_sim() result = 0 if self.comp_bench: result = self.compare_to_benchmark(rtol) if self.make_bench or (result != 0 and self.reset_bench_on_fail): self.store_as_benchmark() if self.comp_bench: retur...
Python
nomic_cornstack_python_v1
function fromMesh cls mesh export_matrix matPtr materials isCollision=false begin global DO comment gettings the positions and normals set positions = list none * length vertices set normals = call getNormalData mesh for tuple i v in enumerate vertices begin set positions at i = call Vector3 export_matrix @ co set norm...
def fromMesh(cls, mesh: bpy.types.Mesh, export_matrix: mathutils.Matrix, matPtr: int, materials: List[Material], isCollision: bool = False): global DO # gettings the positions and normals positions = [None] * len(mesh.vertices) normals = common.getNormalData(mesh) for i, v in enumerate(m...
Python
nomic_cornstack_python_v1
function cmd_syst self line begin comment Replying to this command is of questionable utility, because comment this server does not behave in a predictable way w.r.t. the comment output of the LIST command. We emulate Unix ls output, but comment on win32 the pathname can contain drive information at the front comment C...
def cmd_syst (self, line): # Replying to this command is of questionable utility, because # this server does not behave in a predictable way w.r.t. the # output of the LIST command. We emulate Unix ls output, but # on win32 the pathname can contain drive information at the front ...
Python
nomic_cornstack_python_v1
function setAboveDropoffType self val=string True **kwargs begin pass end function
def setAboveDropoffType(self, val='True', **kwargs): pass
Python
nomic_cornstack_python_v1
comment Blank Python import scraperwiki call attach string electiondates set data = select sqlite string * from swdata order by election_date desc limit 10
# Blank Python import scraperwiki scraperwiki.sqlite.attach("electiondates") data = scraperwiki.sqlite.select( '''* from swdata order by election_date desc limit 10''' )
Python
zaydzuhri_stack_edu_python
function calculate_sum_positive_even_numbers numbers begin string Calculates the sum of all positive even numbers from a given list. Args: numbers (list): The list of numbers. Returns: int: The sum of all positive even numbers. Raises: ValueError: If the input list contains non-integer elements. comment Validate the in...
def calculate_sum_positive_even_numbers(numbers): """ Calculates the sum of all positive even numbers from a given list. Args: numbers (list): The list of numbers. Returns: int: The sum of all positive even numbers. Raises: ValueError: If the input list contains non-intege...
Python
jtatman_500k
function targetInArray arr target begin for i in range length arr begin for j in range length arr at i begin if target == arr at i at j begin return true end end end return false end function
def targetInArray(arr,target): for i in range(len(arr)): for j in range(len(arr[i])): if target == arr[i][j]: return True return False
Python
flytech_python_25k
function product a b begin return a * b end function function judge num begin if num % 2 == 0 begin print string Even end else begin print string Odd end end function set tuple a b = map int split input call judge product a b
def product(a, b): return a * b def judge(num): if num % 2 == 0: print('Even') else: print('Odd') a, b = map(int, input().split()) judge(product(a, b))
Python
zaydzuhri_stack_edu_python
comment Matrix24 import random import numpy as np set M = call randrange 1 5 set N = call randrange 1 5 print string M = M print string N = N set A = random integer 7 size=tuple M N print string Матрица: A for i in range N begin set x = A at tuple slice : : i print string Столбец: x print string Максимум: max x end
#Matrix24 import random import numpy as np M = random.randrange(1,5) N = random.randrange(1,5) print('M = ',M) print('N = ',N) A = np.random.randint(7,size=(M,N)) print('Матрица:',A) for i in range(N): x = A[:,i] print('Столбец:',x) print('Максимум:',max(x))
Python
zaydzuhri_stack_edu_python
function check_sparkdf_find_dupes sparkdf columns begin return sort where string count>1 string count ascending=false end function
def check_sparkdf_find_dupes(sparkdf,columns): return sparkdf.groupBy(columns).count().where('count>1').sort('count', ascending=False)
Python
nomic_cornstack_python_v1
function test_list_repos_200 self begin set response = get client reverse string api:list_repos dict string language language_exists assert equal status_code 200 end function
def test_list_repos_200(self): response = self.client.get( reverse('api:list_repos'), {'language': self.language_exists} ) self.assertEqual(response.status_code, 200)
Python
nomic_cornstack_python_v1
function first_acquired self first_acquired begin if first_acquired is none begin comment noqa: E501 raise call ValueError string Invalid value for `first_acquired`, must not be `None` end set _first_acquired = first_acquired end function
def first_acquired(self, first_acquired): if first_acquired is None: raise ValueError("Invalid value for `first_acquired`, must not be `None`") # noqa: E501 self._first_acquired = first_acquired
Python
nomic_cornstack_python_v1
function number_of_changes_in_pressure self fs fc=none n=none begin return call compute wrapper number_of_changes_in_pressure fs=fs fc=fc n=n end function
def number_of_changes_in_pressure(self, fs, fc=None, n=None): return self.compute(self.wrapper, number_of_changes_in_pressure, fs=fs, fc=fc, n=n)
Python
nomic_cornstack_python_v1
from bs4 import BeautifulSoup import csv import requests import pandas as pd set start_url = string https://en.wikipedia.org/wiki/List_of_brightest_stars_and_other_record_stars set page = get requests start_url function scrape begin set headers = list string Proper name string Distance string Mass string Radius set sta...
from bs4 import BeautifulSoup import csv import requests import pandas as pd start_url = "https://en.wikipedia.org/wiki/List_of_brightest_stars_and_other_record_stars" page = requests.get(start_url) def scrape(): headers = ["Proper name", "Distance", "Mass", "Radius"] star_data = [] soup = BeautifulSoup(...
Python
zaydzuhri_stack_edu_python
function setup self horizontals begin print string SETUP for tuple n h in enumerate horizontals begin comment run through m for tuple m val in enumerate split h begin set number = integer val call set_value n m number setup=true end end comment set the value list for horizintals and verticals for i in range 9 begin cal...
def setup(self, horizontals): print('SETUP') for n, h in enumerate(horizontals): # run through m for m, val in enumerate(h.split()): number = int(val) self.set_value(n, m, number, setup=True) # set the value list for horizintals and vertic...
Python
nomic_cornstack_python_v1
function gcd a b begin while a != 0 begin set tuple a b = tuple b % a a end return b end function function reduce_by_gcd arr begin set gcd_val = arr at 0 for i in range length arr begin set gcd_val = call gcd gcd_val arr at i end return list comprehension a // gcd_val for a in arr end function set reduced_arr = call re...
def gcd(a, b): while a != 0: a, b = b % a, a return b def reduce_by_gcd(arr): gcd_val = arr[0] for i in range(len(arr)): gcd_val = gcd(gcd_val, arr[i]) return [a // gcd_val for a in arr] reduced_arr = reduce_by_gcd([30, 20, 45]) print(reduced_arr) # [2, 3, 5]
Python
flytech_python_25k
function expand_and_calculate begin from math import comb function expand_binomial n begin comment Generate coefficients using Pascal's triangle set coefficients = list comprehension call comb n k for k in range n + 1 set terms = list for k in range n + 1 begin if k == 0 begin append terms string a^ { n } end else if ...
def expand_and_calculate(): from math import comb def expand_binomial(n): # Generate coefficients using Pascal's triangle coefficients = [comb(n, k) for k in range(n + 1)] terms = [] for k in range(n + 1): if k == 0: terms.append(f'a^{n}') ...
Python
dbands_pythonMath
import job_scraper import argparse set parser = call ArgumentParser description=string Find Most-Wanted Skills for Different Jobs on indeed.com call add_argument string --city nargs=1 help=string target city call add_argument string --state nargs=1 help=string target state in abbreviation like "WA", "CA", or "NY" set a...
import job_scraper import argparse parser = argparse.ArgumentParser(description='Find Most-Wanted Skills for Different Jobs on indeed.com') parser.add_argument('--city', nargs = 1, help='target city') parser.add_argument('--state', nargs = 1, help='target state in abbreviation like "WA", "CA", or "NY"') args = parser....
Python
zaydzuhri_stack_edu_python
import numpy as np import sympy as sym from sympy.abc import x function trapezoidal f k a b begin set N = 2 ^ k set h = b - a / N set res = 0.0 for n in range N begin set res = res + h / 2 * call subs x a + n * h + call subs x a + h + n * h end return res end function set X = array list 0.04691008 0.23076534 0.5 0.7692...
import numpy as np import sympy as sym from sympy.abc import x def trapezoidal(f, k, a, b): N = 2 ** k h = (b - a)/ N res = 0.0 for n in range(N): res += (h/2) * (f.subs(x, a + n*h) + f.subs(x, a + h + n*h)) return res X = np.array([0.04691008, 0.23076534, 0.5, 0.76923466, 0.95308992]) C =...
Python
zaydzuhri_stack_edu_python
import sys import argparse from Compiler import Compiler from Interpreter import Interpreter function main begin comment parse arguments set arg_parser = call ArgumentParser description=string Compiler for the functional programming language zlang call add_argument string files nargs=string + help=string input files ca...
import sys import argparse from Compiler import Compiler from Interpreter import Interpreter def main(): # parse arguments arg_parser = argparse.ArgumentParser( description="Compiler for the functional programming language zlang" ) arg_parser.add_argument('files', nargs="+", help="inpu...
Python
zaydzuhri_stack_edu_python
function createspk self Code start stop begin set obsid = call mpc2internal Code set startet = call mjd2et start set stopet = call mjd2et stop comment Search for Observatory in List of Dictionaries for i in obsdict begin if i at string Code == Code begin set selected_observer = i comment Location in km set x = i at str...
def createspk(self,Code, start, stop): obsid=self.mpc2internal(Code) startet=self.mjd2et(start) stopet=self.mjd2et(stop) # Search for Observatory in List of Dictionaries for i in self.obsdict: if i['Code'] == Code: selected_observer=i ...
Python
nomic_cornstack_python_v1
function find_pair arr s t begin for x in arr begin set y = t - x if y in s and x != y begin return true end end return false end function
def find_pair(arr, s, t): for x in arr: y = t-x if (y in s) and (x != y): return True return False
Python
nomic_cornstack_python_v1
function complete_greedy numbers num_parts=2 return_indices=false objective=none begin set sorted_numbers = sorted enumerate numbers key=lambda x -> x at 1 reverse=true comment Create a stack whose elements are partitions, their sums, and current depth set to_visit : List at Tuple at tuple Partition List at int int = l...
def complete_greedy( numbers: List[int], num_parts: int = 2, return_indices: bool = False, objective: Optional[Callable[[Partition], float]] = None, ) -> Iterator[PartitioningResult]: sorted_numbers = sorted(enumerate(numbers), key=lambda x: x[1], reverse=True) # Create a stack whose elements ar...
Python
nomic_cornstack_python_v1
function __set__ self oself value begin set original = get attribute oself originalAttribute set attribute original attributeName value end function
def __set__(self, oself, value): original = getattr(oself, self.originalAttribute) setattr(original, self.attributeName, value)
Python
nomic_cornstack_python_v1
function __get_and_clear_adapted_buffer self begin set output = __adapted_buffer set __adapted_buffer = b'' return output end function
def __get_and_clear_adapted_buffer(self): output = self.__adapted_buffer self.__adapted_buffer = b'' return output
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns import math function twoCharGram dataset begin with open dataset string r as data begin set textFile = replace read data string string set kGrams = set comment 2-Char gram for i in range length textFile - 1 begin if textF...
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import seaborn as sns import math def twoCharGram(dataset): with open(dataset, 'r') as data: textFile = data.read().replace('\n', ' ') kGrams = set() # 2-Char gram for i in range(len(textFile)-1): ...
Python
zaydzuhri_stack_edu_python
comment Number Letter Counts comment If the numbers 1 to 5 are written out in words: one, two, three, four, five, comment then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. comment If all the numbers from 1 to 1000 (one thousand) inclusive comment were written out in words, how many letters would be used? com...
# Number Letter Counts # # If the numbers 1 to 5 are written out in words: one, two, three, four, five, # then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total. # # If all the numbers from 1 to 1000 (one thousand) inclusive # were written out in words, how many letters would be used? # # NOTE: Do not count spaces...
Python
zaydzuhri_stack_edu_python
from sklearn.svm import SVC from sklearn.preprocessing import StandardScaler from random import shuffle from sklearn.model_selection import train_test_split , GridSearchCV from sklearn.metrics import classification_report import numpy as np import pickle from calculate_features import extract_features , HogParameters f...
from sklearn.svm import SVC from sklearn.preprocessing import StandardScaler from random import shuffle from sklearn.model_selection import train_test_split, GridSearchCV from sklearn.metrics import classification_report import numpy as np import pickle from calculate_features import extract_features, HogParameters fr...
Python
zaydzuhri_stack_edu_python
function lqi_repeaters self lqi_repeaters begin set _lqi_repeaters = lqi_repeaters end function
def lqi_repeaters(self, lqi_repeaters): self._lqi_repeaters = lqi_repeaters
Python
nomic_cornstack_python_v1
function _get_relation_alias self relation_id begin for relation in relations at relation_name begin if id == relation_id begin return get data at local_unit string alias end end return none end function
def _get_relation_alias(self, relation_id: int) -> Optional[str]: for relation in self.charm.model.relations[self.relation_name]: if relation.id == relation_id: return relation.data[self.local_unit].get("alias") return None
Python
nomic_cornstack_python_v1
comment main.py print string ================================ print string Running main.py - module name: { __name__ } import module1 print module1 call pprint_dict string main.globals globals print string ================================
# main.py print('================================') print(f'Running main.py - module name: {__name__}') import module1 print(module1) module1.pprint_dict('main.globals', globals()) print('================================')
Python
zaydzuhri_stack_edu_python
import random import string function generate_random_password length begin comment String of characters to choose from set chars = ascii_letters + digits + string !@#$%^&*() comment Randomly choose 4 characters from the list of characters set random_chars = join string generator expression random choice chars for i in...
import random import string def generate_random_password(length): # String of characters to choose from chars = string.ascii_letters + string.digits + '!@#$%^&*()' # Randomly choose 4 characters from the list of characters random_chars = ''.join(random.choice(chars) for i in range(length)) # Gene...
Python
flytech_python_25k
function is_on self begin set run_state = call _get_run_state return STATE_DISHWASHER_POWER_OFF not in run_state end function
def is_on(self): run_state = self._get_run_state() return STATE_DISHWASHER_POWER_OFF not in run_state
Python
nomic_cornstack_python_v1
function DJAlgCircuit size U_f begin comment The last qubit is defined as an ancilla qubit with value 1 set c = call QCircuit size size - 1 string Deutsch-Josza Algorithm ancilla=list 1 comment We apply a Hadamard gate to all the qubits for i in range size begin call add_operation string H targets=i end comment We appl...
def DJAlgCircuit(size, U_f): # The last qubit is defined as an ancilla qubit with value 1 c = QCircuit(size, size-1, "Deutsch-Josza Algorithm", ancilla=[1]) # We apply a Hadamard gate to all the qubits for i in range(size): c.add_operation("H", targets=i) # We apply the U_f oracle c.ad...
Python
nomic_cornstack_python_v1
import aiohttp import asyncio import async_timeout import time from bs4 import BeautifulSoup set AAA = list async function fetch_coroutine client url begin with call timeout 10 begin async_with get client url as response begin comment 如果server端成功回應 assert status == 200 comment 取得html檔 set html = await call text commen...
import aiohttp import asyncio import async_timeout import time from bs4 import BeautifulSoup AAA = [] async def fetch_coroutine(client, url): with async_timeout.timeout(10): async with client.get(url) as response: assert response.status == 200 ## 如果server端成功回應 html = await respo...
Python
zaydzuhri_stack_edu_python
function train_single config begin print string | Starting training on single device. set pre_train_dataset = if expression pre_train_dataset then call load_dataset data_files=pre_train_dataset batch_size=batch_size sink_mode=dataset_sink_mode else none set fine_tune_dataset = if expression fine_tune_dataset then call ...
def train_single(config): print(" | Starting training on single device.") pre_train_dataset = load_dataset(data_files=config.pre_train_dataset, batch_size=config.batch_size, sink_mode=config.dataset_sink_mode) if config.pre_train_dataset...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python from lexer import *
#!/usr/bin/env python from lexer import *
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd from numpy.random import randn seed 101 set df = call DataFrame randn 5 4 list string A string B string C string D string E list string W string X string Y string Z comment print date frame values print df comment print value of column 'W' in data frame print df at string W commen...
import numpy as np import pandas as pd from numpy.random import randn np.random.seed(101) df = pd.DataFrame(randn(5, 4), ['A', 'B', 'C', 'D', 'E'], ['W', 'X', 'Y', 'Z']) # print date frame values print(df) # print value of column 'W' in data frame print(df['W']) # print the type of data frame print(type(df)) # pr...
Python
zaydzuhri_stack_edu_python
function annotate_alignment_file sample_name outpath alignment_file family_size_min family_size_max nm_max nm_max_dloop mtdna_offset tag_excl tag_incl mtdna_alt_seq alt_fmin alt_fmax begin comment dump QC+ reads to a new bam file set cmd = string %s view -hbS -o %s - % tuple samtools outpath + sep + sample_name + strin...
def annotate_alignment_file(sample_name, outpath, alignment_file, family_size_min, family_size_max, nm_max, nm_max_dloop, mtdna_offset, tag_excl, tag_incl, mtdna_alt_seq, alt_fmin, alt_fmax): #dump QC+ reads to a new bam file cmd = "%s view -hbS -o %s - " % (samtools, outpath + os.path.sep + sample_name + ".%s.conse...
Python
nomic_cornstack_python_v1
function test_gbc x y tune begin comment Perform classification without tuning. It was determined through trial-and-error comment that log2 features produced the highest accuracy set gbt = gradient boosting classifier max_features=string log2 set pipeline = call create_pipeline gbt return call accuracy pipeline x y end...
def test_gbc(x, y, tune): # Perform classification without tuning. It was determined through trial-and-error # that log2 features produced the highest accuracy gbt = GradientBoostingClassifier(max_features="log2") pipeline = create_pipeline(gbt) return accuracy(pipeline, x, y)
Python
nomic_cornstack_python_v1
import pandas as pd from sklearn.linear_model import LinearRegression import joblib set ds = read csv string SalaryData.csv set y = ds at string Salary set x = ds at string YearsExperience set x = reshape values 30 1 set y = reshape values 30 1 set model = linear regression comment create formula y = c + wx fit model x...
import pandas as pd from sklearn.linear_model import LinearRegression import joblib ds = pd.read_csv('SalaryData.csv') y = ds['Salary'] x = ds['YearsExperience'] x =x.values.reshape(30,1) y = y.values.reshape(30,1) model = LinearRegression() # create formula y = c + wx model.fit(x,y) joblib.dump(model , 'model.p...
Python
zaydzuhri_stack_edu_python
comment Write a function that checks whether a number is ina given range (inclusive of high and low) function range_check num low high begin if num > low and num < high begin print string { num } is in the range between { low } and { high } . end else begin print string { num } is not in the range between { low } and {...
# Write a function that checks whether a number is ina given range (inclusive of high and low) def range_check(num, low, high): if num > low and num < high: print(f'{num} is in the range between {low} and {high}.') else: print(f'{num} is not in the range between {low} and {high}.') range_check...
Python
zaydzuhri_stack_edu_python
function a_coefficients y1 y2 begin set ACoefficients = as type array list y1 y2 float return ACoefficients end function
def a_coefficients(y1,y2): ACoefficients = np.array([ y1, \ y2 ]).astype(float) return(ACoefficients)
Python
nomic_cornstack_python_v1
import os from collections import defaultdict import numpy as np from sklearn import linear_model import matplotlib.pyplot as plt import re import warnings filter warnings string ignore set PATH_TO_DATA = string twitter_dataset set tuple TRAIN_DIR TRAIN_FILE = tuple join path PATH_TO_DATA string train string trainingda...
import os from collections import defaultdict import numpy as np from sklearn import linear_model import matplotlib.pyplot as plt import re import warnings warnings.filterwarnings("ignore") PATH_TO_DATA = 'twitter_dataset' TRAIN_DIR, TRAIN_FILE = os.path.join(PATH_TO_DATA, 'train'), "trainingdata-all-annotations.txt"...
Python
zaydzuhri_stack_edu_python
function longest strings from_start=true begin return reduce lambda x y -> tuple tuple y x at length x > length y tuple y x at from_start at length x == length y strings list end function
def longest(strings: list, from_start=True) -> object: return reduce((lambda x, y: ((y, x)[len(x) > len(y)], (y, x)[from_start]) [len(x) == len(y)]), strings, [])
Python
nomic_cornstack_python_v1
function get_health self begin return __healthy end function
def get_health(self): return self.__healthy
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- string Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. A sudoku puzzle... ...and its solution numbers marked in red. comment 如果把九宫格按照行从0开始标号,那么数字board[i][j] 位于第 i...
#-*- coding:utf-8 -*- """ Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique solution. A sudoku puzzle... ...and its solution numbers marked in red. """ # 如果把九宫格按照行从0开始标号,那么数字board[i][j] 位于第 i/3*3...
Python
zaydzuhri_stack_edu_python