code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment -*- coding: utf-8 -*-
import cv2
import numpy as np
from PIL import Image , ImageDraw , ImageFont , ImageColor
import requests
set RESPONSE = get requests string https://yandex.ru/pogoda/murino?utm_campaign=informer&utm_content=main_informer&utm_medium=web&utm_source=home&utm_term=title
set TEMPLATE_PATH = stri... | # -*- coding: utf-8 -*-
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont, ImageColor
import requests
RESPONSE = requests.get(
r'https://yandex.ru/pogoda/murino?utm_campaign=informer&utm_content=main_informer&utm_medium=web&utm_source'
r'=home&utm_term=title')
TEMPLATE_PATH =... | Python | zaydzuhri_stack_edu_python |
function init2 self input_tube output_tubes num_workers disable_result do_stop_task
begin
comment Read task from the input tube.
comment Send result on all the output tubes.
comment Total number of workers in the stage.
comment Whether to override any result with None.
comment Whether to call doTask() on "stop" request... | def init2(
self,
input_tube, # Read task from the input tube.
output_tubes, # Send result on all the output tubes.
num_workers, # Total number of workers in the stage.
disable_result, # Whether to override any result with None.
do_stop_task, # Whether to ... | Python | nomic_cornstack_python_v1 |
from functools import wraps
from flask import Flask , request , Response
set app = call Flask __name__
function check_auth username password
begin
return username == string admin and password == string secret
end function
function requires_auth f
begin
decorator wraps f
function decorated *args **kwargs
begin
set auth ... | from functools import wraps
from flask import Flask, request, Response
app = Flask(__name__)
def check_auth(username, password):
return username == 'admin' and password == 'secret'
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization
if not auth o... | Python | zaydzuhri_stack_edu_python |
function setUp self
begin
set player = call Player name=string Player
set player2 = call Player name=string Player 2
set player3 = call Player name=string Player 3
set game = call Game list player player2 player3 call Expansion name=string empty deck_regular=list deck_major=list landmarks=list MarketBase
comment Get ... | def setUp(self):
self.player = Player(name='Player')
self.player2 = Player(name='Player 2')
self.player3 = Player(name='Player 3')
self.game = Game([self.player, self.player2, self.player3],
cards.Expansion(name='empty',
deck_regular=[],
... | Python | nomic_cornstack_python_v1 |
function buy_item self item_name cost additional_cps
begin
if _current_cookie >= cost
begin
set _cps = _cps + additional_cps
set _current_cookie = _current_cookie - cost
append _history tuple _game_time item_name cost _total_cookies
end
return 0
end function | def buy_item(self, item_name, cost, additional_cps):
if self._current_cookie >= cost:
self._cps += additional_cps
self._current_cookie -= cost
self._history.append((self._game_time, item_name, cost, self._total_cookies))
return 0 | Python | nomic_cornstack_python_v1 |
function register_route self router path=string /ws
begin
decorator call websocket path
async function websocket_endpoint websocket
begin
await call main_loop websocket
end function
end function | def register_route(self, router, path="/ws"):
@router.websocket(path)
async def websocket_endpoint(websocket: WebSocket):
await self.main_loop(websocket) | Python | nomic_cornstack_python_v1 |
comment Emma Stoverink
comment August 31, 2018
comment Lab 1
comment Runner runs 14 km in 45 m 30 s
comment Find speed in MPH
set mile_in_km = 1.6
set distance = 14
set time = 45.5
set hour = 60
set scale = hour / time
set distance_in_miles = distance / mile_in_km
print scale * distance_in_miles
print string MPH
commen... | #Emma Stoverink
#August 31, 2018
#Lab 1
#Runner runs 14 km in 45 m 30 s
#Find speed in MPH
mile_in_km = 1.6
distance = 14
time= 45.5
hour = 60
scale = hour/time
distance_in_miles = distance / mile_in_km
print(scale * distance_in_miles)
print("MPH")
#print time / distance in km by miles in km
print((60/45.5)*(14/1.... | Python | zaydzuhri_stack_edu_python |
import sqlite3
from Menu import Menu
string Build a Python application which stores the following example data in a SQLite database Finally a program to celebrate the feats of Chainsaw Jugglers!!! This program will . . . - Let users add a new row for a record holder. - Let user search for a record holder by name. - Let... | import sqlite3
from Menu import Menu
"""
Build a Python application which stores the following example data in a SQLite database
Finally a program to celebrate the feats of Chainsaw Jugglers!!!
This program will . . .
- Let users add a new row for a record holder.
- Let user search for a record holder by name.... | Python | zaydzuhri_stack_edu_python |
function setOid self value
begin
return call setColumnValue OID_COLUMN value
end function | def setOid(self, value):
return self.getDbRecord().setColumnValue(OID_COLUMN, value) | Python | nomic_cornstack_python_v1 |
function allocate_and_init_parameters self
begin
set param_info = ordered dictionary list tuple string W_xe tuple data_dim hidden_dim tuple string W_hh tuple hidden_dim hidden_dim tuple string W_eh tuple hidden_dim hidden_dim tuple string b_h tuple hidden_dim tuple string W_ho tuple hidden_dim out_dim tuple string b_o ... | def allocate_and_init_parameters(self):
param_info = OrderedDict([
('W_xe', (self.data_dim, self.hidden_dim)), # Embedding matrix
('W_hh', (self.hidden_dim, self.hidden_dim)), # state transition
('W_eh', (self.hidden_dim, self.hidden_dim)),
('b_h', (self.... | Python | nomic_cornstack_python_v1 |
function init self info
begin
comment Run the associated Python code if the 'auto-run' feature is enabled:
if auto_run
begin
call run_code
end
end function | def init(self, info):
# Run the associated Python code if the 'auto-run' feature is enabled:
if info.object.auto_run:
info.object.run_code() | Python | nomic_cornstack_python_v1 |
comment 给定一个二维网格和一个单词,找出该单词是否存在于网格中。
comment 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
comment 示例:
comment board =
comment [
comment ['A','B','C','E'],
comment ['S','F','C','S'],
comment ['A','D','E','E']
comment ]
comment 给定 word = "ABCCED", 返回 true.
comment 给定 word = "SEE", 返回 true.
comm... | # 给定一个二维网格和一个单词,找出该单词是否存在于网格中。
# 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
# 示例:
# board =
# [
# ['A','B','C','E'],
# ['S','F','C','S'],
# ['A','D','E','E']
# ]
# 给定 word = "ABCCED", 返回 true.
# 给定 word = "SEE", 返回 true.
# 给定 word = "ABCB", 返回 false.
class Solution:
def exist(... | Python | zaydzuhri_stack_edu_python |
function run_wwfs
begin
set args = call parse_args
call main args
end function | def run_wwfs():
args = parser.parse_args()
main(args) | Python | nomic_cornstack_python_v1 |
import json
import numpy as np
import pickle
set RADIANT = 1
set DIRE = - 1
set SYNERGIES = load pickle open string data/synergy.p string rb
function synergy a b
begin
set syn = if expression b > a then SYNERGIES at tuple a b else SYNERGIES at tuple b a
set syn at string name = name
if syn at string synergy > 0
begin
s... | import json
import numpy as np
import pickle
RADIANT=1
DIRE=-1
SYNERGIES = pickle.load(open('data/synergy.p','rb'))
def synergy(a,b):
syn = SYNERGIES[(a,b)] if b > a else SYNERGIES[(b,a)]
syn['name'] = Hero.by_id(b).name
if syn['synergy'] > 0:
verb = 'performs'
else:
ve... | Python | zaydzuhri_stack_edu_python |
from sympy import *
set tuple x y = call symbols string x y
set a = call series x 10
print a
set b = call series x 0
print b
set z = 1 / cos x
print z
set w = call series x 0
print w
set v = z ^ 8
print v | from sympy import *
x,y = symbols('x y')
a = sin(x).series(x,10)
print(a)
b = sin(x).series(x,0)
print(b)
z = 1/cos(x)
print(z)
w = z.series(x,0)
print(w)
v = z**8
print(v)
| Python | zaydzuhri_stack_edu_python |
function find_module module predicate
begin
if call predicate module
begin
return module
end
set module_path = call Path *module.__path__
for sub in list comprehension parent for sub in glob module_path string **/__init__.py
begin
if sub == module_path
begin
continue
end
set sub_module_path = call relative_to module_pa... | def find_module(
module: ModuleType, predicate: Callable[[ModuleType], bool]
) -> Optional[ModuleType]:
if predicate(module):
return module
module_path = Path(*module.__path__)
for sub in [sub.parent for sub in module_path.glob("**/__init__.py")]:
if sub == module_path:
con... | Python | nomic_cornstack_python_v1 |
function testCaseSkip self
begin
set dsURI = call ODataURI string Orders?$orderby=OrderDate%20desc&$skip=10 string /x.svc
set skip = sysQueryOptions at skip
assert true type skip is IntType string skip type
assert true skip == 10 string skip 10
set dsURI = call ODataURI string Customers('ALFKI')/Orders?$skip=10 string ... | def testCaseSkip(self):
dsURI=ODataURI("Orders?$orderby=OrderDate%20desc&$skip=10",'/x.svc')
skip=dsURI.sysQueryOptions[SystemQueryOption.skip]
self.assertTrue(type(skip) is IntType,"skip type")
self.assertTrue(skip==10,"skip 10")
dsURI=ODataURI("Customers('ALFKI')/Orders?$skip=10",'/x.svc')
skip=dsURI.sysQ... | Python | nomic_cornstack_python_v1 |
function asDict self key values cache=false
begin
set recarray = call asRecArray
if cache
begin
if tuple key values not in _dictViews
begin
set _dictViews at tuple key values = dictionary zip recarray at key recarray at values
end
return _dictViews at tuple key values
end
return dictionary zip recarray at key recarray ... | def asDict( self, key, values, cache=False ):
recarray = self.asRecArray( )
if cache:
if ( key, values ) not in self._dictViews:
self._dictViews[ ( key, values ) ] = dict( zip( recarray[ key ], recarray[ values ] ) )
return self._dictViews[ ( key, values ) ]... | Python | nomic_cornstack_python_v1 |
import MapReduce
import sys
string Relational join based on Python MapReduce Framework.
set mr = call MapReduce
comment =============================
comment Do not modify above this line
function mapper record
begin
comment record = a tuple in database, type = list(str)
comment key: order_id, index = 1
comment value: ... | import MapReduce
import sys
"""
Relational join based on Python MapReduce Framework.
"""
mr = MapReduce.MapReduce()
# =============================
# Do not modify above this line
def mapper(record):
# record = a tuple in database, type = list(str)
# key: order_id, index = 1
# value: the record
key ... | Python | zaydzuhri_stack_edu_python |
function pop_extra_coords kwargs
begin
if string extra_coords in kwargs
begin
warn format string EQL gridder will ignore extra_coords: {}. kwargs at string extra_coords
pop kwargs string extra_coords
end
end function | def pop_extra_coords(kwargs):
if "extra_coords" in kwargs:
warn("EQL gridder will ignore extra_coords: {}.".format(kwargs["extra_coords"]))
kwargs.pop("extra_coords") | Python | nomic_cornstack_python_v1 |
function guess self button
begin
comment if it has already been guessed
if call get_clicked
begin
return
end
move
call click
call hover true button none
call guess coord := call get_coord false
call config text=call nearest_ship coord relief=SUNKEN bg=string grey
comment if a ship was hit
if type call output at coord a... | def guess(self, button: Square) -> None:
if (button.get_clicked()): # if it has already been guessed
return
self.move()
button.click()
self.hover(True, button, None)
self.board.guess(coord := button.get_coord(), False)
button.config(
text=self.board.nearest_ship(coord),
relief=SUNKEN,
bg='gre... | Python | nomic_cornstack_python_v1 |
function notify_width_changed self
begin
set new_table_width = sum list comprehension width for col in columns
set width = new_table_width
end function | def notify_width_changed(self):
new_table_width = sum([col.width for col in self.columns])
self._graphic_frame.width = new_table_width | Python | nomic_cornstack_python_v1 |
function register self runner
begin
add _runners runner
add _idle runner
end function | def register(self, runner):
self._runners.add(runner)
self._idle.add(runner) | Python | nomic_cornstack_python_v1 |
function has_more_commands self
begin
return _current_inst < length _lines - 1
end function | def has_more_commands(self):
return self._current_inst < len(self._lines) - 1 | Python | nomic_cornstack_python_v1 |
function test_recycling_not_enabled
begin
set client = call TestClient app
set response = get client url=string http://localhost/v1/pois/osm:node:36153800
assert status_code == 200
set resp = json response
assert resp at string id == string osm:node:36153800
assert resp at string name == string Poubelle
assert length l... | def test_recycling_not_enabled():
client = TestClient(app)
response = client.get(url=f"http://localhost/v1/pois/osm:node:36153800")
assert response.status_code == 200
resp = response.json()
assert resp["id"] == "osm:node:36153800"
assert resp["name"] == "Poubelle"
assert len([x for x in r... | Python | nomic_cornstack_python_v1 |
function findRasters dirFiles newGDB uniquePrefix=none
begin
comment import modules
import os , arcpy
from datetime import datetime
comment start_time = datetime.now()
change directory dirFiles
set root = get current directory
end function | def findRasters(dirFiles, newGDB, uniquePrefix = None):
import os, arcpy #import modules
from datetime import datetime
#start_time = datetime.now()
os.chdir(dirFiles)
root = os.getcwd() | Python | nomic_cornstack_python_v1 |
function codegen_reload_data
begin
return dict string package string fn_mcafee_tie ; string message_destinations list string mcafee_tie_md ; string functions list string mcafee_tie_set_file_reputation string mcafee_tie_search_hash ; string workflows list string mcafee_tie_get_file_reputation string mcafee_tie_get_lates... | def codegen_reload_data():
return {
"package": u"fn_mcafee_tie",
"message_destinations": [u"mcafee_tie_md"],
"functions": [u"mcafee_tie_set_file_reputation", u"mcafee_tie_search_hash"],
"workflows": [u"mcafee_tie_get_file_reputation", u"mcafee_tie_get_latest_reputation", u"mcafee_tie... | Python | nomic_cornstack_python_v1 |
function phi U n
begin
set phi_params = n at string phi
return phi_params at string r_max / 1 + exp - phi_params at string beta * U - phi_params at string alpha
end function | def phi(U, n):
phi_params = n['phi']
return phi_params['r_max'] / (1 + np.exp(-phi_params['beta'] * (U - phi_params['alpha']))) | Python | nomic_cornstack_python_v1 |
comment this is the fastest way to calculate combinations
set c_prev = list 1
set c_new = list
for n in range runs
begin
append c_new n + 1
append c_new 1
for k in range 1 n
begin
set c_new at k = c_prev at k + c_prev at k - 1
end
set tuple c_new c_prew = tuple c_prev c_new
end | # this is the fastest way to calculate combinations
c_prev = [1]
c_new = []
for n in range(runs):
c_new.append(n + 1)
c_new.append(1)
for k in range(1, n):
c_new[k] = c_prev[k] + c_prev[k - 1]
c_new, c_prew = c_prev, c_new
| Python | zaydzuhri_stack_edu_python |
function set_mptcp_enabled enabled
begin
set e = if expression enabled then 1 else 0
info string setting MPTCP enabled to %s % e
call sysctl_set string net.mptcp.mptcp_enabled e
end function | def set_mptcp_enabled(enabled):
e = 1 if enabled else 0
lg.info("setting MPTCP enabled to %s\n" % e)
sysctl_set('net.mptcp.mptcp_enabled', e) | Python | nomic_cornstack_python_v1 |
function saveMotionDiffPair aMotionImg aDiffImg aTimestamp aTag
begin
set motionImgName = string ./saved_images/ + aTimestamp + aTag + string .jpg
set diffImgName = string ./saved_images/ + aTimestamp + aTag + string diff.jpg
call imwrite motionImgName aMotionImg
call imwrite diffImgName aDiffImg
end function | def saveMotionDiffPair(aMotionImg, aDiffImg, aTimestamp, aTag):
motionImgName = './saved_images/' + aTimestamp + aTag + '.jpg'
diffImgName = './saved_images/' + aTimestamp + aTag + 'diff.jpg'
cv2.imwrite(motionImgName, aMotionImg)
cv2.imwrite(diffImgName, aDiffImg) | Python | nomic_cornstack_python_v1 |
function read_fasta fastaFile
begin
set tempHold = list
set sequence = list parse SeqIO fastaFile string fasta
for i in range 0 length sequence
begin
append tempHold id
append tempHold seq
end
return tempHold
end function | def read_fasta(fastaFile):
tempHold=[]
sequence = list(SeqIO.parse(fastaFile, "fasta"))
for i in range(0,len(sequence)):
tempHold.append(sequence[i].id)
tempHold.append(sequence[i].seq)
return tempHold | Python | nomic_cornstack_python_v1 |
function name_test input_name namelist
begin
if input_name in namelist
begin
return true
end
else
begin
print string Name is None.
return false
end
end function
function pw_test pw index_pw
begin
if pw == index_pw
begin
print string Welcome.
return 1
end
else
begin
print string Password is None.
end
end function
set na... | def name_test(input_name, namelist):
if input_name in namelist:
return True
else:
print('Name is None.')
return False
def pw_test(pw ,index_pw):
if pw == index_pw:
print ('Welcome.')
return 1
else:
print ('Password is None.')
namelist = []
pwlist... | Python | zaydzuhri_stack_edu_python |
function test_valueconstraint00401m7_positive mode save_output output_format
begin
call assert_bindings schema=string sunData/ElemDecl/valueConstraint/valueConstraint00401m/valueConstraint00401m7.xsd instance=string sunData/ElemDecl/valueConstraint/valueConstraint00401m/valueConstraint00401m7_p.xml class_name=string Ro... | def test_valueconstraint00401m7_positive(mode, save_output, output_format):
assert_bindings(
schema="sunData/ElemDecl/valueConstraint/valueConstraint00401m/valueConstraint00401m7.xsd",
instance="sunData/ElemDecl/valueConstraint/valueConstraint00401m/valueConstraint00401m7_p.xml",
class_name=... | Python | nomic_cornstack_python_v1 |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
set config = dict string user string postgres ; string password string password ; string host string localhost ; string port 5432 ; string echo true
function get_engine
begin
return call create_engine format string postgresql://{user}:{passwor... | from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
config = {
'user': 'postgres',
'password': 'password',
'host': 'localhost',
'port': 5432,
'echo': True
}
def get_engine():
return create_engine(
'postgresql://{user}:{password}@{host}:{port}'.format(**config)... | Python | zaydzuhri_stack_edu_python |
from unittest import TestCase
from toyrobot import ToyRobot
class Test extends TestCase
begin
function test_placetest self
begin
set robot = call ToyRobot
call place 2 2 string WEST
assert equal call report string (2, 2, WEST)
comment more than board bounds
call place 1 6 string SOUTH
assert not equal call report strin... | from unittest import TestCase
from toyrobot import ToyRobot
class Test(TestCase):
def test_placetest(self):
robot = ToyRobot()
robot.place(2, 2, "WEST")
self.assertEqual(robot.report(), "(2, 2, WEST)")
# more than board bounds
robot.place(1, 6, "SOUTH")
self.asse... | Python | zaydzuhri_stack_edu_python |
function getTridiagCoefficients self num_nodes
begin
comment Coefficients for Gauss quadrature type
set tuple alpha beta = call getOrthogPolyCoefficients num_nodes
comment If not Gauss quadrature type, modify the alpha/beta coefficients
if starts with quad_type string RADAU
begin
set b = if expression ends with quad_ty... | def getTridiagCoefficients(self, num_nodes):
# Coefficients for Gauss quadrature type
alpha, beta = self.getOrthogPolyCoefficients(num_nodes)
# If not Gauss quadrature type, modify the alpha/beta coefficients
if self.quad_type.startswith('RADAU'):
b = -1.0 if self.quad_type.... | Python | nomic_cornstack_python_v1 |
comment @judge Zerojudge
comment @id e895
comment @name 好多正方形
comment @contest
comment @tag math, dp
set dp = list 0 * 100005
set dp at 0 = 0
set dp at 1 = 1
for i in range 2 100003
begin
set dp at i = dp at i - 1 ? 1
if dp at i >= 10007
begin
set dp at i = dp at i - 10007
end
end
while true
begin
try
begin
set n = int... | #
# @judge Zerojudge
# @id e895
# @name 好多正方形
# @contest
#
# @tag math, dp
#
dp = [0]*100005
dp[0] = 0
dp[1] = 1
for i in range(2, 100003):
dp[i] = dp[i-1] << 1
if dp[i] >= 10007:
dp[i] -= 10007
while True:
try:
n = int(input())
print(dp[n])
except EOFError:
break
| Python | zaydzuhri_stack_edu_python |
import random
set suits = tuple string C string S string H string D
set faces = tuple string A string 2 string 3 string 4 string 5 string 6 string 7 string 8 string 9 string T string J string Q string K
set cards = list comprehension suit + face for face in faces for suit in suits
print cards
print list enumerate cards... | import random
suits = ('C', 'S', 'H', 'D')
faces = ('A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K')
cards = [suit+face for face in faces for suit in suits]
print (cards)
print(list(enumerate(cards)))
random.shuffle(cards)
print(list(cards))
#print(list(enumerate(cards))) | Python | zaydzuhri_stack_edu_python |
comment propina
set pago = decimal input string Cuanto a pagar?
set propina = integer input string La propina es 18%, 20%, 25%
print string Solo pueden pagar 3 persons la cuenta
set personas = integer input string Cuantas personas pagaran la cuenta? + string
if personas == 1
begin
set porcentaje = propina * 0.01
set to... | #propina
pago = float(input("Cuanto a pagar? "))
propina = int(input ('La propina es 18%, 20%, 25%'))
print ('Solo pueden pagar 3 persons la cuenta')
personas = int(input('Cuantas personas pagaran la cuenta?'+'\n'))
if personas == 1:
porcentaje = propina*.01
total=(pago*porcentaje)+pago
print ('Tota... | Python | zaydzuhri_stack_edu_python |
from mcpi.minecraft import Minecraft
set mc = call create
string HOME
comment displays the home menu
function home
begin
print string What would you like to do?
print string 1 - Save Checkpoint
print string 2 - Restore Checkpoint
print string 3 - Terraform
print string 4 - Navigate
print string 5 - Build
set choice = i... | from mcpi.minecraft import Minecraft
mc = Minecraft.create()
'''
HOME
'''
# displays the home menu
def home():
print("What would you like to do?")
print("1 - Save Checkpoint")
print("2 - Restore Checkpoint")
print("3 - Terraform")
print("4 - Navigate")
print("5 - Build")
choice = input("H... | Python | zaydzuhri_stack_edu_python |
import pygame
import random
from MovingObject import MovingObject
from Mushroom import Mushroom
class Mushroomer extends MovingObject
begin
function __init__ self
begin
set image = load image string images/mushroomer.gif
call __init__ self 25 25 5 image 0 25
set x = random integer 0 screenwidth / 25 - 1 * 25
end functi... | import pygame
import random
from MovingObject import MovingObject
from Mushroom import Mushroom
class Mushroomer(MovingObject):
def __init__(self):
image = pygame.image.load("images/mushroomer.gif")
MovingObject.__init__(self, 25, 25, 5, image, 0, 25)
self.rect.x = random.randint(0, self... | Python | zaydzuhri_stack_edu_python |
function reservePids host port user password namespace numPids
begin
set req = RESERVE_PIDS % tuple call unicode string numPids call unicode namespace
set p = call ParserCreate
set sp = call SP
set StartElementHandler = start
set EndElementHandler = end
set CharacterDataHandler = cdata
end function | def reservePids(host, port, user, password, namespace, numPids):
req = templates.RESERVE_PIDS % (unicode(str(numPids)), unicode(namespace))
p = xml.parsers.expat.ParserCreate()
sp = SP()
p.StartElementHandler = sp.start
p.EndElementHandler = sp.end
p.CharacterDataHandler = sp.cdata | Python | nomic_cornstack_python_v1 |
function fetch_content self single_date coin
begin
set content = string
set counter = 1
set tries = tries
while counter <= tries and not content
begin
try
begin
set browser_driver = call get_browser_driver
get browser_driver url
set element_present = call presence_of_element_located tuple NAME string moneda
set elemen... | def fetch_content(self, single_date, coin):
content = ''
counter = 1
tries = self.tries
while counter <= tries and not content:
try:
browser_driver = self.get_browser_driver()
browser_driver.get(self.url)
element_present = EC.p... | Python | nomic_cornstack_python_v1 |
function convert_leaky_relu g op block
begin
set alpha = call attr string alpha
set x = call get_node input string X at 0
set out = call leaky_relu x alpha=alpha
call add_node call output string Out at 0 out
end function | def convert_leaky_relu(g, op, block):
alpha = op.attr("alpha")
x = g.get_node(op.input("X")[0])
out = _op.nn.leaky_relu(x, alpha=alpha)
g.add_node(op.output("Out")[0], out) | Python | nomic_cornstack_python_v1 |
import unittest
import logging
from nose.tools import assert_true
from helpers.app_helpers import create_page , delete_page
from helpers import data_helpers as data
class PageTest extends TestCase
begin
function _get_page_data self
begin
set page_data = call create_page_data
set page_data at string name = format string... | import unittest
import logging
from nose.tools import assert_true
from helpers.app_helpers import create_page, delete_page
from helpers import data_helpers as data
class PageTest(unittest.TestCase):
def _get_page_data(self):
page_data = data.create_page_data()
page_data['name'] = 'DELETE_ME.{}'.fo... | Python | zaydzuhri_stack_edu_python |
function get_data_for_area self area_code
begin
set filter = string filters=&areaType=msoa&areaCode= { area_code }
set data = get self filter=filter
if data is not none
begin
set df = call json_normalize data meta=list string areaCode string areaName string UtlaName
end
else
begin
return none
end
return df
end function | def get_data_for_area(self, area_code):
filter = f'filters=&areaType=msoa&areaCode={area_code}'
data = self.get(filter=filter)
if data is not None:
df = json_normalize(data,
meta=['areaCode', 'areaName', 'UtlaName'])
else:
return N... | Python | nomic_cornstack_python_v1 |
import argparse
from shutil import copyfile
import os
function exportar carpeta_destino
begin
if not exists path carpeta_destino
begin
raise exception string La carpeta destino { carpeta_destino } no existe.
end
set path = join path carpeta_destino string modelo.h5
call copyfile string training/cp.h5 path
print string ... | import argparse
from shutil import copyfile
import os
def exportar(carpeta_destino):
if not os.path.exists(carpeta_destino): raise Exception(f"La carpeta destino {carpeta_destino} no existe.")
path = os.path.join(carpeta_destino, "modelo.h5")
copyfile('training/cp.h5', path)
print(f"Modelo exportado a ... | Python | zaydzuhri_stack_edu_python |
function deserialize_numpy self str numpy
begin
try
begin
set end = 0
set start = end
set end = end + 4
set tuple length = call unpack str at slice start : end :
set start = end
set end = end + length
if python3
begin
set model = decode str at slice start : end : string utf-8
end
else
begin
set model = str at slice st... | def deserialize_numpy(self, str, numpy):
try:
end = 0
start = end
end += 4
(length,) = _struct_I.unpack(str[start:end])
start = end
end += length
if python3:
self.model = str[start:end].decode('utf-8')
else:
self.model = str[start:end]
return sel... | Python | nomic_cornstack_python_v1 |
function test_consistencies self
begin
from sklearn.ensemble import RandomForestClassifier
set data = call make_hastie_10_2 2000
set index_randperm = call permutation range 2000
set data = list data at 0 at tuple index_randperm slice : : data at 1 at index_randperm
set out_of_sample = list data at 0 at tuple slice 1... | def test_consistencies(self):
from sklearn.ensemble import RandomForestClassifier
data = make_hastie_10_2(2000)
index_randperm = np.random.permutation(range(2000))
data = [data[0][index_randperm, :], data[1][index_randperm]]
out_of_sample = [data[0][1000:2000, :], data[1][1000:2... | Python | nomic_cornstack_python_v1 |
function get_source_spectra ztfname
begin
set url = BASEURL + string api/sources/ + ztfname + string /spectra
set response = call api string GET url
return response
end function | def get_source_spectra(ztfname):
url = BASEURL + "api/sources/" + ztfname + "/spectra"
response = api('GET',url)
return (response) | Python | nomic_cornstack_python_v1 |
comment Binary Search Algorithm in List
function BinarySearch arr target
begin
set tuple lower upper = tuple 0 length arr - 1
while lower <= upper
begin
set mid = lower + upper // 2
if arr at mid == target
begin
return true
end
if arr at mid < target
begin
set lower = mid + 1
end
else
begin
set upper = mid - 1
end
end
... | #Binary Search Algorithm in List
def BinarySearch(arr, target):
lower, upper = 0, len(arr)-1
while(lower<=upper):
mid = (lower+upper)//2
if (arr[mid] == target):
return True
if (arr[mid]<target):
lower = mid+1
else:
upper = mid-1... | Python | zaydzuhri_stack_edu_python |
comment updating 1 item:
set d = dict string brand string ford ; string model string Mustang ; string year 1995
print d
print string updating:
set d at string year = 2020
print d
comment updating more Number of items
print string
print string updating more Number of items:
update d dict string Mileage 35 ; string type ... | # updating 1 item:
d = {"brand": "ford", "model": "Mustang", "year": 1995}
print(d)
print("updating:")
d["year"] = 2020
print(d)
# updating more Number of items
print(" ")
print("updating more Number of items:")
d.update({"Mileage": 35, "type": "petrol"})
print(d)
# updating using list of tuple method
print(" ")
prin... | Python | zaydzuhri_stack_edu_python |
function mul num1 num2
begin
return num1 * num2
end function | def mul(num1, num2):
return num1 * num2 | Python | nomic_cornstack_python_v1 |
function set_margin_timed self value
begin
set value = call decimal value
if call isempty value
begin
set sale_price_timed = cost_price
end
else
begin
set cp = cost_price or zero
set sale_price_timed = call decimal cp / cem - value / cem true
end
end function | def set_margin_timed(self, value):
value = u.decimal(value)
if u.isempty(value):
self.sale_price_timed = self.cost_price
else:
cp = self.cost_price or zero
self.sale_price_timed = u.decimal(cp/((cem-value)/cem), True) | Python | nomic_cornstack_python_v1 |
if s % 2 == 0 and s % 3 == 0 and s % 5 == 0
begin
print 1
end
else
begin
print 0
end | if s%2==0 and s%3==0 and s%5==0: print (1)
else: print (0) | Python | zaydzuhri_stack_edu_python |
import json
import datetime
set GOLD = string gold
set SILVER = string Silver
class Player extends object
begin
function __init__ self email password name
begin
set email = string email
set password = string password
set name = string name
set session = list
set wallet = dict
set counter = dict
end function
function... | import json
import datetime
GOLD = 'gold'
SILVER = 'Silver'
class Player(object):
def __init__(self, email, password, name):
self.email = str(email)
self.password = str(password)
self.name = str(name)
self.session = []
self.wallet = {}
self.counter = {}
def i... | Python | zaydzuhri_stack_edu_python |
comment 함수 선언 시 매개변수값을 지정하면 기본값으로 설정된다
comment 이 경우 함수 호출에서 해당 매개변수를 지정하지 않아도 정상적으로 수행된다.
string 주의점1 : 기본 매개변수 다음에 일반 매개변수가 올수 없다..마지막에 기본 매개변수를 지정한다고 생각하면 될 듯 에러 발생) def print_n_times(n=2, value): 생각해보면 당연하다..매개변수가 기본매개변수 뒤에 위치하면..함수 호출 시 위치 때문에... 매개변수 생략을 할 수 없다..그럼 의미가 없어진다.
function print_n_times value n=2
begin
... | # 함수 선언 시 매개변수값을 지정하면 기본값으로 설정된다
# 이 경우 함수 호출에서 해당 매개변수를 지정하지 않아도 정상적으로 수행된다.
'''
주의점1 : 기본 매개변수 다음에 일반 매개변수가 올수 없다..마지막에 기본 매개변수를 지정한다고 생각하면 될 듯
에러 발생) def print_n_times(n=2, value):
생각해보면 당연하다..매개변수가 기본매개변수 뒤에 위치하면..함수 호출 시 위치 때문에...
매개변수 생략을 할 수 없다..그럼 의미가 없어진다.
'''
def print_n_times(value, n=2):
for i in rang... | Python | zaydzuhri_stack_edu_python |
from classes import *
import time
import sys
comment Pre Game Control Flow
comment Pre Game Phase 1 - Welcome user, get player name.
print string Hello! Welcome to Blackjack!
comment time.sleep(2)
set player = call Player string input string What is your name?:
print string ---
print format string Hi {}, Good Luck! ---... | from classes import *
import time
import sys
#Pre Game Control Flow
#Pre Game Phase 1 - Welcome user, get player name.
print("Hello! Welcome to Blackjack!\n")
#time.sleep(2)
player = Player(str(input("What is your name?: ")))
print("---")
print("Hi {}, Good Luck!\n---".format(player.name))
#time.sleep(2)
#Pre Game Ph... | Python | zaydzuhri_stack_edu_python |
function _extract_features self audio_paths use_vtlp=true
begin
set feature_dict = ordered dictionary
print string --------UNQIUE---------
comment print(unique(audio_paths))
for audio in unique audio_paths
begin
set feature_dict at audio = call _create_feature_vect audio
end
return feature_dict
end function | def _extract_features(self, audio_paths, use_vtlp=True):
feature_dict = OrderedDict()
print('--------UNQIUE---------')
# print(unique(audio_paths))
for audio in unique(audio_paths):
feature_dict[audio] = self._create_feature_vect(audio)
return feature_dict | Python | nomic_cornstack_python_v1 |
function RSS_GLS model target gamma
begin
set GLS_domain = where absolute model > 0.0001
set OLS_domain = where absolute model <= 0.0001
set GLS_res = model at GLS_domain - target at GLS_domain / absolute model at GLS_domain ^ gamma
set OLS_res = model at OLS_domain - target at OLS_domain
set GLS_RSS = norm GLS_res ^ 2... | def RSS_GLS(model,target,gamma):
GLS_domain = np.where(np.abs(model)>1e-4)
OLS_domain = np.where(np.abs(model)<=1e-4)
GLS_res = (model[GLS_domain]-target[GLS_domain])/(np.abs(model[GLS_domain])**gamma)
OLS_res = model[OLS_domain]-target[OLS_domain]
GLS_RSS = np.linalg.norm(GLS_res)**2
... | Python | nomic_cornstack_python_v1 |
class Model
begin
string Model Ising runner Execute with run
set dimension = none
set dynamicType = none
set populateType = none
set outputType = none
set output = none
set matrix = none
set size = none
set iterate = 1
set currentIterate = 0
set time = list
set aceitableSize = tuple 1000 1000000000000
set aceitableDim... | class Model():
"""
Model Ising runner
Execute with run
"""
dimension = None
dynamicType = None
populateType = None
outputType = None
output = None
matrix = None
size = None
iterate = 1
currentIterate = 0
time = []
aceitableSize = 1000, 1000000000000
ace... | Python | zaydzuhri_stack_edu_python |
function iteravtive string
begin
set count = 0
for i in range length string
begin
if lower string at i in vowels
begin
set count = count + 1
end
end
return count
end function
function recursion string i
begin
if i == 1
begin
set a = lower string at i - 1 in vowels
return a
end
return lower string at i - 1 in vowels + c... | def iteravtive(string):
count=0
for i in range(len(string)):
if string[i].lower() in vowels:
count+=1
return count
def recursion(string,i):
if i==1:
a=string[i-1].lower() in vowels
return a
return (string[i-1].lower() in vowels)+recursion(string,i-1)
# if i>=l... | Python | zaydzuhri_stack_edu_python |
function hamsterday_time_to_datetime hamsterday time
begin
string Return the civil datetime corresponding to a given hamster day and time. The hamster day start is taken into account.
comment work around cyclic imports
from hamster.lib.configuration import conf
if time < day_start
begin
comment early morning, between m... | def hamsterday_time_to_datetime(hamsterday, time):
"""Return the civil datetime corresponding to a given hamster day and time.
The hamster day start is taken into account.
"""
# work around cyclic imports
from hamster.lib.configuration import conf
if time < conf.day_start:
# early mor... | Python | jtatman_500k |
function normalize_bulk_return fun
begin
decorator wraps fun
function _fixed_bulk self *args **kwargs
begin
function fix_item item
begin
if string status in item at string index
begin
set item at string index at string ok = 200 <= item at string index at string status < 300
end
return item
end function
set ret = call f... | def normalize_bulk_return(fun):
@wraps(fun)
def _fixed_bulk(self, *args, **kwargs):
def fix_item(item):
if 'status' in item['index']:
item['index']['ok'] = (
200 <= item['index']['status'] < 300)
... | Python | nomic_cornstack_python_v1 |
comment thư viện tính toán toán học
import numpy as np
comment visualize data sử dụng đồ thị
import matplotlib.pyplot as plt
comment Hỗ trợ tính khoảng cách
from scipy.spatial.distance import cdist
comment Khởi tạo 500 điểm xung quanh 3 cluster (2,2) (9,2) (4,9)
comment 3 cluster đầu tiên
set means = list list 2 2 list... | import numpy as np # thư viện tính toán toán học
import matplotlib.pyplot as plt # visualize data sử dụng đồ thị
from scipy.spatial.distance import cdist # Hỗ trợ tính khoảng cách
# Khởi tạo 500 điểm xung quanh 3 cluster (2,2) (9,2) (4,9)
means = [[2, 2], [9, 2], [4, 9]] # 3 cluster đầu tiên
cov = [[2, 0], [0, 2]]
n_s... | Python | zaydzuhri_stack_edu_python |
import random
import time
import datetime as dt
set METADATA = string META DATA: 2000 (объем бочки) 1000 (текущий объем воды в бочке)
set N_ACTIONS = 14000
set USERNAMES = list string username1 string username2 string username3
set ACTION_TYPES = list string wanna top up string wanna scoop
set ACTION_CODES = list strin... | import random
import time
import datetime as dt
METADATA = """META DATA:
2000 (объем бочки)
1000 (текущий объем воды в бочке)
"""
N_ACTIONS = 14000
USERNAMES = ['username1', 'username2', 'username3']
ACTION_TYPES = ['wanna top up', 'wanna scoop']
ACTION_CODES = ['фейл', 'успех']
capacity = {'total_cap': 2000, 'curre... | Python | zaydzuhri_stack_edu_python |
function proof_of_work header
begin
info string Mining block for %s version and %s difficulty version difficulty
while not call valid_nonce header
begin
set nonce = nonce + 1
end
return header
end function | def proof_of_work(header: Header) -> Header:
logger.info(
"Mining block for %s version and %s difficulty",
header.version,
header.difficulty,
)
while not Verification.valid_nonce(header):
header.nonce += 1
return header | Python | nomic_cornstack_python_v1 |
function Non_Local_101 last_stride pretrained=false **kwargs
begin
set model = call ResNet_IBN last_stride Bottleneck_IBN list 3 4 23 3 keyword kwargs
if pretrained
begin
load state dict model call load_url model_urls at string resnet101
end
return model
end function | def Non_Local_101(last_stride, pretrained=False, **kwargs):
model = ResNet_IBN(last_stride, Bottleneck_IBN, [3, 4, 23, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet101']))
return model | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import sys
for arg in argv at slice 1 : :
begin
set stat = split arg string :
try
begin
set JobNumber = integer stat at 0
set Wage = integer stat at 1
end
except any
begin
print string Parameter Error
end
set TaxableAmount = Wage - 3500 - Wage * 0.165
set FiveInsuOneGold = Wage * 0.165
i... | #!/usr/bin/env python3
import sys
for arg in sys.argv[1:]:
stat = arg.split(':')
try:
JobNumber = int(stat[0])
Wage = int(stat[1])
except:
print("Parameter Error")
TaxableAmount = (Wage - 3500 - Wage*0.165)
FiveInsuOneGold = (Wage*0.165)
if (Wage <= 3500):
SalaryAfterTax = ... | Python | zaydzuhri_stack_edu_python |
function train self intent_fst
begin
comment pylint: disable=E0401
from flair.data import Sentence , Token
comment pylint: disable=E0401
from flair.models import SequenceTagger , TextClassifier
comment pylint: disable=E0401
from flair.embeddings import FlairEmbeddings , StackedEmbeddings , DocumentRNNEmbeddings
comment... | def train(self, intent_fst) -> None:
# pylint: disable=E0401
from flair.data import Sentence, Token
# pylint: disable=E0401
from flair.models import SequenceTagger, TextClassifier
# pylint: disable=E0401
from flair.embeddings import (
FlairEmbeddings,
... | Python | nomic_cornstack_python_v1 |
import random
import string
function gen_random_password
begin
set chars = ascii_letters + digits
set password = join string generator expression random choice chars for _ in range 8
return password
end function
print call gen_random_password | import random
import string
def gen_random_password():
chars = string.ascii_letters + string.digits
password = ''.join(random.choice(chars) for _ in range(8))
return password
print(gen_random_password())
| Python | flytech_python_25k |
class Solution
begin
comment @param {string} s
comment @return {string}
function longestPalindrome self s
begin
set max_v = 1
set res = string
set size = length s
if size <= 1
begin
return s
end
for i in call xrange size
begin
if i - max_v >= 1
begin
set temp = s at slice i - max_v - 1 : i + 1 :
if temp == temp at sl... | class Solution:
# @param {string} s
# @return {string}
def longestPalindrome(self, s):
max_v = 1
res = ""
size = len(s)
if size <= 1:
return s
for i in xrange(size):
if i - max_v >= 1:
temp = s[i-max_v-1:i+1]
if ... | Python | zaydzuhri_stack_edu_python |
function pascal_triangle n
begin
set trow = list 1
set y = list 0
for x in range max n 0
begin
print trow
set trow = list comprehension l + r for tuple l r in zip trow + y y + trow
end
end function
comment Driver program to test the above function
set n = 5
call pascal_triangle n | def pascal_triangle(n):
trow = [1]
y = [0]
for x in range(max(n,0)):
print(trow)
trow=[l+r for l,r in zip(trow+y, y+trow)]
# Driver program to test the above function
n = 5
pascal_triangle(n) | Python | iamtarun_python_18k_alpaca |
comment 5. Реализовать формирование списка, используя функцию range() и возможности генератора.
comment В список должны войти четные числа от 100 до 1000 (включая границы).
comment Необходимо получить результат вычисления произведения всех элементов списка.
comment Подсказка: использовать функцию reduce().
from functoo... | #5. Реализовать формирование списка, используя функцию range() и возможности генератора.
# В список должны войти четные числа от 100 до 1000 (включая границы).
# Необходимо получить результат вычисления произведения всех элементов списка.
#Подсказка: использовать функцию reduce().
from functools import reduce
list =... | Python | zaydzuhri_stack_edu_python |
from dotenv import load_dotenv
call load_dotenv
import os
import csv
import re
import requests
import jinja2
set templateLoader = call FileSystemLoader searchpath=string ./
set templateEnv = call Environment loader=templateLoader
function getRepoInfo repoUrl
begin
set info = dict
set api_path = string https://api.gith... | from dotenv import load_dotenv
load_dotenv()
import os
import csv
import re
import requests
import jinja2
templateLoader = jinja2.FileSystemLoader(searchpath="./")
templateEnv = jinja2.Environment(loader=templateLoader)
def getRepoInfo(repoUrl):
info = {}
api_path = 'https://api.github.com/repos/' + re.sear... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment 38% 175.0E-12
comment 40% 255.2E-12
comment 48% 656.3E-12
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.formula.api as smf | #!/usr/bin/python
# 38% 175.0E-12
# 40% 255.2E-12
# 48% 656.3E-12
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.formula.api as smf
| Python | zaydzuhri_stack_edu_python |
function hyperbolic_distance x y
begin
set inner = call hyperbolic_inner x y
return call arccosh - inner
end function | def hyperbolic_distance(x, y):
inner = hyperbolic_inner(x, y)
return np.arccosh(-inner) | Python | nomic_cornstack_python_v1 |
import time
import threading
import socket
from rte_order import *
class RTEEndpoint extends object
begin
comment static
set order_book_thread = dict
function __init__ self ip port
begin
set _ip = ip
set _port = port
if length order_book_thread == 0
begin
set order_book_thread at string t = thread target=__fetch_order... | import time
import threading
import socket
from rte_order import *
class RTEEndpoint(object):
order_book_thread = {} # static
def __init__(self, ip, port):
self._ip = ip
self._port = port
if len(self.order_book_thread) == 0:
self.order_book_thread['t'] = threading.Thread(t... | Python | zaydzuhri_stack_edu_python |
class Person extends object
begin
function __init__ self name lastname company position age
begin
set name = name
set lastname = lastname
set company = company
set position = position
set age = age
end function
function __str__ self
begin
return string Category: %s Name: %s %s, Company: %s, Position: %s, Age: %d % tupl... | class Person(object):
def __init__(self,name,lastname,company,position,age):
self.name=name
self.lastname=lastname
self.company=company
self.position=position
self.age=age
def __str__(self):
return ("Category: %s\n Name: %s %s, Company: %s, Position: %s, Age: %d" %
(self.__class__.__name__,self.name,se... | Python | zaydzuhri_stack_edu_python |
from tensorflow import keras
from keras import models
from keras import layers
from tensorflow.python.keras.backend import relu , sigmoid
from tensorflow.python.keras.models import Sequential
from ReplayMemory import ReplayMemory
import numpy as np
from ReplayMemory import ReplayMemory
class DQNAgent extends object
beg... | from tensorflow import keras
from keras import models
from keras import layers
from tensorflow.python.keras.backend import relu, sigmoid
from tensorflow.python.keras.models import Sequential
from ReplayMemory import ReplayMemory
import numpy as np
from ReplayMemory import ReplayMemory
class DQNAgent(object):
def ... | Python | zaydzuhri_stack_edu_python |
class BooleanFunction
begin
function __init__ self List
begin
comment Getting maximum minterm(number) in list
set max_no = max List
comment Getting no of binary bits/variables for greatest number
set variables = length format string {0:b} max_no
set List = List
set EI = list
end function
comment Main Method for minimi... | class BooleanFunction():
def __init__(self,List):
##Getting maximum minterm(number) in list
max_no=max(List)
##Getting no of binary bits/variables for greatest number
self.variables=len("{0:b}".format(max_no))
self.List=List
self.EI=[]
## Main Method for minimization
def minimize(self):
L=self.Bin... | Python | zaydzuhri_stack_edu_python |
import csv
import re
import os
from difflib import SequenceMatcher
comment dicționar pentru materiile din anul 1 / șablon
set dct_an1 = dict string Algoritmi si structuri de date I list 28 28 - 1 6 ; string Programare I list 28 28 - 1 6 ; string Logică computationala list 28 28 - 1 6 ; string Algebra si geometrie anali... | import csv
import re
import os
from difflib import SequenceMatcher
#dicționar pentru materiile din anul 1 / șablon
dct_an1={
'Algoritmi si structuri de date I':[28, 28, -1, 6],
'Programare I':[28, 28, -1, 6],
'Logică computationala':[28, 28, -1, 6],
'Algebra si geometrie analitica':[28, 28, -1, 5],
... | Python | zaydzuhri_stack_edu_python |
function sign_message self
begin
set keyPair = call generate bits=1024
set sign_msg = bytes string message string cp1251
set hash = call from_bytes call digest byteorder=string big
set signature = power hash d n
set signature = encode string signature string ascii
set public_key_r = encode string n string ascii
set pub... | def sign_message(self):
keyPair = RSA.generate(bits=1024)
sign_msg = bytes(str(self.message), 'cp1251')
hash = int.from_bytes(sha512(sign_msg).digest(), byteorder='big')
signature = pow(hash, keyPair.d, keyPair.n)
signature = str(signature).encode('ascii')
public_... | Python | nomic_cornstack_python_v1 |
comment Scrivere una classe di base ClsBase in cui c’e`un metodo addAttr che
comment prende in input due argomenti: una stringa s e un valore v,
comment controlla se la classe ha l’attributo di nome s
comment e se tale attributo non e`presente allora aggiunge alla classe
comment l’attributo s con valore v; in caso cont... | #Scrivere una classe di base ClsBase in cui c’e`un metodo addAttr che
# prende in input due argomenti: una stringa s e un valore v,
# controlla se la classe ha l’attributo di nome s
# e se tale attributo non e`presente allora aggiunge alla classe
# l’attributo s con valore v; in caso contrario non fa niente.
# Il metod... | Python | zaydzuhri_stack_edu_python |
for a in string
begin
if is upper a == true
begin
set count1 = count1 + 1
set new_string = lower a
end
else
if is lower a == true
begin
set count2 = count2 + 1
set new_string = upper a
end
else
if is space a == true
begin
set count3 = count3 + 1
set new_string = a
end
end
print string In original string: string
print s... | for a in string:
if a.isupper() == True:
count1 += 1
new_string = a.lower()
elif a.islower() == True:
count2 += 1
new_string = a.upper()
elif a.isspace() == True:
count3 += 1
new_string = a
print("In original string: ", string)
print("Uppercase:", ... | Python | zaydzuhri_stack_edu_python |
function rsa_matching_keys privatekey publickey
begin
comment We will attempt to encrypt then decrypt and check that the message matches
set testmessage = string A quick brown fox.
comment Encrypt with the public key
set encryptedmessage = call rsa_encrypt testmessage publickey
comment Decrypt with the private key
try
... | def rsa_matching_keys(privatekey, publickey):
# We will attempt to encrypt then decrypt and check that the message matches
testmessage = "A quick brown fox."
# Encrypt with the public key
encryptedmessage = rsa_encrypt(testmessage, publickey)
# Decrypt with the private key
try:
decryptedmes... | Python | nomic_cornstack_python_v1 |
import pygame
comment pygame中有一个类叫做Surface,我们之前建立的窗口其实都属于Surface类
comment 在Pygame中,一个位图也叫做Surface
comment 加载位图使用pygame.image.load()函数
comment 对于太空背景图,可以加载位图,也可以使用pygame.gfxdraw.pixel()函数来做到
set space = call convert
comment 最后的convert()函数将位图转换为程序窗口的本地颜色深度,如果加载时没有转换,绘制时也必须
comment 该函数还有另一种形式convert_alpha(),在加载必须使用透明度方式绘制... | import pygame
# pygame中有一个类叫做Surface,我们之前建立的窗口其实都属于Surface类
# 在Pygame中,一个位图也叫做Surface
# 加载位图使用pygame.image.load()函数
# 对于太空背景图,可以加载位图,也可以使用pygame.gfxdraw.pixel()函数来做到
space = pygame.image.load("space.png").convert()
# 最后的convert()函数将位图转换为程序窗口的本地颜色深度,如果加载时没有转换,绘制时也必须
# 该函数还有另一种形式convert_alpha(),在加载必须使用透明度方式绘制的前景对象时,需要使... | Python | zaydzuhri_stack_edu_python |
function key self key
begin
if key is none
begin
comment noqa: E501
raise call ValueError string Invalid value for `key`, must not be `None`
end
set _key = key
end function | def key(self, key):
if key is None:
raise ValueError("Invalid value for `key`, must not be `None`") # noqa: E501
self._key = key | Python | nomic_cornstack_python_v1 |
function get_other_state self state
begin
if state == 0
begin
return 0
end
else
begin
return list comprehension st for st in range 2 if st != state at 0
end
end function | def get_other_state(self,state):
if state == 0:
return 0
else:
return [st for st in range(2)
if st != state][0] | Python | nomic_cornstack_python_v1 |
function to_image_space data
begin
return call swapaxes call flip data 1 0 1
end function | def to_image_space(data):
return np.swapaxes(np.flip(data, 1), 0, 1) | Python | nomic_cornstack_python_v1 |
import sys
from django.core.management import BaseCommand
from migrator import Migrator
from loader import Loader
from exceptions import UnmigratedApp , NonexistentMigration , AmbiguousMigration , NonexistentDependency | import sys
from django.core.management import BaseCommand
from ...migrator import Migrator
from ...loader import Loader
from ...exceptions import UnmigratedApp, NonexistentMigration, AmbiguousMigration, NonexistentDependency
| Python | zaydzuhri_stack_edu_python |
from math import log10
function rwh_primes2 n
begin
set correction = n % 6 > 1
set n = dict 0 n ; 1 n - 1 ; 2 n + 4 ; 3 n + 3 ; 4 n + 2 ; 5 n + 1 at n % 6
set sieve = list true * n / 3
set sieve at 0 = false
for i in call xrange integer n ^ 0.5 / 3 + 1
begin
if sieve at i
begin
set k = 3 * i + 1 ? 1
set sieve at slice ... | from math import log10
def rwh_primes2(n):
correction = (n%6>1)
n = {0:n,1:n-1,2:n+4,3:n+3,4:n+2,5:n+1}[n%6]
sieve = [True] * (n/3)
sieve[0] = False
for i in xrange(int(n**0.5)/3+1):
if sieve[i]:
k=3*i+1|1
sieve[ ((k*k)/3) ::2*k]=[False]*((n/6-(k*k)/6-1)/k+1)
... | Python | zaydzuhri_stack_edu_python |
function contour_imcrop im contour patch_size
begin
set tuple x y w h = call boundingRect contour
set add_ht = patch_size - h
set add_wd = patch_size - w
assert tuple add_ht add_wd >= tuple 0 0 msg string added height: %d, added width: %d % tuple add_ht add_wd
set im_pad = call pad im tuple tuple patch_size / 2 patch_s... | def contour_imcrop(im, contour, patch_size):
x, y, w, h = cv2.boundingRect(contour)
add_ht=patch_size-h
add_wd=patch_size-w
assert((add_ht, add_wd)>=(0, 0)), 'added height: %d, added width: %d'%(add_ht, add_wd)
im_pad=np.pad(im, ((patch_size/2, patch_size/2), (patch_size/2, patch_size/2), (0, 0)), 'edge')
... | Python | nomic_cornstack_python_v1 |
import networkx as nx
import pylab as plt
import itertools
import connections
import circle
import random
import math
set G = call erdos_renyi_graph 100 p=0.01 directed=true
set centres = list tuple - 5 - 5 tuple - 5 0 tuple - 5 5 tuple 0 - 5 tuple 0 0 tuple 0 5 tuple 5 - 5 tuple 5 0 tuple 5 5
set pos = dict
for i in ... | import networkx as nx
import pylab as plt
import itertools
import connections
import circle
import random
import math
G = nx.erdos_renyi_graph(100,p=0.01,directed=True)
centres = [(-5,-5),(-5,0),(-5,5),(0,-5),(0,0),(0,5),(5,-5),(5,0),(5,5)]
pos = {}
for i in range(100):
G.add_node(i)
pos[i] = plt.array( cir... | Python | zaydzuhri_stack_edu_python |
function test_collection_defaults_to_hook_config
begin
set cm = call CollectionManager
call create_collection string foo
set include_regex = string *
set save_config = dict EVAL call SaveConfigMode save_interval=20
set hook = call Hook out_dir=string /tmp/test_collections/ + string now save_config=dict TRAIN call SaveC... | def test_collection_defaults_to_hook_config():
cm = CollectionManager()
cm.create_collection("foo")
cm.get("foo").include_regex = "*"
cm.get("foo").save_config = {ModeKeys.EVAL: SaveConfigMode(save_interval=20)}
hook = Hook(
out_dir="/tmp/test_collections/" + str(datetime.datetime.now()),
... | Python | nomic_cornstack_python_v1 |
function get self id timeout=none
begin
set req = call NodeGetRequest
set id = id
set tries = 0
set plumbing_response = none
while true
begin
try
begin
set plumbing_response = get stub req metadata=call get_metadata string Nodes.Get req timeout=timeout
end
except Exception as e
begin
if call shouldRetry tries e
begin
s... | def get(self, id, timeout=None):
req = NodeGetRequest()
req.id = (id)
tries = 0
plumbing_response = None
while True:
try:
plumbing_response = self.stub.Get(
req,
metadata=self.parent.get_metadata('Nodes.Get', re... | Python | nomic_cornstack_python_v1 |
function _safe_close self
begin
close database
call destory
end function | def _safe_close(self):
self.database.close()
self.master.destory() | Python | nomic_cornstack_python_v1 |
function get_next self num_bytes=none
begin
string Get the next bytes in the buffer without modifying the offset.
if num_bytes is none
begin
return _data at slice _offset : :
end
else
begin
return _data at slice _offset : _offset + num_bytes :
end
end function | def get_next(self, num_bytes=None):
"""Get the next bytes in the buffer without modifying the offset."""
if num_bytes is None:
return self._data[self._offset:]
else:
return self._data[self._offset:self._offset + num_bytes] | Python | jtatman_500k |
function move_to self target
begin
comment type: (RoomPosition) -> None
set hive = hive
set home = call find_home
set origin = call find_origin
set total_distance = call find_path_length origin target call new_movement_opts
set min_distance_from_home = Infinity
set min_distance_to_origin = Infinity
set min_distance_to_... | def move_to(self, target):
# type: (RoomPosition) -> None
hive = self.home.hive
home = self.find_home()
origin = self.find_origin()
total_distance = hive.honey.find_path_length(origin, target, self.new_movement_opts())
min_distance_from_home = Infinity
min_dista... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.