code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function test_1
begin
seed 90
set g = sog_gradient
set d = 100
set P = 50
set lambda_1 = 1
set lambda_2 = 10
set sigma_sq = 1
set tuple store_x0 matrix_combined store_c = call function_parameters_sog P d lambda_1 lambda_2
set func_args = tuple P sigma_sq store_x0 matrix_combined store_c
set tolerance = 1e-05
set bounds... | def test_1():
np.random.seed(90)
g = mt_obj.sog_gradient
d = 100
P = 50
lambda_1 = 1
lambda_2 = 10
sigma_sq = 1
store_x0, matrix_combined, store_c = (mt_obj.function_parameters_sog
(P, d, lambda_1, lambda_2))
func_args = P, sigma_sq, store_x0... | Python | nomic_cornstack_python_v1 |
function dfa_tv_estimator appro mask=none wtype=0 j1=3 j2=7 lbda=1
begin
if mask is none
begin
set mask = ones shape at slice : - 1 :
end
if ndim > 2
begin
set shape = reduce lambda a b -> a * b tuple 1 + shape at slice : - 1 :
set appro = reshape np appro tuple shape shape at - 1
end
set tuple Hurst_exponent dico = ... | def dfa_tv_estimator(appro, mask=None, wtype=0, j1=3, j2=7, lbda=1):
if mask is None:
mask = np.ones(appro.shape[:-1])
if appro.ndim > 2:
shape = (reduce(lambda a,b : a*b , (1,) + simulation.shape[:-1]))
appro = np.reshape(appro, (shape, appro.shape[-1]))
Hurst_exponent, dico... | Python | nomic_cornstack_python_v1 |
import os
import argparse
import pprint
from collections import defaultdict
function get_file_name_path_size_list dir_path
begin
set file_name_path_size_list = list
for tuple dir_name sub_dir_names file_names in walk dir_path
begin
for file_name in file_names
begin
set file_path = join path dir_name file_name
set file_... | import os
import argparse
import pprint
from collections import defaultdict
def get_file_name_path_size_list(dir_path):
file_name_path_size_list = list()
for dir_name, sub_dir_names, file_names in os.walk(dir_path):
for file_name in file_names:
file_path = os.path.join(dir_name, file_name)... | Python | zaydzuhri_stack_edu_python |
comment coding:utf-8
import pandas as pd
import numpy as np
import datetime
comment x到预测日的距离
function getTopred2 pred_day x
begin
set n_p = string parse time pred_day string %Y-%m-%d
set n_d = string parse time x string %Y/%m/%d
return days
end function
function getTopred pred_day x
begin
set n_p = string parse time pr... | #coding:utf-8
import pandas as pd
import numpy as np
import datetime
##x到预测日的距离
def getTopred2(pred_day,x):
n_p=datetime.datetime.strptime(pred_day,"%Y-%m-%d")
n_d=datetime.datetime.strptime(x,'%Y/%m/%d')
return (n_p-n_d).days
def getTopred(pred_day,x):
n_p=datetime.datetime.strptime(pred_day,"%Y-%m-%... | Python | zaydzuhri_stack_edu_python |
from unittest import TestCase
from leetcode.strings import lc_392
class Test392 extends TestCase
begin
function test_input1 self
begin
set s = call Solution
call assertEquals true call isSubsequence string abc string ahbgc
call assertEquals false call isSubsequence string leeeeetcode string yyyyyletcodeyyyy
end functio... | from unittest import TestCase
from leetcode.strings import lc_392
class Test392(TestCase):
def test_input1(self):
s = lc_392.Solution()
self.assertEquals(True, s.isSubsequence('abc', 'ahbgc'))
self.assertEquals(False, s.isSubsequence(
'leeeeetcode', 'yyyyyletcodeyyyy'))
| Python | zaydzuhri_stack_edu_python |
from ball import Ball
from matka import Matka
set DOWN = 0
set STAND = 1
set UP = 2
class Bot
begin
function decide self ball bat
begin
if y < y
begin
return UP
end
else
if y > y
begin
return DOWN
end
return STAND
end function
end class | from ball import Ball
from matka import Matka
DOWN = 0
STAND = 1
UP = 2
class Bot:
def decide(self, ball: Ball, bat: Matka) -> int:
if bat.y < ball.y:
return UP
elif bat.y > ball.y:
return DOWN
return STAND
| Python | zaydzuhri_stack_edu_python |
function stop_echo_server self ip_addr=string localhost port=DEFAULT_ECHO_PORT
begin
set out = none
if port in echo_server_procs and echo_server_procs at port is not none
begin
set es_proc = echo_server_procs at port
set out = terminate es_proc
pop echo_server_procs port
end
return out
end function | def stop_echo_server(self, ip_addr='localhost',
port=zephyr_constants.DEFAULT_ECHO_PORT):
out = None
if (port in self.echo_server_procs and
self.echo_server_procs[port] is not None):
es_proc = self.echo_server_procs[port]
out = es_proc.ter... | Python | nomic_cornstack_python_v1 |
function get_eigenpairs mesh V num_eigvals=100 eps_target=1.0
begin
comment Define Laplace-Beltrami eigenproblem
set tuple psi phi = tuple call TestFunction V call TrialFunction V
set L = call inner grad phi grad psi * dx
set M = phi * psi * dx
set petsc_L = handle
set petsc_M = handle
comment Run eigensolver
set opts ... | def get_eigenpairs(mesh, V, num_eigvals=100, eps_target=1.0):
# Define Laplace-Beltrami eigenproblem
psi, phi = TestFunction(V), TrialFunction(V)
L = inner(grad(phi), grad(psi)) * dx
M = phi * psi * dx
petsc_L = assemble(L).M.handle
petsc_M = assemble(M).M.handle
# Run eigensolver
opt... | Python | nomic_cornstack_python_v1 |
import pandas as pd
set data = list list 110 105 99 list 105 88 115 list 109 120 130
set index = list 1 2 3
set columns = list string 语文 string 数学 string 英语
set df = call DataFrame data=data index=index columns=columns
comment df['总成绩']=df.sum(axis=1,skipna=1) | import pandas as pd
data = [[110,105,99],[105,88,115],[109,120,130]]
index = [1,2,3]
columns = ['语文','数学','英语']
df = pd.DataFrame(data=data, index=index, columns=columns)
#df['总成绩']=df.sum(axis=1,skipna=1)
| Python | zaydzuhri_stack_edu_python |
function root_accounts self
begin
set options = options
return tuple options at string name_assets options at string name_liabilities options at string name_equity options at string name_income options at string name_expenses
end function | def root_accounts(self) -> tuple[str, str, str, str, str]:
options = self.options
return (
options["name_assets"],
options["name_liabilities"],
options["name_equity"],
options["name_income"],
options["name_expenses"],
) | Python | nomic_cornstack_python_v1 |
function _fr_print_ t
begin
set res = string DataFrame Enries/#%d % length t
set _c = list call columns
sort _c
set res = res + string Columns: %s % call multicolumn _c indent=2 pad=1
return res
end function | def _fr_print_ ( t ) :
##
res = "DataFrame Enries/#%d" % len ( t )
##
_c = list ( t.columns () )
_c.sort ()
res += "\nColumns:\n%s" % multicolumn ( _c , indent = 2 , pad = 1 )
return res | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
comment In[1]:
set a = list string apple string banana string computer
comment In[2]:
print a at 0
print a at 1
print a at 2
comment In[ ]:
comment for 變數 in 物件:
comment code block
comment In[5]:
for element in a
begin
print element
end
comment In[8]:
set b = list 20 10 50
set total = 0
for i in b... | # coding: utf-8
# In[1]:
a=["apple","banana","computer"]
# In[2]:
print(a[0])
print(a[1])
print(a[2])
# In[ ]:
#for 變數 in 物件:
# code block
# In[5]:
for element in a:
print(element)
# In[8]:
b=[20,10,50]
total=0
for i in b:
print(i)
total+=i
print(total)
# In[7]:
#list function
c=li... | Python | zaydzuhri_stack_edu_python |
comment -*-coding:utf-8 -*-
comment 判断一个二叉树是否是镜像二叉树
class TreeNode
begin
function __init__ self val=0 left=none right=none
begin
set val = val
set right = right
set left = left
end function
end class
comment 递归
class Solution
begin
function isSymmetric self root
begin
if not root
begin
return true
end
function tree p q... | # -*-coding:utf-8 -*-
#判断一个二叉树是否是镜像二叉树
class TreeNode:
def __init__(self,val=0,left=None,right=None):
self.val=val
self.right=right
self.left=left
#递归
class Solution:
def isSymmetric(self,root):
if not root:
return True
def tree(p,q):
if not p and... | Python | zaydzuhri_stack_edu_python |
function add_item item=string coin amount_found=1
begin
set item = lower item
if item in inventory
begin
set current_quantity = inventory at item
set inventory at item = current_quantity + amount_found
end
else
begin
set inventory at item = amount_found
end
end function
function print_item item
begin
set item = lower i... | def add_item(item = "coin", amount_found = 1):
item = item.lower()
if item in inventory:
current_quantity = inventory[item]
inventory[item] = current_quantity + amount_found
else:
inventory[item] = amount_found
def print_item(item):
item = item.lower()
if item not in inven... | Python | zaydzuhri_stack_edu_python |
comment -*- encoding: utf-8 -*-
comment !/usr/bin/env python
string @File : lesson56_Regular_Expression_3.py @Time : 2020/05/05 12:04:16 @Author : Stone_Hou @Version : 1.0 @Contact : xiangxing985529@163.com @License : (C)Copyright 2010-2020, Stone_Hou @Desc : None @Refer : https://github.com/xiangxing98
comment here pu... | # -*- encoding: utf-8 -*-
# !/usr/bin/env python
'''
@File : lesson56_Regular_Expression_3.py
@Time : 2020/05/05 12:04:16
@Author : Stone_Hou
@Version : 1.0
@Contact : xiangxing985529@163.com
@License : (C)Copyright 2010-2020, Stone_Hou
@Desc : None
@Refer : https://github.com/xiangxing98
''... | Python | zaydzuhri_stack_edu_python |
function getJSON self
begin
set obj = dict
comment obj["title"] = self.getTitle()
comment obj["authors"] = self.getAuthors()
comment obj["description"] = self.getDescription()
comment nums = self.getNumbers()
comment obj["average"] = nums["average"]
comment obj["ratings"] = nums["ratings"]
comment obj["reviews"] = num... | def getJSON(self):
obj = {}
# obj["title"] = self.getTitle()
# obj["authors"] = self.getAuthors()
# obj["description"] = self.getDescription()
# nums = self.getNumbers()
# obj["average"] = nums["average"]
# obj["ratings"] = nums["ratings"]
# obj["reviews"]... | Python | nomic_cornstack_python_v1 |
from collections import Counter
from string import ascii_lowercase
with open string trialanderror.txt as b
begin
set x = counter generator expression letter for line in b for letter in lower line if letter == string e in ascii_lowercase
end
set lettercount = counter x
for letter in x
begin
print lettercount at letter
e... | from collections import Counter
from string import ascii_lowercase
with open("trialanderror.txt") as b:
x = (Counter(letter for line in b
for letter in line.lower()
if letter == "e" in ascii_lowercase))
lettercount = Counter(x)
for letter in x:
print(lettercount[l... | Python | zaydzuhri_stack_edu_python |
function distance_cycle_to_full cycle dic1 dic2
begin
if cycle not in keys dic1
begin
pass
end
else
begin
comment Get the range of voltages for the curve under evaluation.
set a = flatten values
set a_max = max
set a_min = min
set a = a at slice 1 : : 2
set Y = list
comment Calculate distance between the curve under ... | def distance_cycle_to_full(cycle, dic1, dic2):
if cycle not in dic1.keys():
pass
else:
# Get the range of voltages for the curve under evaluation.
a = dic1[cycle][['voltage']].values.flatten()
a_max = a.max()
a_min = a.min()
a = a[1::2]
Y = []
... | Python | nomic_cornstack_python_v1 |
import unittest
from TestUtils import TestParser
class ParserSuite extends TestCase
begin
function test_simple_program self
begin
string Simple program: int main() {}
set input = string Var: x;
set expect = string successful
assert true call checkParser input expect 201
end function
function test_wrong_miss_close self
... | import unittest
from TestUtils import TestParser
class ParserSuite(unittest.TestCase):
def test_simple_program(self):
"""Simple program: int main() {} """
input = """Var: x;"""
expect = "successful"
self.assertTrue(TestParser.checkParser(input,expect,201))
def test_wrong_mi... | Python | zaydzuhri_stack_edu_python |
function get_posts db_cursor page_num
begin
set posts = list
execute db_cursor string SELECT * FROM posts ORDER BY time_posted DESC LIMIT ?, ? tuple POSTS_PER_PAGE * page_num - 1 POSTS_PER_PAGE
for post in call fetchall
begin
append posts dict string url_id post at 1 ; string title post at 2 ; string time_posted post ... | def get_posts(db_cursor, page_num):
posts = []
db_cursor.execute("SELECT * FROM posts ORDER BY time_posted DESC LIMIT ?, ?", (POSTS_PER_PAGE*(page_num-1), POSTS_PER_PAGE))
for post in db_cursor.fetchall():
posts.append({
'url_id': post[1],
'title': post[2],
... | Python | nomic_cornstack_python_v1 |
function parse_response self response
begin
string Parse XMLRPC response
set tuple parser unmarshaller = call getparser
call feed encode text string utf-8
close parser
return close unmarshaller
end function | def parse_response(self, response):
"""
Parse XMLRPC response
"""
parser, unmarshaller = self.getparser()
parser.feed(response.text.encode('utf-8'))
parser.close()
return unmarshaller.close() | Python | jtatman_500k |
function test_containership_atoms self
begin
set atm = next iterate substructure
assert in atm structure
end function | def test_containership_atoms(self):
atm = next(iter(self.substructure))
self.assertIn(atm, self.structure) | Python | nomic_cornstack_python_v1 |
function resource_group_name self
begin
return get pulumi self string resource_group_name
end function | def resource_group_name(self) -> pulumi.Input[str]:
return pulumi.get(self, "resource_group_name") | Python | nomic_cornstack_python_v1 |
function longest_prefix_palindrome s
begin
if length s <= 1
begin
return s
end
set max_length = 0
for i in range 1 length s
begin
if s at slice : i : == s at slice i - 1 : : - 1
begin
set max_length = i
end
end
return s at slice : max_length :
end function
print call longest_prefix_palindrome string abca | def longest_prefix_palindrome(s):
if len(s) <= 1:
return s
max_length = 0
for i in range(1,len(s)):
if s[:i] == s[i-1::-1]:
max_length = i
return s[:max_length]
print(longest_prefix_palindrome("abca")) | Python | jtatman_500k |
function send_log self level msg
begin
if Console
begin
set print_msg = string %s|%s % tuple level msg
print print_msg
end
if SendServer
begin
set send_msg = string %s.%s|%s % tuple SystemName level msg
set sock_cli = call socket AF_INET SOCK_DGRAM
try
begin
set total_send_len = length send_msg
if total_send_len > Send... | def send_log(self, level, msg):
if self.Console:
print_msg = "%s|%s" % (level, msg)
print(print_msg)
if self.SendServer:
send_msg = "%s.%s|%s" % (self.SystemName, level, msg)
sock_cli = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
... | Python | nomic_cornstack_python_v1 |
import os , datetime
function add_suffix file_name_in suffix
begin
comment extract file name without extension
set file_name_out = join string . split file_name_in string . at slice : - 1 :
set file_extension = split file_name_in string . at - 1
comment then add resized string
set file_name_out = file_name_out + strin... | import os, datetime
def add_suffix(file_name_in, suffix):
# extract file name without extension
file_name_out = '.'.join(file_name_in.split('.')[:-1])
file_extension = file_name_in.split('.')[-1]
# then add resized string
file_name_out = file_name_out + "_" + suffix + "." + file_extension
retu... | Python | zaydzuhri_stack_edu_python |
function isAnagram s1 s2
begin
comment Sort both strings
set s1 = sorted s1
set s2 = sorted s2
comment Compare sorted strings
if s1 == s2
begin
return true
end
else
begin
return false
end
end function
set s1 = string test
set s2 = string ttes
if call isAnagram s1 s2
begin
print string The strings are anagrams.
end
else... | def isAnagram(s1, s2):
# Sort both strings
s1 = sorted(s1)
s2 = sorted(s2)
# Compare sorted strings
if( s1 == s2):
return True
else:
return False
s1 = "test"
s2 = "ttes"
if (isAnagram(s1, s2)):
print ("The strings are anagrams.")
else:
print ("The strings aren'... | Python | jtatman_500k |
function get_table self
begin
return deep copy _table
end function | def get_table(self):
return copy.deepcopy(self._table) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
set graph = dict
set graph at string start = dict
set graph at string start at string a = 6
set graph at string start at string b = 2
set graph at string a = dict
set graph at string a at string fin = 1
set graph at string b = dict
set graph at string b at string a = 3
set graph at string ... | #!/usr/bin/python3
graph = {}
graph['start'] = {}
graph['start']['a'] = 6
graph['start']['b'] = 2
graph['a'] = {}
graph['a']['fin'] = 1
graph['b'] = {}
graph['b']['a'] = 3
graph['b']['fin'] = 5
graph['fin'] = {}
parents = {}
parents['a'] = 'start'
parents['b'] = 'start'
parents['fin'] = None
infinity = float('inf')
... | Python | zaydzuhri_stack_edu_python |
class Aluno extends object
begin
function __init__ self
begin
set cr = 0
set tCargaHoraria = 0
set nota = 0
set ch = 0
set operacao = 0
end function
function processar_dados self nota ch
begin
set nota = integer nota
set ch = integer ch
set tCargaHoraria = tCargaHoraria + ch
set operacao = operacao + nota * ch
set cr =... | class Aluno(object):
def __init__(self):
self.cr=0
self.tCargaHoraria=0
self.nota = 0
self.ch = 0
self.operacao = 0
def processar_dados(self,nota,ch):
self.nota = int(nota)
self.ch = int(ch)
self.tCargaHoraria += self.ch
self.oper... | Python | zaydzuhri_stack_edu_python |
string Classe Labyrinthe
class Labyrinthe
begin
string Classe qui va gérer tous les mouvements du joueur en les traduisants en position valide ou non
set derniere_position = string
function __init__ self chaine
begin
set structure = dict
set robot = tuple
set sortie = tuple
set door = dict
comment récupération de la... | """Classe Labyrinthe"""
class Labyrinthe:
"""Classe qui va gérer tous les mouvements du joueur en les traduisants
en position valide ou non"""
derniere_position = ' '
def __init__(self, chaine):
self.structure = {}
self.robot = tuple()
self.sortie = tuple()
self.door = {... | Python | zaydzuhri_stack_edu_python |
function renderError self error_code
begin
error error_code
write response string Oops! Something went wrong.
end function | def renderError(self, error_code):
self.error(error_code)
self.response.write("Oops! Something went wrong.") | Python | nomic_cornstack_python_v1 |
string Created on Wed Nov 6 00:23:37 2019 Function file that adds two numbers/strings/lists... @author: CHINTAN
function add a b
begin
return a + b
end function
print add 1 3 | """
Created on Wed Nov 6 00:23:37 2019
Function file that adds two numbers/strings/lists...
@author: CHINTAN
"""
def add(a,b):
return(a+b)
print(add(1,3))
| Python | zaydzuhri_stack_edu_python |
string 给出一个长度为 n 的单链表和一个值 x ,单链表的每一个值为 list[i],请返回一个链表的头结点, 要求新链表中小于 x 的节点全部在大于等于x 的节点左侧,并且两个部分之内的节点之间与原来的链表要保持相对顺序不变
class ListNode
begin
function __init__ self x
begin
set val = x
set next = none
end function
end class
class Solution
begin
function partition self head x
begin
comment write code here
comment 使用两个伪节点将链... | '''
给出一个长度为 n 的单链表和一个值 x ,单链表的每一个值为 list[i],请返回一个链表的头结点,
要求新链表中小于 x 的节点全部在大于等于x 的节点左侧,并且两个部分之内的节点之间与原来的链表要保持相对顺序不变
'''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def partition(self , head , x ):
# write code here
# 使用两个伪节点将链表分隔开
... | Python | zaydzuhri_stack_edu_python |
function checkout self branch_name tracking=false
begin
comment First see if this branch refers to an origin
if length split branch_name string / > 1
begin
set origin = split branch_name string / at 0
end
else
begin
set origin = none
end
for repo in repos
begin
info string checkout %s in repo %s % tuple branch_name rep... | def checkout(self, branch_name, tracking=False):
# First see if this branch refers to an origin
if len(branch_name.split('/')) > 1:
origin = branch_name.split('/')[0]
else:
origin = None
for repo in self.assembly.repos:
logging.info('checkout %s in repo %s' % (branch_name, repo['path']))
gitrepo = g... | Python | nomic_cornstack_python_v1 |
function get_data self
begin
return dict string _id string AE-2011-PY ; string state string Puducherry ; string election_type string assembly ; string year string 2011 ; string url url ; string constituencies call get_constituencies
end function | def get_data(self):
return {
"_id": "AE-2011-PY",
"state": "Puducherry",
"election_type": "assembly",
"year": "2011",
"url": self.url,
"constituencies": self.get_constituencies()
} | Python | nomic_cornstack_python_v1 |
import pyautogui
from gpiozero import Button
set FAILSAFE = false
set MOVE_DISTANCE = 5
set SPEED_INCREASE = 1
set UP = 3
set DOWN = 14
set LEFT = 4
set RIGHT = 2
set x_increase = 0
set y_increase = 0
set buttons = list comprehension call Button x for x in list UP DOWN LEFT RIGHT
while true
begin
set direction_values =... | import pyautogui
from gpiozero import Button
pyautogui.FAILSAFE = False
MOVE_DISTANCE = 5
SPEED_INCREASE = 1
UP = 3
DOWN = 14
LEFT = 4
RIGHT = 2
x_increase = 0
y_increase = 0
buttons = [Button(x) for x in [UP, DOWN, LEFT, RIGHT]]
while True:
direction_values = [i.is_pressed for i in buttons]
print(direct... | Python | zaydzuhri_stack_edu_python |
import xlsxwriter
set filepath = string Example_Output/
set filename = string CCG-ShiftTracker-StationName.xlsx
set wb = call Workbook filepath + filename
comment color variables
class Colors
begin
comment Red
set port = string #CC0000
comment Green
set stbd = string #008800
comment Slategray-ish
set daily = string #6F... | import xlsxwriter
filepath = 'Example_Output/'
filename = 'CCG-ShiftTracker-StationName.xlsx'
wb = xlsxwriter.Workbook(filepath + filename)
#color variables
class Colors:
port = '#CC0000' #Red
stbd = '#008800' #Green
daily = '#6F8F8F' #Slategray-ish
weekly = 'FFBB00' #Yellow-Orange
shift = '#1E90F... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from scipy import constants as cst
function potential_linecharge x y k x0 y0
begin
string Electric potential line charge Inputs: (float) k : line charge (float) x : x coordinate potential (float) y : y coordinate potential (float) x0 : x coordinate wire (float) y0 : y coordinate wire
set dr = square ... | import numpy as np
from scipy import constants as cst
def potential_linecharge(x, y, k, x0, y0):
"""
Electric potential line charge
Inputs:
(float) k : line charge
(float) x : x coordinate potential
(float) y : y coordinate potential
(float) x0 : x coordinate ... | Python | zaydzuhri_stack_edu_python |
function test_correct_wind_dir_bounds
begin
set bounds = list tuple string N 349 11 tuple string NNE 12 33 tuple string NE 34 56 tuple string ENE 57 78 tuple string E 79 101 tuple string ESE 102 123 tuple string SE 124 146 tuple string SSE 147 168 tuple string S 169 191 tuple string SSW 192 213 tuple string SW 214 236 ... | def test_correct_wind_dir_bounds():
bounds = [('N', 349, 11), ('NNE', 12, 33), ('NE', 34, 56),
('ENE', 57, 78), ('E', 79, 101), ('ESE', 102, 123), ('SE', 124, 146),
('SSE', 147, 168), ('S', 169, 191), ('SSW', 192, 213), ('SW', 214, 236),
('WSW', 237, 258), ('W', 259, 281), ('WNW', 282, 303), ('NW', 304... | Python | nomic_cornstack_python_v1 |
function ip4_route node
begin
set output = call splitlines
set result = dict
for line in output
begin
set columns = split line string
set route = dict
set result at columns at 0 = dict
set prev = none
for column in columns
begin
if prev == string dev
begin
set route at string dev = column
end
if prev == string via
b... | def ip4_route(node):
output = normalize_text(node.run('ip route')).splitlines()
result = {}
for line in output:
columns = line.split(' ')
route = result[columns[0]] = {}
prev = None
for column in columns:
if prev == 'dev':
route['dev'] = column
... | Python | nomic_cornstack_python_v1 |
function pairwise_distance x y=none metric=string euclidean **kwargs
begin
from sktime.distances._numba_utils import _compute_pairwise_distance , _make_3d_series
set _x = call _make_3d_series x
if y is none
begin
set y = x
end
set _y = call _make_3d_series y
set symmetric = call array_equal _x _y
set _metric_callable =... | def pairwise_distance(
x: np.ndarray,
y: np.ndarray = None,
metric: Union[
str,
Callable[
[np.ndarray, np.ndarray, dict], Callable[[np.ndarray, np.ndarray], float]
],
Callable[[np.ndarray, np.ndarray], float],
NumbaDistance,
] = "euclidean",
**kwar... | Python | nomic_cornstack_python_v1 |
function handle_long_project_repeating_form_request **kwargs
begin
set headers = kwargs at string headers
set data = kwargs at string data
set resp = none
comment import (JSON only)
if string data in data
begin
set repeat_forms = loads data at string data at 0
set resp = length repeat_forms
end
else
begin
comment expor... | def handle_long_project_repeating_form_request(**kwargs) -> Any:
headers = kwargs["headers"]
data = kwargs["data"]
resp = None
# import (JSON only)
if "data" in data:
repeat_forms = json.loads(data["data"][0])
resp = len(repeat_forms)
# export (JSON only)
else:
resp =... | Python | nomic_cornstack_python_v1 |
function calculate_equation_result n
begin
set result = 0
set modulo = integer 1000000000.0 + 7
for i in range 1 n + 1
begin
set x = i
set result = result + x * i - 2 * i - 1 ^ 2
set result = result % modulo
end
return result
end function
comment Test the program
set n = integer input string Enter the value of n:
set r... | def calculate_equation_result(n):
result = 0
modulo = int(1e9) + 7
for i in range(1, n+1):
x = i
result += (x*i - (2*i-1))**2
result %= modulo
return result
# Test the program
n = int(input("Enter the value of n: "))
result = calculate_equation_result(n)
print("Result:", resul... | Python | jtatman_500k |
comment for name in open_file:
comment print(name)
set cupcake_types = list
for line in open_file
begin
set line = strip line
set values = split line string ,
append cupcake_types values at 2
end
print cupcake_types
seek open_file 0 0
set total_invoice = list
for line in open_file
begin
set line = strip line
set valu... | # for name in open_file:
# print(name)
cupcake_types = []
for line in open_file:
line = line.strip()
values = line.split(',')
cupcake_types.append(values[2])
print(cupcake_types)
open_file.seek(0,0)
total_invoice = []
for line in open_file:
line = line.strip()
values = line.split(',')
... | Python | zaydzuhri_stack_edu_python |
function vec_shift_left x
begin
return set x at slice 1 : :
end function | def vec_shift_left(x):
return jnp.zeros_like(x).at[0:-1].set(x[1:]) | Python | nomic_cornstack_python_v1 |
import collections
class Solution
begin
function findevents self arrs durs
begin
set L = length arrs
set inters = default dictionary lambda -> decimal string inf
for i in range L
begin
set inters at arrs at i = min inters at arrs at i arrs at i + durs at i
end
set gaps = sorted items inters
set tuple ans end = tuple 0... | import collections
class Solution:
def findevents(self,arrs,durs):
L=len(arrs)
inters=collections.defaultdict(lambda : float('inf'))
for i in range(L):
inters[arrs[i]]=min(inters[arrs[i]],arrs[i]+durs[i])
gaps=sorted(inters.items())
ans,end=0,-1
for curSt... | Python | zaydzuhri_stack_edu_python |
comment init
from pyparrot.Minidrone import Mambo
import cv2
comment If you are using BLE: you will need to change this to the address of YOUR mambo
comment if you are using Wifi, this can be ignored
set mamboAddr = string d0:3a:d1:dc:e6:20
comment make my mambo object
comment remember to set True/False for the wifi de... | #init
from pyparrot.Minidrone import Mambo
import cv2
# If you are using BLE: you will need to change this to the address of YOUR mambo
# if you are using Wifi, this can be ignored
mamboAddr = "d0:3a:d1:dc:e6:20"
# make my mambo object
# remember to set True/False for the wifi depending on if you are using the wifi o... | Python | zaydzuhri_stack_edu_python |
import hashlib
from django.http import JsonResponse
from django.shortcuts import redirect
from comments.helper import json_msg
from personalBlog.settings import SECRET_KEY
comment 创建一个函数, 实现对粉丝用户提交的密码进行加密处理
from user.models import UserModel
function set_password password
begin
comment 利用sha-256进行加密, 为进一步提高密码的安全性, 需要进行加... | import hashlib
from django.http import JsonResponse
from django.shortcuts import redirect
from comments.helper import json_msg
from personalBlog.settings import SECRET_KEY
# 创建一个函数, 实现对粉丝用户提交的密码进行加密处理
from user.models import UserModel
def set_password(password):
# 利用sha-256进行加密, 为进一步提高密码的安全性, 需要进行加盐处理
# 将... | Python | zaydzuhri_stack_edu_python |
function entity_type self
begin
set entityType = call get_value string entityType
return if expression entityType in list asset scene then entityType else noContext
end function | def entity_type(self):
entityType = self.get_value('entityType')
return entityType if entityType in [self.asset, self.scene] else self.noContext | Python | nomic_cornstack_python_v1 |
function set_unauthorized_mode unauthorized
begin
set _UNAUTHORIZED = unauthorized
end function | def set_unauthorized_mode(unauthorized):
BonsaiWS._UNAUTHORIZED = unauthorized | Python | nomic_cornstack_python_v1 |
function command
begin
set server = call get_server
call bash format string ssh -i {ssh_key_path} {username}@{hostname} ssh_key_path=get server string ssh_key_path username=get server string username hostname=get server string hostname
end function | def command():
server = get_server()
bash('ssh -i {ssh_key_path} {username}@{hostname}'.format(
ssh_key_path=server.get('ssh_key_path'),
username=server.get('username'),
hostname=server.get('hostname')
)) | Python | nomic_cornstack_python_v1 |
comment seleniumのみ(BeautifulSoupを使用しない)スクレイピング
import time
import os
from common.driver import Driver
from common.fileio import CSVio
from common.logger import set_logger
from selenium.webdriver.common.by import By
comment ログの設定(モジュール名の設定)
set logger = call set_logger __name__
comment amazonランキングのセールストップ画面
set RNK_TOP_... | # seleniumのみ(BeautifulSoupを使用しない)スクレイピング
import time
import os
from common.driver import Driver
from common.fileio import CSVio
from common.logger import set_logger
from selenium.webdriver.common.by import By
# ログの設定(モジュール名の設定)
logger = set_logger(__name__)
# amazonランキングのセールストップ画面
RNK_TOP_URL = "https... | Python | zaydzuhri_stack_edu_python |
function inference images scale3 perturbFM
begin
comment We instantiate all variables using tf.get_variable() instead of
comment tf.Variable() in order to share variables across multiple GPU training runs.
comment If we only ran this model on a single GPU, we could simplify this function
comment by replacing all instan... | def inference(images, scale3, perturbFM):
###
# We instantiate all variables using tf.get_variable() instead of
# tf.Variable() in order to share variables across multiple GPU training runs.
# If we only ran this model on a single GPU, we could simplify this function
# by replacing all instances of tf.get_... | Python | nomic_cornstack_python_v1 |
for i in range 1 n + 1
begin
for j in range 1 k + 1
begin
if j + z > n
begin
set flag = false
break
end
end
if flag == true
begin
set z = z + 1
end
end
print z | for i in range(1, n+1):
for j in range(1, k+1):
if(j+z > n):
flag = False
break
if(flag == True):
z+=1
print(z) | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import rospy
from std_msgs.msg import Int32
from random import randint
comment a function to generate the random number
function generate_random_number
begin
set rnd = random integer 0 5000
comment rnd = int(input())
return rnd
end function
function generate_random_number2
begin
set rnd = r... | #!/usr/bin/env python
import rospy
from std_msgs.msg import Int32
from random import randint
#a function to generate the random number
def generate_random_number():
rnd= randint(0,5000)
#rnd = int(input())
return rnd
def generate_random_number2():
rnd= randint(0,5000)
#rnd = int(input())
retur... | Python | zaydzuhri_stack_edu_python |
function reduction_error_analysis rom fom reductor test_mus basis_sizes=0 estimator=true condition=false error_norms=tuple error_norm_names=none estimator_norm_index=0 custom=tuple plot=false plot_custom_logarithmic=true pool=dummy_pool
begin
assert not error_norms or fom and reductor
assert error_norm_names is none ... | def reduction_error_analysis(rom, fom, reductor, test_mus,
basis_sizes=0,
estimator=True, condition=False, error_norms=(), error_norm_names=None,
estimator_norm_index=0, custom=(),
plot=False, plot_custom... | Python | nomic_cornstack_python_v1 |
from urllib import request
set header = dict string User-Agent string Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36
set rq = call Request string https://www.baidu.com headers=header
set resp = url open rq
print read resp | from urllib import request
header={
'User-Agent':' Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36'
}
rq=request.Request('https://www.baidu.com',headers=header)
resp=request.urlopen(rq)
print(resp.read()) | Python | zaydzuhri_stack_edu_python |
function as_dict value
begin
if has attribute value string as_dict and callable as_dict
begin
return call as_dict
end
else
if is instance value tuple list tuple
begin
return list comprehension call as_dict v for v in value
end
else
if is instance value dict
begin
return dictionary generator expression tuple call as_dic... | def as_dict(value):
if hasattr(value, 'as_dict') and callable(value.as_dict):
return value.as_dict()
elif isinstance(value, (list, tuple)):
return [as_dict(v) for v in value]
elif isinstance(value, dict):
return dict((as_dict(k), as_dict(v))
for k, v in value.iteritems())
elif isinst... | Python | nomic_cornstack_python_v1 |
function request_to_json request req_id
begin
if not is instance request Request
begin
raise call TypeError string { request } is not an instance of { Request }
end
set payload = dictionary
set payload at string reqID = integer req_id
if is instance request DiscoverRequest
begin
set payload at string msgType = string d... | def request_to_json(request: lwm2m.Message, req_id: int) -> str:
if not isinstance(request, lwm2m.Request):
raise TypeError(f"{request!r} is not an instance of {lwm2m.Request!r}")
payload = dict()
payload["reqID"] = int(req_id)
if isinstance(request, lwm2m.DiscoverRequest):
payload["msgT... | Python | nomic_cornstack_python_v1 |
import threading
from functools import wraps
function Category
begin
return r lock
end function
function synchronized lock=none
begin
if not lock
begin
set lock = r lock
end
function _dec f
begin
decorator wraps f
function _f *args **kwargs
begin
with lock
begin
return f dist *args keyword kwargs
end
end function
retur... | import threading
from functools import wraps
def Category():
return threading.RLock()
def synchronized(lock = None):
if not lock: lock = threading.RLock()
def _dec(f):
@wraps(f)
def _f(*args, **kwargs):
with lock:
return f(*args, **kwargs)
return _f
re... | Python | zaydzuhri_stack_edu_python |
function get_specific_office office_id
begin
set query = format string SELECT * FROM offices WHERE office_id = '{}' office_id
set office = call Office
set office = call select_from_db query
if not office
begin
return call make_response call jsonify dict string status 404 ; string message format string Office with id {}... | def get_specific_office(office_id):
query = """SELECT * FROM offices WHERE office_id = '{}'""".format(office_id)
office = office_model.Office()
office = database.select_from_db(query)
if not office:
return make_response(jsonify({
"status":404,
"message": "Office with id {} is no... | Python | nomic_cornstack_python_v1 |
comment Example function 1: return the sum of two numbers.
function sum a b
begin
return a + b
end function
comment Example function 2: return the size of list, and modify the list to now be sorted.
set my_list = list string Robert string Cynthia string Robbie
function list_sort my_list
begin
sort my_list
return tuple ... | # Example function 1: return the sum of two numbers.
def sum(a, b):
return a+b
# Example function 2: return the size of list, and modify the list to now be sorted.
my_list = ["Robert", "Cynthia", "Robbie"]
def list_sort(my_list):
my_list.sort()
return len(my_list), my_list
print(list_sort(my_list))
###... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/python
comment stack implementation in python.
comment gods i love python!!
class Stack
begin
string Time Complexity : append and pop both run with a O(1) time complexity - meaning this algorithm will perform in constant time no matter the item count. to reverse the algorithm and use indexing (insert... | #! /usr/bin/python
# stack implementation in python.
# gods i love python!!
class Stack:
"""
Time Complexity : append and pop both run
with a O(1) time complexity - meaning this algorithm
will perform in constant time no matter the item count.
to reverse the algorithm and use indexing (insert and pop)
will... | Python | zaydzuhri_stack_edu_python |
import pygame
from pygame import *
import numpy as np
function flip_bit bit
begin
return tuple 1 0 at bit
end function
function get_bitfield num
begin
return call binary_repr num=num width=8
end function
class CellularAutomata
begin
function __init__ self size rule
begin
set size = size
set grid = zeros shape=tuple siz... | import pygame
from pygame import *
import numpy as np
def flip_bit(bit: int):
return (1, 0)[bit]
def get_bitfield(num):
return np.binary_repr(num=num, width=8)
class CellularAutomata:
def __init__(self, size: int, rule: int):
self.size = size
self.grid = np.zeros(shape=(self.size, self... | Python | zaydzuhri_stack_edu_python |
function secz self frame
begin
set Z = call deg2rad 90 * deg - alt
return 1 / cos Z
end function | def secz(self, frame):
Z = np.deg2rad(90 * u.deg - self.altaz_transform(frame).alt)
return 1 / np.cos(Z) | Python | nomic_cornstack_python_v1 |
function leave self room
begin
remove session at string rooms call _get_room_name room
end function | def leave(self, room):
self.socket.session['rooms'].remove(self._get_room_name(room)) | Python | nomic_cornstack_python_v1 |
import datetime
class LogEntry
begin
function __init__ self timestamp logger_name severity message
begin
set timestamp = string parse time timestamp string %Y-%m-%d %H:%M:%S,%f
set severity = severity
set logger_name = logger_name
set message = message
end function
function __str__ self
begin
return string timestamp + ... | import datetime
class LogEntry:
def __init__(self, timestamp, logger_name, severity, message):
self.timestamp = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S,%f')
self.severity = severity
self.logger_name = logger_name
self.message = message
def __str__(self):
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Sun Feb 17 15:42:55 2019 @author: 25493
from __future__ import division , print_function , absolute_import
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
set mnist = call read_data_sets... | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 17 15:42:55 2019
@author: 25493
"""
from __future__ import division, print_function, absolute_import
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets(... | Python | zaydzuhri_stack_edu_python |
string 三角函数相关
import math
comment 返回正弦值
set a = sin pi / 2
comment 返回余弦值
set b = cos pi
comment 返回正切值
set c = tan 2 / pi
print a
print b
print c
print string
comment 弦值求弧度
comment 返回反余弦弧度值
set a = call acos - 1
3.141592653589793
comment 返回反正弦弧度值
set b = call asin 1
1.5707963267948966
comment 返回反正切弧度值
set c = call atan ... | '''三角函数相关'''
import math
a= math.sin(math.pi/2) # 返回正弦值
b= math.cos(math.pi) # 返回余弦值
c= math.tan(2/math.pi) # 返回正切值
print(a)
print(b)
print(c)
print('')
# 弦值求弧度
a = math.acos(-1) # 返回反余弦弧度值
3.141592653589793
b = math.asin(1) # 返回反正弦弧度值
1.5707963267948966
c = math.atan(2) # 返回反正... | Python | zaydzuhri_stack_edu_python |
comment 정수 내림차순으로 배치하기
comment https://programmers.co.kr/learn/courses/30/lessons/12933
comment 함수 solution은 정수 n을 매개변수로 입력받습니다.
comment n의 각 자릿수를 큰것부터 작은 순으로 정렬한 새로운 정수를 리턴해주세요. 예를들어 n이 118372면 873211을 리턴하면 됩니다.
comment 나의 풀이
function solution n
begin
set list = list
for i in range length string n
begin
append list s... | #정수 내림차순으로 배치하기
#https://programmers.co.kr/learn/courses/30/lessons/12933
#함수 solution은 정수 n을 매개변수로 입력받습니다.
#n의 각 자릿수를 큰것부터 작은 순으로 정렬한 새로운 정수를 리턴해주세요. 예를들어 n이 118372면 873211을 리턴하면 됩니다.
#나의 풀이
def solution(n):
list = []
for i in range(len(str(n))):
list.append(str(n)[i])
list.sort(reverse = True)
... | Python | zaydzuhri_stack_edu_python |
function _to_dict self
begin
string Return a json dictionary representing this model.
set _dict = dict
if has attribute self string normalized_text and normalized_text is not none
begin
set _dict at string normalized_text = normalized_text
end
if has attribute self string start_time and start_time is not none
begin
se... | def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self,
'normalized_text') and self.normalized_text is not None:
_dict['normalized_text'] = self.normalized_text
if hasattr(self, 'start_time') and self.start_ti... | Python | jtatman_500k |
set var1 = list string carro string moto string bike
print var1
comment substitue o primeiro elemento da lista
set var1 at 0 = string barco
print var1 | var1 = ['carro','moto','bike']
print(var1)
var1[0]="barco" #substitue o primeiro elemento da lista
print(var1)
| Python | zaydzuhri_stack_edu_python |
comment Definition for a binary tree node.
comment class TreeNode(object):
comment def __init__(self, x):
comment self.val = x
comment self.left = None
comment self.right = None
comment follow up, when the BST tree changes and the BST tree is changed often
comment we will store counts in the tree node
comment method 3,... | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# follow up, when the BST tree changes and the BST tree is changed often
# we will store counts in the tree node
# method 3, best time complexity fo... | Python | zaydzuhri_stack_edu_python |
function sample self sample
begin
set _sample = sample
end function | def sample(self, sample):
self._sample = sample | Python | nomic_cornstack_python_v1 |
import sys
import os
class Task
begin
function __init__ self name=string priority=0
begin
set name = name
set priority = priority
end function
function set_priority self priority
begin
if priority <= 0
begin
comment To be fixed.
print string Error.
exit 1
end
set priority = priority
end function
function print self
be... | import sys
import os
class Task:
def __init__(self, name = "", priority = 0):
self.name = name
self.priority = priority
def set_priority(self, priority):
if priority <= 0:
print("Error.") # To be fixed.
sys.exit(1)
self.priority = priority
def pri... | Python | zaydzuhri_stack_edu_python |
class MyName
begin
function printMe self
begin
print format string {:s} {:s} firstname surname
end function
function __repr__ self
begin
return format string {:s} {:s} {:s} firstname midname surname
end function
end class
set me = call MyName
set firstname = string Stuart
set surname = string Allen
set midname = string... | class MyName:
def printMe(self):
print("{:s} {:s}".format(self.firstname, self.surname))
def __repr__(self):
return ("{:s} {:s} {:s}".format(self.firstname, self.midname, self.surname))
me = MyName()
me.firstname="Stuart"
me.surname="Allen"
me.midname="LuL"
print(me)
| Python | zaydzuhri_stack_edu_python |
set a = integer call raw_input
set b = a + 1
set c = a * b
set d = c / 2
print d | a=int(raw_input())
b=a+1
c=a*b
d=c/2
print(d)
| Python | zaydzuhri_stack_edu_python |
string Life Expectancy By Country Over the course of the past few centuries, technological and medical advancements have helped increase the life expectancy of humans. However, as of now, the average life expectancy of humans varies depending on what country you live in. In this project, we will investigate a dataset c... | """
Life Expectancy By Country
Over the course of the past few centuries, technological and medical advancements have helped increase the life expectancy of
humans. However, as of now, the average life expectancy of humans varies depending on what country you live in.
In this project, we will investigate a dataset c... | Python | zaydzuhri_stack_edu_python |
import cv2
import numpy as np
from matplotlib import pyplot as plt
set img = call imread string taha.jpg IMREAD_GRAYSCALE
set canny = call Canny img 50 200
set titles = list string image string canny
set images = list img canny
for i in range 2
begin
tuple subplot 1 2 i + 1 image show images at i string gray
title plt ... | import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread("taha.jpg", cv2.IMREAD_GRAYSCALE)
canny = cv2.Canny(img,50,200)
titles = ['image','canny']
images = [img,canny]
for i in range(2):
plt.subplot(1,2,i+1), plt.imshow(images[i],'gray')
plt.title(titles[i])
plt.... | Python | zaydzuhri_stack_edu_python |
function receive_key self modulus exponent key signature
begin
set k = power key _secret modulus
set s = power signature _secret modulus
return tuple format k string x if expression k == power s exponent modulus then true else false
end function | def receive_key(self, modulus: int, exponent: int, key: int, signature: int) -> (str, bool):
k = pow(key, self._secret, self.modulus)
s = pow(signature, self._secret, self.modulus)
return format(k, 'x'), True if k == pow(s, exponent, modulus) else False | Python | nomic_cornstack_python_v1 |
function increment self status
begin
if status == OK
begin
set ok_count = ok_count + 1
end
else
if status == MISSING
begin
set missing_count = missing_count + 1
end
else
if status == MINOR
begin
set minor_count = minor_count + 1
end
else
if status == MAJOR
begin
set major_count = major_count + 1
end
else
if status == L... | def increment(self, status: StatusEnum):
if status == StatusEnum.OK:
self.ok_count += 1
elif status == StatusEnum.MISSING:
self.missing_count += 1
elif status == StatusEnum.MINOR:
self.minor_count += 1
elif status == StatusEnum.MAJOR:
self.... | Python | nomic_cornstack_python_v1 |
comment https://programmers.co.kr/learn/courses/30/lessons/82612
function solution price money count
begin
set temp = list 0 * count + 1
for i in range count + 1
begin
set temp at i = price * i
end
set total_price = sum temp
set result = money - total_price
if result > 0
begin
return 0
end
return absolute result
end fu... | #https://programmers.co.kr/learn/courses/30/lessons/82612
def solution(price, money, count):
temp = [0]*(count+1)
for i in range(count+1):
temp[i] = price * i
total_price = sum(temp)
result = money - total_price
if result > 0 :
return 0
return abs(result)
print(solution(... | Python | zaydzuhri_stack_edu_python |
function __len__ self
begin
comment the if-clause here looks a bit dumb, should we make it clearer?
return sum generator expression 1 for item in self if item in self + 1
end function | def __len__(self):
# the if-clause here looks a bit dumb, should we make it clearer?
return sum(1 for item in self if item in self) + 1 | Python | nomic_cornstack_python_v1 |
function predictions self
begin
return _logits
end function | def predictions(self):
return self._logits | Python | nomic_cornstack_python_v1 |
function unscaled_eigen_prob Q lam_inv a centres batch_size
begin
set tuple d _ = call _shape Q
set tuple distances true_exp = call _eigen_distances_squared Q lam_inv a centres batch_size
set exponentials = exp - 0.5 * distances
return call reduce_mean exponentials axis=1
end function | def unscaled_eigen_prob(Q, lam_inv, a, centres, batch_size):
d, _ = _shape(Q)
distances, true_exp = _eigen_distances_squared(Q, lam_inv, a, centres, batch_size)
exponentials = tf.exp(-0.5 * distances)
return tf.reduce_mean(exponentials, axis=1) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
from concurrent.futures import ThreadPoolExecutor
import threading
from queue import Queue
from multiprocessing import Process
from multiprocessing.pool import Pool
function func
begin
print string %s this is multi thread % call current_thread
end function
function process
begin
set p = pr... | # -*- coding: utf-8 -*-
from concurrent.futures import ThreadPoolExecutor
import threading
from queue import Queue
from multiprocessing import Process
from multiprocessing.pool import Pool
def func():
print('%s this is multi thread' % threading.current_thread())
def process():
p = Process(target=func)
... | Python | zaydzuhri_stack_edu_python |
function characters self content
begin
set _current_content = _current_content + strip string content
end function | def characters(self, content):
self._current_content += str(content).strip() | Python | nomic_cornstack_python_v1 |
function get_N_HexCol N
begin
if N <= 9
begin
return list comprehension format string C{} i for i in range N
end
set HSV_tuples = list comprehension tuple x * 1.0 / N 0.5 0.8 for x in range N
set hex_out = list
for rgb in HSV_tuples
begin
set rgb = map lambda x -> integer x * 255 call hsv_to_rgb *rgb
append hex_out st... | def get_N_HexCol(N):
if N <= 9:
return ["C{}".format(i) for i in range(N)]
HSV_tuples = [(x * 1.0 / N, 0.5, 0.8) for x in range(N)]
hex_out = []
for rgb in HSV_tuples:
rgb = map(lambda x: int(x * 255), colorsys.hsv_to_rgb(*rgb))
hex_out.append('#%02x... | Python | nomic_cornstack_python_v1 |
function get_default_treatment cls
begin
return call _load_treatment_file at string default_treatment
end function | def get_default_treatment(cls) -> str:
return cls._load_treatment_file()['default_treatment'] | Python | nomic_cornstack_python_v1 |
function validation_data_size self
begin
return get pulumi self string validation_data_size
end function | def validation_data_size(self) -> Optional[float]:
return pulumi.get(self, "validation_data_size") | Python | nomic_cornstack_python_v1 |
comment from django.http import HttpResponse
from django.shortcuts import render , get_object_or_404
from django.core.paginator import Paginator , PageNotAnInteger , EmptyPage
comment from django.template import loader
from models import Reference , Contact , Reservation , Stock , Menu , Comptoir
comment def index(requ... | #from django.http import HttpResponse
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
#from django.template import loader
from .models import Reference, Contact, Reservation, Stock, Menu, Comptoir
# def index(request):
# message = "Sal... | Python | zaydzuhri_stack_edu_python |
import tensorflow as tf
import numpy as np
import numpy.random as rng
import pandas.io.data as web
import numpy as np
import pandas as pd
from TF_model import Model
function get_prices symbol
begin
set tuple start end = tuple string 2007-05-02 string 2016-04-11
set data = call DataReader symbol string yahoo start end
s... | import tensorflow as tf
import numpy as np
import numpy.random as rng
import pandas.io.data as web
import numpy as np
import pandas as pd
from TF_model import Model
def get_prices(symbol):
start, end = '2007-05-02', '2016-04-11'
data = web.DataReader(symbol, 'yahoo', start, end)
data=pd.DataFrame(data)
... | Python | zaydzuhri_stack_edu_python |
function get_html self
begin
set context = dict string display_name display_name_with_default ; string element_id element_id ; string instructions_html instructions ; string content_html call _render_content
return call render_template string annotatable.html context
end function | def get_html(self):
context = {
'display_name': self.display_name_with_default,
'element_id': self.element_id,
'instructions_html': self.instructions,
'content_html': self._render_content()
}
return self.system.render_template('annotatable... | Python | nomic_cornstack_python_v1 |
from torchtext.data import Dataset
from torchtext.data import Example
import json
import six
class FlatFeverDataset extends Dataset
begin
function __init__ self path
begin
set tv_datafields = list tuple string claim TEXT tuple string label LABEL tuple string evidence TEXT
set path = path
set samples = call get_lines pa... | from torchtext.data import Dataset
from torchtext.data import Example
import json
import six
class FlatFeverDataset(Dataset):
def __init__(self, path):
self.tv_datafields = [
("claim", TEXT), ("label", LABEL),
("evidence", TEXT)
]
self.path = path
... | Python | zaydzuhri_stack_edu_python |
function description self
begin
return get _data string description
end function | def description(self):
return self._data.get('description') | Python | nomic_cornstack_python_v1 |
function _normalize_argument self value
begin
return call normalize_empty_to_none value
end function | def _normalize_argument(self, value):
return storepass.utils.normalize_empty_to_none(value) | Python | nomic_cornstack_python_v1 |
function average_reward self
begin
set T = length self
return sum rewards / T
end function | def average_reward(self):
T = len(self)
return np.sum(self.rewards / T) | Python | nomic_cornstack_python_v1 |
function get_transaction_recipient_value
begin
set tx_recipient = input string Enter the recipient for the transaction:
set tx_amount = decimal input string Please enter your transaction amount:
return tuple tx_recipient tx_amount
end function | def get_transaction_recipient_value():
tx_recipient = input("Enter the recipient for the transaction: ")
tx_amount = float(input("Please enter your transaction amount: "))
return (tx_recipient, tx_amount) | Python | nomic_cornstack_python_v1 |
comment Function to calculate PISANO PERIOD of 10.
function pp
begin
comment As we have to find the last digit of sum of series.i.e (num % 10).
set tuple p1 p2 = tuple 0 1
for i in range 100
begin
set tuple p1 p2 = tuple p2 p1 + p2 % 10
if p1 == 0 and p2 == 1
begin
return i + 1
end
end
end function
comment Function to ... | def pp(): #Function to calculate PISANO PERIOD of 10.
p1, p2 = 0, 1 #As we have to find the last digit of sum of series.i.e (num % 10).
for i in range(100):
p1, p2 = p2, (p1+p2) % 10
if p1 == 0 and p2 == 1:
return i+1
... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.