code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
from reasoning_model import *
from ahpy.ahpy import ahpy
import pickle
import random
from functools import reduce
class Strategy extends Enum
begin
set INVASIVE = string invasive
set SECURE = string secure
end class
decorator dataclass
class WorldFactory
begin
set world_dim : list
set n_teams : int
set hitter_energy_me... | from reasoning_model import *
from ahpy.ahpy import ahpy
import pickle
import random
from functools import reduce
class Strategy(Enum):
INVASIVE = 'invasive'
SECURE = 'secure'
@dataclass
class WorldFactory:
world_dim: list
n_teams: int
hitter_energy_mean: float
hitter_energy_deviation: float
resource_energy_... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function convert self s numRows
begin
string :type s: str :type numRows: int :rtype: str
set row_dict = dict
set index_arr = list
for index in range numRows
begin
append index_arr index
set row_dict at index = list
end
for index in range numRows - 2 0 - 1
begin
append index_arr index
end
set pos... | class Solution:
def convert(self, s, numRows):
"""
:type s: str
:type numRows: int
:rtype: str
"""
row_dict = {}
index_arr = []
for index in range(numRows):
index_arr.append(index)
row_dict[index] = []
for i... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
from tkinter import ttk
comment creates a blank window named root
set root = call Tk
comment renames title to Roddy
title root string Roddy
comment Two different functions demonstrating two techniques with almost the same outcome:
comment In the second technique, it invokes the function once you c... | from tkinter import *
from tkinter import ttk
root = Tk() # creates a blank window named root
root.title('Roddy') # renames title to Roddy
# Two different functions demonstrating two techniques with almost the same outcome:
# In the second technique, it invokes the function once you click down the mouse butto... | Python | zaydzuhri_stack_edu_python |
function not_empty self key
begin
if call __contains__ key and self at key
begin
return true
end
return false
end function | def not_empty(self, key):
if self.__contains__(key) and self[key]:
return True
return False | Python | nomic_cornstack_python_v1 |
import win32com.client as wincl
from Speech import stt
from Read import pread , read
from Answer import re_answer
set speak = call Dispatch string SAPI.SpVoice
comment answer unsolved questions
function unsolved arr c
begin
set uns = false
for q in range 1 c + 1
begin
if arr at q == 1
begin
set uns = true
call Speak st... | import win32com.client as wincl
from Speech import stt
from Read import pread,read
from Answer import re_answer
speak = wincl.Dispatch("SAPI.SpVoice")
def unsolved (arr,c): #answer unsolved questions
uns=False
for q in range(1, c + 1):
if arr[q] == 1:
uns=True
speak.Speak("Q... | Python | zaydzuhri_stack_edu_python |
function read_abaqus abaqus_inp_filename log=none debug=false
begin
set model = call Abaqus log=log debug=debug
call read_abaqus_inp abaqus_inp_filename
return model
end function | def read_abaqus(abaqus_inp_filename, log=None, debug=False):
model = Abaqus(log=log, debug=debug)
model.read_abaqus_inp(abaqus_inp_filename)
return model | Python | nomic_cornstack_python_v1 |
from character import character
from rand import loot , event
from character import weapons
function get_home
begin
set prompt = input string Please select a function: (1) Add a Weapon: (2) View a Character: (3) Random Loot (4) Random Event >
if prompt == string 1
begin
call create_weapon
end
else
if prompt == string 2... | from character import character
from rand import loot, event
from character import weapons
def get_home():
prompt = input("\nPlease select a function: \n (1) Add a Weapon: \n (2) View a Character: \n (3) Random Loot \n (4) Random Event \n>")
if prompt == "1":
weapons.create_weapon()
elif prompt == "2":
c... | Python | zaydzuhri_stack_edu_python |
function HalfHelixTiltConsistent self TiltDiscrepancyThreshold=30.0
begin
string within a given threshold (default value at 30.0 DEG)
set HalfHelixTiltsPCAI = call HalfHelixTiltsPCA
set HalfHelixTiltsCOMI = call HalfHelixTiltsCOM_Vector
for N in range 2
begin
if absolute HalfHelixTiltsPCAI at N - HalfHelixTiltsCOMI at ... | def HalfHelixTiltConsistent (self, TiltDiscrepancyThreshold = 30.0 ):
""" within a given threshold (default value at 30.0 DEG) """
HalfHelixTiltsPCAI = self. HalfHelixTiltsPCA ()
HalfHelixTiltsCOMI = self. HalfHelixTiltsCOM_Vect... | Python | nomic_cornstack_python_v1 |
function _dict_from_refs lines
begin
set refs = dictionary
for line in lines
begin
set tmp = split line
if length tmp == 2
begin
set v = strip tmp at 0 string
set k = strip tmp at 1 string
if v and k
begin
set refs at k = v
end
end
end
return refs
end function | def _dict_from_refs(lines):
refs = dict()
for line in lines:
tmp = line.split()
if (len(tmp) == 2):
v = tmp[0].strip("\r\n\t ")
k = tmp[1].strip("\r\n\t ")
if v and k:
refs[k] = v
return refs | Python | nomic_cornstack_python_v1 |
function dispersy_get_walk_candidate self
begin
set now = time
set result = none
set method = candidate_strategy
comment walk_type="with_restarts"
function get_score candidate
begin
try
begin
set peer = call get_peer_from_candidate candidate
end
except any
begin
warning string fault in the database: unable to get peer ... | def dispersy_get_walk_candidate(self):
now = time()
result = None
method = self._scenario_script.candidate_strategy
#walk_type="with_restarts"
def get_score(candidate):
try:
peer = self._scenario_script.get_peer_from_candidate(candidate)
... | Python | nomic_cornstack_python_v1 |
function bubblesort list descending=false
begin
set unsorted_numbers = length list
if descending
begin
while unsorted_numbers >= 1
begin
set last_unsorted_index = 0
for i in range 1 unsorted_numbers
begin
if list at i - 1 < list at i
begin
set tuple list at i list at i - 1 = tuple list at i - 1 list at i
set last_unsor... | def bubblesort(list, descending=False):
unsorted_numbers = len(list)
if descending:
while unsorted_numbers >= 1:
last_unsorted_index = 0
for i in range(1, unsorted_numbers):
if list[i-1] < list[i]:
list[i], list[i-1] = list[i-1], ... | Python | nomic_cornstack_python_v1 |
function comparador formula
begin
set diccionario = dict
for i in range 0 length formula
begin
if formula at i == string @
begin
update diccionario dict formula at i 1
end
else
if get diccionario formula at i >= 1
begin
update diccionario dict formula at i 1 + diccionario at formula at i
end
else
begin
update dicciona... | def comparador (formula):
diccionario = {}
for i in range(0, len(formula)):
if formula[i] == '@':
diccionario.update({formula[i]:1})
elif diccionario.get(formula[i])>=1:
diccionario.update({formula[i]:1+diccionario[formula[i]]})
else:
diccion... | Python | nomic_cornstack_python_v1 |
function compute_confidence_interval data axis=0
begin
set a = 1.0 * array data
set m = mean np a axis=axis
set std = standard deviation np a axis=axis
set pm = 1.96 * std / square root shape at axis
return tuple m pm
end function | def compute_confidence_interval(data, axis=0):
a = 1.0 * np.array(data)
m = np.mean(a, axis=axis)
std = np.std(a, axis=axis)
pm = 1.96 * (std / np.sqrt(a.shape[axis]))
return m, pm | Python | nomic_cornstack_python_v1 |
comment !/bin/python
from abstractstemmer import AbstractStemmer
import porterstemmer
import sys
class PorterStemmer extends AbstractStemmer
begin
function __init__ self
begin
call __init__
set basename = string porter
end function
function process self words
begin
return list comprehension call stem word for word in w... | #!/bin/python
from abstractstemmer import AbstractStemmer
import porterstemmer
import sys
class PorterStemmer(AbstractStemmer):
def __init__(self, ):
super(PorterStemmer, self).__init__()
self.basename = 'porter'
def process(self, words):
return [porterstemmer.stem(word) for word in ... | Python | zaydzuhri_stack_edu_python |
comment if s1 is less then print -1
comment if s2 is less print 1
comment if both are same print 0
if s1 < s2
begin
set result = - 1
end
if s1 > s2
begin
set result = 1
end
print result | # if s1 is less then print -1
# if s2 is less print 1
# if both are same print 0
if s1 < s2:
result = -1
if s1 >s2:
result = 1
print(result)
| Python | zaydzuhri_stack_edu_python |
string A Binary Heap is a Binary Tree with following properties. 1) It’s a complete binary tree (All levels are completely filled except possibly the last level and the last level has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array. 2) A Binary Heap is either Min... | """
A Binary Heap is a Binary Tree with following properties.
1) It’s a complete binary tree (All levels are completely filled except possibly the last level and the last level
has all keys as left as possible). This property of Binary Heap makes them suitable to be stored in an array.
2) A Binary Heap is either Min H... | Python | zaydzuhri_stack_edu_python |
function sample_persons df pid=string pid n=none frac=0.1
begin
if is instance df Series
begin
set ids = call nunique
end
else
begin
set ids = unique
end
if not n
begin
set n = integer frac * length ids
end
set new_ids = random choice ids size=n
if is instance df Series
begin
set new_sample = df at ids
end
else
begin
s... | def sample_persons(df, pid='pid', n=None, frac=0.1):
if isinstance(df, pd.Series):
ids = df.index.nunique()
else:
ids = df[pid].unique()
if not n:
n = int(frac * len(ids))
new_ids = np.random.choice(ids, size=n)
if isinstance(df, pd.Series):
new_sample = df[ids]
... | Python | nomic_cornstack_python_v1 |
function update_lineplots self diff_sec
begin
set current_goals = list
for tuple ig line ax goal metric in zip range length goals completed_lines axes at tuple slice : : 0 goals metrics_history
begin
if line is not none
begin
remove line
end
clear collections
set tuple completed_lines at ig = plot work_time_hours m... | def update_lineplots(self, diff_sec):
current_goals = []
for ig, line, ax, goal, metric in zip(range(len(self.data.goals)), self.completed_lines, self.axes[:,0],
self.data.goals, self.data.metrics_history):
if line is not None:
l... | Python | nomic_cornstack_python_v1 |
function plot_scatter data label=none title=none x_label=string x y_label=string y show_index=none pca=true n_components=2 save_path=none
begin
if not is instance data ndarray
begin
set data = array data
end
comment dimensionality reduction
if shape at 1 > n_components
begin
if pca
begin
set pca = principal component a... | def plot_scatter(data,
label=None,
title=None,
x_label='x',
y_label='y',
show_index=None,
pca=True,
n_components=2,
save_path=None):
if not isinstance(data, np.ndarray):
da... | Python | nomic_cornstack_python_v1 |
function registerInitialState self gameState
begin
string Make sure you do not delete the following line. If you would like to use Manhattan distances instead of maze distances in order to save on initialization time, please take a look at CaptureAgent.registerInitialState in captureAgents.py.
call registerInitialState... | def registerInitialState(self, gameState):
'''
Make sure you do not delete the following line. If you would like to
use Manhattan distances instead of maze distances in order to save
on initialization time, please take a look at
CaptureAgent.registerInitialState in captureAgents.py.
'''
Cap... | Python | nomic_cornstack_python_v1 |
function perceptron_criteria_der m A Y
begin
reshape A m
reshape Y m
set p = Y * A
set b = zeros shape
set b at p > 0 = 0
set b at p <= 0 = - Y at p <= 0
set b at b == 0 = - 1
return reshape b 1 m
end function | def perceptron_criteria_der(m, A, Y):
A.reshape(m)
Y.reshape(m)
p = Y * A
b = np.zeros(A.shape)
b[p > 0] = 0
b[p <= 0] = -Y[p <= 0]
b[b == 0] = -1
return b.reshape(1,m) | Python | nomic_cornstack_python_v1 |
function load_keras_model config_json_path weights_path_prefix=none weights_data_buffers=none load_weights=true use_unique_name_scope=false
begin
with open config_json_path string rt as f
begin
set model_and_weights_manifest = load json f
end
if not is instance model_and_weights_manifest dict
begin
raise call TypeError... | def load_keras_model(config_json_path,
weights_path_prefix=None,
weights_data_buffers=None,
load_weights=True,
use_unique_name_scope=False):
with open(config_json_path, 'rt') as f:
model_and_weights_manifest = json.load(f)
if n... | Python | nomic_cornstack_python_v1 |
from project.hardware.hardware import Hardware
class HeavyHardware extends Hardware
begin
set TYPE = string Heavy
function __init__ self name capacity memory
begin
call __init__ name TYPE capacity * 2 integer memory * 0.75
end function
end class | from project.hardware.hardware import Hardware
class HeavyHardware(Hardware):
TYPE = "Heavy"
def __init__(self, name, capacity, memory):
super().__init__(name, self.TYPE, capacity * 2, int(memory * 0.75))
| Python | jtatman_500k |
import os
import csv
import psycopg2
set database = string mytestdb
set username = get environ string USER_NAME_PSQL
set password = get environ string PASSWORD_PSQL
set hostname = string 192.168.1.14
set port = string 5432
try
begin
comment For connecting to the database
set conn = call connect user=username password=p... | import os
import csv
import psycopg2
database = "mytestdb"
username = os.environ.get("USER_NAME_PSQL")
password = os.environ.get('PASSWORD_PSQL')
hostname = "192.168.1.14"
port = "5432"
try:
#For connecting to the database
conn = psycopg2.connect(user=username,
password=p... | Python | zaydzuhri_stack_edu_python |
function factorial n
begin
if n <= 1
begin
return 1
end
return n * call factorial n - 1
end function
print string Factorial of 10 call factorial 10 | def factorial(n):
if n <= 1: return 1
return n * factorial(n - 1)
print('Factorial of 10', factorial(10))
| Python | zaydzuhri_stack_edu_python |
function test_status_code self
begin
set url = string https://api.github.com/search/repositories?q=language:java&sort=stars
set r = get requests url
assert equal status_code 200
end function | def test_status_code(self):
url = 'https://api.github.com/search/repositories?q=language:java&sort=stars'
r = requests.get(url)
self.assertEqual(r.status_code, 200) | Python | nomic_cornstack_python_v1 |
function renderSession self session glyph failure=none
begin
set host = host_string
set header = format string {glyph} {host} glyph=glyph host=host
comment working list of resulting lines
set lines = list header
if failure
begin
comment if there is a session failure simply append it
set message = call red call unicode ... | def renderSession(self, session, glyph, failure=None):
host = session.worker.host_string
header = u"{glyph} {host}".format(glyph=glyph, host=host)
lines = [header] # working list of resulting lines
if failure:
# if there is a session failure simply append it
messa... | Python | nomic_cornstack_python_v1 |
from src.hacker_rank.challenges.finding_the_percentage import finding_the_percentage
function test_finding_the_percentage capsys
begin
call finding_the_percentage string Krishna
set captured = call readouterr
assert out == string 68.00
call finding_the_percentage string Harsh
set captured = call readouterr
assert out =... | from src.hacker_rank.challenges.finding_the_percentage import finding_the_percentage
def test_finding_the_percentage(capsys):
finding_the_percentage('Krishna')
captured = capsys.readouterr()
assert captured.out == '68.00\n'
finding_the_percentage('Harsh')
captured = capsys.readouterr()
asser... | Python | zaydzuhri_stack_edu_python |
function multiarray2np data
begin
set np_data = array data
comment Assuming that the output is a square matrix simplifies the problem.
set dim_size = integer square root size
set data_array = reshape np_data list dim_size dim_size
return data_array
end function | def multiarray2np(data):
np_data = np.array(data.data)
# Assuming that the output is a square matrix simplifies the problem.
dim_size = int(np.sqrt(np_data.size))
data_array = np_data.reshape([dim_size, dim_size])
return data_array | Python | nomic_cornstack_python_v1 |
comment Import Pygame librarie
import pygame
comment import of Class Button
from Class.boutton import Button
comment import of Class GameState
from Class.game_state import GameState
comment Function for Menu Screen
function menu_screen screen game_state
begin
string Args: screen - Screen dimensions game_state - GameSta... | import pygame # Import Pygame librarie
from Class.boutton import Button # import of Class Button
from Class.game_state import GameState # import of Class GameState
# Function for Menu Screen
def menu_screen(screen, game_state):
"""
Args:
screen - Screen dimensi... | Python | zaydzuhri_stack_edu_python |
from collections import defaultdict , Counter
comment Testando o uso de diversas coleções
set texto1 = string Existem várias questões que podem levar o profissional a considerar uma transição de carreira, e uma delas é ter insatisfações com o seu rumo profissional ou cargo atual e está tudo bem se isso acontecer, mudar... | from collections import defaultdict, Counter
# Testando o uso de diversas coleções
texto1 = """
Existem várias questões que podem levar o profissional a considerar uma transição de carreira, e uma delas é ter insatisfações com o seu rumo profissional ou cargo atual e está tudo bem se isso acontecer, mudar faz par... | Python | zaydzuhri_stack_edu_python |
import sys
import nltk
function getTypeWord word pos neg
begin
set answer = string none
set negg = open neg string r
set poss = open pos string r
for w in negg
begin
if strip w string == word
begin
set answer = string neg
end
end
comment print(w)
for w in poss
begin
if strip w string == word
begin
set answer = string p... | import sys
import nltk
def getTypeWord(word,pos,neg):
answer = "none"
negg = open(neg,"r")
poss = open(pos,"r")
for w in negg:
if w.strip('\n') == word:
answer = "neg"
#print(w)
for w in poss:
if w.strip('\n') == word:
answer = "pos"
#print(w)
return answer
def analyse(sen,pos,neg):
text =... | Python | zaydzuhri_stack_edu_python |
function cos direction
begin
return integer absolute 2 - direction - 1
end function | def cos(direction):
return int(abs(2 - direction) - 1) | Python | nomic_cornstack_python_v1 |
function handle_category_name
begin
set email = call auth at string email
set database_api = call get_database
if method == string GET
begin
set dataset_id = get args string id string
if dataset_id == string
begin
return tuple string Please provide an id 400
end
return call json_response call category_names email data... | def handle_category_name():
email = get_auth().auth()['email']
database_api = get_database()
if request.method == 'GET':
dataset_id = request.args.get('id', '')
if dataset_id == '':
return 'Please provide an id', 400
return json_response(database_api.category_names(email... | Python | nomic_cornstack_python_v1 |
import ika
import engine
import polar
import line
import collision
from point import Point
class Enemy
begin
function __init__ self x y r max_hp
begin
set corner = call Point x y
set r = r
set center = call GetCenter
set dead = false
set hp = max_hp
set dmgdealt = 10
set PLANET_CENTER_X = HALF_SCREEN_W
set PLANET_CENTE... | import ika
import engine
import polar
import line
import collision
from point import Point
class Enemy:
def __init__(self, x, y, r, max_hp):
self.corner = Point(x,y)
self.r = r
self.center = self.GetCenter()
self.dead = False
self.hp = max_hp
self.dmgdealt = 10
self.PLANET_CENTER_X = eng... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment Copyright (c) 2019 Jordi Mas i Hernandez <jmas@softcatala.org>
comment This program is free software; you can redistribute it and/or
comment modify it under the terms of the GNU Lesser General Public
comment License as published by the Free Software Foundation; either
comment versi... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2019 Jordi Mas i Hernandez <jmas@softcatala.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at yo... | Python | zaydzuhri_stack_edu_python |
comment 종료시간이 가장 빠른 am 선택 이건 무조건 답
comment a1 의 종료시간에 맞거나 이상인 친구들 중에서 해를 구함
import sys
set stdin = open string input9.txt string r
comment 탐욕 문제들은 대부분 정렬을 하고 한다
for tc in range 1 integer input + 1
begin
comment 개수
set N = integer input
set jobs = list comprehension list map int split input for _ in range N
comment 종료시간... | # 종료시간이 가장 빠른 am 선택 이건 무조건 답
# a1 의 종료시간에 맞거나 이상인 친구들 중에서 해를 구함
import sys
sys.stdin = open('input9.txt', 'r')
for tc in range(1, int(input())+1): # 탐욕 문제들은 대부분 정렬을 하고 한다
N = int(input()) # 개수
jobs = [list(map(int, input().split())) for _ in range(N)]
# 종료시간순으로 정렬
jobs.sort(key = lambda x: x[1]... | Python | zaydzuhri_stack_edu_python |
function test_ducts_with_subprocess self
begin
exists call assert_that SUBPROCESS_TEST_SCRIPT
set proc = none
set parent = none
try
begin
set parent = call psuedo_anonymous_parent_duct
call bind
set proc = popen list executable SUBPROCESS_TEST_SCRIPT listener_address env=dict string PYTHONPATH ROOT_DIR
call is_true
for... | def test_ducts_with_subprocess(self):
assert_that(SUBPROCESS_TEST_SCRIPT).exists()
proc = None
parent = None
try:
parent = MessageDuctParent.psuedo_anonymous_parent_duct()
parent.bind()
proc = subprocess.Popen(
[sys.executable, SUBPROCE... | Python | nomic_cornstack_python_v1 |
function put self path data=string mimetype=none metadata=dict
begin
comment Deal with missing mimetype
if not mimetype
begin
set tuple type_ enc_ = call guess_type path
if not type_
begin
set mimetype = string application/octet-stream
end
else
if enc_ == string gzip and type_ == string application/x-tar
begin
set mim... | def put(self, path, data="", mimetype=None, metadata={}):
# Deal with missing mimetype
if not mimetype:
type_, enc_ = mimetypes.guess_type(path)
if not type_:
mimetype = "application/octet-stream"
else:
if enc_ == "gzip" and type_ == "a... | Python | nomic_cornstack_python_v1 |
comment 반복문
comment 문제 02
comment (별 그리기)
comment 5이상 9이하의 홀수를 입력받아 다이아몬드 형태의 별을 출력하는 프로그램을 작성하시오.
comment 예) N=7
comment *
comment ***
comment *****
comment *******
comment *****
comment ***
comment *
set n = integer input string 5이상 9이하의 홀수를 입력하시오.:
for i in range 1 n
begin
for k in range 0 n - i - 1
begin
print stri... | ### 반복문
## 문제 02
## (별 그리기)
## 5이상 9이하의 홀수를 입력받아 다이아몬드 형태의 별을 출력하는 프로그램을 작성하시오.
## 예) N=7
## *
## ***
## *****
## *******
## *****
## ***
## *
n = int(input('5이상 9이하의 홀수를 입력하시오.: '))
for i in range(1, n):
for k in range(0, n - i -1):
print(' ', sep = '', end = '')
print('*' * (i * 2 - 1)... | Python | zaydzuhri_stack_edu_python |
import math
import argparse
set parser = call ArgumentParser description=string Calculate area of a rectangle
call add_argument string -w string --width type=int metavar=string required=true help=string Width of Rectangle
call add_argument string -H string --height type=int metavar=string required=true help=string He... | import math
import argparse
parser = argparse.ArgumentParser(description='Calculate area of a rectangle')
parser.add_argument('-w', '--width', type=int, metavar='', required=True, help='Width of Rectangle')
parser.add_argument('-H', '--height', type=int, metavar='', required=True, help='Height of Rectangle')
parser.a... | Python | zaydzuhri_stack_edu_python |
comment Definition for a binary tree node.
comment class TreeNode(object):
comment def __init__(self, x):
comment self.val = x
comment self.left = None
comment self.right = None
class Queue
begin
function __init__ self
begin
set array = list
end function
function is_empty self
begin
return if expression length array =... | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Queue:
def __init__(self):
self.array = []
def is_empty(self):
return (True if len(self.array) == 0 else False... | Python | zaydzuhri_stack_edu_python |
from time import sleep
import pytest
from pages.profile_settings import ProfileSettings
from pages.site_pages import SitePage
from pages.webview import WebView
from pages.my_site import MySite
from utils.readExcel import ReadData
from basetest import BaseTest
comment This test case is to verify if the blog web view dis... | from time import sleep
import pytest
from pages.profile_settings import ProfileSettings
from pages.site_pages import SitePage
from pages.webview import WebView
from pages.my_site import MySite
from utils.readExcel import ReadData
from basetest import BaseTest
# This test case is to verify if the blog web view displa... | Python | zaydzuhri_stack_edu_python |
import requests
from bs4 import BeautifulSoup
set url = string https://www.example.com
set r = get requests url
set soup = call BeautifulSoup content string html.parser
set title = string
set description = find soup string meta attrs=dict string name string description at string content
print string Title: title
print ... | import requests
from bs4 import BeautifulSoup
url = 'https://www.example.com'
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
title = soup.title.string
description = soup.find('meta', attrs={'name': 'description'})['content']
print('Title:', title)
print('Description:', description) | Python | jtatman_500k |
function remove_duplicates nums
begin
comment Step 1: Sort the array
sort nums
comment Step 2: Initialize the pointer to the current unique value
set i = 0
comment Step 3: Iterate through the array
for j in range 1 length nums
begin
comment If the current value is not equal to the value at index `i`,
comment we have en... | def remove_duplicates(nums):
# Step 1: Sort the array
nums.sort()
# Step 2: Initialize the pointer to the current unique value
i = 0
# Step 3: Iterate through the array
for j in range(1, len(nums)):
# If the current value is not equal to the value at index `i`,
# we have encoun... | Python | jtatman_500k |
function all self
begin
set candidates = list
set as_dict_list = call get_all
for as_dict in as_dict_list
begin
comment Transform from DB format to DTO format
set as_dict at string screen_name = as_dict at string _id
append candidates call Candidate keyword as_dict
end
return candidates
end function | def all(self):
candidates = []
as_dict_list = self.get_all()
for as_dict in as_dict_list:
# Transform from DB format to DTO format
as_dict['screen_name'] = as_dict['_id']
candidates.append(Candidate(**as_dict))
return candidates | Python | nomic_cornstack_python_v1 |
from flask import Flask
comment 渲染
from flask import render_template
set app = call Flask __name__
decorator call route string /
comment 主页地址,装饰器
function news
begin
set the_news = dict string Dayou string 全栈工程师 ; string Zhilong string 勇敢的打工人 ; string Aileen string 网页架构师 ; string Wenteng string 项目经理 ; string John strin... | from flask import Flask
from flask import render_template #渲染
app=Flask(__name__)
@app.route('/') #主页地址,装饰器
def news():
the_news = {
'Dayou':'全栈工程师',
'Zhilong':'勇敢的打工人',
'Aileen':'网页架构师',
'Wenteng':'项目经理',
'John':'团队甲方',
}
context={
'title':'小组007',
'... | Python | zaydzuhri_stack_edu_python |
import numpy
function nonlin x deriv=false
begin
if deriv == true
begin
return x * 1 - x
end
return 1 / 1 + exp - x
end function
comment input data
comment This data represents an NAND gate
comment each value is array of 1 x 2
set x = array list list 0 0 list 0 1 list 1 0 list 1 1
comment corresponding output for input... | import numpy
def nonlin(x, deriv=False):
if deriv == True:
return (x * (1 - x))
return (1/(1 + numpy.exp(-x)))
# input data
# This data represents an NAND gate
# each value is array of 1 x 2
x = numpy.array([[0,0],
[0,1],
[1,0],
[1,1]])
# corresponding output for input data
# This represents outp... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python2
import sys
import struct
from datetime import datetime
comment You can use this method to exit on failure conditions.
function bork msg
begin
exit msg
end function
comment Some constants. You shouldn't need to change these.
set MAGIC = 2343432205
set VERSION = 1
set counter = 8
if length a... | #!/usr/bin/env python2
import sys
import struct
from datetime import datetime
# You can use this method to exit on failure conditions.
def bork(msg):
sys.exit(msg)
# Some constants. You shouldn't need to change these.
MAGIC = 0x8BADF00D
VERSION = 1
counter = 8
if len(sys.argv) < 2:
sys.exit("Usage: python ... | Python | zaydzuhri_stack_edu_python |
import math
from functools import partial
from typing import TypeVar , Generic , List , Iterable , Callable , Optional , Tuple , Any
from akramRtree.models.rect import Rect , union_all
set T = call TypeVar string T
set DEFAULT_MAX_ENTRIES = 8
set EPSILON = 1e-05
class RTreeEntry extends Generic at T
begin
string R-Tree... | import math
from functools import partial
from typing import TypeVar, Generic, List, Iterable, Callable, Optional, Tuple, Any
from akramRtree.models.rect import Rect, union_all
T = TypeVar('T')
DEFAULT_MAX_ENTRIES = 8
EPSILON = 1e-5
class RTreeEntry(Generic[T]):
"""
R-Tree entry, containing either a pointer ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
comment -*- coding: utf8 -*-
print string Primer punto
set a = input string Escribe un número:
function sumatoria a
begin
if a == 1
begin
return 1
end
else
begin
return a + call sumatoria a - 1
end
end function | #!/usr/bin/python3
# -*- coding: utf8 -*-
print('Primer punto')
a=input("Escribe un número: ")
def sumatoria(a):
if a==1:
return 1
else:
return a+sumatoria(a-1) | Python | zaydzuhri_stack_edu_python |
function port2_docking_date self
begin
return _port2_docking_date
end function | def port2_docking_date(self):
return self._port2_docking_date | Python | nomic_cornstack_python_v1 |
function bilinear_sampler img x y
begin
comment prepare useful params
set B = call shape img at 0
set H = call shape img at 1
set W = call shape img at 2
set C = call shape img at 3
set max_y = call cast H - 1 string int32
set max_x = call cast W - 1 string int32
set zero = zeros list dtype=string int32
comment cast i... | def bilinear_sampler(img, x, y):
# prepare useful params
B = tf.shape(img)[0]
H = tf.shape(img)[1]
W = tf.shape(img)[2]
C = tf.shape(img)[3]
max_y = tf.cast(H - 1, 'int32')
max_x = tf.cast(W - 1, 'int32')
zero = tf.zeros([], dtype='int32')
# cast indices as float32 (for rescaling)
... | Python | nomic_cornstack_python_v1 |
function test_rb_decay self a b alpha
begin
set x = array range 1 100 5
set y = a * alpha ^ x + b
set alpha_guess = call rb_decay x y b=b
call assertAlmostEqual alpha alpha_guess delta=alpha * 0.1
end function | def test_rb_decay(self, a, b, alpha):
x = np.arange(1, 100, 5)
y = a * alpha**x + b
alpha_guess = guess.rb_decay(x, y, b=b)
self.assertAlmostEqual(alpha, alpha_guess, delta=alpha * 0.1) | Python | nomic_cornstack_python_v1 |
from lib.FileBound import FileBound
from lib.filestrategy.JsonStrategy import JsonDecoder , JsonEncoder
from lib.FileDataHandler import FileDataHandler
import os
comment Data classes
class Student
begin
function __init__ self studentNo=string lastName=string firstName=string gender=none description=string program=s... | from lib.FileBound import FileBound
from lib.filestrategy.JsonStrategy import JsonDecoder, JsonEncoder
from lib.FileDataHandler import FileDataHandler
import os
# Data classes
class Student:
def __init__(self, studentNo = "", lastName = "", firstName = "",
gender = None, description = "", program... | Python | zaydzuhri_stack_edu_python |
function preloop self
begin
comment handle any auto-commands for this cmdloop run
comment auto-commanding when needed
global TOURNAMENT_COMMAND_QUEUE
comment do any auto-commanding
set cmdqueue = TOURNAMENT_COMMAND_QUEUE
comment continue command loop
return false
end function | def preloop(self):
# handle any auto-commands for this cmdloop run
global TOURNAMENT_COMMAND_QUEUE # auto-commanding when needed
self.cmdqueue = TOURNAMENT_COMMAND_QUEUE # do any auto-commanding
return False # continue command loop | Python | nomic_cornstack_python_v1 |
comment Herhaal voor iedere karakter uit de string
comment Bereken ascii-waarde van het karakter
for letter in woord
begin
set code = ordinal letter
comment Druk achter elkaar af het karakter, de ascii-waarde van het karakter, de hexadecimale notatie en de binaire code
print format string {} {} {:x} {:b} letter code co... | #Herhaal voor iedere karakter uit de string
#Bereken ascii-waarde van het karakter
for letter in woord:
code = ord(letter)
#Druk achter elkaar af het karakter, de ascii-waarde van het karakter, de hexadecimale notatie en de binaire code
print('{} {} {:x} {:b}'.format(letter, code, code, code))
| Python | zaydzuhri_stack_edu_python |
import random
from art import logo
from art import vs
from game_data import data
function get_random_account
begin
return random choice data
end function
function format_data account
begin
set name = account at string name
set description = account at string description
set country = account at string country
comment p... | import random
from art import logo
from art import vs
from game_data import data
def get_random_account():
return random.choice(data)
def format_data(account):
name = account["name"]
description = account["description"]
country = account["country"]
# print(f'{name}: {account["follower_count"]}')... | Python | zaydzuhri_stack_edu_python |
function lines a b
begin
set similars = list
set lines_a = strip split a string
set lines_b = strip split b string
for line_a in lines_a
begin
for line_b in lines_b
begin
if line_b == line_a and line_a not in similars
begin
append similars line_a
end
end
end
return similars
end function
function sentences a b
begin
se... | def lines(a, b):
similars = []
lines_a = a.split("\n").strip()
lines_b = b.split("\n").strip()
for line_a in lines_a:
for line_b in lines_b:
if line_b == line_a and line_a not in similars:
similars.append(line_a)
return similars
def sentences(a, b):
simi... | Python | zaydzuhri_stack_edu_python |
function configure self instrument=none obs_duration=none lst=none
begin
set obs_plan = dict
comment subarray specific setup options
if instrument is not none and length instrument > 0
begin
set obs_plan at string instrument = instrument
end
comment set observation duration if specified
if obs_duration is not none
beg... | def configure(self,
instrument=None,
obs_duration=None,
lst=None):
obs_plan = {}
# subarray specific setup options
if instrument is not None and len(instrument) > 0:
obs_plan["instrument"] = instrument
# set observation du... | Python | nomic_cornstack_python_v1 |
function set_logger log_path
begin
set logger = call getLogger
call setLevel INFO
if not handlers
begin
comment Logging to a file
set file_handler = call FileHandler log_path
call setFormatter call Formatter string %(asctime)s:%(levelname)s: %(message)s
call addHandler file_handler
comment Logging to console
set stream... | def set_logger(log_path):
logger = logging.getLogger()
logger.setLevel(logging.INFO)
if not logger.handlers:
# Logging to a file
file_handler = logging.FileHandler(log_path)
file_handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s: %(message)s'))
logger.addHand... | Python | nomic_cornstack_python_v1 |
comment @lc app=leetcode.cn id=39 lang=python3
comment [39] 组合总和
comment @lc code=start
class Solution
begin
function combinationSum self candidates target
begin
set res = list
sort candidates
function dfs track start target
begin
if target == 0
begin
append res track at slice : :
end
for i in range start length can... | #
# @lc app=leetcode.cn id=39 lang=python3
#
# [39] 组合总和
#
# @lc code=start
class Solution:
def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
res = []
candidates.sort()
def dfs(track, start, target):
if target==0:
res... | Python | zaydzuhri_stack_edu_python |
function percentage_adv_max self
begin
return __percentage_adv_max
end function | def percentage_adv_max(self) -> float:
return self.__percentage_adv_max | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import time
import numpy as np
class RealTimePlotter
begin
string Plot in real time.
function __init__ self yLabels ylimMaxVals tStop=3000
begin
set size = 0.5
set yLabels = yLabels
set tuple _fig _ax = call subplots length yLabels 1 figsize=tuple 16 * size 9 * size
set _resultsFolder = ... | import matplotlib.pyplot as plt
import time
import numpy as np
class RealTimePlotter():
""" Plot in real time. """
def __init__(self, yLabels, ylimMaxVals, tStop=3000):
size = 0.5
self.yLabels = yLabels
self._fig, self._ax = plt.subplots(len(self.yLabels),1,figsize=(16*size,9*size))
self._resultsFolder = "... | Python | zaydzuhri_stack_edu_python |
import os
set environ at string FLASK_ENV = string development
from flask import Flask , render_template , request , redirect , session , flash
set app = call Flask __name__
set secret_key = string admin
import re
set EMAIL_REGEX = compile string ^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$
decorator call route string... | import os
os.environ["FLASK_ENV"] = "development"
from flask import Flask, render_template, request, redirect, session, flash
app = Flask(__name__)
app.secret_key = "admin"
import re
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
@app.route('/')
def index():
return render_template("ind... | Python | zaydzuhri_stack_edu_python |
function hierarchical_clustering cluster_list num_clusters
begin
while length cluster_list > num_clusters
begin
sort cluster_list key=lambda cluster -> call horiz_center
set tuple dummy_dist idx_i idx_j = call fast_closest_pair cluster_list
call merge_clusters cluster_list at idx_j
pop cluster_list idx_j
end
return clu... | def hierarchical_clustering(cluster_list, num_clusters):
while len(cluster_list) > num_clusters:
cluster_list.sort(key = lambda cluster: cluster.horiz_center())
dummy_dist, idx_i, idx_j = fast_closest_pair(cluster_list)
cluster_list[idx_i].merge_clusters(cluster_list[idx_j])
cluster_list.pop(idx_j)
return clu... | Python | nomic_cornstack_python_v1 |
comment A work in progress
comment A text adventure game to get to grips with bits of Python
comment If I had the commitment I'd make this the scale of Myst
comment but with more cyber-punk overtones.
comment If anyone ever finds this, please make the text green
comment so it looks like an 80s terminal.
import time , s... | # A work in progress
# A text adventure game to get to grips with bits of Python
# If I had the commitment I'd make this the scale of Myst
# but with more cyber-punk overtones.
# If anyone ever finds this, please make the text green
# so it looks like an 80s terminal.
import time, sys
def dead(why):
"""Exits the pro... | Python | zaydzuhri_stack_edu_python |
function isIndexed rootPath
begin
Ellipsis
end function | def isIndexed(rootPath: unicode) -> bool:
... | Python | nomic_cornstack_python_v1 |
function wait_func_accept_retry_state wait_func
begin
string Wrap wait function to accept "retry_state" parameter.
if not callable wait_func
begin
return wait_func
end
if call func_takes_retry_state wait_func
begin
return wait_func
end
if call func_takes_last_result wait_func
begin
decorator wraps wait_func
function wr... | def wait_func_accept_retry_state(wait_func):
"""Wrap wait function to accept "retry_state" parameter."""
if not six.callable(wait_func):
return wait_func
if func_takes_retry_state(wait_func):
return wait_func
if func_takes_last_result(wait_func):
@_utils.wraps(wait_func)
... | Python | jtatman_500k |
function create_thumbnail filepath
begin
make directories THUMBNAIL_PATH exist_ok=true
try
begin
set img = call imread filepath
set img = call resize img tuple 300 200 interpolation=INTER_NEAREST
call imwrite format string {}thumb_{} THUMBNAIL_PATH base name ntpath filepath img
print string Thumbnail created!
end
excep... | def create_thumbnail(filepath):
os.makedirs(THUMBNAIL_PATH, exist_ok=True)
try:
img = cv2.imread(filepath)
img = cv2.resize(img, (300, 200), interpolation=cv2.INTER_NEAREST)
cv2.imwrite('{}thumb_{}'.format(THUMBNAIL_PATH, ntpath.basename(filepath)), img)
print("Thumbnail created!... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
comment Advent of code 2017 day 9
comment See https://adventofcode.com/2017/day/9
function next_char line
begin
if line
begin
return tuple line at 0 line at slice 1 : :
end
else
begin
return tuple none list
end
end function
function garbage_next_char line
begin
set tuple next line = call ne... | #!/usr/bin/python3
# Advent of code 2017 day 9
# See https://adventofcode.com/2017/day/9
def next_char(line):
if line:
return line[0], line[1:]
else:
return None, []
def garbage_next_char(line):
next, line = next_char(line)
while next == "!":
# Skip the next character
... | Python | zaydzuhri_stack_edu_python |
class DisJointSetLinkedList
begin
function __init__ self
begin
set head = list none * 9
set tail = list none * 9
set size = - 1
set maxSize = 9
end function
class Node
begin
function __init__ self value
begin
set value = value
set next = none
end function
end class
string def makeSet(self, p): if self.size == self.maxS... | class DisJointSetLinkedList:
def __init__(self):
self.head = [None] * 9
self.tail = [None] * 9
self.size = -1
self.maxSize = 9
class Node:
def __init__(self, value):
self.value = value
self.next = None
'''
def makeSet(self, p):
if... | Python | zaydzuhri_stack_edu_python |
from http.server import SimpleHTTPRequestHandler , HTTPServer
from urllib.parse import urlparse
import functools
from config import cfg , project_root
import handlers
class KanyeHTTPHandler extends SimpleHTTPRequestHandler
begin
set api_root = cfg at string SERVER at string API_ROOT
function do_GET self
begin
set parse... | from http.server import SimpleHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse
import functools
from config import cfg, project_root
import handlers
class KanyeHTTPHandler(SimpleHTTPRequestHandler):
api_root = cfg["SERVER"]["API_ROOT"]
def do_GET(self):
self.parsed_path = urlparse(s... | Python | zaydzuhri_stack_edu_python |
function plot_shapefunctions
begin
set UIC60props = call UIC60properties
set tim4 = call Timoshenko4 UIC60props 0.3
set tuple fig ax = call subplots figsize=tuple 4 3
plot call N_w1 array range 0 1.1 0.1 label=string $N_{w_1}(\xi)$
plot call N_t1 array range 0 1.1 0.1 label=string $N_{\theta_1}(\xi)$
plot call N_w2 arr... | def plot_shapefunctions():
UIC60props = UIC60properties()
tim4 = Timoshenko4(UIC60props,0.3)
fig,ax = plt.subplots(figsize=(4,3))
ax.plot(tim4.N_w1(np.arange(0,1.1,0.1)),label = r'$N_{w_1}(\xi)$')
ax.plot(tim4.N_t1(np.arange(0,1.1,0.1)),label = r'$N_{\theta_1}(\xi)$')
ax.plot(tim4.N_w2(np.arange... | Python | nomic_cornstack_python_v1 |
string Tests for the smarttub integration.
from datetime import timedelta
from openpeerpower.components.smarttub.const import SCAN_INTERVAL
from openpeerpower.util import dt
from tests.common import async_fire_time_changed
async function trigger_update opp
begin
string Trigger a polling update by moving time forward.
s... | """Tests for the smarttub integration."""
from datetime import timedelta
from openpeerpower.components.smarttub.const import SCAN_INTERVAL
from openpeerpower.util import dt
from tests.common import async_fire_time_changed
async def trigger_update(opp):
"""Trigger a polling update by moving time forward."""
... | Python | jtatman_500k |
function iterative_levenshtein s t
begin
set rows = length s + 1
set cols = length t + 1
set dist = list comprehension list comprehension 0 for x in range cols for x in range rows
comment source prefixes can be transformed into empty strings
comment by deletions:
for i in range 1 rows
begin
set dist at i at 0 = i
end
c... | def iterative_levenshtein(s, t):
rows = len(s) + 1
cols = len(t) + 1
dist = [[0 for x in range(cols)] for x in range(rows)]
# source prefixes can be transformed into empty strings
# by deletions:
for i in range(1, rows):
dist[i][0] = i
# target prefixes can be created from an empty s... | Python | nomic_cornstack_python_v1 |
function _make_jobs self
begin
for tuple perturbation_instance search in zip _perturbation_instances _searches
begin
set instance = copy instance
set perturbation = perturbation_instance
set dataset = call simulate_function instance
yield call Job analysis=call analysis_class dataset model=model perturbation_model=pert... | def _make_jobs(self) -> Generator[Job, None, None]:
for perturbation_instance, search in zip(
self._perturbation_instances,
self._searches
):
instance = copy(self.instance)
instance.perturbation = perturbation_instance
dataset = ... | Python | nomic_cornstack_python_v1 |
function minimal_ident self
begin
comment Not @Lazy, implemented manually because _ident is in the structure
comment of the greenlet for fast access
if _ident is none
begin
set _ident = call _get_minimal_ident
end
return _ident
end function | def minimal_ident(self):
# Not @Lazy, implemented manually because _ident is in the structure
# of the greenlet for fast access
if self._ident is None:
self._ident = self._get_minimal_ident()
return self._ident | Python | nomic_cornstack_python_v1 |
function hpx_to_coords h shape
begin
string Generate an N x D list of pixel center coordinates where N is the number of pixels and D is the dimensionality of the map.
set tuple x z = call hpx_to_axes h shape
set x = square root x at slice 0 : - 1 : * x at slice 1 : :
set z = z at slice : - 1 : + 0.5
set x = call ra... | def hpx_to_coords(h, shape):
""" Generate an N x D list of pixel center coordinates where N is
the number of pixels and D is the dimensionality of the map."""
x, z = hpx_to_axes(h, shape)
x = np.sqrt(x[0:-1] * x[1:])
z = z[:-1] + 0.5
x = np.ravel(np.ones(shape) * x[:, np.newaxis])
z = np.... | Python | jtatman_500k |
comment -*- coding: utf-8 -*-
import redis
set pool = call ConnectionPool host=string 127.0.0.1 port=6379
set r = call Redis connection_pool=pool
comment 向集合中添加元素
call sadd string num1 33 44 55 66
call sadd string num2 66 77
comment 获取集合中元素的个数
print call scard string num1
comment 获取集合中所有的成员
print call smembers string n... | # -*- coding: utf-8 -*-
import redis
pool = redis.ConnectionPool(host='127.0.0.1', port=6379)
r = redis.Redis(connection_pool=pool)
# 向集合中添加元素
r.sadd('num1', 33, 44, 55, 66)
r.sadd('num2', 66, 77)
# 获取集合中元素的个数
print(r.scard('num1'))
# 获取集合中所有的成员
print(r.smembers('num1'))
# 获取多个集合的差集,第一个集合减掉第二个集合中相同的,保留剩下的
print(r.sd... | Python | zaydzuhri_stack_edu_python |
if produto < produto_2 and produto < produto_3
begin
print string O primeiro produto é mais barato
end
else
if produto_2 < produto and produto_2 < produto_3
begin
print string O segundo produto é mais barato
end
else
if produto_3 < produto_2 and produto_3 < produto
begin
print string O terceiro produto é mais barato
en... | if produto < produto_2 and produto < produto_3:
print("O primeiro produto é mais barato")
elif produto_2 < produto and produto_2 < produto_3:
print("O segundo produto é mais barato")
elif produto_3 < produto_2 and produto_3 < produto:
print("O terceiro produto é mais barato") | Python | zaydzuhri_stack_edu_python |
function notes self notes
begin
set _notes = notes
end function | def notes(self, notes):
self._notes = notes | Python | nomic_cornstack_python_v1 |
function init_sum board
begin
set tuple h w = tuple length cases_tab length cases_tab at 0
function find_point x y board
begin
set case = cases_tab at y at x
if case != 0 and state == 1 and score == 1
begin
set dirs = list list 1 - 1 list 2 0 list 1 1 list - 1 1 list - 2 0 list - 1 - 1
function advance x y dx dy
begin
... | def init_sum (board) :
h, w = len(board.cases_tab), len(board.cases_tab[0])
def find_point (x, y, board):
case = board.cases_tab[y][x]
if case != 0 and case.state == 1 and case.score == 1 :
dirs = [[1, -1], [2, 0], [1, 1], [-1, 1], [-2, 0], [-1, -1]]
def advance(x, y... | Python | zaydzuhri_stack_edu_python |
function get_num_instances im non_building_labels
begin
return call setdiff1d im non_building_labels
end function | def get_num_instances(im, non_building_labels):
return np.setdiff1d(im, non_building_labels) | Python | nomic_cornstack_python_v1 |
comment while lagao ...you dont need to ask for digits of number
function sumDigit x
begin
set l = 0
set y = 0
while x != 0
begin
set l = x % 10
set y = y + l
set x = x // 10
end
return y
end function
set s = call sumDigit n
print string the sum of digits of n string is s | #while lagao ...you dont need to ask for digits of number
def sumDigit(x):
l = 0
y = 0
while x != 0:
l = x%10
y += l
x = x//10
return y
s = sumDigit(n)
print("the sum of digits of",n,"is",s) | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from __future__ import division
set n = integer input string Digite um número de base binária:
set contador = 0
for i in range 0 n 1
begin
set n = n % 10
set contador = contador + 1
end | # -*- coding: utf-8 -*-
from __future__ import division
n=int(input('Digite um número de base binária:'))
contador=0
for i in range (0,n,1):
n=n%10
contador=contador+1 | Python | zaydzuhri_stack_edu_python |
class CustomException extends Exception
begin
function __init__ self message
begin
set message = message
end function
end class
function fibonacci n memo=dict
begin
if n < 0
begin
raise call CustomException string Input value cannot be negative.
end
if n <= 1
begin
return n
end
if n not in memo
begin
set memo at n = ca... | class CustomException(Exception):
def __init__(self, message):
self.message = message
def fibonacci(n, memo={}):
if n < 0:
raise CustomException("Input value cannot be negative.")
if n <= 1:
return n
if n not in memo:
memo[n] = fibonacci(n-1, memo) + fibonacci(n-2, mem... | Python | jtatman_500k |
comment !/usr/bin/env python2.7
comment Find the sum of all numbers which are equal to
comment the sum of the factorial of their digits.
comment Note: as 1! = 1 and 2! = 2 are not sums they are not included.
comment this solution reaches the answer by pure dynamic programming
comment on the factor sums and takes ~2 sec... | #!/usr/bin/env python2.7
# Find the sum of all numbers which are equal to
# the sum of the factorial of their digits.
# Note: as 1! = 1 and 2! = 2 are not sums they are not included.
# this solution reaches the answer by pure dynamic programming
# on the factor sums and takes ~2 seconds
from math import factorial, l... | Python | zaydzuhri_stack_edu_python |
function update self data
begin
string Updates object information with live data (if live data has different values to stored object information). Changes will be automatically applied, but not persisted in the database. Call `db.session.add(elb)` manually to commit the changes to the DB. Args: # data (:obj:) AWS API R... | def update(self, data):
'''Updates object information with live data (if live data has
different values to stored object information). Changes will be
automatically applied, but not persisted in the database. Call
`db.session.add(elb)` manually to commit the changes to the DB.
A... | Python | jtatman_500k |
function euclidean_distance x1 y1 x2 y2
begin
comment Calculating distance
return square root power x2 - x1 2 + power y2 - y1 2
end function
comment Driver Code
set x1 = integer input string Enter x1:
set y1 = integer input string Enter y1:
set x2 = integer input string Enter x2:
set y2 = integer input string Enter y2:... | def euclidean_distance(x1, y1, x2, y2):
# Calculating distance
return math.sqrt(math.pow(x2 - x1, 2) + math.pow(y2 - y1, 2))
# Driver Code
x1 = int(input("Enter x1:"))
y1 = int(input("Enter y1:"))
x2 = int(input("Enter x2:"))
y2 = int(input("Enter y2:"))
print(euclidean_distance(x1,y1,x2,y2)) | Python | jtatman_500k |
function save self *args **kwargs
begin
set total = price
save *args keyword kwargs
end function | def save(self, *args, **kwargs):
self.total = self.product.price
super().save(*args, **kwargs) | Python | nomic_cornstack_python_v1 |
from sqlalchemy import create_engine
from sqlalchemy import Table , Column , Integer , MetaData
set connection_data = dict string type string postgres ; string user string john ; string password string qwerty ; string host string localhost ; string port string 5432 ; string database string test
set db = call create_eng... | from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, MetaData
connection_data = {
'type': 'postgres',
'user': 'john',
'password': 'qwerty',
'host': 'localhost',
'port': '5432',
'database': 'test'
}
db = create_engine("{type}://{user}:{password}@{host}:{port}/{d... | Python | zaydzuhri_stack_edu_python |
import util
import numpy as np
import sys
import random
set PRINT = true
comment DON'T CHANGE THE SEEDS ##########
seed 42
seed 42
function small_classify y
begin
set tuple classifier data = y
return call classify data
end function
class AdaBoostClassifier
begin
string AdaBoost classifier. Note that the variable 'datum... | import util
import numpy as np
import sys
import random
PRINT = True
###### DON'T CHANGE THE SEEDS ##########
random.seed(42)
np.random.seed(42)
def small_classify(y):
classifier, data = y
return classifier.classify(data)
class AdaBoostClassifier:
"""
AdaBoost classifier.
Note that the variable... | Python | zaydzuhri_stack_edu_python |
function _download_batch self dates path
begin
if length dates < 1
begin
return
end
set tstart = time
print string Download started in folder { path }
with call ThreadPoolExecutor max_workers=60 as executor
begin
for date in dates
begin
call submit _download date path
end
end
print string Download finished in { time - ... | def _download_batch(self, dates, path):
if len(dates) < 1:
return
tstart = time.time()
print(f'Download started in folder {path}')
with futures.ThreadPoolExecutor(max_workers=60) as executor:
for date in dates:
executor.submit(self._download, date... | Python | nomic_cornstack_python_v1 |
function _get_pooled_connection self
begin
set pool = get pools config_tuple set
try
begin
set connection = pop pool
end
except KeyError
begin
set connection = call _new_connection
end
return connection
end function | def _get_pooled_connection(self):
pool = PooledConnection.pools.get(self.config_tuple, set())
try:
connection = pool.pop()
except KeyError:
connection = self._new_connection()
return connection | Python | nomic_cornstack_python_v1 |
function set_prediction self new
begin
set prediction = call Series new
end function | def set_prediction(self, new):
self.prediction = pd.Series(new) | Python | nomic_cornstack_python_v1 |
function mask_cross_entropy pred target label reduction=string mean avg_factor=none class_weight=none ignore_index=none **kwargs
begin
assert ignore_index is none msg string BCE loss does not support ignore_index
comment TODO: handle these two reserved arguments
assert reduction == string mean and avg_factor is none
se... | def mask_cross_entropy(pred,
target,
label,
reduction='mean',
avg_factor=None,
class_weight=None,
ignore_index=None,
**kwargs):
assert ignore_index is None... | Python | nomic_cornstack_python_v1 |
function trash_file file_to_trash document_name
begin
call dtpo_log string debug string trash_file file -> %s file_to_trash
set source = call get_source_directory + string / + file_to_trash
set destination = call get_trash_directory + string / + document_name
rename source destination
end function | def trash_file(file_to_trash, document_name) :
dtpo_log('debug', "trash_file file -> %s", file_to_trash)
source = Config.config.get_source_directory() + '/' + file_to_trash
destination = Config.config.get_trash_directory() + '/' + document_name
os.rename(source, destination) | Python | nomic_cornstack_python_v1 |
comment capitalisation of the start of the class name and its pascal camel case helps to differenciate between methods and functions
class Customer
begin
comment every __init__ needs a self, as the first declaration. Think of this as a function with the parameters name nd cash
function __init__ self name cash
begin
com... | class Customer: # capitalisation of the start of the class name and its pascal camel case helps to differenciate between methods and functions
def __init__(self, name, cash): # every __init__ needs a self, as the first declaration. Think of this as a function with the parameters name nd... | Python | zaydzuhri_stack_edu_python |
function _pde neurite
begin
comment Get the X, Y,Z coordinates of the points in each section
set points = points at tuple slice : : slice : 3 :
return call principal_direction_extent points at direction
end function | def _pde(neurite):
# Get the X, Y,Z coordinates of the points in each section
points = neurite.points[:, :3]
return morphmath.principal_direction_extent(points)[direction] | 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.