code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
string Write a function that is given a string and returns a boolean indicating whether that string has balanced parentheses. The string may have characters other than parentheses, and should be ignored. e.g. 'x()' is balanced, '((y(z' is not, 'a(b())' is balanced, ')()(' is not.
function is_balanced s
begin
set stack ... | """
Write a function that is given a string and returns a boolean indicating whether
that string has balanced parentheses. The string may have characters other than
parentheses, and should be ignored. e.g. 'x()' is balanced, '((y(z' is not, 'a(b())' is balanced, ')()(' is not.
"""
def is_balanced(s):
stack = []
... | Python | zaydzuhri_stack_edu_python |
class ValueOutOfRange extends Exception
begin
pass
end class
while true
begin
try
begin
set start = integer input string Enter a starting value:
set end = integer input string Enter a ending value:
set step = integer input string What is the increment:
if start > end
begin
raise ValueOutOfRange
end
else
begin
break
end... | class ValueOutOfRange(Exception):
pass
while True:
try:
start = int(input("Enter a starting value: "))
end = int(input("Enter a ending value: "))
step = int(input("What is the increment: "))
if start > end:
raise ValueOutOfRange
else:
break
except ValueError:
print("One of th... | Python | zaydzuhri_stack_edu_python |
import random
from fitness import Fitness
class GA
begin
function __init__ self population population_size elite_size mutation_rate generations
begin
set initial_pop = call generate_initial_pop population_size population
set elite_size = elite_size
set mutation_rate = mutation_rate
set generations = generations
end fun... | import random
from fitness import Fitness
class GA:
def __init__(self, population, population_size, elite_size, mutation_rate, generations):
self.initial_pop = self.generate_initial_pop(population_size, population)
self.elite_size = elite_size
self.mutation_rate = mutation_rate
self... | Python | zaydzuhri_stack_edu_python |
function _var_key var
begin
comment pylint: disable=protected-access
comment Get the distributed variable if it exists.
if get attribute var string _distributed_container none is not none
begin
set var = call _distributed_container
end
if _in_graph_mode
begin
return _shared_name
end
return _unique_id
end function | def _var_key(var):
# pylint: disable=protected-access
# Get the distributed variable if it exists.
if getattr(var, "_distributed_container", None) is not None:
var = var._distributed_container()
if var._in_graph_mode:
return var._shared_name
return var._unique_id | Python | nomic_cornstack_python_v1 |
import sys
set input = readline
set S = input
if string 9 in S
begin
print string Yes
end
else
begin
print string No
end | import sys
input = sys.stdin.readline
S = input()
if "9" in S: print("Yes")
else: print("No") | Python | zaydzuhri_stack_edu_python |
string 第 0003 题: 将 0001 题生成的 200 个激活码(或者优惠券)保存到 Redis 非关系型数据库中。
import uuid
import redis
function getcode count
begin
set codelist = list
for i in range count
begin
set code = string uuid 4
append codelist code
end
return codelist
end function
function save_code codelist
begin
set r = call Redis host=string 127.0.0.1 ... | """
第 0003 题: 将 0001 题生成的 200 个激活码(或者优惠券)保存到 Redis 非关系型数据库中。
"""
import uuid
import redis
def getcode(count):
codelist = []
for i in range(count):
code = str(uuid.uuid4())
codelist.append(code)
return codelist
def save_code(codelist):
r = redis.Redis(host='127.0.0.1', port='6379', pas... | Python | zaydzuhri_stack_edu_python |
function instance_template self
begin
return get pulumi self string instance_template
end function | def instance_template(self) -> pulumi.Input[str]:
return pulumi.get(self, "instance_template") | Python | nomic_cornstack_python_v1 |
import ping
class Stat
begin
function __init__ self
begin
set time = list
set results = dict string success 0 ; string failed 0
set min_time = 0
set max_time = 0
set avg_time = 0
end function
function get self
begin
if time
begin
set min_time = min time
set max_time = max time
set avg_time = sum time / length time
end... | import ping
class Stat:
def __init__(self):
self.time = []
self.results = {'success': 0, 'failed': 0}
self.min_time = 0
self.max_time = 0
self.avg_time = 0
def get(self):
if self.time:
self.min_time = min(self.time)
self.max_time = max(s... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
comment 指定默认字体
set rcParams at string font.sans-serif = list string SimHei
comment 解决保存图像是负号'-'显示为方块的问题
set rcParams at string axes.unicode_minus = false
comment PSO的参数
comment 惯性因子,一般取1
set w = 1
comment 学习因子,一般取2
set c1 = 2
set c2 = 2
comment... | import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['font.sans-serif'] = ['SimHei'] # 指定默认字体
mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
# PSO的参数
w = 1 # 惯性因子,一般取1
c1 = 2 # 学习因子,一般取2
c2 = 2 #
r1 = None # 为两个(0,1)之间的随机数
r2 = None
dim = 2 # 维度的维度
size = ... | Python | zaydzuhri_stack_edu_python |
function __len__ self
begin
return _weight_data at 1
end function | def __len__(self) -> int:
return self._weight_data[1] | Python | nomic_cornstack_python_v1 |
function generate_action_sequences num_sequences len_horizon env
begin
set action_sequences = zeros tuple num_sequences len_horizon shape at 0
for s in range num_sequences
begin
for h in range len_horizon
begin
comment random action
set action_sequences at tuple s h = random sample
end
end
return action_sequences
end f... | def generate_action_sequences(num_sequences, len_horizon, env):
action_sequences = np.zeros((num_sequences, len_horizon, env.action_space.shape[0]))
for s in range(num_sequences):
for h in range(len_horizon):
action_sequences[s,h] = env.action_space.sample() # random action
return action_sequences | Python | nomic_cornstack_python_v1 |
function get_task_type_scan_info self rawdata
begin
set task_info = ingest_header at string task_configuration at string task_scan_info
set mode = task_info at string antenna_scan_mode
set key = string task_type_scan_info
if mode in list 1 4
begin
set task_info at key = call _unpack_dictionary task_info at key TASK_PPI... | def get_task_type_scan_info(self, rawdata):
task_info = self.ingest_header["task_configuration"]["task_scan_info"]
mode = task_info["antenna_scan_mode"]
key = "task_type_scan_info"
if mode in [1, 4]:
task_info[key] = _unpack_dictionary(
task_info[key], TASK_PP... | Python | nomic_cornstack_python_v1 |
function print_to_screen inp
begin
print inp
end function | def print_to_screen(inp):
print(inp) | Python | nomic_cornstack_python_v1 |
function validate_request req
begin
set mandatory_fields = conf at string api at string mandatory-fields
set optional_fields = conf at string api at string optional-fields
if not content_length
begin
return dict string invalid string no data
end
set data = call get_json
for field in mandatory_fields
begin
if field not ... | def validate_request(req):
mandatory_fields = conf["api"]["mandatory-fields"]
optional_fields = conf["api"]["optional-fields"]
if not req.content_length:
return {"invalid": "no data"}
data = req.get_json()
for field in mandatory_fields:
if field not in data:
data["inva... | Python | nomic_cornstack_python_v1 |
function evaluate_polynomial polynomial x
begin
set terms = split polynomial string +
set result = 0
for term in terms
begin
set tuple factor exponent = split term string x^
set result = result + integer factor * x ^ integer exponent
end
return result
end function
set polynomial = string 4x^3 + 7x + 2
set x = 6
print c... | def evaluate_polynomial(polynomial, x):
terms = polynomial.split("+")
result = 0
for term in terms:
factor, exponent = term.split("x^")
result += int(factor)*(x**int(exponent))
return result
polynomial = "4x^3 + 7x + 2"
x = 6
print(evaluate_polynomial(polynomial, x))
| Python | flytech_python_25k |
function totalProfit name sortlist max
begin
set result = string go to + name + string and buy
set tp = 0
for i in range length sortlist
begin
if sortlist at i at 1 at 2 > 0
begin
if sortlist at i at 1 at 0 <= max
begin
set max = max - sortlist at i at 1 at 0
set t = sortlist at i at 1 at 2 * sortlist at i at 1 at 0
se... | def totalProfit(name,sortlist, max):
result= "go to "+ name+" and buy"
tp=0
for i in range(len(sortlist)):
if sortlist[i][1][2]>0 :
if sortlist[i][1][0]<=max:
max= max-sortlist[i][1][0]
t=(sortlist[i][1][2] * sortlist[i][1][0])
result= res... | Python | nomic_cornstack_python_v1 |
function set_downlink_rx_power self signal_level
begin
set new_config = call BtsConfig
set output_power = call calibrated_downlink_rx_power primary_config signal_level
call configure_bts new_config
call incorporate new_config
end function | def set_downlink_rx_power(self, signal_level):
new_config = self.BtsConfig()
new_config.output_power = self.calibrated_downlink_rx_power(
self.primary_config, signal_level)
self.simulator.configure_bts(new_config)
self.primary_config.incorporate(new_config) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string python读取文件,每两行为一组
import io
function fenhang infile outfile
begin
set infopen = open infile string r encoding=string utf-8
set outopen = open outfile string w encoding=string utf-8
set lines = read lines infopen
set i = 1
end function | # -*- coding: utf-8 -*-
'''
python读取文件,每两行为一组
'''
import io
def fenhang(infile,outfile):
infopen = io.open(infile,'r',encoding='utf-8')
outopen = io.open(outfile,'w',encoding='utf-8')
lines = infopen.readlines()
i = 1 | Python | zaydzuhri_stack_edu_python |
comment 1. all wikipedia links
set links = set links
length links
comment 2. all high textrank terms
for link in links
begin
call add_word link
end
set high_textrank_terms = set call textrank content topK=integer length content * 0.1 withWeight=false
length high_textrank_terms
high_textrank_terms
comment 3. all nouns i... | # 1. all wikipedia links
links = set(page.links)
len(links)
# 2. all high textrank terms
for link in links:
jieba.add_word(link)
high_textrank_terms = set(jieba.analyse.textrank(page.content, topK=int(len(page.content)*0.1), withWeight=False))
len(high_textrank_terms)
high_textrank_terms
# 3. all nouns in sentence... | Python | zaydzuhri_stack_edu_python |
string leetcode 2280: Minimum lines to represent line chart. Given a 2D integer array 'prices' where price[i] = (day, price) indicates the price of a stock on 'day' is 'price', a line chart is created from the array by plotting the points on a 2D plane with the x-axis representing the day and the y-axis representing th... | """
leetcode 2280: Minimum lines to represent line chart.
Given a 2D integer array 'prices' where price[i] = (day, price) indicates the
price of a stock on 'day' is 'price', a line chart is created from the array by
plotting the points on a 2D plane with the x-axis representing the day and the
y-axis representing the ... | Python | zaydzuhri_stack_edu_python |
import asyncio
from binance import AsyncClient , BinanceSocketManager
from datetime import datetime
comment Exercise 1
async function main
begin
set client = await call create
set bm = call BinanceSocketManager client
comment start any sockets here, i.e a trade socket
set ts = call trade_socket string ETHBUSD
comment t... | import asyncio
from binance import AsyncClient, BinanceSocketManager
from datetime import datetime
# Exercise 1
async def main():
client = await AsyncClient.create()
bm = BinanceSocketManager(client)
# start any sockets here, i.e a trade socket
ts = bm.trade_socket('ETHBUSD')
# then start receivi... | Python | zaydzuhri_stack_edu_python |
comment 문자열의 오른쪽에 공백이 있을 때 이를 제거해보세요.
set data = string 039490
set data = right strip data
print data | # 문자열의 오른쪽에 공백이 있을 때 이를 제거해보세요.
data = "039490 "
data = data.rstrip()
print(data)
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
string For the specified gene and locus lists, determine which genes are located within a specific range from the middle or edges of each locus. The gene symbols are then added to the last column of the locus table and printed to the output file. Usage: python3 get_genes_in_range.py -i <in... | #!/usr/bin/env python3
"""
For the specified gene and locus lists, determine which genes are located within a specific range from the middle or edges of each locus.
The gene symbols are then added to the last column of the locus table and printed to the output file.
Usage: python3 get_genes_in_range.py -i <input.bed>... | Python | zaydzuhri_stack_edu_python |
import wget
call download string url | import wget
wget.download('url')
| Python | jtatman_500k |
function forward_train self imgs label token_ids=none segment_ids=none input_mask=none ans_ids=none ans_mask=none **kwargs
begin
comment (batch_size, num_clips*num_crops, channel, num_segments, h, w) -> (batch_size*num_clips*num_crops, channel, num_segments, h, w)
set imgs = reshape imgs tuple - 1 + shape at slice 2 : ... | def forward_train(self, imgs, label, token_ids=None, segment_ids=None, input_mask=None, ans_ids=None, ans_mask=None, **kwargs):
# (batch_size, num_clips*num_crops, channel, num_segments, h, w) -> (batch_size*num_clips*num_crops, channel, num_segments, h, w)
imgs = imgs.reshape((-1, ) + imgs.shape[2:])
... | Python | nomic_cornstack_python_v1 |
function HP self
begin
return _hp
end function | def HP(self):
return self._hp | Python | nomic_cornstack_python_v1 |
import unittest
from alphabets import RUSSIAN_ALPHABET , ENGLISH_ALPHABET
from binary_gamma_chiper import BinaryGammaCipher
class TestAtbashCipher extends TestCase
begin
function setUp self
begin
set alphabet = list
set table = list
extend alphabet upper RUSSIAN_ALPHABET
extend table range 192 197 + 1
append table 16... | import unittest
from ..alphabets import RUSSIAN_ALPHABET, ENGLISH_ALPHABET
from ..binary_gamma_chiper import BinaryGammaCipher
class TestAtbashCipher(unittest.TestCase):
def setUp(self):
alphabet = []
table = []
alphabet.extend(RUSSIAN_ALPHABET.upper())
table.extend(range(0xC0, 0... | Python | zaydzuhri_stack_edu_python |
function fetch_digital_ocean api_key ignore_tags=none
begin
set message = string
set instances = list
set capable = false
set active_droplets = none
if ignore_tags is none
begin
set ignore_tags = list
end
set headers = dict string Content-Type string application/json
try
begin
set active_droplets = get requests digi... | def fetch_digital_ocean(api_key, ignore_tags=None):
message = ""
instances = []
capable = False
active_droplets = None
if ignore_tags is None:
ignore_tags = []
headers = {"Content-Type": "application/json"}
try:
active_droplets = requests.get(
digital_ocean_endpo... | Python | nomic_cornstack_python_v1 |
function insert self num
begin
comment Do nothing if number is already present
if data == num
begin
return self
end
comment Insert number into BST
if num < data
begin
if left is none
begin
set left = call Node num
set up = self
end
else
begin
insert left num
end
end
else
if right is none
begin
set right = call Node num... | def insert(self,num):
# Do nothing if number is already present
if self.data == num:
return self
# Insert number into BST
if num < self.data:
if self.left is None:
self.left = Node(num)
self.left.up = self
else:... | Python | nomic_cornstack_python_v1 |
function create_habit content recipient_id hour
begin
set habit = call Habit recipient_id=recipient_id content=content
save
set schedule = call Schedule habit_id=habit hour=hour
save
end function | def create_habit(content, recipient_id, hour):
habit = Habit(recipient_id=recipient_id, content=content)
habit.save()
schedule = Schedule(habit_id=habit, hour=hour)
schedule.save() | Python | nomic_cornstack_python_v1 |
function validate_types self
begin
for req in requests
begin
set required_types = call get_required_types
set available_types = call get_types
end
end function | def validate_types(self):
for req in self.requests:
required_types = req.get_required_types()
available_types = self.substrate.get_types() | Python | nomic_cornstack_python_v1 |
import random
comment generating random number from 0 to 100
print random integer 0 100
comment generating random number from 0 to 100
print random integer 0 100
comment generating random number from 0 to 100
print random integer 0 100
comment generating random number from 0 to 100
print random integer 0 100 | import random
print(random.randint(0,100)) #generating random number from 0 to 100
print(random.randint(0,100)) #generating random number from 0 to 100
print(random.randint(0,100)) #generating random number from 0 to 100
print(random.randint(0,100)) #generating random number from 0 to 100 | Python | zaydzuhri_stack_edu_python |
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import matplotlib.pyplot as plt
from sklearn.svm import SVC
comment 导入mglearn模块
import sys
append path string ../
import mglearn
set tuple X y = call make_blobs n_samples=tuple 400 50 centers=2 cluster_std=list 7.0 2 ... | from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import matplotlib.pyplot as plt
from sklearn.svm import SVC
# 导入mglearn模块
import sys
sys.path.append("../")
import mglearn
X, y = mglearn.datasets.make_blobs(n_samples=(400, 50), centers=2, cluster_std=[7.0, 2], ran... | Python | zaydzuhri_stack_edu_python |
class tense
begin
function Fancy self jeans
begin
set jeans = jeans
print jeans
end function
end class
class present extends tense
begin
function Stylish self skirts
begin
set skirts = skirts
print skirts
end function
end class
class future extends present
begin
function orthodox self saree
begin
set saree = saree
prin... | class tense:
def Fancy(self,jeans):
self.jeans=jeans
print(self.jeans)
class present(tense):
def Stylish(self,skirts):
self.skirts=skirts
print(self.skirts)
class future(present):
def orthodox(self,saree):
self.saree=saree
print(self.saree)
obj=tense()
obj.Fan... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
set df = read csv string C:/Users/lenovo/Desktop/trip.csv
import numpy as np
from scipy.stats import norm
from keras.layers import Input , Dense , Lambda
from keras.models import Model
from keras import backend as K
from keras import metrics
import tensorflow as tf
import matplotlib.pyplot as plt
co... | import pandas as pd
df=pd.read_csv('C:/Users/lenovo/Desktop/trip.csv')
import numpy as np
from scipy.stats import norm
from keras.layers import Input,Dense,Lambda
from keras.models import Model
from keras import backend as K
from keras import metrics
import tensorflow as tf
import matplotlib.pyplot as pl... | Python | zaydzuhri_stack_edu_python |
from selenium import webdriver
import csv
import time
import codecs
set f_csv = open string ncku_course.csv string w encoding=string utf_8_sig
set writer = writer f_csv
set course_list_name = list string 學院 string 系所名稱 string 系號-序號 string 課程碼-分班碼 string 屬性碼 string 年級 string 類別 string 科目名稱 string 學分 string 必/選修 string 教... | from selenium import webdriver
import csv
import time
import codecs
f_csv = codecs.open('ncku_course.csv', 'w', encoding="utf_8_sig")
writer = csv.writer(f_csv)
course_list_name = ['學院','系所名稱', '系號-序號', '課程碼-分班碼', '屬性碼', '年級', '類別',
'科目名稱', '學分', '必/選修', '教師姓名', '已選課人數/餘額', '時間', '教室', '課程大綱']
wri... | Python | zaydzuhri_stack_edu_python |
function test_get_score self mock__calculate_strike_score mock__calculate_spare_score mock__calculate_open_score
begin
set score = call get_score
assert is none score
set frame_type = OPEN
set score = call get_score
assert equal score return_value
set frame_type = SPARE
set score = call get_score
assert equal score ret... | def test_get_score(
self,
mock__calculate_strike_score,
mock__calculate_spare_score,
mock__calculate_open_score
):
score = self.frame.get_score()
self.assertIsNone(score)
self.frame.frame_type = Frame.OPEN
score = self.frame.get_score()
self.a... | Python | nomic_cornstack_python_v1 |
string Class implementing the agents' behavior
import numpy as np
import random
import math
import cvxpy as cp
class Agent extends object
begin
function __init__ self agent_id agent_type x_real delta
begin
set id = agent_id
set type = agent_type at agent_id
set delta = delta
comment array([x,y])
set x_real = x_real at ... | ''' Class implementing the agents' behavior '''
import numpy as np
import random
import math
import cvxpy as cp
class Agent(object):
def __init__(self, agent_id, agent_type, x_real, delta):
self.id = agent_id
self.type = agent_type[agent_id]
self.delta = delt... | Python | zaydzuhri_stack_edu_python |
function failure_threshold self
begin
return get pulumi self string failure_threshold
end function | def failure_threshold(self) -> Optional[pulumi.Input[int]]:
return pulumi.get(self, "failure_threshold") | Python | nomic_cornstack_python_v1 |
function instantiate_model_from_ast x y ast params=none
begin
set kernel = call ast_to_kernel ast build=true
return call instantiate_model_from_kernel x y kernel params=params
end function | def instantiate_model_from_ast(x: np.ndarray, y: np.ndarray, ast: Node,
params: Optional[Dict[str, np.ndarray]]=None) -> gpflow.models.GPR:
kernel = ast_to_kernel(ast, build=True)
return instantiate_model_from_kernel(x, y, kernel, params=params) | Python | nomic_cornstack_python_v1 |
import numpy
class newtongauss
begin
decorator staticmethod
comment f is the vectorised function
comment fs is scalar version of function
comment p adjustable parameters of function
comment pf fixed parameters of function
comment x array
comment y array
function fit f p pf x y fs=none
begin
if fs == none
begin
set fs =... | import numpy
class newtongauss:
# f is the vectorised function
# fs is scalar version of function
# p adjustable parameters of function
# pf fixed parameters of function
# x array
# y array
@staticmethod
def fit(f, p, pf, x, y, fs = None):
if(fs == None):
fs = f
p_best = p... | Python | zaydzuhri_stack_edu_python |
import cv2
set lena = call imread string lena.bmp IMREAD_UNCHANGED
comment 添加文字
set font = FONT_HERSHEY_SIMPLEX
call putText lena string mao tuple 0 100 font 2 tuple 255 255 255 7
comment 显示
image show string demo lena
set key = call waitKey
comment 关闭
call destroyAllWindows
comment 保存
comment cv2.imwrite( 'result.bmp'... | import cv2
lena = cv2.imread('lena.bmp', cv2.IMREAD_UNCHANGED)
# 添加文字
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(lena, "mao", (0, 100), font, 2, (255, 255, 255), 7)
# 显示
cv2.imshow("demo", lena )
key=cv2.waitKey()
# 关闭
cv2.destroyAllWindows()
# 保存
# cv2.imwrite( 'result.bmp', lena )
| Python | zaydzuhri_stack_edu_python |
function send self email
begin
return call receive email
end function | def send(self, email):
return self.clients[email.recipient_name].receive(email) | Python | nomic_cornstack_python_v1 |
comment Sprite class for platform game
import pygame as pg
from settings import *
set vec = Vector2
class Spritesheet
begin
comment utility for loading sprites
function __init__ self filename
begin
set spritesheet = call convert
end function
function get_image self x y width height
begin
comment grab an image out of la... | # Sprite class for platform game
import pygame as pg
from settings import *
vec = pg.math.Vector2
class Spritesheet:
# utility for loading sprites
def __init__(self, filename):
self.spritesheet = pg.image.load(filename).convert()
def get_image(self, x, y, width, height):
# grab an image o... | Python | zaydzuhri_stack_edu_python |
function tokenize text
begin
comment regular expression to avoid pucntuations or any special character
set tokenizer = call RegexpTokenizer string \w+
comment tokenizing text
set tokens = call tokenize text
comment initiating lemmatizer
set lemmatizer = call WordNetLemmatizer
comment iteratating through each token
set ... | def tokenize(text):
#regular expression to avoid pucntuations or any special character
tokenizer = nltk.RegexpTokenizer(r"\w+")
#tokenizing text
tokens = tokenizer.tokenize(text)
#initiating lemmatizer
lemmatizer = WordNetLemmatizer()
#iteratating through each token
c... | Python | nomic_cornstack_python_v1 |
function compute_PSL filename inputinf=none
begin
set ncfile = call Dataset filename string r
comment Get the sea level pressure using wrf-python
set psl = call getvar ncfile string slp ALL_TIMES
comment Smooth the sea level pressure since it tends to be noisy near the mountains
set smooth_psl = call smooth2d psl 3
set... | def compute_PSL(filename,inputinf=None):
ncfile = nc.Dataset(filename,'r')
# Get the sea level pressure using wrf-python
psl = wrf.getvar(ncfile, "slp",wrf.ALL_TIMES)
# Smooth the sea level pressure since it tends to be noisy near the mountains
smooth_psl = wrf.smooth2d(psl, 3)
atts = {"st... | Python | nomic_cornstack_python_v1 |
function is_env_set env value
begin
comment JAVA OPTS is not required to be set
if env is string JAVA_OPTS
begin
info string Environment variable JAVA_OPTS is set to %s value
return true
end
if not value
begin
error string Environment variable %s is not set env
return false
end
info string Environment variable %s is se... | def is_env_set(env, value):
# JAVA OPTS is not required to be set
if env is 'JAVA_OPTS':
logging.info("Environment variable JAVA_OPTS is set to %s", value)
return True
if not value:
logging.error("Environment variable %s is not set", env)
return False
logging.info("Environme... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3.4
set T = integer input
for case in range 1 T + 1
begin
set gab = string Case #%d: GABRIEL % case
set ric = string Case #%d: RICHARD % case
set tuple X R C = map int split input
if R > C
begin
set tuple R C = tuple C R
end
if X == 1
begin
print gab
end
if X == 2
begin
if R * C % 2 == 1
begin
p... | #!/usr/bin/python3.4
T = int(input())
for case in range(1, T + 1):
gab = "Case #%d: GABRIEL" % case
ric = "Case #%d: RICHARD" % case
X, R, C = map(int, input().split())
if (R > C):
R, C = C, R
if (X == 1):
print(gab)
if (X == 2):
if ((R*C % 2) == 1):
print(... | Python | zaydzuhri_stack_edu_python |
import requests
from flask import Flask , render_template , redirect , request
from flask_mysqldb import MySQL
import re
import json
from flask import flash
set app = call Flask __name__
set secret_key = b'_5#y2L"F4Q8z\n\xec]/'
set config at string MYSQL_HOST = string 127.0.0.1
set config at string MYSQL_USER = string ... | import requests
from flask import Flask, render_template, redirect, request
from flask_mysqldb import MySQL
import re
import json
from flask import flash
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
app.config['MYSQL_HOST'] = '127.0.0.1'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'... | Python | zaydzuhri_stack_edu_python |
function _maybe_load_checkpoint self checkpoint_path mode
begin
if not checkpoint_path
begin
info string No checkpoint was provided, using randomly initialized model parameters.
set _global_step = 0
set _initial_step = 0
return
end
if CSOFT_PACKAGE in tuple SRC WHEEL
begin
from cerebras_pytorch.saver.pt_h5_saver import... | def _maybe_load_checkpoint(self, checkpoint_path: Optional[str], mode: str):
if not checkpoint_path:
logging.info(
f"No checkpoint was provided, using randomly initialized model "
f"parameters."
)
self._global_step = 0
self._initial... | Python | nomic_cornstack_python_v1 |
comment !usr/bin/python
string Owner :Jaideep Kekre #_author_ = Jaideep Kekre #_info_ = This module contains a Python Script
import xml.etree.ElementTree as ET
import math
set tree = parse ET string math2.xml
set root = get root tree
comment print root
set op1 = list
set oper = string
set x = string | #!usr/bin/python
"""
Owner :Jaideep Kekre
#_author_ = Jaideep Kekre
#_info_ = This module contains a Python Script
"""
import xml.etree.ElementTree as ET
import math
tree = ET.parse('math2.xml')
root = tree.getroot()
#print root
op1 = list()
oper = ""
x = "" | Python | zaydzuhri_stack_edu_python |
function handle_error self destination reason
begin
comment Create dummy data for the source, destination, and signature fields.
set s = string 0 * 128
set d = string 0 * 128
set sign = s * 3
comment Format the message according to the protocol.
set message = call format_content ERROR s d reason sign
comment Send the m... | def handle_error(self, destination: socket, reason: HexString) -> None:
# Create dummy data for the source, destination, and signature fields.
s = d = "0" * 128
sign = s * 3
# Format the message according to the protocol.
message = Protocol.format_content(Protocol.MessageTypes.ER... | Python | nomic_cornstack_python_v1 |
function test_add_collision_filter_group_struct self
begin
set dut = call AddCollisionFilterGroup name=string foo
assert in string foo call repr dut
copy copy dut
deep copy dut
end function | def test_add_collision_filter_group_struct(self):
dut = AddCollisionFilterGroup(name="foo")
self.assertIn("foo", repr(dut))
copy.copy(dut)
copy.deepcopy(dut) | Python | nomic_cornstack_python_v1 |
function __init__ __self__ enabled
begin
set __self__ string enabled enabled
end function | def __init__(__self__, *,
enabled: bool):
pulumi.set(__self__, "enabled", enabled) | Python | nomic_cornstack_python_v1 |
from copy import deepcopy
from random import randrange
comment triplets de hoare
comment Input: t, N = len(t), a, b, c
comment PE:
comment N >= 1
comment (t[a:b+1], <=)
comment (t[b+1:c+1], <=)
comment fusion(t, a, b, c)
comment PS:
comment (t[a:c+1], <=)
comment t = permut(T)
function fusion t a b c
begin
set before =... | from copy import deepcopy
from random import randrange
# triplets de hoare
# Input: t, N = len(t), a, b, c
# PE:
# N >= 1
# (t[a:b+1], <=)
# (t[b+1:c+1], <=)
# fusion(t, a, b, c)
# PS:
# (t[a:c+1], <=)
# t = permut(T)
def fusion(t, a, b, c):
before = t[0:a]
after = t[c+1:]
first = t[a : b+1]
lenF ... | Python | zaydzuhri_stack_edu_python |
function _iterative_graph_search cls bqm sample ordered_priority visited size method
begin
set graph = call to_networkx_graph
call remove_nodes_from visited
set variables = set
set order = iterate ordered_priority
while length variables < size and length graph
begin
comment find the next untraversed variable in (energy... | def _iterative_graph_search(cls, bqm, sample, ordered_priority, visited, size, method):
graph = bqm.to_networkx_graph()
graph.remove_nodes_from(visited)
variables = set()
order = iter(ordered_priority)
while len(variables) < size and len(graph):
# find the next untr... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Thu Oct 4 15:37:42 2018 @author: anec
comment main script to run to get the charge (coulomb passed), CO2RR product distribution, FE distribution for each fill
from collections import defaultdict
from glob import glob
import pandas as pd
import os
from Coulomb import coulo... | # -*- coding: utf-8 -*-
"""
Created on Thu Oct 4 15:37:42 2018
@author: anec
"""
# main script to run to get the charge (coulomb passed), CO2RR product distribution, FE distribution for each fill
from collections import defaultdict
from glob import glob
import pandas as pd
import os
from Coulomb import c... | Python | zaydzuhri_stack_edu_python |
function lambda_handler event context
begin
comment pylint: disable=unused-argument,broad-except
info event
set is_test_run = event == string TEST_RUN
if is_test_run
begin
warning string Going through test run, will not actually scale anything
end
comment Initialize data.
set cluster_defs = call load_cluster_defs
set c... | def lambda_handler(event, context):
# pylint: disable=unused-argument,broad-except
logger.info(event)
is_test_run = event == "TEST_RUN"
if is_test_run:
logger.warning(
"Going through test run, will not actually scale anything"
)
# Initialize data.
cluster_defs = loa... | Python | nomic_cornstack_python_v1 |
while string multiply in my_input
begin
set index = index my_input string multiply
set n1 = integer index - 1
set n2 = integer index + 1
set rezult = integer my_input at n1 * integer my_input at n2
set my_input at n1 = rezult
pop my_input n2
pop my_input index
print string =======
print my_input
end
while string divide... | while 'multiply' in my_input:
index=my_input.index('multiply')
n1=int(index)-1
n2=int(index)+1
rezult=int(my_input[n1]) * int(my_input[n2])
my_input[n1]=rezult
my_input.pop(n2)
my_input.pop(index)
print("=======")
print(my_input)
while 'divide' in my_input:
index=my_input.index(... | Python | zaydzuhri_stack_edu_python |
function get_broker broker_id=none broker_name=none tags=none opts=none
begin
set __args__ = dictionary
set __args__ at string brokerId = broker_id
set __args__ at string brokerName = broker_name
set __args__ at string tags = tags
set opts = merge call get_invoke_opts_defaults opts
set __ret__ = value
return call Await... | def get_broker(broker_id: Optional[str] = None,
broker_name: Optional[str] = None,
tags: Optional[Mapping[str, str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetBrokerResult:
__args__ = dict()
__args__['brokerId'] = broker_id
__args__['bro... | Python | nomic_cornstack_python_v1 |
function getPandaIDsWithTaskID jediTaskID verbose=false
begin
comment instantiate curl
set curl = call _Curl
set verbose = verbose
comment execute
set url = baseURL + string /getPandaIDsWithTaskID
set data = dict string jediTaskID jediTaskID
set tuple status output = post url data
try
begin
return tuple status call pic... | def getPandaIDsWithTaskID(jediTaskID,verbose=False):
# instantiate curl
curl = _Curl()
curl.verbose = verbose
# execute
url = baseURL + '/getPandaIDsWithTaskID'
data = {'jediTaskID':jediTaskID}
status,output = curl.post(url,data)
try:
return status, pickle_loads(output)
excep... | Python | nomic_cornstack_python_v1 |
function is_point_inside self q
begin
return call orient p1 p2 q == call orient p2 p3 q == call orient p3 p1 q
end function | def is_point_inside(self, q):
return orient(self.p1, self.p2, q) == orient(self.p2, self.p3, q) == orient(self.p3, self.p1, q) | Python | nomic_cornstack_python_v1 |
comment Project Experiment 4
from agent import Agent
from PDWorld import World
from SelectMove import SelectMove
from Storing import updateMatrix
import copy
import pygame
from Visualize import Visual
class E4
begin
set agent = call Agent 0 4 false
set oldAgent1 = deep copy agent
set oldAgent2 = deep copy agent
set hav... | # Project Experiment 4
from agent import Agent
from PDWorld import World
from SelectMove import SelectMove
from Storing import updateMatrix
import copy
import pygame
from Visualize import Visual
class E4:
agent = Agent(0, 4, False)
oldAgent1 = copy.deepcopy(agent)
oldAgent2 = copy.deepcopy(agent)
have... | Python | zaydzuhri_stack_edu_python |
function run self
begin
while not _stopping
begin
try
begin
set _connection = call connect
start ioloop
end
except KeyboardInterrupt
begin
call stop
if _connection is not none and not is_closed
begin
start ioloop
end
end
end
print string Stopping publisher thread
end function | def run(self):
while not self._stopping:
try:
self._connection = self.connect()
self._connection.ioloop.start()
except KeyboardInterrupt:
self.stop()
if (self._connection is not None and not self._connection.is_closed):
... | Python | nomic_cornstack_python_v1 |
function output self
begin
comment call frcnn method
call frcnn
comment call charseg method
call charseg
comment call predict method
predict self
print string
print string ---------------------------------------------------------
if exists path string ./outputs/out.csv
begin
set outfile = open string ./outputs/out.csv ... | def output(self):
self.frcnn()#call frcnn method
self.charseg()#call charseg method
self.predict()#call predict method
print("\n")
print("---------------------------------------------------------")
if os.path.exists("./outputs/out.csv"):
outfile = open('./outp... | Python | nomic_cornstack_python_v1 |
function check x
begin
if x % 2 == 0 or x % 4 == 0
begin
return 1
end
end function
set evens = list filter check range 2 22
print evens
function checkkrbhai num
begin
if num % 2 == 0 or num % 4 == 0
begin
return 1
end
end function
set number = list filter checkkrbhai range 2 70
print number | def check(x):
if(x % 2 == 0 or x % 4 == 0):
return 1
evens=list(filter(check, range(2,22)))
print(evens)
def checkkrbhai(num):
if(num % 2 ==0 or num % 4 ==0):
return 1
number=list(filter(checkkrbhai, range(2,70)))
print(number)
| Python | zaydzuhri_stack_edu_python |
function get self key **kwargs
begin
set fp = string { url } / { key } .gz
yield from call deserialize_shard_from_file fp fs=fs keyword kwargs
end function | def get(self, key: str, **kwargs) -> t.Iterator[SampleType]:
fp = f"{self.url}/{key}.gz"
yield from self.serializer.deserialize_shard_from_file(fp, fs=self.fs, **kwargs) | Python | nomic_cornstack_python_v1 |
import argparse
import re
import sys
function parse_args argv
begin
set p = call ArgumentParser
call add_argument string --sizeX type=int default=7
call add_argument string --sizeY type=int default=7
call add_argument string --type choices=list string number string pos1 string pos2 string pos3 string error1x string err... | import argparse
import re
import sys
def parse_args(argv):
p = argparse.ArgumentParser()
p.add_argument("--sizeX", type=int, default=7)
p.add_argument("--sizeY", type=int, default=7)
p.add_argument("--type", choices=['number','pos1','pos2','pos3', 'error1x', 'error1y', 'error2x', 'error2y', 'error3x',... | Python | zaydzuhri_stack_edu_python |
function str self
begin
return gameState
end function | def str(self):
return self.gameState | Python | nomic_cornstack_python_v1 |
function check_interface_vlan self interface vlan vdc=none
begin
assert is instance vlan str
assert is instance interface str
set interface = title interface
set checkflag = false
for vdcname in vdc
begin
set checkflag = checkflag or call check_interface_vlan interface vlan
end
return checkflag
end function | def check_interface_vlan(self, interface, vlan, vdc=None):
assert isinstance(vlan, str)
assert isinstance(interface, str)
interface = interface.title()
checkflag = False
for vdcname in vdc:
checkflag = checkflag or self.vdcs[vdcname].check_interface_vlan(interface, v... | Python | nomic_cornstack_python_v1 |
function fit_event self x y
begin
set list xs sxs sigmas = call find_known_lines linelist ll spec options
set foundlines = xs
set foundlinesig = sxs
set mask = call isfinite sxs
set local_linelist = linelist at mask
set xs = xs at mask
set sxs = sxs at mask
set list deltas cfit perror = call fit_chebyshev_to_lines xs s... | def fit_event(self, x, y):
[xs, sxs, sigmas] = find_known_lines(self.linelist, self.ll,
self.spec, self.options)
self.foundlines = xs
self.foundlinesig = sxs
mask = (np.isfinite(sxs))
local_linelist=self.linelist[mask]
xs = xs[mask]
sxs = sxs[mask]
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Mon May 4 11:18:33 2020 @author: AsteriskAmpersand
function startReplace self
begin
call startRecording
return
end function
function _pathReplace self index rindex content
begin
set record = call access index
set attribute record string path%d % rindex content
call emit i... | # -*- coding: utf-8 -*-
"""
Created on Mon May 4 11:18:33 2020
@author: AsteriskAmpersand
"""
def startReplace(self):
self.startRecording()
return
def _pathReplace(self,index,rindex,content):
record = self.access(index)
setattr(record,"path%d"%rindex,content)
self.pathEdited.emit(index,rindex)
... | Python | zaydzuhri_stack_edu_python |
function mark_neighbors row col
begin
comment use recursion to mark all the neighbor ones, and their neighbor ones and so on, until no neighbors are left. So we make sure that if a 1 is marked, no other ones that are attached to it will not be marked as a separate leap
set board at row at col = - 1
if row + 1 < length ... | def mark_neighbors(row, col):
# use recursion to mark all the neighbor ones, and their neighbor ones and so on, until no neighbors are left. So we make sure that if a 1 is marked, no other ones that are attached to it will not be marked as a separate leap
board[row][col] = -1
if row + 1 < len(board) and ... | Python | zaydzuhri_stack_edu_python |
string 问题2: 输入一个数,计算并在控制台打印出这个数的阶乘
function is_digital str
begin
try
begin
integer str
return true
end
except tuple TypeError ValueError
begin
return false
end
end function
set num = string 8
if not call is_digital num
begin
print string the number you input is not digit
end
else
begin
set result = 1
set d = integer nu... | """
问题2: 输入一个数,计算并在控制台打印出这个数的阶乘
"""
def is_digital(str):
try:
int(str)
return True
except (TypeError, ValueError):
return False
num = '8'
if not is_digital(num):
print('the number you input is not digit')
else:
result = 1
d = int(num)
while d > 0:
result *= d
... | Python | zaydzuhri_stack_edu_python |
from __future__ import print_function
from apiclient import discovery
from httplib2 import Http
from oauth2client import file , client , tools
set SCOPES = string https://www.googleapis.com/auth/spreadsheets.readonly
comment The ID and range of a sample spreadsheet.
set SAMPLE_SPREADSHEET_ID = string 1ZH-JVx8LL09L0stBu... | from __future__ import print_function
from apiclient import discovery
from httplib2 import Http
from oauth2client import file, client, tools
SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1ZH-JVx8LL09L0stBu2RBF-zi1ElqOtQapWFQAQBD... | Python | zaydzuhri_stack_edu_python |
function rafraichir_position adversaire *arg
begin
for nom_du_bateau in arg
begin
for elements in range taille_bateau
begin
set col = coordonnees_bateau at elements at 1
set rangee = coordonnees_bateau at elements at 0
if tableau at rangee at col == string @
begin
set coordonnees_bateau at elements at 2 = string @
end
... | def rafraichir_position(adversaire: object, *arg):
for nom_du_bateau in arg:
for elements in range(nom_du_bateau.taille_bateau):
col = nom_du_bateau.coordonnees_bateau[elements][1]
rangee = nom_du_bateau.coordonnees_bateau[elements][0]
if adversaire.plateau_joueur.tableau... | Python | nomic_cornstack_python_v1 |
function convert_nkjp nkjp_path output_dir
begin
comment Load XML NKJP
print string Reading data from %s % nkjp_path
if is file path nkjp_path and ends with nkjp_path string .tar.gz or ends with nkjp_path string .tgz
begin
with temporary directory as nkjp_dir
begin
print string Temporarily extracting %s to %s % tuple n... | def convert_nkjp(nkjp_path, output_dir):
# Load XML NKJP
print("Reading data from %s" % nkjp_path)
if os.path.isfile(nkjp_path) and (nkjp_path.endswith(".tar.gz") or nkjp_path.endswith(".tgz")):
with tempfile.TemporaryDirectory() as nkjp_dir:
print("Temporarily extracting %s to %s" % (nk... | Python | nomic_cornstack_python_v1 |
while l < r
begin
if s at l == string x
begin
if s at r == string x
begin
set l = l + 1
set r = r - 1
end
else
begin
set a = a + 1
set l = l + 1
end
end
else
if s at r == string x
begin
set a = a + 1
set r = r - 1
end
else
if s at l == s at r
begin
set l = l + 1
set r = r - 1
end
else
begin
print - 1
exit
end
end
print... | while l<r:
if s[l]=="x":
if s[r]=="x":
l+=1
r-=1
else:
a+=1
l+=1
else:
if s[r]=="x":
a+=1
r-=1
else:
if s[l]==s[r]:
l+=1
r-=1
else:
print(-1)
exit()
print(a) | Python | zaydzuhri_stack_edu_python |
function huge_attack self other
begin
if _mp >= 50
begin
set _mp = _mp - 50
set injury = hp * 3 // 4
set injury = if expression injury >= 50 then injury else 50
set hp = hp - injury
return true
end
else
begin
call attack other
return false
end
end function | def huge_attack(self, other):
if self._mp >= 50:
self._mp -= 50
injury = other.hp * 3 // 4
injury = injury if injury >= 50 else 50
other.hp -= injury
return True
else:
self.attack(other)
return False | Python | nomic_cornstack_python_v1 |
from tkinter import *
from random import randint
import time
class Snake
begin
function __init__ self row col size field_color snake_color food_color
begin
set row = row
set col = col
set size = size
set field_color = field_color
set snake_color = snake_color
set food_color = food_color
set snake_array = list
set y = ... | from tkinter import *
from random import randint
import time
class Snake():
def __init__(self, row, col, size, field_color, snake_color, food_color):
self.row = row
self.col = col
self.size = size
self.field_color = field_color
self.snake_color = snake_color
... | Python | zaydzuhri_stack_edu_python |
function issue_date self
begin
string Date when the DOI was issued (:class:`datetime.datetime.Datetime`).
set dates = call _pluralize _r at string dates string date
for date in dates
begin
if date at string @dateType == string Issued
begin
return string parse time date at string #text string %Y-%m-%d
end
end
end functi... | def issue_date(self):
"""Date when the DOI was issued (:class:`datetime.datetime.Datetime`).
"""
dates = _pluralize(self._r['dates'], 'date')
for date in dates:
if date['@dateType'] == 'Issued':
return datetime.datetime.strptime(date['#text'], '%Y-%m-%d') | Python | jtatman_500k |
function get_assessments_offered self
begin
comment osid.assessment.AssessmentOfferedList
return
end function | def get_assessments_offered(self):
return # osid.assessment.AssessmentOfferedList | Python | nomic_cornstack_python_v1 |
function main
begin
print string Se quiser fazer o procedimento no diretório atual e arquivo a ser copiado esta nele
print string apenas entre com o nome do arquivo já existente e o nome do novo arquivo
set antigo = input string caminho do arquivo a ser copiado:
set valido = true
try
begin
set arquivo = open antigo str... | def main():
print('Se quiser fazer o procedimento no diretório atual e arquivo a ser copiado esta nele')
print('apenas entre com o nome do arquivo já existente e o nome do novo arquivo\n')
antigo = input('caminho do arquivo a ser copiado: ')
valido = True
try:
arquivo = open(antigo, 'r')
... | Python | zaydzuhri_stack_edu_python |
function sum_add_two_dictionaries dict dict_to_add
begin
comment go over the dictionary to add
for key in dict_to_add
begin
if key in dict
begin
set dict at key = dict at key + dict_to_add at key
end
else
begin
set dict at key = dict_to_add at key
end
end
end function | def sum_add_two_dictionaries(dict, dict_to_add):
# go over the dictionary to add
for key in dict_to_add:
if key in dict:
dict[key] += dict_to_add[key]
else:
dict[key] = dict_to_add[key] | Python | nomic_cornstack_python_v1 |
function addReference self item newclaim url
begin
call output string Adding new reference claim to %s % item
comment Add url, isReference=True
set refurl = call Claim repo string P854
call setTarget url
set refdate = call Claim repo string P813
set today = today
set date = call WbTime year=year month=month day=day
cal... | def addReference(self, item, newclaim, url):
pywikibot.output('Adding new reference claim to %s' % item)
refurl = pywikibot.Claim(self.repo, u'P854') # Add url, isReference=True
refurl.setTarget(url)
refdate = pywikibot.Claim(self.repo, u'P813')
today = datetime.datetime.today()
... | Python | nomic_cornstack_python_v1 |
function setCursor self _name=none
begin
set _before = _cursor
set _cursor = _name
if _before != _name
begin
append _updated tuple rect
call updateCursor
append _updated tuple rect
end
end function | def setCursor(self, _name = None):
_before = self._cursor
self._cursor = _name
if _before != _name:
self._updated.append(tuple(self.rect))
self.updateCursor()
self._updated.append(tuple(self.rect)) | Python | nomic_cornstack_python_v1 |
function __str__ self
begin
comment Start by building the canonical strings for the rules
set out_rules = dict
for tuple key value in items self
begin
comment Use empty string for singleton TrueCheck instances
if is instance value TrueCheck
begin
set out_rules at key = string
end
else
begin
set out_rules at key = str... | def __str__(self):
# Start by building the canonical strings for the rules
out_rules = {}
for key, value in self.items():
# Use empty string for singleton TrueCheck instances
if isinstance(value, TrueCheck):
out_rules[key] = ''
else:
... | Python | nomic_cornstack_python_v1 |
function recent_apps_show self
begin
set recentsid = call genid string com.android.systemui string recents_view
update wait
if exists wait timeout=3000
begin
return true
end
for _ in call xrange 2
begin
update wait
call recent
update wait
if exists wait timeout=12000
begin
return true
end
end
return false
end function | def recent_apps_show(self):
recentsid = util.genid('com.android.systemui', 'recents_view')
self.dev.wait.update()
if self.dev(resourceId=recentsid).wait.exists(timeout=3000):
return True
for _ in xrange(2):
self.dev.wait.update()
self.dev.press.recent(... | Python | nomic_cornstack_python_v1 |
from src.data.dataset import SyntaxMappingDataset
from src.data.syntax import Production
from src.utils.preprocess import collectSymbols
import re
import torch.nn as nn
import torch
from math import sqrt
class SymbolEmbedding extends Module
begin
function __init__ self symbols embedding_dim
begin
call __init__
set embe... | from src.data.dataset import SyntaxMappingDataset
from src.data.syntax import Production
from src.utils.preprocess import collectSymbols
import re
import torch.nn as nn
import torch
from math import sqrt
class SymbolEmbedding(nn.Module):
def __init__(self, symbols, embedding_dim):
super(SymbolEmbeddin... | Python | zaydzuhri_stack_edu_python |
from random import randint
import turtle
import numpy as np
set number_of_turtles = 30
set steps_of_time_number = 1000
set pool = list comprehension call Turtle for i in range number_of_turtles
set Vx = list comprehension random integer - 50 50 for i in range number_of_turtles
set Vy = list comprehension random integer... | from random import randint
import turtle
import numpy as np
number_of_turtles = 30
steps_of_time_number = 1000
pool = [turtle.Turtle() for i in range(number_of_turtles)]
Vx = [randint(-50, 50) for i in range(number_of_turtles)]
Vy = [randint(-50, 50) for i in range(number_of_turtles)]
x = [randint(-400, 400) for i ... | Python | zaydzuhri_stack_edu_python |
function make_padding_mask input_ids padding_idx=1
begin
set padding_mask = call eq padding_idx
if not any
begin
set padding_mask = none
end
return padding_mask
end function | def make_padding_mask(input_ids, padding_idx=1):
padding_mask = input_ids.eq(padding_idx)
if not padding_mask.any():
padding_mask = None
return padding_mask | Python | nomic_cornstack_python_v1 |
function wait_until self expression expected_result global_variables local_variables
begin
debug string Waiting for condition.
set wait_event = event
call on_change lambda obs old new -> if expression new == expected_result then set else none
append current_waiting_events wait_event
wait wait_event
remove current_waiti... | def wait_until(self, expression, expected_result, global_variables, local_variables):
logger.debug('Waiting for condition.')
wait_event = threading.Event()
aexpr(expression, global_variables, local_variables)\
.on_change(lambda obs, old, new: wait_event.set() if new == expected_resul... | Python | nomic_cornstack_python_v1 |
function _get_search_config self
begin
comment Load default configs if available
set app_path = directory name path absolute path path __file__ + string /..
set local_config = format string {0}/local/elasticsplunk.json app_path
if is file path local_config
begin
set config_file = open local_config
set config = load jso... | def _get_search_config(self):
# Load default configs if available
app_path = os.path.dirname(os.path.abspath(__file__)) + "/.."
local_config = "{0}/local/elasticsplunk.json".format(app_path)
if os.path.isfile(local_config):
config_file = open(local_config)
config... | Python | nomic_cornstack_python_v1 |
import json
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tweepy
function get_twitter_credentials path
begin
string Obtain twitter credentials from .json file as dict
with open path string r as j
begin
set twitter_credentials_dict = loads read j
end
return twitter_credentials_dict
end fu... | import json
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tweepy
def get_twitter_credentials(path):
'''
Obtain twitter credentials from .json file as dict
'''
with open(path, 'r') as j:
twitter_credentials_dict = json.loads(j.read())
return twitter_credentials_dict
#s... | Python | zaydzuhri_stack_edu_python |
function test_failure_nonauthorized_fileserver self
begin
delete
set url = reverse string fileserver_authorize_upload
set hash_checksum = string ABC
set ticket_decrypted = dict string chunk_position 1 ; string hash_checksum hash_checksum
set ticket_encrypted = call encrypt secret_key encode dumps ticket_decrypted
set d... | def test_failure_nonauthorized_fileserver(self):
models.Fileserver_Cluster_Member_Shard_Link.objects.all().delete()
url = reverse('fileserver_authorize_upload')
hash_checksum = 'ABC'
ticket_decrypted = {
'chunk_position': 1,
'hash_checksum': hash_checksum,
... | Python | nomic_cornstack_python_v1 |
comment -*- encoding:utf-8 -*-
import numpy as np
import pandas as pd
import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import LocalKalman
import csv
comment csv読み込み#1行目ヘッダー (移動平均後)
set r_filename = string ../csv/gps/weight_m.csv
set t_filename = string ../csv/gps/weight_t.csv
set w_file... | #-*- encoding:utf-8 -*-
import numpy as np
import pandas as pd
import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import LocalKalman
import csv
#csv読み込み#1行目ヘッダー (移動平均後)
r_filename = "../csv/gps/weight_m.csv"
t_filename = "../csv/gps/weight_t.csv"
w_filename = "../csv/gps/weight_a.csv"
df... | Python | zaydzuhri_stack_edu_python |
comment Dependencies and Setup
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
comment File to Load (Remember to change these)
set city_data_to_load = string data/city_data.csv
set ride_data_to_load = string data/ride_data.csv
comment Read the City and Ride Data
set ride_df = read csv ride_data_t... | # Dependencies and Setup
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# File to Load (Remember to change these)
city_data_to_load = "data/city_data.csv"
ride_data_to_load = "data/ride_data.csv"
# Read the City and Ride Data
ride_df = pd.read_csv(ride_data_to_load)
city_df = pd.read_csv(city_... | Python | zaydzuhri_stack_edu_python |
class Car
begin
function __init__ self model color
begin
set model = model
set color = color
end function
function __eq__ self other_car
begin
return lower model == lower model and lower color == lower color
end function
decorator staticmethod
function age days
begin
if days == 7
begin
return string A week old
end
else... | class Car:
def __init__(self, model, color):
self.model = model
self.color = color
def __eq__(self, other_car):
return (
self.model.lower() == other_car.model.lower()
and self.color.lower() == other_car.color.lower()
)
@staticmethod
def age(days)... | Python | zaydzuhri_stack_edu_python |
from scipy.spatial import distance as dist
from imutils.video import FileVideoStream
from imutils.video import VideoStream
from imutils import face_utils
import numpy as np
import argparse
import imutils
import time
import dlib
import cv2
set img = call imread string y1.JPG
function mouth_aspect_ratio mouth
begin
comme... | from scipy.spatial import distance as dist
from imutils.video import FileVideoStream
from imutils.video import VideoStream
from imutils import face_utils
import numpy as np
import argparse
import imutils
import time
import dlib
import cv2
img = cv2.imread('y1.JPG')
def mouth_aspect_ratio(mouth):
# Compute the eu... | Python | zaydzuhri_stack_edu_python |
function test_make_model_positive self
begin
set test_model = call Line2D
set test_data = list call Point2D x=0 y=1 call Point2D x=1 y=2
call make_model test_data
assert equal slope 1
assert equal y_int 1
assert equal x_int - 1
end function | def test_make_model_positive(self) -> None:
test_model = line2d.Line2D()
test_data = [line2d.Point2D(x=0, y=1), line2d.Point2D(x=1, y=2)]
test_model.make_model(test_data)
self.assertEqual(test_model.slope, 1)
self.assertEqual(test_model.y_int, 1)
self.assertEqual(test_m... | 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.