code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment File name: BernoulliNaiveBayes.py
comment Author: Thomas Racine
comment Purpose: implement the Bernoulli Naive Bayes classification model
import numpy as np
comment The function signatures for fit and predict are made to match scikit learn's function signatures to help implementation
comment The model assumes t... | ###########################################################
# File name: BernoulliNaiveBayes.py
# Author: Thomas Racine
# Purpose: implement the Bernoulli Naive Bayes classification model
###########################################################
import numpy as np
# The function signatures for fit and predict are m... | Python | zaydzuhri_stack_edu_python |
function get_file_path mdir=none
begin
if mdir is none
begin
set mdir = get current directory
end
set mpath = absolute path path mdir
while true
begin
call _print_tree mpath
set f = input string >
set m = join path mpath f
if is file path m
begin
call _clear
return m
end
else
if is directory path m
begin
set mpath = ab... | def get_file_path(mdir=None) -> str:
if mdir is None:
mdir = os.getcwd()
mpath = os.path.abspath(mdir)
while True:
_print_tree(mpath)
f = input(">")
m = os.path.join(mpath, f)
if os.path.isfile(m):
_clear()
return m
elif os.path.isdir(m... | Python | nomic_cornstack_python_v1 |
comment first we ask the user to input the student's scores
print string Please enter the student scores for the subjects below:
comment save the user input for the appropriate subject
set maths = integer input string Maths:
set english = integer input string English:
set programming = integer input string Programming:... | # first we ask the user to input the student's scores
print("Please enter the student scores for the subjects below:")
# save the user input for the appropriate subject
maths = int(input("Maths: "))
english = int(input("English: "))
programming = int(input("Programming: "))
accounting = int(input("Accounting: "))
#... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from datetime import datetime
import kColor.algs.convFuncs as conv
import kColor.algs.imgFuncs as utils
function kTonePx img x y loss tones lossConv
begin
set start = now
set tuple _ color error _ = call closest img at tuple y x + loss at tuple y x tones
set closestTime = now
comment print(f"closest ... | import numpy as np
from datetime import datetime
import kColor.algs.convFuncs as conv
import kColor.algs.imgFuncs as utils
def kTonePx(img, x, y, loss, tones, lossConv):
start = datetime.now()
_,color,error,_ = utils.closest(img[y,x] + loss[y,x], tones)
closestTime = datetime.now()
#print(f"closest t... | Python | zaydzuhri_stack_edu_python |
function gen_frame_paths root_path
begin
for tuple root _ files in walk root_path
begin
if length files == 0 or not ends with files at 0 string .dcm or find root string sax == - 1
begin
continue
end
set prefix = call rsplit string - 1 at 0
set fileset = set files
set expected = list comprehension string %s-%04d.dcm % t... | def gen_frame_paths(root_path):
for root, _, files in os.walk(root_path):
if len(files) == 0 or not files[0].endswith(".dcm") or root.find("sax") == -1:
continue
prefix = files[0].rsplit('-', 1)[0]
fileset = set(files)
expected = ["%s-%04d.dcm" % (prefix, i + 1) for i in ... | Python | nomic_cornstack_python_v1 |
function count_frequency string
begin
set counts = dict
for char in string
begin
if char in counts
begin
set counts at char = counts at char + 1
end
else
begin
set counts at char = 1
end
end
return counts
end function | def count_frequency(string):
counts = {}
for char in string:
if char in counts:
counts[char] += 1
else:
counts[char] = 1
return counts | Python | jtatman_500k |
function profile_detail request username
begin
set user = call get_object_or_404 User username=username
if user != user
begin
raise call Http404
end
set tuple profile created = call get_or_create user=user
if created and user == user
begin
set response = call call as_view template_name=string site_welcome.html request
... | def profile_detail(request, username):
user = get_object_or_404(User, username=username)
if user != request.user:
raise Http404()
profile, created = UserProfile.objects.get_or_create(user=user)
if created and user == request.user:
response = TemplateView.as_view(template_name="site_welco... | Python | nomic_cornstack_python_v1 |
function single_type_count clothes_list type
begin
set type_count = 0
for garment in clothes_list
begin
if clothing_type
begin
if clothing_type == type
begin
set type_count = type_count + 1
end
end
end
return type_count
end function | def single_type_count(clothes_list, type):
type_count = 0
for garment in clothes_list:
if garment.db.clothing_type:
if garment.db.clothing_type == type:
type_count += 1
return type_count | Python | nomic_cornstack_python_v1 |
function listen self
begin
raise NotImplementedError
end function | def listen(self) -> None:
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
import random
set wi = random integer 0 9
set a = integer input string Guess the no:--
set c = 1
set p = a
while p != wi
begin
if wi == a
begin
print string YOU WIN THE GAME CONGRATS!!!
print string The actual no is { wi }
break
end
else
if wi < a
begin
print string you entered a higher no than actual number>
end
else
... | import random
wi=random.randint(0,9)
a=int(input("Guess the no:--"))
c=1
p=a
while p!=wi:
if wi==a:
print("YOU WIN THE GAME\n CONGRATS!!!")
print(f"The actual no is {wi}")
break
elif wi<a:
print("you entered a higher no than actual number>")
elif wi>a:
print... | Python | zaydzuhri_stack_edu_python |
class BasketballPlayer
begin
function __init__ self full_name team position height weight
begin
set full_name = full_name
set team = team
set position = position
set height = height
set weight = weight
set career_statistics = dict string points_per_game 0 ; string rebounds_per_game 0 ; string assists_per_game 0 ; strin... | class BasketballPlayer:
def __init__(self, full_name, team, position, height, weight):
self.full_name = full_name
self.team = team
self.position = position
self.height = height
self.weight = weight
self.career_statistics = {
'points_per_game': 0,
... | Python | greatdarklord_python_dataset |
from surprise import Dataset
from surprise import Reader
from surprise import accuracy
from surprise.model_selection import KFold
comment cross_validate() 是被调用的外部接口,fit_and_score() 是在 cross_validate() 中被调用的。
comment 输入有算法对象,数据集,需要测量的指标,交叉验证的次数等。它对输入的数据 data,分成 cv 份,然后每次选择其中一份作为测试集,其余的作为训练集。在数据集划分完后,对它们分别调用 fit_and_scor... | from surprise import Dataset
from surprise import Reader
from surprise import accuracy
from surprise.model_selection import KFold
#cross_validate() 是被调用的外部接口,fit_and_score() 是在 cross_validate() 中被调用的。
#输入有算法对象,数据集,需要测量的指标,交叉验证的次数等。它对输入的数据 data,分成 cv 份,然后每次选择其中一份作为测试集,其余的作为训练集。在数据集划分完后,对它们分别调用 fit_and_score(),去... | Python | zaydzuhri_stack_edu_python |
set user_string = input string Enter a string:
set char_dict = dictionary comprehension i : char for tuple i char in enumerate user_string
print char_dict | user_string = input('Enter a string: ')
char_dict = {i:char for i, char in enumerate(user_string)}
print(char_dict)
| Python | flytech_python_25k |
function start self
begin
run
end function | def start(self):
self.run() | Python | nomic_cornstack_python_v1 |
function annotations self
begin
return get pulumi self string annotations
end function | def annotations(self) -> Optional[Sequence[Any]]:
return pulumi.get(self, "annotations") | Python | nomic_cornstack_python_v1 |
import Tkinter as tk
import ttk
set LARGE_FONT = tuple string Verdana 12
class StreamerGui extends Tk
begin
function __init__ self *args **kwargs
begin
call __init__ self *args keyword kwargs
call iconbitmap self default=string favicon.ico
call wm_title self string Hello
call geometry string 350x240
comment self.resiza... | import Tkinter as tk
import ttk
LARGE_FONT = ("Verdana", 12)
class StreamerGui(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
tk.Tk.iconbitmap(self, default='favicon.ico')
tk.Tk.wm_title(self, "Hello")
self.geometry("350x240")
... | Python | zaydzuhri_stack_edu_python |
function sample_delay self *args **kwargs
begin
return call Mapper_ATSC_sptr_sample_delay self *args keyword kwargs
end function | def sample_delay(self, *args, **kwargs):
return _mack_sdr_rossi_swig.Mapper_ATSC_sptr_sample_delay(self, *args, **kwargs) | Python | nomic_cornstack_python_v1 |
async function test_app_is_hoisted_to_previous_event test_app
begin
set actual = await call prepare_incoming_message test_app dict string message 1
assert actual at string events at - 1 at string app == name
end function | async def test_app_is_hoisted_to_previous_event(test_app):
actual = await prepare_incoming_message(
test_app, {'message': 1})
assert actual['events'][-1]['app'] == test_app.name | Python | nomic_cornstack_python_v1 |
function convert self input_path=none output_path=none markup=none break_lines=false divide_works=false latin=false extra_args=none
begin
string :param input_path: TLG filepath to convert. :param output_path: filepath of new converted text. :param markup: Specificity of inline markup. Default None removes all numerical... | def convert(self, input_path=None, output_path=None, markup=None,
break_lines=False, divide_works=False, latin=False,
extra_args=None):
"""
:param input_path: TLG filepath to convert.
:param output_path: filepath of new converted text.
:param markup: Speci... | Python | jtatman_500k |
string Created on Mar 26, 2015 @author: tmougham
import unittest
from furnishings import *
set exp_counter = string Beds: 1 Bookshelves: 0 Sofas: 1 Tables: 0
class Test extends TestCase
begin
function test_counter self
begin
set home = list
append home call Bed string Bedroom
append home call Sofa string Living Room
a... | '''
Created on Mar 26, 2015
@author: tmougham
'''
import unittest
from furnishings import *
exp_counter = """Beds: 1
Bookshelves: 0
Sofas: 1
Tables: 0
"""
class Test(unittest.TestCase):
def test_counter(self):
home = []
home.append(Bed('Bedroom'))
home.append(S... | Python | zaydzuhri_stack_edu_python |
function setViewMode self state=true
begin
if _viewMode == state
begin
return
end
set _viewMode = state
if state
begin
call setDragMode ScrollHandDrag
end
else
begin
call setDragMode RubberBandDrag
end
call emitViewModeChanged
end function | def setViewMode( self, state = True ):
if ( self._viewMode == state ):
return
self._viewMode = state
if ( state ):
self._mainView.setDragMode( self._mainView.ScrollHandDrag )
else:
self._mainView.setDragMode( self._mainView.RubberBandDrag ... | Python | nomic_cornstack_python_v1 |
for tuple k v in items classmates
begin
print k + string : + v
end | for k,v in classmates.items():
print(k+":"+v) | Python | zaydzuhri_stack_edu_python |
function bitwise_not self destination
begin
set value = bytearray
comment F7 /2 NOT r/m32
append value 247
set rm = call get_register_encoding destination
comment F7 /2 NOT r/m32
set reg = 2
comment ModR_byte encoded operands ( ModR/M Byte) MOD 11, RM source and
comment REG destination
set mod = 3
set modr_byte = mod ?... | def bitwise_not(self, destination):
value = bytearray()
value.append(0xf7) # F7 /2 NOT r/m32
rm = get_register_encoding(destination)
reg = 2 # F7 /2 NOT r/m32
# ModR_byte encoded operands ( ModR/M Byte) MOD 11, RM source and
# REG destination
mod = 0b11
... | Python | nomic_cornstack_python_v1 |
function _update_parameters self instance prediction averaging adapt param averagedWeightVectors updatesLeft
begin
comment first we need to get the score for the correct answer
comment if the instance has more than one correct answer then pick the min
set minCorrectLabelScore = decimal string inf
set minCorrectLabel = ... | def _update_parameters(self, instance, prediction, averaging, adapt, param,
averagedWeightVectors, updatesLeft):
# first we need to get the score for the correct answer
# if the instance has more than one correct answer then pick the min
minCorrectLabelScore = float("i... | Python | nomic_cornstack_python_v1 |
from typing import List
class Solution
begin
function largestDivisibleSubset self nums
begin
if length nums == 0
begin
return list
end
sort nums
set dp = list comprehension list nums at i for i in range length nums
set maxLenIndex = 0
for i in range 1 length nums
begin
set j = i - 1
while j >= 0
begin
if nums at i % n... | from typing import List
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
if len(nums) == 0:
return []
nums.sort()
dp = [[nums[i]] for i in range(len(nums))]
maxLenIndex = 0
for i in range(1, len(nums)):
j = i - 1
while j >= 0:
if nums[i] % ... | Python | zaydzuhri_stack_edu_python |
function __init__ self sessionOptions=none
begin
set onnx_path = join path models_path string mask_googlenet_slim.onnx
call download_file_from_google_drive file_id=string 1PHGb4d0ews2jNBGBaYZ4HWNJzph00oJa dest_path=onnx_path
set __session = call InferenceSession onnx_path sessionOptions
set __input_name = name
end func... | def __init__(self, sessionOptions = None):
onnx_path = os.path.join(models_path, "mask_googlenet_slim.onnx")
g.download_file_from_google_drive(file_id='1PHGb4d0ews2jNBGBaYZ4HWNJzph00oJa', dest_path=onnx_path)
self.__session = onnxruntime.InferenceSession(onnx_path, sessionOptions)
self._... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import random
comment from main import *
comment this is the file we will want to update
set file_to_learn = string cool_words.csv
function random_number_generator word_list
begin
comment random value from 0 to 24
set x = random integer 0 length word_list - 1
print string random value: { x }
comment... | import pandas as pd
import random
# from main import *
# this is the file we will want to update
file_to_learn = 'cool_words.csv'
def random_number_generator(word_list):
# random value from 0 to 24
x = random.randint(0, len(word_list)-1)
print(f'random value: {x}')
# a single dictionary f... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import sys
from pathlib import Path
import statistics
comment 'standard' conditions of experiment. Flowrates in sccm
set flowRateHe = 30
set initFlowRateCO = 2
set initFlowRateO2 = 4
function print_usage
begin
print string Usage: calculate-conversion.py <directory with spectra> <calibration... | #!/usr/bin/env python
import sys
from pathlib import Path
import statistics
# 'standard' conditions of experiment. Flowrates in sccm
flowRateHe = 30
initFlowRateCO = 2
initFlowRateO2 = 4
def print_usage():
print('Usage: calculate-conversion.py <directory with spectra> <calibration file>')
def parse_spectrum(fil... | Python | zaydzuhri_stack_edu_python |
while line
begin
print line
set line = read line file
end
close file | while line:
print(line)
line=file.readline()
file.close()
| Python | zaydzuhri_stack_edu_python |
function test_render_with_images self
begin
set activity = deep copy ACTIVITY
append activity at string object at string attachments dict string objectType string image ; string image dict string url string http://image/2
set got = call activities_to_atom list activity ACTOR title=string
call assert_multiline_in string... | def test_render_with_images(self):
activity = copy.deepcopy(test_instagram.ACTIVITY)
activity['object']['attachments'].append(
{'objectType': 'image', 'image': {'url': 'http://image/2'}})
got = atom.activities_to_atom([activity],test_instagram.ACTOR, title='')
self.assert_multiline_in(
'<im... | Python | nomic_cornstack_python_v1 |
function chunks l n
begin
for i in range 0 length l n
begin
yield l at slice i : i + n :
end
end function | def chunks(l, n):
for i in range(0, len(l), n):
yield l[i:i + n] | Python | nomic_cornstack_python_v1 |
function fingerprint
begin
set conn = call connect server user password string database
set cursor = call cursor
execute cursor string SELECT COUNT(*) FROM Camera
set num = call fetchone at 0
execute cursor string SELECT Fingerprint.Fingerprint_Id, Fingerprint.Technology, Fingerprint.SensorLocation, Company.Name, Compo... | def fingerprint():
conn = pymssql.connect(server, user, password, "database")
cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) FROM Camera')
num=cursor.fetchone()[0]
cursor.execute('SELECT Fingerprint.Fingerprint_Id, Fingerprint.Technology, Fingerprint.SensorLocation, Company.Name, Component... | Python | nomic_cornstack_python_v1 |
from pieces.piece import Piece
class General extends Piece
begin
function __init__ self x_location y_location colour board
begin
call __init__ x_location y_location colour board
if colour == string red
begin
set piece_name = string 帅
end
else
begin
set piece_name = string 将
end
end function
comment General overrides th... | from pieces.piece import Piece
class General(Piece):
def __init__(self, x_location, y_location, colour, board):
super().__init__(x_location, y_location, colour, board)
if self.colour == 'red':
self.piece_name = "帅"
else:
self.piece_name = "将"
# General overrid... | Python | zaydzuhri_stack_edu_python |
comment label: minimax difficulty: easy
string 思路:当剩下4个石头时轮到的那个人必输。 如果只有一、两、或三块石头,在你的回合,可以把全部石子拿走,从而在游戏中取胜。如果恰好有四块石头,你就会失败。 因为在这种情况下不管你取走多少石头,总会为你的对手留下几块,使得他可以在游戏中打败你。因此,要想获胜,在你的回合中,必须避免石头堆中的石子数为 4 的情况。 同样地,如果有五、六、或七块石头,你可以控制自己拿取的石头数,总是恰好给你的对手留下四块石头,使他输掉这场比赛。 但是如果石头堆里有八块石头,你就不可避免地会输掉,因为不管你从一堆石头中挑出一块、两块还是三块,你的对手都可以选择三块、... | #label: minimax difficulty: easy
"""
思路:当剩下4个石头时轮到的那个人必输。
如果只有一、两、或三块石头,在你的回合,可以把全部石子拿走,从而在游戏中取胜。如果恰好有四块石头,你就会失败。
因为在这种情况下不管你取走多少石头,总会为你的对手留下几块,使得他可以在游戏中打败你。因此,要想获胜,在你的回合中,必须避免石头堆中的石子数为 4 的情况。
同样地,如果有五、六、或七块石头,你可以控制自己拿取的石头数,总是恰好给你的对手留下四块石头,使他输掉这场比赛。
但是如果石头堆里有八块石头,你就不可避免地会输掉,因为不管你从一堆石头中挑出一块、两块还是三块,你的对手都可以选择三块、两块或一块... | Python | zaydzuhri_stack_edu_python |
function failure text **kwarg
begin
print call textcol text t=string red s=string bold keyword kwarg
end function | def failure(text, **kwarg):
print(textcol(text,t="red",s="bold"),**kwarg) | Python | nomic_cornstack_python_v1 |
function load file_name data_dir=string ./ getinfo=true
begin
comment TODO: need to clean data before loading?
set data_file = join path data_dir file_name
if not exists path data_file
begin
if data_dir == string ./
begin
set data_dir = string current
end
set error_msg = file_name + string was not found in + data_dir +... | def load(file_name, data_dir = './', getinfo = True):
# TODO: need to clean data before loading?
data_file = os.path.join(data_dir, file_name)
if not os.path.exists(data_file):
if data_dir == './':
data_dir = "current"
error_msg = file_name + " was not fou... | Python | nomic_cornstack_python_v1 |
comment encoding: utf-8
import os
import csv
class my_csv_storer extends object
begin
function __init__ self csv_file_name
begin
set filename = csv_file_name
set filehandle = open filename string a
set writer = writer filehandle
end function
function store self info_hash content magnet
begin
write row writer list info_... | #encoding: utf-8
import os
import csv
class my_csv_storer(object):
def __init__(self, csv_file_name):
self.filename = csv_file_name
self.filehandle = open(self.filename, 'a')
self.writer = csv.writer(self.filehandle)
def store(self, info_hash, content, magnet):
self.writer.writerow([info_hash, content, ... | Python | zaydzuhri_stack_edu_python |
function signal_handler signum frame
begin
set signal_enum = call Signals signum
error string Job received a { name } signal!
end function
comment Perform quick actions that will help the job resume later.
comment If you use Weights & Biases: https://docs.wandb.ai/guides/runs/resuming#preemptible-sweeps
comment if wand... | def signal_handler(signum: int, frame: FrameType | None):
signal_enum = signal.Signals(signum)
logger.error(f"Job received a {signal_enum.name} signal!")
# Perform quick actions that will help the job resume later.
# If you use Weights & Biases: https://docs.wandb.ai/guides/runs/resuming... | Python | nomic_cornstack_python_v1 |
for i in range 2
begin
comment координаты клада
append treasure integer input
end | for i in range(2):
treasure.append(int(input())) #координаты клада
| Python | zaydzuhri_stack_edu_python |
if number1 > number2 and number1 > number3
begin
set biggest = number1
end
else
if number2 > number1 and number2 > number3
begin
set biggest = number2
end
else
begin
set biggest = number3
end | if (number1 > number2) and (number1 > number3):
biggest = number1
elif (number2 > number1) and (number2 > number3):
biggest = number2
else:
biggest = number3 | Python | zaydzuhri_stack_edu_python |
from sage.calculus.functional import taylor
from sage.functions.log import log , ln
from sage.functions.other import sqrt , real , imag , ceil , floor
from sage.functions.trig import tan
from sage.matrix.constructor import Matrix , identity_matrix
from sage.misc.functional import n as num
from sage.misc.persist import ... | from sage.calculus.functional import taylor
from sage.functions.log import log, ln
from sage.functions.other import sqrt,real,imag,ceil,floor
from sage.functions.trig import tan
from sage.matrix.constructor import Matrix, identity_matrix
from sage.misc.functional import n as num
from sage.misc.persist import save
from ... | Python | zaydzuhri_stack_edu_python |
async function togglerole self ctx role
begin
set user = author
await delete
if role == string MK8D
begin
if mk8d_role in roles
begin
await call remove_roles mk8d_role
await call send string Left MK8D role
end
else
begin
await call add_roles mk8d_role
await call send string Joined MK8D role
end
end
else
begin
await cal... | async def togglerole(self, ctx, role):
user = ctx.message.author
await ctx.message.delete()
if role == "MK8D":
if self.bot.mk8d_role in user.roles:
await user.remove_roles(self.bot.mk8d_role)
await user.send("Left MK8D role")
el... | Python | nomic_cornstack_python_v1 |
import pytest
import sys
append path string ..
from app.hash_table import HashTable
set test_hashtable = call HashTable
function test_add
begin
string Tests adding a new key-value pair to the hashtable
add test_hashtable string key string value
assert get test_hashtable string key == string value
end function
function ... | import pytest
import sys
sys.path.append('..')
from app.hash_table import HashTable
test_hashtable = HashTable()
def test_add():
"""
Tests adding a new key-value pair to the hashtable
"""
test_hashtable.add('key', 'value')
assert test_hashtable.get('key') == 'value'
def test_replace_word():
... | Python | zaydzuhri_stack_edu_python |
function plot_functions self
begin
print string Plotting!
if n_dims == 2
begin
set n_plot = 21
set x_plot = linear space bounds at tuple 0 0 bounds at tuple 0 1 n_plot
set y_plot = linear space bounds at tuple 1 0 bounds at tuple 1 1 n_plot
set tuple X Y = call meshgrid x_plot y_plot
set x_values = T
set y_plot_high = ... | def plot_functions(self):
print("Plotting!")
if self.n_dims == 2:
n_plot = 21
x_plot = np.linspace(self.bounds[0, 0], self.bounds[0, 1], n_plot)
y_plot = np.linspace(self.bounds[1, 0], self.bounds[1, 1], n_plot)
X, Y = np.meshgrid(x_plot, y_plot)... | Python | nomic_cornstack_python_v1 |
import functools
import shapely
import pyproj
import geojson
import shapefile
import warnings
import zipfile
import trimesh
from shapely.geometry import Polygon
import numpy as np
import random
set geod = call Geod ellps=string WGS84
function geo_area_of_polygon poly
begin
string :param poly: :type poly: shapely or geo... | import functools
import shapely
import pyproj
import geojson
import shapefile
import warnings
import zipfile
import trimesh
from shapely.geometry import Polygon
import numpy as np
import random
geod = pyproj.Geod(ellps='WGS84')
def geo_area_of_polygon(poly):
'''
:param poly:
:type poly: shapely or geojs... | Python | zaydzuhri_stack_edu_python |
function _error self str
begin
raise call SyntaxError string Expecting %s found %s on line %d % tuple str lookahead lineNum
end function | def _error(self, str):
raise SyntaxError("Expecting %s found %s on line %d" % \
(str, self.lookahead, self.lexer.lineNum)) | Python | nomic_cornstack_python_v1 |
function choose_not_hitler_chancellor player valid_players
begin
set probabilities = probs
set fascist_players = list
for curr_player in valid_players
begin
if curr_player in probabilities
begin
if probabilities at curr_player at 1 != 1
begin
append fascist_players curr_player
end
end
end
set choices = if expression l... | def choose_not_hitler_chancellor(player: Player, valid_players: List[Name]):
probabilities = player.probs
fascist_players = []
for curr_player in valid_players:
if curr_player in probabilities:
if probabilities[curr_player][1] != 1:
fascist_players.append(curr_player)
... | Python | nomic_cornstack_python_v1 |
function custom_pop lst index=- 1
begin
if index < 0
begin
set index = index + length lst
end
set popped_element = lst at index
set lst at slice index : index + 1 : = list
return popped_element
end function
set some_list = list 1 2 3
set popped_element = call custom_pop some_list
comment Output: 3
print popped_elemen... | def custom_pop(lst, index=-1):
if index < 0:
index += len(lst)
popped_element = lst[index]
lst[index:index + 1] = []
return popped_element
some_list = [1, 2, 3]
popped_element = custom_pop(some_list)
print(popped_element) # Output: 3
print(some_list) # Output: [1, 2]
| Python | jtatman_500k |
string Restore the Array From Adjacent Pairs There is an integer array nums that consists of n unique elements, but you have forgotten it. However, you do remember every pair of adjacent elements in nums. You are given a 2D integer array adjacentPairs of size n - 1 where each adjacentPairs[i] = [ui, vi] indicates that ... | """
Restore the Array From Adjacent Pairs
There is an integer array nums that consists of n unique elements,
but you have forgotten it. However, you do remember every pair of
adjacent elements in nums.
You are given a 2D integer array adjacentPairs of size n - 1 where
each adjacentPairs[i] = [ui, vi] indicates that... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Mon Dec 2 08:51:35 2019 @author: Luna Kadysz
import numpy as np
from sklearn.linear_model import LinearRegression
set x = reshape array list 5 15 25 35 45 55 tuple - 1 1
set y = array list 5 20 14 32 22 38
set model = linear regression
comment compact: model = LinearRegre... | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 2 08:51:35 2019
@author: Luna Kadysz
"""
import numpy as np
from sklearn.linear_model import LinearRegression
x = np.array([5, 15, 25, 35, 45, 55]).reshape((-1, 1))
y = np.array([5, 20, 14, 32, 22, 38])
model = LinearRegression()
model.fit(x, y) ## compact: model = Li... | Python | zaydzuhri_stack_edu_python |
async function get_last_price self pair
begin
set ohlc = await call get_ohlc_data pair
return decimal list values ohlc at 0 at - 1 at 4
end function | async def get_last_price(self, pair: str) -> float:
ohlc = await self.get_ohlc_data(pair)
return float(list(ohlc.values())[0][-1][4]) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import sys
import getopt
from PIL import Image , ImageDraw | # -*- coding: utf-8 -*-
import sys
import getopt
from PIL import Image, ImageDraw
| Python | zaydzuhri_stack_edu_python |
from root import Root
from button import *
from label import *
from dragbar import *
from textbox import TextBox
from inputbox import InputBox
from menu import Menu
from servo import Servo | from root import Root
from button import *
from label import *
from dragbar import *
from textbox import TextBox
from inputbox import InputBox
from menu import Menu
from servo import Servo
| Python | zaydzuhri_stack_edu_python |
function ordered_accounts filtered_accounts
begin
return sorted filtered_accounts key=lambda x -> tuple IntervalEnd - PK reverse=true
end function | def ordered_accounts(filtered_accounts: List[Account]) -> List[Account]:
return sorted(
filtered_accounts, key=lambda x: (x.IntervalEnd, -x.PK), reverse=True
) | Python | nomic_cornstack_python_v1 |
function cone *args axis=none caching=true degree=3 endSweep=2 heightRatio=2.0 nodeState=0 pivot=none radius=1.0 sections=8 spans=1 startSweep=0 tolerance=0.01 useOldInitBehaviour=false useTolerance=false constructionHistory=true name=string object=true polygon=0 q=true query=true e=true edit=true **kwargs
begin
pass
... | def cone(*args, axis: Union[List[float, float, float], bool]=None, caching: bool=True, degree:
Union[int, bool]=3, endSweep: Union[float, bool]=2, heightRatio: Union[float,
bool]=2.0, nodeState: Union[int, bool]=0, pivot: Union[List[float, float, float],
bool]=None, radius: Union[float, bool]... | Python | nomic_cornstack_python_v1 |
function on_network_adapter_change self network_adapter change_adapter
begin
string Triggered when settings of a network adapter of the associated virtual machine have changed. in network_adapter of type :class:`INetworkAdapter` in change_adapter of type bool raises :class:`VBoxErrorInvalidVmState` Session state preven... | def on_network_adapter_change(self, network_adapter, change_adapter):
"""Triggered when settings of a network adapter of the
associated virtual machine have changed.
in network_adapter of type :class:`INetworkAdapter`
in change_adapter of type bool
raises :class:`VBoxErrorInva... | Python | jtatman_500k |
function _unescape_str value
begin
if is instance value int
begin
return string %d % value
end
set value = replace value string \\ string \
for tuple i j in call iteritems
begin
set value = replace value j i
end
return value
end function | def _unescape_str(value):
if isinstance(value, int): return "%d" % value
value = value.replace(r"\\", "\\")
for i, j in ts3_escape.iteritems():
value = value.replace(j, i)
return value | Python | nomic_cornstack_python_v1 |
function get_position self position
begin
set current = head
if head
begin
while current
begin
if position == position
begin
return current
end
set current = next
end
end
return none
end function | def get_position(self, position):
current = self.head
if self.head:
while current:
if position == current.position:
return current
current = current.next
return None | Python | nomic_cornstack_python_v1 |
function sumUpTo n
begin
string Objective: To compute the sum of first 'n' whole numbers. Input: n: A whole number 'n' upto which we have to calculate the sum. Output: Sum of first 'n' whole numbers.
comment Approach: Recurrsion- sumUpTo(n) = n + sumUpTo(n-1)
if n == 0
begin
return 0
end
else
begin
return n + call sumU... | def sumUpTo(n):
'''
Objective: To compute the sum of first 'n' whole numbers.
Input:
n: A whole number 'n' upto which we have to calculate the sum.
Output:
Sum of first 'n' whole numbers.
'''
#Approach: Recurrsion- sumUpTo(n) = n + sumUpTo(n-1)
if n==0:
return 0
... | Python | zaydzuhri_stack_edu_python |
function get_permutation_name basename permutation=1
begin
return string basename + string . + string permutation
end function | def get_permutation_name(basename, permutation=1):
return str(basename)+"."+str(permutation) | Python | nomic_cornstack_python_v1 |
function insert self ind value
begin
if ind == length self
begin
set _len = _len + 1
call __setitem__ ind value
end
else
begin
raise call IndexError string You can only insert at the end.
end
end function | def insert(self, ind, value):
if ind == len(self):
self._len += 1
self.__setitem__(ind, value)
else:
raise IndexError("You can only insert at the end.") | Python | nomic_cornstack_python_v1 |
function is_indefinite_iterable val
begin
set instance = call _isinstance val string Instance
set cls_instance = call _isinstance cls string Class
if not instance and cls_instance and not is_concrete
begin
return false
end
for cls in mro
begin
if full_name == string builtins.str
begin
return false
end
else
if full_name... | def is_indefinite_iterable(val: _BaseValueType) -> bool:
instance = _isinstance(val, "Instance")
cls_instance = _isinstance(val.cls, "Class")
if not (instance and cls_instance and not val.is_concrete):
return False
for cls in val.cls.mro:
if cls.full_name == "builtins.str":
return False
elif c... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Mon Oct 14 16:52:21 2019 @author: atezbas
comment Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
comment Data
set X = array list list 1.0 3.0 list 2.0 3.0 list 2.0 4.0 list 3.0 1.0 list 3.0 2.0 list 4.0 2.0
set y = array list 1 1 1 - 1 - 1 - 1
... | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 14 16:52:21 2019
@author: atezbas
"""
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
# Data
X = np.array([
[1., 3.],
[2., 3.],
[2., 4.],
[3., 1.],
[3., 2.],
[4., 2.],
])
y = np.array([1,1,1,-1,-1,-1])
n1 = len(X[ y == 1]) ... | Python | zaydzuhri_stack_edu_python |
function error_f v i
begin
set u = tuple 0 0.05
set error = - 1 + call cosine u v + cos i * pi / 6
set error = call arcsin error * 180 / pi
print error
end function | def error_f(v, i) :
u = (0, 0.05)
error = -1 + ssd.cosine(u, v) + np.cos((i*np.pi/6))
error = (np.arcsin(error)*180/np.pi)
print(error) | Python | nomic_cornstack_python_v1 |
function __repr__ self
begin
return call to_str
end function | def __repr__(self):
return self.to_str() | Python | nomic_cornstack_python_v1 |
function log_metrics target_seconds=10
begin
global last_timer_reset
set start = call monotonic_ns
set elapsed_nanos = start - last_timer_reset
if start - last_timer_reset < target_seconds * 1000000000
begin
return
end
set last_timer_reset = start
print string -------------- Metrics ------------------------------------... | def log_metrics(target_seconds=10) -> None:
global last_timer_reset
start = time.monotonic_ns()
elapsed_nanos = start - last_timer_reset
if (start - last_timer_reset) < (target_seconds * 1000000000):
return
last_timer_reset = start
print('\n\n-------------- ... | Python | nomic_cornstack_python_v1 |
from shark.render import ImageLoader , get_key
from shark.base import Action , Direction
from pathlib import Path
from pyglet.image import Animation , ImageData
function get_image_loader
begin
set cwd = call cwd
return call ImageLoader cwd
end function
function test_image_loader_size
begin
set loader = call get_image_l... | from shark.render import ImageLoader, get_key
from shark.base import Action, Direction
from pathlib import Path
from pyglet.image import Animation, ImageData
def get_image_loader():
cwd = Path.cwd()
return ImageLoader(cwd)
def test_image_loader_size():
loader = get_image_loader()
assert len(loader) ... | Python | zaydzuhri_stack_edu_python |
function __repr__ self
begin
return call to_str
end function | def __repr__(self):
return self.to_str() | Python | nomic_cornstack_python_v1 |
async function async_setup_service hass
begin
async function send_text_command call
begin
string Send a text command to Google Assistant SDK.
set commands : list at str = data at SERVICE_SEND_TEXT_COMMAND_FIELD_COMMAND
set media_players : list at str ? none = get data SERVICE_SEND_TEXT_COMMAND_FIELD_MEDIA_PLAYER
set co... | async def async_setup_service(hass: HomeAssistant) -> None:
async def send_text_command(call: ServiceCall) -> ServiceResponse:
"""Send a text command to Google Assistant SDK."""
commands: list[str] = call.data[SERVICE_SEND_TEXT_COMMAND_FIELD_COMMAND]
media_players: list[str] | None = call.d... | Python | nomic_cornstack_python_v1 |
function is_prime number
begin
if number <= 1
begin
return false
end
for i in range 2 number
begin
if number % i == 0
begin
return false
end
end
return true
end function
function print_primes upper_limit
begin
for i in range 2 upper_limit + 1
begin
if call is_prime i
begin
print i
end
end
end function
call print_primes... | def is_prime(number):
if number <= 1:
return False
for i in range(2, number):
if number % i == 0:
return False
return True
def print_primes(upper_limit):
for i in range(2, upper_limit+1):
if is_prime(i):
print(i)
print_primes(25)
| Python | flytech_python_25k |
function parse_clinical_file args tfams
begin
set tuple mouse2pheno target_pheno other_phenos = tuple list list list
with open clinical string r as infile
begin
set header = split strip read line infile string
comment find column of target phenotype
set targetcol = index header target
set tuple mousecol straincol = ... | def parse_clinical_file(args, tfams):
mouse2pheno, target_pheno, other_phenos = [], [], []
with(open(args.clinical, 'r')) as infile:
header = infile.readline().strip().split('\t')
targetcol = header.index(args.target) # find column of target phenotype
mousecol, straincol = header.index('mouse_number'),... | Python | nomic_cornstack_python_v1 |
function generate_cons_pos_all_info cons_pos_all all_gpcrs_info
begin
for prot_info in all_gpcrs_info
begin
set cons_pos_prot = prot_info at 4
for tuple gpcr_class cons_class_lists in items cons_pos_prot
begin
if cons_class_lists
begin
comment list 0 or 1
set list_num = 0
while list_num < length cons_class_lists
begin
... | def generate_cons_pos_all_info(cons_pos_all,all_gpcrs_info):
for prot_info in all_gpcrs_info:
cons_pos_prot = prot_info[4]
for gpcr_class, cons_class_lists in cons_pos_prot.items():
if cons_class_lists:
list_num=0 # list 0 or 1
while list_num < len(cons_class... | Python | nomic_cornstack_python_v1 |
function do_displays self sock args
begin
set n_displays = 0
for spu in range length allSPUs
begin
set n_displays = n_displays + length displays
end
set displays = string %d % n_displays
for spu in range length allSPUs
begin
for i in range length displays
begin
set display = displays at i
set tmp_display = string %d %d... | def do_displays( self, sock, args ):
n_displays = 0
for spu in range(len(allSPUs)):
n_displays += len(allSPUs[spu].displays)
displays = "%d " % n_displays
for spu in range(len(allSPUs)):
for i in range(len(allSPUs[spu].displays)):
display = allSPUs[spu].displays[i]
tmp_display = "%d %d %d %s... | Python | nomic_cornstack_python_v1 |
function my_function
begin
print string Hello, World!
end function
if __name__ == string __main__
begin
call my_function
end
if __name__ == string __main__
begin
call my_function
end | def my_function():
print("Hello, World!")
if __name__ == '__main__':
my_function()
if __name__ == '__main__':
my_function() | Python | jtatman_500k |
comment imports
import torch
import torch.nn as nn
from torch.nn.modules import module
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader
from torchvision.datasets import MNIST
comment device config
set device = device if expression cal... | # imports
import torch
import torch.nn as nn
from torch.nn.modules import module
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader
from torchvision.datasets import MNIST
# device config
device = torch.device('cuda' if torch.cuda.is_av... | Python | zaydzuhri_stack_edu_python |
function main
begin
import sys
from collections import Counter
set N = integer read line stdin
set A = list map int split read line stdin
set C = counter list comprehension i + x for tuple i x in enumerate A
set output = 0
for tuple key val in items counter list comprehension i - x for tuple i x in enumerate A
begin
if... | def main():
import sys
from collections import Counter
N=int(sys.stdin.readline())
A=list(map(int,sys.stdin.readline().split()))
C=Counter([i+x for i,x in enumerate(A)])
output=0
for key,val in Counter([i-x for i,x in enumerate(A)]).items():
if key in C.keys():
output+=va... | Python | zaydzuhri_stack_edu_python |
function weightDecay self arg0 arg1 arg2
begin
return call SigmaProcess_weightDecay self arg0 arg1 arg2
end function | def weightDecay(self, arg0, arg1, arg2):
return _pythia8.SigmaProcess_weightDecay(self, arg0, arg1, arg2) | Python | nomic_cornstack_python_v1 |
function test_bad_max_bytes self
begin
set garbage = string gfgfgf
set event = call _make_event dict string url FILE_URL ; string input string txt ; string max_bytes garbage dict string origin MOCK_ORIGIN
set resp = call lambda_handler event none
assert resp at string statusCode == 400 msg string Expected 400 on event ... | def test_bad_max_bytes(self):
garbage = 'gfgfgf'
event = self._make_event({
'url': self.FILE_URL,
'input': 'txt',
'max_bytes': garbage}, {'origin': MOCK_ORIGIN})
resp = t4_lambda_preview.lambda_handler(event, None)
assert resp['statusCode'] == 400, f'E... | Python | nomic_cornstack_python_v1 |
import requests
from bs4 import BeautifulSoup
set link = string https://finance.naver.com/world
set res = get requests link
set html = text
set start = find html string var americaData
set end = find html string var indexLocation start
print html at slice start : end :
string soup = BeautifulSoup(res.content, 'html.par... | import requests
from bs4 import BeautifulSoup
link = 'https://finance.naver.com/world'
res = requests.get(link)
html = res.text
start = html.find('var americaData')
end = html.find('var indexLocation',start)
print(html[start:end])
'''
soup = BeautifulSoup(res.content, 'html.parser')
# data = soup.select("table")
data... | Python | zaydzuhri_stack_edu_python |
import requests
import urllib.request
import time
from bs4 import BeautifulSoup , Comment
import re
set main_url = string https://data.ibb.gov.tr/dataset
set sort_recent_url = string ?sort=views_total+desc&page=
set webpage_counter = list 1 2 3 4 5 6 7 8 9 10
set categories_url = string ?groups=
set sort_url = string ?... | import requests
import urllib.request
import time
from bs4 import BeautifulSoup,Comment
import re
main_url = 'https://data.ibb.gov.tr/dataset'
sort_recent_url = '?sort=views_total+desc&page='
webpage_counter = [1,2,3,4,5,6,7,8,9,10]
categories_url = '?groups='
sort_url = '?sort=views_recent+desc'
categories... | Python | zaydzuhri_stack_edu_python |
function get_all_recipes current_user
begin
comment default query
set query = call group_by id
comment get query string
set query_string = args
comment filters
set name_keyword = get query_string string name
set text_keyword = get query_string string text
set ingredient_keyword_list = call getlist string ingredient
com... | def get_all_recipes(current_user):
# default query
query = Recipe.query.join(Recipe.used).group_by(Recipe.id)
# get query string
query_string = request.args
# filters
name_keyword = query_string.get('name')
text_keyword = query_string.get('text')
ingredient_keyword_list = query_string.... | Python | nomic_cornstack_python_v1 |
function set_order self order
begin
string Takes a list of dictionaries. Those correspond to the arguments of `list.sort` and must contain the keys 'key' and 'reverse' (a boolean). You must call `set_labels` before this!
set m = call ListStore bool str
for item in order
begin
append m tuple item at string reverse item ... | def set_order(self, order):
"""
Takes a list of dictionaries. Those correspond to the arguments of
`list.sort` and must contain the keys 'key' and 'reverse' (a boolean).
You must call `set_labels` before this!
"""
m = gtk.ListStore(bool, str)
for item in order:
... | Python | jtatman_500k |
comment !/usr/bin/env python2.7
from bs4 import BeautifulSoup
import json
import sys
set html = string
for line in stdin
begin
set html = html + line
end
set html = replace html string </tr> string
set soup = call BeautifulSoup html string html.parser
set data = list
set c = 0
set col = dict
set cells = find all fin... | #!/usr/bin/env python2.7
from bs4 import BeautifulSoup
import json
import sys
html = ''
for line in sys.stdin:
html += line
html = html.replace('</tr>', '')
soup = BeautifulSoup(html, 'html.parser')
data = []
c = 0
col = {}
cells = soup.find('tbody').find_all('td')
for cell in cells:
c += 1
if c == 1:
... | Python | zaydzuhri_stack_edu_python |
from django.shortcuts import render , redirect
comment Create your views here.
function index request
begin
return call render request string land/index.html
end function
function land request number
begin
set value = integer number
if value <= 50
begin
set picture = string
if value >= 1 and value <= 10
begin
set pict... | from django.shortcuts import render, redirect
# Create your views here.
def index(request):
return render(request, 'land/index.html')
def land(request, number):
value = int(number)
if value <=50:
picture = ''
if value >= 1 and value <= 10:
picture = 'snow'
elif value >=... | Python | zaydzuhri_stack_edu_python |
function spherical_to_geodetic self longitude spherical_latitude radius
begin
set sinlat = sin call radians spherical_latitude
set coslat = square root 1 - sinlat ^ 2
set big_z = radius * sinlat
set p_0 = radius ^ 2 * coslat ^ 2 / semimajor_axis ^ 2
set q_0 = 1 - eccentricity ^ 2 / semimajor_axis ^ 2 * big_z ^ 2
set r_... | def spherical_to_geodetic(self, longitude, spherical_latitude, radius):
sinlat = np.sin(np.radians(spherical_latitude))
coslat = np.sqrt(1 - sinlat**2)
big_z = radius * sinlat
p_0 = radius**2 * coslat**2 / self.semimajor_axis**2
q_0 = (1 - self.eccentricity**2) / self.semimajor_a... | Python | nomic_cornstack_python_v1 |
function printState_8p state
begin
return call printState state
end function | def printState_8p(state):
return printState(state) | Python | nomic_cornstack_python_v1 |
function check_study_time self
begin
if call weekday != 6 and _lesson_calls at 0 at string start at string h <= hour <= _lesson_calls at 5 at string end at string h
begin
if hour == _lesson_calls at 5 at string end at string h and minute > _lesson_calls at 5 at string end at string m
begin
return false
end
comment if s... | def check_study_time(self) -> bool:
if self._current_time.weekday() != 6 \
and self._lesson_calls[0]['start']['h'] <= self._current_time.hour <= self._lesson_calls[5]['end']['h']:
if self._current_time.hour == self._lesson_calls[5]['end']['h'] \
and self._current... | Python | nomic_cornstack_python_v1 |
function search a x
begin
return call __search a x 0 length a - 1
end function
function __search a x low high
begin
if low > high
begin
return - 1
end
set mid = low + high / 2
if a at mid == x
begin
return mid
end
if a at mid > x
begin
return call __search a x mid + 1 high
end
else
begin
return call __search a x low mi... | def search(a, x):
return __search(a, x, 0, len(a) - 1)
def __search(a, x, low, high):
if low > high:
return -1
mid = (low + high) / 2
if a[mid] == x:
return mid
if a[mid] > x:
return __search(a, x, mid + 1, high)
else:
return __search(a, x, low, mid - 1)
l = [1... | Python | zaydzuhri_stack_edu_python |
if tuple 2 <= A B and C <= 10000
begin
print A + B % C
print A % C + B % C % C
print A * B % C
print A % C * B % C % C
end | if (2 <= A,B and C <= 10000):
print((A+B)%C)
print((A%C + B%C)%C)
print((A*B)%C)
print((A%C * B%C)%C) | Python | zaydzuhri_stack_edu_python |
from random import *
import math
import copy
comment init mat
function initNN m n
begin
set para = list
for i in range m
begin
append para list
for j in range n
begin
append para at i random
end
end
return para
end function
comment hide level function
function fun x
begin
return 1.0 / exp - x + 1.0
end function
commen... | from random import *
import math
import copy
#init mat
def initNN(m,n):
para=[]
for i in range(m):
para.append([])
for j in range(n):
para[i].append(random())
return para
#hide level function
def fun(x):
return 1.0/(math.exp(-x)+1.0)
#forward
def predict(data,V,W,b1,b2):
... | Python | zaydzuhri_stack_edu_python |
import sys
from game.engine import loop
from game.utils.generate_game import generate
from scrimmage.client import Client
import version
import updater
import game.config
import argparse
if __name__ == string __main__
begin
comment Setup Primary Parser
set par = call ArgumentParser
comment Create Subparsers
set spar = ... | import sys
from game.engine import loop
from game.utils.generate_game import generate
from scrimmage.client import Client
import version
import updater
import game.config
import argparse
if __name__ == '__main__':
#Setup Primary Parser
par = argparse.ArgumentParser()
# Create Subparsers
spar = par.ad... | Python | zaydzuhri_stack_edu_python |
function catchment_settings self data filename=string Clarea.xml lakes=none areas=none
begin
comment Get the number of vegetation zones
comment ---------------------------------------------------------------------
set vg = list
for value in columns
begin
append vg integer value at 7
end
set vegetation_zone_count = max... | def catchment_settings(
self, data, filename='Clarea.xml', lakes=None, areas=None):
# Get the number of vegetation zones
# ---------------------------------------------------------------------
vg = []
for value in data.columns:
vg.append(int(value[7]))
veg... | Python | nomic_cornstack_python_v1 |
comment Write a Python program to get the Python version you are using
import sys
import platform
print string Python version is:
print version at slice 0 : 5 :
print string version info:
print version_info
print
print call python_version | # Write a Python program to get the Python version you are using
import sys
import platform
print('Python version is:')
print(sys.version[0:5])
print('version info:')
print(sys.version_info)
print()
print(platform.python_version()) | Python | zaydzuhri_stack_edu_python |
function save_data_to_db data
begin
set db = call DbService
set queries = list comprehension string INSERT INTO { table } ( { join string , columns } ) VALUES { call get_values data at table } for tuple table columns in items DATA_TABLES
for query in queries
begin
execute db query
end
end function | def save_data_to_db(data):
db = DbService()
queries = [
f"INSERT INTO {table} ({','.join(columns)}) "
f"VALUES {get_values(data[table])}"
for table, columns in DATA_TABLES.items()
]
for query in queries:
db.execute(query) | Python | nomic_cornstack_python_v1 |
function custom_compliance_standard self
begin
return _custom_compliance_standard
end function | def custom_compliance_standard(self):
return self._custom_compliance_standard | Python | nomic_cornstack_python_v1 |
function reward self observation action reward
begin
if reward > 0
begin
print string win
set done = 1
set done_MC = 1
end
else
begin
set done = 0
end
set current_state = observation
set current_action = action
set current_reward = reward
append reward_list item reward
append log_probs log_prob
append values value
appe... | def reward(self, observation, action, reward):
if reward > 0 :
print("win")
self.done=1
self.done_MC=1
else:
self.done=0
self.current_state=observation
self.current_action=action
self.current_reward=... | Python | nomic_cornstack_python_v1 |
function update self zeta omega
begin
function function x kwargs
begin
string Computes part of the likelihood function that has terms containing `alpha`.
set zeta = kwargs at string zeta
set omega = kwargs at string omega
set constant = kwargs at string constant
set zetaestim = kwargs at string zetaestim
set func = arr... | def update(self, zeta, omega):
def function(x, kwargs):
"""Computes part of the likelihood function that has
terms containing `alpha`.
"""
zeta = kwargs['zeta']
omega = kwargs['omega']
constant = kwargs['constant']
zetaestim =... | Python | nomic_cornstack_python_v1 |
comment IN THIS PROBLEM WE HAVE TO CLASSIFY THE PEOPLE ACCORDING TO WHO BOUGHT THE car AND WHO DIDN'T
comment ACCORDING TO AGE AND INCOME(SEE DATASET IN MS-EXCEL)
comment Classification template
comment Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
comment Importing the ... | #IN THIS PROBLEM WE HAVE TO CLASSIFY THE PEOPLE ACCORDING TO WHO BOUGHT THE car AND WHO DIDN'T
#ACCORDING TO AGE AND INCOME(SEE DATASET IN MS-EXCEL)
# Classification template
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read... | Python | zaydzuhri_stack_edu_python |
string 读取配置。
import os
from tools.file_reader import YamlReader
comment 通过当前文件的绝对路径,其父级目录一定是框架的base目录,然后确定各层的绝对路径
set BASE_PATH = split path directory name path absolute path path __file__ at 0
set CONFIG_FILE = join path BASE_PATH string config string config.yml
set DATA_PATH = join path BASE_PATH string data
set DRIV... | '''
读取配置。
'''
import os
from tools.file_reader import YamlReader
#通过当前文件的绝对路径,其父级目录一定是框架的base目录,然后确定各层的绝对路径
BASE_PATH = os.path.split(os.path.dirname(os.path.abspath(__file__)))[0]
CONFIG_FILE = os.path.join(BASE_PATH,'config','config.yml')
DATA_PATH = os.path.join(BASE_PATH,'data')
DRIVER_PATH =os.path.join(BASE_PATH... | Python | zaydzuhri_stack_edu_python |
while start <= end
begin
set mid = start + end // 2
set total = 0
for city in cities
begin
if city > mid
begin
set total = total + mid
end
else
begin
set total = total + city
end
end
if total <= budgets
begin
set start = mid + 1
end
else
begin
set end = mid - 1
end
end
print end | while start <= end:
mid = (start + end) // 2
total = 0
for city in cities:
if city > mid:
total += mid
else:
total += city
if total <= budgets:
start = mid + 1
else:
end = mid - 1
print(end)
| 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.