code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
set mnist = call read_data_sets string data one_hot=true
type mnist
shape
set sample = reshape images at 2 28 28
image show sample cmap=string Greys
set learning_rate = 0.001
set training_epochs = 15
set b... | import tensorflow as tf
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('data', one_hot=True)
type(mnist)
mnist.train.images.shape
sample = mnist.train.images[2].reshape(28, 28)
plt.imshow(sample, cmap='Greys')
learning_rate = 0.001
trainin... | Python | zaydzuhri_stack_edu_python |
comment 재귀용법을 이용한 다른 풀이
function fac n
begin
if n == 1
begin
return 1
end
else
begin
return n * call fac n - 1
end
end function
set n = integer input
print call fac n | # 재귀용법을 이용한 다른 풀이
def fac(n):
if n==1 : return 1
else : return n*fac(n-1)
n = int(input())
print(fac(n)) | Python | zaydzuhri_stack_edu_python |
comment # for x in range(0,5):
comment # print("hello %s" % x)
comment # bob=["bob,joe,sd,sdds,ds,ds,dsdsd"]
comment # for i in bob:
comment # print(i)
comment # print(i)
comment # for i in range(1,4):
comment # print(i)
comment # for j in range(1,i):
comment # print(j)
comment for e in range(1,5):
comment print(e*"*")... | # # for x in range(0,5):
# # print("hello %s" % x)
# # bob=["bob,joe,sd,sdds,ds,ds,dsdsd"]
# # for i in bob:
# # print(i)
# # print(i)
# # for i in range(1,4):
# # print(i)
# # for j in range(1,i):
# # print(j)
# for e in range(1,5): ... | Python | zaydzuhri_stack_edu_python |
comment funcão que recebe uma lista e devolve a soma de todos os elementos desta lista
function soma_elementos l
begin
set lista = l
set soma = 0
for elem in lista
begin
set soma = soma + elem
end
return soma
end function
set lista = list 7 3 33 12 3 3 3 7 12 100
print call soma_elementos lista | # funcão que recebe uma lista e devolve a soma de todos os elementos desta lista
def soma_elementos(l):
lista = l
soma = 0
for elem in lista:
soma = soma + elem
return soma
lista = [7,3,33,12,3,3,3,7,12,100]
print(soma_elementos(lista))
| Python | zaydzuhri_stack_edu_python |
function create_cube cls name size component_format
begin
set img = call cls string ImgCube- + name
set tuple comp_type comp_format = call convert_texture_format component_format
call setup_cube_map size comp_type comp_format
return img
end function | def create_cube(cls, name, size, component_format):
img = cls("ImgCube-" + name)
comp_type, comp_format = cls.convert_texture_format(component_format)
img.setup_cube_map(size, comp_type, comp_format)
return img | Python | nomic_cornstack_python_v1 |
comment Bayesian AB testing based on https://www.evanmiller.org/bayesian-ab-testing.html
from math import lgamma
from numba import jit
import numpy as np
from scipy.stats import beta
from calc_prob import calc_prob_between
import matplotlib.pyplot as plt
decorator jit
comment defining the functions used
function h a b ... | # Bayesian AB testing based on https://www.evanmiller.org/bayesian-ab-testing.html
from math import lgamma
from numba import jit
import numpy as np
from scipy.stats import beta
from calc_prob import calc_prob_between
import matplotlib.pyplot as plt
# defining the functions used
@jit
def h(a, b, c, d):
... | Python | zaydzuhri_stack_edu_python |
function calculate_population_one_child_breaking_law num_of_people men_factor fertility breaking_law_percentage
begin
comment initial variables with starting values
set population_list : list = list num_of_people
set generations_list : list = list 0
set num_of_man : int = floor num_of_people * men_factor
set num_of_wom... | def calculate_population_one_child_breaking_law(num_of_people: int, men_factor: float,
fertility: float, breaking_law_percentage: float) -> None:
# initial variables with starting values
population_list: list = [num_of_people]
generations_list: list = [0]
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import sys
import re
import r2pipe
class GoBinaryStripper
begin
string This script leverages radare2 scripting capabilities to overwrite with null bytes all the relevant information located within the Gopclntab section that might allow restoration of the original function names, difficultin... | #!/usr/bin/env python
import sys
import re
import r2pipe
class GoBinaryStripper():
"""
This script leverages radare2 scripting capabilities to overwrite with null
bytes all the relevant information located within the Gopclntab section that
might allow restoration of the original function names, difficulting this... | Python | zaydzuhri_stack_edu_python |
import time as t
class Mytimer
begin
comment 初始化一些参数
function __init__ self
begin
set unit = list string year string month string day string hour string minute string second
comment 当没有开始计时器是会提示的信息
set prompt = string Haven't start the timer.
comment 通过列表的操作进行字符串拼接
set lasted = list
set begin = 0
set end = 0
end funct... | import time as t
class Mytimer:
#初始化一些参数
def __init__(self):
self.unit = [' year ', ' month ', ' day ', ' hour ', ' minute ', ' second ']
self.prompt = 'Haven\'t start the timer.' #当没有开始计时器是会提示的信息
self.lasted = [] #通过列表的操作进行字符串拼接
self.begin = 0
self.end = 0
d... | Python | zaydzuhri_stack_edu_python |
for line in open file_name1 string r
begin
set m = m + 1
set a at split strip string line string at 0 = m
end
print length a string unique ids in + file_name1
set tuple Num b = tuple 0 list
for line in open file_name2 string r
begin
set Num = Num + 1
if Num % 1 == 0
begin
print Num string sequences have been searched!... | for line in open(file_name1,'r'):
m+=1
a[str(line).strip().split('\t')[0]]=m
print(len(a),'unique ids in '+file_name1)
Num, b = 0, []
for line in open(file_name2,'r'):
Num+=1
if Num%1==0:
print(Num, 'sequences have been searched!')
if line.startswith('>'):
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment -*- coding:utf-8 -*-
comment Python version: 2.7.11
comment pygame version:1.9.2a0
comment system:windows7 64 bit
comment Author: WangQihui E-mail : wangqihui0324@gmail.com
comment date: 2016/05/14 -05/18
comment version: 1.0
import pygame
from pygame.locals import *
from sys import... | #!/usr/bin/env python
# -*- coding:utf-8 -*-
# Python version: 2.7.11
# pygame version:1.9.2a0
# system:windows7 64 bit
# Author: WangQihui E-mail : wangqihui0324@gmail.com
# date: 2016/05/14 -05/18
# version: 1.0
import pygame
from pygame.locals import *
from sys import exit
import time
import random
from fir_ai i... | Python | zaydzuhri_stack_edu_python |
comment coding = utf-8
import requests
import unittest
import mock
function post_request url data
begin
set res = post url=url data=data
return res
end function
function get_request url data=none
begin
set res = get requests url=url params=data
return res
end function
class TestLogin extends TestCase
begin
comment setU... | #coding = utf-8
import requests
import unittest
import mock
def post_request(url,data):
res = requests.post(url=url,data=data)
return res
def get_request(url,data=None):
res = requests.get(url=url,params=data)
return res
class TestLogin(unittest.TestCase):
#setUp和tearDown方法在每个case执行前后执行
def... | Python | zaydzuhri_stack_edu_python |
function next_step self step
begin
from timing_system import round_next
set stepsize = stepsize
if step > 0.5 * stepsize
begin
set step = max call round_next step stepsize stepsize
end
return step
end function | def next_step(self,step):
from timing_system import round_next
stepsize = self.register.stepsize
if step > 0.5*stepsize:
step = max(round_next(step,stepsize),stepsize)
return step | Python | nomic_cornstack_python_v1 |
function format_and_make_string code json_file_path
begin
if code == 0
begin
set f = open json_file_path
set data = load json f
set data_string = dict string docs list
for rows in data
begin
append data_string at string docs rows
end
set string = replace replace string data_string string ' string " string " string \"
... | def format_and_make_string(code, json_file_path):
if code == 0:
f = open(json_file_path)
data = json.load(f)
data_string = {"docs": []}
for rows in data:
data_string["docs"].append(rows)
string = str(data_string).replace("'", "\"").replace('"', '\\"')
re... | Python | nomic_cornstack_python_v1 |
import sys
append path string ..
import math
import numpy as np
import cubature._test_integrands as ti
from cubature import cubature
comment test that the Genz oscillatory exact formula actually agrees at an
comment even and odd dimension
function test_genz_oscillatory_exact_d3
begin
set exact = 4 * cos 1056 + pi / 7 *... | import sys
sys.path.append('..')
import math
import numpy as np
import cubature._test_integrands as ti
from cubature import cubature
# test that the Genz oscillatory exact formula actually agrees at an
# even and odd dimension
def test_genz_oscillatory_exact_d3():
exact = 4 * np.cos(1056 + np.pi/7)*np.sin(12)*np... | Python | zaydzuhri_stack_edu_python |
function numTrees n
begin
set dp = list 0 * n + 1
set dp at 0 = 1
set dp at 1 = 1
for i in range 2 n + 1
begin
for j in range i
begin
set dp at i = dp at i + dp at j * dp at i - 1 - j
set dp at i = dp at i % 10 ^ 9 + 7
end
end
return dp at n
end function | def numTrees(n: int) -> int:
dp = [0] * (n + 1)
dp[0] = 1
dp[1] = 1
for i in range(2, n + 1):
for j in range(i):
dp[i] += dp[j] * dp[i - 1 - j]
dp[i] %= (10**9 + 7)
return dp[n]
| Python | jtatman_500k |
function estimate_induced_trips self
begin
if state != OK
begin
return
end
set control_template_dir = join path common_dir string STM/STM_A/Control_Template
set executable = join path stma_software_dir string ConvertTrips.exe
set controls = dict
set _environ = dictionary environ
for tuple purpose period in product PUR... | def estimate_induced_trips(self):
if self.state != TaskStatus.OK:
return
control_template_dir = os.path.join(self.common_dir, 'STM/STM_A/Control_Template')
executable = os.path.join(self.stma_software_dir, 'ConvertTrips.exe')
controls = {}
_environ = dict(os.enviro... | Python | nomic_cornstack_python_v1 |
string Created on Aug 11, 2017 @author: neerajalakshmia.k
from validations import UserValidation , BookMovieValidations , BankingValidation , TransferMoneyValidation
from database import TransferMoneyDB , CheckDB , InsertDB
import time
from exceptions.CustomException import InvalidMobileException
from classes.Transacti... | '''
Created on Aug 11, 2017
@author: neerajalakshmia.k
'''
from validations import UserValidation, BookMovieValidations,BankingValidation,TransferMoneyValidation
from database import TransferMoneyDB, CheckDB,InsertDB
import time
from exceptions.CustomException import InvalidMobileException
from classes.Transa... | Python | zaydzuhri_stack_edu_python |
function netapi32_NetDfsRemoveStdRoot jitter
begin
set tuple ret_ad args = call func_args_stdcall list string ServerName string RootShare string Flags
raise call RuntimeError string API not implemented
call func_ret_stdcall ret_ad ret_value
end function | def netapi32_NetDfsRemoveStdRoot(jitter):
ret_ad, args = jitter.func_args_stdcall(["ServerName", "RootShare", "Flags"])
raise RuntimeError('API not implemented')
jitter.func_ret_stdcall(ret_ad, ret_value) | Python | nomic_cornstack_python_v1 |
class dbConnect
begin
set _instance = none
function __new__ cls name
begin
if not _instance
begin
set _instance = call __new__ cls
print string super is called
print string db con is established
set _name = name
end
return _instance
end function
comment def __init__(self, name):
comment print("db is initialized")
funct... | class dbConnect():
_instance = None
def __new__(cls, name):
if not cls._instance:
cls._instance = super().__new__(cls)
print("super is called")
print("db con is established")
cls._name = name
return cls._instance
# def __init__(self, name):
... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import numpy as np
set x1 = linear space - 10.0 10.0 100
set x2 = linear space - 10.0 10.0 100
comment plt.scatter(x1, x2)
comment plt.show()
set tuple X1 X2 = call meshgrid x1 x2
set Y = square root call square X1 + call square X2
set cp = call contour X1 X2 Y
call clabel cp inline=1 fo... | import matplotlib.pyplot as plt
import numpy as np
x1 = np.linspace(-10.0, 10.0, 100)
x2 = np.linspace(-10.0, 10.0, 100)
# plt.scatter(x1, x2)
# plt.show()
X1, X2 = np.meshgrid(x1, x2)
Y = np.sqrt(np.square(X1) + np.square(X2))
cp = plt.contour(X1, X2, Y)
plt.clabel(cp, inline=1, fontsize=10)
plt.show()
| Python | zaydzuhri_stack_edu_python |
function build_desired_state_vpc clusters ocm_map awsapi account_filter
begin
set desired_state = list
set error = false
for cluster_info in clusters
begin
try
begin
set cluster = cluster_info at string name
set ocm = if expression ocm_map is none then none else get ocm_map cluster
set items = call build_desired_state... | def build_desired_state_vpc(
clusters, ocm_map: Optional[OCMMap], awsapi: AWSApi, account_filter: Optional[str]
):
desired_state = []
error = False
for cluster_info in clusters:
try:
cluster = cluster_info["name"]
ocm = None if ocm_map is None else ocm_map.get(cluster)
... | Python | nomic_cornstack_python_v1 |
function sign_up username password cli_s cli_addr
begin
if call check_new_username username
begin
set ad = call Admin username password cli_s cli_addr
call insert_into_table username password
return tuple true ad
end
return tuple false none
end function | def sign_up(username, password, cli_s,cli_addr):
if admins_sql.check_new_username(username):
ad = Admin(username, password, cli_s, cli_addr)
admins_sql.insert_into_table(username, password)
return True, ad
return False, None | Python | nomic_cornstack_python_v1 |
function validate_constrictions morphology
begin
set result = list
comment start with root, do depth-first traverse up to depth 10
set eligible_nodes = list
set to_visit = list tuple call get_root 0
while to_visit
begin
set tuple node depth = pop to_visit
if depth < 10
begin
append eligible_nodes node
extend to_visit... | def validate_constrictions(morphology):
result = []
# start with root, do depth-first traverse up to depth 10
eligible_nodes = []
to_visit = [(morphology.get_root(), 0)]
while to_visit:
(node, depth) = to_visit.pop()
if depth < 10:
eligible_nodes.append(node)
... | Python | nomic_cornstack_python_v1 |
function add self meta
begin
string Add a resource to this pool. The resource is loaded and returned when ``load_pool()`` is called. :param meta: The resource description
call _check_meta meta
call resolve_loader meta
append _resources meta
end function | def add(self, meta):
"""
Add a resource to this pool.
The resource is loaded and returned when ``load_pool()`` is called.
:param meta: The resource description
"""
self._check_meta(meta)
self.resolve_loader(meta)
self._resources.append(meta) | Python | jtatman_500k |
comment -*- coding: utf-8 -*-
string Created on Fri May 22 14:32:14 2015 Description: Inputs: Outputs: @author: Gurunath Reddy M
import numpy as np
from scipy.signal import get_window
import dftStft as stft
from scipy.fftpack import fft
import peakDetectCorrect as pdc
function getSinusoids x fs
begin
comment FFT parame... | # -*- coding: utf-8 -*-
"""
Created on Fri May 22 14:32:14 2015
Description:
Inputs:
Outputs:
@author: Gurunath Reddy M
"""
import numpy as np
from scipy.signal import get_window
import dftStft as stft
from scipy.fftpack import fft
import peakDetectCorrect as pdc
def getSinusoids(x, fs):
# FFT parameter setting... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import random
import math
import copy
from collections import namedtuple
set Point = named tuple string Point string x y
set show_animation = true
class Pose2D
begin
function __init__ self x y theta
begin
set x = x
set y = y
set theta = theta
end func... | import matplotlib.pyplot as plt
import matplotlib.patches as patches
import random
import math
import copy
from collections import namedtuple
Point = namedtuple('Point', 'x y')
show_animation = True
class Pose2D():
def __init__(self, x, y, theta):
self.x = x
self.y = y
self.theta = theta
... | Python | zaydzuhri_stack_edu_python |
function size self
begin
return length local_nstep_buffer
end function | def size(self):
return len(self.local_nstep_buffer) | Python | nomic_cornstack_python_v1 |
string Contains Scrapper classes
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen
import re
import os
class Scrapper
begin
set type = none
function __init__ self target
begin
set __target = target
end function
function getTarget self
begin
return __target
end function
function setTarget self tar... | """
Contains Scrapper classes
"""
from bs4 import BeautifulSoup as soup
from urllib.request import urlopen
import re
import os
class Scrapper:
type = None
def __init__(self, target):
self.__target = target
def getTarget(self):
return self.__target
def setTarget(self, target):
... | Python | zaydzuhri_stack_edu_python |
comment 2021-03-12, lucas.mayer.almeida@ccc.ufcg.edu.br
comment Calcula a média das notas de um aluno e a quantidade de minitestes para determinar sua situação na disciplina
set minitestes = integer input
set notas = 0
for i in range minitestes
begin
set valor = decimal input
set notas = notas + valor
end
set media = n... | # 2021-03-12, lucas.mayer.almeida@ccc.ufcg.edu.br
# Calcula a média das notas de um aluno e a quantidade de minitestes para determinar sua situação na disciplina
minitestes = int(input())
notas = 0
for i in range(minitestes):
valor = float(input())
notas += valor
media = notas / minitestes
if minitestes ==... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment -*- coding: UTF-8 -*-
import os
import logging
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
set sender = string trueno_wlz@sina.com
set passwd = string www13787196449
function send_m... | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import os
import logging
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
sender = 'trueno_wlz@sina.com'
passwd = 'www13787196449'
def send_mail(subject, content, receiver... | Python | zaydzuhri_stack_edu_python |
from selenium.webdriver.common.keys import Keys
import time
from selenium import webdriver
set browser = call Chrome
comment 1. 네이버 이동
get browser string http://naver.com
comment 2. 로그인 버튼 클릭
set elem = call find_element_by_class_name string link_login
call click
comment browser.back()
comment browser.forward()
comment... | from selenium.webdriver.common.keys import Keys
import time
from selenium import webdriver
browser = webdriver.Chrome()
# 1. 네이버 이동
browser.get("http://naver.com")
# 2. 로그인 버튼 클릭
elem = browser.find_element_by_class_name("link_login")
elem.click()
# browser.back()
# browser.forward()
# browser.refresh()
# browser.ba... | Python | zaydzuhri_stack_edu_python |
import exercises
import unittest
class RunExercises extends TestCase
begin
set celsius_to_fahrenheit = tuple tuple 0 32 tuple 50 122 tuple 100 212
set time_to_fall = tuple tuple 0 0 tuple 10 1.4285714285714286 tuple 20 2.0203050891044216 tuple 40 2.857142857142857 tuple 50 3.1943828249996997
set tower_checks = tuple tu... | import exercises
import unittest
class RunExercises(unittest.TestCase):
celsius_to_fahrenheit = ( (0, 32),
(50, 122),
(100, 212) )
time_to_fall = ( (0, 0),
(10, 1.4285714285714286),
(20, 2.0203050891044216),... | Python | zaydzuhri_stack_edu_python |
function iterative_binary_search arr x
begin
set low = 0
set high = length arr
set mid = low + high - low / 2
while x != arr at mid and low <= high
begin
if x < arr at mid
begin
set high = mid - 1
end
else
begin
set low = mid + 1
end
set mid = low + high - low / 2
end
if low > high
begin
return - 1
end
return mid
end f... | def iterative_binary_search(arr, x):
low = 0
high = len(arr)
mid = low + (high - low) / 2
while x != arr[mid] and low <= high:
if x < arr[mid]:
high = mid - 1
else:
low = mid + 1
mid = low + (high - low) / 2
if low > high:
return -1
re... | Python | nomic_cornstack_python_v1 |
function find_charge_center density lattice
begin
set avg = zeros 3
for i in range shape at 0
begin
for j in range shape at 1
begin
for k in range shape at 2
begin
set avg = avg + dot array tuple i j k / array shape lattice * density at tuple i j k
end
end
end
return avg / sum density
end function | def find_charge_center(density: np.ndarray, lattice: np.ndarray) -> np.ndarray:
avg = np.zeros(3)
for i in range(density.shape[0]):
for j in range(density.shape[1]):
for k in range(density.shape[2]):
avg += np.dot(np.array((i, j, k)) / np.array(density.shape),
... | Python | nomic_cornstack_python_v1 |
from config import DB_FILE
from config import INITIAL_FOOT
from util import insert_into_table
from util import check_insert_into_table
function insert_into_foot value
begin
string Insert one row in Foot table :param value: value to be inserted in Foot table
set db_file = DB_FILE
set sql = string INSERT INTO Foot(foot) ... | from config import DB_FILE
from config import INITIAL_FOOT
from util import insert_into_table
from util import check_insert_into_table
def insert_into_foot(value):
'''
Insert one row in Foot table
:param value: value to be inserted in Foot table
'''
db_file = DB_FILE
sql = "INSERT INTO Foot(foot) VALUES(?)"
... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
comment @param triangle, a list of lists of integers
comment @return an integer
function minimumTotal self triangle
begin
if length triangle == 0
begin
return 0
end
set cur = triangle at 0
for i in range 1 length triangle
begin
set next = list cur at 0 + triangle at i at 0
for j in range 1 length c... | class Solution:
# @param triangle, a list of lists of integers
# @return an integer
def minimumTotal(self, triangle):
if len(triangle) == 0: return 0
cur = triangle[0]
for i in range(1, len(triangle)):
next = [cur[0] + triangle[i][0]]
for j in range(1, len(cur... | Python | zaydzuhri_stack_edu_python |
from graphIO import *
from basicgraphs import graph
import time
import bisect
from Ex1_makegraphs import disjointunion
set step_counter = 0
set autolist = list
function generate_automorphism G trivial
begin
set finaldict = call fast_color_refine G
set automorphism = true
set colorclass = list
for color in keys finald... | from graphIO import *
from basicgraphs import graph
import time
import bisect
from Ex1_makegraphs import disjointunion
step_counter = 0
autolist = []
def generate_automorphism(G, trivial):
finaldict = fast_color_refine(G)
automorphism = True
colorclass = []
for color in finaldict.keys():
length = len(finald... | Python | zaydzuhri_stack_edu_python |
function get_kdmer_nodes_overlap_assembler d real_k=false
begin
function spl kdmer
begin
return split kdmer string |
end function
function assembler iterable
begin
set first = true
for node in iterate iterable
begin
set tuple a b = call spl key
comment a, b = spl(node)
if first
begin
if real_k
begin
set k = length a
en... | def get_kdmer_nodes_overlap_assembler(d, real_k=False):
def spl(kdmer):
return kdmer.split('|')
def assembler(iterable):
first = True
for node in iter(iterable):
a, b = spl(node.key)
#a, b = spl(node)
if first:
... | Python | nomic_cornstack_python_v1 |
import logging
import pandas as pd
import numpy as np
from sklearn import metrics
set __author__ = string Shahars
class AucCalculator extends object
begin
function __init__ self
begin
set __logger = call getLogger string endor.machine_learning.stats_calculator
end function
function calc_sorted_scorer_auc self sorted_sc... | import logging
import pandas as pd
import numpy as np
from sklearn import metrics
__author__ = 'Shahars'
class AucCalculator(object):
def __init__(self):
self.__logger = logging.getLogger('endor.machine_learning.stats_calculator')
def calc_sorted_scorer_auc(self, sorted_scores_df, scorer_name):
... | Python | zaydzuhri_stack_edu_python |
import pdb
comment See assignment sheet for an explanation of finding the silhouette of a
comment set of buildings...
function silhouette Buildings
begin
return call silhouetteAux Buildings 0 length Buildings - 1
end function
comment Find the silhouette of Buildings[i..k] using a divide-and-conquer algorithm
function s... | import pdb
# See assignment sheet for an explanation of finding the silhouette of a
# set of buildings...
def silhouette(Buildings):
return silhouetteAux(Buildings, 0, len(Buildings)-1)
# Find the silhouette of Buildings[i..k] using a divide-and-conquer algorithm
def silhouetteAux(Buildings, i, k):
if (i ==... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
comment In[1]:
import nltk
set texts = list string The year of birth of Socrates stated is an assumed date,[50] or estimate,[51] given the fact of the dating of anything in ancient history in part being sometimes reliant on argument stemming from the inexact period floruit of individuals. [52] Dio... | # coding: utf-8
# In[1]:
import nltk
texts = ["""The year of birth of Socrates stated is an assumed date,[50] or estimate,[51] given the fact of the dating of anything in ancient history in part being sometimes reliant on argument stemming from the inexact period floruit of individuals.
[52] Diogenes Laërtius state... | Python | zaydzuhri_stack_edu_python |
import click
from flask.cli import with_appcontext
from extensions import db
from users.models import User , Role
from sqlalchemy.exc import NoResultFound
decorator call command
decorator with_appcontext
decorator call argument string email nargs=1
decorator call argument string password nargs=1
function create_admin_u... | import click
from flask.cli import with_appcontext
from .extensions import db
from .users.models import User, Role
from sqlalchemy.exc import NoResultFound
@click.command()
@with_appcontext
@click.argument('email', nargs=1)
@click.argument('password', nargs=1)
def create_admin_user(email, password):
"""
A CLI ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python2
comment -*- coding: utf-8 -*-
function roundRobin units sets=none
begin
string Generates a schedule of "fair" pairings from a list of units
if length units % 2
begin
append units none
end
set count = length units
set sets = sets or count - 1
set half = count / 2
set schedule = list
for turn i... | #!/usr/bin/python2
# -*- coding: utf-8 -*-
def roundRobin(units, sets=None):
""" Generates a schedule of "fair" pairings from a list of units """
if len(units) % 2:
units.append(None)
count = len(units)
sets = sets or (count - 1)
half = count / 2
schedule = []
for turn in ... | Python | zaydzuhri_stack_edu_python |
comment !/bin/python3
from abc import abstractmethod
import itertools
from networkx import DiGraph
import networkx as nx
class Input
begin
decorator abstractmethod
function get self
begin
raise NotImplementedError
end function
function parse self
begin
set graph = call DiGraph
for line in split strip get self string st... | #!/bin/python3
from abc import abstractmethod
import itertools
from networkx import DiGraph
import networkx as nx
class Input:
@abstractmethod
def get(self) -> str:
raise NotImplementedError
def parse(self) -> DiGraph:
graph = DiGraph()
for line in self.get().strip('\n').split('... | Python | zaydzuhri_stack_edu_python |
function J_integ_outside self mu r
begin
return exp - 2.0 * chi * R * call g r mu
end function | def J_integ_outside(self, mu, r):
return np.exp(-2. * self.chi * self.R * self.g(r, mu)) | Python | nomic_cornstack_python_v1 |
function eat self herb_list
begin
set eaten_herbs = list
set remaining_appetite = params at string F
for herbivore in herb_list
begin
if call check_carn_prey call calculate_fitness call calculate_fitness
begin
append eaten_herbs herbivore
if remaining_appetite - weight >= 0
begin
set weight_to_eat = weight
end
else
be... | def eat(self, herb_list):
eaten_herbs = []
remaining_appetite = self.params['F']
for herbivore in herb_list:
if self.check_carn_prey(herbivore.calculate_fitness(), self.calculate_fitness()):
eaten_herbs.append(herbivore)
if remaining_appetite - herbi... | Python | nomic_cornstack_python_v1 |
import unittest
from centre_generator import waiting_list , centre_list , open_centre_list , full_centres , rand_centre_trainees
from centre_generator import add_trainee_to_centre
comment Testing the waiting_list variable is indeed a list.
class TestingWaitList extends TestCase
begin
function test_trainees self
begin
a... | import unittest
from centre_generator import waiting_list, centre_list, open_centre_list, full_centres, rand_centre_trainees
from centre_generator import add_trainee_to_centre
# Testing the waiting_list variable is indeed a list.
class TestingWaitList(unittest.TestCase):
def test_trainees(self):
self.ass... | Python | zaydzuhri_stack_edu_python |
function begin self fname
begin
set data at fname = dict string loc 0 ; string nosec 0
set current = data at fname
end function | def begin(self, fname):
self.data[fname] = {'loc': 0, 'nosec': 0}
self.current = self.data[fname] | Python | nomic_cornstack_python_v1 |
function parse_lemme self linea origin=0 _deramise=true
begin
string Constructeur de la classe Lemme à partir de la ligne linea. Exemple de linea avec numéro d'éclat: # cădo|lego|cĕcĭd|cās|is, ere, cecidi, casum|687 # 0 | 1 | 2 | 3 | 4 | 5 :param linea: Ligne à parser :type linea: str :param origin: 0 for original cura... | def parse_lemme(self, linea: str, origin: int=0, _deramise: bool=True):
""" Constructeur de la classe Lemme à partir de la ligne linea.
Exemple de linea avec numéro d'éclat:
# cădo|lego|cĕcĭd|cās|is, ere, cecidi, casum|687
# 0 | 1 | 2 | 3 | 4 | 5
... | Python | jtatman_500k |
comment (Sum the digits in an integer) Write a program that reads an integer between 0 and
comment 1000 and adds all the digits in the integer. For example, if an integer is 932, the
comment sum of all its digits is 14. (Hint: Use the % operator to extract digits, and use the //
comment operator to remove the extracted... | # (Sum the digits in an integer) Write a program that reads an integer between 0 and
# 1000 and adds all the digits in the integer. For example, if an integer is 932, the
# sum of all its digits is 14. (Hint: Use the % operator to extract digits, and use the //
# operator to remove the extracted digit. For instance, 93... | Python | zaydzuhri_stack_edu_python |
import math
import itertools
import functools
import operator
function sieve n
begin
set is_prime = list true * n + 1
set is_prime at 0 = false
set is_prime at 1 = false
set result = list
for tuple i prime in enumerate is_prime
begin
if prime
begin
append result integer i
for j in range i * i n + 1 i
begin
set is_prim... | import math
import itertools
import functools
import operator
def sieve(n):
is_prime=[True]*(n+1)
is_prime[0]=False
is_prime[1]=False
result=[]
for i,prime in enumerate(is_prime):
if prime:
result.append(int(i))
for j in range(i*i,n+1,i):
... | Python | zaydzuhri_stack_edu_python |
function get_configuration
begin
set root = call getLogger
set name_levels = list tuple string call getLevelName level
extend name_levels generator expression tuple name call getLevelName level for tuple name logger in items loggerDict if has attribute logger string level
set config_string = join string , generator ex... | def get_configuration():
root = getLogger()
name_levels = [('', logging.getLevelName(root.level))]
name_levels.extend(
(name, logging.getLevelName(logger.level))
for name, logger
in root.manager.loggerDict.items()
if hasattr(logger, 'level')
)
config_string = ','.joi... | Python | nomic_cornstack_python_v1 |
function iter_items cls repo *args **kwargs
begin
raise call NotImplementedError string To be implemented by Subclass
end function | def iter_items(cls, repo, *args, **kwargs):
raise NotImplementedError("To be implemented by Subclass") | Python | nomic_cornstack_python_v1 |
comment coding:utf-8
import sys | # coding:utf-8
import sys
| Python | zaydzuhri_stack_edu_python |
import sys
import os
append path directory name path filepath
from tools_level import *
from tools_blender import *
import bmesh
import bpy
from random import *
from bpy.props import *
comment properties of the panel
function initSceneProperties scn
begin
set Level = call IntProperty name=string Level description=strin... | import sys
import os
sys.path.append(os.path.dirname(bpy.data.filepath))
from tools_level import *
from tools_blender import *
import bmesh
import bpy
from random import *
from bpy.props import *
#properties of the panel
def initSceneProperties(scn):
bpy.types.Scene.Level = IntProperty(
name = "Level", ... | Python | zaydzuhri_stack_edu_python |
function trainingsVocabulary context
begin
set ct = call getToolByName context string portal_catalog
set dictSearch = dict string portal_type string apyb.papers.training ; string sort_on string sortable_title ; string review_state string confirmed
set trainings = call searchResults keyword dictSearch
set trainings = li... | def trainingsVocabulary(context):
ct = getToolByName(context,'portal_catalog')
dictSearch = {'portal_type':'apyb.papers.training',
'sort_on':'sortable_title',
'review_state':'confirmed'}
trainings = ct.searchResults(**dictSearch)
trainings = [SimpleTerm(b.UID,b.UID,b.... | Python | nomic_cornstack_python_v1 |
from tkinter import *
set root = call Tk
call config bg=string #000
set c = call StringVar
set f = call StringVar
function ctof
begin
set cel1 = integer get cel_entry
set far1 = cel1 * 1.8 + 32
set far1
end function
function ftoc
begin
set far2 = integer get far_entry
set cel2 = far2 - 32 / 1.8
set cel2
end function
se... | from tkinter import *
root = Tk()
root.config(bg = '#000')
c = StringVar()
f = StringVar()
def ctof():
cel1 = int(cel_entry.get())
far1 = (cel1*1.8)+32
f.set(far1)
def ftoc():
far2 = int(far_entry.get())
cel2 = (far2 - 32)/1.8
c.set(cel2)
lbl_Celsius = Label(root, text='Celsius' ,fg = '#... | Python | zaydzuhri_stack_edu_python |
function get_sentiment_history
begin
set params = args
set result = dict
set handle = params at string figure
set result_type = params at string result_type
set df = call read_time_data_for_person handle result_type
for tuple index row in call iterrows
begin
set result at index = dictionary row
end
return call jsonify... | def get_sentiment_history():
params = request.args
result = {}
handle = params['figure']
result_type = params['result_type']
df = read_time_data_for_person(handle, result_type)
for index, row in df.iterrows():
result[index] = dict(row)
return jsonify({
'sentiment_distribu... | Python | nomic_cornstack_python_v1 |
function _wiggle_writers self lib_name strands no_of_aligned_reads min_no_of_aligned_reads
begin
set coverage_writers_raw = dictionary list comprehension tuple strand call WiggleWriter string %s_%s % tuple lib_name strand open call wiggle_file_raw_path lib_name strand string w for strand in strands
set coverage_writers... | def _wiggle_writers(self, lib_name, strands, no_of_aligned_reads,
min_no_of_aligned_reads):
coverage_writers_raw = dict([(
strand, WiggleWriter(
"%s_%s" % (lib_name, strand),
open(self._paths.wiggle_file_raw_path(lib_name, strand),
... | Python | nomic_cornstack_python_v1 |
function Wanquanshu
begin
for i in range 1 10000
begin
set a = 0
for j in range 1 i
begin
if i % j == 0
begin
set a = a + j
end
end
if i == a
begin
print i
end
end
end function
call Wanquanshu | def Wanquanshu():
for i in range(1,10000):
a = 0
for j in range(1,i):
if i % j == 0:
a += j
if i == a:
print(i)
Wanquanshu() | Python | zaydzuhri_stack_edu_python |
function set_harmonic self harm
begin
if harm >= 1 and harm <= 19999
begin
set freq = decimal call get_frequency
if harm * freq <= 102000
begin
write instr format string HARM {0:d} harm
end
else
begin
raise call ValueError string Value for the harmonic is too high. Keyword harm has to fulfill the condition harm*freq<=1... | def set_harmonic(self, harm):
if harm >=1 and harm <=19999:
freq = float(self.get_frequency())
if harm*freq <= 102000:
self.instr.write('HARM {0:d}'.format(harm))
else:
raise ValueError('Value for the harmonic is too high. Keyword harm has to f... | Python | nomic_cornstack_python_v1 |
function connected self
begin
return connected
end function | def connected(self):
return self._periph.connected | Python | nomic_cornstack_python_v1 |
comment 프로그래머스 카카오 인턴 수식 최대화 문제
comment https://programmers.co.kr/learn/courses/30/lessons/67257
import re
set p = compile string ([0-9]*|[\-\+\*])
function operate op arr
begin
set idx = 1
while true
begin
if idx >= length arr - 1
begin
break
end
if arr at idx == op
begin
set v = 0
if op == string -
begin
set v = arr ... | # 프로그래머스 카카오 인턴 수식 최대화 문제
# https://programmers.co.kr/learn/courses/30/lessons/67257
import re
p = re.compile("([0-9]*|[\-\+\*])")
def operate(op,arr):
idx = 1
while True:
if idx >= len(arr) - 1 : break
if arr[idx] == op:
v = 0
if op == '-': v = arr[idx-1] - arr[idx + 1... | Python | zaydzuhri_stack_edu_python |
for i in range t
begin
set n = string input
set x = integer n at 0 + integer n at length n - 1
print x
end | for i in range(t):
n=str(input())
x=int(n[0])+int(n[len(n)-1])
print(x)
| Python | zaydzuhri_stack_edu_python |
function write_txt_lines file_path data_list overwrite=false
begin
set size = length data_list
if overwrite
begin
set mode = string w
end
else
begin
set mode = string a
end
comment # list in list.
comment for i in range(size):
comment with open(file_path, mode) as f:
comment for item in data_list[i]:
comment f.write("{... | def write_txt_lines(file_path, data_list, overwrite=False):
size = len(data_list)
if overwrite:
mode = 'w'
else:
mode = 'a'
# # list in list.
# for i in range(size):
# with open(file_path, mode) as f:
# for item in data_list[i]:
# f.write("{0}\n".f... | Python | nomic_cornstack_python_v1 |
function test_nfa_2 nfa
begin
set eingabe : str = string abababbaa
print string Test Case 0 with word '%s' with length %s started --- % tuple eingabe length eingabe
set eingabe : List at str = list eingabe
set start_zustand = 7
call do_simulation nfa start_zustand eingabe
print string Test Case 0 ended ---
end function | def test_nfa_2(nfa: NFA[S, A]) -> None:
eingabe: str = 'abababbaa'
print("Test Case 0 with word '%s' with length %s started ---" % (eingabe, len(eingabe)))
eingabe: List[str] = list(eingabe)
start_zustand = 7
do_simulation(nfa, start_zustand, eingabe)
print("Test Case 0 ended ---\n") | Python | nomic_cornstack_python_v1 |
function sta_fun np_data
begin
comment perform a sanity check
if np_data is none
begin
raise call ValueError string Input array cannot be None
end
comment perform the feature extraction
set dat_min = min np_data
set dat_max = max np_data
set dat_mean = mean np np_data
set dat_rms = square root sum call square np_data /... | def sta_fun(np_data):
# perform a sanity check
if np_data is None:
raise ValueError("Input array cannot be None")
# perform the feature extraction
dat_min = np.min(np_data)
dat_max = np.max(np_data)
dat_mean = np.mean(np_data)
dat_rms = np.sqrt(np.sum(np.square(np_data)) / len(np_d... | Python | nomic_cornstack_python_v1 |
import sqlite3
string 创建自定义比较函数:create_collation(name,callable) name:自定义函数名 callable:对应函数。该函数包含两个参数,两个参数进行比较,返回正数则第一个大,返回负数,第二个大,返回0,两个相等
comment 比较字符串的第一个字符
function compare_s s1 s2
begin
if s1 at 0 == s2 at 0
begin
return 0
end
else
if s1 at 0 > s2 at 0
begin
return 1
end
else
begin
return - 1
end
end function
commen... | import sqlite3
'''
创建自定义比较函数:create_collation(name,callable)
name:自定义函数名
callable:对应函数。该函数包含两个参数,两个参数进行比较,返回正数则第一个大,返回负数,第二个大,返回0,两个相等
'''
# 比较字符串的第一个字符
def compare_s(s1, s2):
if s1[0] == s2[0]:
return 0
elif s1[0] > s2[0]:
return 1
else:
return -1
# 打开数据库
conn = sqlite3.... | Python | zaydzuhri_stack_edu_python |
function get_url self page
begin
return server_url + page
end function | def get_url(self, page):
return self.server_url + page | Python | nomic_cornstack_python_v1 |
function __init__ self n_jobs=1 verbose=true
begin
set n_jobs = n_jobs
set verbose = verbose
end function | def __init__(self, n_jobs=1, verbose=True):
self.n_jobs = n_jobs
self.verbose = verbose | Python | nomic_cornstack_python_v1 |
function calc_kernel_shap_values model
begin
set explainer = call KernelExplainer predict_proba X_tr
comment results are symmetric (-,+)
set shap_values = call shap_values X_te l1_reg=0.0 nsamples=500 at 0
comment Calculate average over samples (patients)
set shap_values_mean_over_samples = mean np shap_values axis=0
r... | def calc_kernel_shap_values(model):
explainer = shap.KernelExplainer(model.best_model.predict_proba, model.X_tr)
shap_values = explainer.shap_values(model.X_te,l1_reg=0.0,nsamples=500)[0] #results are symmetric (-,+)
# Calculate average over samples (patients)
shap_values_mean_over_samples = np.mea... | Python | nomic_cornstack_python_v1 |
function load self filename set_current=true add_where=string end
begin
string Load filename, create an editor instance and return it *Warning* This is loading file, creating editor but not executing the source code analysis -- the analysis must be done by the editor plugin (in case multiple editorstack instances are h... | def load(self, filename, set_current=True, add_where='end'):
"""
Load filename, create an editor instance and return it
*Warning* This is loading file, creating editor but not executing
the source code analysis -- the analysis must be done by the editor
plugin (in case multi... | Python | jtatman_500k |
function __init__ self cmd shell=false stdout=PIPE stderr=PIPE
begin
set command = cmd
try
begin
if not shell
begin
comment Set empty double-quotes as empty list item
comment Required for commands like; ssh-keygen ... -N ""
set cmd = list comprehension if expression i == string "" or i == string '' then string else i ... | def __init__(
self,
cmd: str,
shell: bool = False,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
):
self.command = cmd
try:
if not shell:
# Set empty double-quotes as empty list item
# Required for commands like... | Python | nomic_cornstack_python_v1 |
class Primegrid
begin
function __init__ self size
begin
set size = size
set grid = list comprehension true for i in call xrange size + 1
set grid at 0 = false
set grid at 1 = false
setup self
end function
function setup self
begin
for i in call xrange 2 size
begin
if grid at i
begin
set start = i * i
if start > size
be... | class Primegrid:
def __init__(self,size):
self.size = size
self.grid = [True for i in xrange(self.size+1)]
self.grid[0] = False
self.grid[1] = False
self.setup()
def setup(self):
for i in xrange(2,self.size):
if self.grid[i]:
start = i*... | Python | zaydzuhri_stack_edu_python |
function longestPalindromeSubseq word1 word2
begin
set tuple n m = tuple length word1 length word2
set dp = list comprehension list 0 * m + 1 for _ in range n + 1
for i in range n
begin
for j in range m
begin
if word1 at i == word2 at j
begin
set dp at i + 1 at j + 1 = dp at i at j + 1
end
else
begin
set dp at i + 1 at... | def longestPalindromeSubseq(word1, word2):
n, m = len(word1), len(word2)
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(n):
for j in range(m):
if word1[i] == word2[j]:
dp[i + 1][j + 1] = dp[i][j] + 1
else:
dp[i + 1][j + 1] = max(dp[... | Python | jtatman_500k |
import threading
import time
set exitFlag = false
function print_time threadName delay counter
begin
while counter
begin
if exitFlag
begin
exit
end
sleep delay
print string %s: %s % tuple threadName call ctime time
set counter = counter - 1
end
end function
function write file content start=0 end=100
begin
with open fi... | import threading
import time
exitFlag = False
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
def write(file, content, start=0, end=100,)... | Python | zaydzuhri_stack_edu_python |
function test_get_quiz_question self
begin
set Data = dict string previous_questions list 2 6 ; string quiz_category dict string id 5 ; string type string History
set res = post string /quizzes json=Data
set data = loads data
assert equal status_code 200
assert equal data at string success true
assert true data at stri... | def test_get_quiz_question(self):
Data = {
'previous_questions': [2, 6],
'quiz_category': {
'id': 5,
'type': 'History'
}
}
res = self.client().post('/quizzes', json=Data)
data = json.loads(res.data)
self.assertEq... | Python | nomic_cornstack_python_v1 |
from tkinter import Tk , Label , Button , Text , Entry , Checkbutton , IntVar
from tkinter import N , E , W , NW , END
import os
import re
class BulkRename
begin
function __init__ self master
begin
set master = master
title master string SDL Rename Tool
set filenames_label = call Label master text=string Old paths:
gri... | from tkinter import Tk, Label, Button, Text, Entry, Checkbutton, IntVar
from tkinter import N, E, W, NW, END
import os
import re
class BulkRename:
def __init__(self, master):
self.master = master
master.title("SDL Rename Tool")
self.filenames_label = Label(master, text="Old paths:")
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Mar 2 09:11:55 2021 This model only use encoder part of transformer Inputs are C3D feature for each shot Outputs are the probability of one shot related to another shot @author: NTUT
import time
import random
import os
import csv
import math
import random
import numpy... | # -*- coding: utf-8 -*-
"""
Created on Tue Mar 2 09:11:55 2021
This model only use encoder part of transformer
Inputs are C3D feature for each shot
Outputs are the probability of one shot related to another shot
@author: NTUT
"""
import time
import random
import os
import csv
import math
import random
import numpy a... | Python | zaydzuhri_stack_edu_python |
function original_name self
begin
return call original_name name
end function | def original_name(self):
return original_name(self.name) | Python | nomic_cornstack_python_v1 |
comment ambientes de desenvolvimento web: IDE, git, PIP (virtualenv, django, bootstrap, cliente_mysql, ...), Python 3.X
comment estrutura de código Python: orientado a edentação/indentação (converter o TAB para 3 ou 4 espaços em branco)
comment instruções de controle: seleção; repetição
comment estruturas de dados: var... | #ambientes de desenvolvimento web: IDE, git, PIP (virtualenv, django, bootstrap, cliente_mysql, ...), Python 3.X
#estrutura de código Python: orientado a edentação/indentação (converter o TAB para 3 ou 4 espaços em branco)
#instruções de controle: seleção; repetição
#estruturas de dados: variáveis primitivas; listas (c... | Python | zaydzuhri_stack_edu_python |
set nome = input string Qual seu nome?
print format string Bem vindo funcionario(a): {:=^20} nome
print string Aumentos do mês, calcule seu novo sálario:
set n1 = decimal input string Digite seu salário atual:
print string Esse mês seu salário tera um aumento de 15%
set n2 = 0.15
set n3 = n2 * n1
print format string Sa... | nome = input('Qual seu nome?')
print('Bem vindo funcionario(a): {:=^20}'.format(nome))
print('Aumentos do mês, calcule seu novo sálario:')
n1 = float(input('Digite seu salário atual: '))
print('Esse mês seu salário tera um aumento de 15%')
n2 = 0.15
n3 = n2 * n1
print('Salário com aumento {} = '.format(n1+n3))
n=int(i... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python2
comment -*- coding: utf-8 -*-
string Allows to manage the users models Created on Tue Mar 14 11:22:17 2017 @author: elsa
from os.path import isfile , exists
from os import makedirs
from keras.models import model_from_json
from MovieProject.resources import RES_MODEL_PATH
function saveModel... | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Allows to manage the users models
Created on Tue Mar 14 11:22:17 2017
@author: elsa
"""
from os.path import isfile, exists
from os import makedirs
from keras.models import model_from_json
from MovieProject.resources import RES_MODEL_PATH
def saveModel(username, mod... | Python | zaydzuhri_stack_edu_python |
comment Crie um programa que faça o computador jogar JOKENPÕ com você
comment -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-#
from random import randint
from time import sleep
set lista = tuple string PEDRA string PAPEL string TESOURA
set comp = random integer 0 2
print string Escolha uma opção: -------------- [ 0... | # Crie um programa que faça o computador jogar JOKENPÕ com você
#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-#
from random import randint
from time import sleep
lista = ('PEDRA', 'PAPEL', 'TESOURA')
comp = randint(0, 2)
print('''Escolha uma opção:
--------------
[ 0 ] PEDRA
[ 1 ] PAPEL
[ 2 ] T... | Python | zaydzuhri_stack_edu_python |
function disabled self
begin
return get pulumi self string disabled
end function | def disabled(self) -> pulumi.Output[Optional[bool]]:
return pulumi.get(self, "disabled") | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment B - ペア
comment https://atcoder.jp/contests/abc034/tasks/abc034_b
set n = integer input
if n % 2 == 0
begin
print n - 1
end
else
begin
print n + 1
end
comment 0:32 - 0:33 | # -*- coding: utf-8 -*-
# B - ペア
# https://atcoder.jp/contests/abc034/tasks/abc034_b
n = int(input())
if n % 2 == 0:
print(n - 1)
else:
print(n + 1)
# 0:32 - 0:33
| Python | zaydzuhri_stack_edu_python |
import csv
import numpy as np
import time
import sys
set train = argv at 1
set test = argv at 2
set start_time = time
function File filename
begin
set file = open filename string r
set reader = reader file
set rows = list
for row in reader
begin
append rows row
end
close file
set rows = array rows dtype=string float64... | import csv;
import numpy as np;
import time;
import sys;
train = sys.argv[1]
test = sys.argv[2]
start_time = time.time()
def File(filename):
file = open(filename , 'r');
reader = csv.reader(file);
rows=[];
for row in reader:
rows.append(row);
file.close();
rows=np.array(rows, dtype = ... | Python | zaydzuhri_stack_edu_python |
import curses , curses.panel , curses.ascii
set win = call initscr
call curs_set 0
call start_color
call init_pair 1 COLOR_CYAN COLOR_WHITE
call init_pair 2 COLOR_RED COLOR_WHITE
set size = call getmaxyx
set b = string Thumb's Up Man!!! Keep Going...
set x = list comprehension b at slice 0 : j : for j in range 1 lengt... | import curses,curses.panel,curses.ascii
win=curses.initscr()
curses.curs_set(0)
curses.start_color()
curses.init_pair(1,curses.COLOR_CYAN,curses.COLOR_WHITE)
curses.init_pair(2,curses.COLOR_RED,curses.COLOR_WHITE)
size=win.getmaxyx()
b="Thumb's Up Man!!! Keep Going..."
x=[b[0:j] for j in range(1,len(b)+1)]
win.bkgd(cu... | Python | zaydzuhri_stack_edu_python |
import csv
import hashlib
import os
from datetime import datetime , timezone
from tqdm import tqdm
from django.conf import settings
from django.core.management import BaseCommand
from pyunpack import Archive
from core.models import *
class Helper
begin
set SDS_PATH = string media/sds
function hash self name provider
be... | import csv
import hashlib
import os
from datetime import datetime, timezone
from tqdm import tqdm
from django.conf import settings
from django.core.management import BaseCommand
from pyunpack import Archive
from core.models import *
class Helper:
SDS_PATH = f'media/sds'
def hash(self, name, provider):
... | Python | zaydzuhri_stack_edu_python |
while i < length x
begin
print x at i
set i = i + 1
end
print string - * 40
for el in x
begin
print el
end
for el in enumerate x
begin
print el
end
for tuple i el in enumerate x
begin
print el
end | while i < len(x):
print(x[i])
i += 1
print("-"*40)
for el in x:
print(el)
for el in enumerate(x):
print(el)
for i, el in enumerate(x):
print(el)
| Python | zaydzuhri_stack_edu_python |
function find_uniq arr
begin
sort arr
return if expression arr at 0 != arr at 1 then arr at 0 else arr at - 1
end function
comment your code here
comment n: unique integer in the array | def find_uniq(arr):
arr.sort()
return arr[0] if arr[0] != arr[1] else arr[-1]
# your code here
# n: unique integer in the array
| Python | zaydzuhri_stack_edu_python |
function plotProfileInstance self is_plot=true ylim=list - 4 4 title=none ax=none x_spacing=3
begin
set df_profile = call profileInstance
set instances = call to_list
set columns = list INTERCEPT
extend columns list
set df_plot = call DataFrame df_profile at columns
function shade mult
begin
string Shades the region fo... | def plotProfileInstance(self, is_plot=True,
ylim=[-4, 4], title=None, ax=None, x_spacing=3):
df_profile = self.profileInstance()
instances = df_profile.index.to_list()
columns = [cn.INTERCEPT]
columns.extend(self.list)
df_plot = pd.DataFrame(df_profile[columns])
#
def shade(mult):
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
string 3 steps: 1. Simplify by removing varialbes that only appear sparsely. 2. Solve the remaining equations (if any). 3. Simplify the equations.
import os
from pathlib import Path
import sys
set __projectdir__ = call Path directory name path real path path __file__ + string /../
comment ... | #!/usr/bin/env python3
"""
3 steps:
1. Simplify by removing varialbes that only appear sparsely.
2. Solve the remaining equations (if any).
3. Simplify the equations.
"""
import os
from pathlib import Path
import sys
__projectdir__ = Path(os.path.dirname(os.path.realpath(__file__)) + '/../')
# Main Functions:{{{1
def... | Python | zaydzuhri_stack_edu_python |
function apply_transformation_np source transformation
begin
set source_homog = ones tuple shape at 0 4
set source_homog at tuple slice : : slice : - 1 : = source
comment source_homog = np.hstack(
comment (source, np.ones(source.shape[0], 1))
comment )
set source_transformed = T at tuple slice : : slice : - 1 ... | def apply_transformation_np(source, transformation):
source_homog = np.ones((source.shape[0], 4))
source_homog[:, :-1] = source
# source_homog = np.hstack(
# (source, np.ones(source.shape[0], 1))
# )
source_transformed = np.matmul(transformation, source_homog.T).T[:, :-1]
return source_... | Python | nomic_cornstack_python_v1 |
string remove_every_other([1,2,3,4,5]) # [1,3,5] remove_every_other([5,1,2,4,1]) # [5,2,1] remove_every_other([1]) # [1]
function remove_every_other new_list
begin
return list generator expression x for x in new_list at slice 0 : : 2
end function
comment [1,3,5]
print call remove_every_other list 1
print call remove_e... | '''
remove_every_other([1,2,3,4,5]) # [1,3,5]
remove_every_other([5,1,2,4,1]) # [5,2,1]
remove_every_other([1]) # [1]
'''
def remove_every_other(new_list):
return list(x for x in new_list[0::2])
print(remove_every_other([1])) # [1,3,5]
print(remove_every_other([5,1,2,4,1])) | Python | zaydzuhri_stack_edu_python |
function save_data df database_filename
begin
set engine = call create_engine string sqlite:/// { database_filename }
call to_sql string messages engine index=false
end function | def save_data(df, database_filename):
engine = create_engine(f'sqlite:///{database_filename}')
df.to_sql('messages', engine, index=False) | Python | nomic_cornstack_python_v1 |
function check_valid cx cy N M maze visited
begin
if cx < 0 or cx >= N
begin
return false
end
if cy < 0 or cy >= M
begin
return false
end
if maze at cx at cy == 0
begin
return false
end
if visited at cx at cy == true
begin
return false
end
return true
end function
function BFS cx cy N M visited maze
begin
set q = list ... | def check_valid(cx, cy, N, M, maze, visited):
if cx<0 or cx>=N: return False
if cy<0 or cy>=M: return False
if maze[cx][cy]==0: return False
if visited[cx][cy]==True: return False
return True
def BFS(cx, cy, N, M, visited, maze):
q = []
q.append([cx,cy,1]) # 첫 시작을 큐에 넣음
visite... | Python | zaydzuhri_stack_edu_python |
while true
begin
set x = integer input
if x == 0
begin
break
end
set soma = 0
if x % 2 == 0
begin
for i in range x x + 9 2
begin
set soma = soma + i
end
print soma
end
else
if x % 2 == 1
begin
for j in range x + 1 x + 11 2
begin
set soma = soma + j
end
print soma
end
end | while True:
x = int(input())
if x == 0:
break
soma = 0
if x % 2 == 0:
for i in range(x, x + 9, 2):
soma += i
print(soma)
elif x % 2 == 1:
for j in range(x + 1, x + 11, 2):
soma += j
print(soma)
| Python | zaydzuhri_stack_edu_python |
import pandas as pd
import matplotlib.pyplot as plt
set dataset = read csv string Posneg.csv engine=string python nrows=100000
set X = iloc at tuple slice : : 5
set Y = iloc at tuple slice : : 7
for i in range 100000
begin
if X at i < 0
begin
set Y at i = - 1
end
else
if X at i == 0
begin
set Y at i = 0
end
else
... | import pandas as pd
import matplotlib.pyplot as plt
dataset=pd.read_csv("Posneg.csv",engine="python",nrows=100000)
X=dataset.iloc[:,5]
Y=dataset.iloc[:,7]
for i in range(100000):
if(X[i]<0):
Y[i]=-1
elif(X[i]==0):
Y[i]=0
else:
Y[i]=1
dataset['len']=Y
Z=data... | 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.