code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function get_subcommands parser cfg prefix=string fail_no_subcommand=true
begin
if _subcommands_action is none
begin
return tuple none none
end
set action = _subcommands_action
set require_single = get single_subcommand
comment Get subcommand settings keys
set subcommand_keys = list comprehension k for k in keys choic... | def get_subcommands(
parser: "ArgumentParser",
cfg: Namespace,
prefix: str = "",
fail_no_subcommand: bool = True,
) -> Tuple[Optional[List[str]], Optional[List["ArgumentParser"]]]:
if parser._subcommands_action is None:
return None, None
action = parser._s... | Python | nomic_cornstack_python_v1 |
comment @lc app=leetcode.cn id=98 lang=python3
comment [98] 验证二叉搜索树
comment @lc code=start
comment Definition for a binary tree node.
comment class TreeNode:
comment def __init__(self, x):
comment self.val = x
comment self.left = None
comment self.right = None
class Solution
begin
function isValidBST self root
begin
se... | #
# @lc app=leetcode.cn id=98 lang=python3
#
# [98] 验证二叉搜索树
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
a =... | Python | zaydzuhri_stack_edu_python |
import random
class IDgenerator
begin
function __init__ self start end
begin
set start = start
set end = end
end function
function generate self
begin
set numbers = list
while length numbers < end - start + 1
begin
set num = random integer start end
if num % 3 != 0 and num not in numbers
begin
append numbers num
end
e... | import random
class IDgenerator:
def __init__(self, start, end):
self.start = start
self.end = end
def generate(self):
numbers = []
while len(numbers) < self.end - self.start + 1:
num = random.randint(self.start, self.end)
if num % 3 != 0 and num not... | Python | jtatman_500k |
comment ! /usr/bin/env python
import numpy as np
import re
import sys
import csv
import pickle
import pcalda
import wndcharm
function openobject filename
begin
with open filename string rb as inputfile
begin
set obj = load pickle inputfile
end
return obj
end function
function format_data data
begin
set data = array dat... | #! /usr/bin/env python
import numpy as np
import re
import sys
import csv
import pickle
import pcalda
import wndcharm
def openobject(filename):
with open(filename, 'rb') as inputfile:
obj = pickle.load(inputfile)
return obj
def format_data(data):
data=np.array(data)
#data=data[1:len(data),:]
ind=-1
for i in r... | Python | zaydzuhri_stack_edu_python |
function print_mult_table n
begin
for i in range 1 11
begin
print format string {} x {} = {} n i n * i
end
end function | def print_mult_table(n):
for i in range(1, 11):
print('{} x {} = {}'.format(n, i, n*i))
| Python | flytech_python_25k |
function recurrent_cycle n
begin
for r in range 1 n
begin
if 10 ^ r % n == 1
begin
return r
end
end
return 0
end function
print string The number with the longest recurrent cycle is '%s' ('%s') % max list comprehension tuple i call recurrent_cycle i for i in range 2 d key=lambda tup -> tup at - 1 | def recurrent_cycle(n):
for r in range(1, n):
if 10 ** r % n == 1:
return r
return 0
print("The number with the longest recurrent cycle is '%s' ('%s')" %
max([(i, recurrent_cycle(i)) for i in range(2, d)],
key=lambda tup: tup[-1])) | Python | zaydzuhri_stack_edu_python |
comment dan = int(input("구구단 몇단을 계산할까요?"))
comment result = 0
comment print('구구단', dan,'단을 계산합니다.')
comment for i in range(1,10):
comment result = dan * i
comment print(dan, 'x', i, '=', result) | # dan = int(input("구구단 몇단을 계산할까요?"))
# result = 0
#
# print('구구단', dan,'단을 계산합니다.')
#
# for i in range(1,10):
# result = dan * i
# print(dan, 'x', i, '=', result)
| Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
comment In[21]:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as se
comment import regex as re
function startsWithDateTime s
begin
set pattern = string ^([0-2][0-9]|(3)[0-1])(\/)(((0)[0-9])|((1)[0-2]))(\/)(\d{2}|\d{4}), ([0-9][0-9]):([0-9][0-9])
set result = match pattern s
if... | # coding: utf-8
# In[21]:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as se
#import regex as re
def startsWithDateTime(s):
pattern = '^([0-2][0-9]|(3)[0-1])(\/)(((0)[0-9])|((1)[0-2]))(\/)(\d{2}|\d{4}), ([0-9][0-9]):([0-9][0-9])'
result = re.match(pattern, s)
if result:
ret... | Python | zaydzuhri_stack_edu_python |
comment Lambda - Ananymous Function
comment normal function
comment imported for the function 'reduce'
from functools import *
function Func_1 x y
begin
return x * x + y
end function
set result = call Func_1 6 2
print result
comment simplified - using lambda
set result_2 = lambda a b -> a * a + b
print call result_2 6 ... | #Lambda - Ananymous Function
#normal function
from functools import * # imported for the function 'reduce'
def Func_1(x,y):
return (x*x)+y
result = Func_1(6,2)
print(result)
#simplified - using lambda
result_2 = lambda a,b : (a*a)+b
print(result_2(6,2))
# Filter, Map, Reduce
lst = [1,2,3,... | Python | zaydzuhri_stack_edu_python |
function create_table h5file where name result attrs=none index=true expectedrows=10000 overwrite=false **table_config
begin
set table_desc = call dtype_to_table dtype
if call _has_node h5file where name=name and not overwrite
begin
debug string Returning existing table %s/%s % tuple where name
set table = call get_nod... | def create_table(h5file, where, name, result, attrs=None,
index=True, expectedrows=10000, overwrite=False,
**table_config):
table_desc = dtype_to_table(result.dtype)
if _has_node(h5file, where, name=name) and not overwrite:
logger.debug('Returning existing table %s/%s'... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import os
import datetime as dt
function sort_statement_file ff
begin
set x = call read_excel ff
set ff_name = split ff string .xls at 0
set dates = x at string Unnamed: 1 at slice 3 : :
set descs = x at string Unnamed: 2 at slice 3 : :
set outs = x at string Unnamed: 4 at slice 3 : :
set outs... | import pandas as pd
import os
import datetime as dt
def sort_statement_file(ff):
x = pd.read_excel(ff)
ff_name = ff.split('.xls')[0]
dates = x['Unnamed: 1'][3:]
descs = x['Unnamed: 2'][3:]
outs = x['Unnamed: 4'][3:]
outs = [float(a.replace(',','')) if type(a)==str else a for a in outs]
ins = x['Unnamed: 5... | Python | zaydzuhri_stack_edu_python |
function solution N number
begin
comment 조합으로 나올수 있는 가능한 숫자들
set possible_set = list 0 list N
comment 주어진 숫자와 사용해야 하는 숫자가 같은 경우 1개
if N == number
begin
return 1
end
for i in range 2 9
begin
set case_set = list
set basic_num = integer string N * i
append case_set basic_num
comment 절반 이상으로 넘어가면 같은 결과 반복
for i_half in ra... | def solution(N, number):
possible_set = [0,[N]] # 조합으로 나올수 있는 가능한 숫자들
if N == number: #주어진 숫자와 사용해야 하는 숫자가 같은 경우 1개
return 1
for i in range(2, 9):
case_set = []
basic_num = int(str(N)*i)
case_set.append(basic_num)
for i_half in range(1, i//2+1): # 절반 이상으로 넘어가면 같은 결... | Python | zaydzuhri_stack_edu_python |
comment 不同大小的牌
set card = dict 3 string 3 ; 4 string 4 ; 5 string 5 ; 6 string 6 ; 7 string 7 ; 8 string 8 ; 9 string 9 ; 10 string 10 ; 11 string Jack ; 12 string Queen ; 13 string King ; 14 string A ; 15 string 2 ; 16 string Joker_low ; 17 string Joker_high
comment 牌型:空、单张、对子、三个不带、三带一、三带一对、顺子5~12、连对3~10、飞机2~5、炸弹
set ... | #不同大小的牌
card = {3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: '10', 11: 'Jack', 12: 'Queen', 13: 'King', 14: 'A', 15: '2', 16: 'Joker_low', 17: 'Joker_high'}
#牌型:空、单张、对子、三个不带、三带一、三带一对、顺子5~12、连对3~10、飞机2~5、炸弹
combo = {'null': 0, 'single': 1, 'pair': 2, 'trible0': 3, 'trible1': 4, 'trible12': 5, 'straight5'... | Python | zaydzuhri_stack_edu_python |
function print_progress current total
begin
write stdout string Progress: %d/%d % tuple current total
flush stdout
end function | def print_progress(current: int, total: int):
sys.stdout.write("Progress: %d/%d \r" % (current, total))
sys.stdout.flush() | Python | nomic_cornstack_python_v1 |
class sort
begin
string 排序几种方法
comment 冒泡排序
function bubble self list_target
begin
comment 外层循环计算比较的轮数
for i in range length list_target - 1
begin
comment 内层循环把控计较次数
for j in range length list_target - 1 - i
begin
if list_target at j > list_target at j + 1
begin
set tuple list_target at j list_target at j + 1 = tuple l... | class sort:
"""
排序几种方法
"""
# 冒泡排序
def bubble(self,list_target):
# 外层循环计算比较的轮数
for i in range(len(list_target) - 1):
# 内层循环把控计较次数
for j in range(len(list_target) - 1 - i):
if list_target[j] > list_target[j + 1]:
list_target[... | Python | zaydzuhri_stack_edu_python |
function private_endpoint self
begin
return get pulumi self string private_endpoint
end function | def private_endpoint(self) -> 'outputs.ResourceIdResponse':
return pulumi.get(self, "private_endpoint") | Python | nomic_cornstack_python_v1 |
import random
import bottle
import os
import time
from app.dto.PublicGameState import PublicGameState
from app.dto.PublicPlayer import PublicPlayer
from app.dto.ReturnDirections import ReturnDirections
set last_desired_point = none
set last_desired_point_reached = false
set last_home_point = none
set eaten_big_points =... | import random
import bottle
import os
import time
from app.dto.PublicGameState import PublicGameState
from app.dto.PublicPlayer import PublicPlayer
from app.dto.ReturnDirections import ReturnDirections
last_desired_point = None
last_desired_point_reached = False
last_home_point = None
eaten_big_points = 0
@bottle.p... | Python | zaydzuhri_stack_edu_python |
for value in range M
begin
append reunioes list comprehension integer value for value in split input string ->
set restricoes = if expression 1 < reunioes at - 1 at 0 and reunioes at - 1 at 0 < N then true else restricoes
pop reunioes at - 1 0
set restricoes = if expression any generator expression P < 1 and N < P for ... | for value in range(M):
reunioes.append([int(value) for value in input('-> ').split()])
restricoes = True if 1<reunioes[-1][0] and reunioes[-1][0]<N else restricoes
reunioes[-1].pop(0)
restricoes = True if any(P<1 and N<P for P in reunioes[-1]) else restricoes
if restricoes:
for i in range (R-1, M):... | Python | zaydzuhri_stack_edu_python |
function zonal_resiliency self
begin
return get pulumi self string zonal_resiliency
end function | def zonal_resiliency(self) -> Optional[bool]:
return pulumi.get(self, "zonal_resiliency") | Python | nomic_cornstack_python_v1 |
import boto3
import os
import csv
set session = call Session profile_name=string aws_mentoring_s3_readonly
set s3 = call client string s3
class FileInfo
begin
set fileName = string
set filePath = string
end class
function GetS3Keys bucket
begin
set keys = list
set resp = call list_objects_v2 Bucket=bucket
for obj in... | import boto3
import os
import csv
session = boto3.Session(profile_name='aws_mentoring_s3_readonly')
s3 = session.client('s3')
class FileInfo:
fileName = ""
filePath = ""
def GetS3Keys(bucket):
keys = []
resp = s3.list_objects_v2(Bucket=bucket)
for obj in resp['Contents']:
keys.append(obj['Key... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
import pygal
class Diagrammprogramm
begin
function __init__ self window bar
begin
set svg = string .svg
set obertext = string Hello
set barzeiger = string
set zähler = 0
call Entrys
call Labels
call Buttons
end function
function Entrys self
begin
set title = call Entry window bg=string #2ECCFA
gr... | from tkinter import *
import pygal
class Diagrammprogramm:
def __init__(self, window, bar):
self.svg = ".svg"
self.obertext = "Hello"
self.barzeiger = ""
self.zähler = 0
self.Entrys()
self.Labels()
self.Buttons()
def Entrys(self):
... | Python | zaydzuhri_stack_edu_python |
function countAll self listOfChars text
begin
set total = 0
for char in listOfChars
begin
comment Text.count returns the amount of a certain character in a string, do this recursively
set total = total + count text char
end
return total
end function | def countAll(self, listOfChars, text):
total = 0
for char in listOfChars:
total += text.count(char) # Text.count returns the amount of a certain character in a string, do this recursively
return total | Python | nomic_cornstack_python_v1 |
import pymysql
string mysql用户类
class mysqlpython extends object
begin
function __init__ self database host=string localhost user=string root password=string 123456 charset=string utf8
begin
set host = host
set user = user
set password = password
set charset = charset
set database = database
end function
function myopen... | import pymysql
'''mysql用户类'''
class mysqlpython(object):
def __init__(self,database,host='localhost',user='root',password='123456',charset='utf8'):
self.host = host
self.user = user
self.password = password
self.charset = charset
self.database = database
def myopen(s... | Python | zaydzuhri_stack_edu_python |
function update_dir src dest
begin
if not is directory path dest
begin
print string ERROR: destination must be a directory when updating more than 1 file
end
else
begin
set source_files = list directory src
set dest_files = list directory dest
for dest_file in dest_files
begin
if dest_file in source_files
begin
set src... | def update_dir(src, dest):
if not os.path.isdir(dest):
print("ERROR: destination must be a directory when updating more than 1 file")
else:
source_files = os.listdir(src)
dest_files = os.listdir(dest)
for dest_file in dest_files:
if dest_file in source_files:
... | Python | nomic_cornstack_python_v1 |
function initAlgorithm self config
begin
set default_extent = call extent
set default_extent_value = format string {0},{1},{2},{3} call xMinimum call xMaximum call yMinimum call yMaximum
call addParameter call QgsProcessingParameterString CANVAS_NAME call tr string Canvas name
call addParameter call QgsProcessingParame... | def initAlgorithm(self, config):
default_extent = iface.mapCanvas().extent()
default_extent_value = '{0},{1},{2},{3}'.format(
default_extent.xMinimum(),
default_extent.xMaximum(),
default_extent.yMinimum(),
default_extent.yMaximum()
)
sel... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding:utf-8 -*-
import socket
import sys
comment 创建 socket
set serverSocket = call socket AF_INET SOCK_STREAM
comment 获取本地主机名
set host = call gethostname
set port = 9999
comment 绑定端口号
call bind tuple host port
comment 设置最大连接数。超过后排队
call listen 5
while true
begin
comment 建立客户端连接... | #!/usr/bin/env python
#-*- coding:utf-8 -*-
import socket
import sys
#创建 socket
serverSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#获取本地主机名
host = socket.gethostname()
port = 9999
#绑定端口号
serverSocket.bind((host,port))
#设置最大连接数。超过后排队
serverSocket.listen(5)
while True:
#建立客户端连接
clientsocket,addr ... | Python | zaydzuhri_stack_edu_python |
from init import build_graph , initialize_cluster
from rankFunctions import simple_rank , cluster_reassign , check_null , EM
import multiprocessing as mp
import heapq
class Config
begin
set input_file = string data_preprocessed.txt
set input_path = string data/
set output_file = string output_data.csv
set output_path =... | from init import build_graph, initialize_cluster
from rankFunctions import simple_rank, cluster_reassign, check_null, EM
import multiprocessing as mp
import heapq
class Config:
input_file = 'data_preprocessed.txt'
input_path = 'data/'
output_file = 'output_data.csv'
output_path = 'output_path/'
# N... | Python | zaydzuhri_stack_edu_python |
import os
import torch
from torch import nn
import torch.nn.functional as F
from torch import optim
from torch.distributions import Categorical , Normal , MultivariateNormal
import pdb
from utils import *
from collections import namedtuple
import random
import gym
set device = string cpu
comment https://github.com/open... | import os
import torch
from torch import nn
import torch.nn.functional as F
from torch import optim
from torch.distributions import Categorical, Normal, MultivariateNormal
import pdb
from utils import *
from collections import namedtuple
import random
import gym
device='cpu'
# https://github.com/openai/gym/blob/mast... | Python | zaydzuhri_stack_edu_python |
function insert_data self cbor
begin
call insert_event cbor
end function | def insert_data(self, cbor):
self.insert_event(cbor) | Python | nomic_cornstack_python_v1 |
import cv2
class FaceRecognizer
begin
function __init__ self
begin
set recognizer = call LBPHFaceRecognizer_create
end function
function load self saved_model_path
begin
read recognizer saved_model_path
end function
function train self x_train y_labels saved_model_path
begin
train recognizer x_train y_labels
save saved... | import cv2
class FaceRecognizer:
def __init__(self):
self.recognizer = cv2.face.LBPHFaceRecognizer_create()
def load(self, saved_model_path):
self.recognizer.read(saved_model_path)
def train(self, x_train, y_labels, saved_model_path):
self.recognizer.train(x_train,... | Python | zaydzuhri_stack_edu_python |
function check_dtype lhs rhs
begin
return dtype == string float16 and dtype == string float16 or dtype == string float32 and dtype == string float32 or dtype in list string int8 string uint8 and dtype in list string int8 string uint8
end function | def check_dtype(lhs, rhs):
return (
(lhs.dtype == "float16" and rhs.dtype == "float16")
or (lhs.dtype == "float32" and rhs.dtype == "float32")
or (lhs.dtype in ["int8", "uint8"] and rhs.dtype in ["int8", "uint8"])
) | Python | nomic_cornstack_python_v1 |
function searchUsers keyword limit=none
begin
set url = string https://users.roblox.com/v1/users/search?keyword= { keyword } &limit= { limit }
set acceptableLimits = tuple 10 25 50 100
if limit in acceptableLimits
begin
set r = get requests url
set j = loads text
set data = j at string data
return data
end
else
if limi... | def searchUsers(keyword, limit=None):
url = f"https://users.roblox.com/v1/users/search?keyword={keyword}&limit={limit}"
acceptableLimits = (10, 25, 50, 100)
if limit in acceptableLimits:
r = requests.get(url)
j = json.loads(r.text)
data = j['data']
... | Python | nomic_cornstack_python_v1 |
function add_slab_scalar self n1 thickness alpha
begin
set n0 = n
set k = k
set k1 = n1 / n0 * k
set ky = ky
set kx = kx
set kz = kz
comment note that, at alpha=0, k_rho remains the same in the slab, in agreement with Snell's law
with call errstate invalid=string ignore
begin
set theta0 = call arcsin ky / k
set theta1 ... | def add_slab_scalar(self, n1, thickness, alpha):
n0 = self.n
k= self.k
k1 = n1/n0 * k
ky=self.ky
kx=self.kx
kz=self.kz
# note that, at alpha=0, k_rho remains the same in the slab, in agreement with Snell's law
with n... | Python | nomic_cornstack_python_v1 |
import itertools
function partition collection
begin
if length collection == 1
begin
yield list collection
return
end
set first = collection at 0
for smaller in call partition collection at slice 1 : :
begin
comment insert `first` in each of the subpartition's subsets
for tuple n subset in enumerate smaller
begin
yiel... | import itertools
def partition(collection):
if len(collection) == 1:
yield [ collection ]
return
first = collection[0]
for smaller in partition(collection[1:]):
# insert `first` in each of the subpartition's subsets
for n, subset in enumerate(smaller):
... | Python | zaydzuhri_stack_edu_python |
from lib.models import engine
class PopDb extends object
begin
function __init__ self clients
begin
set connection = call connect
set clients = clients
set events = list
end function
function set_events self
begin
for client in clients
begin
extend events call get_events
end
return self
end function
function insert_ev... | from lib.models import engine
class PopDb(object):
def __init__(self, clients):
self.connection = engine.connect()
self.clients = clients
self.events = []
def set_events(self):
for client in self.clients:
self.events.extend(client.get_events())
return self
... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python
from wsgiref.simple_server import make_server
string This is the application
function application environ start_response
begin
set response_body = list comprehension string %s : %s % tuple key value for tuple key value in sorted items environ
set response_body = join string response_body
... | #! /usr/bin/env python
from wsgiref.simple_server import make_server
'''
This is the application
'''
def application(environ, start_response):
response_body = ['%s : %s' % (key, value) for key, value in sorted(environ.items()) ]
response_body = '\n'.join(response_body)
status = '200 OK'
res... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import requests
import sys
import time
import json
set API_KEY = string
function get_records url
begin
set resp = string
set status = 0
while status != 200
begin
set resp = get requests url
set status = status_code
sleep 2
end
return json resp
end function
function process_data key title... | #!/usr/bin/env python3
import requests
import sys
import time
import json
API_KEY = ""
def get_records(url):
resp = ''
status = 0
while status != 200:
resp = requests.get(url)
status = resp.status_code
time.sleep(2)
return resp.json()
def process_data(key, title):
... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import numpy as np
set tuple n m = map int split input
set beginning_inventory = 3
set lead_time = 2
set total_demand = 0
set ending_inventory = 0
set shortage_quantity = 0
set order_quantity = 8
set shortage_day = 0
seed 0
set ending_inventory_g = list
for cycle in range 10
begin
print... | import matplotlib.pyplot as plt
import numpy as np
n, m = map(int, input().split())
beginning_inventory = 3
lead_time = 2
total_demand = 0
ending_inventory = 0
shortage_quantity = 0
order_quantity = 8
shortage_day = 0
np.random.seed(0)
ending_inventory_g = []
for cycle in range(10):
print("Cycle nu... | Python | zaydzuhri_stack_edu_python |
import ast
import datetime
import os
comment returns a list with [who_is_playing ('R'/'C'), start_time, child selection, end_time, game result, number of moves, total time of game, who_is_playing, ...]
function get_headers
begin
return list string subject_id string player string start_time string selection string end_t... | import ast
import datetime
import os
# returns a list with [who_is_playing ('R'/'C'), start_time, child selection, end_time, game result, number of moves, total time of game, who_is_playing, ...]
def get_headers():
return ['subject_id', 'player', 'start_time', 'selection', 'end_time', 'result', '#moves', 'total_g... | Python | zaydzuhri_stack_edu_python |
function _eight_byte_real_to_float value
begin
set tuple short1 short2 long3 = call unpack string >HHL value
set exponent = short1 ? 32512 // 256 - 64
set mantissa = short1 ? 255 * 65536 + short2 * 4294967296 + long3 / 7.205759403792794e+16
if short1 ? 32768
begin
return - mantissa * 16.0 ^ exponent
end
return mantissa... | def _eight_byte_real_to_float(value):
short1, short2, long3 = struct.unpack('>HHL', value)
exponent = (short1 & 0x7f00) // 256 - 64
mantissa = (((short1 & 0x00ff) * 65536 + short2) * 4294967296 +
long3) / 72057594037927936.0
if short1 & 0x8000:
return -mantissa * 16.**exponent
... | Python | nomic_cornstack_python_v1 |
comment A simple python script
print string Hello, World! | # A simple python script
print("Hello, World!") | Python | jtatman_500k |
comment def outer():
comment x = 1
comment b = 2
comment def inner():
comment return x + b # 1
comment return inner
comment foo = outer()
comment print foo()
comment def test(x,y,*args):
comment print x,y,args
comment test(1,2,3,4,5,6)
comment Arguments can be passed into functions as follows.
comment if they are passe... | # def outer():
# x = 1
# b = 2
# def inner():
# return x + b # 1
# return inner
#
#
# foo = outer()
# print foo()
# def test(x,y,*args):
# print x,y,args
#
# test(1,2,3,4,5,6)
# Arguments can be passed into functions as follows.
# if they are passed in as *lst they will be unpacket appro... | Python | zaydzuhri_stack_edu_python |
function max_contig_sum L
begin
import itertools
set max = L at 0
set max_list = list
for i in range length L
begin
for j in range i length L + 1
begin
if i == j
begin
if L at i > max
begin
set max = L at i
end
end
else
begin
set tot = sum L at slice i : j :
if tot > max
begin
set max = tot
end
end
end
end
return max
... | def max_contig_sum(L):
import itertools
max = L[0]
max_list = []
for i in range(len(L)):
for j in range(i,len(L)+1):
if i == j:
if L[i] > max:
max = L[i]
else:
tot = sum(L[i:j])
if tot > max:
... | Python | nomic_cornstack_python_v1 |
function see_organic_red_growth
begin
with open string Barnabys_sales_fabriacted_data_copy.csv as file
begin
set csv_reader = reader file
set data_year = list
for row in csv_reader
begin
comment joins data from data an quantity ordered
append data_year row at 8
end
set list_data_sells = list data_year
end
set year_orga... | def see_organic_red_growth():
with open("Barnabys_sales_fabriacted_data_copy.csv") as file:
csv_reader = csv.reader(file)
data_year = list()
for row in csv_reader:
# joins data from data an quantity ordered
data_year.append((row[8]))
list_data_sells = list(dat... | Python | nomic_cornstack_python_v1 |
comment The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left:
comment 3797, 379, 37, and 3.
comment Find the sum of the only eleven primes that are ... | # The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left:
# 3797, 379, 37, and 3.
# Find the sum of the only eleven primes that are both truncatable... | Python | zaydzuhri_stack_edu_python |
import socket
comment create a socket object
set s = call socket
comment get local machine name
set host = call gethostname
comment reserve the port for client service
set port = 60667
comment bind to the port
call connect tuple host port
comment Now wait for client connection
call listen 5 | import socket
s = socket.socket() #create a socket object
host = socket.gethostname() #get local machine name
port = 60667 #reserve the port for client service
s.connect((host,port)) #bind to the port
s.listen(5) #Now wait for client connection | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import sys
import re
function get_correspondence filename
begin
set to_return = dict
set regex = compile string ^c ([0-9]+): \(([0-9]+), ([0-9]+)\) is a ([0-9]+)
with open filename as f
begin
for line in f
begin
set maybe = match line
if maybe
begin
set to_return at integer maybe at 1 = d... | #!/usr/bin/env python3
import sys
import re
def get_correspondence(filename):
to_return = {}
regex = re.compile(r'^c ([0-9]+): \(([0-9]+), ([0-9]+)\) is a ([0-9]+)')
with open(filename) as f:
for line in f:
maybe = regex.match(line)
if maybe:
to_return[int(... | Python | zaydzuhri_stack_edu_python |
class Stack
begin
function __init__ self
begin
set items = list
end function
function push self item
begin
append items item
end function
function pop self
begin
return pop items
end function
function isEmpty self
begin
return items == list
end function
end class | class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def isEmpty(self):
return self.items == [] | Python | jtatman_500k |
function sanity_check_step self
begin
comment selection of libraries
set libs = list string Amesos string Anasazi string AztecOO string Belos string Epetra string EpetraExt string Galeri string Ifpack string Intrepid string Isorropia string Kokkos string Komplex string LOCA string ML string Moertel string NOX string Pa... | def sanity_check_step(self):
# selection of libraries
libs = ["Amesos", "Anasazi", "AztecOO", "Belos", "Epetra", "EpetraExt", "Galeri",
"Ifpack", "Intrepid", "Isorropia", "Kokkos",
"Komplex", "LOCA", "ML", "Moertel", "NOX",
"Pamgen", "PyTrilinos", "RTOp",... | Python | nomic_cornstack_python_v1 |
from colordescriptor import ColorDescriptor
from searcher import Searcher
import argparse
import cv2
comment Construct the arguments parser and pars the arguments
set argParser = call ArgumentParser
call add_argument string -i string --index required=true help=string Path to the index file
call add_argument string -q s... | from colordescriptor import ColorDescriptor
from searcher import Searcher
import argparse
import cv2
# Construct the arguments parser and pars the arguments
argParser = argparse.ArgumentParser()
argParser.add_argument("-i", "--index", required=True,
help="Path to the index file")
argParser.add_argument("-q", "--qu... | Python | zaydzuhri_stack_edu_python |
from nose.tools import assert_equal
class Solution
begin
comment @param A, a list of integer
comment @return an integer
function singleNumber self A
begin
string An explanation to the Solutions can be found at: https://oj.leetcode.com/discuss/857/constant-space-solution.
comment return self._solve1(A)
comment return se... | from nose.tools import assert_equal
class Solution:
# @param A, a list of integer
# @return an integer
def singleNumber(self, A):
"""
An explanation to the Solutions can be found at:
https://oj.leetcode.com/discuss/857/constant-space-solution.
"""
#return self._solve... | Python | zaydzuhri_stack_edu_python |
from production import AND , OR , NOT , PASS , FAIL , IF , THEN , match , populate , simplify , variables
from zookeeper import ZOOKEEPER_RULES
comment This function, which you need to write, takes in a hypothesis
comment that can be determined using a set of rules, and outputs a goal
comment tree of which statements i... | from production import AND, OR, NOT, PASS, FAIL, IF, THEN, \
match, populate, simplify, variables
from zookeeper import ZOOKEEPER_RULES
# This function, which you need to write, takes in a hypothesis
# that can be determined using a set of rules, and outputs a goal
# tree of which statements it would need to test... | Python | zaydzuhri_stack_edu_python |
function post_process_labels labels orig_img_sizes cfg
begin
set labels = call numpy
set processed_labels = list
for tuple i label in enumerate labels
begin
comment Remove label padding
set label = label at absolute sum axis=1 != 0.0
set label = call standardize_labels label image_size image_size
set orig_img_size = o... | def post_process_labels(labels: torch.Tensor, orig_img_sizes: torch.Tensor, cfg: CfgNode) -> List[np.array]:
labels = labels.detach().numpy()
processed_labels = []
for i, label in enumerate(labels):
# Remove label padding
label = label[np.abs(label.sum(axis=1)) != 0.]
label = stand... | Python | nomic_cornstack_python_v1 |
function progressRange start stop=none step=1 message=string updateRate=1
begin
comment mimic behavior of built in range
if stop is none
begin
set stop = start
set start = 0
end
with call trackProgress stop - start message updateRate as pbar
begin
for cur in range start stop step
begin
yield cur
comment advance only u... | def progressRange(start, stop=None, step=1, message="", updateRate=1):
# mimic behavior of built in range
if stop is None:
stop = start
start = 0
with trackProgress(stop-start, message, updateRate) as pbar:
for cur in range(start, stop, step):
yield cur
# ad... | Python | nomic_cornstack_python_v1 |
function relative_matmul x z transpose
begin
set batch_size = shape at 0
set heads = shape at 1
set length = shape at 2
set x_t = permute x 2 0 1 3
set x_t_r = reshape x_t length heads * batch_size - 1
if transpose
begin
set z_t = transpose z 1 2
set x_tz_matmul = matrix multiply x_t_r z_t
end
else
begin
set x_tz_matmu... | def relative_matmul(x, z, transpose):
batch_size = x.shape[0]
heads = x.shape[1]
length = x.shape[2]
x_t = x.permute(2, 0, 1, 3)
x_t_r = x_t.reshape(length, heads * batch_size, -1)
if transpose:
z_t = z.transpose(1, 2)
x_tz_matmul = torch.matmul(x_t_r, z_t)
else:
x_tz... | Python | nomic_cornstack_python_v1 |
function update_outputs_recon self new
begin
call define_inspect_outputs
end function | def update_outputs_recon(self, new):
self.stages["Diffusion"].define_inspect_outputs() | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
class K_means
begin
function __init__ self
begin
set classifier = none
set category = none
set data = none
comment cooresponding to centers
set n_clusters = 3
set iter_times = 300
end function
f... | import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
class K_means:
def __init__(self):
self.classifier = None
self.category = None
self.data = None
self.n_clusters = 3 # cooresponding to centers
... | Python | zaydzuhri_stack_edu_python |
function run_installer self
begin
call set_mirrorlist self
call install_base_system self
call create_fstab self
call set_timezone self
call set_locales self
call set_virtual_console self
call set_hostname_file self
call set_root_passwd self
call create_user self
call install_network self
call install_grub_bootloader se... | def run_installer(self):
set_mirrorlist(self)
install_base_system(self)
create_fstab(self)
set_timezone(self)
set_locales(self)
set_virtual_console(self)
set_hostname_file(self)
set_root_passwd(self)
create_user(self)
install_network(self)
install_grub_bootloader(self)
in... | Python | nomic_cornstack_python_v1 |
from datetime import datetime
function calculate_rank user_ratings submission_dates num_views num_comments user_reputation
begin
set weights = dict string ratings 0.4 ; string date 0.3 ; string views 0.2 ; string comments 0.1 ; string reputation 0.05
set scores = list
comment Calculate scores for each submission
for i... | from datetime import datetime
def calculate_rank(user_ratings, submission_dates, num_views, num_comments, user_reputation):
weights = {
'ratings': 0.4,
'date': 0.3,
'views': 0.2,
'comments': 0.1,
'reputation': 0.05
}
scores = []
# Calculate scores for e... | Python | greatdarklord_python_dataset |
from Downloader import getURL , getFileName , getSavePath , download
from datetime import datetime
from dateutil.relativedelta import relativedelta
import freezegun
import os
import pathlib
import unittest
set now = now
set lastmonth = now - call relativedelta months=1
function removeOutputfile filepath
begin
string [s... | from Downloader import getURL, getFileName, getSavePath, download
from datetime import datetime
from dateutil.relativedelta import relativedelta
import freezegun
import os
import pathlib
import unittest
now = datetime.now()
lastmonth = now - relativedelta(months=1)
def removeOutputfile(filepath: str):
"""[summar... | Python | zaydzuhri_stack_edu_python |
from matplotlib import pyplot as plt
function plot X y
begin
set m = length y
set xpos = list
set xneg = list
for i in range m
begin
if y at i == 1.0
begin
append xpos list X at i at 0 X at i at 1
end
else
begin
append xneg list X at i at 0 X at i at 1
end
end
figure 1
axis list 30 100 30 100
plot list comprehension ... | from matplotlib import pyplot as plt
def plot(X,y):
m=len(y)
xpos=[]
xneg=[]
for i in range(m):
if y[i]==1.0:
xpos.append([X[i][0], X[i][1]])
else:
xneg.append([X[i][0], X[i][1]])
plt.figure(1)
plt.axis([30,100,30,100])
plt.plot([x[0] for x in xpos], [x[1] for x in xpos], linestyle='', marker='.', co... | Python | zaydzuhri_stack_edu_python |
string Two pointers. 1. max[seen]: the number of the most frequent chars within s[left:right+1] 2. Move left pointer right when right - left + 1 - m > k, because more than k chars need to be replaced to make s[left:right+1] is repeating of single char.
class Solution
begin
function characterReplacement self s k
begin
c... | '''
Two pointers.
1. max[seen]: the number of the most frequent chars within s[left:right+1]
2. Move left pointer right when right - left + 1 - m > k, because more than k chars need to be replaced to make s[left:right+1] is repeating of single char.
'''
class Solution:
def characterReplacement(self, s: st... | Python | zaydzuhri_stack_edu_python |
from typing import List
class Solution
begin
function coinChange self coins amount
begin
set dp = list comprehension decimal string inf for _ in range amount + 1
set dp at 0 = 0
for i in range 1 amount + 1
begin
for j in coins
begin
if i - j >= 0
begin
set dp at i = min dp at i - j dp at i
end
end
set dp at i = dp at i... | from typing import List
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [float('inf') for _ in range(amount+1)]
dp[0] = 0
for i in range(1, amount+1):
for j in coins:
if i - j >= 0:
dp[i] = min(dp[i-j], dp[i])
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
import sys
import binascii
set dna = dict string A string 00 ; string C string 01 ; string G string 10 ; string T string 11
set binary = string
for letter in argv at 1
begin
set binary = binary + dna at letter
end
print string binary: binary
print string decimal: integer binary 2
print string... | #!/usr/bin/python3
import sys
import binascii
dna = {'A': '00', 'C': '01', 'G': '10', 'T': '11'}
binary = ''
for letter in sys.argv[1]:
binary += dna[letter]
print('binary:', binary)
print('decimal:', int(binary, 2))
print('hex:', hex(int(binary, 2))[2:])
| Python | zaydzuhri_stack_edu_python |
function reset_store self store_name=string ooi store_id=string ooi
begin
try
begin
set url = join string list importer_service_url string /service=resetstore&name= store_name string &id= store_id
set r = post url
if status_code == 200
begin
return true
end
else
begin
return false
end
end
except Exception as e
begin
e... | def reset_store(self, store_name='ooi', store_id='ooi'):
try:
url = ''.join([self.importer_service_url, '/service=resetstore&name=', store_name, '&id=', store_id])
r = requests.post(url)
if r.status_code == 200:
return True
else:
re... | Python | nomic_cornstack_python_v1 |
function last_modified_by self
begin
return get pulumi self string last_modified_by
end function | def last_modified_by(self) -> Optional[str]:
return pulumi.get(self, "last_modified_by") | Python | nomic_cornstack_python_v1 |
import timeit
function method0 maxVal
begin
set result = 0
set term0 = 1
set term1 = 1
while term1 <= maxVal
begin
if term1 % 2 == 0
begin
set result = result + term1
end
set term1 = term1 + term0
set term0 = term1 - term0
end
return result
end function
function method1 maxVal
begin
set a = 2
set b = 8
set c = 34
set r... | import timeit
def method0(maxVal):
result = 0
term0 = 1
term1 = 1
while term1 <= maxVal:
if term1 % 2 == 0:
result += term1
term1 += term0
term0 = term1 - term0
return result
def method1(maxVal):
a = 2
b = 8
c = 34
result = a+b
while c <= ma... | Python | zaydzuhri_stack_edu_python |
async function set_chat_title self chat_id title read_timeout=DEFAULT_NONE write_timeout=DEFAULT_NONE connect_timeout=DEFAULT_NONE pool_timeout=DEFAULT_NONE api_kwargs=none
begin
set data : JSONDict = dict string chat_id chat_id ; string title title
return await call _post string setChatTitle data read_timeout=read_tim... | async def set_chat_title(
self,
chat_id: Union[str, int],
title: str,
*,
read_timeout: ODVInput[float] = DEFAULT_NONE,
write_timeout: ODVInput[float] = DEFAULT_NONE,
connect_timeout: ODVInput[float] = DEFAULT_NONE,
pool_timeout: ODVInput[float] = DEFAULT_N... | Python | nomic_cornstack_python_v1 |
comment -*-coding:utf-8-*-
import torch
from torch.autograd import Variable
set tensor = call FloatTensor list list 1 2 list 3 4
comment 把tensor放到varbiable
set variable = call Variable tensor requires_grad=true
comment 通过variable搭建计算图纸,误差反向传播通过variable反向传播,requires_grad表示是不是要进行反向传播的计算
comment x^2
set t_out = mean torch... | # -*-coding:utf-8-*-
import torch
from torch.autograd import Variable
tensor = torch.FloatTensor([[1, 2], [3, 4]])
variable = Variable(tensor, requires_grad=True) #把tensor放到varbiable
#通过variable搭建计算图纸,误差反向传播通过variable反向传播,requires_grad表示是不是要进行反向传播的计算
t_out = torch.mean(tensor*tensor) # x^2
v_out = torch.mean(variab... | Python | zaydzuhri_stack_edu_python |
function read_sheet_by_index self sheet_index
begin
set tables = call make_tables
set length = length tables
if sheet_index < length
begin
return call read_sheet tables at sheet_index
end
else
begin
raise call IndexError string Index %d of out bound %d % tuple sheet_index length
end
end function | def read_sheet_by_index(self, sheet_index):
tables = self._native_book.make_tables()
length = len(tables)
if sheet_index < length:
return self.read_sheet(tables[sheet_index])
else:
raise IndexError("Index %d of out bound %d" % (
sheet_index, length... | Python | nomic_cornstack_python_v1 |
import itertools
import xlrd
import pandas as pd
comment 读取Excel文件内容
comment input = input("Inpurt you file:")
comment data = xlrd.open_workbook(input)
set data = call open_workbook string D:/Document/WeChat Files/hsfbhao539/Files/1.5作者.xlsx
set table = call sheets at 0
set nrows = nrows
comment 初始化写入文件行坐标
set row = 0
... | import itertools
import xlrd
import pandas as pd
# 读取Excel文件内容
# input = input("Inpurt you file:")
# data = xlrd.open_workbook(input)
data = xlrd.open_workbook("D:/Document/WeChat Files/hsfbhao539/Files/1.5作者.xlsx")
table = data.sheets()[0]
nrows = table.nrows
# 初始化写入文件行坐标
row = 0
print("CSV文件写入中...")
record = []
f... | Python | zaydzuhri_stack_edu_python |
function Offset2 thisCurve directionPoint normal distance tolerance angleTolerance loose cornerStyle endStyle multiple=false
begin
set url = string rhino/geometry/curve/offset-curve_point3d_vector3d_double_double_double_bool_curveoffsetcornerstyle_curveoffsetendstyle
if multiple
begin
set url = url + string ?multiple=t... | def Offset2(thisCurve, directionPoint, normal, distance, tolerance, angleTolerance, loose, cornerStyle, endStyle, multiple=False):
url = "rhino/geometry/curve/offset-curve_point3d_vector3d_double_double_double_bool_curveoffsetcornerstyle_curveoffsetendstyle"
if multiple: url += "?multiple=true"
args = [this... | Python | nomic_cornstack_python_v1 |
comment 단방향 연결리스트 ###
comment 노드 클래스
class _Node
begin
function __init__ self element=none next=none
begin
comment 노드에 저장되는 element 값
set _element = element
comment 다음 노드로의 링크 (초기값은 None)
set _next = next
end function
function __str__ self
begin
comment 출력 문자열 (print(node)에서 사용)
return string _element
end function
end ... | ### 단방향 연결리스트 ###
# 노드 클래스
class _Node:
def __init__(self, element=None, next=None):
self._element = element # 노드에 저장되는 element 값
self._next = next # 다음 노드로의 링크 (초기값은 None)
def __str__(self):
return str(self._element) # 출력 문자열 (print(node)에서 사용)
# 클래스 선언
class SinglyLinkedList:
def __init__(self):... | Python | zaydzuhri_stack_edu_python |
function remove_melds player_hand all_melds
begin
set remains = sum values player_hand
set melds = list
for meld in all_melds
begin
while player_hand ? meld == meld
begin
set player_hand = player_hand - meld
set remains = remains - 3
append melds meld
if remains < 3
begin
break
end
end
if remains < 3
begin
break
end
e... | def remove_melds(player_hand: Counter, all_melds: Tuple) -> Tuple[Counter]:
remains = sum(player_hand.values())
melds = []
for meld in all_melds:
while player_hand & meld == meld:
player_hand -= meld
remains -= 3
melds.append(meld)
if remains < 3:
... | Python | nomic_cornstack_python_v1 |
comment string substitution
comment or substitution
comment the old way
comment $ is the substitution sign (to be inserted soon)
set my_string = string I like %s % string Python
comment I like Python
print my_string
set var = string cookies
set newString = string I like %s % var
newString
comment I like cookies
print n... | # string substitution
# or substitution
# the old way
# $ is the substitution sign (to be inserted soon)
my_string = "I like %s" % "Python"
print( my_string) #I like Python
var = "cookies"
newString = "I like %s" % var
newString
print(newString) #I like cookies
another_string = "I like %s and %s" % ("Python", var)
p... | Python | zaydzuhri_stack_edu_python |
function create_waypoints_from_path path max_number rotation gimbal
begin
if path is none
begin
raise call ValueError string Parameter line required
end
if not is instance gimbal Gimbal
begin
raise call ValueError string Parameter gimbal have to be a Gimbal
end
set rotation = decimal rotation
set max_number = integer m... | def create_waypoints_from_path(path, max_number, rotation, gimbal):
if path is None:
raise ValueError('Parameter line required')
if not isinstance(gimbal, Gimbal):
raise ValueError('Parameter gimbal have to be a Gimbal')
rotation = float(rotation)
max_number = int(max_number)
resu... | Python | nomic_cornstack_python_v1 |
function getTender self
begin
return _Tender
end function | def getTender(self):
return self._Tender | Python | nomic_cornstack_python_v1 |
import sys
set tuple n s = map int split read line stdin
if n * 2 <= s
begin
print string YES
set st = 1
set ans = list
while st < n
begin
print 2 end=string
set st = st + 1
end
print s - n - 1 * 2
print 1
end
else
begin
print string NO
end | import sys
n,s=map(int,sys.stdin.readline().split())
if(n*2<=s):
print('YES')
st=1
ans=[]
while(st<n):
print(2,end=' ')
st+=1
print(s-(n-1)*2)
print(1)
else:
print('NO')
| Python | zaydzuhri_stack_edu_python |
function calc_midpt self p1 p2
begin
set midpt = list p1 at 0 + p2 at 0 // 2 p1 at 1 + p2 at 1 // 2
return midpt
end function | def calc_midpt(self, p1, p2):
midpt = [(p1[0] + p2[0]) // 2, (p1[1] + p2[1]) //2]
return midpt | Python | nomic_cornstack_python_v1 |
function open uri mode=string r key=none attr=none config=none timestamp=none ctx=none
begin
return call load_typed uri mode=mode key=key timestamp=timestamp attr=attr ctx=call _get_ctx ctx config
end function | def open(uri, mode="r", key=None, attr=None, config=None, timestamp=None, ctx=None):
return tiledb.Array.load_typed(
uri,
mode=mode,
key=key,
timestamp=timestamp,
attr=attr,
ctx=_get_ctx(ctx, config),
) | Python | nomic_cornstack_python_v1 |
function write self
begin
return call _write_complex_object _defaults _values
end function | def write(self):
return _write_complex_object(self._defaults, self._values) | Python | nomic_cornstack_python_v1 |
import cs50
import sys
set key = integer argv at 1
set plaintext = string input string plaintext:
print string ciphertext: end=string
for i in plaintext
begin
set number = ordinal i
if number >= 65 and number <= 90 or number >= 97 and number <= 122
begin
set lower = 0
if is lower i
begin
set number = number - 32
set lo... | import cs50
import sys
key = int(sys.argv[1])
plaintext = str(input('plaintext: '))
print("ciphertext: ", end ='')
for i in plaintext:
number = ord(i)
if (number>=65 and number<=90)or(number>=97 and number<=122):
lower = 0
if i.islower():
number = number - 32
lower = 1... | Python | zaydzuhri_stack_edu_python |
import requests
set url_provinsi = string http://raw.githubusercontent.com/LintangWisesa/Ujian_Fundamental_JCDS08/master/data/provinsi.json
set url_kodepos = string http://raw.githubusercontent.com/LintangWisesa/Ujian_Fundamental_JCDS08/master/data/kodepos.json
set data_provinsi = get requests url_provinsi
set data_kod... | import requests
url_provinsi = 'http://raw.githubusercontent.com/LintangWisesa/Ujian_Fundamental_JCDS08/master/data/provinsi.json'
url_kodepos = 'http://raw.githubusercontent.com/LintangWisesa/Ujian_Fundamental_JCDS08/master/data/kodepos.json'
data_provinsi = requests.get(url_provinsi)
data_kodepos = requests.get(url_k... | Python | zaydzuhri_stack_edu_python |
from math import inf
function nextElement arr right=true greater=true
begin
string return the array of next smaller/bigger element to the left/right
set N = length arr
set iterable = if expression right then range N - 1 - 1 - 1 else range 0 N 1
set checker = if expression greater then lambda a b -> a <= b else lambda a... | from math import inf
def nextElement(arr, right=True, greater=True):
""" return the array of next smaller/bigger element to the left/right """
N = len(arr)
iterable = range(N-1,-1,-1) if right else range(0,N,1)
checker = (lambda a,b: a <= b) if greater else (lambda a,b: a >= b)
output, stack = [-1]... | Python | zaydzuhri_stack_edu_python |
comment https://colah.github.io/posts/2015-08-Understanding-LSTMs/
import torch
import torch.nn as nn
comment PARAMETERS
set input_dim = 1
set hidden_layer_size = 2
set num_layers = 1
set output_dim = 1
comment Esto no es necesario aqui
set num_of_epochs = 2000
set display_step = 100
set learning_rate = 0.01
comment MO... | #https://colah.github.io/posts/2015-08-Understanding-LSTMs/
import torch
import torch.nn as nn
#PARAMETERS
input_dim = 1;
hidden_layer_size = 2
num_layers = 1
output_dim = 1
# Esto no es necesario aqui
num_of_epochs = 2000
display_step = 100
learning_rate = 0.01
#MODEL
class LSTM(nn.Module):
def... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
from os import path
import io , operator , json
import matplotlib
import matplotlib.pyplot as plt
from wordcloud import WordCloud , STOPWORDS
import jieba
import datetime
function rank_query filename
begin
set query = dict
set stopw = set list comprehension decode strip line string utf-8 ... | # -*- coding: utf-8 -*-
from os import path
import io, operator, json
import matplotlib
import matplotlib.pyplot as plt
from wordcloud import WordCloud,STOPWORDS
import jieba
import datetime
def rank_query(filename):
query = {}
stopw = set([line.strip().decode('utf-8') for line in open('stopwords.txt').readl... | Python | zaydzuhri_stack_edu_python |
function findAll wordList lStr
begin
set result = list
for w in wordList
begin
set wordcopy = w at slice : :
set strcopy = lStr at slice : :
for c in wordcopy
begin
if c in strcopy
begin
replace wordcopy c string
replace strcopy c string
end
end
end
end function | def findAll(wordList, lStr):
result = []
for w in wordList:
wordcopy = w[:]
strcopy = lStr[:]
for c in wordcopy:
if c in strcopy:
wordcopy.replace(c, '')
strcopy.replace(c, '') | Python | zaydzuhri_stack_edu_python |
comment sum: 1 to 10 (or any number)
set i = 1
set total = 0
while i <= 10
begin
comment total = total + 1
set total = total + i
set i = i + 1
end
print total | # sum: 1 to 10 (or any number)
i = 1
total = 0
while i <= 10:
total += i # total = total + 1
i += 1
print(total) | Python | zaydzuhri_stack_edu_python |
import re
set f = open string error.log string r
set error_log = read lines f
close f
for error in error_log
begin
set error_file = find all string ^(.*)Traceback \(most recent call last\):$ error
end | import re
f = open('error.log','r')
error_log = f.readlines()
f.close()
for error in error_log:
error_file = re.findall('^(.*)Traceback \(most recent call last\):$',error) | Python | zaydzuhri_stack_edu_python |
async function exec_dss req resp
begin
info string got a request for executing a dss
set media = await call media string files
debug string %s string media
set params = loads media at string input at string content
if string model_name in media
begin
set params at string model_run at string model_name = decode media at... | async def exec_dss(req, resp):
logger.info("got a request for executing a dss")
media = await req.media('files')
logger.debug("%s", str(media))
params = json.loads(media['input']['content'])
if 'model_name' in media:
params['model_run']['model_name'] = media['model_name'].decode()
exec_... | Python | nomic_cornstack_python_v1 |
function sphere self center radius texture
begin
append _objects call Sphere center radius texture
end function | def sphere(self, center, radius, texture):
self._objects.append(Sphere(center, radius, texture)) | Python | nomic_cornstack_python_v1 |
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 |
function ICreateSplinesByEqnParams self PropArray=defaultNamedNotOptArg KnotsArray=defaultNamedNotOptArg CntrlPntCoordArray=defaultNamedNotOptArg
begin
set ret = call InvokeTypes 66099 LCID 1 tuple 13 0 tuple tuple 16387 1 tuple 16389 1 tuple 16389 1 PropArray KnotsArray CntrlPntCoordArray
if ret is not none
begin
comm... | def ICreateSplinesByEqnParams(self, PropArray=defaultNamedNotOptArg, KnotsArray=defaultNamedNotOptArg, CntrlPntCoordArray=defaultNamedNotOptArg):
ret = self._oleobj_.InvokeTypes(66099, LCID, 1, (13, 0), ((16387, 1), (16389, 1), (16389, 1)),PropArray
, KnotsArray, CntrlPntCoordArray)
if ret is not None:
# See ... | Python | nomic_cornstack_python_v1 |
function _get_wifi_status_code self
begin
return call get_object_property proxy=proxy prop_name=wifi_prop
end function | def _get_wifi_status_code(self):
return self.get_object_property(
proxy=self.proxy,
prop_name=self.wifi_prop
) | Python | nomic_cornstack_python_v1 |
function vals self values=none params=none
begin
if params is none
begin
set params = params
end
if values is none
begin
return array list comprehension get attribute self par for par in params
end
else
if is instance values Mapping
begin
for par in values
begin
set attribute self par values at par
end
end
else
if is i... | def vals(self, values=None, params=None):
if params is None:
params = self.params
if values is None:
return np.array([getattr(self, par) for par in params])
elif isinstance(values, collections.Mapping):
for par in values:
setattr(self, par, val... | Python | nomic_cornstack_python_v1 |
comment Enoncé : Créez une fonction qui ne prend pas d'arguments. Lorsqu'elle est appelée, cette fonction dit
comment Hello World !
comment region indice
comment Pour créer une fonction en Python, on utilise le mot def suivi du nom de la fonction
comment suivi d'un couple de parenthèse avec dedans les potentiels argume... | # Enoncé : Créez une fonction qui ne prend pas d'arguments. Lorsqu'elle est appelée, cette fonction dit
# Hello World !
#region indice
# Pour créer une fonction en Python, on utilise le mot def suivi du nom de la fonction
# suivi d'un couple de parenthèse avec dedans les potentiels arguments
# Suivi du signe deux po... | Python | zaydzuhri_stack_edu_python |
comment WGU C964 Capstone Project
comment Equipment Faults in Manufacturing Environments
comment Sean Naramor
comment July 23, 2021
comment This function was used to parse the vast amount of files that contained our data
function parse_data
begin
import os
import pandas as pd
set path = directory name path __file__ + s... | #
# WGU C964 Capstone Project
# Equipment Faults in Manufacturing Environments
# Sean Naramor
# July 23, 2021
#
####################################
# This function was used to parse the vast amount of files that contained our data
####################################
def parse_data():
import os
import pandas a... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
from tkinter import filedialog
import tensorflow as tf
import numpy as np
import cv2
comment Creating a tkinter gui window
set root = call Tk
call config background=string #A9CCE3
title root string HCR
call iconbitmap string C:/Users/Ashwini/PycharmProjects/deep/guihcr/iconfinder_Ocr S_38896.ico
c... | from tkinter import *
from tkinter import filedialog
import tensorflow as tf
import numpy as np
import cv2
#Creating a tkinter gui window
root = Tk()
root.config(background="#A9CCE3")
root.title("HCR")
root.iconbitmap(r"C:/Users/Ashwini/PycharmProjects/deep/guihcr/iconfinder_Ocr S_38896.ico")
#Defining our recogniz... | Python | zaydzuhri_stack_edu_python |
function add_paho_logging_hook device_client log_func=print
begin
set paho = call get_paho_from_device_client device_client
for name in PAHO_FUNCTIONS_TO_HOOK
begin
call add_logging_hook obj=paho func_name=name log_func=log_func module_name=string Paho log_args=PAHO_FUNCTIONS_TO_HOOK at name
end
end function | def add_paho_logging_hook(device_client, log_func=print):
paho = logging_hook.get_paho_from_device_client(device_client)
for name in PAHO_FUNCTIONS_TO_HOOK:
logging_hook.add_logging_hook(
obj=paho,
func_name=name,
log_func=log_func,
module_name="Paho",
... | Python | nomic_cornstack_python_v1 |
function test25 self
begin
set fname = call fixture_file string cpio_archive.cpio
set sio = call StringIO read open fname string r
set seek = none
set archive = call CpioArchive fobj=sio
comment get the second file in the archive
set archive_file = find archive string file1
assert is not none archive_file
assert equal ... | def test25(self):
fname = self.fixture_file('cpio_archive.cpio')
sio = StringIO(open(fname, 'r').read())
sio.seek = None
archive = CpioArchive(fobj=sio)
# get the second file in the archive
archive_file = archive.find('file1')
self.assertIsNotNone(archive_file)
... | 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.