code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function quicksort array
begin
if length array < 2
begin
comment base case, arrays with 0 or 1 element are already sorted
return array
end
else
begin
comment recursive case
set pivot = array at 0
comment sub-array of all the elements less than the pivot
set less = list comprehension i for i in array at slice 1 : : if... | def quicksort(array):
if len(array) < 2:
# base case, arrays with 0 or 1 element are already sorted
return array
else:
# recursive case
pivot = array[0]
# sub-array of all the elements less than the pivot
less = [i for i in array[1:] if i <= pivot]
# sub-array of all the elements greater... | Python | jtatman_500k |
function _must_be_finalized self submission
begin
if not is_finalized
begin
raise call InvalidEvent self string Submission is not finalized
end
end function | def _must_be_finalized(self, submission: Submission) -> None:
if not submission.is_finalized:
raise InvalidEvent(self, "Submission is not finalized") | Python | nomic_cornstack_python_v1 |
comment multifract3.py
set total_access = 2048
set time_slot = 2187
set biases = list 0.1 0.2 0.7
set order = 7
function multi_fract order time
begin
set prob = 1
for i in range order
begin
set prob = prob * biases at time % 3
set time = time / 3
end
return total_access * prob
end function
function gen_hist
begin
retur... | #multifract3.py
total_access = 2048
time_slot = 2187
biases = [0.1, 0.2, 0.7]
order = 7
def multi_fract(order, time):
prob = 1
for i in range(order):
prob *= biases[time % 3]
time /= 3
return total_access * prob
def gen_hist():
return [(i, multi_fract(order, i)) for i in range(time_slot)]
if __name__... | Python | zaydzuhri_stack_edu_python |
import tkinter as tk
from tkinter import messagebox
import re
from Domain.BDWindowsInteractor import BDWindowsInteractor
from Domain.MainWindowInteractor import MainWindowInteractor
class EditEntryInfoWindow extends Toplevel object
begin
string Класс отвечающий за окно изменения данных Автор Кабисов Г.Ч. БИВ185
set __i... | import tkinter as tk
from tkinter import messagebox
import re
from Domain.BDWindowsInteractor import BDWindowsInteractor
from Domain.MainWindowInteractor import MainWindowInteractor
class EditEntryInfoWindow(tk.Toplevel, object):
"""
Класс отвечающий за окно изменения данных
Автор Кабисов Г.Ч. БИВ185
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
comment -*- coding:utf-8 -*-
string rectangle module. This is the Rectangle class inherited from the Base class, with private attributes width, height and x and y as offsets for printing the rectangle, each with its getters and setters, and public methods area, display, update, and to_dictiona... | #!/usr/bin/python3
# -*- coding:utf-8 -*-
"""rectangle module.
This is the Rectangle class inherited from the Base class, with private
attributes width, height and x and y as offsets for printing the rectangle,
each with its getters and setters, and public methods area, display, update,
and to_dictionary.
"""
from mod... | Python | zaydzuhri_stack_edu_python |
function step self
begin
raise call NotImplementedError string { __name__ } must implement a `step` method.
end function | def step(self):
raise NotImplementedError(
f'{self.__class__.__name__} must implement a `step` method.'
) | Python | nomic_cornstack_python_v1 |
function get_matching_kwargs func kwargs
begin
string Takes a function and keyword arguments and returns the ones that can be passed.
set tuple args uses_startstar = call _get_argspec func
if uses_startstar
begin
return copy kwargs
end
else
begin
set matching_kwargs = dictionary generator expression tuple k kwargs at k... | def get_matching_kwargs(func, kwargs):
"""Takes a function and keyword arguments and returns the ones that can be passed."""
args, uses_startstar = _get_argspec(func)
if uses_startstar:
return kwargs.copy()
else:
matching_kwargs = dict((k, kwargs[k]) for k in args if k in kwargs)
... | Python | jtatman_500k |
while 1
begin
set N = integer input
if N == 0
begin
break
end
set R = list comprehension list comprehension 0 for i in range N + 1 for i in range N + 1
function dfs_max cur pre
begin
set _max = - R at cur at pre
for i in range N + 1
begin
if R at cur at i > 0 and i != pre
begin
set _max = max _max call dfs_max i cur + ... | while 1:
N = int(input())
if N == 0:break
R = [[0 for i in range(N+1)] for i in range(N+1)]
def dfs_max(cur, pre):
_max = -R[cur][pre]
for i in range(N+1):
if R[cur][i] > 0 and i != pre:
_max = max(_max, dfs_max(i, cur) + R[cur][i])
# print('max : %d' ... | Python | jtatman_500k |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
comment @Author: ningyanke
comment @Date: 2018-01-05 01:38:53
comment @Last Modified by: chanafanghua
comment @Last Modified time: 2018-01-08 23:17:52
from tkinter import *
set root = call Tk
comment 为顶层窗口绑定2个事件
comment Key 事件处理函数
function printEvent event
begi... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: ningyanke
# @Date: 2018-01-05 01:38:53
# @Last Modified by: chanafanghua
# @Last Modified time: 2018-01-08 23:17:52
from tkinter import *
root = Tk()
# 为顶层窗口绑定2个事件
# Key 事件处理函数
def printEvent(event):
print('<key>', event.keycode)
# Return 事件处理函数
de... | Python | zaydzuhri_stack_edu_python |
comment 투시 변환
comment 직사각형 형태의 영상이 자유도가 높은 임의의 사각형으로 만들어 내는 것
comment 3 x 3 행렬로 표현이 된다. -> 미지수 8개 이다.
comment cv2.getPerspectiveTransform(src, dst, solveMethod)
comment 입력영상(src), 출력영상(dst) 4개의 좌표점을
comment numpy.ndarray.shape(4,2) => np.array([[x1,y1],[x2,y2],[x3,y3],[x4,y4]], np.float32) 같은 형태로 넣어주면 된다.
comment cv2.w... | # 투시 변환
# 직사각형 형태의 영상이 자유도가 높은 임의의 사각형으로 만들어 내는 것
# 3 x 3 행렬로 표현이 된다. -> 미지수 8개 이다.
# cv2.getPerspectiveTransform(src, dst, solveMethod)
# 입력영상(src), 출력영상(dst) 4개의 좌표점을
# numpy.ndarray.shape(4,2) => np.array([[x1,y1],[x2,y2],[x3,y3],[x4,y4]], np.float32) 같은 형태로 넣어주면 된다.
# cv2.warpAffine()
# affine 변환을 해서 출력 영상을 만들어 ... | Python | zaydzuhri_stack_edu_python |
function handle_todo bot ievent
begin
if length args > 0
begin
call handle_todo2 bot ievent
return
end
set name = call getname userhost
try
begin
set todoos = get todo name
end
except KeyError
begin
call reply string i dont have todo info for %s % name
return
end
call saytodo bot ievent todoos
end function | def handle_todo(bot, ievent):
if len(ievent.args) > 0:
handle_todo2(bot, ievent)
return
name = users.getname(ievent.userhost)
try:
todoos = todo.get(name)
except KeyError:
ievent.reply('i dont have todo info for %s' % user.name)
return
saytodo(bot, ievent, tod... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Tue Aug 07 13:52:08 2018 @author: Student
import numpy as np
import math
import pandas as pd
import csv
set dfile = string D:/115cs0231/patient.csv
comment df=csv.reader(dfile)
set df = read csv dfile | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 07 13:52:08 2018
@author: Student
"""
import numpy as np
import math
import pandas as pd
import csv
dfile='D:/115cs0231/patient.csv'
#df=csv.reader(dfile)
df=pd.read_csv(dfile) | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import numpy as np
import math
set h = 0.01
set t = 1000
set R = 2
set d = 6
set pt = array range 0 t h
set vx0 = 0
set pla1 = call Circle tuple 0 - 3 R lw=1 alpha=0.5
set pla2 = call Circle tuple 0 3 R lw=1 alpha=0.5
call add_artist pla1
call add_artist pla2
call xlim list - 50 50
call ... | import matplotlib.pyplot as plt
import numpy as np
import math
h=0.01
t=1000
R=2
d=6
pt=np.arange(0,t,h)
vx0=0
pla1 = plt.Circle((0, -3), R,lw=1,alpha=0.5)
pla2 = plt.Circle((0, 3),R,lw=1,alpha=0.5)
plt.gcf().gca().add_artist(pla1)
plt.gcf().gca().add_artist(pla2)
plt.xlim([-50,50])
plt.ylim([-50,50])
while(vx0<1):
... | Python | zaydzuhri_stack_edu_python |
string Question 35: Define a function which can generate a dictionary where the keys are numbers between 1 and 20 (both included) and the values are square of keys. The function should just print the values only.
set input_num = input string Write number:
set dict1 = dictionary
function dic n1 n2
begin
string function ... | """
Question 35:
Define a function which can generate a dictionary where the keys are numbers between 1 and 20
(both included) and the values are square of keys. The function should just print the values only.
"""
input_num = input("Write number:")
dict1=dict()
def dic(n1,n2):
"""
function to generate and print valu... | Python | zaydzuhri_stack_edu_python |
comment Name: Aisangam
comment Url: http://www.aisangam.com/
comment Blog:http://www.aisangam.com/blog/
comment Company: Aisangam
comment YouTube Channel Link: https://www.youtube.com/channel/UC9x_PL-LPk3Wp5V85F4GLHQ
comment Discription: https://youtu.be/PePk_YkMQn0?list=PLCK5Mm9zwPkFt1iX30kD5eJ9hy-EeijQn
import cv2
fr... | #Name: Aisangam
# Url: http://www.aisangam.com/
# Blog:http://www.aisangam.com/blog/
#Company: Aisangam
# YouTube Channel Link: https://www.youtube.com/channel/UC9x_PL-LPk3Wp5V85F4GLHQ
# Discription: https://youtu.be/PePk_YkMQn0?list=PLCK5Mm9zwPkFt1iX30kD5eJ9hy-EeijQn
import cv2
from skimage.exposure import rescale_in... | Python | zaydzuhri_stack_edu_python |
function scrape url_to_scrape=none cached_data=none
begin
set all_items = list
if cached_data
begin
set cat_dict = cached_data at string categories_dict
end
else
begin
comment {item_id: { 'id': item_id, 'category_list': [categories], 'url': item_url } }
set cat_dict = call _traverse_categories
end
set category_list = ... | def scrape(url_to_scrape=None, cached_data=None):
all_items = []
if cached_data:
cat_dict = cached_data['categories_dict']
else:
cat_dict = _traverse_categories() # {item_id: { 'id': item_id, 'category_list': [categories], 'url': item_url } }
category_list = None
brand = None
... | Python | nomic_cornstack_python_v1 |
string DO NOT CHANGE THE NAME OF THIS FILE, or else the tester will not work. The first function requires that you replace the given strings with your personal details. It is important that you enter your student number and your student email correctly. If your number and email do not match we will then check your name... | '''
DO NOT CHANGE THE NAME OF THIS FILE, or else the tester will not work.
The first function requires that you replace the given strings with
your personal details. It is important that you enter your student number
and your student email correctly. If your number and email do not match we
will then check your name, s... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from scipy.signal import convolve2d
import matplotlib.pyplot as plt
from scipy.misc import imread , imsave , imresize
import tensorflow as tf
import os
from magenta.models.image_stylization import image_utils
from magenta.models.image_stylization import model
function generate_map map_size=tuple 64 6... | import numpy as np
from scipy.signal import convolve2d
import matplotlib.pyplot as plt
from scipy.misc import imread, imsave, imresize
import tensorflow as tf
import os
from magenta.models.image_stylization import image_utils
from magenta.models.image_stylization import model
def generate_map(map_size=(64,64),num_i... | Python | zaydzuhri_stack_edu_python |
function sniff self request
begin
return call UserAgent sniffers request
end function | def sniff(self, request):
return UserAgent(self.sniffers, request) | Python | nomic_cornstack_python_v1 |
function gcs_archive self
begin
return get pulumi self string gcs_archive
end function | def gcs_archive(self) -> pulumi.Output[Optional['outputs.LogsArchiveGcsArchive']]:
return pulumi.get(self, "gcs_archive") | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
import math
import ROOT
comment 26.5.2014
function GetBinContents histo
begin
set nx = call GetNbins
set content = list
for binx in range 1 nx + 1
begin
append content call GetBinContent binx
end
return content
end function
function GetBinEdges histo
begin
set nx = call GetNbins
set edges = li... | #!/usr/bin/python
import math
import ROOT
# 26.5.2014
def GetBinContents(histo):
nx = histo.GetXaxis().GetNbins()
content = []
for binx in range(1,nx+1):
content.append(histo.GetBinContent(binx))
return content
def GetBinEdges(histo):
nx = histo.GetXaxis().GetNbins()
edges = []
f... | Python | zaydzuhri_stack_edu_python |
function test_start self worker mocker write_results_side_effect
begin
for method in tuple string get_policies string get_configured string get_data string refresh_all string refresh_prefix_list string notice
begin
call object worker method autospec=true
end
call object worker string write_results autospec=true side_ef... | def test_start(self, worker, mocker, write_results_side_effect):
for method in ("get_policies", "get_configured", "get_data",
"refresh_all", "refresh_prefix_list", "notice"):
mocker.patch.object(worker, method, autospec=True)
mocker.patch.object(worker, "write_results"... | Python | nomic_cornstack_python_v1 |
function c
begin
global env robot manip
end function | def c():
global env,robot,manip | Python | nomic_cornstack_python_v1 |
comment 153 - Write a Python program to remove an item from a set if it is present in the set.
set A = set list 1 2 3 4 5
set elem = integer input string Digite o elemento a ser removido:
if elem in A
begin
discard A elem
print A
end
else
begin
print string Elemento não existe.
end | #153 - Write a Python program to remove an item from a set if it is present in the set.
A = set([1,2,3,4,5])
elem = int(input('Digite o elemento a ser removido: '))
if elem in A:
A.discard(elem)
print(A)
else:
print('Elemento não existe.') | Python | zaydzuhri_stack_edu_python |
function isNear self *args
begin
return call Pose2D_isNear self *args
end function | def isNear(self, *args):
return _almathswig.Pose2D_isNear(self, *args) | Python | nomic_cornstack_python_v1 |
comment find max(a[j]-a[i]) where i<j
set lst = list 5 9 18 32 32 33 40 49 50 70 74 86 89 96 114 137 142 148 159 160 162 181 202 204 209 212 253 256 260 262 266 280 291 295 298 316 348 351 363 363 403 409 422 436 438 442 444 447 456 458 475 489 499 501 501 512 513 540 559 560 562 564 578 592 599 606 611 614 648 659 673... | #find max(a[j]-a[i]) where i<j
lst = [5, 9, 18, 32, 32, 33, 40, 49, 50, 70, 74, 86, 89, 96, 114, 137, 142, 148, 159, 160, 162, 181, 202, 204, 209, 212, 253, 256, 260, 262, 266, 280, 291, 295, 298, 316, 348, 351, 363, 363, 403, 409, 422, 436, 438, 442, 444, 447, 456, 458, 475, 489, 499, 501, 501, 512, 513, 540, 559, 56... | Python | zaydzuhri_stack_edu_python |
function word2ind wordlist word_ind addword=true k=300 fill0=true padding_len=50 paddingAtEnd=true
begin
if fill0
begin
set res = list 0 * length wordlist
set maxind = length word_ind
set count = 0
for tuple i iword in enumerate wordlist
begin
if iword in word_ind
begin
set res at i = word_ind at iword
end
else
if addw... | def word2ind(wordlist, word_ind, addword = True,k=300,fill0 = True,padding_len = 50, paddingAtEnd = True):
if fill0:
res = [0]*len(wordlist)
maxind = len(word_ind)
count = 0
for i,iword in enumerate(wordlist):
if iword in word_ind:
... | Python | nomic_cornstack_python_v1 |
function plot_dyn_spec vis fobs mjd bname normalize=false outname=none show=true
begin
set tuple fig ax = call subplots 9 5 figsize=tuple 8 * 5 8 * 9
set ax = flatten ax
set dplot = real
set dplot = dplot / mean reshape dplot 45 - 1 axis=- 1 at tuple slice : : newaxis newaxis
if normalize
begin
set dplot = dplot / a... | def plot_dyn_spec(vis,fobs,mjd,bname,normalize=False,
outname=None,show=True):
fig,ax = plt.subplots(9,5,figsize=(8*5,8*9))
ax = ax.flatten()
dplot = (np.nanmean(np.nanmean(vis[:,:vis.shape[1]//125*125,:].reshape(
45,125,-1,625),2).reshape(45,125,125,5),-1)).real
dplot = dp... | Python | nomic_cornstack_python_v1 |
function upload_package path **kwargs
begin
return call devpi string upload list string --from-dir string --no-vcs cwd=path keyword kwargs
end function | def upload_package(path, **kwargs):
return devpi("upload", ["--from-dir", "--no-vcs"], cwd=path, **kwargs) | Python | nomic_cornstack_python_v1 |
import urllib
import requests
set response = split text string
set listaDeNomes = list
set listaDeValores = list
set conta = 0
set count = 0
for r in response
begin
if string Dust Cost: in r
begin
set count = count + 1
end
if string <span class="card-name"> in r
begin
set nome = split split r string span class="card-... | import urllib
import requests
response = requests.get(raw_input("\nInsira link, por favor: ")).text.split("\n")
listaDeNomes = []
listaDeValores = []
conta = 0
count = 0
for r in response:
if "Dust Cost:" in r:
count += 1
if '<span class="card-name">' in r:
nome = r.split('span class="card-na... | Python | zaydzuhri_stack_edu_python |
import socket
import sys
set sock = call socket AF_INET SOCK_STREAM
set bind_address = call gethostbyname call getfqdn
set bind_port = 8082
print format string connecting to server {} on port {} bind_address bind_port file=stderr
call connect tuple bind_address bind_port
try
begin
set message = string GET / HTTP/1.0 ho... | import socket
import sys
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
bind_address = socket.gethostbyname(socket.getfqdn())
bind_port = 8082
print('connecting to server {} on port {}'.format(bind_address, bind_port),
file=sys.stderr)
sock.connect((bind_address, bind_port))
try:
message = 'GET... | Python | zaydzuhri_stack_edu_python |
function generate_fit_block_hawkes event_dict node_membership bp_mu bp_alpha bp_beta duration seed=none
begin
comment Generating a network
set n_nodes = length node_membership
set tuple _ block_count = unique node_membership return_counts=true
set class_prob = block_count / sum block_count
set tuple generated_node_memb... | def generate_fit_block_hawkes(event_dict, node_membership,
bp_mu, bp_alpha, bp_beta,
duration, seed=None):
# Generating a network
n_nodes = len(node_membership)
_, block_count = np.unique(node_membership, return_counts=True)
class_prob = bloc... | Python | nomic_cornstack_python_v1 |
import re
import clusters
set post = dict
set wordcounts = dict
set apcount = dict
set newsByLine = list comprehension line for line in open string TranslatedToEnglish.txt
function createDictionaryNewsById
begin
set i = 1
set newss = string
set default post string string i string
for news in newsByLine
begin
set li... | import re
import clusters
post={}
wordcounts={}
apcount={}
newsByLine = [ line for line in open("TranslatedToEnglish.txt")]
def createDictionaryNewsById():
i=1
newss=""
post.setdefault(str("i"),"")
for news in newsByLine:
list_of_output=[] | Python | zaydzuhri_stack_edu_python |
function percent_destroyed
begin
comment gives an integer for how much damage rats do
set rat_percent_chance = random integer 10 30
comment converts above integer to decimal value
set rat_float_chance = decimal rat_percent_chance / 100
return rat_float_chance
end function | def percent_destroyed():
rat_percent_chance = random.randint(10,30) #gives an integer for how much damage rats do
rat_float_chance = float(rat_percent_chance)/100 #converts above integer to decimal value
return rat_float_chance | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string @Author : Xu @Software: PyCharm @File : compound_speech.py @Time : 2020/5/2 12:10 下午 @Desc : 语音合成
from Model.TTS.api import AipSpeech
import os
import random
import traceback
import logging
import string
comment 生成随机的字符串,可用于文件名等
comment 参数:
comment strlen 字符串长度,默认为10
comment 返回:
com... | # -*- coding: utf-8 -*-
"""
@Author : Xu
@Software: PyCharm
@File : compound_speech.py
@Time : 2020/5/2 12:10 下午
@Desc : 语音合成
"""
from Model.TTS.api import AipSpeech
import os
import random
import traceback
import logging
import string
# 生成随机的字符串,可用于文件名等
# 参数:
# strlen 字符串长度,默认为10
# 返回... | Python | zaydzuhri_stack_edu_python |
import time
import random
function str_time_prop start end format prop
begin
set stime = call mktime string parse time start format
set etime = call mktime string parse time end format
set ptime = stime + prop * etime - stime
return string format time time format call localtime ptime
end function
function random_date s... | import time
import random
def str_time_prop(start, end, format, prop):
stime = time.mktime(time.strptime(start, format))
etime = time.mktime(time.strptime(end, format))
ptime = stime + prop * (etime - stime)
return time.strftime(format, time.localtime(ptime))
def random_date(start, end, prop):
... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
for i in range 3
begin
set file = open string 10 ^ i + 1 + string .txt
set x_list = list
set analytic = list
set numeric = list
read line file
for line in file
begin
set contents = split line
append x_list decimal contents at 0
append analytic decimal contents at 1
append numeric deci... | import matplotlib.pyplot as plt
for i in range(3):
file = open(str(10**(i+1))+".txt")
x_list = []
analytic = []
numeric = []
file.readline()
for line in file:
contents = line.split()
x_list.append(float(contents[0]))
analytic.append(float(contents[1]))
numeric.ap... | Python | zaydzuhri_stack_edu_python |
function content_type self
begin
if task_type == FORWARDING_TASK_TYPE_ID
begin
return string opengever.inbox.forwarding
end
return string opengever.task.task
end function | def content_type(self):
if self.task_type == FORWARDING_TASK_TYPE_ID:
return 'opengever.inbox.forwarding'
return 'opengever.task.task' | Python | nomic_cornstack_python_v1 |
comment Calculates area and circumference
comment of a circle
import math
comment radius
set radius = decimal input string Enter Radius
comment area
set area = pi * radius ^ 2
comment circumference
set circumference = 2 * pi * radius
print area circumference | #Calculates area and circumference
#of a circle
import math
# radius
radius = float(input("Enter Radius"))
# area
area = math.pi * radius ** 2
# circumference
circumference = 2 * math.pi * radius
print (area, circumference) | Python | zaydzuhri_stack_edu_python |
function from_json_string json_string
begin
if json_string is none or length json_string == 0
begin
set json_string = string []
end
return loads json_string
end function | def from_json_string(json_string):
if json_string is None or len(json_string) == 0:
json_string = "[]"
return json.loads(json_string) | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function minimumCost self N connections
begin
string :type N: int :type connections: List[List[int]] :rtype: int
set adjList = call getAdjList N connections
set heap = list tuple 0 1
set seen = set
set globalDist = 0
while heap
begin
set tuple currPath currNode = call heappop heap
if... | class Solution(object):
def minimumCost(self, N, connections):
"""
:type N: int
:type connections: List[List[int]]
:rtype: int
"""
adjList = self.getAdjList(N, connections)
heap = [(0, 1)]
seen = set()
globalDist = 0
... | Python | zaydzuhri_stack_edu_python |
comment Program to match word with particular pattern
import re
set str = string Sat, hat, mat, pat
set allstr = find all string [Shmp]at str
for i in allstr
begin
print i
end | #Program to match word with particular pattern
import re
str ="Sat, hat, mat, pat"
allstr = re.findall("[Shmp]at", str)
for i in allstr:
print(i)
| Python | zaydzuhri_stack_edu_python |
import pandas as pd
from sklearn import linear_model
from sklearn.metrics import mean_squared_error
set housing_data_set = read csv string boston_housing.txt header=none
set housing_data_set = values
comment print(housing_data_set)
set shape_list = reshape housing_data_set shape at 0
set split_list = list comprehension... | import pandas as pd
from sklearn import linear_model
from sklearn.metrics import mean_squared_error
housing_data_set = pd.read_csv('boston_housing.txt', header=None)
housing_data_set = housing_data_set.values
#print(housing_data_set)
shape_list = housing_data_set.reshape(housing_data_set.shape[0])
split_list = [val.sp... | Python | zaydzuhri_stack_edu_python |
comment from __future__ import print_function
import numpy as np
from scipy.stats import chi2
function generate_XOR_labels X
begin
set y = exp X at tuple slice : : 0 * X at tuple slice : : 2
set prob_1 = call expand_dims 1 / 1 + y 1
set prob_0 = call expand_dims y / 1 + y 1
set y = concatenate tuple prob_0 prob_1... | # from __future__ import print_function
import numpy as np
from scipy.stats import chi2
def generate_XOR_labels(X):
y =np.exp(X[:,0]*X[:,2])
prob_1 = np.expand_dims(1 / (1+y) ,1)
prob_0 = np.expand_dims(y / (1+y) ,1)
y = np.concatenate((prob_0,prob_1), axis = 1)
return y
d... | Python | zaydzuhri_stack_edu_python |
function sort_list lst
begin
sort lst key=lambda x -> x at 1
return lst
end function | def sort_list(lst):
lst.sort(key = lambda x: x[1])
return lst
| Python | flytech_python_25k |
comment textplus.py
from graphics import *
set DEFAULT_CONFIG at string anchor = string nw
class TextPlus extends Text
begin
set tuple N NE E SE S SW W NW C = tuple string n string ne string e string se string s string sw string w string nw string center
set tuple L R F = tuple string left string right string fill
func... | #textplus.py
from graphics import *
DEFAULT_CONFIG["anchor"]="nw"
class TextPlus(Text):
N,NE,E,SE,S,SW,W,NW,C="n","ne","e","se","s","sw","w","nw","center"
L,R,F="left","right","fill"
def __init__(self, p, text):
GraphicsObject.__init__(self, ["fill","text","font","anchor"])
self.se... | Python | zaydzuhri_stack_edu_python |
function test_calculate_multiples_sum self
begin
set multiples = list 3
set limit = 3
set res = call calculate_multiples_sum multiples limit
set exp = 3
assert equal res exp
end function | def test_calculate_multiples_sum(self):
multiples = [3]
limit = 3
res = pe.calculate_multiples_sum(multiples, limit)
exp = 3
self.assertEqual(res, exp) | Python | nomic_cornstack_python_v1 |
from __future__ import print_function
from operator import itemgetter
import fileinput
function order line
begin
set chars = list line
sort chars key=call itemgetter 0
set ordered = join string chars
return ordered
end function
comment read from file and prepare
set words = list
for line in input
begin
set word = lis... | from __future__ import print_function
from operator import itemgetter
import fileinput
def order(line):
chars = list(line)
chars.sort(key=itemgetter(0))
ordered = "".join(chars)
return ordered
# read from file and prepare
words = []
for line in fileinput.input():
word = []
# word.append(line.lower()... | Python | zaydzuhri_stack_edu_python |
function create_tests population
begin
return list comprehension call MegamanAITest for _ in call xrange population
end function | def create_tests(population):
return [MegamanAITest() for _ in xrange(population)] | Python | nomic_cornstack_python_v1 |
function zip_htmls context
begin
info string Creating viewable archives for all html files
change directory output_dir
set html_files = glob glob string *.html
comment if there is an index.html, do it first and re-name it for safe keeping
set save_name = string
if exists op string index.html
begin
call zip_it_zip_it_g... | def zip_htmls(context):
context.log.info(' Creating viewable archives for all html files')
os.chdir(context.output_dir)
html_files = glob.glob('*.html')
# if there is an index.html, do it first and re-name it for safe keeping
save_name = ''
if op.exists('index.html'):
zip_it_zip_it_go... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Wed Dec 12 12:55:13 2018 @author: Jens Reichwein
import numpy as np
import matplotlib.pyplot as plt
function pressure
begin
comment ,2412,2415,2418,4408,4412,4415,4418]
set NACA = list 2418
comment 822,1210,2091,4061,4180,4320]
set S = list 833
set reynolds = list
set pa... | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 12 12:55:13 2018
@author: Jens Reichwein
"""
import numpy as np
import matplotlib.pyplot as plt
def pressure():
NACA = [2418]#,2412,2415,2418,4408,4412,4415,4418]
S = [833]#822,1210,2091,4061,4180,4320]
reynolds = []
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment follow https://iancoleman.io/bip39/ patern
comment bytes.fromhex(seedS)
import getpass
import sys
import argparse
from library import *
set coins = list string bitcoin string bitcoin-testnet string ethereum
set parser = call ArgumentParser description=string Generate hd wallet and ... | #!/usr/bin/env python3
#follow https://iancoleman.io/bip39/ patern
#bytes.fromhex(seedS)
import getpass
import sys
import argparse
from library import *
coins = ['bitcoin','bitcoin-testnet','ethereum']
parser = argparse.ArgumentParser(description='Generate hd wallet and account for bitcoin and ethereum')
group = ... | Python | zaydzuhri_stack_edu_python |
function warn message
begin
print string WARNING: { message }
end function | def warn(message):
print(f"WARNING: {message}") | Python | nomic_cornstack_python_v1 |
comment Problem 25
string Q. Lily likes to play games with integers and their reversals. For some integer x, we define reversed(x) to be the reversal of all digits in x. For example, reversed(123) = 321, reversed(21) = 12, and reversed(120) = 21. Logan wants to go to the movies with Lily on some day x satisfying (i <= ... | # Problem 25
"""
Q. Lily likes to play games with integers and their reversals. For some integer x, we define
reversed(x) to be the reversal of all digits in x. For example, reversed(123) = 321,
reversed(21) = 12, and reversed(120) = 21.
Logan wants to go to the movies with Lily on some day x satisf... | Python | zaydzuhri_stack_edu_python |
for file in files
begin
set file = strip file string
while true
begin
set number = number + 1
set file_2 = split file
print string В { number } строке: { length file } символов и { length file_2 } слов
break
end
end | for file in files:
file = file.strip("\n")
while True:
number += 1
file_2 = file.split()
print(f"В {number} строке: {len(file)} символов и {len(file_2)} слов")
break
| Python | zaydzuhri_stack_edu_python |
function vis_imgs2 self X y_ y path
begin
if ndim == 2
begin
set y = y at tuple slice : : slice : : newaxis
end
if ndim == 2
begin
set y_ = y_ at tuple slice : : slice : : newaxis
end
assert ndim == 3
call save_images call asarray list X at tuple slice : : slice : : 0 newaxis X at tuple slice : : s... | def vis_imgs2(self, X, y_, y, path):
if y.ndim == 2:
y = y[:,:,np.newaxis]
if y_.ndim == 2:
y_ = y_[:,:,np.newaxis]
assert X.ndim == 3
tl.vis.save_images(np.asarray([X[:,:,0,np.newaxis],
X[:,:,1,np.newaxis], X[:,:,2,np.newaxis],
X[:,:,3,np.... | Python | nomic_cornstack_python_v1 |
async function send_room self document_id annotationId message
begin
comment Check they are in this room
print string DocumentChatConsumer: send_room { document_id }
if document_id != none
begin
if string document_id != string document_id
begin
raise call ClientError string ROOM_ACCESS_DENIED string Document access den... | async def send_room(self, document_id, annotationId, message):
# Check they are in this room
print(f'DocumentChatConsumer: send_room {self.document_id }')
if self.document_id != None:
if str(document_id) != str(self.document_id):
raise ClientError("ROOM_ACCESS_DENIED", "Document access denied")
if not i... | Python | nomic_cornstack_python_v1 |
import os , math
set path = get current directory
call add_library string minim
set audioPlayer = call Minim this
class Creature
begin
function __init__ self x y radius img frame_width frame_height num_frames
begin
set x = x
set y = y
comment Velocity up or down
set vy = 0
comment Velocity left or right
set vx = 0
set ... | import os, math
path = os.getcwd()
add_library("minim")
audioPlayer = Minim(this)
class Creature:
def __init__(self, x, y, radius, img, frame_width, frame_height, num_frames):
self.x = x
self.y = y
self.vy = 0 # Velocity up or down
self.vx = 0 # Velocity left or right
self.r... | Python | zaydzuhri_stack_edu_python |
import discord
from discord.ext import commands
from asyncio import sleep
from json import load
from datetime import datetime
function get_prefix ctx message
begin
with open string Bases/prefixes_base.json mode=string r as f
begin
set prefixes = load f
end
return prefixes at string id
end function
class DurationConvert... | import discord
from discord.ext import commands
from asyncio import sleep
from json import load
from datetime import datetime
def get_prefix(ctx, message):
with open('Bases/prefixes_base.json', mode="r") as f:
prefixes = load(f)
return prefixes[str(message.guild.id)]
class DurationConverter... | Python | zaydzuhri_stack_edu_python |
function tempcelcius a
begin
set c = a - 32 * 5 / 9
print string temp in celcius is c
end function
function tempfeh b
begin
set d = c * 9 / 5 + 32
print string temperature in fahrenie is d
end function
while true
begin
set x = input string enter your choice : 1 for feh to celcius 2 for celcius to feh 3 for exit
if x ==... | def tempcelcius(a):
c = ((a-32)*5)/9
print("temp in celcius is ", c)
def tempfeh(b):
d = ((c*9)/5) +32
print("temperature in fahrenie is ",d)
while True:
x = input("enter your choice : \n 1 for feh to celcius \n 2 for celcius to feh \n 3 for exit \n")
if x == "1":
f = float(input("enter feh value") )
tem... | Python | zaydzuhri_stack_edu_python |
from typing import List , Dict , Union
import pandas as pd
import pandera as pa
set _ACCEPTED_DTYPES = tuple string int64 string float64 string object string string
set _dtype_to_pandera_map = dict string int64 Int ; string float64 Float ; string object String ; string string String
class Interval
begin
string Class fo... | from typing import List, Dict, Union
import pandas as pd
import pandera as pa
_ACCEPTED_DTYPES = (
'int64',
'float64',
'object',
'string',
)
_dtype_to_pandera_map = {
'int64': pa.Int,
'float64': pa.Float,
'object': pa.String,
'string': pa.String,
}
class Interval:
"""Class for ho... | Python | zaydzuhri_stack_edu_python |
function ai_1 board
begin
set cur_piece = cpiece
if cur_piece is not none
begin
for tuple x y in open_spots
begin
set move = call find_win_spot cur_piece board
if move
begin
return call update_board_then_give_random board move
end
end
end
call ai_random_move
return board
end function | def ai_1(board: BoardState) -> BoardState:
cur_piece = board.cpiece
if cur_piece is not None:
for (x,y) in board.open_spots:
move = find_win_spot(cur_piece, board)
if move:
return update_board_then_give_random(board, move)
board.ai_random_move()
return boa... | Python | nomic_cornstack_python_v1 |
function test_serialization_fit_model self
begin
comment Setup
set instance = call VineCopula string regular
set X = call DataFrame data=list list 1 0 0 list 0 1 0 list 0 0 1
fit instance X
comment Run
set result = call from_dict call to_dict
comment Check
call compare_nested_dicts call to_dict call to_dict
end functio... | def test_serialization_fit_model(self):
# Setup
instance = VineCopula('regular')
X = pd.DataFrame(data=[
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]
])
instance.fit(X)
# Run
result = VineCopula.from_dict(instance.to_dict())
# Chec... | Python | nomic_cornstack_python_v1 |
function remove_system_drift2 self
begin
set com = call get_system_com
set cov = call get_system_com_velocity
set angmom = call get_system_angmom
set inertia_inv = zeros tuple 3 3
set EPSILON = 1e-08
set inertia = call get_system_inertia_tensor
set det = call det inertia
end function | def remove_system_drift2(self):
com = self.get_system_com()
cov = self.get_system_com_velocity()
angmom = self.get_system_angmom()
inertia_inv = np.zeros((3,3))
EPSILON = 1.0e-8
inertia = self.get_system_inertia_tensor()
det = np.linalg.det(inertia) | Python | nomic_cornstack_python_v1 |
function test_generate_text text special_dict num_words
begin
from trigrams import generate_text
assert length call generate_text text special_dict num_words == num_words
end function | def test_generate_text(text, special_dict, num_words):
from trigrams import generate_text
assert len(generate_text(text, special_dict, num_words)) == num_words | Python | nomic_cornstack_python_v1 |
import telebot
from pyowm import OWM
from pyowm.utils.config import get_default_config
set owm = call OWM string 72a1f31dc5df9b64e7f6138990faaf53
set mgr = call weather_manager
set config_dict = call get_default_config
set config_dict at string language = string ru
set bot = call TeleBot string 1432598281:AAGvRH-XwBfNg... | import telebot
from pyowm import OWM
from pyowm.utils.config import get_default_config
owm = OWM('72a1f31dc5df9b64e7f6138990faaf53')
mgr = owm.weather_manager()
config_dict = get_default_config()
config_dict['language'] = 'ru'
bot = telebot.TeleBot("1432598281:AAGvRH-XwBfNgdWnUpIEHA8kslQ5dibpatA", parse_mode=None)
@... | Python | zaydzuhri_stack_edu_python |
function test_close_project_sets_visible_config projects tmpdir value
begin
comment Set config to opposite value so that we can check that it's set correctly
call set_option string visible_if_project_open not value
call open_project path=call to_text_string tmpdir
if value
begin
call show_explorer
end
else
begin
close ... | def test_close_project_sets_visible_config(projects, tmpdir, value):
# Set config to opposite value so that we can check that it's set correctly
projects.set_option('visible_if_project_open', not value)
projects.open_project(path=to_text_string(tmpdir))
if value:
projects.show_explorer()
el... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Script to make a 3d vector plot of the b-field, pretty handy for visualizing. Created on Tue Sep 25 09:24:46 2019 @author: fpiermaier
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
comment noqa: F401 unused import
from mpl_t... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script to make a 3d vector plot of the b-field, pretty handy for visualizing.
Created on Tue Sep 25 09:24:46 2019
@author: fpiermaier
"""
import pandas as pd
import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa: F40... | Python | zaydzuhri_stack_edu_python |
import cv2
import os
from skimage.feature import hog
from sklearn.svm import SVC
import numpy as np
from sklearn.model_selection import cross_val_score , train_test_split , ShuffleSplit , StratifiedKFold
from sklearn.metrics import accuracy_score , precision_score , recall_score , confusion_matrix
import matplotlib.pyp... | import cv2
import os
from skimage.feature import hog
from sklearn.svm import SVC
import numpy as np
from sklearn.model_selection import cross_val_score, train_test_split, ShuffleSplit, StratifiedKFold
from sklearn.metrics import accuracy_score, precision_score, recall_score, confusion_matrix
import matplotlib.pyplot a... | Python | zaydzuhri_stack_edu_python |
function _to_dict self
begin
return call to_dict
end function | def _to_dict(self):
return self.to_dict() | Python | nomic_cornstack_python_v1 |
while true
begin
set n = integer input
if n == 0
begin
break
end
set center = map int split input
for i in range n
begin
set pos = map int split input
end
end | while True:
n = int(input())
if n == 0:
break
center = map(int, input().split())
for i in range(n):
pos = map(int, input().split()) | Python | zaydzuhri_stack_edu_python |
function dft_recursive self starting_vertex visited=none
begin
if not visited
begin
set visited = set
end
comment add to visited
add visited starting_vertex
comment print this value
print starting_vertex
comment for each vertice
for found_vertex in vertices at starting_vertex
begin
comment call dft_recursive on this ve... | def dft_recursive(self, starting_vertex, visited=None):
if not visited:
visited = set()
# add to visited
visited.add(starting_vertex)
# print this value
print(starting_vertex)
# for each vertice
for found_vertex in self.vertices[starting_vertex]:
... | Python | nomic_cornstack_python_v1 |
import requests
import re
import time
from bs4 import BeautifulSoup
function get_one_page url
begin
try
begin
set headers = dict string User-Agent string Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36
set response = get requests url headers=headers timeout... | import requests
import re
import time
from bs4 import BeautifulSoup
def get_one_page(url):
try:
headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.146 Safari/537.36'}
response = requests.get(url, headers=headers, timeout=10)
print(response.statu... | Python | zaydzuhri_stack_edu_python |
string 谱聚类 只需要数据之间的相似度矩阵,因此对于处理稀疏数据的聚类很有效。使用了降维,因此在处理高维数据聚类时的复杂度比传统聚类算法好。 如果最终聚类的维度非常高,则由于降维的幅度不够,谱聚类的运行速度和最后的聚类效果均不好。 聚类效果依赖于相似矩阵,不同的相似矩阵得到的最终聚类效果可能很不同。 不需要事先标准化,Ncut拉普拉斯矩阵已标准化
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import SpectralClustering , KMeans , Birch , DBSCAN
from sklea... | """
谱聚类
只需要数据之间的相似度矩阵,因此对于处理稀疏数据的聚类很有效。使用了降维,因此在处理高维数据聚类时的复杂度比传统聚类算法好。
如果最终聚类的维度非常高,则由于降维的幅度不够,谱聚类的运行速度和最后的聚类效果均不好。
聚类效果依赖于相似矩阵,不同的相似矩阵得到的最终聚类效果可能很不同。
不需要事先标准化,Ncut拉普拉斯矩阵已标准化
"""
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import SpectralClustering, KMeans, Birch, DBSCAN
from sklea... | Python | zaydzuhri_stack_edu_python |
with open path as f
begin
set lines = read lines f
for line in lines
begin
set line = replace line string string
set line = split line string :
if length line == 2
begin
set setting at integer line at 0 = line at 1
end
else
begin
set problem = integer line at 0
set answer = integer line at 0
end
end
end
set setting = ... | with open(path) as f:
lines = f.readlines()
for line in lines:
line = line.replace('\n', '')
line = line.split(':')
if len(line) == 2:
setting[int(line[0])] = line[1]
else:
problem = int(line[0])
answer = int(line[0])
setting = sorted(setting.... | Python | zaydzuhri_stack_edu_python |
function mean_normlztn Y R
begin
set tuple m n = shape
set Y_mean = zeros tuple m 1
set Y_norm = zeros tuple m n
for i in range length R
begin
set idx = where R at tuple i slice : : == 1 at 0
set Y_mean at i = mean Y at tuple i idx
set Y_norm at tuple i idx = Y at tuple i idx - Y_mean at i
end
return tuple Y_norm Y_... | def mean_normlztn(Y, R):
m, n = Y.shape
Y_mean = zeros((m, 1))
Y_norm = zeros((m, n))
for i in range(len(R)):
idx = where(R[i, :] == 1)[0]
Y_mean[i] = mean(Y[i, idx])
Y_norm[i, idx] = Y[i, idx] - Y_mean[i]
return Y_norm, Y_mean | Python | nomic_cornstack_python_v1 |
import copy
import time
from memory_profiler import profile
decorator profile
function deepcopy i simple_object
begin
append simple_object deep copy simple_object at i - 1
return simple_object
end function
decorator profile
function remove_reference simple_object
begin
del simple_object at 0
return simple_object
end fu... | import copy
import time
from memory_profiler import profile
@profile
def deepcopy(i,simple_object):
simple_object.append(copy.deepcopy(simple_object[i-1]))
return simple_object
@profile
def remove_reference(simple_object):
del simple_object[0]
return simple_object
n = 5
simple_object = [[1,2,[3,4],5]]
for j... | Python | zaydzuhri_stack_edu_python |
async function _get_metadata client_session credentials project instance
begin
if not is instance credentials Credentials or not is instance project str or not is instance instance str
begin
raise call TypeError string Arguments must be as follows: + string service (googleapiclient.discovery.Resource), + string proj_na... | async def _get_metadata(
client_session: aiohttp.ClientSession,
credentials: Credentials,
project: str,
instance: str,
) -> Dict[str, Any]:
if (
not isinstance(credentials, Credentials)
or not isinstance(project, str)
or not isinstance(instance, str)
):
raise Typ... | Python | nomic_cornstack_python_v1 |
import Adafruit_CharLCD as LCD
import RPi.GPIO as GPIO
call setmode BCM
set lcdrs = 13
set lcden = 19
set lcdd4 = 26
set lcdd5 = 16
set lcdd6 = 20
set lcdd7 = 21
set lcd = call Adafruit_CharLCD lcdrs lcden lcdd4 lcdd5 lcdd6 lcdd7 0 16 2
call message string IoT Champs
comment (col, row)
call set_cursor 0 1
call message ... | import Adafruit_CharLCD as LCD
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
lcdrs=13
lcden=19
lcdd4=26
lcdd5=16
lcdd6=20
lcdd7=21
lcd = LCD.Adafruit_CharLCD(lcdrs, lcden, lcdd4,lcdd5 , lcdd6 , lcdd7 ,0 ,16,2)
lcd.message("IoT Champs")
lcd.set_cursor(0, 1) #(col, row)
lcd.message("Welcome")
| Python | zaydzuhri_stack_edu_python |
function add_record self data
begin
if not call _validate_columns data
begin
raise call ValueError string Invalid column names
end
set formatted_data = list comprehension string data at column for column in column_names
call write_line join string , formatted_data + string filename string a
end function | def add_record(self, data):
if not self._validate_columns(data):
raise ValueError('Invalid column names')
formatted_data = [str(data[column]) for column in self.column_names]
utils.write_line(','.join(formatted_data) + '\n', self.filename, 'a') | Python | nomic_cornstack_python_v1 |
function zlexcount self *args
begin
if _cluster
begin
return execute self string ZLEXCOUNT *args shard_key=args at 0
end
return execute self string ZLEXCOUNT *args
end function | def zlexcount(self, *args):
if self._cluster:
return self.execute(u'ZLEXCOUNT', *args, shard_key=args[0])
return self.execute(u'ZLEXCOUNT', *args) | Python | nomic_cornstack_python_v1 |
function summary df city month day
begin
call time_stats df month day
call station_stats df
call trip_duration_stats df
call user_stats df city
call display_data df
end function | def summary(df, city, month, day):
time_stats(df, month, day)
station_stats(df)
trip_duration_stats(df)
user_stats(df, city)
display_data(df) | Python | nomic_cornstack_python_v1 |
for i in range IH
begin
add IHM input
end
set NR1 = integer input
for i in range NR1
begin
set NR = input
set IE1 = integer input
for j in range IE1
begin
add IE input
end
for i in IE
begin
if i in IHM
begin
set N = true
end
else
begin
set N = not true
end
end
if N
begin
print NR
end
set IE = set
end | for i in range(IH):
IHM.add(input())
NR1 = int(input())
for i in range(NR1):
NR = input()
IE1 = int(input())
for j in range(IE1):
IE.add(input())
for i in IE:
if i in IHM:
N = True
else:
N = not True
if N:
print(NR)
IE = set() | Python | zaydzuhri_stack_edu_python |
comment %%
import boto3
import awscli
function detect_labels photo bucket
begin
string processes an image from s3 bucket into Amazon Rekognition to determine objects in image + bounding box locations
set client = call client string rekognition region_name=string us-east-1
set response = call detect_labels Image=dict st... | # %%
import boto3
import awscli
def detect_labels(photo, bucket):
'''processes an image from s3 bucket into Amazon Rekognition
to determine objects in image + bounding box locations'''
client=boto3.client('rekognition', region_name='us-east-1')
response = client.detect_labels(Image={'S3Object':{'Bucket': b... | Python | zaydzuhri_stack_edu_python |
function get_task_optimizer self
begin
pass
end function | def get_task_optimizer(self) -> torch.optim.Optimizer:
pass | Python | nomic_cornstack_python_v1 |
import tensorflow as tf
comment 声明变量
comment w1: 2*3矩阵
set w1 = call Variable call random_normal list 2 3 stddev=1 seed=1
comment b1: [0 0 0] 向量
set b1 = call Variable call constant 0.0 shape=list 3
comment w2: 3*1矩阵 (3行1列)
set w2 = call Variable call random_normal list 3 1 stddev=1 seed=1
comment b2: [0]向量
set b2 = ca... | import tensorflow as tf
#声明变量
#w1: 2*3矩阵
w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
#b1: [0 0 0] 向量
b1 = tf.Variable(tf.constant(0.0, shape=[3]))
#w2: 3*1矩阵 (3行1列)
w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))
#b2: [0]向量
b2 = tf.Variable(tf.constant(0.0, shape=[1]))
#暂时将输入的特征向量定义为一个常量... | Python | zaydzuhri_stack_edu_python |
from collections import defaultdict
from datetime import datetime , timedelta
function preprocess events
begin
sort events
set guard_minute_sleep = default dictionary lambda -> default dictionary int
set cur_guard = - 1
for tuple i event in enumerate events
begin
if event at 1 == string begin
begin
set cur_guard = eve... | from collections import defaultdict
from datetime import datetime, timedelta
def preprocess(events):
events.sort()
guard_minute_sleep = defaultdict(lambda: defaultdict(int))
cur_guard = -1
for i, event in enumerate(events):
if event[1] == "begin":
cur_guard = event[2]
elif... | Python | zaydzuhri_stack_edu_python |
function create_dc_attnd_table params freq
begin
set pvd_dc_attnd = call read_excel daily_census_data sheet_name=string pvd parse_dates=list string date
set woon_dc_attnd = call read_excel daily_census_data sheet_name=string woon parse_dates=list string date
set wes_dc_attnd = call read_excel daily_census_data sheet_na... | def create_dc_attnd_table(params, freq):
pvd_dc_attnd = pd.read_excel(
daily_census_data, sheet_name="pvd", parse_dates=["date"]
)
woon_dc_attnd = pd.read_excel(
daily_census_data, sheet_name="woon", parse_dates=["date"]
)
wes_dc_attnd = pd.read_excel(
daily_census_data, shee... | Python | nomic_cornstack_python_v1 |
function main
begin
global collection
comment args = argparse.ArgumentParser()
comment args.add_argument('directory', help='Directory in which the files'
comment 'are stored.')
comment args.add_argument('collection', help='The collection to use.')
comment parser = args.parse_args()
set collection = call get_collection
... | def main():
global collection
#args = argparse.ArgumentParser()
#args.add_argument('directory', help='Directory in which the files'
#'are stored.')
#args.add_argument('collection', help='The collection to use.')
#parser = args.parse_args()
collection = get_collection()
#documents... | Python | nomic_cornstack_python_v1 |
function setSnapPoint self snapValue snapRange
begin
append snapPoints tuple snapValue - snapRange / 2 snapValue snapValue + snapRange / 2
end function | def setSnapPoint(self, snapValue, snapRange):
self.snapPoints.append( (snapValue - snapRange / 2, snapValue, snapValue + snapRange / 2)) | Python | nomic_cornstack_python_v1 |
for i in numList
begin
if not i % 2
begin
set finStr = finStr + string i + string
end
end
print finStr | for i in numList:
if not (i % 2):
finStr += str(i) + ' '
print(finStr)
| Python | zaydzuhri_stack_edu_python |
from pathlib import Path
function get_base_path
begin
return parent
end function
function get_file_path relative_path
begin
return call resolve
end function | from pathlib import Path
def get_base_path():
return Path(__file__).parent
def get_file_path(relative_path):
return (get_base_path() / relative_path).resolve()
| Python | zaydzuhri_stack_edu_python |
async function async_turn_off self
begin
if _container
begin
try
begin
call stop
end
except Exception as ex
begin
info format string Cannot stop container ({}) ex
end
end
end function | async def async_turn_off(self):
if self._container:
try:
self._container.stop()
except Exception as ex:
_LOGGER.info("Cannot stop container ({})".format(ex)) | Python | nomic_cornstack_python_v1 |
function GmatBase_GetInstanceCount
begin
return call GmatBase_GetInstanceCount
end function | def GmatBase_GetInstanceCount():
return _gmat_py.GmatBase_GetInstanceCount() | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
class WiiOrderModel extends object
begin
function __init__ self db
begin
set db = db
set params = dict string operatorType string ; string operatorTypeTile string ; string channelCode string ; string appCode string ; string payCode string ; string imsi string ; string tel string ; string st... | # coding: utf-8
class WiiOrderModel(object):
def __init__(self, db):
self.db = db
self.params = {
"operatorType": "",
"operatorTypeTile": "",
"channelCode": "",
"appCode": "",
"payCode": "",
"imsi": "",
"tel": "",
... | Python | zaydzuhri_stack_edu_python |
comment count issues for each user
comment Run python file: python userDetector.py input.txt output.txt (eg: python userDetector.py group8.txt output8.txt)
function reader inputFile outputFile
begin
set fd = open inputFile string r
set wd = open outputFile string w
comment record each user's issue number
set userDict =... | # count issues for each user
# Run python file: python userDetector.py input.txt output.txt (eg: python userDetector.py group8.txt output8.txt)
def reader(inputFile, outputFile):
fd = open(inputFile, 'r')
wd = open(outputFile, 'w')
userDict = {}; # record each user's issue number
issueCount = 0; # cou... | Python | zaydzuhri_stack_edu_python |
import random , pickle
from PIL import Image , ImageDraw
comment Открываем изображение.
set image = open string grid.png
comment Создаем инструмент для рисования.
set draw = call Draw image
comment Определяем ширину.
set width = size at 0
comment Определяем высоту.
set height = size at 1
comment Выгружаем значения пикс... | import random, pickle
from PIL import Image, ImageDraw
image = Image.open("grid.png") #Открываем изображение.
draw = ImageDraw.Draw(image) #Создаем инструмент для рисования.
width = image.size[0] #Определяем ширину.
height = image.size[1] #Определяем высоту.
pix = image.load() #Выгружаем значения пикселей.
datatable =... | Python | zaydzuhri_stack_edu_python |
import itertools
set shapes = list string circle string triangle string square
set result = call combinations shapes 2
for each in result
begin
print each
end
print string -------------------------------------
set shapes = list string circle string triangle string square
set result = call combinations_with_replacement ... | import itertools
shapes = ['circle', 'triangle', 'square',]
result = itertools.combinations(shapes, 2)
for each in result:
print(each)
print("-------------------------------------")
shapes = ['circle', 'triangle', 'square',]
result = itertools.combinations_with_replacement(shapes, 2)
for each in result:
prin... | Python | zaydzuhri_stack_edu_python |
function timer self name
begin
pass
end function | def timer(self, name):
pass | Python | nomic_cornstack_python_v1 |
import unittest
from BackTracking.q037_sudoku_solver import Solution
class TestSudokuSolver extends TestCase
begin
string Test q037_sudoku_solver.py
function test_sudoku_solver self
begin
set s = call Solution
comment self.assertEqual((0, 0), s.cal(0, 0))
comment self.assertEqual((0, 1), s.cal(0, 1))
comment self.asser... | import unittest
from BackTracking.q037_sudoku_solver import Solution
class TestSudokuSolver(unittest.TestCase):
"""Test q037_sudoku_solver.py"""
def test_sudoku_solver(self):
s = Solution()
# self.assertEqual((0, 0), s.cal(0, 0))
# self.assertEqual((0, 1), s.cal(0, 1))
# sel... | 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.