code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment !/usr/bin/env python
import sys
from Error import *
from Structures import *
from Semantic import *
from FunctionDirectory import *
from VirtualMachine import *
comment Compiler implementation
class Compiler
begin
set _INT = string int
set _FLOAT = string float
comment Initialize Compiler
function __init__ self... | #!/usr/bin/env python
import sys
from Error import *
from Structures import *
from Semantic import *
from FunctionDirectory import *
from VirtualMachine import *
# Compiler implementation
class Compiler:
_INT = 'int'
_FLOAT = 'float'
# Initialize Compiler
def __init__(self):
# Errors
... | Python | zaydzuhri_stack_edu_python |
function __str__ self
begin
set n_params = sum list comprehension numel p for p in parameters self if requires_grad
set separate_line_str = string - * 50
return string { separate_line_str } { call __str__ } { separate_line_str } Trainable parameters: { n_params } { separate_line_str }
end function | def __str__(self) -> str:
n_params = sum([p.numel() for p in self.parameters() if p.requires_grad])
separate_line_str = "-" * 50
return (
f"{separate_line_str}\n{super().__str__()}\n{separate_line_str}\n"
f"Trainable parameters: {n_params}\n{separate_line_str}"
) | Python | nomic_cornstack_python_v1 |
class Queue
begin
function __init__ self
begin
set items = list
end function
function __repr__ self
begin
return call repr items
end function
function enqueue self v
begin
append items v
end function
function dequeue self
begin
return pop items 0
end function
function isEmpty self
begin
print length items == 0
end fun... | class Queue:
def __init__(self):
self.items = []
def __repr__(self):
return repr(self.items)
def enqueue(self,v):
self.items.append(v)
def dequeue(self):
return self.items.pop(0)
def isEmpty(self):
print (len(self.items)==0)
def size(s... | Python | zaydzuhri_stack_edu_python |
function calculate_vika_income
begin
comment Known value of Saheed's income
set saheed_income = 216
comment Relationship of Kayla's income to Vika's
comment Saheed's income is four times Kayla's income
comment Thus, we set up the equation
set kayla_income = saheed_income / 4
comment From the relationship, Kayla made $3... | def calculate_vika_income():
# Known value of Saheed's income
saheed_income = 216
# Relationship of Kayla's income to Vika's
# Saheed's income is four times Kayla's income
# Thus, we set up the equation
kayla_income = (saheed_income / 4)
# From the relationship, Kayla made $30 less... | Python | dbands_pythonMath |
import dash
import datetime
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input , Output
from keys import mapbox_token
comment Inicializando app e definindo stylesheet
set external_st... | import dash
import datetime
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from keys import mapbox_token
# Inicializando app e definindo stylesheet
external_stylesheets ... | Python | zaydzuhri_stack_edu_python |
function BearingSubtract btype
begin
import numpy as np
from math import pi
from washer import washer
comment Where btype is the integer which denotes the type of bearing
string 1 == Type A 2 == Type B 3 == Type C ... etc.
comment First, bearing must be broken up into a list of cylinders from the
comment ... bearing de... | def BearingSubtract(btype):
import numpy as np
from math import pi
from washer import washer
# Where btype is the integer which denotes the type of bearing
'''
1 == Type A
2 == Type B
3 == Type C
... etc.
'''
# First, bearing must be broken up into a list of c... | Python | zaydzuhri_stack_edu_python |
set number = integer input string Введите число:
print number - 1 string < number string < number + 1 | number = int(input("Введите число: "))
print(number-1,"<", number,"<", number+1)
| Python | zaydzuhri_stack_edu_python |
function test_substitutions_in_word self
begin
set m = call MultiReplace dict string cat string kedi ; string purple string mor
assert equal sub string Thecatispurple string Thekediismor
end function | def test_substitutions_in_word(self):
m = strutils.MultiReplace({r'cat': 'kedi', r'purple': 'mor', })
self.assertEqual(m.sub('Thecatispurple'), 'Thekediismor') | Python | nomic_cornstack_python_v1 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from keras.layers import Conv1D , Input , Add , Activation , Dropout
from keras.models import Sequential , Model
from keras.regularizers import l2
from keras.initializers import TruncatedNormal
from keras.layers.advanced_acti... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from keras.layers import Conv1D, Input, Add, Activation, Dropout
from keras.models import Sequential, Model
from keras.regularizers import l2
from keras.initializers import TruncatedNormal
from keras.layers.advanced_activat... | Python | zaydzuhri_stack_edu_python |
function save_config self
begin
with open config_path string w as handle
begin
dump config handle
end
end function | def save_config(self):
with open(self.config_path, "w") as handle:
json.dump(self.config, handle) | Python | nomic_cornstack_python_v1 |
function test_get_partial_charges self force_field
begin
set ethanol : Molecule = call create_ethanol
set ethanol_partial_charges = call from_openmm call get_partial_charges_from_create_openmm_system ethanol force_field
set partial_charges = call get_partial_charges ethanol
assert all
assert shape == tuple n_atoms
end ... | def test_get_partial_charges(self, force_field):
ethanol: Molecule = create_ethanol()
ethanol_partial_charges = from_openmm(
self.get_partial_charges_from_create_openmm_system(ethanol, force_field)
)
partial_charges = force_field.get_partial_charges(ethanol)
assert... | Python | nomic_cornstack_python_v1 |
function get_details self
begin
set pilot_details = list
for pcs in pilot_job_services
begin
for pc in call list_pilots
begin
append pilot_details call get_details
end
end
return pilot_details
end function | def get_details(self):
pilot_details=[]
for pcs in self.pilot_job_services:
for pc in pcs.list_pilots():
pilot_details.append(pc.get_details())
return pilot_details | Python | nomic_cornstack_python_v1 |
import numpy as np
from random import randint
class Sprite
begin
function __init__ self
begin
set matrix = none
set x = 0
set y = 0
end function
function set_sprite self
begin
set matrix = call getTetrisSprites
end function
function getTetrisSprites self
begin
string Defines a dictionary with every sprite in tetris Bas... | import numpy as np
from random import randint
class Sprite():
def __init__(self):
self.matrix = None
self.x = 0
self.y = 0
def set_sprite(self):
self.matrix = self.getTetrisSprites()
def getTetrisSprites(self):
"""Defines a dictionary with every sprite in tetris
... | Python | zaydzuhri_stack_edu_python |
from timeit import Timer
comment Примеры функций
function print_ok
begin
string Пример функции без параметров
print string I'm okay
end function
function echo m
begin
string Пример функции с параметром
print m
end function
function summa x y
begin
string Пример функции с параметрами, возвращающей сумму двух переменных
... | from timeit import Timer
#Примеры функций
def print_ok():
""" Пример функции без параметров """
print("I'm okay ")
def echo(m):
""" Пример функции с параметром """
print(m)
def summa(x, y):
""" Пример функции с параметрами,
возвращающей сумму двух переменных """
return x... | Python | zaydzuhri_stack_edu_python |
from loginAndPassword import login
import time
from selenium import webdriver
set driver = call Chrome string /usr/local/bin/chromedriver
function login_and_show_channel channel
begin
get driver string https://msan-usf.slack.com
set userfield = call find_element_by_id string email
set passwordfield = call find_element_... | from loginAndPassword import login
import time
from selenium import webdriver
driver = webdriver.Chrome('/usr/local/bin/chromedriver')
def login_and_show_channel(channel):
driver.get('https://msan-usf.slack.com')
userfield = driver.find_element_by_id('email')
passwordfield = driver.find_element_by_id('pas... | Python | zaydzuhri_stack_edu_python |
comment Takes in a pheno_pops.csv file and returns the temporal host and parasite heterogeneity
import sys
import math
import numpy as np
comment Main function
function get_dominant filename
begin
set times = list
set host_doms = list
set para_doms = list
with open filename as ifile
begin
set header = next ifile
set... | # Takes in a pheno_pops.csv file and returns the temporal host and parasite heterogeneity
import sys
import math
import numpy as np
# Main function
def get_dominant(filename):
times = []
host_doms = []
para_doms = []
with open(filename) as ifile:
header = next(ifile)
num_pheno = (len(he... | Python | zaydzuhri_stack_edu_python |
function _get_sentence_features message
begin
set tuple _ dense_sentence_features = call get_dense_features TEXT
if dense_sentence_features is not none
begin
call raise_warning string Dense features are being computed but not used.
end
set tuple _ sentence_features = call get_sparse_features TEXT
if sentence_features i... | def _get_sentence_features(message: Message) -> scipy.sparse.spmatrix:
_, dense_sentence_features = message.get_dense_features(TEXT)
if dense_sentence_features is not None:
rasa.shared.utils.io.raise_warning(
"Dense features are being computed but not used."
)
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python2
comment -*- coding: utf-8 -*-
string Created on Wed Nov 6 11:41:27 2019 @author: felipe https://raw.githubusercontent.com/advinstai/python-datascience/master/csv/College.csv descubra as colunas qualitativas e quantitativas Descreva os intervalos das colunas quantitativas calcule a media, m... | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 6 11:41:27 2019
@author: felipe
https://raw.githubusercontent.com/advinstai/python-datascience/master/csv/College.csv
descubra as colunas qualitativas e quantitativas
Descreva os intervalos das colunas quantitativas
calcule a media, mediana e ... | Python | zaydzuhri_stack_edu_python |
string Lecture 12 Trees
comment closure property of data types
comment method (combining data values) has 'closure property' --> the result can be combined by the same method
comment why important --> create hierarchical structures (made up of parts; parts are made up of parts)
comment trees
comment tree (1) leaf (2) a... | """
Lecture 12
Trees
"""
# closure property of data types
## method (combining data values) has 'closure property' --> the result can be combined by the same method
## why important --> create hierarchical structures (made up of parts; parts are made up of parts)
# trees
# tree (1) leaf (2) a sequence of trees
# tre... | Python | zaydzuhri_stack_edu_python |
function sieve_flavius min_n max_n
begin
set pointer = 1
set lst = list range 1 max_n + 1 2
while pointer < length lst
begin
set new_lst = list
set num = lst at pointer
for i in range length lst
begin
if i + 1 % num != 0
begin
append new_lst lst at i
end
end
set lst = new_lst
set pointer = pointer + 1
end
set ind = 0
... | def sieve_flavius(min_n, max_n) -> set:
pointer = 1
lst = list(range(1, max_n + 1, 2))
while pointer < len(lst):
new_lst = []
num = lst[pointer]
for i in range(len(lst)):
if (i + 1) % num != 0:
new_lst.append(lst[i])
lst = new_lst
pointer +... | Python | nomic_cornstack_python_v1 |
for i in List
begin
if i at slice : : - 1 == i
begin
print i
end
else
begin
print string Nothing!
end
end | for i in List:
if i[::-1] == i:
print(i)
else:
print("Nothing!")
| Python | zaydzuhri_stack_edu_python |
async function test_routine self
begin
print string Running test routine...
await sleep 1.0
print string RPC-style with empty payloads:
await call request
await call request
await call request
await call request
await call request
await call request
print string RPC with complete wait for finite-periods blink:
await ca... | async def test_routine(self):
print('Running test routine...')
await asyncio.sleep(1.0)
print('RPC-style with empty payloads:')
await self.protocol.request()
await self.protocol.blink.request()
await self.protocol.blink.high_interval.request()
await self.protocol... | Python | nomic_cornstack_python_v1 |
comment coding=utf-8
string 任意一个M*N的矩阵A(M行*N列,M>N),可以被写成三个矩阵的乘机: 1.U:(M行M列的列正交矩阵) 2.S:(M*N的对角线矩阵,矩阵元素非负) 3.V:(N*N的正交矩阵的倒置) 即A=U*S*V‘(注意矩阵V需要倒置) https://qiita.com/kyoro1/items/4df11e933e737703d549
import numpy as np
comment A=UΣVT
set dataMat = array list list 1 1 list 1 1 list 0 0
set tuple U s V = call svd dataMat ful... | # coding=utf-8
"""
任意一个M*N的矩阵A(M行*N列,M>N),可以被写成三个矩阵的乘机:
1.U:(M行M列的列正交矩阵)
2.S:(M*N的对角线矩阵,矩阵元素非负)
3.V:(N*N的正交矩阵的倒置)
即A=U*S*V‘(注意矩阵V需要倒置)
https://qiita.com/kyoro1/items/4df11e933e737703d549
"""
import numpy as np
#A=UΣVT
dataMat=np.array([
[1,1],
[1,1],
[0,0]
])
U, s, V = np.linalg.svd(dataMat, full_m... | Python | zaydzuhri_stack_edu_python |
from bs4 import BeautifulSoup
import requests
function main
begin
set data = list
set headers = dict string User-agent string Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9) Gecko/2008052906 Firefox/3.0
for pages in range 125
begin
set url = string https://auto.ria.com/search/?body.id[0]=3&body.id[3]=4&body.id[5]... | from bs4 import BeautifulSoup
import requests
def main():
data = []
headers = {'User-agent': 'Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9) Gecko/2008052906 Firefox/3.0'}
for pages in range(125):
url = "https://auto.ria.com/search/?body.id[0]=3&body.id[3]=4&body.id[5]=6&year[0].gte=1990... | Python | zaydzuhri_stack_edu_python |
function resnet_multiimage_input num_layers pretrained=false num_input_images=1
begin
assert num_layers in list 18 50 msg string Can only run with 18 or 50 layer resnet
set blocks = dict 18 list 2 2 2 2 ; 50 list 3 4 6 3 at num_layers
set block_type = dict 18 BasicBlock ; 50 Bottleneck at num_layers
set model = call Re... | def resnet_multiimage_input(num_layers, pretrained=False, num_input_images=1):
assert num_layers in [18, 50], "Can only run with 18 or 50 layer resnet"
blocks = {18: [2, 2, 2, 2], 50: [3, 4, 6, 3]}[num_layers]
block_type = {18: models.resnet.BasicBlock, 50: models.resnet.Bottleneck}[num_layers]
model = ... | Python | nomic_cornstack_python_v1 |
comment It works, but we need to make it run faster
set counter = 0
set c_loop = 0
set compare_number = 0
set compare_number_l = dict
set compare_number_right = dict
set number_of_entries = integer input
set base_number = integer input
for i in range 0 number_of_entries - 1
begin
set c_loop = 0
print counter
set comp... | #It works, but we need to make it run faster
counter = 0
c_loop = 0
compare_number = 0
compare_number_l = {}
compare_number_right = {}
number_of_entries = int(input())
base_number = int(input())
for i in range(0,number_of_entries-1):
c_loop = 0
print(counter)
compare_number = base_number
number = int(i... | Python | zaydzuhri_stack_edu_python |
import gspeech
import time
import RPi.GPIO as GPIO
call setmode BCM
setup GPIO 21 OUT
function main
begin
set gsp = call Gspeech
print string start program
while true
begin
comment 음성 인식 될때까지 대기 한다.
set stt = call getText
if stt is none
begin
break
end
print stt
sleep 0.01
if string 불 켜 in stt
begin
call output 21 true... | import gspeech
import time
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(21, GPIO.OUT)
def main():
gsp = gspeech.Gspeech()
print("start program")
while True:
# 음성 인식 될때까지 대기 한다.
stt = gsp.getText()
if stt is None:
break
print(stt)
time.sleep(0.01)
if('불 켜' in stt):
GPIO.output(21, Tru... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Wed Oct 17 09:30:38 2018 @author: Franc
comment In[]
import pandas as pd
import numpy as np
comment DRAGONS
import xgboost as xgb
import lightgbm as lgb
import catboost as cat
comment plots
import matplotlib.pyplot as plt
comment pandas / plt options
set max_columns = 999... | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 17 09:30:38 2018
@author: Franc
"""
# In[]
import pandas as pd
import numpy as np
# DRAGONS
import xgboost as xgb
import lightgbm as lgb
import catboost as cat
# plots
import matplotlib.pyplot as plt
# pandas / plt options
pd.options.display.max_columns = 999
plt.rcParams... | Python | zaydzuhri_stack_edu_python |
set daily_screen_time = integer input string Enter your daily screen time in minutes:
set weekly_screen_time = daily_screen_time * 7
print string Your weekly screen time is { weekly_screen_time } minutes. | daily_screen_time = int(input('Enter your daily screen time in minutes: '))
weekly_screen_time = daily_screen_time * 7
print(f'Your weekly screen time is {weekly_screen_time} minutes.')
| Python | flytech_python_25k |
function harmonize_ocean ocean elevation ocean_level
begin
set shallow_sea = ocean_level * 0.85
set midpoint = shallow_sea / 2.0
set ocean_points = call logical_and elevation < shallow_sea ocean
set shallow_ocean = call logical_and elevation < midpoint ocean_points
set elevation at shallow_ocean = midpoint - midpoint -... | def harmonize_ocean(ocean, elevation, ocean_level):
shallow_sea = ocean_level * 0.85
midpoint = shallow_sea / 2.0
ocean_points = numpy.logical_and(elevation < shallow_sea, ocean)
shallow_ocean = numpy.logical_and(elevation < midpoint, ocean_points)
elevation[shallow_ocean] = midpoint - ((midpoint... | Python | nomic_cornstack_python_v1 |
function add_trip_detail self detail_name detail_value
begin
assert detail_name in list string start string end msg string Invalid detail name passed
comment assert type(detail_value)==datetime, "Invalid detail value passed"
if detail_name == string start
begin
set trip_start = detail_value
end
else
if detail_name == s... | def add_trip_detail(self, detail_name, detail_value):
assert detail_name in ['start','end'], "Invalid detail name passed"
# assert type(detail_value)==datetime, "Invalid detail value passed"
if detail_name == 'start':
self.trip_start = detail_value
elif detail_name == 'end':
self.trip_end = detial_value | Python | nomic_cornstack_python_v1 |
function read self cnxn_str table_names=none
begin
if table_names is none
begin
set table_names = list comprehension conversion_dict at attribute at string odm_name for attribute in keys conversion_dict
end
set attributes = list
for table_name in table_names
begin
for tuple k v in items conversion_dict
begin
if v at s... | def read(
self,
cnxn_str: str,
table_names: list[str] = None
) -> None:
if table_names is None:
table_names = [
self.conversion_dict[attribute]["odm_name"]
for attribute in self.conversion_dict.keys()]
attributes = []
... | Python | nomic_cornstack_python_v1 |
function test_past_and_future_publishing_end_date self
begin
call create_product name=string Ruler description=string School ruler 30cm days=- 3 company=company
call create_product name=string School Bag description=string bag days=5 company=company
set response = get client reverse string list
call assertQuerysetEqual... | def test_past_and_future_publishing_end_date(self):
create_product(name="Ruler", description='School ruler 30cm', days=-3,
company=self.company)
create_product(name="School Bag", description='bag', days=5,
company=self.company)
response = self.client... | Python | nomic_cornstack_python_v1 |
function get_ave self recalc=false
begin
if ave is not none and not recalc
begin
return ave
end
set ave = mean np call ravel
return ave
end function | def get_ave(self, recalc=False):
if self.ave is not None and not recalc:
return self.ave
self.ave = np.mean(self.img.ravel())
return self.ave | Python | nomic_cornstack_python_v1 |
function dir_threshold img sobel_kernel=3 thresh=tuple 0 pi / 2
begin
comment NOTE : thresh = (0.7, 1.3) will result in this function roughly identifying the
comment lane lines but with lots of noise
comment 1) Convert to grayscale
set gray = call cvtColor img COLOR_RGB2GRAY
comment 2) Calculate the gradient in x and y... | def dir_threshold(img, sobel_kernel=3, thresh=(0, np.pi / 2)):
# NOTE : thresh = (0.7, 1.3) will result in this function roughly identifying the
# lane lines but with lots of noise
# 1) Convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
# 2) Calculate the gradien... | Python | nomic_cornstack_python_v1 |
comment **********Tome Rater Project****************
comment Needs this for the invalid email check
import re
class InvalidUserEmail extends Exception
begin
pass
end class
comment ***************************User class*************************************
class User extends object
begin
comment constructor
function __in... | #**********Tome Rater Project****************
#Needs this for the invalid email check
import re
class InvalidUserEmail(Exception):
pass
#***************************User class*************************************
class User(object):
#constructor
def __init__(self, name, email):
self.name = name
self.email... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import os
import math
import pandas as pd
from igraph import Graph
comment diretorio para resultados e dados
set rd = directory name path directory name path get current directory
set rd = rd + string /Resultados e Dados/Amazonas
string leitura dos arquivos
comment fire_nrt_M6_94041.csv co... | # -*- coding: utf-8 -*-
import os
import math
import pandas as pd
from igraph import Graph
# diretorio para resultados e dados
rd = os.path.dirname(os.path.dirname(os.getcwd()))
rd = rd + '/Resultados e Dados/Amazonas'
''' leitura dos arquivos '''
# fire_nrt_M6_94041.csv contem dados de 2019-10-01 ate 20... | Python | zaydzuhri_stack_edu_python |
function myers_diff_length_optimize_y_variant old_sequence new_sequence
begin
set N = length old_sequence
set M = length new_sequence
set MAX = N + M
set V = list none * 2 * MAX + 2
set V at - 1 = 0
for D in range 0 MAX + 1
begin
for k in range - D D + 1 2
begin
if k == D or k != - D and V at k - 1 > V at k + 1
begin
s... | def myers_diff_length_optimize_y_variant(old_sequence, new_sequence):
N = len(old_sequence)
M = len(new_sequence)
MAX = N + M
V = [None] * (2 * MAX + 2)
V[-1] = 0
for D in range(0, MAX + 1):
for k in range(-D, D + 1, 2):
if k == D or k != -D and V[k - 1] > V[k + 1]:
... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import json
class MenteesReport
begin
function __init__ self
begin
comment - load mentees from specified csv file
set data = read csv string mentees.csv
comment - get the number of mentees
set num_mentees = length index
comment - get set of all languages mentees know
set languages = set unique
comme... | import pandas as pd
import json
class MenteesReport:
def __init__(self):
# - load mentees from specified csv file
self.data = pd.read_csv('mentees.csv')
# - get the number of mentees
self.num_mentees = len(self.data.index)
# - get set of all languages mentees kno... | Python | zaydzuhri_stack_edu_python |
import json
import geog
import pygeoj
import shapely
from shapely.geometry import Polygon , LineString
import numpy as np
class road
begin
function __init__ self properties=none geometry=none
begin
set properties = properties
set geometry = geometry
end function
function isInside self bounding_box
begin
set poly = call... | import json
import geog
import pygeoj
import shapely
from shapely.geometry import Polygon, LineString
import numpy as np
class road:
def __init__(self,properties= None,geometry=None):
self.properties = properties
self.geometry = geometry
def isInside(self,bounding_box):
poly = Polygon... | Python | zaydzuhri_stack_edu_python |
import unittest
class ListTest extends TestCase
begin
function testCreate self
begin
set a = list string a string beh 1 false none string z
assert equal 6 length a
assert equal string a a at 0
comment casting False
assert equal 0 a at 3
assert equal string z a at - 1
comment slice
assert equal list string beh 1 a at sl... | import unittest
class ListTest(unittest.TestCase):
def testCreate(self):
a = ['a', 'beh', 1, False, None, 'z']
self.assertEqual(6, len(a))
self.assertEqual('a', a[0])
self.assertEqual(0, a[3]) # casting False
self.assertEqual('z', a[-1])
self.assertEqual(['beh'... | Python | zaydzuhri_stack_edu_python |
while cnt < input_num
begin
set cnt = cnt + index
set index = index + 1
end
set index = index - 1
set cnt = cnt - input_num
if index % 2 == 0
begin
set son = index - cnt
set mom = 1 + cnt
end
else
begin
set son = 1 + cnt
set mom = index - cnt
end
print string son + string / + string mom | while cnt < input_num:
cnt += index
index += 1
index -= 1
cnt -= input_num
if index % 2 == 0:
son = index - cnt
mom = 1 + cnt
else:
son = 1 + cnt
mom = index - cnt
print(str(son)+"/"+str(mom))
| Python | zaydzuhri_stack_edu_python |
function to_str self
begin
return call pformat call to_dict
end function | def to_str(self):
return pprint.pformat(self.to_dict()) | Python | nomic_cornstack_python_v1 |
from tkinter import messagebox
from tkinter import filedialog
import os
from Make_Model.Functions import *
import threading
set THREAD_LOCK = lock
import datetime
from timeit import default_timer as timer
from tkinter import *
import joblib
class TrainModel_Application extends Frame
begin
function __init__ self master=... | from tkinter import messagebox
from tkinter import filedialog
import os
from Make_Model.Functions import *
import threading
THREAD_LOCK = threading.Lock()
import datetime
from timeit import default_timer as timer
from tkinter import *
import joblib
class TrainModel_Application(Frame):
def __init__(self, master=Non... | Python | zaydzuhri_stack_edu_python |
string A Python 3 script for requesting json-weather-data from wwo website according to the yaml-file specification. The script will then write the server response into a text-/json-file
import yaml
import urllib.request
import os.path
comment read the yaml-configuration file and look for the specifications
with open s... | '''
A Python 3 script for requesting json-weather-data from wwo website according to the yaml-file specification.
The script will then write the server response into a text-/json-file
'''
import yaml
import urllib.request
import os.path
# read the yaml-configuration file and look for the specifications
with open("con... | Python | zaydzuhri_stack_edu_python |
function number_to_words num
begin
comment Define arrays to store words corresponding to each digit
set units = list string string One string Two string Three string Four string Five string Six string Seven string Eight string Nine
set teens = list string string Eleven string Twelve string Thirteen string Fourteen st... | def number_to_words(num):
# Define arrays to store words corresponding to each digit
units = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine']
teens = ['', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen']
tens = ['', 'Ten',... | Python | jtatman_500k |
string 线程函数传参
from threading import Thread
import time
comment 含有参数的线程函数
function fun01 sec_ name
begin
sleep sec_
print string '%s' 执行完毕 % name
end function
comment 创建多个线程
set jobs = list
for i in range 5
begin
set t = thread target=fun01 args=tuple 2 kwargs=dict string name string 小木
append jobs t
start t
end
commen... | """
线程函数传参
"""
from threading import Thread
import time
# 含有参数的线程函数
def fun01(sec_, name):
time.sleep(sec_)
print("'%s' 执行完毕" % name)
# 创建多个线程
jobs = []
for i in range(5):
t = Thread(target=fun01, args=(2,), kwargs={'name': '小木'})
jobs.append(t)
t.start()
# 循环回收线程
for i in jobs:
i.join()
| Python | zaydzuhri_stack_edu_python |
comment to know how many keys are there, simply use len method
print length student
comment to know all the keys
print keys student
comment to know all the values
print values student
comment to know keys and values together
print items student
comment looping through keys
for a in student
begin
print a
end
for a in ke... | #to know how many keys are there, simply use len method
print(len(student))
#to know all the keys
print(student.keys())
#to know all the values
print(student.values())
#to know keys and values together
print(student.items())
#looping through keys
for a in student:
print(a)
for a in student.keys():
... | Python | zaydzuhri_stack_edu_python |
function merge_equivalent_regions temporary_list equivalences
begin
set count = 0
set regions = temporary_list
for i in temporary_list
begin
for tuple set_id _ in items equivalences
begin
if i in equivalences at set_id and i > min equivalences at set_id
begin
set regions at count = min equivalences at set_id
end
else
b... | def merge_equivalent_regions(temporary_list, equivalences):
count = 0
regions = temporary_list
for i in temporary_list:
for set_id, _ in equivalences.items():
if i in equivalences[set_id] and i > min(equivalences[set_id]):
regions[count] = min(equivalences[set_id])
... | Python | nomic_cornstack_python_v1 |
string Adapt the binary search algorithm so that instead of outputting whether a specific value was found, it outputs whether a value within an interval (specified by you) was found. Write the pseudocode and code and give the time complexity of the algorithm using the Big O notation
comment Search Algorithm:
comment ... | """Adapt the binary search algorithm so that instead of outputting whether a specific value was found, it
outputs whether a value within an interval (specified by you) was found. Write the pseudocode and
code and give the time complexity of the algorithm using the Big O notation"""
#Search Algorithm:
# 1 Find midd... | Python | zaydzuhri_stack_edu_python |
function shorten_to_date long_date
begin
set sort1 = split long_date string ,
return sort1 at 0
end function
print call shorten_to_date string Monday February 2, 8pm | def shorten_to_date(long_date):
sort1=long_date.split(',')
return sort1[0]
print(shorten_to_date("Monday February 2, 8pm"))
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment encoding=utf-8
from tempfile import TemporaryFile , NamedTemporaryFile , TemporaryDirectory
with temporary file string w+t as f
begin
write f string heyheyhey
seek f 0
set data = read f
print data
end
with named temporary file string w+t as f
begin
write f string I'm NamedTemporary... | #!/usr/bin/env python3
# encoding=utf-8
from tempfile import TemporaryFile, NamedTemporaryFile, TemporaryDirectory
with TemporaryFile('w+t') as f:
f.write('heyheyhey')
f.seek(0)
data = f.read()
print(data)
with NamedTemporaryFile('w+t') as f:
f.write('I\'m NamedTemporaryFile')
f.seek(0)
da... | Python | zaydzuhri_stack_edu_python |
function previous_event self previous_event
begin
set _previous_event = previous_event
end function | def previous_event(self, previous_event):
self._previous_event = previous_event | Python | nomic_cornstack_python_v1 |
function DetectedFault self
begin
global g_faultDetected
return g_faultDetected
end function | def DetectedFault(self):
global g_faultDetected
return g_faultDetected | Python | nomic_cornstack_python_v1 |
function name self
begin
return get pulumi self string name
end function | def name(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "name") | Python | nomic_cornstack_python_v1 |
class Node
begin
function __init__ self data
begin
set data = data
set nextNode = none
end function
end class
class LinkedList
begin
function __init__ self
begin
set head = none
set size = 0
end function
function InsertStart self data
begin
set size = size + 1
set newNode = call Node data
if not head
begin
set head = n... | class Node:
def __init__(self, data):
self.data = data
self.nextNode = None
class LinkedList:
def __init__(self):
self.head = None
self.size = 0
def InsertStart(self, data):
self.size = self.size + 1
newNode = Node(data)
if not self.head:
... | Python | zaydzuhri_stack_edu_python |
function create_dict_prod self
begin
comment create dico
set dict_prod = dict
print string -- Interroge l'API ! --
comment ["Poissons"], list_selected
for cat in TUP_CATEGORIES
begin
set list_prod = call _get_list_for_cat cat
comment for each cat I fill the dictionnary dict_prod with a list
set dict_prod at cat = list... | def create_dict_prod(self):
dict_prod = {} #create dico
print(" -- Interroge l'API ! -- ")
for cat in self.TUP_CATEGORIES: #["Poissons"], list_selected
list_prod = self._get_list_for_cat(cat)
#for each cat I fill the dictionnary dict_prod with a list
dict_p... | Python | nomic_cornstack_python_v1 |
import speech_recognition as sr
set r = call Recognizer
with call Microphone as source
begin
print string Say something...
set audio = call listen source
end
try
begin
print string TEXT: + call recognize_google audio language=string ta-IN
end
except UnknownValueError
begin
print string Couldn't understand
end
except Re... | import speech_recognition as sr
r = sr.Recognizer()
with sr.Microphone() as source:
print("Say something... ")
audio = r.listen(source)
try:
print("TEXT: "+r.recognize_google(audio, language='ta-IN'))
except sr.UnknownValueError:
print("Couldn't understand")
except sr.RequestError as e:
pri... | Python | zaydzuhri_stack_edu_python |
import sys
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
import spr
string Set up matplotlib to create a plot with an empty square
function setupPlot
begin
set fig = figure num=none dpi=120 facecolor=string w edgecolor=string k
set ax = call subplots
call set_axis... | import sys
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
import spr
'''
Set up matplotlib to create a plot with an empty square
'''
def setupPlot():
fig = plt.figure(num=None, dpi=120, facecolor='w', edgecolor='k')
ax = fig.subplots()
ax... | Python | zaydzuhri_stack_edu_python |
function weighting word words date distance=0
begin
set CUTOFF_D = 50
set BASE_D = 0.5
function FUNC_D d
begin
return if expression d <= CUTOFF_D then - 0.09 * d + 5 else BASE_D
end function
set CUTOFF_DS = 10
set BASE_DS = 0.5
function FUNC_DS d
begin
return if expression d <= CUTOFF_DS then - 0.45 * d + 5 else BASE_D... | def weighting(word, words, date, distance=0):
CUTOFF_D = 50
BASE_D = .5
def FUNC_D(d): return -.09 * d + 5 if d <= CUTOFF_D else BASE_D
CUTOFF_DS = 10
BASE_DS = .5
def FUNC_DS(d): return -.45 * d + 5 if d <= CUTOFF_DS else BASE_DS
year = int(date[:4])
current_year = gmtime()[0]
tim... | Python | nomic_cornstack_python_v1 |
import pickle
import csv
import matplotlib.pyplot as plt
import base64
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.patches as mpatches
call use string seaborn-whitegrid
from six.moves import cPickle as pickle
from sklearn import preprocessing , svm
from sklearn.preprocessing import Po... | import pickle
import csv
import matplotlib.pyplot as plt
import base64
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.patches as mpatches
plt.style.use('seaborn-whitegrid')
from six.moves import cPickle as pickle
from sklearn import preprocessing, svm
from sklearn.preproces... | Python | zaydzuhri_stack_edu_python |
function set_base_hash_array
begin
comment Create base array for hashing
set base_hash_array = list comprehension character x for x in range 128
comment Replace the null value with the global variable null
comment This will reduce errors from arising.
set base_hash_array at 0 = NULL_STRING
return base_hash_array
end fu... | def set_base_hash_array():
# Create base array for hashing
base_hash_array = [chr(x) for x in range(128)]
# Replace the null value with the global variable null
# This will reduce errors from arising.
base_hash_array[0] = NULL_STRING
return base_hash_array | Python | nomic_cornstack_python_v1 |
function get_all_acts_dialogues doc
begin
set scene_list = call getElementsByTagName string div + call getElementsByTagName string div1 + call getElementsByTagName string div2
set scene_list = list comprehension s for s in scene_list if call getAttribute string type in list string act string acte
return list comprehens... | def get_all_acts_dialogues(doc):
scene_list = doc.getElementsByTagName('div') + doc.getElementsByTagName('div1') + doc.getElementsByTagName('div2')
scene_list = [s for s in scene_list if s.getAttribute("type") in ["act", "acte"]]
return [get_stances_succession(s) for s in scene_list] | Python | nomic_cornstack_python_v1 |
comment Question 3
import check
comment A keycode is a list of length 2, [d, n] where
comment d is an int from 0 - 9 representing a digit on a phone keypad and
comment n is an int[>0], representing the number of times the key has
comment been pressed. The value of n will be less than or equal to
comment the number of s... | ## Question 3
import check
## A keycode is a list of length 2, [d, n] where
## d is an int from 0 - 9 representing a digit on a phone keypad and
## n is an int[>0], representing the number of times the key has
## been pressed. The value of n will be less than or equal to
## the number of symbo... | Python | zaydzuhri_stack_edu_python |
function search q start=0 wait=10 asynchronous=false cached=false
begin
string Returns a Google web query formatted as a GoogleSearch list object.
set service = GOOGLE_SEARCH
return call GoogleSearch q start service string wait asynchronous cached
end function | def search(q, start=0, wait=10, asynchronous=False, cached=False):
""" Returns a Google web query formatted as a GoogleSearch list object.
"""
service = GOOGLE_SEARCH
return GoogleSearch(q, start, service, "", wait, asynchronous, cached) | Python | jtatman_500k |
comment !/usr/bin/env python
from helpers import stopwatch
import numpy as np
import theano
import theano.tensor as T
from theano.tensor.nlinalg import matrix_inverse
comment Perform an element-wise operation on a vector
comment read the float specification from the configuration
set FLOATX = floatX
comment Set the ran... | #!/usr/bin/env python
from helpers import stopwatch
import numpy as np
import theano
import theano.tensor as T
from theano.tensor.nlinalg import matrix_inverse
## Perform an element-wise operation on a vector
# read the float specification from the configuration
FLOATX = theano.config.floatX
# Set the random number ... | Python | zaydzuhri_stack_edu_python |
function check_hours
begin
while true
begin
set business_object = call query_business_name
if business_object == string back
begin
return
end
else
if business_object is none
begin
continue
end
print string { business_object at string name } hours are: { business_object at string hours }
end
end function | def check_hours():
while True:
business_object = query_business_name()
if business_object == "back":
return
elif business_object is None:
continue
print(f"{business_object['name']} hours are: "
f"{business_object['hours']}") | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding: utf-8
comment In[1]:
comment !/bin/python3
import math
import os
import random
import re
import sys
if __name__ == string __main__
begin
set n = integer input
for i in range 10
begin
set tot = n * i + 1
print n string x i + 1 string = tot
end
end
comment In[ ]: | #!/usr/bin/env python
# coding: utf-8
# In[1]:
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input())
for i in range(10):
tot = n*(i+1)
print(n ,"x" , i+1 , "=" , tot)
# In[ ]:
| Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string This is the script used to train an activity recognition classifier on accelerometer data.
import os
import sys
import numpy as np
import sklearn
from sklearn.tree import export_graphviz
from features import extract_features
from util import slidingWindow , reorient , reset_vars
imp... | # -*- coding: utf-8 -*-
"""
This is the script used to train an activity recognition
classifier on accelerometer data.
"""
import os
import sys
import numpy as np
import sklearn
from sklearn.tree import export_graphviz
from features import extract_features
from util import slidingWindow, reorient, reset_vars
import ... | Python | zaydzuhri_stack_edu_python |
function test_projection_v3_x self
begin
from pedemath.vec3 import projection_v3
set vec_a = call Vec3 3 4 5
set vec_b = call Vec3 1 0 0
set result = call projection_v3 vec_a vec_b
assert equal 3 result
end function | def test_projection_v3_x(self):
from pedemath.vec3 import projection_v3
vec_a = Vec3(3, 4, 5)
vec_b = Vec3(1, 0, 0)
result = projection_v3(vec_a, vec_b)
self.assertEqual(3, result) | Python | nomic_cornstack_python_v1 |
function tokenize self data
begin
for match in call finditer scanner data
begin
for tuple idx capture in enumerate call groups
begin
if capture is not none
begin
set rule = rules at idx
set symbol = symbol
if symbol is not none
begin
if is_functional
begin
yield call symbol capture
end
else
begin
yield symbol
end
end
b... | def tokenize(self, data):
for match in re.finditer(self.scanner, data):
for idx, capture in enumerate(match.groups()):
if capture is not None:
rule = self.rules[idx]
symbol = rule.symbol
if rule.symbol is not None:
... | Python | nomic_cornstack_python_v1 |
function solve_node_based self voltage_src_matrix current_sink_matrix resistance_matrix N=- 1 threshold=- 1
begin
call init_matrices voltage_src_matrix current_sink_matrix resistance_matrix N=if expression N == - 1 then N else N threshold=if expression threshold == - 1 then threshold else threshold
comment set up loopi... | def solve_node_based(self, voltage_src_matrix, current_sink_matrix, resistance_matrix, N = -1, threshold=-1):
self.init_matrices(voltage_src_matrix, current_sink_matrix, resistance_matrix, N = (self.N if N==-1 else N),threshold = (self.threshold if threshold==-1 else threshold))
# set up looping
... | Python | nomic_cornstack_python_v1 |
function step self y_true y_preds batch_size **kwargs
begin
set count = count + batch_size
set score = call accuracy_score y_true y_preds
set total_score = score * batch_size
set sum = sum + total_score
return sum / count
end function | def step(self, y_true, y_preds, batch_size, **kwargs):
self.count += batch_size
self.score = sklearn.metrics.accuracy_score(y_true, y_preds)
total_score = self.score * batch_size
self.sum += total_score
return self.sum / self.count | Python | nomic_cornstack_python_v1 |
import numpy as np
import librosa
from tensorflow.keras.models import model_from_json
from tensorflow import keras
import tensorflow as tf
import IPython.display as ipd
import matplotlib.pyplot as plt
import librosa.display
set classDict = dict 0 string Air Conditioner ; 1 string Car Horn ; 2 string Children Playing ; ... | import numpy as np
import librosa
from tensorflow.keras.models import model_from_json
from tensorflow import keras
import tensorflow as tf
import IPython.display as ipd
import matplotlib.pyplot as plt
import librosa.display
classDict = {0: "Air Conditioner", 1: "Car Horn", 2: "Children Playing", 3: "Dog Bark", 4: "D... | Python | zaydzuhri_stack_edu_python |
function abort self
begin
set _want_abort = true
end function | def abort(self):
self._want_abort = True | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
comment using list comprehensions
comment since matrix = mxm you can iterate over the diagonal by iterating over the index range once (0,0), (1,1), (2,2)
comment for the second diagonal you can reverse the index range with enumerate (0,2), (1,1), (2,0)
comment both methods require iterations o... | #!/usr/bin/python3
#using list comprehensions
#since matrix = mxm you can iterate over the diagonal by iterating over the index range once (0,0), (1,1), (2,2)
#for the second diagonal you can reverse the index range with enumerate (0,2), (1,1), (2,0)
#both methods require iterations of the order n only (where n is the... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
set samples = list string A sociologia é a parte das ciências humanas que estuda o comportamento humano em função do meio e os processos que interligam os indivíduos em associações, grupos e instituições. Enquanto o indivíduo na sua singularidade é estudado pela psicologia, a sociologia te... | # -*- coding: utf-8 -*-
samples = [
"""A sociologia é a parte das ciências humanas que estuda o comportamento
humano em função do meio e os processos que interligam os indivíduos em
associações, grupos e instituições. Enquanto o indivíduo na sua
singularidade é estudado pela psicologia, a sociologia tem uma base
teóri... | Python | zaydzuhri_stack_edu_python |
function plot_waypoints self number
begin
set orientation_list = list
set top = call get_path string mobility_games
set sound_folder = join path top string auditory/sound_files
set waypoints = list
set r = call Rate 10
print string Searching for Tango...
while not call is_shutdown
begin
if x and not start
begin
set s... | def plot_waypoints(self, number):
self.orientation_list = []
top = RosPack().get_path('mobility_games')
self.sound_folder = path.join(top, 'auditory/sound_files')
waypoints = []
r = rospy.Rate(10)
print("Searching for Tango...")
while not rospy.is_shutdown():
... | Python | nomic_cornstack_python_v1 |
comment Паша очень любит кататься на общественном транспорте, а получая билет,
comment сразу проверяет, счастливый ли ему попался. Билет считается счастливым,
comment если сумма первых трех цифр совпадает с суммой последних трех цифр номера билета.
comment Однако Паша очень плохо считает в уме, поэтому попросил вас нап... | # Паша очень любит кататься на общественном транспорте, а получая билет,
# сразу проверяет, счастливый ли ему попался. Билет считается счастливым,
# если сумма первых трех цифр совпадает с суммой последних трех цифр номера билета.
# Однако Паша очень плохо считает в уме, поэтому попросил вас написать
# программу, котор... | Python | zaydzuhri_stack_edu_python |
from hashlib import md5
set SECRET_KEY = string ckczppom
function find_hash
begin
set num = 0
set secret_hash = md5
update secret_hash SECRET_KEY
while true
begin
set current_hash = copy secret_hash
update current_hash string num
end
end function | from hashlib import md5
SECRET_KEY = "ckczppom"
def find_hash():
num = 0
secret_hash = md5()
secret_hash.update(SECRET_KEY)
while True:
current_hash = secret_hash.copy()
current_hash.update(str(num)) | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment ---------------------------------------------------------------------------------------
comment Load configuration values
comment ---------------------------------------------------------------------------------------
comment see https://wiki.python.org/moin/ConfigParserShootout
fro... | #!/usr/bin/env python
#---------------------------------------------------------------------------------------
# Load configuration values
#
#---------------------------------------------------------------------------------------
# see https://wiki.python.org/moin/ConfigParserShootout
from configobj import ConfigObj
... | Python | zaydzuhri_stack_edu_python |
function getObserved filename
begin
set obs = list
set times = list
try
begin
set f = open filename string r
end
except IOError
begin
call apflog string Couldn't open %s % filename level=string warn echo=true
return tuple obs times
end
try else
begin
for line in f
begin
set line = strip line
if length line > 0
begin
... | def getObserved(filename):
obs = []
times = []
try:
f = open(filename, 'r')
except IOError:
apflog( "Couldn't open %s" % filename,level="warn",echo=True)
return obs, times
else:
for line in f:
line = line.strip()
if len(line) > 0:
... | Python | nomic_cornstack_python_v1 |
function test_correct_levels_loading self
begin
comment initialization
set manager = call LevelManager string testdata/correctlevels
call load_next_level
set first_level = current_level
set second_level = call load_next_level
comment check first level
assert equal level 1
assert equal snake_max_length 15
assert equal m... | def test_correct_levels_loading(self):
#initialization
manager = LevelManager("testdata/correctlevels")
manager.load_next_level()
first_level = manager.current_level
second_level = manager.load_next_level()
#check first level
self.assertEqual(first_level.level, 1)... | Python | nomic_cornstack_python_v1 |
function consume self
begin
set tuple token_type token_string token_line_number = token_data at pos
set pos = pos + 1
return tuple token_type token_string token_line_number
end function | def consume(self):
token_type, token_string, token_line_number = self.token_data[self.pos]
self.pos += 1
return token_type, token_string, token_line_number | Python | nomic_cornstack_python_v1 |
function addAtHead self val
begin
call addAtIndex 0 val
end function | def addAtHead(self, val: int) -> None:
self.addAtIndex(0, val) | Python | nomic_cornstack_python_v1 |
function created_at self
begin
return _created_at
end function | def created_at(self):
return self._created_at | Python | nomic_cornstack_python_v1 |
from statistics import mean , median
import pandas as pd
import numpy as np
import random
import matplotlib.pyplot as plt
function mean_func points
begin
return tuple mean list comprehension p at 0 for p in points mean list comprehension p at 1 for p in points
end function
function median_func points
begin
return tuple... | from statistics import mean , median
import pandas as pd
import numpy as np
import random
import matplotlib.pyplot as plt
def mean_func(points):
return mean([p[0] for p in points]), mean([p[1] for p in points])
def median_func(points):
return median([p[0] for p in points]), median([p[1] for p in points])
... | Python | zaydzuhri_stack_edu_python |
comment %%
comment prediction of house based on area, bedroom and age
import pandas as pd
import numpy as np
from sklearn import linear_model
import math
set df = read csv string data3.csv
set median_bedrooms = floor median
median_bedrooms
set bedrooms = fill missing bedrooms median_bedrooms
df
set reg = linear regress... | #%%
# prediction of house based on area, bedroom and age
import pandas as pd
import numpy as np
from sklearn import linear_model
import math
df = pd.read_csv("data3.csv")
median_bedrooms = math.floor(df.bedrooms.median())
median_bedrooms
df.bedrooms = df.bedrooms.fillna(median_bedrooms)
df
reg = linear_model.LinearRegr... | Python | zaydzuhri_stack_edu_python |
function get_table self
begin
set table = call HebComparisonTable context request heb_pks
if length get request string heb_pk == 3
begin
call alsoProvides table IHebergementComparisonThree
end
else
if length get request string heb_pk == 4
begin
call alsoProvides table IHebergementComparisonFour
end
update table
return ... | def get_table(self):
table = hebcomparison.HebComparisonTable(self.context,
self.request,
self.heb_pks)
if len(self.request.get('heb_pk')) == 3:
zope.interface.alsoProvides(
tabl... | Python | nomic_cornstack_python_v1 |
from keras.models import Sequential
from keras.layers import Dense , Activation , Dropout
import numpy as np
import pickle
from dictionary import Dictionary
class Trainer
begin
function __init__ self
begin
call reset
end function
function reset self
begin
set model = none
set x_train_list = list
set y_train_list = lis... | from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout
import numpy as np
import pickle
from dictionary import Dictionary
class Trainer:
def __init__(self):
self.reset()
def reset(self):
self.model = None
self.x_train_list = []
self.y_train_lis... | Python | zaydzuhri_stack_edu_python |
comment import openpyxl
comment pip install openpyxl
from openpyxl import workbook
from openpyxl import load_workbook
from fileDownloader import get_mayafiles_htmlFIle , get_requiredData_from_htmlURL
function writeToExcel linksArray pageIndex
begin
set wb = call load_workbook string somepath/workbook.xlsx
set sheets = ... | # import openpyxl
from openpyxl import workbook # pip install openpyxl
from openpyxl import load_workbook
from fileDownloader import get_mayafiles_htmlFIle, get_requiredData_from_htmlURL
def writeToExcel(linksArray, pageIndex):
wb = load_workbook("somepath/workbook.xlsx")
sheets = wb.sheetnames
Sheet1 = ... | Python | zaydzuhri_stack_edu_python |
function download_url url root filename=none md5=none
begin
set root = call safe_path root
if not filename
begin
set filename = base name path url
end
set filename = join path root filename
make directories root exist_ok=true
comment downloads file
if not is file path filename
begin
set bar_updater = call _gen_bar_upda... | def download_url(
url,
root,
*,
filename=None,
md5=None,
):
root = safe_path(root)
if not filename:
filename = os.path.basename(url)
filename = os.path.join(root, filename)
os.makedirs(root, exist_ok=True)
# downloads file
if not os.path.isfile(f... | Python | nomic_cornstack_python_v1 |
function minor_unit self
begin
return __currency at string minor_unit
end function | def minor_unit(self) -> int:
return self.__currency['minor_unit'] | Python | nomic_cornstack_python_v1 |
comment counting vowels in given string
set string = input string enter the string ::
set count = 0
for i in string
begin
if i == string a or i == string o or i == string e or i == string i or i == string u
begin
set count = count + 1
end
end
print string Numbers of vowels in the string are :: count | #counting vowels in given string
string = input('enter the string :: ')
count = 0
for i in string:
if i == 'a' or i == 'o' or i == 'e' or i == 'i' or i == 'u':
count +=1
print('Numbers of vowels in the string are :: ', count) | Python | zaydzuhri_stack_edu_python |
string Guess a Number A.I Wesley F
import random
import math
comment helper functions
function show_start_screen
begin
print string _____ _ _ _ _____
print string / ____| | \ | | | | /\ |_ _|
print string | | __ _ _ ___ ___ ___ __ _ | \| |_ _ _ __ ___ | |__ ___ _ __ / \ | |
print string | | |_ | | | |/ _ \/ __/ __| / _... | """
Guess a Number A.I
Wesley F
"""
import random
import math
# helper functions
def show_start_screen():
print(" _____ _ _ _ _____ ")
print(" / ____| | \ | | | | /\ ... | Python | zaydzuhri_stack_edu_python |
import math
set s = input
set n = length s
function is_kaibun s
begin
set n = length s
set h = s at slice 0 : ceil n - 1 / 2 :
set t = s at slice n + 3 // 2 - 1 : n :
comment print(h,t)
return h == t at slice : : - 1
end function
set h = s at slice 0 : n - 1 // 2 :
set t = s at slice n + 3 // 2 - 1 : n :
if call ... | import math
s = input()
n = len(s)
def is_kaibun(s):
n = len(s)
h = s[0:math.ceil((n-1)/2)]
t = s[(n+3)//2-1:n]
#print(h,t)
return h == t[::-1]
h = s[0:(n-1)//2]
t = s[(n+3)//2-1:n]
if is_kaibun(s) and is_kaibun(h) and is_kaibun(t):
print("Yes")
else:
print("No")
#print(h)
#print(t[::-... | Python | zaydzuhri_stack_edu_python |
function RL_deconv_cont t y kernel kernel_param iterations=4 mass_conserve=true EPS=1e-15
begin
set y_mass = call trapz x=t y=y
set x_hat = deep copy y
set x_hat at x_hat < EPS = EPS
set r = ones shape
comment Iterate towards ML estimate for the latent signal
for i in range iterations
begin
set y_hat = call convint t=t... | def RL_deconv_cont(t, y, kernel, kernel_param, iterations=4, mass_conserve=True, EPS=1e-15):
y_mass = trapz(x=t, y=y)
x_hat = copy.deepcopy(y)
x_hat[x_hat < EPS] = EPS
r = np.ones(y.shape)
# Iterate towards ML estimate for the latent signal
for i in range(iterations):
y_hat... | Python | nomic_cornstack_python_v1 |
function unpack_validation_data validation_data raise_if_ambiguous=true
begin
if is instance validation_data tuple Iterator IteratorBase DatasetV2 Sequence or not has attribute validation_data string __len__
begin
set val_x = validation_data
set val_y = none
set val_sample_weight = none
end
else
if length validation_da... | def unpack_validation_data(validation_data, raise_if_ambiguous=True):
if (isinstance(validation_data, (iterator_ops.Iterator,
iterator_ops.IteratorBase,
data_types.DatasetV2,
data_utils.Sequence))
or not has... | Python | nomic_cornstack_python_v1 |
function download_data
begin
if not exists path PATH_DATA
begin
make directory os PATH_DATA
print string Data are missing. Downloading them now (~150 Mo)... end=string flush=true
url retrieve DOWNLOAD_URL ARCHIVE_FNAME
print string Ok.
print string Extracting now... end=string flush=true
set tf = open ARCHIVE_FNAME
e... | def download_data():
if not os.path.exists(PATH_DATA):
os.mkdir(PATH_DATA)
print("Data are missing. Downloading them now (~150 Mo)...",
end="", flush=True)
urlretrieve(DOWNLOAD_URL, ARCHIVE_FNAME)
print("Ok.")
print("Extracting now...", end="", flush=True)
... | Python | nomic_cornstack_python_v1 |
function GetElementIfIndexExists self arg0 arg1
begin
return call itkVectorContainerULLNPI2F_GetElementIfIndexExists self arg0 arg1
end function | def GetElementIfIndexExists(self, arg0: 'unsigned long long', arg1: 'itkNodePairI2F') -> "bool":
return _ITKFastMarchingBasePython.itkVectorContainerULLNPI2F_GetElementIfIndexExists(self, arg0, arg1) | 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.