code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment COPY A LIST set new_list = copy the_list print new_list comment ANOTHER WAY set new_list_2 = list the_list print new_list_2
# COPY A LIST new_list = the_list.copy() print(new_list) # ANOTHER WAY new_list_2 = list(the_list) print(new_list_2)
Python
zaydzuhri_stack_edu_python
function insert_location location begin set query = string INSERT INTO { location_table_name } (` { location_col_name } `) VALUES (%s) comment Get connection set factory = call connection_manager set connection = connection set cursor = call cursor try begin execute cursor query list location end except any begin raise...
def insert_location(location): query = f"INSERT INTO {sensor_DAO.location_table_name} (`{sensor_DAO.location_col_name}`) VALUES (%s)" # Get connection factory = connection_manager() connection = factory.connection cursor = connection.cursor() try: cursor.exe...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- import requests class http_request begin function __init__ self cookie=none begin set set_cookie = none set cookies = call RequestsCookieJar end function function post self url body=none begin try begin set r = post url=url data=body cookies=cookies timeout=10....
#!/usr/bin/env python # -*- coding: utf-8 -*- import requests class http_request: def __init__(self, cookie=None): self.set_cookie = None self.cookies = requests.cookies.RequestsCookieJar() def post(self, url, body=None): try: r = requests.post(url=url, data=body, cookies...
Python
zaydzuhri_stack_edu_python
function login self email password begin string login using email and password :param email: email address :param password: password set rsp = call _request set default_headers at string Authorization = data at string token return rsp end function
def login(self, email, password): """ login using email and password :param email: email address :param password: password """ rsp = self._request() self.default_headers['Authorization'] = rsp.data['token'] return rsp
Python
jtatman_500k
class Solution extends object begin function countAndSay self n begin string :type n: int :rtype: str set x = string 1 for i in range 1 n begin set x = call do x end return x end function function do self n begin set x = list string n insert x 0 string 0 append x string 0 set rv = list set count = 0 for i in range 1 l...
class Solution(object): def countAndSay(self, n): """ :type n: int :rtype: str """ x = "1" for i in range(1, n): x = self.do(x) return x def do(self, n): x = list(str(n)) x.insert(0, "0") x.append("0") rv = [] ...
Python
zaydzuhri_stack_edu_python
import random set rand_num = random integer 0 1 if rand_num == 0 begin print string Heads end else begin print string Tails end
import random rand_num = random.randint(0,1) if rand_num == 0: print("Heads") else: print("Tails")
Python
flytech_python_25k
function test_parseUnformattedText self begin assert equal call parseFormattedText string hello normal at string hello end function
def test_parseUnformattedText(self): self.assertEqual(irc.parseFormattedText("hello"), A.normal["hello"])
Python
nomic_cornstack_python_v1
function yes_redo status begin assert equal call gy at string PipelineStatus: status call touch string pipeline/lane1.redo assert equal call gy at string PipelineStatus: string redo call rm string pipeline/lane1.redo end function
def yes_redo(status): self.assertEqual(gy()['PipelineStatus:'], status) self.touch('pipeline/lane1.redo') self.assertEqual(gy()['PipelineStatus:'], 'redo') self.rm('pipeline/lane1.redo')
Python
nomic_cornstack_python_v1
function ultrasonic self num ext=C_EXT_MASTER wait=true begin class inp extends object begin function __init__ self outer num ext begin set _outer = outer set _num = num set _ext = ext end function function distance self begin return call getCurrentInput num - 1 _ext end function end class set tuple M I = call getConfi...
def ultrasonic(self, num, ext=ftTXT.C_EXT_MASTER, wait=True): class inp(object): def __init__(self, outer, num, ext): self._outer=outer self._num=num self._ext=ext def distance(self): return self._outer.getCurrentInput(num-1, self._ext) M, I = self.getConfig(ext)...
Python
nomic_cornstack_python_v1
function validate self args begin set exceptions = list for opt in options begin extend exceptions call validate args end return exceptions end function
def validate(self, args: 'argparse.Namespace') -> 'List[Exception]': exceptions = [] for opt in self.options: exceptions.extend(opt.validate(args)) return exceptions
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from tensorflow.keras.datasets import cifar10 set tuple tuple X_train y_train tuple X_test y_test = call load_data image show X_train at 5 set X_train = as type X_train string float32 set X_test = as type X_test string float32 ...
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from tensorflow.keras.datasets import cifar10 (X_train,y_train),(X_test,y_test) = cifar10.load_data() plt.imshow(X_train[5]) X_train = X_train.astype('float32') X_test = X_test.astype('float32') import tensorflow.keras.utils...
Python
zaydzuhri_stack_edu_python
function prepare self begin set encoded = encode jwt dict string some string payload ; string exp call utcnow + time delta seconds=600 SECRET algorithm=string HS256 end function
def prepare(self): self.encoded = jwt.encode({ 'some': 'payload', 'exp': datetime.datetime.utcnow() + datetime.timedelta(seconds=600)}, SECRET, algorithm='HS256' )
Python
nomic_cornstack_python_v1
from sys import stderr set t = integer input function search start origin cnt visited begin set cur = start set last = start while cur not in visited begin add visited cur if bff at cur == last begin set best = length visited comment We've looped back on ourselves! We can try to find another set (which is either self s...
from sys import stderr t = int(input()) def search(start, origin, cnt, visited): cur = last = start while cur not in visited: visited.add(cur) if bff[cur] == last: best = len(visited) # We've looped back on ourselves! We can try to find another set (which is eithe...
Python
zaydzuhri_stack_edu_python
comment ================================== comment Author: Gabriel Bartosch Caminha - gbcaminha@gmail.com comment ================================== string Package to deal with lens sub-halos import math import numpy as np from scipy.integrate import quad import functions as fu import constants as cs
# ================================== # Author: Gabriel Bartosch Caminha - gbcaminha@gmail.com # ================================== """ Package to deal with lens sub-halos """ import math import numpy as np from scipy.integrate import quad import functions as fu import constants as cs
Python
zaydzuhri_stack_edu_python
function get_tagged self tag **params begin return call get_all string api string tag string livsmedelsverket format string {}.json tag keyword params end function
def get_tagged(self, tag, **params): return self.get_all('api', 'tag', 'livsmedelsverket', '{}.json'.format(tag), **params)
Python
nomic_cornstack_python_v1
comment Create a Node class that has properties for the value stored in the Node, and a pointer to the next Node. class Node begin function __init__ self value next=none begin comment Assign data set value = value comment Initialize next as null set next = next end function end class comment Within your LinkedList clas...
# Create a Node class that has properties for the value stored in the Node, and a pointer to the next Node. class Node(): def __init__(self,value, next=None): self.value = value # Assign data self.next = next # Initialize next as null # Within your LinkedList class, include a head property. Upon...
Python
zaydzuhri_stack_edu_python
function post begin set errors = call check_voters_keys2 request if errors begin return call raise_error 400 format string Invalid {} key join string , errors end set details = call get_json set createdBy = details at string createdBy set office = details at string office set candidate = details at string candidate set...
def post(): errors = check_voters_keys2(request) if errors: return raise_error(400, "Invalid {} key".format(', '.join(errors))) details = request.get_json() createdBy = details['createdBy'] office = details['office'] candidate = details['candidate'] ...
Python
nomic_cornstack_python_v1
import json from base64 import b64encode , b64decode from Crypto.Cipher import AES from Crypto.Util.Padding import pad , unpad import time import argparse import string import filecmp from random import randint from utils_demo import * if __name__ == string __main__ begin set parser = call ArgumentParser description=st...
import json from base64 import b64encode, b64decode from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad import time import argparse import string import filecmp from random import randint from utils_demo import * if __name__ == "__main__": parser = argparse.ArgumentParser(descripti...
Python
zaydzuhri_stack_edu_python
comment docx 轉 html import mammoth function test1 begin set style_map = string p[style-name='heading 1'] => h1:fresh p[style-name^='Heading'] => h2:fresh p[style-name='Subtle Reference'] => em:fresh set docx_fiel = string C:\Users\user\Desktop\test.docx with open docx_fiel string rb as docx_file begin set result = call...
import mammoth # docx 轉 html def test1(): style_map = """ p[style-name='heading 1'] => h1:fresh p[style-name^='Heading'] => h2:fresh p[style-name='Subtle Reference'] => em:fresh """ docx_fiel = r'C:\Users\user\Desktop\test.docx' with open(docx_fiel, "rb") as docx_file: result = mam...
Python
zaydzuhri_stack_edu_python
string Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Try to solve it in linear time/space. Return 0 if the array contains less than 2 elements. You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range. class ...
""" Given an unsorted array, find the maximum difference between the successive elements in its sorted form. Try to solve it in linear time/space. Return 0 if the array contains less than 2 elements. You may assume all elements in the array are non-negative integers and fit in the 32-bit signed integer range. """ ...
Python
zaydzuhri_stack_edu_python
function __IP_to_str ip begin return call inet_ntop AF_INET ip end function
def __IP_to_str(ip): return socket.inet_ntop(socket.AF_INET, ip)
Python
nomic_cornstack_python_v1
function __init__ self begin set ci_swimming_lanes = list string services string releases set cdis_public_bucket_base_url = string https://cdistest-public-test-bucket.s3.amazonaws.com/ end function
def __init__(self): self.ci_swimming_lanes = ["services", "releases"] self.cdis_public_bucket_base_url = ( "https://cdistest-public-test-bucket.s3.amazonaws.com/" )
Python
nomic_cornstack_python_v1
function test_magmom convcell_cr begin set symprec = 1e-05 set symmetry_nonspin = call Symmetry convcell_cr symprec=symprec set atom_map_nonspin = call get_map_atoms set len_sym_nonspin = length symmetry_operations at string rotations set spin = list 1 - 1 set cell_withspin = copy convcell_cr set magnetic_moments = spi...
def test_magmom(convcell_cr: PhonopyAtoms): symprec = 1e-5 symmetry_nonspin = Symmetry(convcell_cr, symprec=symprec) atom_map_nonspin = symmetry_nonspin.get_map_atoms() len_sym_nonspin = len(symmetry_nonspin.symmetry_operations["rotations"]) spin = [1, -1] cell_withspin = convcell_cr.copy() ...
Python
nomic_cornstack_python_v1
function correct_horizontal_jittering projs omegas remove_bad_frames=true begin comment assume equal step, find the index range equals to 180 degree set dn = integer pi / omegas at 1 - omegas at 0 comment identify bad frames if necesary if remove_bad_frames begin set tuple _ idx_good = call detect_corrupted_proj projs ...
def correct_horizontal_jittering( projs: np.ndarray, omegas: np.ndarray, remove_bad_frames: bool=True, ) -> Tuple[np.ndarray, np.ndarray]: # assume equal step, find the index range equals to 180 degree dn = int(np.pi/(omegas[1] - omegas[0])) # identify bad frames if necesary if remove_b...
Python
nomic_cornstack_python_v1
comment A palindromic number reads the same both ways. The largest palindrome comment made from the product of two 2-digit numbers is 9009 = 91 * 99. comment Find the largest palindrome made from the product of two 3-digit numbers. assert list 1 2 3 at slice 1 : - 1 : == list 2 function is_palindrome n begin set s = s...
# A palindromic number reads the same both ways. The largest palindrome # made from the product of two 2-digit numbers is 9009 = 91 * 99. # Find the largest palindrome made from the product of two 3-digit numbers. assert [1,2,3][1:-1] == [2] def is_palindrome(n): s = str(n) while len(s) > 1: ...
Python
zaydzuhri_stack_edu_python
import pprint function show_state state ghost_pos=none begin string Show the state graphically, and the position of the ghost, if it is known set chars = dict string C string C ; string -C string 0 ; string NV string . set ss = list comprehension range 4 for _ in range 4 for s in state begin set tuple c i j = split s s...
import pprint def show_state(state, ghost_pos=None): """Show the state graphically, and the position of the ghost, if it is known""" chars = {'C': 'C', '-C': '0', 'NV': '.'} ss = [range(4) for _ in range(4)] for s in state: c, i, j = s.split('_') ss[int(i)...
Python
zaydzuhri_stack_edu_python
function api_rand self begin set obj = get call limit 1 return call object_detail obj end function
def api_rand(self): obj = self.model.select().where( self.model.disk_type << ['B'] ).order_by(fn.Rand()).limit(1).get() return self.object_detail(obj)
Python
nomic_cornstack_python_v1
function copy_filelink_tree self source_root dest_root overwrite=false followlinks=false begin set dodir = dodir set unlink = unlink set symlink = symlink if overwrite begin for tuple source dest relpath dirs files dirnames in call walk_copy_tree source_root dest_root followlinks=followlinks begin for tuple tuple sourc...
def copy_filelink_tree ( self, source_root, dest_root, overwrite=False, followlinks=False ): dodir = self.dodir unlink = self.unlink symlink = self.symlink if overwrite: for source, dest, relpath, dirs, files, dirnames in ( walk_copy_tree ( source_root, dest_roo...
Python
nomic_cornstack_python_v1
function backward self model_output target_vertices begin assert shape at 0 == shape at 0 set loss = call loss model_output target_vertices return loss end function
def backward(self, model_output, target_vertices): assert model_output.shape[0] == target_vertices.shape[0] loss = self.loss(model_output, target_vertices) return loss
Python
nomic_cornstack_python_v1
function draw_tile self begin if not selected begin call rect screen color rect end else begin call rect screen selected_color rect end if number or user_number begin call blit num_img num_img_rect end end function
def draw_tile(self): if not self.selected: pygame.draw.rect(self.screen, self.color, self.rect) else: pygame.draw.rect(self.screen, self.selected_color, self.rect) if self.number or self.user_number: self.screen.blit(self.num_img, self.num_img_rect)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import socket import sys set MSG_FASTOPEN = 536870912 set host = argv at 1 print format string connecting to host {} ... host set addr = tuple host 8080 set s = call socket AF_INET SOCK_STREAM comment 以 Fast Open 方式发送数据,不需要 connect call sendto string hello! MSG_FASTOPEN addr
#!/usr/bin/env python3 import socket import sys MSG_FASTOPEN = 0x20000000 host = sys.argv[1] print("connecting to host {} ...".format(host)) addr = (host, 8080) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 以 Fast Open 方式发送数据,不需要 connect s.sendto("hello!", MSG_FASTOPEN, addr)
Python
zaydzuhri_stack_edu_python
from textblob import TextBlob function sentiment_classifier sentence begin set sentiment_score = polarity if sentiment_score > 0 begin return string positive end else if sentiment_score < 0 begin return string negative end else begin return string neutral end end function
from textblob import TextBlob def sentiment_classifier(sentence): sentiment_score = TextBlob(sentence).sentiment.polarity if sentiment_score > 0: return 'positive' elif sentiment_score < 0: return 'negative' else: return 'neutral'
Python
jtatman_500k
comment !/usr/bin/env python comment coding=utf-8 import requests function googleproxy url begin set headers = dict string User-Agent string Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36 print string crawling : %s % encode url string utf-8 try begin set respon...
#!/usr/bin/env python # coding=utf-8 import requests def googleproxy(url): headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36' } print('crawling : %s' % url.encode('utf-8')) try: response = reques...
Python
zaydzuhri_stack_edu_python
import requests import bs4 from bs4 import BeautifulSoup class Product begin function __init__ self title price img begin set title = title set price = price set img = img end function end class function scrap query begin set url = string https://www.snapdeal.com/search set params = dict string keyword query set r = ge...
import requests import bs4 from bs4 import BeautifulSoup class Product: def __init__(self, title, price, img): self.title = title self.price = price self.img = img def scrap(query): url = "https://www.snapdeal.com/search" params = { "keyword" : query } r = re...
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt from numpy import linalg as LA import math function parab_gen y a begin set x = y ^ 2 / a return x end function comment setting up plot set fig = figure set ax = call add_subplot 111 aspect=string equal set len = 100 set y = linear space - 4 4 len comment parab paramet...
import numpy as np import matplotlib.pyplot as plt from numpy import linalg as LA import math def parab_gen(y,a): x=y**2/a return x #setting up plot fig = plt.figure() ax = fig.add_subplot(111, aspect='equal') len = 100 y = np.linspace(-4,4,len) #parab parameters V = np.array(([0,0],[0,1])) u = np.array(([-3...
Python
zaydzuhri_stack_edu_python
function solution nums begin set n = length nums set nums = list 1 + nums + list 1 set table = list comprehension list 0 * n + 2 for _ in range n + 2 for l in range 1 n + 1 begin for i in range 1 n - l + 2 begin set j = i + l - 1 for k in range i j + 1 begin set table at i at j = max table at i at j table at i at k - 1...
def solution(nums): n = len(nums) nums = [1] + nums + [1] table = [[0] * (n+2) for _ in range(n+2)] for l in range(1, n+1): for i in range(1, n-l+2): j = i+l-1 for k in range(i, j+1): table[i][j] = max(table[i][j], table[i...
Python
zaydzuhri_stack_edu_python
function change_one_dim_plot self index_val begin call give_plot index=index_val end function
def change_one_dim_plot(self, index_val): self.one_dim_plot.give_plot(index=index_val)
Python
nomic_cornstack_python_v1
import psycopg2 as pg import yaml from pathlib import Path import os import pandas as pd import configparser from config import * import sys import argparse import re function check_for_fhv_2017_type name files begin comment if months over 7+ cut list if name == string fhv_tripdata_2017 begin set files = list comprehen...
import psycopg2 as pg import yaml from pathlib import Path import os import pandas as pd import configparser from config import * import sys import argparse import re def check_for_fhv_2017_type(name, files): # if months over 7+ cut list if name == "fhv_tripdata_2017": files = [x for x in files if int(...
Python
zaydzuhri_stack_edu_python
function reveal_if_valid answer_matrix current_board x y begin if call is_valid_tile current_board x y and answer_matrix at x at y != string ! and current_board at x at y == string ? begin if answer_matrix at x at y == 0 begin set current_board at x at y = string call reveal_neighbors answer_matrix current_board x y e...
def reveal_if_valid(answer_matrix, current_board, x, y): if is_valid_tile(current_board, x, y) and answer_matrix[x][y] != '!' and current_board[x][y] == '?': if answer_matrix[x][y] == 0: current_board[x][y] = ' ' reveal_neighbors(answer_matrix, current_board, x, y) else: ...
Python
nomic_cornstack_python_v1
import sys import random from itertools import permutations function binary_digits n begin set res = list while n > 0 begin append res n % 2 set n = n / 2 end return res end function function MillerRabin n s=50 begin set b = call binary_digits n - 1 for _ in call xrange s begin set a = random integer 1 n - 1 set a = 6...
import sys import random from itertools import permutations def binary_digits(n): res = [] while n > 0: res.append(n % 2) n = n / 2 return res def MillerRabin(n, s = 50): b = binary_digits(n - 1) for _ in xrange(s): a = random.randint(1, n - 1) a = 6738399 d = 1 for i in xrange(len(b...
Python
zaydzuhri_stack_edu_python
if a <= 20 == true begin for i in range 1 a + 1 begin set f = f * i end print f end
if (a<=20)==True: for i in range (1,a+1): f=f*i print(f)
Python
zaydzuhri_stack_edu_python
from numpy import RankWarning from numpy import array from numpy import polyfit from numpy import zeros from numpy import poly1d from matplotlib import pyplot from datetime import datetime import warnings import random comment For all the numerical processing & graphin functions function avg someset rounded=true begin ...
from numpy import RankWarning from numpy import array from numpy import polyfit from numpy import zeros from numpy import poly1d from matplotlib import pyplot from datetime import datetime import warnings import random # For all the numerical processing & graphin functions def avg(someset, rounded=True): if round...
Python
zaydzuhri_stack_edu_python
import random function get_sample01 A s begin set A = random sample A s print A end function function get_sample02 A s begin for i in range s begin set r = random integer 0 length A - 1 set tuple A at i A at r = tuple A at r A at i end print A at slice : s : end function set A = list 0 1 2 3 4 5 6 7 8 9 call get_sampl...
import random; def get_sample01(A, s): A = random.sample(A, s); print(A) def get_sample02(A, s): for i in range(s): r = random.randint(0, len(A)-1); A[i], A[r] = A[r], A[i] print(A[:s]) A = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; get_sample01(A, 3); get_sample02(A, 3);
Python
zaydzuhri_stack_edu_python
comment Imports import pygame import random comment Initialize game engine call init comment Window set WIDTH = 800 set HEIGHT = 700 set SIZE = tuple WIDTH HEIGHT set TITLE = string Battle For Tortuga set screen = call set_mode SIZE call set_caption TITLE comment Timer set clock = call Clock set refresh_rate = 60 comme...
# Imports import pygame import random # Initialize game engine pygame.init() # Window WIDTH = 800 HEIGHT = 700 SIZE = (WIDTH, HEIGHT) TITLE = "Battle For Tortuga" screen = pygame.display.set_mode(SIZE) pygame.display.set_caption(TITLE) # Timer clock = pygame.time.Clock() refresh_rate = 60 # C...
Python
zaydzuhri_stack_edu_python
function Objective argument1 begin return call render_template argument1 end function
def Objective(argument1): return render_template(argument1)
Python
nomic_cornstack_python_v1
comment https://leetcode.com/problems/maximum-69-number/ class Solution begin function maximum69Number self num begin return integer replace string num string 6 string 9 1 end function end class if __name__ == string __main__ begin set X = call Solution print call maximum69Number 9669 end
# https://leetcode.com/problems/maximum-69-number/ class Solution: def maximum69Number(self, num): return int(str(num).replace('6', '9', 1)) if __name__ == "__main__": X = Solution() print( X.maximum69Number(9669) )
Python
zaydzuhri_stack_edu_python
function multiply x y begin set result = 0 for i in range y begin set result = result + x end return result end function function power x y begin set result = 1 for i in range y begin set result = result * x end return result end function
def multiply(x, y): result = 0 for i in range(y): result += x return result def power(x, y): result = 1 for i in range(y): result *= x return result
Python
jtatman_500k
class Solution begin function smallestMissingValueSubtree self parents nums begin set n = length parents set ans = list 1 * n set graph = list comprehension list for _ in range n set seen = set set minMiss = 1 for i in range 1 n begin append graph at parents at i i end function getNode nums begin for tuple i num in en...
class Solution: def smallestMissingValueSubtree(self, parents: List[int], nums: List[int]) -> List[int]: n = len(parents) ans = [1] * n graph = [[] for _ in range(n)] seen = set() minMiss = 1 for i in range(1, n): graph[parents[i]].append(i) def getNode(nums: List[int]) -> int: ...
Python
zaydzuhri_stack_edu_python
import math import random import turtle function main begin print call find_double_return 100 0.01 return_fixed_rate end function function encrypt_dist input_str=string example pos=1 begin comment to decrypt, use pos = -1 * pos_initial set normal_str = string abcdefghijklmnopqrtsuvwxyz set result = string for char in ...
import math import random import turtle def main(): print(find_double_return(100, 0.01, return_fixed_rate)) def encrypt_dist(input_str='example', pos=1): # to decrypt, use pos = -1 * pos_initial normal_str = 'abcdefghijklmnopqrtsuvwxyz ' result = '' for char in input_str: ...
Python
zaydzuhri_stack_edu_python
import sys import math function input_value input_msg error_msg=none is_int=true ran=tuple 1 0 begin while true begin try begin set value = if expression is_int then integer input input_msg else decimal input input_msg if ran at 0 > ran at 1 begin return value end if value < ran at 0 or value > ran at 1 begin raise exc...
import sys import math def input_value(input_msg, error_msg=None, is_int=True, ran=(1, 0)): while True: try: value = int(input(input_msg)) if is_int else float(input(input_msg)) if ran[0] > ran[1]: return value if value < ran[0] or value > ran[1]: ...
Python
zaydzuhri_stack_edu_python
function parse_prerequisites course_node begin set description = text if string Prereq: not in description begin return list end set parts = split split split description string Coreqs: at 0 string Prereq: at 1 string . if ends with parts at 0 string . begin set parts at 0 = parts at 0 at slice : - 1 : end set prere...
def parse_prerequisites(course_node): description = course_node.find_element_by_class_name( 'courseDescription').text if 'Prereq:' not in description: return [] parts = description.split('Coreqs:')[0].split('Prereq:')[1].split('. ') if parts[0].endswith('.'): parts[0] = parts[0][:-1] prerequis...
Python
nomic_cornstack_python_v1
function __str__ self begin return call getBooksString + string + call getPatronsString end function
def __str__(self): return self.getBooksString() + "\n" + self.getPatronsString()
Python
nomic_cornstack_python_v1
for i in range length ui begin set count = count + 1 if count % 3 == 1 begin print string | end=string end print ui at i end=string if count % 3 == 0 begin print string | end if ui at i == string X begin set x_count = x_count + 1 end else if ui at i == string O begin set o_count = o_count + 1 end end print string -----...
for i in range(len(ui)): count += 1 if count % 3 == 1: print("|", end=" ") print(ui[i], end=" ") if count % 3 == 0: print("|") if ui[i] == 'X': x_count += 1 elif ui[i] == 'O': o_count += 1 print("---------") def x_wins(): if ui[0] == ui[1] and ui[0] == ui[2]...
Python
zaydzuhri_stack_edu_python
function __send_post_request self parameters_dict begin return loads decode content string utf8 end function
def __send_post_request(self, parameters_dict): return json.loads(requests.post(self.__url, json=parameters_dict).content.decode("utf8"))
Python
nomic_cornstack_python_v1
import pickle import pandas import keras import numpy as np import matplotlib.pyplot as plt import os import cv2 import random function mostra img name=string Name begin set img1 = copy img set img1 = as type img1 uint8 call namedWindow name WINDOW_AUTOSIZE image show name img1 call waitKey 0 call destroyAllWindows end...
import pickle import pandas import keras import numpy as np import matplotlib.pyplot as plt import os import cv2 import random def mostra(img, name='Name'): img1 = img.copy() img1 = img1.astype(np.uint8) cv2.namedWindow(name, cv2.WINDOW_AUTOSIZE) cv2.imshow(name, img1) cv2.waitKey(0) cv2.des...
Python
zaydzuhri_stack_edu_python
import re set nodeKeys = list string nodeID string locationXY string shippingStatus string configurationStatus comment ensure the submitted node's properties are formatted validly function validateNode node checkID begin comment prevent setting projectName in order to use dedicated assignment logic and routes if string...
import re nodeKeys = ['nodeID', 'locationXY', 'shippingStatus', 'configurationStatus'] # ensure the submitted node's properties are formatted validly def validateNode(node, checkID): # prevent setting projectName in order to use dedicated assignment logic and routes if 'projectName' in node: ret...
Python
zaydzuhri_stack_edu_python
comment import requests comment from bs4 import BeautifulSoup as bs comment def download_pic(url, path): comment pic = requests.get(url) comment f = open(path, 'wb') comment f.write(pic.content) comment f.close() comment url = 'https://cdn.pixabay.com/photo/2015/06/08/15/02/pug-801826__340.jpg' comment pic_path = '/Use...
# import requests # from bs4 import BeautifulSoup as bs # def download_pic(url, path): # pic = requests.get(url) # f = open(path, 'wb') # f.write(pic.content) # f.close() # url = 'https://cdn.pixabay.com/photo/2015/06/08/15/02/pug-801826__340.jpg' # pic_path = '/Users/tobias/Desktop/未命名檔案夾/'+ url[url.r...
Python
zaydzuhri_stack_edu_python
import random set OXJudge = list string string string string string string string string string function DefaultField begin print string -------------- 1 | 2 | 3 ______________ 4 | 5 | 6 -------------- 7 | 8 | 9 -------------- end function function PrintResult begin global OXJudge print string -------------- %...
import random OXJudge = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] def DefaultField(): print(""" -------------- 1 | 2 | 3 ______________ 4 | 5 | 6 -------------- 7 | 8 | 9 -------------- """) def PrintResult(): global OXJudge print(""" ----...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import codecs import re from os import path from distutils.core import setup from setuptools import find_packages function read *parts begin return read open join path directory name path __file__ *parts encoding=string utf-8 end function function find_version *file_paths begin set version...
# -*- coding: utf-8 -*- import codecs import re from os import path from distutils.core import setup from setuptools import find_packages def read(*parts): return codecs.open(path.join(path.dirname(__file__), *parts), encoding='utf-8').read() def find_version(*file_paths): version_fil...
Python
jtatman_500k
from sklearn.decomposition import PCA function cal_pca traj n_components begin string traj: mdtraj.Trajectory n_components: int, number of pc to output return projections on pc set pca = principal component analysis n_components=n_components call superpose traj 0 set reduced_cartesian = fit transform pca reshape xyz n_...
from sklearn.decomposition import PCA def cal_pca(traj, n_components): """ traj: mdtraj.Trajectory n_components: int, number of pc to output return projections on pc """ pca = PCA(n_components = n_components) traj.superpose(traj, 0) reduced_cartesian = pca.fit_transform(traj.xyz...
Python
zaydzuhri_stack_edu_python
import requests import json import argparse import traceback import re class AuthError extends Exception begin pass end class set parser = call ArgumentParser description=string Check health of an Elasticsearch host. If --node is specified, check health of the node instead. call add_argument string -H string --host req...
import requests import json import argparse import traceback import re class AuthError(Exception): pass parser = argparse.ArgumentParser(description='Check health of an Elasticsearch host. If --node is specified, check health of the node instead.') parser.add_argument('-H', '--host', required=True, help='The Elas...
Python
zaydzuhri_stack_edu_python
import random import requests import math import matplotlib.pyplot as plt comment last updated 9/6/14 class WinRateCalculator extends object begin set base_url = string https://api.worldoftanks.com/wot/ set application_id = string insert application id here set account_id = string set wins = 0.0 set losses = 0.0 set b...
import random import requests import math import matplotlib.pyplot as plt # last updated 9/6/14 class WinRateCalculator(object): base_url = 'https://api.worldoftanks.com/wot/' application_id = 'insert application id here' account_id = '' wins = 0.0 losses = 0.0 battles = 0.0 win_rate = 0.0 g...
Python
zaydzuhri_stack_edu_python
function _create_mapping self begin set data = call get_simple movieglu_base movieglu_search movie_name query_text n=15 headers=movieglu_headers set rtr = none set films = get data string films if films is none begin return dict string moviedb_id query ; string movieglu_id rtr ; string imdb_id imdb_id end for film in f...
def _create_mapping(self): data = SimpleGetter.get_simple(self.movieglu_base, self.movieglu_search,\ self.movie_name, self.query_text, n=15, headers=self.movieglu_headers) rtr = None films = data.get('films') if films is None: return {'moviedb_id': self.qu...
Python
nomic_cornstack_python_v1
function __init__ self c num_classes begin call __init__ set features = sequential relu inplace=true call AvgPool2d 5 stride=3 padding=0 count_include_pad=false conv 2d c 128 1 bias=false call BatchNorm2d 128 relu inplace=true conv 2d 128 768 2 bias=false call BatchNorm2d 768 relu inplace=true comment after avgpool ima...
def __init__(self, c, num_classes): super(AuxiliaryHead, self).__init__() self.features = nn.Sequential( nn.ReLU(inplace=True), # after avgpool image size is 2x2 nn.AvgPool2d(5, stride=3, padding=0, count_include_pad=False), nn.Conv2d(c, 128, 1, bias...
Python
nomic_cornstack_python_v1
comment 1: 1 comment 2: 1 1 comment 3: 1 2 1 comment 4: 1 3 3 1 class Solution extends object begin function getRow self rowIndex begin set row = list 0 * rowIndex + 1 set row at 0 = 1 for i in range rowIndex + 1 begin set prev = 0 for j in range i + 1 begin set tmp = row at j set row at j = row at j + prev set prev = ...
# 1: 1 # 2: 1 1 # 3: 1 2 1 # 4: 1 3 3 1 class Solution(object): def getRow(self, rowIndex): row = [0] * (rowIndex + 1) row[0] = 1 for i in range(rowIndex + 1): prev = 0 for j in range(i+1): tmp = row[j] row[j] += prev ...
Python
zaydzuhri_stack_edu_python
function generate_report_path report_name report_extension=string csv begin return join path REPORT_DIRECTORY string { report_name } _ { DATESTAMP } . { report_extension } end function
def generate_report_path(report_name: str, report_extension: str = "csv") -> str: return os.path.join(REPORT_DIRECTORY, f"{report_name}_{DATESTAMP}.{report_extension}")
Python
nomic_cornstack_python_v1
string Definition for a point. class Point: def __init__(self, a=0, b=0): self.x = a self.y = b from collections import deque class Solution begin string @param grid: a chessboard included 0 (false) and 1 (true) @param source: a point @param destination: a point @return: the shortest path function shortestPath self gri...
""" Definition for a point. class Point: def __init__(self, a=0, b=0): self.x = a self.y = b """ from collections import deque class Solution: """ @param grid: a chessboard included 0 (false) and 1 (true) @param source: a point @param destination: a point @return: the shortest pa...
Python
zaydzuhri_stack_edu_python
function softplus x begin return log 1.0 + exp x end function
def softplus(x): return tf.log(1.0 + tf.exp(x))
Python
nomic_cornstack_python_v1
import codecs import sys set error_handling = argv at 1 set text = string français print string Original : text with open string decode_error.txt mode=string w encoding=string utf-16 as f begin write f text end with open string decode_error.txt string r encoding=string utf-8 errors=error_handling as f begin try begin s...
import codecs import sys error_handling = sys.argv[1] text = 'français' print('Original :', text) with codecs.open('decode_error.txt', mode='w', encoding='utf-16') as f: f.write(text) with open('decode_error.txt', 'r', encoding='utf-8', errors=error_handling) as f: try: data = f.read() excep...
Python
zaydzuhri_stack_edu_python
function copyFilesOfPattern patterns=list string * sourceDir=string ./ destDir=string ./copyFolder begin import os import shutil import re for filename in list directory sourceDir begin for pattern in patterns begin if match pattern filename begin copy shutil filename destDir end end end end function
def copyFilesOfPattern(patterns=['*'], sourceDir='./', destDir='./copyFolder'): import os import shutil import re for filename in os.listdir(sourceDir): for pattern in patterns: if re.match(pattern, filename): shutil.copy(filename, destDir)
Python
nomic_cornstack_python_v1
comment Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. comment Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. comment Note: comment You are not sup...
# Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. # Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. # Note: # You are not suppose to use the librar...
Python
zaydzuhri_stack_edu_python
function get_chessboard_corners_in3d self begin set depth_frame = call post_process_depth_frame frames at depth set depth_intrinsics = intrinsic at depth set infrared_frame = frames at color set tuple found_corners points2D = call cv_find_chessboard depth_frame infrared_frame chessboard_params if found_corners begin se...
def get_chessboard_corners_in3d(self): depth_frame = post_process_depth_frame(self.frames[rs.stream.depth]) depth_intrinsics = self.intrinsic[rs.stream.depth] infrared_frame = self.frames[rs.stream.color] found_corners, points2D = cv_find_chessboard(depth_frame, infrared_frame, self.chessboard_params) if foun...
Python
nomic_cornstack_python_v1
function outputSpikeCounts outfile infile_name expression_nbins=none fold_nbins=none expression_bins=none fold_bins=none begin set df = read csv infile_name sep=string index_col=0 debug string read %i rows and %i columns of data % shape if string edger in lower outfile begin comment edger: treatment_mean and control_m...
def outputSpikeCounts(outfile, infile_name, expression_nbins=None, fold_nbins=None, expression_bins=None, fold_bins=None): df = pandas.read_csv(infile_name, sep="\t", index_col=...
Python
nomic_cornstack_python_v1
comment Faça um Programa que leia 4 notas, mostre as notas e a média na tela. set notas = list set soma = 0 for i in range 0 4 begin set x = integer input string Insira a nota: append notas x set soma = soma + x end print notas set media = soma / length notas print string Media: %.2f % media
#Faça um Programa que leia 4 notas, mostre as notas e a média na tela. notas = [] soma = 0 for i in range(0,4): x = int(input("Insira a nota: ")) notas.append(x) soma = soma + x print(notas) media = soma /len(notas) print("Media: %.2f"%(media))
Python
zaydzuhri_stack_edu_python
function index_to_letter idx begin if 0 <= idx < 20 begin return character 97 + idx end else begin raise call ValueError string A wrong idx value supplied. end end function
def index_to_letter(idx): if 0 <= idx < 20: return chr(97 + idx) else: raise ValueError('A wrong idx value supplied.')
Python
nomic_cornstack_python_v1
function clean_whitespace statement begin string Remove any consecutive whitespace characters from the statement text. import re comment Replace linebreaks and tabs with spaces set text = replace replace replace text string string string string string string comment Remove any leeding or trailing whitespace set text...
def clean_whitespace(statement): """ Remove any consecutive whitespace characters from the statement text. """ import re # Replace linebreaks and tabs with spaces statement.text = statement.text.replace('\n', ' ').replace('\r', ' ').replace('\t', ' ') # Remove any leeding or trailing white...
Python
jtatman_500k
function stop_accel self begin set _accel_callback = none call send_sysex CP_COMMAND list CP_ACCEL_STREAM_OFF end function
def stop_accel(self): self._accel_callback = None self._command_handler.send_sysex(CP_COMMAND, [CP_ACCEL_STREAM_OFF])
Python
nomic_cornstack_python_v1
function read_data_files self radar_dir begin set pattern = pattern set file_counter = 0 set first = true set rain_max_in_period = 0.0 set precips = list set times = list set reverse = false set radar_dir = radar_dir end function
def read_data_files(self, radar_dir): pattern = self.pattern file_counter = 0 first = True rain_max_in_period = 0.0 precips = [] times = [] reverse = False self.radar_dir = radar_dir
Python
nomic_cornstack_python_v1
import os from pathlib import Path from os import path import shutil comment creates a dictionary of the environment variables set environ_variables = dictionary environ comment current path to build file path string set path = expand user path get current directory comment creates directory path string set directory_p...
import os from pathlib import Path from os import path import shutil environ_variables = dict(os.environ) # creates a dictionary of the environment variables path = os.path.expanduser(os.getcwd())#current path to build file path string directory_path = os.path.join(path, 'os_information') #creates directory path ...
Python
zaydzuhri_stack_edu_python
function __init__ __self__ type additional_columns=none disable_metrics_collection=none max_concurrent_connections=none query=none query_timeout=none source_retry_count=none source_retry_wait=none begin set __self__ string type string MySqlSource if additional_columns is not none begin set __self__ string additional_co...
def __init__(__self__, *, type: str, additional_columns: Optional[Any] = None, disable_metrics_collection: Optional[Any] = None, max_concurrent_connections: Optional[Any] = None, query: Optional[Any] = None, query_time...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Wed Jan 8 23:23:14 2020 @author: hkish from google sheets to pandas dataframe set COM_PORT = string COM13 from Google_api_function_2 import Create_Service import pandas as pd import matplotlib.pyplot as plt import numpy as np import serial from time import sleep set CLIEN...
# -*- coding: utf-8 -*- """ Created on Wed Jan 8 23:23:14 2020 @author: hkish from google sheets to pandas dataframe """ COM_PORT = 'COM13' from Google_api_function_2 import Create_Service import pandas as pd import matplotlib.pyplot as plt import numpy as np import serial from time import sleep ...
Python
zaydzuhri_stack_edu_python
from typing import List class Solution begin function __init__ self slate n begin set slate = slate set n = n end function function cutting self i j ni nj direction begin for ii in range i i + ni begin for jj in range j j + nj begin print slate at ii at jj end=string end print end print string -------------------- comm...
from typing import List class Solution: def __init__(self, slate: List[List[int]], n: int): self.slate = slate self.n = n def cutting(self, i: int, j: int, ni: int, nj: int, direction: int): for ii in range(i, i + ni): for jj in range(j, j + nj): p...
Python
zaydzuhri_stack_edu_python
function test_api_expires_char_corp self mock_api begin set return_value = TEST_RESULTS at string full_expires at string char_corp assert false call is_valid assert equal call count_keys_in_database 1 end function
def test_api_expires_char_corp(self, mock_api): mock_api.return_value = TEST_RESULTS['full_expires']['char_corp'] self.assertFalse(self.form().is_valid()) self.assertEqual(self.count_keys_in_database(), 1)
Python
nomic_cornstack_python_v1
function name begin return string project-show end function
def name() -> str: return "project-show"
Python
nomic_cornstack_python_v1
function main begin set builder = call Builder call add_from_file string mattashii_ui/UI.glade set handlers = call handlers call connect_signals handlers set window = call get_object string mattashii_main call show_all call main end function
def main(): builder = Gtk.Builder() builder.add_from_file("mattashii_ui/UI.glade") handlers = models.handlers() builder.connect_signals(handlers) window = builder.get_object("mattashii_main") window.show_all() Gtk.main()
Python
nomic_cornstack_python_v1
string MAIN FILE :: EXPOSURE FUSION Abdulmajeed Muhammad Kabir This is the main file to run Exposure fusion using exposureFusion.py as library import exposureFusion_ as ef call launch string Load Input Images and Setup Dirs comment ------------------------------------------------------------------------------# set path...
############################################################################## """ MAIN FILE :: EXPOSURE FUSION Abdulmajeed Muhammad Kabir This is the main file to run Exposure fusion using exposureFusion.py as library """ import exposureFusion_ as ef ef.launch() "Load Input Images and Setup Dirs" ...
Python
zaydzuhri_stack_edu_python
function connect begin try begin set _db_conn = call connect host=string 192.138.0.132 database=string temperature user=string root password=string B3nmal!gn312 if call is_connected begin print string Connected to MySQL database set _db_cursor = call cursor end end except any begin print string Could not connect to Dat...
def connect(): try: _db_conn = mysql.connector.connect(host='192.138.0.132', database='temperature', user='root', password='B3nmal!gn312') if _db_conn.is_connected(): ...
Python
nomic_cornstack_python_v1
string https://www.cnblogs.com/linyx/p/4066019.html https://www.geeksforgeeks.org/serialize-deserialize-binary-tree/ class TreeNode begin function __init__ self x begin set val = x set left = none set right = none end function end class function serialize root res begin if not root begin return end append res val if le...
""" https://www.cnblogs.com/linyx/p/4066019.html https://www.geeksforgeeks.org/serialize-deserialize-binary-tree/ """ class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def serialize(root, res): if not root: return res.append(root.val)...
Python
zaydzuhri_stack_edu_python
function get_cleaned_string string_data begin set string_data = replace strip string_data string - string set string_data = replace strip string_data string — string set string_data = replace string_data string string set string_data = replace string_data string .?) string .3 set string_data = strip string_data string...
def get_cleaned_string(string_data): string_data = string_data.strip().replace('-\n', '') string_data = string_data.strip().replace('—\n', '') string_data = string_data.replace('\n', ' ') string_data = string_data.replace('.?)', '.3') string_data = string_data.strip(' \n,') return string_data
Python
nomic_cornstack_python_v1
function project_svd_modes self dfft umodes=none svals=none vmodes=none begin set output = call DataContainer dict if umodes is none begin assert svals is not none and vmodes is not none msg string Must feed two of the SVD output matrices comment compute umodes for k in dfft begin if k not in svals or k not in vmodes b...
def project_svd_modes(self, dfft, umodes=None, svals=None, vmodes=None): output = DataContainer({}) if umodes is None: assert svals is not None and vmodes is not None, "Must feed two of the SVD output matrices" # compute umodes for k in dfft: if k not ...
Python
nomic_cornstack_python_v1
comment 다음과 같이 문장을 구성하는 단어를 역순으로 출력하는 프로그램을 작성하십시오. comment 입력 : A better tomorrow comment 출력 : tomorrow better A comment 1. 입력 받을 input 변수를 만들어보자 comment 2. 문장을 split으로 쪼개고 뒤집고 str로 출력하자 set lett = input string set lis = split lett string reverse lis for i in lis begin print i end=string end
# 다음과 같이 문장을 구성하는 단어를 역순으로 출력하는 프로그램을 작성하십시오. # 입력 : A better tomorrow # 출력 : tomorrow better A # 1. 입력 받을 input 변수를 만들어보자 # 2. 문장을 split으로 쪼개고 뒤집고 str로 출력하자 lett = input("") lis = lett.split(" ") lis.reverse() for i in lis: print(i, end= " ")
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3.9 print string Content-Type: text/html string データをmysqlに登録するプログラム import MySQLdb , sys import hashlib set a = read line stdin comment a = open("data.json") set receive = loads a set connection = call connect host=string localhost user=string root passwd=string db=string onlinetest set cursor ...
#!/usr/bin/python3.9 print('Content-Type: text/html\n') """ データをmysqlに登録するプログラム """ import MySQLdb, sys import hashlib a = sys.stdin.readline() #a = open("data.json") receive = json.loads(a) connection = MySQLdb.connect( host='localhost', user='root', passwd='', db='onlinetest') cursor = connection.cur...
Python
zaydzuhri_stack_edu_python
comment Create the areas list set areas = list string hallway 11.25 string kitchen 18.0 string living room 20.0 string bedroom 10.75 string bathroom 9.5 comment Use slicing to create downstairs set downstairs = areas at slice 0 : 6 : comment Use slicing to create upstairs set upstairs = areas at slice 6 : 10 : commen...
# Create the areas list areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50] # Use slicing to create downstairs downstairs = areas[0:6] # Use slicing to create upstairs upstairs = areas[6:10] # Print out downstairs and upstairs print(downstairs) print(upstairs) # Alte...
Python
zaydzuhri_stack_edu_python
function __getitem__ self item begin if is instance item str begin for tuple name data_container in sub_data_containers begin if name == item begin return data_container end end raise call KeyError format string sub_data_container {} not found in data container item end else begin if current_ids is none begin set curre...
def __getitem__(self, item: Union[str, int]): if isinstance(item, str): for name, data_container in self.sub_data_containers: if name == item: return data_container raise KeyError("sub_data_container {} not found in data container".format(item)) ...
Python
nomic_cornstack_python_v1
function run_pip initial_args begin set status_code = call main initial_args comment Clear out the registrations in the pip "logger" singleton. Otherwise, comment loggers keep getting appended to it with every run. Pip assumes only one comment command invocation will happen per interpreter lifetime. set consumers = lis...
def run_pip(initial_args): status_code = pip.main(initial_args) # Clear out the registrations in the pip "logger" singleton. Otherwise, # loggers keep getting appended to it with every run. Pip assumes only one # command invocation will happen per interpreter lifetime. logger.consumers = [] if...
Python
nomic_cornstack_python_v1
import speech_recognition as sr import os import sys import webbrowser function talk words begin print words call system string say + words end function function command begin set r = call Recognizer with call Microphone as source begin print string Speak.... set pause_threshold = 1 call adjust_for_ambient_noise source...
import speech_recognition as sr import os import sys import webbrowser def talk(words): print(words) os.system("say " + words) def command(): r = sr.Recognizer() with sr.Microphone() as source: print("Speak....") r.pause_threshold = 1 r.adjust_for_ambient_noise(source, durat...
Python
zaydzuhri_stack_edu_python
function test_xpath_ellipse_svg self begin set id = string ellipse set cx = call xpath string .//svg:ellipse[@id="%s"]/@cx % id namespaces=ns assert equal cx at 0 string 301.42856 string Doesn't read the tag end function
def test_xpath_ellipse_svg(self): id = "ellipse" cx = self.a1.C.xpath('.//svg:ellipse[@id="%s"]/@cx' % id,namespaces=self.a1.ns) self.assertEqual(cx[0], "301.42856","Doesn't read the tag")
Python
nomic_cornstack_python_v1
function assert_shapes_compatible lhs rhs begin comment This is a stricter-than-necessary check for broadcast-comptability, comment but it's error-prone to allow broadcasting to insert new dimensions so comment we don't allow that. if length lhs != length rhs begin return false end for tuple lhs_dim rhs_dim in zip lhs ...
def assert_shapes_compatible(lhs, rhs): # This is a stricter-than-necessary check for broadcast-comptability, # but it's error-prone to allow broadcasting to insert new dimensions so # we don't allow that. if len(lhs) != len(rhs): return False for lhs_dim, rhs_dim in zip(lhs, rhs): # A dimension of ...
Python
nomic_cornstack_python_v1
class ReverseString begin function __init__ self string begin set string = string end function function reverse self begin set splittedString = split string string set reversedString = list for word in splittedString begin insert reversedString 0 word end set reversedString = join string reversedString return reverse...
class ReverseString(): def __init__(self, string): self.string = string def reverse(self): splittedString = self.string.split(' ') reversedString = [] for word in splittedString: reversedString.insert(0, word) reversedString = ' '.join(reversedString...
Python
jtatman_500k
import heapq class PriorityQueue begin function __init__ self begin set heap = list end function function insert self value begin call heappush heap - value end function function deleteMax self begin if heap begin return - call heappop heap end else begin raise call IndexError string Priority queue is empty end end fu...
import heapq class PriorityQueue: def __init__(self): self.heap = [] def insert(self, value): heapq.heappush(self.heap, -value) def deleteMax(self): if self.heap: return -heapq.heappop(self.heap) else: raise IndexError("Priority queue is emp...
Python
greatdarklord_python_dataset