code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment Fibonacci array
comment recursion version
function fab max
begin
set result = list
set tuple n a b = tuple 0 0 1
while n < max
begin
append result b
set tuple a b = tuple b a + b
set n = n + 1
end
return result
end function
comment generator version
function fabG max
begin
set tuple n a b = tuple 0 0 1
while n... | # Fibonacci array
# recursion version
def fab(max):
result = []
n, a, b = 0, 0, 1
while n < max:
result.append(b)
a, b = b, a + b
n = n + 1
return result
# generator version
def fabG(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
if __name__ == '__main__':
print(fab(5))
... | Python | zaydzuhri_stack_edu_python |
function satisfied_condition self inputs
begin
return call calculate_fitness tree inputs path query_str field_args_dict at 1 == state
end function | def satisfied_condition(self, inputs: list):
return calculate_fitness(self.tree, inputs, self.path, self.query_str, self.field_args_dict)[1] == self.state | Python | nomic_cornstack_python_v1 |
function featurize self tokens
begin
if not is instance tokens list
begin
set tokens = list tokens
end
set lemmata = call lookup tokens
set fixed_lemmata = list
for lemma in lemmata
begin
set lem_lemmata = list comprehension lem at 0 for lem in lemma at 1
append fixed_lemmata lem_lemmata
end
set grams = call trigrammi... | def featurize(self, tokens):
if not isinstance(tokens, list):
tokens = [tokens]
lemmata = self.lemmatizer.lookup(tokens)
fixed_lemmata = []
for lemma in lemmata:
lem_lemmata = [lem[0] for lem in lemma[1]]
fixed_lemmata.append(lem_lemmata)
gram... | Python | nomic_cornstack_python_v1 |
function track R P T L B neighbor_lists
begin
import numpy as np
comment Find the neighborhood N for point P in R:
set N = neighbor_lists at P
set N = list intersection call frozenset N R
print string N N
if N
begin
comment Remove N from R:
set R = list difference call frozenset R N
comment For each neighborhood vertex... | def track(R, P, T, L, B, neighbor_lists):
import numpy as np
# Find the neighborhood N for point P in R:
N = neighbor_lists[P]
N = list(frozenset(N).intersection(R))
print('N', N)
if N:
# Remove N from R:
R = list(frozenset(R).difference(N))
# For each neighborhood ve... | Python | nomic_cornstack_python_v1 |
function store_remote_response incoming_event default_max_size config_keys
begin
call write_error string Starting store_remote_response
set event = deep copy incoming_event
set replace_config = get event string ReplaceConfig none
if not replace_config
begin
return event
end
comment Set default value if FullMessage flag... | def store_remote_response(incoming_event, default_max_size, config_keys):
write_error('Starting store_remote_response')
event = deepcopy(incoming_event)
replace_config = event.get('ReplaceConfig', None)
if not replace_config:
return event
# Set default value if FullMessage flag set
if re... | Python | nomic_cornstack_python_v1 |
function centuryFromYear year
begin
if year % 100 != 0
begin
return year // 100 + 1
end
else
begin
return year // 100
end
end function | def centuryFromYear(year):
if (year%100)!=0:
return ((year//100)+1)
else:
return((year//100))
| Python | zaydzuhri_stack_edu_python |
import openpyxl
function get_row_count file sheetName
begin
set workbook = call load_workbook file
set sheet = workbook at sheetName
return max_row
end function
function get_column_count file sheetName
begin
set workbook = call load_workbook file
set sheet = workbook at sheetName
return max_column
end function
function... | import openpyxl
def get_row_count(file,sheetName):
workbook = openpyxl.load_workbook(file)
sheet = workbook[sheetName]
return(sheet.max_row)
def get_column_count(file,sheetName):
workbook = openpyxl.load_workbook(file)
sheet = workbook[sheetName]
return(sheet.max_column)
def read_... | Python | zaydzuhri_stack_edu_python |
function highlight_faces image faces output_filename
begin
set im = call highlight_polygons image faces
save output_filename
end function | def highlight_faces(image, faces, output_filename):
im = highlight_polygons(image, faces)
im.save(output_filename) | Python | nomic_cornstack_python_v1 |
function test_transmogrify_met
begin
set val_one = call GenericArgs
set val_two = call GenericArgs
set sourcerpm = string foo-1.2-1.src.rpm
set epoch = 0
set name = string foo
set version = string 1.2
set release = string 1
set sourcerpm = string test-0.3-4.src.rpm
set epoch = 1
set name = string test
set version = str... | def test_transmogrify_met():
val_one = GenericArgs()
val_two = GenericArgs()
val_one.sourcerpm = 'foo-1.2-1.src.rpm'
val_one.epoch = 0
val_one.name = 'foo'
val_one.version = '1.2'
val_one.release = '1'
val_two.sourcerpm = 'test-0.3-4.src.rpm'
val_two.epoch = 1
val_two.name = 't... | Python | nomic_cornstack_python_v1 |
from reportlab.graphics.shapes import *
from reportlab.graphics.charts.linecharts import HorizontalLineChart
from reportlab.platypus import SimpleDocTemplate
set story = list
set drawing = call Drawing 400 200
set data = list tuple 13 5 20 22 37 45 19 4 tuple 5 20 46 38 23 21 6 14
set lc = call HorizontalLineChart
set... | from reportlab.graphics.shapes import *
from reportlab.graphics.charts.linecharts import HorizontalLineChart
from reportlab.platypus import SimpleDocTemplate
story = []
drawing = Drawing(400, 200)
data = [
(13, 5, 20, 22, 37, 45, 19, 4),
(5, 20, 46, 38, 23, 21, 6, 14)
]
lc = Horizontal... | Python | zaydzuhri_stack_edu_python |
function clicked_btn_of_grid_factory self idx_row idx_col
begin
return lambda -> call clicked_btn_of_grid idx_row idx_col
end function | def clicked_btn_of_grid_factory(self, idx_row, idx_col):
return lambda: self.clicked_btn_of_grid(idx_row, idx_col) | Python | nomic_cornstack_python_v1 |
function __init__ self state_size action_size hidden_layers seed=123 buffer_size=BUFFER_SIZE batch_size=BATCH_SIZE gamma=GAMMA tau=TAU lr=LR update_every=UPDATE_EVERY
begin
set state_size = state_size
set action_size = action_size
set hidden_layers = hidden_layers
set model_id = join string _ list comprehension string ... | def __init__(self,
state_size,
action_size,
hidden_layers: List[int],
seed: int = 123,
buffer_size: int = BUFFER_SIZE,
batch_size: int = BATCH_SIZE,
gamma: int = GAMMA,
tau: int = TAU,... | Python | nomic_cornstack_python_v1 |
function decrypt_message encoded_encrypted_msg privatekey
begin
set decoded_encrypted_msg = base64 decode encoded_encrypted_msg
set decryptor = call new privatekey
set decoded_decrypted_msg = call decrypt call literal_eval string decoded_encrypted_msg
return decoded_decrypted_msg
end function | def decrypt_message(encoded_encrypted_msg, privatekey):
decoded_encrypted_msg = base64.b64decode(encoded_encrypted_msg)
decryptor = PKCS1_OAEP.new(privatekey)
decoded_decrypted_msg = decryptor.decrypt(ast.literal_eval(str(decoded_encrypted_msg)))
return decoded_decrypted_msg | Python | nomic_cornstack_python_v1 |
function _test_call_check likelihood latent_mean latent_cov latent_dist
begin
raise NotImplementedError
end function | def _test_call_check(likelihood, latent_mean, latent_cov, latent_dist):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function newMenuItem restaurant_id
begin
if method == string POST
begin
set newItem = call MenuItem name=form at string name description=form at string description price=form at string price course=form at string course restaurant_id=restaurant_id
add session newItem
commit session
call flash string Menu Item Created
r... | def newMenuItem(restaurant_id):
if request.method == 'POST':
newItem = MenuItem(name = request.form['name'], description = request.form['description'], price = request.form['price'], course = request.form['course'], restaurant_id = restaurant_id)
session.add(newItem)
session.commit()
flash("Menu Item... | Python | nomic_cornstack_python_v1 |
function to_basic_block self
begin
return call pthread_sptr_to_basic_block self
end function | def to_basic_block(self):
return _pthread_swig.pthread_sptr_to_basic_block(self) | Python | nomic_cornstack_python_v1 |
function __close_archive model_context
begin
set _method_name = string __close_archive
call entering _class_name=_class_name method_name=_method_name
set archive_file = call get_archive_file
if archive_file
begin
close archive_file
end
call exiting class_name=_class_name method_name=_method_name
return
end function | def __close_archive(model_context):
_method_name = '__close_archive'
__logger.entering(_class_name=_class_name, method_name=_method_name)
archive_file = model_context.get_archive_file()
if archive_file:
archive_file.close()
__logger.exiting(class_name=_class_name, method_name=_method_name)
... | Python | nomic_cornstack_python_v1 |
function _get_vm_current_snapshot_mor self vm_moid
begin
set snap_mor = none
try
begin
set vm_mor = call get_vm_mor vm_moid
set snap_moid = _moId
set snap_mor = call get_vm_snapshot_mor_by_moid vm_mor snap_moid
end
except Exception as ex
begin
exception ex
raise exception string Get current snapshot mor of the VM error... | def _get_vm_current_snapshot_mor(self, vm_moid):
snap_mor = None
try:
vm_mor = self.get_vm_mor(vm_moid)
snap_moid = vm_mor.snapshot.currentSnapshot._moId
snap_mor = s_utils.get_vm_snapshot_mor_by_moid(vm_mor, snap_moid)
except Exception as ex:
LOG.... | Python | nomic_cornstack_python_v1 |
function flipImage self
begin
if playerState not in list SWINGING HITTING_PLAYER_SWINGING or call isTurningOrthogonally
begin
if facingDirection == LEFT
begin
set image = call flip image true false
end
else
if facingDirection == UP
begin
set image = call flip image false true
end
end
end function | def flipImage(self):
if self.playerState not in [c.PlayerStates.SWINGING, c.PlayerStates.HITTING_PLAYER_SWINGING] or\
self.isTurningOrthogonally():
if self.facingDirection == c.Directions.LEFT:
self.image = pg.transform.flip(self.image, True, False)
elif s... | Python | nomic_cornstack_python_v1 |
from collections import defaultdict
import logging
import random
from top_covering import largest_scc_from_pref
call basicConfig format=string %(asctime)s [%(levelname)s] %(message)s level=INFO
function votes_to_likes_tables votes
begin
set likes = default dictionary list
for row in votes
begin
set for_group = list
se... | from collections import defaultdict
import logging
import random
from top_covering import largest_scc_from_pref
logging.basicConfig(format='%(asctime)s [%(levelname)s] %(message)s',
level=logging.INFO)
def votes_to_likes_tables(votes):
likes = defaultdict(list)
for row in votes:
... | Python | zaydzuhri_stack_edu_python |
string Package to obtain the options pricing from yahoo finance URL: https://finance.yahoo.com/q/op?s=GOOG+Options Dependencies: python-pandas GitHub: git clone https://github.com/pydata/pandas
from pandas.io.data import Options
class YahooOptionPricing
begin
function __init__ self
begin
pass
end function
function __de... | '''
Package to obtain the options pricing from yahoo finance
URL: https://finance.yahoo.com/q/op?s=GOOG+Options
Dependencies:
python-pandas
GitHub:
git clone https://github.com/pydata/pandas
'''
from pandas.io.data import Options
class YahooOptionPricing:
def __init__(self):
pass
def __del__(self):
pa... | Python | zaydzuhri_stack_edu_python |
comment Brian Wolfe Created: 11/15/2020
comment Creates main dictionary
set candidates = dict
function display_instructions
begin
print string Enter the last name of 3 candidates followed by the total number of votes they received.
end function
function display_header
begin
print format string {:-<40} string
print for... | # Brian Wolfe Created: 11/15/2020
candidates = {} # Creates main dictionary
def display_instructions():
print("Enter the last name of 3 candidates followed by the total number of votes they received.")
def display_header():
print("{:-<40}".format(""))
print("{:^40}".format("Final ... | Python | zaydzuhri_stack_edu_python |
import datetime
from django.test import TestCase
from django.utils import timezone
from core.models import Post , EMPTY_EMPLOYEE , Employee
class PostModelTests extends TestCase
begin
function test_was_published_in_future self
begin
set time = now
set future_question = post date_posted=time
set true = false
if date_pos... | import datetime
from django.test import TestCase
from django.utils import timezone
from core.models import Post, EMPTY_EMPLOYEE, Employee
class PostModelTests(TestCase):
def test_was_published_in_future(self):
time = timezone.now()
future_question = Post(date_posted=time)
true = False
... | Python | zaydzuhri_stack_edu_python |
from veiculo import Veiculo
from carro import Carro
set v1 = call Veiculo string rosa 4 string ford 12
print v1
print type v1
call abastecer 234
print tanque
set car1 = call Carro string azul string bmw 30
call abastecer 10
call abastecer 70 | from veiculo import Veiculo
from carro import Carro
v1 = Veiculo('rosa', 4, 'ford', 12)
print(v1)
print(type(v1))
v1.abastecer(234)
print(v1.tanque)
car1 = Carro('azul', 'bmw', 30)
car1.abastecer(10)
car1.abastecer(70) | Python | zaydzuhri_stack_edu_python |
set n = integer input
set count = 0
while n > 0
begin
set n = n - 1
set k = input
if count k string 1 >= 2
begin
set count = count + 1
end
end
print count | n = int(input())
count = 0
while(n > 0):
n-=1
k = input()
if k.count('1') >= 2:
count +=1
print(count)
| Python | zaydzuhri_stack_edu_python |
import xml.etree.ElementTree as ET
import xml.etree.cElementTree as ET
import pprint
import pickle
from collections import defaultdict
import re
comment We now proceed with the address cleaning.
set OSM_FILE = string seattle_washington.osm
set street_type_re = compile string \b\S+\.?$ IGNORECASE
set expected = list str... | import xml.etree.ElementTree as ET
import xml.etree.cElementTree as ET
import pprint
import pickle
from collections import defaultdict
import re
# We now proceed with the address cleaning.
OSM_FILE = "seattle_washington.osm"
street_type_re = re.compile(r'\b\S+\.?$', re.IGNORECASE)
expected = ["Street", "Avenue", "Bo... | Python | zaydzuhri_stack_edu_python |
comment ------------------- fast io --------------------
import os
import sys
from io import BytesIO , IOBase
set BUFSIZE = 8192
class FastIO extends IOBase
begin
set newlines = 0
function __init__ self file
begin
set _fd = call fileno
set buffer = call BytesIO
set writable = string x in mode or string r not in mode
se... | # ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode... | Python | jtatman_500k |
function get_href self session
begin
return string /
end function | def get_href(self, session):
return "/" | Python | nomic_cornstack_python_v1 |
function load_sequence self idx
begin
comment Load data
set sequence = list load np join path paths at idx string pc1.npy
append sequence load np join path paths at idx string pc2.npy
comment Remove ground points
set is_ground = call logical_and sequence at 0 at tuple slice : : 1 < - 1.4 sequence at 1 at tuple slice... | def load_sequence(self, idx):
# Load data
sequence = [np.load(os.path.join(self.paths[idx], "pc1.npy"))]
sequence.append(np.load(os.path.join(self.paths[idx], "pc2.npy")))
# Remove ground points
is_ground = np.logical_and(sequence[0][:, 1] < -1.4, sequence[1][:, 1] < -1.4)
... | Python | nomic_cornstack_python_v1 |
function met_arguments
begin
import sys
set args = argv at slice 1 : :
comment these will all come in as strings; but Macro does a little processing on them
comment in order to intelligently decide whether their types or string or number;
comment creating a Request with these values will simulate this behaviour
set a... | def met_arguments():
import sys
args = sys.argv[1:]
# these will all come in as strings; but Macro does a little processing on them
# in order to intelligently decide whether their types or string or number;
# creating a Request with these values will simulate this behaviour
args_dict = {i: i f... | Python | nomic_cornstack_python_v1 |
function createMAFAlignment infiles outfile
begin
set outfile = call snip outfile string .gz
set axt_dir = PARAMS at string phyloCSF_location_axt
set to_ignore = compile PARAMS at string phyloCSF_ignore
set axt_files = list
for axt_file in list directory axt_dir
begin
if ends with axt_file string net.axt.gz and not se... | def createMAFAlignment(infiles, outfile):
outfile = P.snip(outfile, ".gz")
axt_dir = PARAMS["phyloCSF_location_axt"]
to_ignore = re.compile(PARAMS["phyloCSF_ignore"])
axt_files = []
for axt_file in os.listdir(axt_dir):
if axt_file.endswith("net.axt.gz") and not to_ignore.search(axt_file):
... | Python | nomic_cornstack_python_v1 |
comment 使用selenium爬取淘宝所有商品信息
from selenium import webdriver
import time
import re
import json
comment 搜索商品
function search_product
begin
call send_keys keyworld
call click
sleep 15
comment 找到一共有多少页
comment 一登录后,就能加载到最后,所以不用滚动鼠标都能找到最后一页
set token = text
set token = integer call group 1
print token
return token
end funct... | # 使用selenium爬取淘宝所有商品信息
from selenium import webdriver
import time
import re
import json
# 搜索商品
def search_product():
browser.find_element_by_id("q").send_keys(keyworld)
browser.find_element_by_xpath('//*[@id="J_TSearchForm"]/div[1]/button').click()
time.sleep(15)
# 找到一共有多少页
# 一登录后,就能加载到最后,所以不用滚动鼠标... | Python | zaydzuhri_stack_edu_python |
function test_sign_app_with_failure dummy_command first_app_with_binaries tmp_path
begin
comment Sign the app. Signing first_dylib.dylib will fail.
function _codesign args **kwargs
begin
if name == string first_dylib.dylib
begin
raise call CalledProcessError returncode=1 cmd=args stderr=string { args at 1 } : Unknown e... | def test_sign_app_with_failure(dummy_command, first_app_with_binaries, tmp_path):
# Sign the app. Signing first_dylib.dylib will fail.
def _codesign(args, **kwargs):
if Path(args[1]).name == "first_dylib.dylib":
raise subprocess.CalledProcessError(
returncode=1, cmd=args, st... | Python | nomic_cornstack_python_v1 |
import pandas as pd
set df = read csv string Municipality_Area.csv
comment print(df.head(5))
comment print(df.columns) #ver columnas
comment print(df['Municipio']) # ver una columna
comment slicing
comment print(df[0:3])
comment print(df.iloc[0:3,0,2])# escger columnas
comment con condicion
comment print(df[df.Departam... | import pandas as pd
df = pd.read_csv('Municipality_Area.csv')
# print(df.head(5))
# print(df.columns) #ver columnas
# print(df['Municipio']) # ver una columna
#slicing
# print(df[0:3])
# print(df.iloc[0:3,0,2])# escger columnas
#con condicion
# print(df[df.Departamento == 'Antioquia'].head(5))# imprime todos que teng... | Python | zaydzuhri_stack_edu_python |
function to_pandas self wrap=false **kwargs
begin
try
begin
import pandas as pd
end
except ImportError
begin
raise call DependencyNotInstalledError string to_pandas requires for `pandas` library
end
function wrapper result
begin
set df = values
if wrap
begin
from import DataFrame
set df = call DataFrame df
end
return ... | def to_pandas(self, wrap=False, **kwargs):
try:
import pandas as pd
except ImportError:
raise DependencyNotInstalledError(
'to_pandas requires for `pandas` library')
def wrapper(result):
df = result.values
if wrap:
... | Python | nomic_cornstack_python_v1 |
function __repr__ self
begin
set res = list
set caracter = character 4
set len_square = length update_board
for i_row in range 0 len_square
begin
if i_row == 0
begin
for _ in range 0 len_square
begin
append res string + caracter + string + caracter
end
append res string + caracter + string
end
for i_column in range... | def __repr__(self):
res = []
caracter = chr(4)
len_square = len(self.update_board)
for i_row in range (0,len_square):
if(i_row == 0):
for _ in range(0,len_square):
res.append(" " + caracter + " " + caracter)
res.append(" " +... | Python | nomic_cornstack_python_v1 |
for i in range 0 a + 1
begin
if i % 60 == 0 and i >= 60
begin
set h = h + 1
set b = b - 60
end
end
print h b | for i in range(0,a+1):
if(i%60==0 and i>=60):
h+=1
b-=60
print(h,b)
| Python | zaydzuhri_stack_edu_python |
function __str__ self
begin
set even_row = sign + space * width
set odd_row = space + even_row
comment using list generator to make strings which will be printed
return join string list comprehension if expression h % 2 then odd_row else even_row for h in range height
end function | def __str__(self):
even_row = (self.sign + self.space) * self.width
odd_row = self.space + even_row
# using list generator to make strings which will be printed
return "\n".join([odd_row if h % 2 else even_row for h in range(self.height)]) | Python | nomic_cornstack_python_v1 |
import numpy as np
import cv2
comment https://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html
comment https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html
set canvas = zeros tuple 300 300 3 dtype=string uint8
set green = tuple 0 255 0
call line canvas tuple 0 0 tuple 300 300 green
image sho... | import numpy as np
import cv2
#https://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html
#https://docs.opencv.org/2.4/modules/core/doc/drawing_functions.html
canvas = np.zeros((300,300,3),dtype = "uint8")
green = (0, 255, 0)
cv2.line(canvas,(0,0),(300,300),green)
cv2.imshow("Canvas",canvas)
red = (0, 0,... | Python | zaydzuhri_stack_edu_python |
function accept_alert self text=none wait=none
begin
string Execute the wrapped code, accepting an alert. Args: text (str | RegexObject, optional): Text to match against the text in the modal. wait (int | float, optional): Maximum time to wait for the modal to appear after executing the wrapped code. Raises: ModalNotFo... | def accept_alert(self, text=None, wait=None):
"""
Execute the wrapped code, accepting an alert.
Args:
text (str | RegexObject, optional): Text to match against the text in the modal.
wait (int | float, optional): Maximum time to wait for the modal to appear after
... | Python | jtatman_500k |
function is_sorted array
begin
for i in range length array - 1
begin
if array at i > array at i + 1
begin
return false
end
end
return true
end function | def is_sorted(array):
for i in range(len(array)-1):
if array[i] > array[i+1]:
return False
return True
| Python | flytech_python_25k |
function signout self name location number notes=string
begin
set found = false
for bank in __banks
begin
if call number == string number
begin
set found = true
if not call out and call signed_in and call returned
begin
call signout name location notes
return tuple true 0
end
else
if call out
begin
return tuple false 1... | def signout(self, name, location, number, notes = ""):
found = False
for bank in self.__banks:
if bank.number() == str(number):
found = True
if not bank.out() and bank.signed_in() and bank.returned():
bank.signout(name, location, notes)
... | Python | nomic_cornstack_python_v1 |
function _getNumberOfSpaces self str
begin
set num = 0
for char in str
begin
if char is string
begin
set num = num + 1
end
end
return num
end function | def _getNumberOfSpaces(self, str):
num = 0
for char in str:
if char is " ":
num += 1
return num | Python | nomic_cornstack_python_v1 |
function setIntegerOption self option value
begin
set result = call voikkoSetIntegerOption __handle option value
if result == 0
begin
raise call VoikkoException string Could not set integer option %s to value %s % tuple option value
end
end function | def setIntegerOption(self, option, value):
result = self.__lib.voikkoSetIntegerOption(self.__handle, option, value)
if result == 0:
raise VoikkoException("Could not set integer option %s to value %s" % (option, value)) | Python | nomic_cornstack_python_v1 |
function get_order self
begin
string Returns the result order by clauses :rtype: str or None
comment first get the filtered attributes in order as they must appear
comment in the order_by first
if not has_order
begin
return none
end
set filter_order_clauses = ordered dictionary list comprehension tuple filter_attr at 0... | def get_order(self):
""" Returns the result order by clauses
:rtype: str or None
"""
# first get the filtered attributes in order as they must appear
# in the order_by first
if not self.has_order:
return None
filter_order_clauses = OrderedDict([(filte... | Python | jtatman_500k |
function format_units v step=none system=string si units=none
begin
string Format the given value in standardized units. ``system`` is either 'binary' or 'si' For more info, see: http://en.wikipedia.org/wiki/SI_prefix http://en.wikipedia.org/wiki/Binary_prefix
if v is none
begin
return tuple 0 string
end
for tuple pre... | def format_units(v, step=None, system="si", units=None):
"""Format the given value in standardized units.
``system`` is either 'binary' or 'si'
For more info, see:
http://en.wikipedia.org/wiki/SI_prefix
http://en.wikipedia.org/wiki/Binary_prefix
"""
if v is None:
return 0, ... | Python | jtatman_500k |
function event_hub_name self
begin
return get pulumi self string event_hub_name
end function | def event_hub_name(self) -> Optional[str]:
return pulumi.get(self, "event_hub_name") | Python | nomic_cornstack_python_v1 |
import random
set name = input string Enter your name:
print string Welcome in dice rolling simulator %s % name
set x = string y
while x == string y
begin
set a = random integer 1 6
if a == 1
begin
print string ___
print string
print string 0
print string
print string ___
end
else
if a == 2
begin
print string ___
print... | import random
name=input('Enter your name: ')
print('Welcome in dice rolling simulator %s'%name)
x='y'
while (x=='y'):
a=random.randint(1,6)
if (a==1):
print('___')
print(' ')
print(' 0 ')
print(' ')
print('___')
elif (a==2):
print('___')
print(' 0... | Python | zaydzuhri_stack_edu_python |
from konlpy.tag import Kkma
from tqdm import tqdm as tq
set kkma = call Kkma
set F = open string news_2020_july_12699.txt string r+ encoding=string utf-8
set F_list = read lines F
set len_sentence = list
for i in call tq F_list
begin
append len_sentence length i
end
comment for mundan in tq(F_list) :
comment ex_sent =... | from konlpy.tag import Kkma
from tqdm import tqdm as tq
kkma = Kkma()
F = open("news_2020_july_12699.txt",'r+', encoding='utf-8')
F_list = F.readlines()
len_sentence = []
for i in tq(F_list) :
len_sentence.append(len(i))
# for mundan in tq(F_list) :
# ex_sent = kkma.sentences(mundan)
# len_sentence.ap... | Python | zaydzuhri_stack_edu_python |
function get_light_raw self id=none
begin
if id is none
begin
set result = call _request HTTP_GET DECONZ_LIGHTS
end
else
begin
set result = call _request HTTP_GET format string {}/{} DECONZ_LIGHTS id
end
if result is none
begin
error string DeCONZ: %s %s did not return data HTTP_GET DECONZ_LIGHTS
end
return result
end ... | def get_light_raw(self, id=None):
if id is None:
result = self._request(HTTP_GET, DECONZ_LIGHTS)
else:
result = self._request(HTTP_GET, "{}/{}".format(DECONZ_LIGHTS, id))
if result is None:
_LOGGER.error("DeCONZ: %s %s did not return data", HTTP_GET, DECONZ_... | Python | nomic_cornstack_python_v1 |
from gpiozero import LED , Button
import lcddriver
from time import *
import os
from pymongo import MongoClient
import datetime | from gpiozero import LED, Button
import lcddriver
from time import *
import os
from pymongo import MongoClient
import datetime | Python | zaydzuhri_stack_edu_python |
for i in range h
begin
for j in range w
begin
if i == 0
begin
set dp at i at j = 1
continue
end
if j == 0
begin
set dp at i at j = 1
continue
end
set dp at i at j = dp at i - 1 at j + dp at i at j - 1 % 10 ^ 9 + 7
end
end
print dp at - 1 at - 1 | for i in range(h):
for j in range(w):
if i == 0:
dp[i][j] = 1
continue
if j == 0:
dp[i][j] = 1
continue
dp[i][j] = (dp[i-1][j] + dp[i][j-1]) % (10**9+7)
print(dp[-1][-1]) | Python | zaydzuhri_stack_edu_python |
function from_dict cls _dict
begin
set args = dict
if string timezone in _dict
begin
set args at string timezone = get _dict string timezone
end
if string user_id in _dict
begin
set args at string user_id = get _dict string user_id
end
if string turn_count in _dict
begin
set args at string turn_count = get _dict strin... | def from_dict(cls, _dict: Dict) -> 'MessageContextGlobalSystem':
args = {}
if 'timezone' in _dict:
args['timezone'] = _dict.get('timezone')
if 'user_id' in _dict:
args['user_id'] = _dict.get('user_id')
if 'turn_count' in _dict:
args['turn_count'] = _di... | Python | nomic_cornstack_python_v1 |
function testCourses self
begin
call invokeFactory type_name=string FSDCourse id=string test-course
call failUnless string test-course in call contentIds
call failUnless string test-course in list comprehension id for c in call getCourses
end function | def testCourses(self):
self.person.invokeFactory(type_name="FSDCourse", id="test-course")
self.failUnless('test-course' in self.person.contentIds())
self.failUnless('test-course' in [c.id for c in self.person.getCourses()]) | Python | nomic_cornstack_python_v1 |
function _initQueryBands self production
begin
set queryBands = ordered dictionary
set queryBands at string ApplicationName = config at string appName
set queryBands at string Version = config at string version
set queryBands at string JobID = runNumber
set queryBands at string ClientUser = call getuser
set queryBands ... | def _initQueryBands(self, production):
self.queryBands = collections.OrderedDict()
self.queryBands['ApplicationName'] = self.config['appName']
self.queryBands['Version'] = self.config['version']
self.queryBands['JobID'] = self.runNumber
self.queryBands['ClientUser'] = getpass.get... | Python | nomic_cornstack_python_v1 |
function open data_dir=PACKAGE_DIR encoding=ENCODING encoding_errors=ENCODING_ERRORS license_code=none
begin
string Initializes the NLPIR API. This calls the function :func:`~pynlpir.nlpir.Init`. :param str data_dir: The absolute path to the directory that has NLPIR's `Data` directory (defaults to :data:`pynlpir.nlpir.... | def open(data_dir=nlpir.PACKAGE_DIR, encoding=ENCODING,
encoding_errors=ENCODING_ERRORS, license_code=None):
"""Initializes the NLPIR API.
This calls the function :func:`~pynlpir.nlpir.Init`.
:param str data_dir: The absolute path to the directory that has NLPIR's
`Data` directory (defaul... | Python | jtatman_500k |
import pygame
import os
import random
import Objetos
class Fantasma
begin
function __init__ this
begin
set x = 0
set y = 0
set velX = 0
set velY = 0
set velocidade = 1
set proxLinha = 0
set proxColuna = 0
set homeX = 0
set homeY = 0
set image = call convert_alpha
end function
function andar this
begin
if call getNivel ... | import pygame
import os
import random
import Objetos
class Fantasma:
def __init__ (this):
this.x = 0
this.y = 0
this.velX = 0
this.velY = 0
this.velocidade = 1
this.proxLinha = 0
this.proxColuna = 0
... | Python | zaydzuhri_stack_edu_python |
function _check_configure_args configure_args
begin
comment SSID must always be present
if not get configure_args string ssid or not is instance configure_args at string ssid str
begin
raise call ConfigureArgsError string SSID must be specified
end
comment If specified, hidden must be a bool
if not get configure_args s... | def _check_configure_args(configure_args: Dict[str, Any]) -> Dict[str, Any]:
# SSID must always be present
if not configure_args.get('ssid')\
or not isinstance(configure_args['ssid'], str):
raise wifi.ConfigureArgsError("SSID must be specified")
# If specified, hidden must be a bool
if no... | Python | nomic_cornstack_python_v1 |
function set_width self w
begin
if call isscalar w
begin
set w = ones _n_parameters * w
end
else
begin
set w = array w copy=true
if length w != _n_parameters
begin
raise call ValueError string Width for interval expansion must a scalar or an array of length n_parameters.
end
end
if any w < 0
begin
raise call ValueError... | def set_width(self, w):
if np.isscalar(w):
w = np.ones(self._n_parameters) * w
else:
w = np.array(w, copy=True)
if len(w) != self._n_parameters:
raise ValueError(
'Width for interval expansion must a scalar or an array'
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string 获取摘要的相关实现模块
from pyhanlp import *
function get_summary text num
begin
string 获取指定句子个数的文本摘要 Args @text 文本 @num 句子个数 Return 文本摘要
comment 加载模型
set TextRankSentence = call JClass string com.hankcs.hanlp.summary.TextRankSentence
comment 抽取摘要
set sentence_list = call extractSummary text n... | # -*- coding: utf-8 -*-
"""
获取摘要的相关实现模块
"""
from pyhanlp import *
def get_summary(text, num):
"""
获取指定句子个数的文本摘要
Args
@text 文本
@num 句子个数
Return
文本摘要
"""
# 加载模型
TextRankSentence = JClass("com.hankcs.hanlp.summary.TextRankSentence")
# 抽取摘要
sentence_list = HanL... | Python | zaydzuhri_stack_edu_python |
function import_pubs filename
begin
set df = read csv filename skipinitialspace=true parse_dates=list string last_visited
set pubs = list comprehension call pub_from_dict row for tuple idx row in call iterrows
return pubs
end function | def import_pubs(filename: str) -> List[Pub]:
df = pd.read_csv(filename, skipinitialspace=True, parse_dates=["last_visited"])
pubs = [pub_from_dict(row) for idx, row in df.iterrows()]
return pubs | Python | nomic_cornstack_python_v1 |
function insertion_sort arr
begin
string Sorts the given list of strings using insertion sort
comment traverse through 1 to len(arr)
for i in range 1 length arr
begin
set key = arr at i
comment Move elements of arr[0..i-1], that are
comment greater than key, to one position ahead
comment of their current position
set j... | def insertion_sort(arr):
"""Sorts the given list of strings using insertion sort"""
# traverse through 1 to len(arr)
for i in range(1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are
# greater than key, to one position ahead
# of their current pos... | Python | flytech_python_25k |
function test_with_blank_csv self
begin
set csvFile = string test_blank_csv.csv
set expectedRetVal = string blank csv file
set obj = call stockPriceAnalyser csvFile
set retData = call getCompWiseHighestStckPriceData
assert equal lower string retData expectedRetVal
end function | def test_with_blank_csv(self):
csvFile = "test_blank_csv.csv"
expectedRetVal = "blank csv file"
obj = stockPriceAnalyser(csvFile)
retData = obj.getCompWiseHighestStckPriceData()
self.assertEqual(str(retData).lower(), expectedRetVal) | Python | nomic_cornstack_python_v1 |
string Written by Siri Khalsa The goal of this is create a population of covid-19 spikes every iteration it will randomly mutate. if the spike is still in the neutral network after the mutation it stays around if it is no longer in the neutral network than the virus will die and a new covid-19 spike will be generated i... | """
Written by Siri Khalsa
The goal of this is create a population of covid-19 spikes
every iteration it will randomly mutate.
if the spike is still in the neutral network after the mutation it stays around
if it is no longer in the neutral network than the virus will die and a
new covid-19 spike will be generated in... | Python | zaydzuhri_stack_edu_python |
from random import random , randint
import math
class Node
begin
function __init__ self pos imp=- 1 cx=- 1 cy=- 1 tatk=0
begin
set pos = pos
set cx = cx
set cy = cy
set adj = list
set imp = imp
comment contatore visite
set visitcount = 0
comment contatore passaggi
set passcount = 0
comment ultima visita
set lastvisit ... | from random import random, randint
import math
class Node:
def __init__(self,pos,imp=-1,cx=-1,cy=-1,tatk=0):
self.pos=pos
self.cx=cx
self.cy=cy
self.adj=[]
self.imp=imp
self.visitcount=0 #contatore visite
self.passcount=0 #contatore passaggi
self.lastvisit=0 #ultima visita
self.valueimp=0 #... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding: utf-8
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Task
begin
function __init__ self priority task
begin
set priority = priority
set task = task
end function
function __eq__ self other
begin
if task == other
begin
return... | #!/usr/bin/env python
# coding: utf-8
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class Task():
def __init__(self, priority, task):
self.priority = priority
self.task = task
def __eq__(self, other):
if(self.task == other):
... | Python | zaydzuhri_stack_edu_python |
import torch
import torch.nn as nn
from torchvision.transforms import CenterCrop
class DoubleConv extends Module
begin
function __init__ self in_channels out_channels mid_channels=none
begin
call __init__
if not mid_channels
begin
set mid_channels = out_channels
end
set conv1 = conv 2d in_channels mid_channels kernel_s... | import torch
import torch.nn as nn
from torchvision.transforms import CenterCrop
class DoubleConv(nn.Module):
def __init__(self, in_channels, out_channels, mid_channels=None):
super().__init__()
if not mid_channels:
mid_channels = out_channels
self.conv1 = nn.Conv2d(in_channels... | Python | zaydzuhri_stack_edu_python |
async function websocket_handle_add hass connection msg
begin
set item = await call async_add msg at string name
call async_fire EVENT dict string action string add ; string item item
call send_message call result_message msg at string id item
end function | async def websocket_handle_add(hass, connection, msg):
item = await hass.data[DOMAIN].async_add(msg["name"])
hass.bus.async_fire(EVENT, {"action": "add", "item": item})
connection.send_message(websocket_api.result_message(msg["id"], item)) | Python | nomic_cornstack_python_v1 |
from __future__ import print_function
import math
import time
import googlemaps
import presets
from dbmanager import DBManager
function calc_distance lat_1 lng_1 lat_2 lng_2
begin
string Calculate the distance between two points. (See https://en.wikipedia.org/wiki/Haversine_formula)
set tuple lat_1 lng_1 = tuple lat_1 ... | from __future__ import print_function
import math
import time
import googlemaps
import presets
from dbmanager import DBManager
def calc_distance(lat_1, lng_1, lat_2, lng_2):
"""Calculate the distance between two points.
(See https://en.wikipedia.org/wiki/Haversine_formula)
"""
lat_1, lng_1 = lat_1 ... | Python | zaydzuhri_stack_edu_python |
function _find_live_src self
begin
with open string /proc/mounts string r as fob
begin
for mount in read lines fob
begin
if string run/live/medium in mount and starts with mount string /dev/
begin
return split mount at 0 at slice 5 : :
end
end
end
return string
end function | def _find_live_src(self):
with open('/proc/mounts', 'r') as fob:
for mount in fob.readlines():
if 'run/live/medium' in mount and mount.startswith('/dev/'):
return mount.split()[0][5:]
return '' | Python | nomic_cornstack_python_v1 |
function average_hinge_loss feature_matrix labels w alpha
begin
comment Write your code here
set hl = list
for i in range length feature_matrix
begin
set z = dot labels at i dot w feature_matrix at i + alpha
if z >= 1
begin
append hl 0
end
else
begin
append hl 1 - z
end
end
return sum hl / length hl
end function | def average_hinge_loss(feature_matrix, labels, w, alpha):
# Write your code here
hl = []
for i in range(len(feature_matrix)):
z = np.dot(labels[i], (np.dot(w, feature_matrix[i]) + alpha))
if z >= 1:
hl.append(0)
else:
hl.append(1 - z)
return sum(hl) / len... | Python | nomic_cornstack_python_v1 |
import datetime
import sys
class Note
begin
set note_number = 0
function __init__ self tag text
begin
set tag = tag
set text = text
set date = string format time now string %d-%m-%Y
set note_number = note_number + 1
set ID = note_number
end function
function match test
begin
if test and strip test
begin
return true
end... | import datetime
import sys
class Note:
note_number = 0
def __init__(self, tag,text):
self.tag = tag
self.text = text
self.date = datetime.datetime.now().strftime('%d-%m-%Y')
Note.note_number+=1
self.ID = Note.note_number
def match(test):
if test ... | Python | zaydzuhri_stack_edu_python |
function make_mesh self expr
begin
set output = output + string >> Generating triangulated mesh
set DEPTH = 0
while DEPTH <= 4
begin
set region = call Region tuple xmin - border * dx ymin - border * dy zmin - border * dz tuple xmax + border * dx ymax + border * dy zmax + border * dz depth=DEPTH
set status = string Rend... | def make_mesh(self, expr):
self.output += '>> Generating triangulated mesh\n'
DEPTH = 0
while DEPTH <= 4:
region = Region(
(expr.xmin - self.cad.border*expr.dx,
expr.ymin - self.cad.border*expr.dy,
expr.zmin - self.cad.b... | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function rightSideView self root
begin
function _rightSideView root result depth
begin
if not root
begin
return
end
if depth == length result
begin
append result val
end
call _rightSideView right result depth + 1
call _rightSideView left result depth + 1
end function
set result = lis... | class Solution(object):
def rightSideView(self, root):
def _rightSideView(root, result, depth):
if not root: return
if depth == len(result):
result.append(root.val)
_rightSideView(root.right, result, depth + 1)
_rightSideView(root.left, result,... | Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function maxIncreaseKeepingSkyline self grid
begin
set xdim = length grid at 0
set ydim = length grid
set total = 0
set ymaxs = list
set xmaxs = list
for y in range ydim
begin
append ymaxs max grid at y
end
for x in range xdim
begin
set thiscol = list
for y in range 0 ydim
begin
a... | class Solution(object):
def maxIncreaseKeepingSkyline(self, grid):
xdim = len(grid[0])
ydim = len(grid)
total = 0
ymaxs = []
xmaxs = []
for y in range (ydim):
ymaxs.append(max(grid[y]))
for x in range (xdim):
thiscol = []
fo... | Python | zaydzuhri_stack_edu_python |
import itertools as itt
import numpy as np
from math import factorial
function ndarray_dprime array0 array1 axis keepdims=false
begin
string general function to calculate the d prime between two arrays with the same shape. the d prime is calculated in a dimension wise manner but for the specified axis, which is treated... | import itertools as itt
import numpy as np
from math import factorial
def ndarray_dprime(array0, array1, axis, keepdims=False):
"""
general function to calculate the d prime between two arrays with the same shape. the d prime is calculated in
a dimension wise manner but for the specified axis, w... | Python | zaydzuhri_stack_edu_python |
set num1 = decimal input string Enter number1:
set num2 = decimal input string Enter number2:
set sum = num1 + num2
set diff = num1 - num2
set product = num1 * num2
set mode = num1 % num2
set quotient = num1 / num2
set power = num1 ^ num2
print string All operations results
print format string Sum of {0} and {1} is {2}... | num1 = float(input("Enter number1:"))
num2 = float(input("\nEnter number2:"))
sum = num1+num2
diff = num1-num2
product = num1*num2
mode = num1%num2
quotient=num1/num2
power=num1**num2
print("All operations results")
print('Sum of {0} and {1} is {2}'.format(num1,num2,sum))
print('Difference of {0} and {1} is {2}'.form... | Python | zaydzuhri_stack_edu_python |
function country self
begin
return get pulumi self string country
end function | def country(self) -> Optional[str]:
return pulumi.get(self, "country") | Python | nomic_cornstack_python_v1 |
import tensorflow as tf
import random
import argparse
import numpy as np
import time
import os
import pdb
set parser = call ArgumentParser
call add_argument string --m type=int default=1000 help=string number of train samples
call add_argument string --n type=int default=100 help=string number of test samples
call add_... | import tensorflow as tf
import random
import argparse
import numpy as np
import time
import os
import pdb
parser = argparse.ArgumentParser()
parser.add_argument('--m', type=int, default=1000, help='number of train samples')
parser.add_argument('--n', type=int, default=100, help='number of test samples')
parser.add_ar... | Python | zaydzuhri_stack_edu_python |
function deduce self items
begin
for grammar in grammars
begin
for item in call deduce_with_itg itg items
begin
if level >= 4
begin
call writeln string new item:
call writeln item
call writeln incoming at 0
end
yield item
end
end
end function | def deduce(self, items):
for grammar in self.grammars:
for item in self.deduce_with_itg(grammar.itg, items):
if logger.level >= 4:
logger.writeln('new item:')
logger.writeln(item)
logger.writeln(item.incoming[0])
... | Python | nomic_cornstack_python_v1 |
if name1 > 60
begin
print string 您输入的数字大于六十,恭喜您
end
else
begin
print string 您输入的数字小于六十,不好意思
end | if name1 > 60:
print("您输入的数字大于六十,恭喜您")
else:
print("您输入的数字小于六十,不好意思")
| Python | zaydzuhri_stack_edu_python |
from aux_functions import *
from default_settings import *
from getting_from_file import *
comment Get the author names exception
set mobi_exceptions = list
set pdf_exceptions = list
comment some of the book titles got some bugs, because they have very difficult names that are difficult to
try
begin
comment estabilis... | from aux_functions import *
from default_settings import *
from getting_from_file import *
#Get the author names exception
mobi_exceptions=[]
pdf_exceptions=[]
try:#some of the book titles got some bugs, because they have very difficult names that are difficult to
#estabilish a pattern, so I've made an extra python ... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
from PIL import ImageTk , Image
set root = call Tk
title root string my menu bars
call iconbitmap string icons/superman.ico
call geometry string 600x600
set my_menu = call Menu root
call config menu=my_menu
function click
begin
set top = call Toplevel
call geometry string 720x720
title top string ... | from tkinter import *
from PIL import ImageTk,Image
root = Tk()
root.title("my menu bars")
root.iconbitmap("icons/superman.ico")
root.geometry("600x600")
my_menu = Menu(root)
root.config(menu=my_menu)
def click():
top = Toplevel()
top.geometry("720x720")
top.title("new file")
def edit():
... | Python | zaydzuhri_stack_edu_python |
from collections import defaultdict
from collections import Counter
import collections
import enum
from re import A
comment import numpy as np
import sys
import argparse
import math
import random
from tkinter import N
comment https://www.daleseo.com/python-typing/
from typing import Optional
from typing import Union
fr... | from collections import defaultdict
from collections import Counter
import collections
import enum
from re import A
#import numpy as np
import sys
import argparse
import math
import random
from tkinter import N
# https://www.daleseo.com/python-typing/
from typing import Optional
from typing import Union
from typing im... | Python | zaydzuhri_stack_edu_python |
async function test_command_line_output hass
begin
with temporary directory as tempdirname
begin
set filename = join path tempdirname string message.txt
set message = string one, two, testing, testing
await call setup_test_service hass dict string command string cat > { filename }
assert call has_service DOMAIN string ... | async def test_command_line_output(hass: HomeAssistant) -> None:
with tempfile.TemporaryDirectory() as tempdirname:
filename = os.path.join(tempdirname, "message.txt")
message = "one, two, testing, testing"
await setup_test_service(
hass,
{
"command": ... | Python | nomic_cornstack_python_v1 |
from bs4 import BeautifulSoup
from decimal import Decimal
import requests
function convert amount cur_from cur_to date
begin
set url = string https://www.cbr.ru/scripts/XML_daily.asp
comment Использовать переданный requests
set response = get requests url params=dict string date_req date
set soup = call BeautifulSoup c... | from bs4 import BeautifulSoup
from decimal import Decimal
import requests
def convert(amount, cur_from, cur_to, date):
url = 'https://www.cbr.ru/scripts/XML_daily.asp'
response = requests.get(url, params={'date_req': date}) # Использовать переданный requests
soup = BeautifulSoup(response.content, 'xml')... | Python | zaydzuhri_stack_edu_python |
function removeAttribute self attribute
begin
pass
end function | def removeAttribute(self, attribute):
pass | Python | nomic_cornstack_python_v1 |
function has_validation_message self
begin
return present
end function | def has_validation_message(self):
return self.q(css=self._bounded_selector(self.VALIDATION_SELECTOR)).present | Python | nomic_cornstack_python_v1 |
function test_execute_no_ws4py self
begin
from pylxd.models import container
set old_installed = _ws4py_installed
set _ws4py_installed = false
function cleanup
begin
set _ws4py_installed = old_installed
end function
call addCleanup cleanup
set an_container = call Container client name=string an-container
assert raises ... | def test_execute_no_ws4py(self):
from pylxd.models import container
old_installed = container._ws4py_installed
container._ws4py_installed = False
def cleanup():
container._ws4py_installed = old_installed
self.addCleanup(cleanup)
an_container = models.Contain... | Python | nomic_cornstack_python_v1 |
function DisplayTodoFile self todo_file
begin
comment write out a header for the inventory table that matches the fixed-width spacing
print string All done, here are the current contents of your todo list file:
print string Item + string * 17 + string Priority + string * 12
print string = * 20 + string + string = * ... | def DisplayTodoFile(self, todo_file):
# write out a header for the inventory table that matches the fixed-width spacing
print("\n\nAll done, here are the current contents of your todo list file: \n")
print('Item' + " " * 17 + "Priority" + " " * 12)
print("=" * 20 + " " + "=" * 20 + "\n"... | Python | nomic_cornstack_python_v1 |
function upper_relu_relax self lower=none upper=none
begin
if lower is none
begin
if lower_bounds is none
begin
raise exception string Missing lower bounds
end
else
begin
set lower = lower_bounds
end
end
if upper is none
begin
if upper_bounds is none
begin
raise exception string Missing upper bounds
end
else
begin
set ... | def upper_relu_relax(self, lower=None, upper=None):
if lower is None:
if self.lower_bounds is None:
raise Exception("Missing lower bounds")
else:
lower = self.lower_bounds
if upper is None:
if self.upper_bounds is None:
... | Python | nomic_cornstack_python_v1 |
function save self event
begin
append saved_events event
end function | def save(self, event):
self.saved_events.append(event) | Python | nomic_cornstack_python_v1 |
function loop_vars self
begin
return __loop_vars
end function | def loop_vars(self):
return self.__loop_vars | Python | nomic_cornstack_python_v1 |
import sys
for line in stdin
begin
set a = integer line
if a > 0
begin
if a % 2 == 0
begin
print a
end
end
end | import sys
for line in sys.stdin:
a = int(line)
if a > 0:
if a % 2 == 0:
print(a) | Python | zaydzuhri_stack_edu_python |
import os.path
import re
import math
from collections import defaultdict
import itertools
import md5
function get_input filename=none
begin
if not filename
begin
set filename = call splitext base name path __file__ at 0 + string .txt
end
with open filename as fp
begin
set input = strip read fp
end
return split input st... | import os.path
import re
import math
from collections import defaultdict
import itertools
import md5
def get_input(filename=None):
if not filename:
filename = os.path.splitext(os.path.basename(__file__))[0]+'.txt'
with open(filename) as fp:
input = fp.read().strip()
return input.split(','... | Python | zaydzuhri_stack_edu_python |
function dispims_color M border=0 bordercolor=list 0.0 0.0 0.0 *imshow_args **imshow_keyargs
begin
set bordercolor = array bordercolor at tuple none none slice : :
set numimages = length M
set M = copy M
for i in range shape at 0
begin
set M at i = M at i - min
set M at i = M at i / max
end
set tuple height width th... | def dispims_color(M, border=0, bordercolor=[0.0, 0.0, 0.0], *imshow_args, **imshow_keyargs):
bordercolor = np.array(bordercolor)[None, None, :]
numimages = len(M)
M = M.copy()
for i in range(M.shape[0]):
M[i] -= M[i].flatten().min()
M[i] /= M[i].flatten().max()
height, width, three =... | Python | nomic_cornstack_python_v1 |
function quote_f s
begin
return format string '{}' s
end function | def quote_f(s):
return "'{}'".format(s) | Python | nomic_cornstack_python_v1 |
function pc_work_time self
begin
return call crc_attachment_sptr_pc_work_time self
end function | def pc_work_time(self):
return _my_lte_swig.crc_attachment_sptr_pc_work_time(self) | Python | nomic_cornstack_python_v1 |
function store_last_seen FILE_NAME last_seen_id
begin
set file_write = open FILE_NAME string w
write file_write string last_seen_id
close file_write
print string Last Seen ID is stored.
return
end function | def store_last_seen(FILE_NAME: str, last_seen_id: int) -> None:
file_write = open(FILE_NAME, 'w')
file_write.write(str(last_seen_id))
file_write.close()
print("Last Seen ID is stored.")
return | Python | nomic_cornstack_python_v1 |
function start self
begin
set thread = thread target=sendGameEvent args=tuple 0 kill_switch
append threads thread
start thread
end function | def start(self):
thread = Thread(target=self.ckl.sendGameEvent, args=(0, self.kill_switch))
self.threads.append(thread)
thread.start() | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.