code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function parse_tag file fp_TIFF IFD_offset tag
begin
comment every IFD starts with 2 bytes representing the number of entries it contains
seek file fp_TIFF + IFD_offset
set entries = call from_bytes read file 2 byte_order signed=false
comment every entry follows the format: 2 bytes: tag, 2 bytes: data type, 4 bytes: nu... | def parse_tag(file, fp_TIFF, IFD_offset, tag):
#every IFD starts with 2 bytes representing the number of entries it contains
file.seek(fp_TIFF + IFD_offset)
entries = int.from_bytes(file.read(2), byte_order, signed=False)
#every entry follows the format: 2 bytes: tag, 2 bytes: data type, 4 bytes: numb... | Python | nomic_cornstack_python_v1 |
comment create a dictionary
set pos = dict string colorless string ADJ ; string ideas string N ; string sleep string V ; string furiously string ADV
comment create a default dictionary with default value 'N'
import nltk
set pos = default dictionary lambda -> string N
set pos at string colorless = string ADJ
pos at str... | #create a dictionary
pos = {'colorless':'ADJ', 'ideas':'N', 'sleep':'V', 'furiously':'ADV'}
#create a default dictionary with default value 'N'
import nltk
pos = nltk.defaultdict(lambda: 'N')
pos['colorless'] = 'ADJ'
pos['blog']
pos.items()
#substitute low-frequent words with 'UNK'
alice = nltk.corpus.gutenberg.words... | Python | zaydzuhri_stack_edu_python |
function retrieve_cplex_mip_duals model
begin
from pyomo.solvers.plugins.solvers.CPLEX import CPLEXSHELL
set old_create_command_line = create_command_line
set logger = logger
function new_create_command_line *args **kwargs
begin
comment call original command
set command = call old_create_command_line *args keyword kwar... | def retrieve_cplex_mip_duals(model):
from pyomo.solvers.plugins.solvers.CPLEX import CPLEXSHELL
old_create_command_line = CPLEXSHELL.create_command_line
logger = model.logger
def new_create_command_line(*args, **kwargs):
# call original command
command = old_create_command_line(*args, ... | Python | nomic_cornstack_python_v1 |
function experience_replay self
begin
return
end function | def experience_replay(self):
return | Python | nomic_cornstack_python_v1 |
function zk_walk self root_path branch_path
begin
string skip ephemeral znodes since there's no point in copying those
set full_path = if expression branch_path then join path root_path branch_path else root_path
try
begin
set children = call get_children full_path
end
except NoNodeError
begin
set children = set
end
ex... | def zk_walk(self, root_path, branch_path):
"""
skip ephemeral znodes since there's no point in copying those
"""
full_path = os.path.join(root_path, branch_path) if branch_path else root_path
try:
children = self.client.get_children(full_path)
except NoNodeEr... | Python | jtatman_500k |
function get_bprop_batchnorm_fold2_ self
begin
set op_reduce = call BatchNormFold2GradReduce freeze_bn=freeze_bn
set op_f = call BatchNormFold2GradD freeze_bn=freeze_bn
function bprop x beta gamma batch_std batch_mean running_std out dout
begin
set tuple dout_reduce dout_x_reduce = call op_reduce dout x
set tuple d_bat... | def get_bprop_batchnorm_fold2_(self):
op_reduce = Q.BatchNormFold2GradReduce(freeze_bn=self.freeze_bn)
op_f = Q.BatchNormFold2GradD(freeze_bn=self.freeze_bn)
def bprop(x, beta, gamma, batch_std, batch_mean, running_std, out, dout):
dout_reduce, dout_x_reduce = op_reduce(dout, x)
d_batch_std... | Python | nomic_cornstack_python_v1 |
function _expm_multiply_interval_core_2 A X h mu m_star s q tol
begin
set d = q // s
set j = q // d
set r = q - d * j
set input_shape = shape at slice 1 : :
set K_shape = tuple m_star + 1 + input_shape
set K = call empty K_shape dtype=dtype
for i in range j + 1
begin
set Z = X at i * d
set K at 0 = Z
set high_p = 0
i... | def _expm_multiply_interval_core_2(A, X, h, mu, m_star, s, q, tol):
d = q // s
j = q // d
r = q - d * j
input_shape = X.shape[1:]
K_shape = (m_star + 1, ) + input_shape
K = np.empty(K_shape, dtype=X.dtype)
for i in range(j + 1):
Z = X[i*d]
K[0] = Z
high_p = 0
... | Python | nomic_cornstack_python_v1 |
function campaign_asset_set_path customer_id campaign_id asset_set_id
begin
return format string customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id} customer_id=customer_id campaign_id=campaign_id asset_set_id=asset_set_id
end function | def campaign_asset_set_path(
customer_id: str, campaign_id: str, asset_set_id: str,
) -> str:
return "customers/{customer_id}/campaignAssetSets/{campaign_id}~{asset_set_id}".format(
customer_id=customer_id,
campaign_id=campaign_id,
asset_set_id=asset_set_id,
... | Python | nomic_cornstack_python_v1 |
function _StreamStepDimensions self inputs
begin
set p = params
set tuple n h = tuple num_heads hidden_dim // num_heads
set s = inference_step_max_length + left_context - 1
set tuple b q = call GetShape inputs 2
return call NestedMap n=n h=h s=s b=b q=q
end function | def _StreamStepDimensions(self, inputs):
p = self.params
n, h = p.num_heads, p.hidden_dim // p.num_heads
s = p.inference_step_max_length + p.left_context - 1
b, q = py_utils.GetShape(inputs, 2)
return py_utils.NestedMap(n=n, h=h, s=s, b=b, q=q) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
string Test Driven Doc import Don't import using __import__
if __name__ == string __main__
begin
import doctest
call testfile string tests/4-print_square.txt
end
function print_square size
begin
string function that prints a square with the character #. Args: size: is the size length of the sq... | #!/usr/bin/python3
"""
Test Driven Doc import
Don't import using __import__
"""
if __name__ == "__main__":
import doctest
doctest.testfile("tests/4-print_square.txt")
def print_square(size):
"""
function that prints a square with the character #.
Args:
size: is the size length of the square
... | Python | zaydzuhri_stack_edu_python |
function __init__ self *args
begin
set this = call new_netnode *args
try
begin
append this this
end
except any
begin
set this = this
end
end function | def __init__(self, *args):
this = _idaapi.new_netnode(*args)
try: self.this.append(this)
except: self.this = this | Python | nomic_cornstack_python_v1 |
function setUp self
begin
set bitmap = call CompressedBitmap list true false false true 4
set un_bitmap = call CompressedBitmap list true false 5
set empty_bitmap = call CompressedBitmap list 0
end function | def setUp(self) -> None:
self.bitmap = CompressedBitmap([True, False, False, True], 4)
self.un_bitmap = CompressedBitmap([True, False], 5)
self.empty_bitmap = CompressedBitmap([], 0) | Python | nomic_cornstack_python_v1 |
comment На вход программе подается натуральное число n, а затем n строк. Напишите программу,
comment которая выводит только уникальные строки, в том же порядке, в котором они были введены.
set lst = list
for i in range integer input
begin
set a = input
if a not in lst
begin
append lst a
print a
end
end | #На вход программе подается натуральное число n, а затем n строк. Напишите программу,
#которая выводит только уникальные строки, в том же порядке, в котором они были введены.
lst = []
for i in range(int(input())):
a = input()
if a not in lst:
lst.append(a)
print(a)
| Python | zaydzuhri_stack_edu_python |
function sum_power power
begin
set max_dig = call find_limit power
set max_val = 9 ^ power * max_dig
end function | def sum_power(power):
max_dig = find_limit(power)
max_val = 9**power * max_dig | Python | nomic_cornstack_python_v1 |
class Evento
begin
function __init__ self nombreEvento fecha localidad provincia precioInscipcion
begin
set nombreEvento = nombreEvento
set fecha = fecha
set localidad = localidad
set provincia = provincia
set precioInscipcion = precioInscipcion
set totalAcumulado = 0
set listadoParticipantes = list
set finalizado = f... | class Evento:
def __init__(self,nombreEvento,fecha,localidad,provincia,precioInscipcion):
self.nombreEvento=nombreEvento
self.fecha=fecha
self.localidad=localidad
self.provincia=provincia
self.precioInscipcion=precioInscipcion
self.totalAcumulado=0
self.listad... | Python | zaydzuhri_stack_edu_python |
function find_hash text
begin
set line = find all string (?<=#)\w+ text
return join string line
end function | def find_hash(text):
line = re.findall(r'(?<=#)\w+', text)
return " ".join(line) | Python | nomic_cornstack_python_v1 |
string # 用于解决json中中文无法显示的问题 import json def trans(str): return eval(json.dumps(str, ensure_ascii=False)) test_html = trans(test_html) con_err = trans(con_err) sql_err_tem = trans(sql_err_tem) db_err_tem = trans(db_err_tem) sql_err_uri = trans(sql_err_uri) db_err_uri = trans(db_err_uri) para_err_tem = trans(para_err_tem... | '''
# 用于解决json中中文无法显示的问题
import json
def trans(str):
return eval(json.dumps(str, ensure_ascii=False))
test_html = trans(test_html)
con_err = trans(con_err)
sql_err_tem = trans(sql_err_tem)
db_err_tem = trans(db_err_tem)
sql_err_uri = trans(sql_err_uri)
db_err_uri = trans(db_err_uri)
para_err_tem = trans(para_err_tem... | Python | zaydzuhri_stack_edu_python |
function cosh self
begin
return call ViewExpression dict string $cosh self
end function | def cosh(self):
return ViewExpression({"$cosh": self}) | Python | nomic_cornstack_python_v1 |
class Solution
begin
function kWeakestRows self mat k
begin
set tem = list comprehension i for i in range length mat
sort tem key=lambda x -> mat at x
return tem at slice : k :
end function
end class | class Solution:
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
tem = [i for i in range(len(mat))]
tem.sort(key = lambda x:mat[x])
return tem[:k] | Python | zaydzuhri_stack_edu_python |
function compose_after_from_vector_inplace self delta
begin
set model_jacobian = jacobian
set points = points
set n_points = n_points
comment compute:
comment -> dW/dp when p=0
comment -> dW/dp when p!=0
comment -> dW/dx when p!=0 evaluated at the source landmarks
comment dW/dp when p=0 and when p!=0 are the same and s... | def compose_after_from_vector_inplace(self, delta):
model_jacobian = self.pdm.model.jacobian
points = self.pdm.model.mean.points
n_points = self.pdm.model.mean.n_points
# compute:
# -> dW/dp when p=0
# -> dW/dp when p!=0
# -> dW/dx when p!=0 evaluated at the sour... | Python | nomic_cornstack_python_v1 |
function normalized self
begin
return call DualQuaternion call normalized q_d
end function | def normalized(self):
return DualQuaternion(self.q_r.normalized(), self.q_d) | Python | nomic_cornstack_python_v1 |
function data self
begin
call _get_latest_content
return get _data string data dict
end function | def data(self):
self._get_latest_content()
return self._data.get('data', {}) | Python | nomic_cornstack_python_v1 |
function target_temperature self
begin
return _target_temperature
end function | def target_temperature(self):
return self._target_temperature | Python | nomic_cornstack_python_v1 |
from tkinter import *
class myBut
begin
function __init__ self master
begin
set frame = call Frame master
call pack
set printBut = call Button frame text=string Print command=printMsg
call pack side=LEFT
set quitBut = call Button frame text=string Quit command=quit
call pack side=LEFT
end function
function printMsg sel... | from tkinter import *
class myBut:
def __init__(self,master):
frame=Frame(master)
frame.pack()
self.printBut = Button(frame,text="Print",command=self.printMsg)
self.printBut.pack(side=LEFT)
self.quitBut = Button(frame,text="Quit",command=frame.quit)
self.quitBut.pa... | Python | zaydzuhri_stack_edu_python |
from queue import *
function bfs A s t n
begin
set dist = list
set rank = list
for k in range n
begin
append dist 0
append rank string
end
set Mark = list
for j in range n
begin
append Mark 0
end
set Mark at s = 1
set Q = queue
put s
while call empty != true
begin
set v = get Q
for j in range 0 length A at v
begin
i... | from queue import *
def bfs(A,s,t,n):
dist=[]
rank=[]
for k in range(n):
dist.append(0)
rank.append('')
Mark=[]
for j in range(n):
Mark.append(0)
Mark[s]=1
Q=Queue()
Q.put(s)
while Q.empty()!=True:
v=Q.get()
for j in range(0,len(A[v])):
... | Python | zaydzuhri_stack_edu_python |
async function _get_already_saved_range self symbol md_type
begin
set table_name = call _get_database_table_name md_type
set symbol_id = await call get_symbol_id symbol
set query = string SELECT min(ts), max(ts) FROM { table_name } WHERE symbol_id=$1
set res = await call fetchrow query symbol_id
return tuple res at str... | async def _get_already_saved_range(self, symbol: Symbol, md_type: MDType) -> \
Tuple[datetime, datetime]:
table_name = self._get_database_table_name(md_type)
symbol_id = await DataBase.get_symbol_id(symbol)
query = f"SELECT min(ts), max(ts) FROM {table_name} WHERE symbol_id=$1"
... | Python | nomic_cornstack_python_v1 |
class GeoPolygon extends object
begin
comment ptList: vertice GeoPoint Array
function __init__ self ptList
begin
comment alloc instance array memory
comment vertice point array
set __v = list
comment vertice index array
set __idx = list
comment number of vertices
set __n = length ptList
for pt in ptList
begin
append ... | class GeoPolygon(object):
def __init__(self, ptList): # ptList: vertice GeoPoint Array
#alloc instance array memory
self.__v = [] # vertice point array
self.__idx = [] # vertice index array
self.__n = len(ptList) # number of vertices
for pt in pt... | Python | zaydzuhri_stack_edu_python |
comment XOR 연산 학습
from sklearn import svm
comment XOR의 계산 결과 데이터
set xor_data = list list 0 0 0 list 0 1 1 list 1 0 1 list 1 1 0
comment 학습을 위해 데이터와 레이블 분리하기
set data = list
set label = list
for row in xor_data
begin
set p = row at 0
set q = row at 1
set r = row at 2
append data list p q
append label r
end
comment 데이... | # XOR 연산 학습
from sklearn import svm
# XOR의 계산 결과 데이터
xor_data = [
[0, 0, 0],
[0, 1, 1],
[1, 0, 1],
[1, 1, 0]
]
# 학습을 위해 데이터와 레이블 분리하기
data = []
label = []
for row in xor_data:
p = row[0]
q = row[1]
r = row[2]
data.append([p,q])
label.append(r)
# 데이터 학습시키기
clf... | Python | zaydzuhri_stack_edu_python |
class Rectangle
begin
function __init__ self a b
begin
set width = a
set height = b
set __area = width * height
end function
decorator property
function area self
begin
return width * height
end function
decorator setter
function area self value
begin
set ratio = value / area ^ 0.5
set width = width * ratio
set height ... | class Rectangle:
def __init__(self, a, b):
self.width = a
self.height = b
self.__area = self.width * self.height
@property
def area(self):
return self.width * self.height
@area.setter
def area(self, value):
ratio = (value / self.area) ** 0.5
self.wid... | Python | zaydzuhri_stack_edu_python |
comment coding:utf-8
string 有一个n面的骰子,掷每一面都是等概率的。其中有m个奖励面,如果掷到奖励面则可以再掷一次骰子。 玩家每掷一次都能获得掷到那一面的分数,求玩家可获得分数的期望。 输入描述:第一行输入两个数 n m 分别表示骰子有 n 面,有 m 个面有奖励(0<=m<n<=10^9) 第二行输入n个数字用空格隔开,表示n个面的分数 输出描述:输出期望,保留小数点后两位 示例: 输入: 6 1 1 1 1 1 1 1 输出: 1.20
set str1 = split strip input string
set n = decimal str1 at 0
set m = decimal str1 ... | # coding:utf-8
'''
有一个n面的骰子,掷每一面都是等概率的。其中有m个奖励面,如果掷到奖励面则可以再掷一次骰子。
玩家每掷一次都能获得掷到那一面的分数,求玩家可获得分数的期望。
输入描述:第一行输入两个数 n m 分别表示骰子有 n 面,有 m 个面有奖励(0<=m<n<=10^9)
第二行输入n个数字用空格隔开,表示n个面的分数
输出描述:输出期望,保留小数点后两位
示例:
输入: 6 1
1 1 1 1 1 1
输出: 1.20
'''
str1 = input().strip().split(' ')
n = float(str1[0])
m = float(str1[1])
str2 = ... | Python | zaydzuhri_stack_edu_python |
comment Generate contours for the random hills dataset.
from pyvista import examples
set hills = call load_random_hills
set contours = call contour
plot line_width=5
comment Generate the surface of a mobius strip using flying edges.
import pyvista as pv
set a = 0.4
set b = 0.1
function f x y z
begin
set xx = x * x
set ... | # Generate contours for the random hills dataset.
#
from pyvista import examples
hills = examples.load_random_hills()
contours = hills.contour()
contours.plot(line_width=5)
#
# Generate the surface of a mobius strip using flying edges.
#
import pyvista as pv
a = 0.4
b = 0.1
def f(x, y, z):
xx = x * x
yy = y * y... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string standard scaler The standard scaler is the preprocessing module, which can process the raw data.
comment Author: Shaohan Huang <buaahsh@gmail.com>
comment License: BSD 3 clause
import numpy as np
from scipy import sparse
from sklearn.base import BaseEstimator , TransformerMixin
from... | # -*- coding: utf-8 -*-
"""
standard scaler
The standard scaler is the preprocessing module, which can process the raw data.
"""
# Author: Shaohan Huang <buaahsh@gmail.com>
#
# License: BSD 3 clause
import numpy as np
from scipy import sparse
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.ut... | Python | zaydzuhri_stack_edu_python |
function login_required f
begin
decorator wraps f
function decorated_function *args **kwargs
begin
print get session string user_id
if string user_id not in session
begin
print string failed because of login_required
return call redirect call url_for string login next=url
end
return f dist *args keyword kwargs
end func... | def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
print(session.get("user_id"))
if "user_id" not in session:
print("failed because of login_required")
return redirect(url_for("login", next=request.url))
return f(*args, **kwargs)
return... | Python | nomic_cornstack_python_v1 |
import time
import logging
import threading
call basicConfig level=DEBUG format=string %(threadName)s => %(message)s
class ThreadTest extends Thread
begin
function __init__ self deamon=false
begin
call __init__ self daemon=deamon
end function
function run self
begin
while true
begin
info string We should put here all t... | import time
import logging
import threading
logging.basicConfig(level=logging.DEBUG, format='%(threadName)s => %(message)s')
class ThreadTest(threading.Thread):
def __init__(self,deamon=False):
threading.Thread.__init__(self, daemon=deamon)
def run(self):
while True:
logging.inf... | Python | zaydzuhri_stack_edu_python |
from Turret import Turret
from Basic_Turret import Basic_Turret
from Heavy_Turret import Heavy_Turret
from LongRange_Turret import LongRange_Turret
from Enemy_Pool import Enemy_Pool
import pygame
class UI
begin
function __init__ self grid turrets nexus app
begin
set turretsSpawn = list tuple 1 6 tuple 1 7 tuple 3 4 tup... | from Turret import Turret
from Basic_Turret import Basic_Turret
from Heavy_Turret import Heavy_Turret
from LongRange_Turret import LongRange_Turret
from Enemy_Pool import Enemy_Pool
import pygame
class UI:
def __init__(self, grid, turrets, nexus, app):
self.turretsSpawn = [(1, 6), (1, 7), (3, 4), (3, 6), (... | Python | zaydzuhri_stack_edu_python |
import geometry
set userinput = input string Enter the side lengths of a triangle:
set inputted = split userinput string ,
set tuple a b c = generator expression decimal number for number in inputted
set P = call triangle_perimeter a b c
set A = call triangle_heronsarea a b c
print format string Perimeter: {:.2f} P
pri... | import geometry
userinput= input("Enter the side lengths of a triangle: ")
inputted= userinput.split(",")
(a,b,c)= (float(number) for number in inputted)
P=geometry.triangle_perimeter(a,b,c)
A=geometry.triangle_heronsarea(a,b,c)
print("Perimeter: {:.2f}".format(P))
print("Area: {:.2f}".format(A)) | Python | zaydzuhri_stack_edu_python |
class Matrix
begin
string This class implements matrix operations Attributes: nline (int): The number of line of the matrix ncol (int): The number of columns matrice (array like): Values of matrix
function __init__ self nline=0 ncol=0
begin
string The constructor of matrix Parameters: nline (int): number of line nco l ... | class Matrix:
"""This class implements matrix operations
Attributes:
nline (int): The number of line of the matrix
ncol (int): The number of columns
matrice (array like): Values of matrix
"""
def __init__(self, nline=0, ncol=0):
"""The constructor of matrix
Parameters:
nline (int): number of line
... | Python | zaydzuhri_stack_edu_python |
function get_pieces_8bits self x
begin
set x_bin = replace call zfill SIZE_X string b string
set pieces = list
for _ in range SIZE_RANDOM_TABLE_AND_PIECES
begin
append pieces x_bin at slice - SIZE_RANDOM_TABLE_AND_PIECES : :
set x_bin = x_bin at slice : - SIZE_RANDOM_TABLE_AND_PIECES :
end
return tuple pieces at sl... | def get_pieces_8bits(self, x):
x_bin = bin(x).zfill(SIZE_X).replace('b', '')
pieces = []
for _ in range(SIZE_RANDOM_TABLE_AND_PIECES):
pieces.append(x_bin[-SIZE_RANDOM_TABLE_AND_PIECES:])
x_bin = x_bin[:-SIZE_RANDOM_TABLE_AND_PIECES]
return pieces[::-1], [int(p... | Python | nomic_cornstack_python_v1 |
try
begin
set n = integer input string Enter an integer:
set char = given_string at n
print string character at index { n } is { char }
end
except ValueError
begin
print string Invalid integer!
end
except IndexError
begin
print string Invalid index!
end | try:
n = int(input("Enter an integer: "))
char = given_string[n]
print(f"character at index {n} is {char}")
except ValueError:
print("Invalid integer!")
except IndexError:
print("Invalid index!")
| Python | zaydzuhri_stack_edu_python |
from math import pow
from unittest import TestCase
class Solution
begin
function isPowerOfThree self n
begin
set exp : int = 0
while power 3 exp < n
begin
set exp = exp + 1
end
return power 3 exp == n
end function
function isPowerOfThree2 self n
begin
comment 3^19 is largest number less than maximum integer
comment 3^1... | from math import pow
from unittest import TestCase
class Solution:
def isPowerOfThree(self, n: int) -> bool:
exp: int = 0
while pow(3, exp) < n:
exp += 1
return pow(3, exp) == n
def isPowerOfThree2(self, n: int) -> bool:
# 3^19 is largest number less than maximum i... | Python | zaydzuhri_stack_edu_python |
class Perro
begin
function ladrar self
begin
print string ladrar
end function
end class
set sparky = call Perro
print string sparky ya puede
call ladrar
set fluffy = call Perro
print string fluffy ya puede
call ladrar | class Perro:
def ladrar(self):
print("ladrar")
sparky = Perro()
print ("sparky ya puede ")
sparky.ladrar()
fluffy = Perro()
print ("fluffy ya puede ")
fluffy.ladrar() | Python | zaydzuhri_stack_edu_python |
function get_key_indices self label_list
begin
set keyindexer = list
comment print label_list, self.labels
comment print label_list in self.labels
for i in list label_list
begin
if i in labels
begin
return index labels i
end
else
begin
assert false msg string Failed to match a label to the table %s % i
end
append keyi... | def get_key_indices(self, label_list):
keyindexer = []
# print label_list, self.labels
# print label_list in self.labels
for i in [label_list]:
if i in self.labels:
return self.labels.index(i)
else:
assert False, "Failed to match a la... | Python | nomic_cornstack_python_v1 |
function compute_n1mix clpp=none normarray=none cls=none rcltt=none rclee=none rclbb=none rclte=none cltt=none clee=none clbb=none lmin=none Lmaxout=none lmax_TT=none Lstep=none Lmin_out=none
begin
set tuple n1ttee n1tteb n1ttte n1tttb n1eeeb n1eete n1eetb n1ebte n1ebtb n1tetb = call compute_n1mix clpp normarray cls rc... | def compute_n1mix(
clpp=None,
normarray=None,
cls=None,
rcltt=None,
rclee=None,
rclbb=None,
rclte=None,
cltt=None,
clee=None,
clbb=None,
lmin=None,
Lmaxout=None,
lmax_TT=None,
Lstep=None,
Lmin_out=None
):
n1ttee,n1tteb,n1ttte,n1tttb,n1eeeb,n1e... | Python | nomic_cornstack_python_v1 |
string Project part 3, solve the 1d advection equation in fortran
import numpy as np
import matplotlib.pyplot as plt
import adv
comment f2py -llapack -c fdmoduleB.f90 ode.f90 advmodule.f90 -m adv --f90flags='-fopenmp' -lgomp
function advection1f tf n dx c=1.0 S=0.0 display=false numthreads=1
begin
string solve advectio... | """Project part 3, solve the 1d advection equation in fortran"""
import numpy as np
import matplotlib.pyplot as plt
import adv
#f2py -llapack -c fdmoduleB.f90 ode.f90 advmodule.f90 -m adv --f90flags='-fopenmp' -lgomp
def advection1f(tf,n,dx,c=1.0,S=0.0,display=False,numthreads=1):
"""solve advection equation, df/... | Python | zaydzuhri_stack_edu_python |
from BaseHTTPServer import BaseHTTPRequestHandler , HTTPServer
import urlparse
function generate_ppt name
begin
import pptx
from pptx.util import Inches , Pt
set f = open string blue.pptx
set prs = call Presentation f
close f
set slide = slides at 0
for shape in shapes
begin
if not has_text_frame
begin
continue
end
set... | from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import urlparse
def generate_ppt(name):
import pptx
from pptx.util import Inches, Pt
f = open("blue.pptx")
prs = pptx.Presentation(f)
f.close()
slide = prs.slides[0]
for shape in slide.shapes:
if not shape.has_text_frame... | Python | zaydzuhri_stack_edu_python |
comment 11-topshiriq
set n = integer input string N sonini kiriting:
set k = 0
set s = 0
while s < n
begin
set k = k + 1
set s = s + k
end
print string k= k
print string yig'indi s= s | # 11-topshiriq
n = int(input("N sonini kiriting:"))
k = 0
s = 0
while (s < n):
k = k + 1
s = s + k
print("k=", k)
print("yig'indi s=", s)
| Python | zaydzuhri_stack_edu_python |
function _parse_single filename label image_size=IMAGE_SIZE
begin
comment Decode and convert image to appropriate type
set image = call decode_png call read_file filename channels=image_size at 2
comment Also scales from [0, 255] to [0, 1)
set image = call convert_image_dtype image float32
comment Resize according to m... | def _parse_single(filename, label, image_size=IMAGE_SIZE):
# Decode and convert image to appropriate type
image = tf.image.decode_png(tf.read_file(filename), channels=image_size[2])
image = tf.image.convert_image_dtype(image, tf.float32) # Also scales from [0, 255] to [0, 1)
# Resize according to modul... | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
function main
begin
set df = list
end function | import pandas as pd
import numpy as np
def main():
df = [] | Python | zaydzuhri_stack_edu_python |
function save_license self request
begin
if POST at string cc_js_want_cc_license == string sure
begin
set cc_js_result_img = POST at string cc_js_result_img
set cc_js_result_name = POST at string cc_js_result_name
set cc_js_result_uri = POST at string cc_js_result_uri
call set_param string license_image cc_js_result_im... | def save_license(self, request):
if request.POST['cc_js_want_cc_license'] ==\
'sure':
cc_js_result_img = request.POST['cc_js_result_img']
cc_js_result_name = request.POST['cc_js_result_name']
cc_js_result_uri = request.POST['cc_js_result_uri']
self.ps... | Python | nomic_cornstack_python_v1 |
function throughput self
begin
return get pulumi self string throughput
end function | def throughput(self) -> Optional[pulumi.Input[int]]:
return pulumi.get(self, "throughput") | Python | nomic_cornstack_python_v1 |
function n_token_occur self token ignorecase=false
begin
if is instance token str
begin
set mydict = dict string form token
end
else
if is instance token dict
begin
set mydict = token
end
else
begin
raise call TypeError string token argument must be either string or dict
end
set count = 0
for tokenJSON in retrieved_tok... | def n_token_occur(self, token, ignorecase=False):
if isinstance(token, str):
mydict = {"form": token}
elif isinstance(token, dict):
mydict = token
else:
raise TypeError("token argument must be either string or dict")
count = 0
for tokenJSON in... | Python | nomic_cornstack_python_v1 |
function testB
begin
comment Test first_inside_quotes():
call assert_equals string cake call first_inside_quotes string The "cake" is a lie
call assert_equals string cake call first_inside_quotes string The "cake" is a "lie"
comment Test get_lhs():
call assert_equals string 42 Euros call get_lhs string {lhs: "42 Euros"... | def testB():
#Test first_inside_quotes():
cunittest.assert_equals("cake",first_inside_quotes("The \"cake\" is a lie"))
cunittest.assert_equals("cake",
first_inside_quotes("The \"cake\" is a \"lie\""))
#Test get_lhs():
cunittest.assert_equals("42 Euros",get_lhs(
... | Python | nomic_cornstack_python_v1 |
function sample_partial_overlap example minimum_overlap maximum_overlap
begin
set rng = call get_rng_example example string offset
set overlap = uniform minimum_overlap maximum_overlap
set num_samples = example at NUM_SAMPLES at ORIGINAL_SOURCE
assert length num_samples == 2 msg tuple length num_samples num_samples
set... | def sample_partial_overlap(example, *, minimum_overlap, maximum_overlap):
rng = get_rng_example(example, 'offset')
overlap = rng.uniform(minimum_overlap, maximum_overlap)
num_samples = example[keys.NUM_SAMPLES][keys.ORIGINAL_SOURCE]
assert len(num_samples) == 2, (len(num_samples), num_samples)
overl... | Python | nomic_cornstack_python_v1 |
function config self **kwargs
begin
set __headertext = pop kwargs string headertext __headertext
set __text = pop kwargs string text __text
set __width = pop kwargs string width __width
set _timeout = pop kwargs string timeout _timeout
set __background = pop kwargs string background __background
if _toplevel
begin
call... | def config(self, **kwargs):
self.__headertext = kwargs.pop("headertext", self.__headertext)
self.__text = kwargs.pop("text", self.__text)
self.__width = kwargs.pop("width", self.__width)
self._timeout = kwargs.pop("timeout", self._timeout)
self.__background = kwargs.pop("backgrou... | Python | nomic_cornstack_python_v1 |
function swap_tree_test
begin
set par_rates = list 0.01 0.02 0.025 0.028 0.036
set maturities = list 1 2 3 4 5
set tuple sig FV c = tuple 0.1743 100 0.04
set tuple fwd_tree swap_values CVA DVA EpEs EnEs = call swap_tree par_rates maturities sig FV c 0.5 0.4 0.025 0.01
print string Credit and debit adjusted value of swa... | def swap_tree_test():
par_rates = [0.01,0.02,0.025,0.028,0.036]
maturities = [1,2,3,4,5]
sig,FV,c = 0.1743,100,0.04
fwd_tree,swap_values,CVA,DVA,EpEs,EnEs = swap_tree(par_rates,maturities,sig,FV,c,0.5,\
0.4,0.025,0.01)
print("Credit and debit adjust... | Python | nomic_cornstack_python_v1 |
for x in range 0 4
begin
print string Hello world
end | for x in range(0, 4):
print ("Hello world") | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment Define your item pipelines here
comment Don't forget to add your pipeline to the ITEM_PIPELINES setting
comment See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import datetime
from pymongo import MongoClient
from scrapySpider.items import stockItem
set MONGODB_URI = ... | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import datetime
from pymongo import MongoClient
from scrapySpider.items import stockItem
MONGODB_URI = 'mongodb://127.0.0.1:2... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
import string
from round import Round
from random import randrange
set mistakes_arr = list string _ string _ string _ string _ string _ string _
set mistakes_cnt = 0
set word_arr = list
set root = call Tk
title root string Simple Calculator
function button_click button letter word
begin
global mi... | from tkinter import *
import string
from round import Round
from random import randrange
mistakes_arr = ['_', '_', '_', '_', '_', '_']
mistakes_cnt = 0
word_arr = []
root = Tk()
root.title("Simple Calculator")
def button_click(button, letter, word):
global mistakes_cnt, word_arr
print(mistakes_cnt)
but... | Python | zaydzuhri_stack_edu_python |
string Created on Mar 6 2020 @author: Changze Han
import csv
import numpy as np
import random
import copy
import math
string For HIV project: (maybe other projects) Calculate euclidean distance for all combination. Algorithm: 1. Categorize data based on fixed column 2. Find all combinations based on varied column 3. ca... | """
Created on Mar 6 2020
@author: Changze Han
"""
import csv
import numpy as np
import random
import copy
import math
'''
For HIV project: (maybe other projects)
Calculate euclidean distance for all combination.
Algorithm:
1. Categorize data based on fixed column
2. Find all c... | Python | zaydzuhri_stack_edu_python |
function readBugFile self
begin
with open filename string r as inputFile
begin
set lines = read lines inputFile
if lines at 0 at 0 != string #
begin
raise call ValueError string The provided filename does not correspond to a valid bugs file
end
call parseConfig lines at 0
return lines at slice 1 : :
end
end function | def readBugFile(self):
with open(self.filename, 'r') as inputFile:
lines = inputFile.readlines()
if lines[0][0] != '#':
raise ValueError('The provided filename does not correspond '
'to a valid bugs file')
self.parseConfig(line... | Python | nomic_cornstack_python_v1 |
function test_hospital_location_name_field self
begin
set field = find hospital_location_record string field[@name='name']
assert equal text string GUH POS Location string Incorrect name on location
end function | def test_hospital_location_name_field(self):
field = self.hospital_location_record.find('field[@name=\'name\']')
self.assertEqual(field.text, 'GUH POS Location',
'Incorrect name on location') | Python | nomic_cornstack_python_v1 |
string Author : Akshay Joshi GitHub : https://github.com/ijoshi90 Created on 19-12-2019 at 14:22
comment generate a password with length "passlen" with no duplicate characters in the password
from random import *
set string = string abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?
set passlen ... | """
Author : Akshay Joshi
GitHub : https://github.com/ijoshi90
Created on 19-12-2019 at 14:22
"""
# generate a password with length "passlen" with no duplicate characters in the password
from random import *
string = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()?"
passlen = 8
password = "... | Python | zaydzuhri_stack_edu_python |
function _plot_predictive_counts predictions color label axis alpha=0.5 debug=false
begin
comment For fast plotting, use a histogram if np.unique(predictions).size > 100.
if size > 100
begin
comment Compute the counts and bin edges when we only want 100 bins
set tuple pred_counts pred_edges = call histogram predictions... | def _plot_predictive_counts(predictions,
color,
label,
axis,
alpha=0.5,
debug=False):
# For fast plotting, use a histogram if np.unique(predictions).size > 100.
if np.uniqu... | Python | nomic_cornstack_python_v1 |
import os
import time
sleep 0.1
set a = call startfile string D:\360MoveData\Users\Windows10\Desktop\音乐\VRChat.mp3
comment 打开图片
comment from PIL import Image
comment import matplotlib.pyplot as plt
comment img=Image.open(r'D:\360MoveData\Users\Windows10\Pictures\Saved Pictures\1.jpg')
comment plt.figure("dog")
comment ... | import os
import time
time.sleep(0.1)
a = os.startfile(r'D:\360MoveData\Users\Windows10\Desktop\音乐\VRChat.mp3')
##打开图片
#from PIL import Image
#import matplotlib.pyplot as plt
#img=Image.open(r'D:\360MoveData\Users\Windows10\Pictures\Saved Pictures\1.jpg')
#plt.figure("dog")
#plt.imshow(img)
#plt.show()
#print(im... | Python | zaydzuhri_stack_edu_python |
from pipeline import Pipeline
from struct import *
from builder import UrlTable
import os , math , time
import operator
set fmt = string 14sHI
set SIZE = 20
function nextWord char
begin
set c = character ordinal char + 1
if c >= string z
begin
return 0
end
else
begin
return c
end
end function
class Analyzer
begin
funct... | from pipeline import Pipeline
from struct import *
from builder import UrlTable
import os,math,time
import operator
fmt = "14sHI"
SIZE = 20
def nextWord(char):
c = chr(ord(char) + 1)
if c >= 'z':
return 0
else :return c
class Analyzer:
def open(self,index):
self.table = UrlTable("url_index",mode = "i... | Python | zaydzuhri_stack_edu_python |
function test_assign_seqs_fasta_only self
begin
comment Initial test for single fasta file alone.
set file_data = dict
set file_data at string fasta_files = list valid_fasta_file_no_errors
set file_data at string qual_files = list
comment file_data['mapping_file'] = self.valid_mapping_data_golay_upper
set file_data a... | def test_assign_seqs_fasta_only(self):
# Initial test for single fasta file alone.
file_data = {}
file_data['fasta_files'] = [self.valid_fasta_file_no_errors]
file_data['qual_files'] = []
#file_data['mapping_file'] = self.valid_mapping_data_golay_upper
file_data['... | Python | nomic_cornstack_python_v1 |
import math
import sys
import copy
class Task
begin
function read self file=string in
begin
return list comprehension list strip p for p in split read open file string if p != string
end function
function compute self a
begin
function next n m a neigbours cnt_L cnt_Hash
begin
set new_a = deep copy a
for i in range 1 n... | import math
import sys
import copy
class Task:
def read(self, file='in'):
return [list(p.strip()) for p in open(file).read().split('\n') if p != '']
def compute(self, a):
def next(n, m, a, neigbours, cnt_L, cnt_Hash):
new_a = copy.deepcopy(a)
for i in range(1, n + 1):
... | Python | zaydzuhri_stack_edu_python |
string Implements the board class
set __author__ = string Hoang Long Dang
from graphics import Point , Circle , GraphWin , Line , Text
from copy import deepcopy
from typing import Tuple , TypeVar
set T = call TypeVar string T
set int_str = call TypeVar string int_str int str
class Tile
begin
string Holds values for eac... | """ Implements the board class """
__author__ = 'Hoang Long Dang'
from graphics import Point, Circle, GraphWin, Line, Text
from copy import deepcopy
from typing import Tuple, TypeVar
T = TypeVar('T')
int_str = TypeVar('int_str', int, str)
class Tile():
"""
Holds values for each tile in the board.
Helper... | Python | zaydzuhri_stack_edu_python |
function has_positive_net_income_from self from_date type
begin
if type not in list string net string operating
begin
raise call ValueError string type should be 'net' or 'operating'
end
set target_statement_num = 0
for statement in income_statements
begin
if not call is_after from_date
begin
continue
end
if report_typ... | def has_positive_net_income_from(self, from_date, type):
if type not in ["net", "operating"]:
raise ValueError("type should be 'net' or 'operating'")
target_statement_num = 0
for statement in self.income_statements:
if not statement.is_after(from_date):
c... | Python | nomic_cornstack_python_v1 |
function parseMetric url
begin
comment get the metric content
set urlObj = url open url
set data = read urlObj
comment remove python style comments
set data = sub compile string #.*$ MULTILINE string data
comment parse the metric
set parsed = find all string (.*?)\t(.*?)\t(.*?)\t(.*?)\t(.*?)\n data M
set entries = lis... | def parseMetric(url):
# get the metric content
urlObj = urllib2.urlopen(url)
data = urlObj.read()
# remove python style comments
data = re.sub(re.compile(r'#.*$', re.MULTILINE), "", data)
# parse the metric
parsed = re.findall(r'(.*?)\t(.*?)\t(.*?)\t(.*?)\t(.*?)\n', data, re.M)
e... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
import glob
from collections import defaultdict
from os import path
from typing import Tuple , Dict , List
function the_name
begin
comment type: Dict[str, int]
set names = default dictionary int
comment type: Dict[str, List[str]]
set name_owners = default dicti... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import glob
from collections import defaultdict
from os import path
from typing import Tuple, Dict, List
def the_name() -> Tuple[str, str]:
names = defaultdict(int) # type: Dict[str, int]
name_owners = defaultdict(list) # type: Dict[str, List[str]]
results ... | Python | zaydzuhri_stack_edu_python |
function is_cycle_unchanged self cycle
begin
if not exists path unchanged_cycles_path
begin
return false
end
set unchanged_cycles = call splitlines
return string cycle in unchanged_cycles
end function | def is_cycle_unchanged(self, cycle: int) -> bool:
if not os.path.exists(self.unchanged_cycles_path):
return False
unchanged_cycles = filesystem.read(
self.unchanged_cycles_path).splitlines()
return str(cycle) in unchanged_cycles | Python | nomic_cornstack_python_v1 |
function viola_channel_msg buf msg color=string green
begin
set msg = string [Viola] %s % msg
call prnt buf call colorize msg color
end function | def viola_channel_msg(buf, msg, color="green"):
msg = "[Viola] %s" % msg
prnt(buf, otrlib.colorize(msg, color)) | Python | nomic_cornstack_python_v1 |
function do_mixing s n
begin
if length s > length n
begin
set bgn_sample = 0
set fin_sample = length n
set s = s at slice 0 : length n :
set mix_audio = s + n
end
else
begin
set n_half = integer length n - length s / 2 + 1
set bgn_sample = n_half
set fin_sample = n_half + length s
set s = concatenate tuple zeros n_hal... | def do_mixing(s, n):
if len(s) > len(n):
bgn_sample = 0
fin_sample = len(n)
s = s[0 : len(n)]
mix_audio = s + n
else:
n_half = int((len(n) - len(s)) / 2) + 1
bgn_sample = n_half
fin_sample = n_half + len(s)
s = np.concatenate((np.zeros(n_half), s, ... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment Parse sitemap xml files and save to csv
comment @author Victor Angus <vjangus@gmail.com>
comment python 2.7
import argparse
import lxml.etree
import os
import sys
import csv
from glob import glob
from urlparse import urlparse
comment Get category
comment Ex. https://www.example.com/... | #!/usr/bin/env python
# Parse sitemap xml files and save to csv
# @author Victor Angus <vjangus@gmail.com>
# python 2.7
import argparse
import lxml.etree
import os
import sys
import csv
from glob import glob
from urlparse import urlparse
# Get category
# Ex. https://www.example.com/Product/item.htm
# Category: Prod... | Python | zaydzuhri_stack_edu_python |
function enable_ldap_authentication self server_uris auth_type=OPTIONAL group_search_base_dn=OPTIONAL group_search_custom_filter=OPTIONAL group_search_type=OPTIONAL search_bind_dn=OPTIONAL search_bind_password=OPTIONAL user_dntemplate=OPTIONAL user_search_base_dn=OPTIONAL user_search_filter=OPTIONAL
begin
call _check_c... | def enable_ldap_authentication(
self,
server_uris,
auth_type=OPTIONAL,
group_search_base_dn=OPTIONAL,
group_search_custom_filter=OPTIONAL,
group_search_type=OPTIONAL,
search_bind_dn=OPTIONAL,
search_bind_password=OPTIONAL,
... | Python | nomic_cornstack_python_v1 |
comment 3. Реализовать программу работы с органическими клетками. Необходимо создать класс Клетка.
comment В его конструкторе инициализировать параметр, соответствующий количеству клеток (целое число).
comment В классе должны быть реализованы методы перегрузки арифметических операторов: сложение (add()), вычитание (sub... | # 3. Реализовать программу работы с органическими клетками. Необходимо создать класс Клетка.
# В его конструкторе инициализировать параметр, соответствующий количеству клеток (целое число).
# В классе должны быть реализованы методы перегрузки арифметических операторов: сложение (add()), вычитание (sub()),
# умножение (... | Python | zaydzuhri_stack_edu_python |
function url_path self
begin
return none
end function | def url_path(self):
return None | Python | nomic_cornstack_python_v1 |
function filter_low_scoring_teeth bboxes teeth_in_bucket=9
begin
set other_bboxes = list comprehension bbox for bbox in bboxes if call get_label != 0
set teeth_bboxes = list comprehension bbox for bbox in bboxes if call get_label == 0
set teeth_scores = list comprehension call get_score for bbox in teeth_bboxes
set sco... | def filter_low_scoring_teeth(bboxes, teeth_in_bucket=9):
other_bboxes = [bbox for bbox in bboxes if bbox.get_label() != 0]
teeth_bboxes = [bbox for bbox in bboxes if bbox.get_label() == 0]
teeth_scores = [bbox.get_score() for bbox in teeth_bboxes]
scores_sorted = np.argsort(teeth_scores)
sorted_teet... | Python | nomic_cornstack_python_v1 |
import requests
import csv
import helper
import sys
import os.path
from bs4 import BeautifulSoup
comment Data to extract.
set header = list string Model string Price UK string Price Netherlands string Price Germany string Availability UK string Availability Netherlands string Availability Germany string City - Cold Wea... | import requests
import csv
import helper
import sys
import os.path
from bs4 import BeautifulSoup
# Data to extract.
header = ['Model', 'Price UK', 'Price Netherlands', 'Price Germany',
'Availability UK', 'Availability Netherlands', 'Availability Germany',
'City - Cold Weather', 'Highway... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
set asr_conf = call parse_yaml at string asr
set device = CPU
set nf = call NeuralModuleFactory placement=device
comment load model configuration
set jasper_params = call parse_yaml join path asr_conf at string model_dir string quartznet15x5.yaml
set labels = jasper_params at string labels
... | def __init__(self):
self.asr_conf = parse_yaml()["asr"]
device = nemo.core.DeviceType.CPU
self.nf = nemo.core.NeuralModuleFactory(placement=device)
# load model configuration
jasper_params = parse_yaml(
os.path.join(self.asr_conf["model_dir"], "quartznet15x5.yaml"))
... | Python | nomic_cornstack_python_v1 |
for ch in text
begin
print string char: ch string ord value: ordinal ch
end
print | for ch in text:
print('char:',ch,'ord value:',ord(ch))
print
| Python | zaydzuhri_stack_edu_python |
function perspective_blockdev_setinfo params
begin
set tuple disk info = params
set disk = call FromDict disk
return call BlockdevSetInfo disk info
end function | def perspective_blockdev_setinfo(params):
(disk, info) = params
disk = objects.Disk.FromDict(disk)
return backend.BlockdevSetInfo(disk, info) | Python | nomic_cornstack_python_v1 |
function calculate_ucb_min self node action
begin
return q_a at action - c * square root call divide log n_visits n_a at action
end function | def calculate_ucb_min(self, node, action):
return node.q_a[action] - self.c * math.sqrt(
np.divide(math.log(node.n_visits),
node.n_a[action])) | Python | nomic_cornstack_python_v1 |
function list2matrix image_list
begin
set flatten_list = list
for image in image_list
begin
append flatten_list call ravel
end
set matrix = vertical stack flatten_list
return matrix
end function | def list2matrix(image_list):
flatten_list = []
for image in image_list:
flatten_list.append(image.ravel())
matrix = np.vstack(flatten_list)
return matrix | Python | nomic_cornstack_python_v1 |
import re
from threading import Timer
from BeautifulSoup import BeautifulSoup as BS
from myUtils import *
from myUrllib import *
from config import GLOBAL
class PageType
begin
set navi = 0
set docu = 1
set other = 2
end class
class URLInfo
begin
function __init__ self url fatherurl title type otherinfo=none
begin
set u... | import re
from threading import Timer
from BeautifulSoup import BeautifulSoup as BS
from myUtils import *
from myUrllib import *
from config import GLOBAL
class PageType:
navi = 0
docu = 1
other = 2
class URLInfo:
def __init__(self, url, fatherurl, title, type, otherinfo=None):
self.url = url
self.fatherurl ... | Python | zaydzuhri_stack_edu_python |
function get_agave_client message
begin
set token = get message string access_token
set api_server = get message string api_server string https://api.tacc.utexas.edu
return call Agave api_server=api_server token=token
end function | def get_agave_client(message):
token = message.get("access_token")
api_server = message.get("api_server", "https://api.tacc.utexas.edu")
return Agave(api_server=api_server, token=token) | Python | nomic_cornstack_python_v1 |
function main opts
begin
comment Create a dataloader for the training images
set tuple train_dataloader _ = call get_emoji_loader emoji opts
comment Create checkpoint and sample directories
call create_dir checkpoint_dir
call create_dir sample_dir
train train_dataloader opts
end function | def main(opts):
# Create a dataloader for the training images
train_dataloader, _ = get_emoji_loader(opts.emoji, opts)
# Create checkpoint and sample directories
utils.create_dir(opts.checkpoint_dir)
utils.create_dir(opts.sample_dir)
train(train_dataloader, opts) | Python | nomic_cornstack_python_v1 |
function setUp self
begin
set app = call create_app
set client = test_client
set casting_assistant = CASTING_ASSISTANT
set casting_director = CASTING_DIRECTOR
set executive_producer = EXECUTIVE_PRODUCER
call setup_db app TEST_DATABASE_URI
with call app_context
begin
set db = call SQLAlchemy
call init_app app
end
end fu... | def setUp(self):
self.app = create_app()
self.client = self.app.test_client
self.casting_assistant = CASTING_ASSISTANT
self.casting_director = CASTING_DIRECTOR
self.executive_producer = EXECUTIVE_PRODUCER
setup_db(self.app, TEST_DATABASE_URI)
with self.app.app_con... | Python | nomic_cornstack_python_v1 |
from pathlib import Path
import pandas as pd
import wikipedia
function run data_path output_path
begin
set df = read csv data_path usecols=list string name string industry
function get_summary x
begin
set summary = string
try
begin
set summary = call summary x
end
except any
begin
pass
end
return summary
end function
... | from pathlib import Path
import pandas as pd
import wikipedia
def run(data_path, output_path):
df = pd.read_csv(data_path, usecols=['name', 'industry'])
def get_summary(x):
summary = ''
try:
summary = wikipedia.summary(x)
except:
pass
return summary
... | Python | zaydzuhri_stack_edu_python |
from django.db import models
from django.contrib.auth.models import AbstractUser
comment User types choices
set USER_TYPE_CHOICES = tuple tuple string Student string Student tuple string Faculty string Faculty
comment department model
class Department extends Model
begin
set name = call CharField max_length=30
function... | from django.db import models
from django.contrib.auth.models import AbstractUser
# User types choices
USER_TYPE_CHOICES = (
("Student","Student"),
("Faculty","Faculty"),
)
#department model
class Department(models.Model):
name = models.CharField(max_length=30)
def __str__(self):
return self.n... | Python | zaydzuhri_stack_edu_python |
function random_forest_clas data labels
begin
comment splits the data in a training and a test set
set df = call DataFrame call toarray
set df at string result_kmeans = labels
set df at string is_train = uniform 0 1 length df <= 0.75
set tuple train test = tuple df at df at string is_train == true df at df at string is... | def random_forest_clas(data, labels):
# splits the data in a training and a test set
df = pd.DataFrame(data.toarray())
df["result_kmeans"] = labels
df['is_train'] = np.random.uniform(0, 1, len(df)) <= .75
train, test = df[df['is_train'] == True], df[df['is_train'] == False]
print('Number of obse... | Python | nomic_cornstack_python_v1 |
import requests
from config import client
from utils.time import SATURDAY , SUNDAY
from utils.users import COMPLETED , CURRENT
set SNOOZE = string snooze
set SKIP = string false
class DefaultMessage
begin
function __init__ self user scheduled_time=none
begin
set user = user
set scheduled_time = scheduled_time
set SCHED... | import requests
from config import client
from utils.time import SATURDAY, SUNDAY
from utils.users import COMPLETED, CURRENT
SNOOZE = 'snooze'
SKIP = 'false'
class DefaultMessage:
def __init__(self, user, scheduled_time=None):
self.user = user
self.scheduled_time = scheduled_time
self.S... | Python | zaydzuhri_stack_edu_python |
string Create a function which takes a `sentence` and returns its abbreviation. Get all of the words over or equal to `n` characters in length and return the first letter of each, _capitalised_ and overall returned as a single string. ### Examples abbreviate("do it yourself") ➞ "Y" abbreviate("do it yourself", 2) ➞ "DI... | """
Create a function which takes a `sentence` and returns its abbreviation. Get
all of the words over or equal to `n` characters in length and return the
first letter of each, _capitalised_ and overall returned as a single string.
### Examples
abbreviate("do it yourself") ➞ "Y"
abbreviate("do it yourself"... | Python | zaydzuhri_stack_edu_python |
function fprop self h_in update_units=false
begin
assert is instance h_in ndarray
assert shape at 1 == n_in
comment For each data point, this is `a_out = W.dot(h_in) + b`
set a_out = dot T + T
if update_units
begin
set h_in = h_in
set a_out = a_out
end
set h_out = eval a_out
comment Dropout
if update_units
begin
set ma... | def fprop(self, h_in, update_units=False):
assert isinstance(h_in, np.ndarray)
assert h_in.shape[1] == self.n_in
# For each data point, this is `a_out = W.dot(h_in) + b`
a_out = h_in.dot(self.W.T) + self.b.T
if update_units:
self.h_in = h_in
se... | Python | nomic_cornstack_python_v1 |
function plot_data_by_average_age_and_sev self df_data severities color file_name append position
begin
set df_data_for_plot = call _add_days_open_column df_data
set tuple fig ax = call subplots
subplot position
x label string Schwachstellen nach Gewichtung
y label string Durschnittliches Alter der Schwachstellen
set d... | def plot_data_by_average_age_and_sev(self, df_data, severities, color, file_name, append, position):
df_data_for_plot = self._add_days_open_column(df_data)
fig, ax = plt.subplots()
plt.subplot(position)
plt.xlabel("Schwachstellen nach Gewichtung")
plt.ylabel("Dursc... | Python | nomic_cornstack_python_v1 |
comment Initialize empty dictionary
set char_count = dict
comment Remove whitespace characters
set string = replace string string string
comment Iterate through each character in the string
for char in string
begin
comment Check if character is already present in the dictionary
if char in char_count
begin
comment Inc... | # Initialize empty dictionary
char_count = {}
# Remove whitespace characters
string = string.replace(" ", "")
# Iterate through each character in the string
for char in string:
# Check if character is already present in the dictionary
if char in char_count:
# Increment count of character by 1
... | Python | jtatman_500k |
function _initialize_rpi_gpio self
begin
call setwarnings false
call setmode BOARD
setup GPIO pin OUT
end function | def _initialize_rpi_gpio(self):
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(self.pin, GPIO.OUT) | Python | nomic_cornstack_python_v1 |
function camera_info self camera_ids **kwargs
begin
set api = _api_info at string camera
set payload = dictionary dict string _sid _sid ; string api api at string name ; string method string GetInfo ; string version api at string version ; string cameraIds join string , generator expression string id for id in camera_i... | def camera_info(self, camera_ids, **kwargs):
api = self._api_info['camera']
payload = dict({
'_sid': self._sid,
'api': api['name'],
'method': 'GetInfo',
'version': api['version'],
'cameraIds': ', '.join(str(id) for id in camera_ids),
},... | Python | nomic_cornstack_python_v1 |
function incrementAll self keys count
begin
for key in keys
begin
set self at key = self at key + count
end
end function | def incrementAll(self, keys, count):
for key in keys:
self[key] += count | 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.