code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
class Solution
begin
function frog self stones
begin
string :type stones: List[int] :rtype: bool
set dp = list comprehension false for _ in range stones at - 1 + 1
for stone in stones
begin
set dp at stone = true
end
print dp
return call backtrack dp 0 0
end function
function backtrack self dp curr_position curr_jump
b... | class Solution:
def frog(self, stones):
"""
:type stones: List[int]
:rtype: bool
"""
dp = [False for _ in range(stones[-1]+1)]
for stone in stones:
dp[stone] = True
print(dp)
return self.backtrack(dp, 0, 0)
... | Python | zaydzuhri_stack_edu_python |
from math import sqrt
import src.main as main
from src.models import Ranking
from scipy.stats import kendalltau , spearmanr
set _RANKING_DIR = string new_rankings/
function normalize_uncertainty uncertainty
begin
set max_unc = length uncertainty - 1
set new_uncertainty = list
for unc in uncertainty
begin
append new_un... | from math import sqrt
import src.main as main
from src.models import Ranking
from scipy.stats import kendalltau, spearmanr
_RANKING_DIR = 'new_rankings/'
def normalize_uncertainty(uncertainty):
max_unc = len(uncertainty) - 1
new_uncertainty = []
for unc in uncertainty:
new_uncertainty.append(round(unc/max... | Python | zaydzuhri_stack_edu_python |
string Additional task – to show the closest leap year in case if entered year is not leap
function is_year_leap year
begin
return not boolean year % 4
end function
set year = input string Please input year -
try
begin
set y = integer year
while y
begin
if call is_year_leap y
begin
print format string Clasest leap year... | '''Additional task
– to show the closest leap year
in case if entered year is not leap'''
def is_year_leap(year):
return not bool(year % 4)
year = input('Please input year - ')
try:
y = int(year)
while y:
if is_year_leap(y):
print('Clasest leap year is {}'.format(y))
br... | Python | zaydzuhri_stack_edu_python |
function set_local_data self butler data **kwargs
begin
call safe_update keyword kwargs
set slots = slots
if slots is none
begin
set slots = ALL_SLOTS
end
for slot in slots
begin
if not exists path data at slot
begin
warn string skipping missing data for %s:%s % tuple raft slot
continue
end
set mask_files = call get_ma... | def set_local_data(self, butler, data, **kwargs):
self.safe_update(**kwargs)
slots = self.config.slots
if slots is None:
slots = ALL_SLOTS
for slot in slots:
if not os.path.exists(data[slot]):
self.log.warn("skipping missing data for %s:%s" % (sel... | Python | nomic_cornstack_python_v1 |
function __init__ self dim inpDim modelId timeDependent RNNdata lossOpt model optimizer
begin
comment Save data:
set dim = dim
set inpDim = inpDim
set modelId = modelId
set RNNdata = RNNdata
set timeDependent = timeDependent
set optimizer = optimizer
comment shared model among computational towers
set model = model
com... | def __init__(self, dim, inpDim, modelId, timeDependent, RNNdata, lossOpt,
model, optimizer):
# Save data:
self.dim = dim
self.inpDim = inpDim
self.modelId = modelId
self.RNNdata = RNNdata
self.timeDependent = timeDependent
self.optimizer =... | Python | nomic_cornstack_python_v1 |
function get_next_sibling self **filters
begin
set siblings = filter keyword filters
return call _get_next_from_qs siblings
end function | def get_next_sibling(self, **filters):
siblings = self.get_siblings(include_self=True).filter(**filters)
return self._get_next_from_qs(siblings) | Python | nomic_cornstack_python_v1 |
import openpyxl
import datetime
from openpyxl import load_workbook
from openpyxl.styles import PatternFill , Border , Side , Alignment , Protection , Font
set CorFill = call PatternFill fill_type=none start_color=string ffffff end_color=string 21f600
set wb = call load_workbook filename=string karsilastir.xlsx
set wsRe... | import openpyxl
import datetime
from openpyxl import load_workbook
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font
CorFill = PatternFill(fill_type=None, start_color='ffffff', end_color='21f600')
wb = load_workbook(filename = 'karsilastir.xlsx')
wsRef = wb.get_sheet_by_name('referenc... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python
comment Ros libraries
import roslib
import rospy
from std_msgs.msg import String
comment from bridge_example.msg import motors, motor
import serial
import time
import threading
set startMarker = string <
set endMarker = string >
set dataStarted = false
set dataBuf = string
set messageComp... | #! /usr/bin/env python
# Ros libraries
import roslib
import rospy
from std_msgs.msg import String
#from bridge_example.msg import motors, motor
import serial
import time
import threading
startMarker = '<'
endMarker = '>'
dataStarted = False
dataBuf = ""
messageComplete = False
go=True
details = None
count = 0
#prevTi... | Python | zaydzuhri_stack_edu_python |
from ilearnscaperQT import Ui_MainWindow
from PyQt5 import QtWidgets
from iLearn_File_Downloader import main_download_loop
from database import add_course , get_semester_amp_courses , get_semester_cap_courses
import yaml , os , request_functions
from cap_tracker import update_cap_courses
function load_config
begin
set ... | from ilearnscaperQT import Ui_MainWindow
from PyQt5 import QtWidgets
from iLearn_File_Downloader import main_download_loop
from database import add_course, get_semester_amp_courses, get_semester_cap_courses
import yaml, os, request_functions
from cap_tracker import update_cap_courses
def load_config():
__path... | Python | zaydzuhri_stack_edu_python |
function _generate_token self input_ids past do_sample temperature top_k top_p attribution_flag
begin
set tuple inputs_embeds token_ids_tensor_one_hot = call _get_embeddings input_ids
set output = model inputs_embeds=inputs_embeds return_dict=true use_cache=false
set predict = logits
set scores = predict at tuple slice... | def _generate_token(self, input_ids, past, do_sample: bool, temperature: float, top_k: int, top_p: float,
attribution_flag: Optional[bool]):
inputs_embeds, token_ids_tensor_one_hot = self._get_embeddings(input_ids)
output = self.model(inputs_embeds=inputs_embeds, return_dict=Tru... | Python | nomic_cornstack_python_v1 |
function flush self refresh=true
begin
raise call NotImplementedError string abstract method
end function | def flush(self, refresh=True):
raise NotImplementedError("abstract method") | Python | nomic_cornstack_python_v1 |
function subpix_quadrature image peaks halfwidth=3
begin
set subpix_peaks = list
for tuple px py in peaks
begin
comment halfwidth points on each side of the the peak
comment data.shape == (2*halfwidth+1, 2*halfwidth+1)
set data = image at tuple slice px - halfwidth : px + halfwidth + 1 : slice py - halfwidth : py + h... | def subpix_quadrature(image, peaks, halfwidth=3):
subpix_peaks = []
for px, py in peaks:
# halfwidth points on each side of the the peak
# data.shape == (2*halfwidth+1, 2*halfwidth+1)
data = image[px-halfwidth:px+halfwidth+1,
py-halfwidth:py+halfwidth+1]
x =... | Python | nomic_cornstack_python_v1 |
set lista = list 3 5 7 8 9 0
set milista = list comprehension key + 1 for key in lista if key < 8
print milista | lista = [3,5,7,8,9,0,]
milista = [key + 1 for key in lista if key < 8 ]
print(milista) | Python | zaydzuhri_stack_edu_python |
async function async_set_repeat self repeat
begin
if repeat == ALL
begin
set repeat_mode = string playlist
end
else
if repeat == ONE
begin
set repeat_mode = string song
end
else
begin
set repeat_mode = string none
end
await call async_set_repeat repeat_mode
end function | async def async_set_repeat(self, repeat: RepeatMode) -> None:
if repeat == RepeatMode.ALL:
repeat_mode = "playlist"
elif repeat == RepeatMode.ONE:
repeat_mode = "song"
else:
repeat_mode = "none"
await self._player.async_set_repeat(repeat_mode) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
function solution b
begin
if b <= 4
begin
return 0
end
set str_binary = format string {0:b} b
set first = find str_binary string 1
set last = reverse find str_binary string 1
set str_binary = str_binary at slice first : last + 1 :
set temp_binary = split str_binary string 1
if length temp... | # -*- coding: utf-8 -*-
def solution(b):
if b <= 4:
return 0
str_binary = "{0:b}".format(b)
first = str_binary.find('1')
last = str_binary.rfind('1')
str_binary = str_binary[first:last+1]
temp_binary = str_binary.split("1")
if len(temp_binary) <= 2:
return 0
max_lengt... | Python | zaydzuhri_stack_edu_python |
function save_imgs self
begin
print string Saving the images with required categories ...
make directories imgs_dir exist_ok=true
comment Save the images into a local folder
for im in call tqdm images
begin
set img_data = content
with open join path imgs_dir im at string file_name string wb as handler
begin
write handl... | def save_imgs(self):
print("Saving the images with required categories ...")
os.makedirs(self.imgs_dir, exist_ok=True)
# Save the images into a local folder
for im in tqdm(self.images):
img_data = requests.get(im['coco_url']).content
with open(os.path.join(self.im... | Python | nomic_cornstack_python_v1 |
function element_effective_area freq_hz
begin
set freqs = array list 50000000.0 70000000.0 110000000.0 170000000.0 250000000.0 350000000.0 450000000.0 550000000.0 650000000.0
set a_eff = array list 1.8791 1.8791 1.8694 1.3193 0.608 0.2956 0.2046 0.1384 0.0792
set f_cut = 2
set f1 = interp 1d call log10 freqs at slice ... | def element_effective_area(freq_hz):
freqs = np.array([0.05e9, 0.07e9, 0.11e9, 0.17e9, 0.25e9, 0.35e9, 0.45e9,
0.55e9, 0.65e9])
a_eff = np.array([1.8791, 1.8791, 1.8694, 1.3193, 0.6080, 0.2956, 0.2046,
0.1384, 0.0792])
f_cut = 2
f1 = interp1d(np.log10(freqs[:f... | Python | nomic_cornstack_python_v1 |
import cv2
import numpy as np
comment カレンダー
set original_img = call imread string test3.jpg
set size = shape at 0 * shape at 1
set img = call cvtColor original_img COLOR_BGR2HLS
set img at 10 > img at tuple slice : : slice : : 0 = 0
set img at 90 < img at tuple slice : : slice : : 0 = 0
call imwrite string ... | import cv2
import numpy as np
# カレンダー
original_img = cv2.imread("test3.jpg")
size = original_img.shape[0] * original_img.shape[1]
img = cv2.cvtColor(original_img, cv2.COLOR_BGR2HLS)
img[10>img[:,:,0]]= 0
img[90<img[:,:,0]]= 0
cv2.imwrite("calendar_mod.png", img)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imwrite... | Python | zaydzuhri_stack_edu_python |
function handle_media environ
begin
comment TODO: implement me
return tuple 200 list format _html title=string MEDIA head=string body=string MEDIA
end function | def handle_media( environ ):
# TODO: implement me
return 200, [], _html.format(
title = 'MEDIA',
head = '',
body = 'MEDIA'
) | Python | nomic_cornstack_python_v1 |
from flask import Flask , render_template , request , redirect , url_for , flash
import json
import os.path
comment This tool allows us to make sure user uploaded files are safe
from werkzeug.utils import secure_filename
comment This is the name of the module running in flask
set app = call Flask __name__
comment This ... | from flask import Flask, render_template, request, redirect, url_for, flash
import json
import os.path
from werkzeug.utils import secure_filename # This tool allows us to make sure user uploaded files are safe
app = Flask(__name__) # This is the name of the module running in flask
app.secret_key = 'h323r842sdf23r843' ... | Python | zaydzuhri_stack_edu_python |
function source_droplet_ids self
begin
return get pulumi self string source_droplet_ids
end function | def source_droplet_ids(self) -> Optional[pulumi.Input[Sequence[pulumi.Input[int]]]]:
return pulumi.get(self, "source_droplet_ids") | Python | nomic_cornstack_python_v1 |
class ValidationError extends BaseException
begin
function __init__ self err_msg *args
begin
set err_msg = err_msg
call __init__ *args
end function
function __repr__ self
begin
return err_msg
end function
end class | class ValidationError(BaseException):
def __init__(self, err_msg, *args: object):
self.err_msg = err_msg
super().__init__(*args)
def __repr__(self) -> str:
return self.err_msg
| Python | zaydzuhri_stack_edu_python |
comment n coins can be exchanged with -> n/2 , n/3 , n/4 coins
comment given n coins find max dollars we can get for it .
set arr = dictionary
function coins n
begin
if n < 10
begin
return n
end
global arr
comment if arr[n] doesn't work in case of dictionaries.
if n in arr
begin
return arr at n
end
set x = call coins n... | # n coins can be exchanged with -> n/2 , n/3 , n/4 coins
# given n coins find max dollars we can get for it .
arr = dict()
def coins(n):
if n < 10:
return n
global arr
if n in arr: ## if arr[n] doesn't work in case of dictionaries.
return arr[n]
x = coins(n//2)+coins(n//3)+coins(n//4)... | Python | zaydzuhri_stack_edu_python |
function __repr__ self
begin
return string <RegistrationForm('%s', '%s', '%s')> % tuple data data data
end function | def __repr__(self):
return "<RegistrationForm('%s', '%s', '%s')>" % (self.name.data, self.fullname.data, self.email.data) | Python | nomic_cornstack_python_v1 |
function from_factor req action user_id credstore config
begin
return call VCCSPasswordFactor action req user_id credstore config
end function | def from_factor(req, action, user_id, credstore, config):
return VCCSPasswordFactor(action, req, user_id, credstore, config) | Python | nomic_cornstack_python_v1 |
import re
set s = string Bitcoin was born on Jan 3rd 2009 as an alternative to the failure of the current financial system. In 2017, the price of 1 BTC reached $20000, with a market cap of over $300B.
set result1 = match string Bitcoin s
print call group
string if the string is not found then below error will be thrown... | import re
s = "Bitcoin was born on Jan 3rd 2009 as an alternative to the failure of the current financial system. In 2017, the price of 1 BTC reached $20000, with a market cap of over $300B."
result1 = re.match("Bitcoin", s)
print(result1.group())
'''
if the string is not found then below error will be thrown
Trace... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
from __future__ import division
import nltk
import re
function ch03_10
begin
set sent = split re string string The dog gave John the newspaper
end function | #!/usr/bin/python
from __future__ import division
import nltk
import re
def ch03_10():
sent = re.split(" ", "The dog gave John the newspaper") | Python | zaydzuhri_stack_edu_python |
for i in range x
begin
set l at i = integer l at i
end
set count = 0
for i in range x
begin
set n = i + 1
for j in range n x
begin
if l at i + l at j == k
begin
set count = count + 1
end
end
end
if count >= 1
begin
print string yes
end
else
begin
print string no
end | for i in range(x):
l[i] = int(l[i])
count = 0
for i in range(x):
n = i+1
for j in range(n,x):
if l[i]+l[j] == k:
count += 1
if(count>=1):
print("yes")
else:
print("no")
| Python | zaydzuhri_stack_edu_python |
function save_to_django_model self model batch_size=none
begin
set mymodel = none
set column_names = none
set mapdict = none
set data_wrapper = none
set name_columns_by_row = - 1
set name_rows_by_column = - 1
set objs = none
set using_rows = false
if is instance model tuple
begin
if length model == 1
begin
set mymodel ... | def save_to_django_model(self, model, batch_size=None):
mymodel = None
column_names = None
mapdict = None
data_wrapper = None
name_columns_by_row = -1
name_rows_by_column = -1
objs = None
using_rows = False
if isinstance(model, tuple):
... | Python | nomic_cornstack_python_v1 |
comment noqa: E501 # noqa: E501
function __init__ self **kwargs
begin
set local_vars_configuration = get kwargs string local_vars_configuration call get_default_copy
set _disks = none
set _vm_id = none
set _vm_name = none
set _vm_snapshot_status = none
set discriminator = none
if string disks in kwargs
begin
set disks ... | def __init__(self, **kwargs): # noqa: E501 # noqa: E501
self.local_vars_configuration = kwargs.get("local_vars_configuration", Configuration.get_default_copy())
self._disks = None
self._vm_id = None
self._vm_name = None
self._vm_snapshot_status = None
self.discriminato... | Python | nomic_cornstack_python_v1 |
comment Graph: An efficient graph.
comment A graph implementation that uses an adjacency list to represent vertices
comment and edges.
comment Your implementation should pass the tests in test_graph.py.
comment Lauryn Gomez
import functools
class Graph
begin
function __init__ self data=none
begin
set data = dict
end f... | # Graph: An efficient graph.
# A graph implementation that uses an adjacency list to represent vertices
# and edges.
# Your implementation should pass the tests in test_graph.py.
# Lauryn Gomez
import functools
class Graph:
def __init__(self, data = None):
self.data = {}
def adjacent(self, v1, v2):
... | Python | zaydzuhri_stack_edu_python |
comment string->boolean
function checkWhiteSpace string
begin
string check if a string contains only white space
for letter in string
begin
if letter != string
begin
return true
end
end
return false
end function
class Song
begin
comment Song(string,string,string,string,string,string)
function __init__ self artist albu... | #string->boolean
def checkWhiteSpace(string):
'''check if a string contains only white space'''
for letter in string:
if letter!=' ':
return True;
return False;
class Song:
#Song(string,string,string,string,string,string)
def __init__(self,artist,album,song,mp3,genre):... | Python | zaydzuhri_stack_edu_python |
function from_data cls data
begin
set runs_data = data at string runs
set working_dir = data at string working_dir
set apps_dir = get data string apps_dir
comment Read tau options and ensure tau_exec is in PATH
set tau_profiling = get data string tau_profiling false
set tau_tracing = get data string tau_tracing false
c... | def from_data(cls, data):
runs_data = data["runs"]
working_dir = data["working_dir"]
apps_dir = data.get("apps_dir")
# Read tau options and ensure tau_exec is in PATH
tau_profiling = data.get("tau_profiling", False)
tau_tracing = data.get("tau_tracing", False)
... | Python | nomic_cornstack_python_v1 |
if BMI < 18.5
begin
set section = string Underweight
end
else
if 18.5 <= BMI < 25
begin
set section = string Normal Weight
end
else
if 25 <= BMI < 30
begin
set section = string Overweight
end
else
begin
set section = string Obese
end
print string Your risk factory is { section } | if BMI<18.5 :
section = "Underweight"
elif 18.5<=BMI<25 :
section = "Normal Weight"
elif 25<=BMI<30 :
section = "Overweight"
else :
section = "Obese"
print(f"Your risk factory is {section}") | Python | zaydzuhri_stack_edu_python |
class vec
begin
string A class representing 2d vector Implements basic vector arithmetic operations
function __init__ self x y=none
begin
if y is none
begin
comment Init from tuple
set tuple x y = x
end
else
begin
comment Init from coordinates
set tuple x y = tuple x y
end
end function
function __add__ self other
begin... | class vec:
""" A class representing 2d vector
Implements basic vector arithmetic operations
"""
def __init__(self, x, y=None):
if y is None:
self.x, self.y = x # Init from tuple
else:
self.x, self.y = x, y # Init from coordinates
def __add__(self, other):... | Python | zaydzuhri_stack_edu_python |
function pig_it text
begin
return join string list comprehension if expression is alpha i then i at slice 1 : : + i at 0 + string ay else i for i in list split text
end function
print call pig_it string Pig latin is cool?
string Move the first letter of each word to the end of it, then add 'ay' to the end of the wor... | def pig_it(text):
return ' '.join([i[1:]+i[0]+'ay' if i.isalpha() else i for i in list(text.split())])
print(pig_it('Pig latin is cool?'))
'''
Move the first letter of each word to the end of it, then add 'ay' to the end of the word.
pig_it('Pig latin is cool') # igPay atinlay siay oolcay
''' | Python | zaydzuhri_stack_edu_python |
comment True
print all list false
comment False
print all list false true
comment False
print all list true true
comment True | #
# True
print( all( [False] ))
#
# False
print( all( [False, True] ))
#
# False
print( all( [True, True] ))
#
# True
| Python | zaydzuhri_stack_edu_python |
function set_releasetype self releasetype
begin
call setChecked true
end function | def set_releasetype(self, releasetype):
self._releasetype_button_mapping[releasetype].setChecked(True) | Python | nomic_cornstack_python_v1 |
comment 일 평균 30만주이상 거래되는 nasdaq, newyork, amex 중(300k_day_coms.xlsx)
comment 20일 이평선 아래에서 최저점을 지나 상승하는 종목 추출(case3_under20_follow.xlsx)
comment 30$ 이하 종목으로 turn around 종목(20 이평선이 60 이평선 아래 있는 경우)
comment 일 1회 가동
from pandas_datareader import data as pdr
import yfinance as yf
import pandas as pd
import matplotlib.pyplot... | # 일 평균 30만주이상 거래되는 nasdaq, newyork, amex 중(300k_day_coms.xlsx)
# 20일 이평선 아래에서 최저점을 지나 상승하는 종목 추출(case3_under20_follow.xlsx)
# 30$ 이하 종목으로 turn around 종목(20 이평선이 60 이평선 아래 있는 경우)
# 일 1회 가동
from pandas_datareader import data as pdr
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
import ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import logging
import tables
from collections import OrderedDict
from scikits.audiolab import Sndfile
from scikits.audiolab import available_file_formats
import os
import sys
append path directory name path directory name path absolute path path __file__
import init
import config
from groun... | #!/usr/bin/env python
import logging
import tables
from collections import OrderedDict
from scikits.audiolab import Sndfile
from scikits.audiolab import available_file_formats
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import init
import config
from ground_truth im... | Python | zaydzuhri_stack_edu_python |
function post_drawing_fbx self request
begin
set HttpRequest = call to_http_info configuration
return call __make_request HttpRequest string POST string file
end function | def post_drawing_fbx(self, request):
HttpRequest = request.to_http_info(self.api_client.configuration)
return self.__make_request(HttpRequest, 'POST', 'file') | Python | nomic_cornstack_python_v1 |
comment Kushendra Ramrup
import random
function build_random_list size max_value
begin
set l = list
set i = 0
while i < size
begin
append l call randrange 0 max_value
set i = i + 1
end
return l
end function
print call build_random_list 10 99
function locate l value
begin
print l
set i = 0
while i < length l
begin
if l... | #Kushendra Ramrup
import random
def build_random_list(size, max_value):
l = []
i= 0
while i < size:
l.append(random.randrange(0,max_value))
i = i+1
return l
print(build_random_list(10, 99))
def locate(l, value):
print(l)
i = 0
while i < len(l):
if l[i] == value:
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment Tuenti Challenge 3
comment Challenge 17 - Silence on the wire
comment Please gentlemen... look directly at the blinking light
comment [Flashes neuralyzer]
string # CODE USED TO DECODE THE INFORMATION IN THE VIDEO import sys import cv if __name__ == '__m... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Tuenti Challenge 3
#
# Challenge 17 - Silence on the wire
# Please gentlemen... look directly at the blinking light
# [Flashes neuralyzer]
'''
# CODE USED TO DECODE THE INFORMATION IN THE VIDEO
import sys
import cv
if __name__ == '__main__':
capture = cv.Captur... | Python | zaydzuhri_stack_edu_python |
function apply_fn_to_curves curves dependent_var_fn independent_var_trim=none
begin
set curves_new = list
for curve in curves
begin
if independent_var_trim == string drop
begin
append curves_new call dependent_var_fn curve at tuple 1 slice : :
end
else
begin
set curve_indices = range shape at 1
if independent_var_tr... | def apply_fn_to_curves(curves, dependent_var_fn, independent_var_trim=None):
curves_new = []
for curve in curves:
if independent_var_trim == 'drop':
curves_new.append(dependent_var_fn(curve[1, :]))
else:
curve_indices = range(curve.shape[1])
if independent_var_trim is not None:
cur... | Python | nomic_cornstack_python_v1 |
import turtle
function koch t length
begin
if length < 3
begin
call fd length
end
else
begin
call koch t length / 3
call lt 60
call koch t length / 3
call rt 60
call koch t length / 3
call lt 60
call koch t length / 3
end
end function
set bob = call Turtle
print bob
call koch bob 500
call mainloop | import turtle
def koch(t, length):
if length < 3:
t.fd(length)
else:
koch(t, length / 3)
t.lt(60)
koch(t, length / 3)
t.rt(60)
koch(t, length / 3)
t.lt(60)
koch(t, length / 3)
bob = turtle.Turtle()
print(bob)
koch(bob, 500)
turtle.mainloop() | Python | zaydzuhri_stack_edu_python |
function test_custom_schema
begin
set graph = call create_object_graph string example testing=true
set codec = find pubsub_message_schema_registry MEDIA_TYPE
call assert_that schema call is_ call instance_of DerivedSchema
end function | def test_custom_schema():
graph = create_object_graph("example", testing=True)
codec = graph.pubsub_message_schema_registry.find(DerivedSchema.MEDIA_TYPE)
assert_that(codec.schema, is_(instance_of(DerivedSchema))) | Python | nomic_cornstack_python_v1 |
function next self
begin
set next_sentence = call next_sentence
if next_sentence != none
begin
return next_sentence
end
else
begin
raise StopIteration
end
end function | def next(self):
next_sentence = self.next_sentence()
if next_sentence != None:
return next_sentence
else:
raise StopIteration | Python | nomic_cornstack_python_v1 |
function bounding_box self
begin
set shapes = call shapes
if not shapes
begin
return none
end
return reduce lambda a b -> union a b generator expression call bounding_box for shape in shapes
end function | def bounding_box(self) -> Optional[Rect]:
shapes = self.shapes()
if not shapes:
return None
return reduce(
lambda a, b: a.union(b), (shape.bounding_box() for shape in shapes)
) | Python | nomic_cornstack_python_v1 |
function _presigned_config_url imagebuilder
begin
comment Do not fail request when S3 bucket is not available
set config_url = string NOT_AVAILABLE
try
begin
set config_url = presigned_config_url
end
except AWSClientError as e
begin
error e
end
return config_url
end function | def _presigned_config_url(imagebuilder):
# Do not fail request when S3 bucket is not available
config_url = "NOT_AVAILABLE"
try:
config_url = imagebuilder.presigned_config_url
except AWSClientError as e:
LOGGER.error(e)
return config_url | Python | nomic_cornstack_python_v1 |
import os
import itertools
class Main extends object
begin
change directory string Text input
function __init__ self
begin
set lst = list
set path = string passport_processing.txt
set count = 1
set countValid = 0
set currentstring = string
set lst = list string byr string iyr string eyr string hgt string hcl string e... | import os
import itertools
class Main(object):
os.chdir("Text input")
def __init__(self):
self.lst = []
self.path = "passport_processing.txt"
self.count = 1
self.countValid = 0
self.currentstring = ""
self.lst = ["byr","iyr","eyr","hgt","hcl","ecl"... | Python | zaydzuhri_stack_edu_python |
string Plotting related functionality
import os
import numpy as np
import matplotlib
from matplotlib.colors import ListedColormap , LinearSegmentedColormap
call use string Agg
from matplotlib import pyplot as plt
function get_cds_regions annotations
begin
string Returns a chromosome-indexed dict of CDS locations for a ... | """
Plotting related functionality
"""
import os
import numpy as np
import matplotlib
from matplotlib.colors import ListedColormap,LinearSegmentedColormap
matplotlib.use('Agg')
from matplotlib import pyplot as plt
def get_cds_regions(annotations):
"""Returns a chromosome-indexed dict of CDS locations for a
sp... | Python | zaydzuhri_stack_edu_python |
function delete_event self event_id
begin
string Delete a event Arguments: event_id (str): The database key for the event
info format string Deleting event{0} event_id
if not is instance event_id ObjectId
begin
set event_id = call ObjectId event_id
end
call delete_one dict string _id event_id
debug format string Event ... | def delete_event(self, event_id):
"""Delete a event
Arguments:
event_id (str): The database key for the event
"""
LOG.info("Deleting event{0}".format(event_id))
if not isinstance(event_id, ObjectId):
event_id = ObjectId(event_id)
self.even... | Python | jtatman_500k |
import numpy as np
import pandas as pd
function loadData filename
begin
set data = read csv filename sep=string \s+ header=none
set data = values
set tuple row col = shape
set data = concatenate tuple ones tuple row 1 data axis=1
set X = data at tuple slice : : slice : - 1 :
set y = data at tuple slice : : slic... | import numpy as np
import pandas as pd
def loadData(filename):
data = pd.read_csv(filename, sep='\s+', header=None)
data = data.values
row, col = data.shape
data = np.concatenate((np.ones((row, 1)), data), axis=1)
X = data[:, :-1]
y = data[:, col:col + 1]
return X, y
def mistake(ypred, y... | Python | zaydzuhri_stack_edu_python |
function test_list_time_min_length_1_nistxml_sv_iv_list_time_min_length_2_4 mode save_output output_format
begin
call assert_bindings schema=string nistData/list/time/Schema+Instance/NISTSchema-SV-IV-list-time-minLength-2.xsd instance=string nistData/list/time/Schema+Instance/NISTXML-SV-IV-list-time-minLength-2-4.xml c... | def test_list_time_min_length_1_nistxml_sv_iv_list_time_min_length_2_4(mode, save_output, output_format):
assert_bindings(
schema="nistData/list/time/Schema+Instance/NISTSchema-SV-IV-list-time-minLength-2.xsd",
instance="nistData/list/time/Schema+Instance/NISTXML-SV-IV-list-time-minLength-2-4.xml",
... | Python | nomic_cornstack_python_v1 |
function reset_due_date request course_id
begin
set course = call get_course_by_id call from_deprecated_string course_id
set student = call get_student_from_identifier get GET string student
set unit = call find_unit course get GET string url
call set_due_date_extension course unit student none
return call JsonResponse... | def reset_due_date(request, course_id):
course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))
student = get_student_from_identifier(request.GET.get('student'))
unit = find_unit(course, request.GET.get('url'))
set_due_date_extension(course, unit, student, None)
r... | Python | nomic_cornstack_python_v1 |
comment Given a RNA sequence and codon table, generate corresponding translated sequence
import re
function readFileOfCodons codonFile
begin
set codonFileRead = open codonFile string r
set linesRead = string
for line in codonFileRead
begin
set linesRead = linesRead + line
end
close codonFileRead
return linesRead
end f... | ## Given a RNA sequence and codon table, generate corresponding translated sequence
import re
def readFileOfCodons(codonFile):
codonFileRead = open(codonFile,'r')
linesRead = '\n'
for line in codonFileRead:
linesRead+=line
codonFileRead.close()
return linesRead
def convertReadCodonFileToDict(codonFile... | Python | zaydzuhri_stack_edu_python |
function loadPuzzle
begin
set board = list
set fileHandle = open string sudokutest.txt string r
set puzzle = read lines fileHandle
for line in range length puzzle
begin
if line != length puzzle - 1
begin
set puzzle at line = puzzle at line at slice : - 1 :
append board list map int split puzzle at line string ,
end
... | def loadPuzzle():
board = []
fileHandle = open("sudokutest.txt", "r")
puzzle = fileHandle.readlines()
for line in range(len(puzzle)):
if line != len(puzzle) - 1:
puzzle[line] = puzzle[line][:-1]
board.append(list(map(int,puzzle[line].split(","))))
else:
... | Python | nomic_cornstack_python_v1 |
function alsoLikes self
begin
set relatedDocs = call alsoLikesFast datamng inputDoc inputUser
if relatedDocs
begin
print relatedDocs
end
end function | def alsoLikes(self):
relatedDocs = self.data_ana.alsoLikesFast(self.datamng, self.inputDoc, self.inputUser)
if relatedDocs:
print(relatedDocs) | Python | nomic_cornstack_python_v1 |
string wordCounter URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views ... | """wordCounter URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-b... | Python | zaydzuhri_stack_edu_python |
function __iter__ self
begin
yield match
raise StopIteration
end function | def __iter__(self):
yield self.match
raise StopIteration | Python | nomic_cornstack_python_v1 |
function train_gensim_topicvec_sklearnclassifier classdict nb_topics sklearn_classifier preprocessor=call standard_text_preprocessor_1 topicmodel_algorithm=string lda toweigh=true normalize=true gensim_paramdict=dict sklearn_paramdict=dict
begin
comment topic model training
set modelerdict = dict string lda LDAModeler... | def train_gensim_topicvec_sklearnclassifier(classdict,
nb_topics,
sklearn_classifier,
preprocessor=textpreprocess.standard_text_preprocessor_1(),
... | Python | nomic_cornstack_python_v1 |
function is_binary image
begin
return sum image == call amin image + sum image == call amax image > 0.99 * size
end function | def is_binary(image):
return sum(image==amin(image))+sum(image==amax(image)) > 0.99*image.size | Python | nomic_cornstack_python_v1 |
async function on_error self event *args **kwargs
begin
set ext_name = __name__
exception string Error from { ext_name } extension on event: { event } , args: { args } , kwargs: { kwargs }
set ex_type = call exc_info at 0
set ex = call exc_info at 1
set tb = call format_exception *sys.exc_info()
set name = __name__
set... | async def on_error(self, event, *args, **kwargs) -> None:
ext_name = type(self).__name__
logging.exception(f'Error from {ext_name} extension on event: {event}, args: {args}, kwargs: {kwargs}')
ex_type = sys.exc_info()[0]
ex = sys.exc_info()[1]
tb = traceback.format_exception(*sy... | Python | nomic_cornstack_python_v1 |
from collections import deque
set tuple N M = map int split input
set array = list comprehension list for _ in range N + 1
for _ in range M
begin
set tuple A B = map int split input
append array at B A
end
function bfs V
begin
set q = deque list V
set visited = list false * N + 1
set visited at V = true
set count = 1
... | from collections import deque
N, M = map(int, input().split())
array = [[] for _ in range(N+1)]
for _ in range(M):
A,B = map(int, input().split())
array[B].append(A)
def bfs(V):
q = deque([V])
visited = [False] * (N+1)
visited[V] = True
count = 1
while q:
V = q.p... | Python | zaydzuhri_stack_edu_python |
function datetime_to_url dt parts=3
begin
set fragments = list string year_{0.year:04} string month_{0.month:02} string day_{0.day:02}
return format join string / fragments at slice : parts : dt + string /
end function | def datetime_to_url(dt, parts=3):
fragments = ["year_{0.year:04}", "month_{0.month:02}", "day_{0.day:02}"]
return "/".join(fragments[:parts]).format(dt) + "/" | Python | nomic_cornstack_python_v1 |
function translate_onnx_type_to_numpy tensor_type
begin
if tensor_type not in onnx_tensor_type_map
begin
raise exception format string Unknown ONNX tensor type = {} tensor_type
end
return onnx_tensor_type_map at tensor_type
end function | def translate_onnx_type_to_numpy(tensor_type: int):
if tensor_type not in onnx_tensor_type_map:
raise Exception("Unknown ONNX tensor type = {}".format(tensor_type))
return onnx_tensor_type_map[tensor_type] | Python | nomic_cornstack_python_v1 |
function is_read_only instance
begin
if call show_global_variables instance at string read_only == string ON
begin
return true
end
end function | def is_read_only(instance):
if show_global_variables(instance)["read_only"] == "ON":
return True | Python | nomic_cornstack_python_v1 |
function _async_start_tracking self
begin
if trackable and _async_unsub_state_changed is none
begin
set _async_unsub_state_changed = call async_track_state_change_event hass trackable _async_state_changed_listener
end
call _async_update_group_state
end function | def _async_start_tracking(self) -> None:
if self.trackable and self._async_unsub_state_changed is None:
self._async_unsub_state_changed = async_track_state_change_event(
self.hass, self.trackable, self._async_state_changed_listener
)
self._async_update_group_stat... | Python | nomic_cornstack_python_v1 |
function swap array firstIndex secondIndex
begin
set temp = array at firstIndex
set array at firstIndex = array at secondIndex
set array at secondIndex = temp
end function
function indexOfMinimum array startIndex
begin
set minValue = array at startIndex
set minIndex = startIndex
for i in call xrange minIndex + 1 length... | def swap(array, firstIndex, secondIndex):
temp = array[firstIndex]
array[firstIndex] = array[secondIndex]
array[secondIndex] = temp
def indexOfMinimum(array, startIndex):
minValue = array[startIndex]
minIndex = startIndex
for i in xrange(minIndex + 1, len(array)):
if minValue > array[i... | Python | zaydzuhri_stack_edu_python |
function equ2gal ra dec
begin
set tuple ra dec = map radians tuple ra dec
set ra_gp = call radians 192.85948
set de_gp = call radians 27.12825
set lcp = call radians 122.932
set sin_b = sin de_gp * sin dec + cos de_gp * cos dec * cos ra - ra_gp
set lcpml = call arctan2 cos dec * sin ra - ra_gp cos de_gp * sin dec - sin... | def equ2gal(ra, dec):
ra, dec = map(radians, (ra, dec))
ra_gp = radians(192.85948)
de_gp = radians(27.12825)
lcp = radians(122.932)
sin_b = (sin(de_gp) * sin(dec) + cos(de_gp) *
cos(dec) * cos(ra - ra_gp))
lcpml = arctan2(cos(dec) * sin(ra - ra_gp),
cos(de_gp) * sin(... | Python | nomic_cornstack_python_v1 |
function new_line self line
begin
comment prevent double empty lines
set out_line = if expression call _is_blank line then string else call _current_indent_space + line
if call _prev_blank_line and out_line == string
begin
return
end
call _add_line_raw out_line
end function | def new_line(self, line: str) -> None:
# prevent double empty lines
out_line = '' if self._is_blank(line) else self._current_indent_space() + line
if self._prev_blank_line() and out_line == '':
return
self._add_line_raw(out_line) | Python | nomic_cornstack_python_v1 |
import requests
from bs4 import BeautifulSoup as bs
from time import sleep
import re
import pandas as pd
set s = call Session
function login_douban
begin
set login_url = string https://accounts.douban.com/j/mobile/login/basic
set data = dict string ck string ; string name string 17604762977 ; string password string lx... | import requests
from bs4 import BeautifulSoup as bs
from time import sleep
import re
import pandas as pd
s= requests.Session()
def login_douban():
login_url = 'https://accounts.douban.com/j/mobile/login/basic'
data={
"ck":"",
"name":"17604762977",
"password":"lxm8225873",
"rem... | Python | zaydzuhri_stack_edu_python |
function _register_with_storage self nestable=false
begin
set _storages at content_class = self
set _storages at __name__ = self
set _storages at lower __name__ = self
comment Add here the logic to change the actual class and add the decorator
comment this is the same as add the decorator (without default_storage,
comm... | def _register_with_storage(self, nestable = False):
self.storage._storages[self.content_class] = self
self.storage._storages[self.content_class.__name__] = self
self.storage._storages[self.content_class.__name__.lower()] = self
# Add here the logic to change the actual class and add th... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
string This script is a module but it can also be used as a standalone script. If you specify a gallery URL, this script will download that gallery. While 01_download_galleries_on_first_page.py only downloads galleries _on the main page_, with this script you can download any gallery on fus... | #!/usr/bin/env python
"""
This script is a module but it can also be used as a
standalone script.
If you specify a gallery URL, this script will download
that gallery.
While 01_download_galleries_on_first_page.py only downloads
galleries _on the main page_, with this script you can
download any gallery on fuskator.... | Python | zaydzuhri_stack_edu_python |
import requests
from models import UserModel
from django.http import HttpResponse , JsonResponse
from config import APPID , SECRET
comment 根据openid查找用户信息
function findByOpenid id
begin
set user = filter openid=id
if length user == 0
begin
return none
end
return user at 0
end function
comment 根据openid获取信用值
function getC... | import requests
from .models import UserModel
from django.http import HttpResponse, JsonResponse
from .config import APPID, SECRET
# 根据openid查找用户信息
def findByOpenid(id):
user = UserModel.objects.filter(openid=id)
if len(user) == 0:
return None
return user[0]
# 根据openid获取信用值
def getCreditByOpenid... | Python | zaydzuhri_stack_edu_python |
comment Sekwencje DNA - bioinformatyka lab 1 zadanie domowe
comment Izabela Orlowska, python 3.4
comment wywolanie: $ python Izabela.Orlowska.1.py <input file>
comment przyklad: $ python Izabela.Orlowska.1.py hemoglobin.txt
function count sequence
begin
return dict string A count sequence string A ; string T count sequ... | # Sekwencje DNA - bioinformatyka lab 1 zadanie domowe
# Izabela Orlowska, python 3.4
# wywolanie: $ python Izabela.Orlowska.1.py <input file>
# przyklad: $ python Izabela.Orlowska.1.py hemoglobin.txt
def count(sequence):
return {'A': sequence.count('A'), 'T': sequence.count('T'), 'C': sequence.count('C'), 'G': ... | Python | zaydzuhri_stack_edu_python |
function upload_package self branch package
begin
pass
end function | def upload_package(self, branch, package):
pass | Python | nomic_cornstack_python_v1 |
import cv2
import numpy as np
set cap = call VideoCapture 0
set tuple image_x image_y = tuple 100 100
from keras.models import load_model
set classifier = call load_model string digit.h5
compile loss=string binary_crossentropy optimizer=string rmsprop metrics=list string accuracy
function predictor
begin
import numpy a... | import cv2
import numpy as np
cap = cv2.VideoCapture(0)
image_x, image_y = 100,100
from keras.models import load_model
classifier = load_model('digit.h5')
classifier.compile(loss='binary_crossentropy',optimizer='rmsprop',metrics=['accuracy'])
def predictor():
import numpy as np
from ker... | Python | zaydzuhri_stack_edu_python |
function preview_wait self timeout
begin
set timeout = integer timeout
if timeout < 1
begin
raise call ValueError string Start time shall be greater than 0
end
set timer = call PoolingTimer timeout
while not call is_timeout
begin
call show_image call _get_preview_image
end
end function | def preview_wait(self, timeout):
timeout = int(timeout)
if timeout < 1:
raise ValueError("Start time shall be greater than 0")
timer = PoolingTimer(timeout)
while not timer.is_timeout():
self._window.show_image(self._get_preview_image()) | Python | nomic_cornstack_python_v1 |
function best_response self opponents_actions tie_breaking=string smallest payoff_perturbation=none tol=none random_state=none
begin
string Return the best response action(s) to `opponents_actions`. Parameters ---------- opponents_actions : scalar(int) or array_like A profile of N-1 opponents' actions, represented by e... | def best_response(self, opponents_actions, tie_breaking='smallest',
payoff_perturbation=None, tol=None, random_state=None):
"""
Return the best response action(s) to `opponents_actions`.
Parameters
----------
opponents_actions : scalar(int) or array_like
... | Python | jtatman_500k |
function export self
begin
set fileName = settings at string projectName + string _codebook.txt
set options = DontResolveSymlinks ? ShowDirsOnly
set directory = call getExistingDirectory none string Select directory to save file call getenv string HOME options
if directory
begin
set fileName = directory + string / + fi... | def export(self):
fileName = self.settings['projectName'] + "_codebook.txt"
options = QtWidgets.QFileDialog.DontResolveSymlinks | QtWidgets.QFileDialog.ShowDirsOnly
directory = QtWidgets.QFileDialog.getExistingDirectory(None,"Select directory to save file",os.getenv('HOME'), options)
i... | Python | nomic_cornstack_python_v1 |
async function send_with_image call resp pk text keyboard image_key
begin
set file_path = get resp image_key
set filename = split file_path string / at - 1
set file_data = await call get_or_none filename=filename parent_id=pk
if not file_data
begin
set resp_file = await get Conn file_path user_id=id
set msg = await cal... | async def send_with_image(call: types.CallbackQuery, resp: dict, pk: int,
text: str, keyboard: types.InlineKeyboardMarkup,
image_key: str):
file_path = resp.get(image_key)
filename = file_path.split('/')[-1]
file_data = await File.get_or_none(filename=file... | Python | nomic_cornstack_python_v1 |
if length root != 0 and root at - 1 != string /
begin
set root = root + string /
end
print root | if (len(root) != 0) and (root[-1] != "/"):
root+="/"
print(root) | Python | zaydzuhri_stack_edu_python |
set var = string Hello World
print var
set var = 13.98
print var
set var = 98
print var | var="Hello World"
print(var)
var=13.98
print(var)
var=98
print(var)
| Python | zaydzuhri_stack_edu_python |
function dt self
begin
function format_time dt
begin
return if expression dt then string format time dt string %Y/%m/%d %H:%M else string
end function
class DateTime
begin
function __init__ this
begin
set pending = call format_time pending_time
set running = call format_time running_time
set finished = call format_tim... | def dt(self) -> Dict[str, str]:
def format_time(dt):
return strftime(dt, '%Y/%m/%d %H:%M') if dt else ''
class DateTime():
def __init__(this):
this.pending = format_time(self.pending_time)
this.running = format_time(self.running_time)
... | Python | nomic_cornstack_python_v1 |
comment from inspect import isfunction
comment class Pep8Warrior:
comment def __new__(cls, *args, **kwargs):
comment name, parents, attrs = args
comment new_name = name.title().replace('_', '')
comment new_attrs = {}
comment print(new_name)
comment for attr, value in attrs.items():
comment if attr.startswith('__'):
com... | # from inspect import isfunction
# class Pep8Warrior:
# def __new__(cls, *args, **kwargs):
# name, parents, attrs = args
# new_name = name.title().replace('_', '')
# new_attrs = {}
# print(new_name)
# for attr, value in attrs.items():
# if attr.startswith('__'):... | Python | zaydzuhri_stack_edu_python |
function make_instance self include_optional
begin
comment model = synclient.models.version_info.VersionInfo() # noqa: E501
if include_optional
begin
return call VersionInfo content_md5=string 0 content_size=string 0 id=string 0 modified_by=string 0 modified_by_principal_id=string 0 modified_on=string 0 version_comment... | def make_instance(self, include_optional):
# model = synclient.models.version_info.VersionInfo() # noqa: E501
if include_optional :
return VersionInfo(
content_md5 = '0',
content_size = '0',
id = '0',
modified_by = '0',
... | Python | nomic_cornstack_python_v1 |
function nonregistered_create_graph
begin
try
begin
set public_association = join string generator expression random choice ascii_uppercase + ascii_lowercase + digits for x in range 8
set unregistered_graph_data = dict string url public_association ; string graph public_association ; string type string mapping ; strin... | def nonregistered_create_graph():
try:
public_association = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for x in range(8))
unregistered_graph_data = {
'url': public_association,
'graph': public_association,
'type': 'mapping',
'date_cr... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*-encoding: utf-8-*-
comment Author: Danil Kovalenko
import json
import numpy as np
from info_metrics_computer.impl import InformationalMetricsComputer
function read_data file_name
begin
with open file_name as f
begin
return load json f
end
end function
function test file_name
beg... | #!/usr/bin/env python3
# -*-encoding: utf-8-*-
# Author: Danil Kovalenko
import json
import numpy as np
from info_metrics_computer.impl import InformationalMetricsComputer
def read_data(file_name: str) -> dict:
with open(file_name) as f:
return json.load(f)
def test(file_name):
data = read_data(... | Python | zaydzuhri_stack_edu_python |
function test_api_v1_configuration_management_tools_post self
begin
pass
end function | def test_api_v1_configuration_management_tools_post(self):
pass | Python | nomic_cornstack_python_v1 |
function get self request department
begin
try
begin
set dep = get objects name__iexact=department
end
except DoesNotExist
begin
return call HttpResponse string Department not found
end
set result = dict string department name ; string questions list ; string grades list ; string stages list ; string sections list
for ... | def get(self, request, department):
try:
dep = DepartmentsModel.objects.get(name__iexact=department)
except DepartmentsModel.DoesNotExist:
return HttpResponse('Department not found')
result = {'department': dep.name,
'questions': list(),
... | Python | nomic_cornstack_python_v1 |
import numpy as np
import sklearn.preprocessing as sp
import sklearn.ensemble as se
import sklearn.model_selection as ms
import matplotlib.pyplot as mp
set data = list
with open string car.txt string r as f
begin
for line in read lines f
begin
append data split line at slice : - 1 : string ,
end
end
set data = T
set... | import numpy as np
import sklearn.preprocessing as sp
import sklearn.ensemble as se
import sklearn.model_selection as ms
import matplotlib.pyplot as mp
data = []
with open('car.txt', 'r') as f:
for line in f.readlines():
data.append(line[:-1].split(','))
data = np.array(data).T
encoders, x = [], []
for ro... | Python | zaydzuhri_stack_edu_python |
function find_delta a b c
begin
if a == 0
begin
raise call ValueError string a is 0! [y = ax^2 + bx + c , a != 0]
end
set delta = b ^ 2 - 4 * a * c
return delta
end function | def find_delta(a, b, c):
if a == 0:
raise ValueError("a is 0! [y = ax^2 + bx + c , a != 0]")
delta = b**2 - 4*a*c
return delta | Python | nomic_cornstack_python_v1 |
import streamlit as st
import numpy as np
import pandas as pd
import time
if call checkbox string Show table
begin
string # My first app First attempt at using data to create a table
set df = call DataFrame dict string x list 1 2 3 ; string x^3 list comprehension x ^ 3 for x in list 1 2 3
df
end
if call checkbox string... | import streamlit as st
import numpy as np
import pandas as pd
import time
if st.sidebar.checkbox('Show table'):
"""
# My first app
First attempt at using data to create a table
"""
df = pd.DataFrame({
'x': [1, 2, 3],
'x^3': [x**3 for x in [1, 2, 3]]
})
df
if st.sidebar.checkbox('Show data frame'):
"""
... | Python | zaydzuhri_stack_edu_python |
class AccountError extends Exception
begin
function __init__ self value
begin
set value = value
end function
function str self
begin
return call repr value
end function
end class
function make_account balance rate
begin
set lastTime = 0
function withdraw amount t
begin
nonlocal balance
nonlocal lastTime
nonlocal rate
i... | class AccountError(Exception):
def __init__(self, value):
self.value = value
def str(self):
return repr(self.value)
def make_account(balance, rate):
lastTime = 0
def withdraw(amount, t):
nonlocal balance
nonlocal lastTime
nonlocal rate
if balance < amount:
raise Accou... | Python | zaydzuhri_stack_edu_python |
function start self
begin
call send_event string start
return call wait_all_in_state string Running _timeout
end function | def start(self):
self.send_event('start')
return self.wait_all_in_state('Running', self._timeout) | Python | nomic_cornstack_python_v1 |
comment An un-ordered, unique collection of elements.
comment Used when you care if something exists or not. Not when you're concerned with the frequency or order.
comment Create a set
set x = set
comment Create a set that has elements inside of it. This is a set literal. Notice duplicates are not displayed.
set s = se... | # An un-ordered, unique collection of elements.
# Used when you care if something exists or not. Not when you're concerned with the frequency or order.
# Create a set
x = set()
# Create a set that has elements inside of it. This is a set literal. Notice duplicates are not displayed.
s = {1,1,1,1,114,104,23,123,1,4... | Python | zaydzuhri_stack_edu_python |
function change_width self value
begin
set edge_width = value
call clearFocus
call setFocus
end function | def change_width(self, value):
self.layer.edge_width = value
self.widthSpinBox.clearFocus()
self.setFocus() | Python | nomic_cornstack_python_v1 |
import numpy as np
import cv2
set cap = call VideoCapture 0
while 1
begin
set tuple _ frame = read cap
set red = call matrix frame at tuple slice : : slice : : 2
set green = call matrix frame at tuple slice : : slice : : 1
set blue = call matrix frame at tuple slice : : slice : : 0
comment np.int16() ... | import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(1):
_,frame = cap.read() #
red = np.matrix(frame[:,:,2])
green = np.matrix(frame[:,:,1])
blue = np.matrix(frame[:,:,0])
red_only = np.int16(red) - np.int16(green) - np.int16(blue) # np.int16() gives us values in int16, so th... | Python | zaydzuhri_stack_edu_python |
comment More on '{maxHeaps}' datastructures By {Chris Murimi}.
string " - maxHeap is a binary tree in which the value of the parent node is always greater than the value of its all children nodes - Operations in a maxHeap: * push - appends an item to the end of the maxHeap and floats it up to its required position * Po... | # More on '{maxHeaps}' datastructures By {Chris Murimi}.
""""
- maxHeap is a binary tree in which the value of the parent node is always greater than the value of
its all children nodes
- Operations in a maxHeap:
* push - appends an item to the end of the maxHeap and floats it up to its required position
* ... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.