code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
string This module is used to practice creating iterators and generators.
from string import punctuation
import re
class SentenceIterator
begin
string Iterator for class Sentence
function __init__ self words
begin
string Initializing the fields of the class
set __words = words
set __index = 0
end function
decorator pro... | """This module is used to practice creating iterators and generators."""
from string import punctuation
import re
class SentenceIterator:
"""Iterator for class Sentence"""
def __init__(self, words):
"""Initializing the fields of the class"""
self.__words = words
self.__index = 0
@... | Python | zaydzuhri_stack_edu_python |
comment Created by Manav Patni
comment Program to find factorial of any number
set num = integer input string Enter any number here:-
set n = num
set fact = 1
while num >= 1
begin
set fact = fact * num
set num = num - 1
end
print string Factorial of n string is fact | #Created by Manav Patni
#Program to find factorial of any number
num = int(input("Enter any number here:- "))
n = num
fact = 1
while num >= 1:
fact = fact * num
num = num - 1
print("Factorial of", n, "is", fact)
| Python | zaydzuhri_stack_edu_python |
set day_temperatures = list 28 28.9 28 29 29 30 31 32 34 36 40 32 30
append day_temperatures 49
insert day_temperatures 4 31
del day_temperatures at 5
del day_temperatures at 6
print day_temperatures at 13
print day_temperatures at 13
print day_temperatures at 13
print day_temperatures | day_temperatures = [28, 28.9, 28, 29, 29, 30, 31, 32, 34, 36, 40, 32, 30]
day_temperatures.append(49)
day_temperatures.insert(4, 31)
del day_temperatures[5]
del day_temperatures[6]
print(day_temperatures[13])
print(day_temperatures[13])
print(day_temperatures[13])
print(day_temperatures) | Python | zaydzuhri_stack_edu_python |
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm , AuthenticationForm , UsernameField
from django.contrib.auth.models import User
from django import forms
from django.contrib.auth.validators import UnicodeUsernameValidator
class CreateUserForm extends UserCreationForm
begin
set ... | from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm, UsernameField
from django.contrib.auth.models import User
from django import forms
from django.contrib.auth.validators import UnicodeUsernameValidator
class CreateUserForm(UserCreationForm):
error_messages... | Python | zaydzuhri_stack_edu_python |
import numpy as np
set x = call rand 5 5
set a = array x - min / max - min
print a | import numpy as np
x = np.random.rand(5,5)
a = (np.array(x)-x.min())/(x.max()-x.min())
print(a)
| Python | zaydzuhri_stack_edu_python |
function __init__ self _x=0 _y=0 _z=0
begin
set this = call new_Point3D _x _y _z
try
begin
append this this
end
except any
begin
set this = this
end
end function | def __init__(self, _x = 0, _y = 0, _z = 0):
this = _fife.new_Point3D(_x, _y, _z)
try: self.this.append(this)
except: self.this = this | Python | nomic_cornstack_python_v1 |
from game.units.unitsinterface import Units
class Army extends Units
begin
function __init__ self
begin
set hp = 5000
set dmg = 250
end function
end class | from game.units.unitsinterface import Units
class Army(Units):
def __init__(self):
self.hp = 5000
self.dmg = 250
| Python | zaydzuhri_stack_edu_python |
function get_B_T_smooth steps R angle_init angle_end d
begin
set res = 0
set theta = call generate_smooth_theta 0 steps R angle_init angle_end d
for t in range 1 steps
begin
set temp = call generate_smooth_theta t steps R angle_init angle_end d
set res = res + norm temp - theta
set theta = temp
end
return res
end funct... | def get_B_T_smooth(steps, R, angle_init, angle_end, d):
res = 0
theta = generate_smooth_theta(0, steps, R, angle_init, angle_end, d)
for t in range(1, steps):
temp = generate_smooth_theta(t, steps, R, angle_init, angle_end, d)
res += np.linalg.norm(temp - theta)
theta = temp
retu... | Python | nomic_cornstack_python_v1 |
function width self width
begin
set _width = width
end function | def width(self, width):
self._width = width | Python | nomic_cornstack_python_v1 |
import io
import textwrap
import unittest
from typing import List
comment type: ignore
import dockerfile
from docker_optimizer.mainapp import DockerCommand , optimize_docker_commands , write_docker_commands
class TestDockerOptimizer extends TestCase
begin
function test_FROM_command self
begin
call _parse_content string... | import io
import textwrap
import unittest
from typing import List
import dockerfile # type: ignore
from docker_optimizer.mainapp import DockerCommand, optimize_docker_commands, write_docker_commands
class TestDockerOptimizer(unittest.TestCase):
def test_FROM_command(self):
self._parse_content("FROM ubu... | Python | zaydzuhri_stack_edu_python |
function is_file_empty file_path
begin
comment Check if file exist and it is empty
return exists path file_path and st_size == 0
end function | def is_file_empty(file_path):
# Check if file exist and it is empty
return os.path.exists(file_path) and os.stat(file_path).st_size == 0 | Python | nomic_cornstack_python_v1 |
function invoke_sync self qualifier payload
begin
set response = call invoke FunctionName=config at string FunctionName InvocationType=string RequestResponse LogType=string Tail Payload=payload or bytes string Qualifier=qualifier
set response at string LogResultDecoded = call decodestring response at string LogResult
r... | def invoke_sync(self, qualifier, payload):
response = self.aws_lambda.invoke(
FunctionName=self.config['FunctionName'],
InvocationType='RequestResponse',
LogType='Tail',
Payload=payload or bytes(''),
Qualifier=qualifier
)
response['Log... | Python | nomic_cornstack_python_v1 |
function read_file filename
begin
set merchant = list
with open filename as f
begin
set x = list
for line in f
begin
if line at 0 != string #
begin
comment print(line.strip('\n'))
append x strip line string
end
end
end
set q = x at 0
set sigma = x at 1
set start = x at 2
set f = x at 3
set delta = x at slice 4 : :
s... | def read_file (filename):
merchant = list()
with open( filename ) as f:
x=[]
for line in f:
if line[0] != '#':
# print(line.strip('\n'))
x.append(line.strip('\n'))
q = x[0]
sigma = x[1]
start = x[2]
f = x[3]
delta = x[... | Python | nomic_cornstack_python_v1 |
function connect
begin
return call connect loginValues at string DB
end function | def connect():
return psycopg2.connect(loginValues['DB']) | Python | nomic_cornstack_python_v1 |
comment Functions to read data from sensors
import smbus
import time
import math
from numpy import mean
from timeit import default_timer as timer
class Error extends Exception
begin
string Base class for other exceptions
pass
end class
class SensorError extends Error
begin
string Raised when the input value is too smal... | # Functions to read data from sensors
import smbus
import time
import math
from numpy import mean
from timeit import default_timer as timer
class Error(Exception):
"""Base class for other exceptions"""
pass
class SensorError(Error):
"""Raised when the input value is too small"""
pass
bus = smbus.... | Python | zaydzuhri_stack_edu_python |
from weapon import Weapon
class Sword extends Weapon
begin
function __init__ self
begin
call __init__ string Sword
set name = string Sword
set damage = 5
set cost = 5
end function
function ultimate_damage self
begin
return damage * 10
end function
end class
function main
begin
Sword
end function
if __name__ == string _... | from weapon import Weapon
class Sword(Weapon):
def __init__(self):
super().__init__("Sword")
self.name = "Sword"
self.damage = 5
self.cost = 5
def ultimate_damage(self):
return self.damage*10
def main():
Sword
if __name__ == "__main__":
main()
| Python | zaydzuhri_stack_edu_python |
function diving_minigame lst
begin
set c = 10
for i in lst
begin
if i > 0
begin
if c < 10
begin
set c = c + 4
end
else
begin
set c = c + 0
end
end
else
if i < 0
begin
set c = c - 2
if c == 0
begin
return false
end
end
end
return c > 0
end function | def diving_minigame(lst):
c = 10
for i in lst:
if i > 0:
if c < 10:
c += 4
else:
c += 0
elif i < 0:
c -= 2
if c == 0:
return False
return c > 0
| Python | zaydzuhri_stack_edu_python |
import sys
import numpy as np
from pandas import DataFrame
import cPickle as pickle
import time
set V = 10
set WEEK = 7
set DAY = 7
set threshold = 50
function prepare
begin
set dat = open string data/part-r-00000 string r
set dat_write = open string data/part-r-00000_nihao string w
set count = 0
set seg = string
comm... | import sys
import numpy as np
from pandas import DataFrame
import cPickle as pickle
import time
V=10
WEEK=7
DAY=7
threshold=50
def prepare():
dat=open('data/part-r-00000','r')
dat_write=open('data/part-r-00000_nihao','w')
count=0
seg='\t'
map={}#(user,user_id)
map_dic={} #(user_id,user)
dic={}
for line in dat.... | Python | zaydzuhri_stack_edu_python |
function read
begin
comment recibimos la longitud del tablero NxN
set n = integer input
set tmp = list
set table = list
comment entrada por teclado o archivo:
for i in range n
begin
append tmp call raw_input
end
comment convertimos el string a una matriz por ahora de caracteres
for i in range length tmp
begin
append ... | def read():
# recibimos la longitud del tablero NxN
n = int(input())
tmp = []
table = []
#entrada por teclado o archivo:
for i in range(n):
tmp.append(raw_input())
#convertimos el string a una matriz por ahora de caracteres
for i in range(len(tmp)):
table.append(tmp[i].split(" "))
#casteamo... | Python | zaydzuhri_stack_edu_python |
function checkforitems curpos
begin
if DARK and not HAS_FLASHLIGHT
begin
comment was 2
call printmessage string But you can't see a thing! 5 MAGENTA 2
return
end
comment if the item at curpos isnt 'None'
if ITEM_LIST at curpos != integer length ITEMTYPES - 2
begin
call printmessage string You found a %s! % ITEMTYPES at... | def checkforitems(curpos):
if DARK and not HAS_FLASHLIGHT:
printmessage("But you can't see a thing!", 5, MAGENTA, 2) # was 2
return
if ITEM_LIST[curpos] != int(len(ITEMTYPES) - 2): # if the item at curpos isnt 'None'
printmessage("You found a %s!" % ITEMTYPES[ITEM_LIST[curpos]], 5, MAGE... | Python | nomic_cornstack_python_v1 |
function clean_decisions rows
begin
set indcons = list
set cntrycons = list
function make_id_counter
begin
string Simple little closure for getting the next available id number :returns : a function which will produce the next number in sequence
set next_id = 1
function id_counter
begin
nonlocal next_id
set id_num = ... | def clean_decisions(rows):
indcons = []
cntrycons = []
def make_id_counter():
"""
Simple little closure for getting the next available id number
:returns : a function which will produce the next number in sequence
"""
next_id = 1
def id_counter():
nonlocal next_id
id_num = next_id
next_id +=... | Python | nomic_cornstack_python_v1 |
function typePath self text=string keys=list keysModifiers=list img=none description=string unknown similar=0.7
begin
if not is instance keys list
begin
raise call ValueException call caller string keys argument is not a list (%s) % type keys
end
comment raise Exception('list expected for keys')
if not is instance k... | def typePath(self, text='', keys=[], keysModifiers=[], img=None, description='unknown', similar=0.70):
if not isinstance( keys, list):
raise TestAdapterLib.ValueException(TestAdapterLib.caller(), "keys argument is not a list (%s)" % type(keys) )
#raise Exception('list expected for keys'... | Python | nomic_cornstack_python_v1 |
function angle_diff ang
begin
while ang > pi
begin
set ang = ang - 2 * pi
end
while ang < - pi
begin
set ang = ang + 2 * pi
end
return ang
end function | def angle_diff(ang):
while ang > math.pi:
ang -= 2*math.pi
while ang < -math.pi:
ang += 2*math.pi
return ang | Python | nomic_cornstack_python_v1 |
function _guess_num_nodes num_nodes source=none target=none
begin
if num_nodes is not none
begin
return num_nodes
end
if source is none and target is none
begin
raise call ValueError string If no num_nodes are given, either source, or target must be given!
end
return max generator expression item max for x in tuple sou... | def _guess_num_nodes(
num_nodes: Optional[int],
source: Optional[NodeIDs] = None,
target: Optional[NodeIDs] = None,
) -> int:
if num_nodes is not None:
return num_nodes
if source is None and target is None:
raise ValueError('If no num_nodes are given, either source, or target must be... | Python | nomic_cornstack_python_v1 |
function filtered_data data regime_matrix class_label filter_vars
begin
set tuple percUP_matrix percDOWN_matrix meanUP_matrix meanDOWN_matrix cvUP_matrix cvDOWN_matrix scc_lag0_matrix scc_lag1_matrix = data
set percup_filter = percUP_matrix at filter_vars
set percdown_filter = percDOWN_matrix at filter_vars
set meanup_... | def filtered_data(data,regime_matrix,class_label,filter_vars):
percUP_matrix,percDOWN_matrix,meanUP_matrix,meanDOWN_matrix,cvUP_matrix,cvDOWN_matrix,scc_lag0_matrix,scc_lag1_matrix = data
percup_filter = percUP_matrix[filter_vars]
percdown_filter = percDOWN_matrix[filter_vars]
meanup_filter = meanUP_m... | Python | nomic_cornstack_python_v1 |
import pygame
from math import ceil
from time import time
comment Initialize pygame
call init
comment Initialize screen
set window_size = tuple 900 500
set screen = call set_mode window_size
call set_caption string Sorting Algorithm Visualizer
comment Color palette
set grey = tuple 100 100 100
set green = tuple 125 240... | import pygame
from math import ceil
from time import time
# Initialize pygame
pygame.init()
# Initialize screen
window_size = (900, 500)
screen = pygame.display.set_mode(window_size)
pygame.display.set_caption("Sorting Algorithm Visualizer")
# Color palette
grey = (100, 100, 100)
green = (125, 240, 125)
white = (250... | Python | zaydzuhri_stack_edu_python |
function setUp self
begin
setup call super
call signup OWNER_EMAIL OWNER_USERNAME
set owner_id = call get_user_id_from_email OWNER_EMAIL
call signup EDITOR_EMAIL EDITOR_USERNAME
set editor_id = call get_user_id_from_email EDITOR_EMAIL
call save_new_valid_exploration EXP_ID owner_id end_state_name=string End
end functio... | def setUp(self) -> None:
super().setUp()
self.signup(self.OWNER_EMAIL, self.OWNER_USERNAME)
self.owner_id = self.get_user_id_from_email(self.OWNER_EMAIL)
self.signup(self.EDITOR_EMAIL, self.EDITOR_USERNAME)
self.editor_id = self.get_user_id_from_email(self.EDITOR_EMAIL)
... | Python | nomic_cornstack_python_v1 |
import sys
function revList lst start howmany
begin
set howmany = start + howmany - 1
while start <= howmany
begin
set tuple lst at start % size lst at howmany % size = tuple lst at howmany % size lst at start % size
set start = start + 1
set howmany = howmany - 1
end
return lst
end function
set filename = argv at 1
se... | import sys
def revList(lst,start,howmany):
howmany = start+howmany-1
while start <= howmany:
lst[start % size], lst[howmany % size] = lst[howmany % size], lst[start % size]
start+=1
howmany-=1
return lst
filename = sys.argv[1]
size = int(sys.argv[2])
with open(filename) as f:
... | Python | zaydzuhri_stack_edu_python |
from activations import *
from optimizers import s_sgd
from utils import numba_backward , numba_predict
string The different Layers are implemented in this file. Every sequential net consists of different/stacked layers
class Dense
begin
function __init__ self input_dim output_dim batch_size=24 optimizer=s_sgd
begin
st... | from activations import *
from optimizers import s_sgd
from utils import numba_backward, numba_predict
"""
The different Layers are implemented in this file.
Every sequential net consists of different/stacked layers
"""
class Dense:
def __init__(self, input_dim, output_dim, batch_size=24, optimizer=s_sgd):
... | Python | zaydzuhri_stack_edu_python |
string Given an integer, n, and n space-separated integers as input, create a tuple, t, of those n integers. Then compute and print the result of hash(t). Note: hash() is one of the functions in the __builtins__ module, so it need not be imported.
if __name__ == string __main__
begin
comment Unnecessary line of code, b... | '''
Given an integer, n, and n space-separated integers as input,
create a tuple, t, of those n integers. Then compute and print the result of hash(t).
Note: hash() is one of the functions in the __builtins__ module, so it need not be imported.
'''
if __name__ == '__main__':
n = int(input()) # Unnecessary line o... | Python | zaydzuhri_stack_edu_python |
function get_rev_num rev
begin
try
begin
set rev_parts = split re string [-+_] rev
comment get numeric part of the version string
set num = list comprehension integer i for i in split rev_parts at 0 string .
comment normalize num to be of length 3
set num = num + list 0 * 3 - length num
comment get identifier part of t... | def get_rev_num(rev):
try:
rev_parts = re.split('[-+_]', rev)
# get numeric part of the version string
num = [int(i) for i in rev_parts[0].split('.')]
num += [0] * (3 - len(num)) # normalize num to be of length 3
# get identifier part of the version string
if len(rev... | Python | nomic_cornstack_python_v1 |
from concurrent.futures import ThreadPoolExecutor
import threading
function action max
begin
set my_sum = 0
for i in range max
begin
print call getName + string + string i
set my_sum = my_sum + i
end
return my_sum
end function
with call ThreadPoolExecutor max_workers=4 as pool
begin
set results = map action tuple 50 1... | from concurrent.futures import ThreadPoolExecutor
import threading
def action(max):
my_sum = 0
for i in range(max):
print(threading.current_thread().getName() + ' ' + str(i))
my_sum += i
return my_sum
with ThreadPoolExecutor(max_workers=4) as pool:
results = pool.map(action, (50, 100... | Python | zaydzuhri_stack_edu_python |
function musician_ads request
begin
set all_ads = all
set context = dict string all_ads all_ads
return call render request string board/musician_ads_board.html context
end function | def musician_ads(request):
all_ads = Musician_Advertisement.objects.all()
context = {
'all_ads': all_ads,
}
return render(request, 'board/musician_ads_board.html', context) | Python | nomic_cornstack_python_v1 |
string Name of script: format_player_info.py Description: formats player info that was gathered from wikipedia infoboxes
import pandas as pd
set players = read csv string pga-tour-players/player_info.csv
comment fix nationalities
replace players at string nationality dict string {{ZAF}} string ZAF ; string {{AUS}} stri... | '''
Name of script: format_player_info.py
Description: formats player info that was gathered
from wikipedia infoboxes
'''
import pandas as pd
players = pd.read_csv('pga-tour-players/player_info.csv')
# fix nationalities
players['nationality'].replace({'{{ZAF}}':'ZAF', '{{AUS}}':'AUS','{{CHL}}':'CHL', '{{KOR}}':'... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
string 对MySQLdb常用函数进行封装的类 整理者:兔大侠和他的朋友们(http://www.tudaxia.com) 日期:2014-04-22 出处:源自互联网,共享于互联网:-) 注意:使用这个类的前提是正确安装 MySQL-Python模块。 官方网站:http://mysql-python.sourceforge.net/
import MySQLdb
import time
class MyDB
begin
string 对MySQLdb常用函数进行封装的类
function __init__ self ... | #!/usr/bin/python
# -*- coding: utf-8 -*-
u'''对MySQLdb常用函数进行封装的类
整理者:兔大侠和他的朋友们(http://www.tudaxia.com)
日期:2014-04-22
出处:源自互联网,共享于互联网:-)
注意:使用这个类的前提是正确安装 MySQL-Python模块。
官方网站:http://mysql-python.sourceforge.net/
'''
import MySQLdb
import time
class MyDB:
u'''对MySQLdb常用函数进行封装的类'''
def __init__(self, c... | Python | zaydzuhri_stack_edu_python |
while moreExpenses == string Y
begin
set userExpense = decimal input string Enter an expense:
set totalExpenses = totalExpenses + userExpense
end | while moreExpenses == "Y":
userExpense = float( input("Enter an expense: ") )
totalExpenses = totalExpenses + userExpense | Python | zaydzuhri_stack_edu_python |
function sql_execute_fetchall self sql_statement params=none
begin
set result_list = list
if params is none
begin
execute cur sql_statement
end
else
begin
execute cur sql_statement params
end
set sql_result = call fetchall
if sql_result is none
begin
return result_list
end
for item in sql_result
begin
set element_list... | def sql_execute_fetchall(self, sql_statement, params=None):
result_list = []
if params is None:
self.cur.execute(sql_statement)
else:
self.cur.execute(sql_statement, params)
sql_result = self.cur.fetchall()
if sql_result is None:
return result_... | Python | nomic_cornstack_python_v1 |
function getCrossSectData self phi s s_ind=none theta_arr=none no_theta=30 theta_s=0 theta_e=PI2 coordsys=none
begin
set s_b = s
comment let's check for s:
if count list s_b s_ind none == 2
begin
raise call InputDataError string no values for s and s_ind
end
comment end if([s_b,s_ind].count(None) == 2):
if coordsys == ... | def getCrossSectData(self, phi, s, s_ind=None, theta_arr=None,
no_theta=30, theta_s=0, theta_e=PI2,
coordsys=None):
s_b = s
# let's check for s:
if([s_b,s_ind].count(None) == 2):
raise InputDataError("no values for s and s_ind")
... | Python | nomic_cornstack_python_v1 |
function select_element_value self locatorList value waitStrategy=string visibility wait_time=explicit_wait_time polling_time=poll_frequency_time
begin
set element = call find_element_from_list_wait locatorList waitStrategy wait_time polling_time
call select_by_value value
return self
end function | def select_element_value(self, locatorList, value, waitStrategy="visibility", wait_time=explicit_wait_time,
polling_time=poll_frequency_time):
element = self.find_element_from_list_wait(locatorList, waitStrategy, wait_time, polling_time)
Select(element).select_by_value(value... | Python | nomic_cornstack_python_v1 |
function reinforce self
begin
comment ToDo can potentially remove this as PFA running on __init__
if empty
begin
print string Run PFA before applying reinforcement
end
else
begin
return call apply_parallel_reinforcement self overloaded_lines
end
end function | def reinforce(self):
#ToDo can potentially remove this as PFA running on __init__
if self.lines_t.p0.empty:
print('Run PFA before applying reinforcement')
else:
return apply_parallel_reinforcement(self,self.overloaded_lines) | Python | nomic_cornstack_python_v1 |
function entry_for_one_class nom klas
begin
try
begin
set tuple args varargs varkw defaults = call getargspec __init__
set argspec = call formatargspec args at slice 1 : : varargs varkw defaults
set funcdoc = __doc__
set methods = list
for attrname in directory klas
begin
set attr = get attribute klas attrname
set a... | def entry_for_one_class(nom, klas):
try:
args, varargs, varkw, defaults = inspect.getargspec(klas.__init__)
argspec = inspect.formatargspec(args[1:], varargs, varkw, defaults)
funcdoc = klas.__init__.__doc__
methods = []
for attrname in dir(klas):
attr = getattr(klas, attrname)
... | Python | nomic_cornstack_python_v1 |
function round x
begin
return round x
end function | def round(x):
return round(x) | Python | nomic_cornstack_python_v1 |
function set_default_by_alias self alias
begin
string Set the default dataset by its alias. After changing the default dataset, all calls without explicitly specifying the dataset by index or alias will be redirected to this dataset. Args: alias (str): The alias of the dataset that should be made the default. Raises: D... | def set_default_by_alias(self, alias):
""" Set the default dataset by its alias.
After changing the default dataset, all calls without explicitly specifying the
dataset by index or alias will be redirected to this dataset.
Args:
alias (str): The alias of the dataset that sh... | Python | jtatman_500k |
for x in range 11 0
begin
set n = n - 1
for a in range 0 n + 1
begin
print string end=string *
end
print
end | for x in range (11,0):
n = n - 1
for a in range (0, n+1):
print ('', end = '*')
print()
| Python | zaydzuhri_stack_edu_python |
import logging
import json
set log = call getLogger __name__
function generate_quest quest
begin
set pokestop_id = quest at string pokestop_id
set quest_reward_type = call questreward quest at string quest_reward_type
set quest_reward_type_raw = quest at string quest_reward_type
set quest_type = call questtype quest at... | import logging
import json
log = logging.getLogger(__name__)
def generate_quest(quest):
pokestop_id = (quest['pokestop_id'])
quest_reward_type = (questreward(quest['quest_reward_type']))
quest_reward_type_raw = quest['quest_reward_type']
quest_type = (questtype(quest['quest_type... | Python | zaydzuhri_stack_edu_python |
from skimage.transform import pyramid_gaussian
from skimage.transform import pyramid_expand
from skimage.io import imread
import matplotlib.pyplot as plt
import numpy as np
import imutils
import cv2
import argparse as ap
import config as cfg
import sys
function getWindowDims image winSize=list winSize winSize stride=li... | from skimage.transform import pyramid_gaussian
from skimage.transform import pyramid_expand
from skimage.io import imread
import matplotlib.pyplot as plt
import numpy as np
import imutils
import cv2
import argparse as ap
import config as cfg
import sys
def getWindowDims(image, winSize=[cfg.winSize, cfg.winSize], stri... | Python | zaydzuhri_stack_edu_python |
function putKinesis cls data stream recType=string work
begin
info string Writing results to Kinesis
set outputObject = dict string status 200 ; string data data ; string type recType
comment The default lambda function here converts all objects into dicts
set kinesisStream = call _convertToJSON outputObject
set partKe... | def putKinesis(cls, data, stream, recType='work'):
logger.info('Writing results to Kinesis')
outputObject = {
'status': 200,
'data': data,
'type': recType
}
# The default lambda function here converts all objects into dicts
kinesisStream = Ou... | Python | nomic_cornstack_python_v1 |
function test_process self
begin
set t = call Terms call Node children=list call Node string ABC5 children=list call Node string child label=list string ref1 call Node string AABBCC5 label=list string ref2 call Node string ABC3 label=list string ref3 call Node string AAA3 label=list string ref4 call Node string ABCABC3... | def test_process(self):
t = Terms(Node(children=[
Node("ABC5", children=[Node("child")], label=['ref1']),
Node("AABBCC5", label=['ref2']),
Node("ABC3", label=['ref3']),
Node("AAA3", label=['ref4']),
Node("ABCABC3", label=['ref5']),
Node("AB... | Python | nomic_cornstack_python_v1 |
comment 500個以上の約数をもつ最初の三角数を求めて表示するプログラム
comment 2番目の関数がnの増加によりとてもとても遅くなるので改良がとても必要
function a_tri_num n
begin
return integer n * n + 1 / 2
end function
function divisor n
begin
set target = call a_tri_num n
set count = 0
set divisor_list = list
for i in range 1 target * 2
begin
if target % i == 0
begin
set divisor_lis... | # 500個以上の約数をもつ最初の三角数を求めて表示するプログラム
# 2番目の関数がnの増加によりとてもとても遅くなるので改良がとても必要
def a_tri_num(n):
return int(n * (n + 1) / 2)
def divisor(n):
target = a_tri_num(n)
count = 0
divisor_list = []
for i in range(1, target * 2):
if (target % i) == 0:
divisor_list += [i]
else:
... | Python | zaydzuhri_stack_edu_python |
function get_aws_reserved_subnets vpc_id aws_region=none
begin
set response = call describe_subnets Filters=list dict string Name string vpc-id ; string Values list vpc_id at string Subnets
set reserved_subnets = list
for subnet in response
begin
append reserved_subnets call PyVPCBlock network=call ip_network subnet a... | def get_aws_reserved_subnets(vpc_id, aws_region=None):
response = boto3.client('ec2', region_name=aws_region).describe_subnets(
Filters=[
{
'Name': 'vpc-id',
'Values': [
vpc_id,
]
}
])['Subnets']
reserve... | Python | nomic_cornstack_python_v1 |
class Solution
begin
function findErrorNums self nums
begin
set currSum = 0
set acSum = 0
for num in nums
begin
set currSum = currSum + num
end
for index in range length nums + 1
begin
set acSum = acSum + index
end
set mis = absolute acSum - currSum
set dup = acSum - sum set nums
if acSum - currSum > 0
begin
return lis... | class Solution:
def findErrorNums(self, nums):
currSum = 0
acSum = 0
for num in nums:
currSum += num
for index in range(len(nums)+1):
acSum += index
mis = abs(acSum - currSum)
dup = acSum - sum(set(nums))
if acSum - currSum > ... | Python | zaydzuhri_stack_edu_python |
from aoc_tools import AoCPuzzle
set p = call AoCPuzzle string day3.txt string \#(\d+)\s+@\s+(\d+),(\d+):\s+(\d+)x(\d+)
set cloth_size = 1000
set overlaps = 0
set cloth = list comprehension list comprehension list for x in range cloth_size for y in range cloth_size
set ids = list comprehension i for i in range 1 length... | from aoc_tools import AoCPuzzle
p = AoCPuzzle('day3.txt', "\#(\d+)\s+@\s+(\d+),(\d+):\s+(\d+)x(\d+)")
cloth_size = 1000
overlaps = 0
cloth = [[[] for x in range(cloth_size)] for y in range(cloth_size)]
ids = [i for i in range(1, len(p.matchers))]
for m in p.matchers:
(id, x, y, w, h) = int(m.groups()[0]), int(m.... | Python | zaydzuhri_stack_edu_python |
from copy import deepcopy
class Vector extends tuple
begin
function __add__ self other
begin
set new_values = list
for tuple own_dimension_value other_dimension_value in zip self other
begin
append new_values own_dimension_value + other_dimension_value
end
return call Vector new_values
end function
function __sub__ se... | from copy import deepcopy
class Vector(tuple):
def __add__(self, other):
new_values = []
for own_dimension_value, other_dimension_value in zip(self, other):
new_values.append(own_dimension_value + other_dimension_value)
return Vector(new_values)
def __sub__(self, other):
... | Python | zaydzuhri_stack_edu_python |
string 1.Log in 2.Go to casino section 3.Find a game in Isoftbet section 4.Launch it
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
comment SetUp
set exec_path = string D:\chromedriver.exe
set URL = string https://www.optibet.com/login
set driver = call Chrome exec_path
... | """
1.Log in
2.Go to casino section
3.Find a game in Isoftbet section
4.Launch it
"""
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
# SetUp
exec_path = "D:\\chromedriver.exe"
URL = "https://www.optibet.com/login"
driver = webdriver.Chrome(exec_path)
driver.implicitly_... | Python | zaydzuhri_stack_edu_python |
import os
import unittest
from unittest.mock import Mock
from src.adapter.file_purchases_repository import FilePurchasesRepository
from src.domain.ecommerce_purchases import EcommerceDataFrame
class DataFrameTest extends TestCase
begin
function setUp self
begin
set file_location = join path directory name path __file__... | import os
import unittest
from unittest.mock import Mock
from src.adapter.file_purchases_repository import FilePurchasesRepository
from src.domain.ecommerce_purchases import EcommerceDataFrame
class DataFrameTest(unittest.TestCase):
def setUp(self):
file_location = os.path.join(os.path.dirname(__file__), ... | Python | zaydzuhri_stack_edu_python |
function distance a b
begin
if length a != length b
begin
raise call ValueError string Hamming Distance is only defined for strands of + string equal length. like woah!
end
return sum generator expression a != b for tuple a b in zip list a list b
end function | def distance(a, b):
if len(a) != len(b):
raise ValueError("Hamming Distance is only defined for strands of " +
"equal length. like woah!")
return sum(a != b for a, b in zip(list(a), list(b)))
| Python | zaydzuhri_stack_edu_python |
function list_domain_policy self _
begin
set FILETIME_TIMESTAMP_FIELDS = dict string lockOutObservationWindow tuple 60 string mins ; string lockoutDuration tuple 60 string mins ; string maxPwdAge tuple 86400 string days ; string minPwdAge tuple 86400 string days ; string forceLogoff tuple 60 string mins
set FOREST_LEVE... | def list_domain_policy(self, _):
FILETIME_TIMESTAMP_FIELDS = {
"lockOutObservationWindow": (60, "mins"),
"lockoutDuration": (60, "mins"),
"maxPwdAge": (86400, "days"),
"minPwdAge": (86400, "days"),
"forceLogoff": (60, "mins")
}
FOREST_... | Python | nomic_cornstack_python_v1 |
comment LED blink Demo 4
comment Date: 2020-04-18
from machine import Pin , Timer
import utime as time
comment 1=OFF, 0=ON
set LED_OFF = 1
comment use GPIO5 for LED output
set LED_GPIO = 5
function main_loop
begin
while true
begin
comment wait forever
sleep - 1
end
end function
try
begin
set led = call Pin LED_GPIO OUT... | #############################################################
# LED blink Demo 4
# Date: 2020-04-18
#############################################################
from machine import Pin, Timer
import utime as time
LED_OFF = 1 # 1=OFF, 0=ON
LED_GPIO = 5 # use GPIO5 for LED output
def main_loop( ):
wh... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python2
comment -*- coding: utf-8 -*-
string Script that scores Gaussian blurred images on scale from 1 to 5. 1 is most blurred and 5 is lease blurred. Approaches the problem by ranking the natural logarithm of the variance of the Laplacian calculated on each image. This approach works well for ex... | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Script that scores Gaussian blurred images on scale from 1 to 5.
1 is most blurred and 5 is lease blurred.
Approaches the problem by ranking the natural logarithm of the variance of the Laplacian calculated on each image.
This approach works well for extreme examples,... | Python | zaydzuhri_stack_edu_python |
function __init__ self path tier embeddings=none preprocessor=none transform=true
begin
call __init__
assert is directory path path
assert exists path join path path string { tier } .csv
assert tier in TIERS
set path = path
set tier = tier
set data = none
set embeddings = embeddings
set preprocessor = preprocessor
set ... | def __init__(
self,
path,
tier,
embeddings=None,
preprocessor=None,
transform=True):
super().__init__()
assert os.path.isdir(path)
assert os.path.exists(os.path.join(path, f'{tier}.csv'))
assert tier in self.TIERS
... | Python | nomic_cornstack_python_v1 |
comment pragma: no cover
function eval self dists
begin
pass
end function | def eval(self, dists): # pragma: no cover
pass | Python | nomic_cornstack_python_v1 |
comment 11720 숫자의 합
comment https://www.acmicpc.net/problem/11720
comment 백준에서 input안에 문자열을 집어넣을 경우 런타임에러
set length = integer input string 개수:
set num_str = input string 계산할 숫자문자열:
comment - 입력받은 문자열의 길이만큼 반복문을 돌려서 결과를 계산
comment 1. python에서 문자열을 하나씩 잘라내어 연산이 가능하므로 문자열형태로 떼어내어 정수형으로 변환해준 후 결과값을 계산
set result = 0
for n... | # 11720 숫자의 합
# https://www.acmicpc.net/problem/11720
# 백준에서 input안에 문자열을 집어넣을 경우 런타임에러
length = int(input('개수: '))
num_str = input('계산할 숫자문자열: ')
# - 입력받은 문자열의 길이만큼 반복문을 돌려서 결과를 계산
# 1. python에서 문자열을 하나씩 잘라내어 연산이 가능하므로 문자열형태로 떼어내어 정수형으로 변환해준 후 결과값을 계산
result = 0
for num in num_str:
result += int(num)
print(re... | Python | zaydzuhri_stack_edu_python |
import sqlalchemy
from sqlalchemy import Column , Integer , Float , String , Boolean , Date , ForeignKey
from sqlalchemy.orm import relationship
from lib.models.declarative_base import DeclarativeBase
import pandas as pd
from pprint import pprint
class SongDB extends DeclarativeBase
begin
set __tablename__ = string son... | import sqlalchemy
from sqlalchemy import Column, Integer, Float, String, Boolean, Date, ForeignKey
from sqlalchemy.orm import relationship
from lib.models.declarative_base import DeclarativeBase
import pandas as pd
from pprint import pprint
class SongDB(DeclarativeBase):
__tablename__ = 'songdb'
song_id = Colu... | Python | zaydzuhri_stack_edu_python |
function read_json_from_file file_name
begin
with open file_name as infile
begin
set in_data = load json infile
end
set decoded_list = list
comment Bug and Reproduce Steps
if file_name == string repro_steps.json
begin
for i in in_data
begin
set decoded = call BugReproStep i at string bug_id i at string repro_step
appe... | def read_json_from_file(file_name):
with open(file_name) as infile:
in_data = json.load(infile)
decoded_list = []
# Bug and Reproduce Steps
if file_name == 'repro_steps.json':
for i in in_data:
decoded = bug_reprostep.BugReproStep(i['bug_id'], i['repro_step'])
de... | Python | nomic_cornstack_python_v1 |
function assemblyContext self
begin
return call Occurrence
end function | def assemblyContext(self):
return fusion.Occurrence() | Python | nomic_cornstack_python_v1 |
import numpy as np
function generate_anchors_1d sequence_length=2372 base_half_width=7 width_delta=0 num_deltas=0 stride=1
begin
set anchors = list
for i in range 0 sequence_length stride
begin
for j in range num_deltas + 1
begin
set half_width = base_half_width + j * width_delta
append anchors list decimal i - half_w... | import numpy as np
def generate_anchors_1d(
sequence_length=2372,
base_half_width=7,
width_delta=0,
num_deltas=0,
stride=1):
anchors = []
for i in range(0, sequence_length, stride):
for j in range(num_deltas + 1):
half_width = (base_half_width + (j * width_delta))
... | Python | zaydzuhri_stack_edu_python |
function get_all_hits self
begin
set page_size = 100
set search_rs = call search_hits page_size=page_size
set total_records = integer TotalNumResults
end function | def get_all_hits(self):
page_size = 100
search_rs = self.search_hits(page_size=page_size)
total_records = int(search_rs.TotalNumResults) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import unittest
import logging
import typing
import pprint
string Daily Coding Problem / Inbox Problem #7 / Medium Difficulty Given the mapping a=1, b=2, ... z=26, and an encoded message, count the number of ways it can be decoded. For example, the message "111" would give 3, since it coul... | #!/usr/bin/env python3
import unittest
import logging
import typing
import pprint
"""
Daily Coding Problem / Inbox Problem #7 / Medium Difficulty
Given the mapping a=1, b=2, ... z=26, and an encoded message,
count the number of ways it can be decoded.
For example, the message "111" would give 3,
since it could be d... | Python | zaydzuhri_stack_edu_python |
function start_ui
begin
import deluge.common
comment Setup the argument parser
set parser = call OptionParser usage=string %prog [options] [actions]
call add_option string -v string --version action=string callback callback=version_callback help=string Show program's version number and exit
call add_option string -u st... | def start_ui():
import deluge.common
# Setup the argument parser
parser = OptionParser(usage="%prog [options] [actions]")
parser.add_option("-v", "--version", action="callback", callback=version_callback,
help="Show program's version number and exit")
parser.add_option("-u", "--ui", dest="u... | Python | nomic_cornstack_python_v1 |
function output_file_name self
begin
return none
end function | def output_file_name(self):
return None | Python | nomic_cornstack_python_v1 |
async function test_bad_retrieve_user_data self m
begin
with assert raises HTTPInternalServerError
begin
await call retrieve_user_data string bad_token
end
end function | async def test_bad_retrieve_user_data(self, m):
with self.assertRaises(aiohttp.web_exceptions.HTTPInternalServerError):
await retrieve_user_data("bad_token") | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
comment -*- coding: utf-8 -*-
comment @Time : 2020/04/06
comment @Author : XU Liu
comment @FileName: 1143.Longest Common Subsequence.py
string 1. 题目类型: DP 2. 题目要求与理解: 找longest common subsequence 3. 解题思路: m = len(text1) n = len(text2) dp: (m+1) * (n+1) xi: text1 yj: text2 状态转移方程: if xi == yj: dp... | # !/usr/bin/python
# -*- coding: utf-8 -*-
# @Time : 2020/04/06
# @Author : XU Liu
# @FileName: 1143.Longest Common Subsequence.py
'''
1. 题目类型:
DP
2. 题目要求与理解:
找longest common subsequence
3. 解题思路:
m = len(text1)
n = len(text2)
dp: (m+1) * (n+1)
xi: text1
yj: text2
状态转移方程:
if... | Python | zaydzuhri_stack_edu_python |
comment !/usr/local/bin/python3
set x = 1
if x > 5
begin
print string x is greater than 5
end
else
begin
print string blah
end
set y = 2
if y == 1
begin
print string she's 1
end
else
if y == 2
begin
print string she 2
end
else
if y == 3
begin
print string she 3
end
else
begin
print string another
end | #!/usr/local/bin/python3
x = 1
if (x > 5):
print("x is greater than 5")
else:
print("blah")
y = 2
if (y == 1):
print("she's 1")
elif (y == 2):
print("she 2")
elif (y == 3):
print("she 3")
else:
print("another") | Python | zaydzuhri_stack_edu_python |
function connect self addr
begin
string Call the :meth:`connect` method of the underlying socket and set up SSL on the socket, using the :class:`Context` object supplied to this :class:`Connection` object at creation. :param addr: A remote address :return: What the socket's connect method returns
call SSL_set_connect_s... | def connect(self, addr):
"""
Call the :meth:`connect` method of the underlying socket and set up SSL
on the socket, using the :class:`Context` object supplied to this
:class:`Connection` object at creation.
:param addr: A remote address
:return: What the socket's connect... | Python | jtatman_500k |
function external_owned self external_owned
begin
set _external_owned = external_owned
end function | def external_owned(self, external_owned):
self._external_owned = external_owned | Python | nomic_cornstack_python_v1 |
from RobotArm import RobotArm
set robotArm = call RobotArm string exercise 10
comment < max 15 lines of code, maar dit is als test anders is het zo langzaam. verwijder line
set speed = 3
set moveR = 9
set moveL = 8
for movement in range 5
begin
call grab
list comprehension call moveRight for movement in range moveR
dro... | from RobotArm import RobotArm
robotArm = RobotArm('exercise 10')
robotArm.speed = 3 # < max 15 lines of code, maar dit is als test anders is het zo langzaam. verwijder line
moveR = 9
moveL = 8
for movement in range (5):
robotArm.grab()
[robotArm.moveRight() for movement in range (moveR)]
robot... | Python | zaydzuhri_stack_edu_python |
import sys
set pieces = split read line stdin
set addrm = list 0 0 0 0 0 0
comment king
set addrm at 0 = string 1 - integer pieces at 0
comment queen
set addrm at 1 = string 1 - integer pieces at 1
comment rooks
set addrm at 2 = string 2 - integer pieces at 2
comment bishops
set addrm at 3 = string 2 - integer pieces a... | import sys
pieces = sys.stdin.readline().split()
addrm = [0,0,0,0,0,0]
#king
addrm[0] = str(1 - int(pieces[0]))
#queen
addrm[1] = str(1 - int(pieces[1]))
#rooks
addrm[2] = str(2 - int(pieces[2]))
#bishops
addrm[3] = str(2 - int(pieces[3]))
#knights
addrm[4] = str(2 - int(pieces[4]))
#pawns
addrm[5] = str(8 - int(pie... | Python | zaydzuhri_stack_edu_python |
function check_func_fork self fcn=string fork
begin
set rv = false
comment got to have this to work
if not call check_type_pid_t
begin
return rv
end
call check_msg fcn
comment setup the tags
set havef = call _config_tag string HAVE_ fcn
set chf = call _cache_tag string ac_cv_func_ fcn
set have_wf = call _config_tag str... | def check_func_fork(self, fcn='fork'):
rv = False
# got to have this to work
if not self.check_type_pid_t():
return rv
self.check_msg(fcn)
# setup the tags
havef = self._config_tag('HAVE_', fcn)
chf = self._cache_tag('ac_cv_func_', fcn)
have... | Python | nomic_cornstack_python_v1 |
class Utils
begin
decorator staticmethod
function read_file filename
begin
set lines_array = list
with open filename string r as file
begin
for line in file
begin
append lines_array strip line
end
end
return lines_array
end function
end class | class Utils:
@staticmethod
def read_file(filename):
lines_array = []
with open(filename, 'r') as file:
for line in file:
lines_array.append(line.strip())
return lines_array
| Python | zaydzuhri_stack_edu_python |
import paho.mqtt.client as mqtt
import json
import uuid
set URL = string localhost
set test_msg = dict string server dict string method string update-photo ; string id string uuid 1 ; string url string http://106.12.220.232/test.bmp ; string list list 0 1 2 3 4 5 6
class MyMqtt extends Client
begin
string 上行连接
set queu... | import paho.mqtt.client as mqtt
import json
import uuid
URL = 'localhost'
#
test_msg = {"server":{
"method":"update-photo",
"id":str(uuid.uuid1()),
"url":"http://106.12.220.232/test.bmp",
"list":[0,1,2,3,4,5,6]
}
}
class MyMqtt(mqtt.Client):
''... | Python | zaydzuhri_stack_edu_python |
function get_img_pos self lx
begin
set xi = call get_img xu lx
return
end function | def get_img_pos(self, lx):
self.xi = get_img(self.xu, lx)
return | Python | nomic_cornstack_python_v1 |
string 作者:王小糖 功能:BMR计算器 版本:2.0(1.0太简单了,不写了) 日期:28/12/2018 新增功能:用户交互
function main
begin
string 主函数
set y_or_n = input string 是否退出程序(y/n)?
while y_or_n == string n
begin
set gender = input string 性别:
print type gender
set weight = decimal input string 体重(kg):
set height = decimal input string 身高(cm):
set age = integer i... | """
作者:王小糖
功能:BMR计算器
版本:2.0(1.0太简单了,不写了)
日期:28/12/2018
新增功能:用户交互
"""
def main():
"""
主函数
"""
y_or_n=input("是否退出程序(y/n)?")
while y_or_n=='n':
gender=input("性别:")
print(type(gender))
weight=float(input("体重(kg):"))
height=float(input("身高(cm):"))
age=int(input("年龄:"))
if gender=="男":
BMR=(13.7... | Python | zaydzuhri_stack_edu_python |
comment encoding:utf-8
import numpy as np
import math
import cv2
class FaceOrient
begin
function __init__ self
begin
pass
end function
function face_orient_1 self points slow_rate=0 point_type=string type4 image=none
begin
string 判断人脸角度方法一
set tuple x1 y1 = points at 4
set tuple x2 y2 = points at 12
if x1 - x2 == 0
beg... | #encoding:utf-8
import numpy as np
import math
import cv2
class FaceOrient:
def __init__(self):
pass
def face_orient_1(self,points,slow_rate=0,point_type="type4",image=None):
"""
判断人脸角度方法一
"""
(x1,y1)=points[4]
(x2,y2)=points[12]
... | Python | zaydzuhri_stack_edu_python |
from abc import abstractmethod
from typing import List
from tqdm.auto import tqdm
class Model
begin
function __call__ self *args **kwargs
begin
return predict self *args keyword kwargs
end function
decorator abstractmethod
function get_prediction self text *args **kwargs
begin
pass
end function
function predict self te... | from abc import abstractmethod
from typing import List
from tqdm.auto import tqdm
class Model:
def __call__(self, *args, **kwargs):
return self.predict(*args, **kwargs)
@abstractmethod
def get_prediction(self, text: str, *args, **kwargs):
pass
def predict(self, texts: List[str], *ar... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
import sys , os
append path directory name path directory name path directory name path __file__
from kanjiProcessor import *
function main
begin
set dirname = join path directory name path directory name path __file__ string txt
comment load
set input_filename = join path dirname string 125_lines... | # coding: utf-8
import sys, os
sys.path.append(os.path.dirname( os.path.dirname (os.path.dirname(__file__) ) ) )
from kanjiProcessor import *
def main():
dirname = os.path.join( os.path.dirname( os.path.dirname(__file__)), 'txt')
# load
input_filename = os.path.join(dirname, "125_lines.txt")
lines = ... | Python | zaydzuhri_stack_edu_python |
print string -----------------------NONO DESAFIO-----------------------
print string Bem vindo a tabuada automatizada do Gabriel ^^
set nome = input string Por favor insira seu nome:
set n1 = integer input format string {}, por favor escolha um número: nome
set t1 = n1 * 1
set t2 = n1 * 2
set t3 = n1 * 3
set t4 = n1 * ... | print('-----------------------NONO DESAFIO-----------------------')
print('Bem vindo a tabuada automatizada do Gabriel ^^')
nome = input('Por favor insira seu nome:')
n1 = int(input('{}, por favor escolha um número:'.format(nome)))
t1 = (n1*1)
t2 = (n1*2)
t3 = (n1*3)
t4 = (n1*4)
t5 = (n1*5)
t6 = (n1*6)
t7 = (... | Python | zaydzuhri_stack_edu_python |
function initialize self
begin
call initialize
call update_menu_bar
end function | def initialize(self):
super(QtMainWindow, self).initialize()
self.update_menu_bar() | Python | nomic_cornstack_python_v1 |
while n < N
begin
set isDiv = 0
for div in lst
begin
if n % div == 0
begin
set isDiv = 1
break
end
end
if isDiv == 0
begin
append lst n
end
set n = n + 2
end
set count = 0
for i in lst
begin
print i end=string
set count = count + 1
if count % 5 == 0
begin
print
end
end | while n < N:
isDiv = 0
for div in lst:
if(n%div == 0):
isDiv = 1
break
if(isDiv == 0):
lst.append(n)
n = n+2
count = 0
for i in lst:
print(i, end='\t')
count = count + 1
if(count % 5 == 0):
print()
| Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
function colored color text
begin
set table = dict string red string [91m ; string green string [92m ; string nc string [0
comment no color
set cv = get table color
set nc = get table string nc
return join string list cv text nc
end function | # coding: utf-8
def colored(color, text):
table = {
'red': '\033[91m',
'green': '\033[92m',
# no color
'nc': '\033[0'
}
cv = table.get(color)
nc = table.get('nc')
return ''.join([cv, text, nc])
| Python | zaydzuhri_stack_edu_python |
import math
set a = call radians 7
set h = tan a * 25
set result = h + 1.5
print result | import math
a = math.radians(7)
h = math.tan(a)*25
result = h + 1.5
print(result)
| Python | zaydzuhri_stack_edu_python |
function get_robot_name
begin
set name = input string What do you want to name your robot?
while length name == 0
begin
set name = input string What do you want to name your robot?
end
return name
end function | def get_robot_name():
name = input("What do you want to name your robot? ")
while len(name) == 0:
name = input("What do you want to name your robot? ")
return name | Python | nomic_cornstack_python_v1 |
function find_orbit ring refpts=none **kwargs
begin
if is_6d
begin
return call find_orbit6 ring refpts=refpts keyword kwargs
end
else
begin
return call find_orbit4 ring refpts=refpts keyword kwargs
end
end function | def find_orbit(ring, refpts: Refpts = None, **kwargs):
if ring.is_6d:
return find_orbit6(ring, refpts=refpts, **kwargs)
else:
return find_orbit4(ring, refpts=refpts, **kwargs) | Python | nomic_cornstack_python_v1 |
function describe_entity_recognizer_controller self request
begin
try
begin
info string Describe Entity Recognizer Controller: { EntityRecognizerArn }
return call describe_entity_recognizer entity_recognizer_arn=EntityRecognizerArn
end
except Exception as error
begin
error string error= { error }
raise error
end
end fu... | def describe_entity_recognizer_controller(self, request):
try:
logging.info(
f"Describe Entity Recognizer Controller: {request.EntityRecognizerArn}"
)
return describe_entity_recognizer(
entity_recognizer_arn=request.EntityRecognizerArn
... | Python | nomic_cornstack_python_v1 |
function _build_url self host handler
begin
set scheme = if expression use_https then string https else string http
return string %s://%s%s % tuple scheme host handler
end function | def _build_url(self, host, handler):
scheme = "https" if self.use_https else "http"
return "%s://%s%s" % (scheme, host, handler) | Python | nomic_cornstack_python_v1 |
function test_contributor_create_both
begin
set user = call create
set contributor_user = call create
set contributor_redditor = call Mock spec=Redditor
set name = username
set api_mock = call Mock add_contributor=call Mock return_value=contributor_redditor
with raises ValueError as ex
begin
call create dict string con... | def test_contributor_create_both():
user = UserFactory.create()
contributor_user = UserFactory.create()
contributor_redditor = Mock(spec=Redditor)
contributor_redditor.name = contributor_user.username
api_mock = Mock(add_contributor=Mock(return_value=contributor_redditor))
with pytest.raises(Va... | Python | nomic_cornstack_python_v1 |
from domains.Driver import Driver
from zipfile import ZipFile
comment Create object driver
set d = call Driver
call run_Driver
comment Function to zip all .txt files
function compressing
begin
set file_paths = list string students.txt string courses.txt string marks.txt
with zip file string students.dat string w as zip... | from domains.Driver import Driver
from zipfile import ZipFile
# Create object driver
d = Driver()
d.run_Driver()
# Function to zip all .txt files
def compressing():
file_paths = ['students.txt', 'courses.txt', 'marks.txt']
with ZipFile('students.dat', 'w') as zip:
for file in file_paths:
z... | Python | zaydzuhri_stack_edu_python |
function disable_and_enable_autorestart duthost
begin
set containers_autorestart_states = call get_container_autorestart_states
set disabled_autorestart_containers = list
for tuple container_name state in items containers_autorestart_states
begin
if state == string enabled
begin
info format string Disabling the autore... | def disable_and_enable_autorestart(duthost):
containers_autorestart_states = duthost.get_container_autorestart_states()
disabled_autorestart_containers = []
for container_name, state in containers_autorestart_states.items():
if state == "enabled":
logger.info("Disabling the autorestart ... | Python | nomic_cornstack_python_v1 |
function update self curr_loss curr_state
begin
raise NotImplementedError
end function | def update(self, curr_loss, curr_state):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
for i in string1
begin
set count = count + 1
end
print count | for i in string1:
count += 1
print(count) | Python | zaydzuhri_stack_edu_python |
function int_func
begin
set x = input string Введите слово/строку с маленьких букв:
for word in split x
begin
set i = 0
for i_s in word
begin
if 97 <= ordinal i_s <= 122
begin
set i = i + 1
end
end
end
if i == length word
begin
print title x
end
else
begin
print string Вводите только английские буквы!
end
end function
... | def int_func():
x = input('Введите слово/строку с маленьких букв: ')
for word in x.split():
i = 0
for i_s in word:
if 97 <= ord(i_s) <= 122:
i += 1
if i == len(word):
print(x.title())
else:
print('Вводите только английские буквы!')
int_func() | 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.