code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function mention self
begin
return string <@& { id } >
end function | def mention(self) -> str:
return f"<@&{self.id}>" | Python | nomic_cornstack_python_v1 |
import os
import csv
class DatasetReader extends object
begin
string For each file we have next#Next line to read
function __init__ self filename toread=0 delimiter=string , filesize=0 init=false
begin
set filename = filename
set filesize = filesize
set toRead = toread
set delimiter = delimiter
set info = dictionary
if... | import os
import csv
class DatasetReader(object):
"""
For each file we have
next#Next line to read
"""
def __init__(self, filename, toread=0, delimiter=',', filesize=0, init=False):
self.filename = filename
self.filesize = filesize
self.toRead = toread
self.delimit... | Python | zaydzuhri_stack_edu_python |
function bot_see self mess args
begin
try
begin
return string %s is %s % tuple args call __getattribute__ args
end
except AttributeError
begin
return string No such attribute
end
end function | def bot_see(self, mess, args):
try:
return "%s is %s" % (args, bc.__getattribute__(args))
except AttributeError:
return "No such attribute" | Python | nomic_cornstack_python_v1 |
function updateMktDepth self id position operation side price size
begin
pass
end function | def updateMktDepth(self, id, position, operation, side, price, size):
pass | Python | nomic_cornstack_python_v1 |
comment coding=utf-8
string 4. 给定一个正整数N,将其表示为数字1,2,5,11相加的形式输出。 要求上述数字出现的总次数最少(每个数字可以重复使用)。 输入说明:一个正整数N (N<= 10000)。 输入:21 输出:11 5 5
tuple 1 2 5 11
set x = integer input string 请输入一个你比较喜欢的正整数:
print
print string 准备好了吗?我要开拆了哈,嘿嘿...
while x >= 11
begin
set x = x - 11
print 11
end
while x >= 5
begin
set x = x - 5
print 5
... | # coding=utf-8
'''4. 给定一个正整数N,将其表示为数字1,2,5,11相加的形式输出。 要求上述数字出现的总次数最少(每个数字可以重复使用)。
输入说明:一个正整数N (N<= 10000)。
输入:21
输出:11
5
5
'''
1,2,5,11
x=int(input('请输入一个你比较喜欢的正整数:'))
print()
print('准备好了吗?我要开拆了哈,嘿嘿...')
while x>=11:
x=x-11
print(11)
while x>=5:
x=x-5
print(5)
while x>=2:
x=x-2
print(2)
... | Python | zaydzuhri_stack_edu_python |
from PIL import Image
set image = open string image.jpg
set rotated_image = call rotate 90
save string rotated_image.jpg
comment This will open the image file 'image.jpg', rotate it 90 degrees, and save it as 'rotated_image.jpg'. | from PIL import Image
image = Image.open('image.jpg')
rotated_image = image.rotate(90)
rotated_image.save('rotated_image.jpg')
# This will open the image file 'image.jpg', rotate it 90 degrees, and save it as 'rotated_image.jpg'.
| Python | flytech_python_25k |
for i in range 2 25
begin
print i * 5
end
for i in range 10 121 5
begin
print i
end
string x = 10 while x <= 120: print(x) x += 5 | for i in range(2,25):
print(i*5)
for i in range(10,121,5):
print(i)
'''
x = 10
while x <= 120:
print(x)
x += 5
''' | Python | zaydzuhri_stack_edu_python |
function safecall func
begin
function wrapper *args **kwargs
begin
try
begin
return call func *args keyword kwargs
end
except Exception
begin
pass
end
end function
return wrapper
end function | def safecall(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception:
pass
return wrapper | Python | nomic_cornstack_python_v1 |
set n1 = decimal input string Ciência Humanas:
set p1 = integer input string Peso:
set n2 = decimal input string Ciências da Natureza:
set p2 = integer input string Peso:
set n3 = decimal input string Linguagens:
set p3 = integer input string Peso:
set n4 = decimal input string Matemática:
set p4 = integer input string... | n1 = float(input('Ciência Humanas: '))
p1 = int(input('Peso: '))
n2 = float(input('Ciências da Natureza: '))
p2 = int(input('Peso: '))
n3 = float(input('Linguagens: '))
p3 = int(input('Peso: '))
n4 = float(input('Matemática: '))
p4 = int(input('Peso: '))
n5 = float(input('Redação: '))
p5 = int(input('Peso: '))
calculo... | Python | zaydzuhri_stack_edu_python |
function blocking_navigate_and_get_source self url timeout=DEFAULT_TIMEOUT_SECS
begin
string Do a blocking navigate to url `url`, and then extract the response body and return that. This effectively returns the *unrendered* page content that's sent over the wire. As such, if the page does any modification of the contai... | def blocking_navigate_and_get_source(self, url, timeout=DEFAULT_TIMEOUT_SECS):
'''
Do a blocking navigate to url `url`, and then extract the
response body and return that.
This effectively returns the *unrendered* page content that's sent over the wire. As such,
if the page does any modification of the conta... | Python | jtatman_500k |
function divide2 a b
begin
try
begin
return a * 1.0 / b
end
except ZeroDivisionError
begin
raise call ValueError string Zero division Error!
end
except Exception as e
begin
raise e
end
end function | def divide2(a, b):
try:
return a * 1.0 / b
except ZeroDivisionError:
raise ValueError("Zero division Error!")
except Exception as e:
raise e | Python | nomic_cornstack_python_v1 |
from iancraft.buttons import Button
from iancraft.constants import BACKGROUNDS
from iancraft.constants import BUTTONS
from iancraft.constants import FONTS
from iancraft.constants import STATES
from iancraft.constants import WHITE
from iancraft.states import State
from iancraft.utils import set_next_state
from pygame.fo... | from iancraft.buttons import Button
from iancraft.constants import BACKGROUNDS
from iancraft.constants import BUTTONS
from iancraft.constants import FONTS
from iancraft.constants import STATES
from iancraft.constants import WHITE
from iancraft.states import State
from iancraft.utils import set_next_state
from pygame.fo... | Python | zaydzuhri_stack_edu_python |
function clear self
begin
call initialize
end function | def clear(self):
self.initialize() | Python | nomic_cornstack_python_v1 |
function xinfo_groups self stream
begin
string Retrieve the consumer groups for a stream
set fut = execute self b'XINFO' b'GROUPS' stream
return call wait_convert fut parse_lists_to_dicts
end function | def xinfo_groups(self, stream):
"""Retrieve the consumer groups for a stream"""
fut = self.execute(b'XINFO', b'GROUPS', stream)
return wait_convert(fut, parse_lists_to_dicts) | Python | jtatman_500k |
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets.samples_generator import make_blobs
from scipy.cluster.hierarchy import linkage , dendrogram
import pandas as pd
comment preparo la visualizzazione
set rcParams at string figure.figsize = tupl... | import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cluster import AgglomerativeClustering
from sklearn.datasets.samples_generator import make_blobs
from scipy.cluster.hierarchy import linkage, dendrogram
import pandas as pd
# preparo la visualizzazione
plt.rcParams["figure.figsize"] = (12, 8)
sns.set()... | Python | zaydzuhri_stack_edu_python |
for i in range 1 n
begin
if integer list at i < mini
begin
set mini = integer list at i
set flag = 1
set c = i + 1
end
else
if integer list at i == mini
begin
set flag = 0
end
end | for i in range(1,n):
if int(list[i]) < mini:
mini=int(list[i])
flag=1
c=i+1
elif int(list[i])==mini :
flag=0 | Python | zaydzuhri_stack_edu_python |
function add_notification_listener self notification_type notification_callback
begin
string Add a notification callback to the notification center. Args: notification_type: A string representing the notification type from .helpers.enums.NotificationTypes notification_callback: closure of function to call when event is... | def add_notification_listener(self, notification_type, notification_callback):
""" Add a notification callback to the notification center.
Args:
notification_type: A string representing the notification type from .helpers.enums.NotificationTypes
notification_callback: closure of function to call wh... | Python | jtatman_500k |
string full cycle as a function
import components
import SteamGenerator_Matt as SG
import Condenser
from iapws import IAPWS97 as steam
class state
begin
comment inlet temperature (K)
set T = 0.0
comment inlet pressure (MPa)
set P = 0.0
comment mass flow rate (kg/s)
set m = 0.0
comment specific enthalpy (kJ/kg)
set h = ... | """
full cycle as a function
"""
import components
import SteamGenerator_Matt as SG
import Condenser
from iapws import IAPWS97 as steam
class state():
T = 0.0 # inlet temperature (K)
P = 0.0 # inlet pressure (MPa)
m = 0.0 # mass flow rate (kg/s)
h = 0.0 # specific enthalpy (kJ/kg)
s = 0.0 # specif... | Python | zaydzuhri_stack_edu_python |
comment Definition for singly-linked list.
class ListNode extends object
begin
function __init__ self x
begin
set val = x
set next = none
end function
end class
class Solution extends object
begin
function deleteNode self node
begin
set nextNode = next
if nextNode is none
begin
set node = nextNode
end
else
begin
set va... | # Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def deleteNode(self, node):
nextNode = node.next
if nextNode is None:
node = nextNode
else:
node.val = nextN... | Python | zaydzuhri_stack_edu_python |
set nickel = integer call raw_input string How many nickels do you have?
set twoCent = integer call raw_input string How many two-cent pieces do you have?
set penny = integer call raw_input string How many pennies do you have?
set total = 5 * nickel + 2 * twoCent + penny | nickel = int(raw_input("How many nickels do you have?"))
twoCent = int(raw_input("How many two-cent pieces do you have?"))
penny = int(raw_input("How many pennies do you have?"))
total = 5*nickel+2*twoCent+penny
| Python | zaydzuhri_stack_edu_python |
function z2rt self z
begin
set v = vertex
set u = pivot
set e1 = call roll v - 1 - v
set w = z at tuple Ellipsis newaxis - v at u
set r = absolute w
set t = call angle w / e1 at u
set tmin = call angle v at tuple slice : : newaxis - v at u / e1 at u
for tuple i j in enumerate u
begin
set tmin at tuple slice : : i... | def z2rt(self,z):
v = self.vertex
u = self.pivot
e1 = np.roll(v,-1) - v
w = z[...,np.newaxis] - v[u]
r = np.abs(w)
t = np.angle(w/(e1[u]))
tmin = np.angle((v[:,np.newaxis] - v[u])/e1[u])
for (i,j) in enumerate(u):
tmin[:,i] = np.roll(tmin[:,i... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
string Advent of Code 2020
import os
import re
import math
import collections
from enum import Enum
from dataclasses import dataclass
set me = base name path __file__
set DEFAULT_INPUT_FILE = string input/ + replace me string .py string .txt
set LOW_HIGH_MAP = dictionary F=0 L=0 B=1 R=1
cla... | #!/usr/bin/env python
"""
Advent of Code 2020
"""
import os
import re
import math
import collections
from enum import Enum
from dataclasses import dataclass
me = os.path.basename(__file__)
DEFAULT_INPUT_FILE = "input/" + me.replace(".py", ".txt")
LOW_HIGH_MAP = dict(
F = 0,
L = 0,
B = 1,
R = 1
)
c... | Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function moveZeroes self nums
begin
string :type nums: List[int] :rtype: None Do not return anything, modify nums in-place instead.
comment bubble sort method
comment Runtime: 2676 ms, faster than 5.01% of Python online submissions for Move Zeroes.
comment Memory Usage: 13.1 MB, less... | class Solution(object):
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
## bubble sort method
## Runtime: 2676 ms, faster than 5.01% of Python online submissions for Move Zeroes.
## M... | Python | zaydzuhri_stack_edu_python |
function test_token_not_live_data rok_connector_with_secret rok_ds_jwt remove_live_data_mode
begin
with raises InvalidAuthenticationMethodError
begin
call get_df rok_ds_jwt
end
end function | def test_token_not_live_data(rok_connector_with_secret, rok_ds_jwt, remove_live_data_mode):
with pytest.raises(InvalidAuthenticationMethodError):
rok_connector_with_secret.get_df(rok_ds_jwt) | Python | nomic_cornstack_python_v1 |
import pika
set queueName = string hello
comment create connection
set connection = call BlockingConnection call ConnectionParameters string localhost
comment create channel
set channel = call channel
comment create queue
call queue_declare queue=queueName
comment send message to queue
call basic_publish exchange=strin... | import pika
queueName = 'hello'
# create connection
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
# create channel
channel = connection.channel()
# create queue
channel.queue_declare(queue=queueName)
# send message to queue
channel.basic_publish(exchange='', routing_key=queueName,
... | Python | zaydzuhri_stack_edu_python |
import random
function genEmptyBoard
begin
set board = list
for k in range N
begin
append board list
end
for i in range N
begin
for j in range N
begin
append board at i 0
end
end
return board
end function
function selectLength avail_squares start board
begin
set poss_lengths = list
set length = 0
if avail_squares < 9... | import random
def genEmptyBoard():
board = []
for k in range(N):
board.append([])
for i in range(N):
for j in range(N):
board[i].append(0)
return board
def selectLength(avail_squares, start, board):
poss_lengths = []
length = 0
if avail_squares < 9:
for... | Python | zaydzuhri_stack_edu_python |
function test_backwards_100_balance_remains_between_1_and_negative_1
begin
from bbst import Bst
set tree = call Bst list comprehension x for x in range 100 at slice : : - 1
assert call balance in range - 1 2
end function | def test_backwards_100_balance_remains_between_1_and_negative_1():
from bbst import Bst
tree = Bst([x for x in range(100)][::-1])
assert tree.balance() in range(-1, 2) | Python | nomic_cornstack_python_v1 |
import re
import math
import collections
from itertools import cycle
set dict = dict
set alphabet = tuple string а string б string в string г string д string е string ж string з string и string й string к string л string м string н string о string п string р string с string т string у string ф string х string ц string... | import re
import math
import collections
from itertools import cycle
dict = {}
alphabet = (
'а', 'б', 'в', 'г', 'д', 'е', 'ж', 'з', 'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р', 'с', 'т', 'у', 'ф', 'х', 'ц',
'ч',
'ш', 'щ', 'ъ', 'ы', 'ь', 'э', 'ю', 'я')
#sumletters = 0
letter_ord = 0
def sumabukv(text):
... | Python | zaydzuhri_stack_edu_python |
from Stack import Stack
function reverse_input stack
begin
set n = input
while n
begin
call push n
try
begin
set n = input
end
except any
begin
break
end
end
while not call is_empty
begin
print pop stack
end
end function | from Stack import Stack
def reverse_input(stack):
n = input()
while n:
stack.push(n)
try:
n = input()
except:
break
while not stack.is_empty():
print(stack.pop()) | Python | zaydzuhri_stack_edu_python |
if decimal a < decimal 2000.0
begin
print string Isento
end
else
begin
if decimal a > decimal 2000 and decimal a < decimal 3000
begin
set x = decimal decimal a - decimal 2000.0
end
else
if decimal a >= decimal 3000
begin
set x = decimal 1000
end
if decimal a > decimal 3000 and decimal a < decimal 4500
begin
set y = dec... | if float(a) < float(2000.00):
print('Isento')
else:
if float(a)>float(2000) and float(a)<float(3000):
x = float(float(a) - float(2000.00))
elif(float(a)>=float(3000)):
x = float(1000)
if float(a)>float(3000) and float(a)<float(4500):
y = float(float(a) - float(3000.00))
elif... | Python | zaydzuhri_stack_edu_python |
function _recycle_left_right left right
begin
try
begin
set left = call recycle_value left call length_of right
end
except DataUnrecyclable
begin
set right = call recycle_value right call length_of left
end
return tuple left right
end function | def _recycle_left_right(left: Any, right: Any) -> Tuple:
try:
left = recycle_value(left, length_of(right))
except DataUnrecyclable:
right = recycle_value(right, length_of(left))
return left, right | Python | nomic_cornstack_python_v1 |
import unittest
from matrix import traverse
class TestMatrixTraversal extends TestCase
begin
function test_3_by_3_matrix self
begin
set matrix = list list 1 2 3 list 4 5 6 list 7 8 9
assert equal list 1 2 3 6 9 8 7 4 5 call traverse matrix
end function
function test_4_by_3_matrix self
begin
set matrix = list list 1 2 3... | import unittest
from matrix import traverse
class TestMatrixTraversal(unittest.TestCase):
def test_3_by_3_matrix(self):
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
self.assertEqual([1, 2, 3, 6, 9, 8, 7, 4, 5], traverse(matrix))
def test_4_by_3_matrix(self):
matrix = [[1, 2, 3, 4], [5,... | Python | zaydzuhri_stack_edu_python |
function setUp self
begin
comment Initialize the board
set gameboard = call BattleshipBoard tuple 5 5
comment Assign a certain fleet formation
set board = array list list 1 1 1 0 0 list 0 0 0 0 1 list 1 0 1 0 1 list 1 0 0 0 0 list 1 0 1 0 1
end function | def setUp(self):
self.gameboard = BattleshipBoard((5, 5)) # Initialize the board
# Assign a certain fleet formation
self.gameboard.board = np.array([[1,1,1,0,0],
[0,0,0,0,1],
[1,0,1,0,1],
... | Python | nomic_cornstack_python_v1 |
function tiene_epicrisis historia_id
begin
return all
end function | def tiene_epicrisis(historia_id):
return Epicrisis.objects.filter(historia=historia_id).all() | Python | nomic_cornstack_python_v1 |
function test_education_instance_created_without_required_arguments self
begin
call create user=user school_name=school_name course_name=course_name start_date=start_date
set education = get objects pk=1
assert equal user user string Users don't match.
assert equal school_name school_name string School names don't matc... | def test_education_instance_created_without_required_arguments(self):
Education.objects.create(
user=self.user,
school_name=self.school_name,
course_name=self.course_name,
start_date=self.start_date,
)
education = Education.objects.get(pk=1)
self.assertEqual(
self.user,
education.user,
"U... | Python | nomic_cornstack_python_v1 |
import pandas as pd
from sklearn.model_selection import train_test_split
import models
from sklearn.ensemble import RandomForestRegressor
set path = string C:\Users\Home\Documents\DANIIL\programming\python\Code\projekts\data_science\models\kursovoj_project\dataset_kurs.csv
comment path = r'D:\Daniil\programming\kursovo... | import pandas as pd
from sklearn.model_selection import train_test_split
import models
from sklearn.ensemble import RandomForestRegressor
path = r'C:\Users\Home\Documents\DANIIL\programming\python\Code\projekts\data_science\models\kursovoj_project\dataset_kurs.csv'
#path = r'D:\Daniil\programming\kursovoj_project\data... | Python | zaydzuhri_stack_edu_python |
function source_resource_id self
begin
return get pulumi self string source_resource_id
end function | def source_resource_id(self) -> str:
return pulumi.get(self, "source_resource_id") | Python | nomic_cornstack_python_v1 |
function count self
begin
return count _obj
end function | def count(self):
return self._obj.Count() | Python | nomic_cornstack_python_v1 |
function clear_input
begin
global sudoku
call fill 0
call config state=NORMAL
comment Clear the input frame
for tuple k v in items ent_dict
begin
if get v
begin
call config dict string background string White
delete 0 string end
end
end
end function | def clear_input():
global sudoku
sudoku.fill(0)
st.config(state=tk.NORMAL)
#Clear the input frame
for k,v in ent_dict.items():
if v.get():
v.config({"background": "White"})
v.delete(0,'end') | Python | nomic_cornstack_python_v1 |
function _treeToText self result
begin
return if expression result is not none then join string list comprehension call repr c at slice 1 : - 1 : for c in children else string
end function | def _treeToText(self, result):
return " ".join([repr(c)[1:-1] for c in result.children]) if result is not None else "" | Python | nomic_cornstack_python_v1 |
function remove self id
begin
for entry in entrys
begin
if entry at string id == id
begin
remove entrys entry
end
end
end function | def remove(self, id):
for entry in self.entrys:
if entry['id'] == id:
self.entrys.remove(entry) | Python | nomic_cornstack_python_v1 |
string Created on 2021. 3. 9. @author: PC-25
set a = list
append a string 1
append a string 2
insert a length a string 3
print length a
print a | '''
Created on 2021. 3. 9.
@author: PC-25
'''
a = []
a.append("1")
a.append("2")
a.insert(len(a), "3")
print(len(a))
print(a)
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import sys
import json
set log = stdin
set adict = dict
while true
begin
set line = read line log
if not line
begin
break
end
set line = strip line
set adict at line = line
end
comment json.dump(adict,sys.stdout) | #!/usr/bin/python
import sys
import json
log=sys.stdin
adict={};
while True:
line=log.readline()
if not line : break
line=line.strip()
adict[line]=line
#json.dump(adict,sys.stdout) | Python | zaydzuhri_stack_edu_python |
function derive_project session_directory corpus_filter session_filter pre_select=1 post_select=0
begin
comment Change to the session directory
with call change_dir session_directory
begin
comment Get the parent directory of the session directory
set parent_directory = directory name path session_directory
comment Chec... | def derive_project(
session_directory, corpus_filter, session_filter, pre_select=1, post_select=0
):
# Change to the session directory
with change_dir(session_directory):
# Get the parent directory of the session directory
parent_directory = os.path.dirname(session_directory)
# Chec... | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/env python3
string ' Title: C. Foe Pairs ' Author: Cheng-Shih, Wong ' Date: 2016/03/26
set tuple n m = map int split input
set p = list comprehension integer i for i in split input
set q = list 0 * n + 1
set lp = list 0 * n + 1
for i in range n
begin
set q at p at i = i
end
for i in range m
begin
set... | #! /usr/bin/env python3
'''
' Title: C. Foe Pairs
' Author: Cheng-Shih, Wong
' Date: 2016/03/26
'''
n, m = map(int, input().split())
p = [int(i) for i in input().split()]
q = [0]*(n+1)
lp = [0]*(n+1)
for i in range(n): q[p[i]] = i
for i in range(m):
u, v = map(int, input().split())
u, v = q[u], q[v]
if u > v: u,... | Python | zaydzuhri_stack_edu_python |
from display import *
from draw import *
set s = call new_screen
set c = list 0 255 0
function stup p1 p2
begin
return tuple p1 at 0 + p2 at 0 p1 at 1 + p2 at 1
end function
function recursion_draw p1 p2 p3 c
begin
if p1 != p2
begin
call draw_line p1 at 0 p1 at 1 p2 at 0 p2 at 1 s c
call draw_line p2 at 0 p2 at 1 p3 at... | from display import *
from draw import *
s = new_screen()
c = [ 0, 255, 0 ]
def stup(p1, p2):
return (p1[0] + p2[0], p1[1] + p2[1])
def recursion_draw(p1, p2, p3, c):
if (p1 != p2):
draw_line(p1[0], p1[1], p2[0], p2[1], s, c)
draw_line(p2[0], p2[1], p3[0], p3[1], s, c)
draw_line(p1[0]... | Python | zaydzuhri_stack_edu_python |
function import_project self cr uid ids context=none
begin
set analytic_pool = get pool string account.analytic.account
set project_pool = get pool string project.project
set partner_pool = get pool string res.partner
set user_pool = get pool string res.users
set task_pool = get pool string project.task
set work_pool =... | def import_project(self, cr, uid, ids, context=None):
analytic_pool = self.pool.get('account.analytic.account')
project_pool = self.pool.get('project.project')
partner_pool = self.pool.get('res.partner')
user_pool = self.pool.get('res.users')
task_pool = self.pool.get('project.ta... | Python | nomic_cornstack_python_v1 |
function update_frame self key ranges=none element=none
begin
call _reset_ranges
set reused = is instance hmap DynamicMap and overlaid
set prev_frame = current_frame
if not reused and element is none
begin
set element = call _get_frame key
end
else
if element is not none
begin
set current_frame = element
set current_ke... | def update_frame(self, key, ranges=None, element=None):
self._reset_ranges()
reused = isinstance(self.hmap, DynamicMap) and self.overlaid
self.prev_frame = self.current_frame
if not reused and element is None:
element = self._get_frame(key)
elif element is not None:
... | Python | nomic_cornstack_python_v1 |
function create_static_view self elements=none
begin
set p = package
set ident = call get_id View
set v = call create_view id=ident mimetype=string text/html
add _idgenerator ident
if not elements
begin
notify self string ViewCreate view=v immediate=true
return v
end
if is instance elements at 0 Annotation
begin
if len... | def create_static_view(self, elements=None):
p=self.package
ident=p._idgenerator.get_id(View)
v=p.create_view(id=ident, mimetype='text/html')
p._idgenerator.add(ident)
if not elements:
self.notify('ViewCreate', view=v, immediate=True)
return v
if i... | Python | nomic_cornstack_python_v1 |
import numpy as np
import string
import random
from datetime import datetime
from neo4j import GraphDatabase , basic_auth
set db = call driver string bolt://localhost auth=call basic_auth string neo4j string neo4j
set session = call session
function printOptions
begin
print string Enter 1 to execute query 1
print strin... | import numpy as np
import string
import random
from datetime import datetime
from neo4j import GraphDatabase, basic_auth
db = GraphDatabase.driver("bolt://localhost", auth=basic_auth("neo4j", "neo4j"))
session = db.session()
def printOptions():
print("Enter 1 to execute query 1")
print("Enter 2 to execute quer... | Python | zaydzuhri_stack_edu_python |
from defines import *
import comm
import time
function go ft direction
begin
if direction != STOP and ft != 0
begin
set ser = call comm
comment send direction to serial port
comment 1182 ticks equals a foot
set ticks = ft * 1182
call send string direction
sleep 1
call send string integer ticks + string T
end
end functi... | from defines import *
import comm
import time
def go(ft, direction):
if direction != STOP and ft != 0:
ser = comm.comm()
#send direction to serial port
#1182 ticks equals a foot
ticks = ft * 1182;
ser.send(str(direction))
time.sleep(1)
ser.send(str(int(ticks... | Python | zaydzuhri_stack_edu_python |
function get_speeds start end
begin
return map lambda date -> call _api_request date WINDSPEED_API_URL call _date_range start end
end function | def get_speeds(start: str, end: str) -> Generator[Dict[str, str], None, None]:
return map(
lambda date: _api_request(date, WINDSPEED_API_URL),
_date_range(start, end)
) | Python | nomic_cornstack_python_v1 |
import ctypes
set _sum = call CDLL string libsum.so
set argtypes = tuple c_int c_int
import wiringpi
comment import os
comment os.system("export LD_LIBRARY_PATH=/home/pi/Desktop")
function our_function
begin
global _sum
set hum = call our_function call c_int 0 call c_int 0
set temp = call our_function call c_int 1 call... | import ctypes
_sum = ctypes.CDLL('libsum.so')
_sum.our_function.argtypes = (ctypes.c_int,ctypes.c_int)
import wiringpi
# import os
# os.system("export LD_LIBRARY_PATH=/home/pi/Desktop")
def our_function():
global _sum
hum = _sum.our_function(ctypes.c_int(0), ctypes.c_int(0))
temp = _sum.our_function(ctype... | Python | zaydzuhri_stack_edu_python |
function isRotation s1 s2
begin
if length s1 != length s2
begin
return false
end
set temp = s1 + s1
if s2 in temp
begin
return true
end
return false
end function
set result = call isRotation string abc string cab
print result | def isRotation(s1, s2):
if (len(s1) != len(s2)):
return False
temp = s1 + s1
if (s2 in temp):
return True
return False
result = isRotation('abc', 'cab')
print(result)
| Python | flytech_python_25k |
comment =======================================
comment 이거 문제 이해가 안감 combinations로 왜 안풀림?
comment =============+=========================
comment A, B 두사람은 서로 무게가 다른 볼링공
comment 볼링공의 총 개수 N
from itertools import combinations
set n = 5
set m = 3
set data = list 1 3 2 3 2
set resComb = list call combinations data 2
set r... | ### =======================================
# 이거 문제 이해가 안감 combinations로 왜 안풀림?
### =============+=========================
# A, B 두사람은 서로 무게가 다른 볼링공
# 볼링공의 총 개수 N
from itertools import combinations
n = 5
m = 3
data = [1, 3, 2, 3, 2]
resComb = list(combinations(data, 2))
result = []
for x in resComb:
if(x[0] + ... | Python | zaydzuhri_stack_edu_python |
function train_neural_network session optimizer keep_probability feature_batch label_batch
begin
comment Implement
run optimizer feed_dict=dict x feature_batch ; y label_batch ; keep_prob keep_probability
end function | def train_neural_network(session, optimizer, keep_probability, feature_batch, label_batch):
# Implement
session.run(optimizer, feed_dict={x: feature_batch, y: label_batch, keep_prob: keep_probability}) | Python | nomic_cornstack_python_v1 |
function _get_ip_unnumbered self unnumbered_type unnumbered_name
begin
string Get and merge the `ip unnumbered` config from an interface. You should not use this method. You probably want `Interface.ip_unnumbered`. Args: unnumbered_type: XML document with the XML to get the donor type. unnumbered_name: XML document wit... | def _get_ip_unnumbered(self, unnumbered_type, unnumbered_name):
"""Get and merge the `ip unnumbered` config from an interface.
You should not use this method.
You probably want `Interface.ip_unnumbered`.
Args:
unnumbered_type: XML document with the XML to get the donor type... | Python | jtatman_500k |
comment from functools import reduce
comment Higher order functions that are used as parameters in functions
comment map - map a function over a collection #####
comment f(x) = 1+x
comment Here, we have:
comment Domain (value fed to x): [1, 2]
comment Range (output of f(x)): [2, 3]
comment map() takes 2 things; It take... | # from functools import reduce
# Higher order functions that are used as parameters in functions
#### map - map a function over a collection #####
# f(x) = 1+x
#Here, we have:
#Domain (value fed to x): [1, 2]
#Range (output of f(x)): [2, 3]
# map() takes 2 things; It takes function as 1st argument ; 2nd thing i... | Python | zaydzuhri_stack_edu_python |
comment coding=utf-8
import os
import sys
from flask import Flask , render_template
from flask import escape
from flask_sqlalchemy import SQLAlchemy
comment init
set app = call Flask __name__
comment SQLite URI compatible
set WIN = starts with platform string win
if WIN
begin
set prefix = string sqlite:///
end
else
beg... | # coding=utf-8
import os
import sys
from flask import Flask, render_template
from flask import escape
from flask_sqlalchemy import SQLAlchemy
# init
app = Flask(__name__)
# SQLite URI compatible
WIN = sys.platform.startswith('win')
if WIN:
prefix = 'sqlite:///'
else:
prefix = 'sqlite:////'
app.config['SQLAL... | Python | zaydzuhri_stack_edu_python |
function saas_package self **kw
begin
set template_databases = search list
return call render string sythil_saas_server.saas_choose_package dict string template_databases template_databases
end function | def saas_package(self, **kw):
template_databases = request.env['saas.template.database'].search([])
return http.request.render('sythil_saas_server.saas_choose_package', {'template_databases': template_databases}) | Python | nomic_cornstack_python_v1 |
function sort_recommendations recommendations
begin
set names_by_score = list
set score = 0
comment need a list to sort before append the final list
set a_list = list
while recommendations
begin
for name_score in recommendations
begin
if name_score at 1 == score
begin
append a_list name_score at 0
end
else
if name_sc... | def sort_recommendations(recommendations):
names_by_score = []
score = 0
# need a list to sort before append the final list
a_list = []
while recommendations:
for name_score in recommendations:
if name_score[1] == score:
a_list.append(name_score[0])
e... | Python | nomic_cornstack_python_v1 |
async function test_did_run coresys
begin
set supervisor_version = call EvaluateSupervisorVersion coresys
set should_run = states
set should_not_run = list comprehension state for state in CoreState if state not in should_run
assert length should_run != 0
assert length should_not_run != 0
with patch string supervisor.r... | async def test_did_run(coresys: CoreSys):
supervisor_version = EvaluateSupervisorVersion(coresys)
should_run = supervisor_version.states
should_not_run = [state for state in CoreState if state not in should_run]
assert len(should_run) != 0
assert len(should_not_run) != 0
with patch(
"su... | Python | nomic_cornstack_python_v1 |
from copy import deepcopy
from abc import abstractmethod
from math import inf
from typing import Dict , Set , Tuple
from collections import defaultdict
string CSP class implemented to solve colorized sudoku.
set totalAssignments = list
class CSP
begin
function __init__ self variables domains
begin
set variables = vari... | from copy import deepcopy
from abc import abstractmethod
from math import inf
from typing import Dict, Set, Tuple
from collections import defaultdict
'''
CSP class implemented to solve colorized sudoku.
'''
totalAssignments = []
class CSP:
def __init__(self, variables: Set[Tuple], domains: Dict[Tuple, Dict]):... | Python | zaydzuhri_stack_edu_python |
function cx_voltage_decay self
begin
clamp self
set val = as type call numpy int
if length val == 1
begin
return val at 0
end
return val
end function | def cx_voltage_decay(self):
self.clamp()
val = quantize(self.voltage_decay).cpu().data.numpy().astype(int)
if len(val) == 1:
return val[0]
return val | Python | nomic_cornstack_python_v1 |
comment =============================================================================
comment # -*- coding: utf-8 -*-
comment """
comment Created on Thu Sep 27 00:11:18 2018
comment @author: Nadim
comment """
comment min_all=np.min(dt1_b)
comment print(min_all)
comment max_all=np.max(dt1_b)
comment dt1_b_norm=(dt1_b-mi... | # =============================================================================
# # -*- coding: utf-8 -*-
# """
# Created on Thu Sep 27 00:11:18 2018
#
# @author: Nadim
# """
#
# min_all=np.min(dt1_b)
# print(min_all)
# max_all=np.max(dt1_b)
# dt1_b_norm=(dt1_b-min_all)/(max_all-min_all)
# dt1_b_norm=dt1_... | Python | zaydzuhri_stack_edu_python |
function apply_over_axes func a axes
begin
set val = call asarray a
set N = ndim
if ndim == 0
begin
set axes = tuple axes
end
for axis in axes
begin
if axis < 0
begin
set axis = N + axis
end
set args = tuple val axis
set res = call func *args
if ndim == ndim
begin
set val = res
end
else
begin
set res = call expand_dims... | def apply_over_axes(func, a, axes):
val = asarray(a)
N = a.ndim
if array(axes).ndim == 0:
axes = (axes,)
for axis in axes:
if axis < 0:
axis = N + axis
args = (val, axis)
res = func(*args)
if res.ndim == val.ndim:
val = res
else:
... | Python | nomic_cornstack_python_v1 |
function load_input self
begin
with open join path MYDIR string input.json as json_data
begin
set d = load json json_data
return d at string subreddits
end
end function | def load_input(self):
with open(os.path.join(config.MYDIR, "input.json")) as json_data:
d = json.load(json_data)
return d["subreddits"] | Python | nomic_cornstack_python_v1 |
if A == B
begin
print string EQUAL
end
else
if length A > length B
begin
print string GREATER
end
else
if length B > length A
begin
print string LESS
end
else
begin
for i in range length A
begin
set a = integer A at i
set b = integer B at i
if a > b
begin
print string GREATER
break
end
else
if b > a
begin
print string ... | if A == B:
print('EQUAL')
elif len(A) > len(B):
print('GREATER')
elif len(B) > len(A):
print('LESS')
else:
for i in range(len(A)):
a = int(A[i])
b = int(B[i])
if a > b:
print('GREATER')
break
elif b > a:
print('LESS')
break | Python | zaydzuhri_stack_edu_python |
function run self
begin
set window_args = dictionary autosize=false height=200 width=200 x_pos=0 y_pos=0
with call window string Drawing keyword window_args
begin
call add_drawing name width=90 height=150
end
with call window string command##window autosize=true y_pos=200 x_pos=0
begin
call add_input_text name=string c... | def run(self):
window_args = dict(
autosize=False,
height=200,
width=200,
x_pos=0,
y_pos=0,
)
with s.window("Drawing", **window_args):
c.add_drawing(
self.name, width=90, height=150
)
wi... | Python | nomic_cornstack_python_v1 |
function move self new_location
begin
set current_location = new_location
end function | def move(self, new_location):
self.current_location = new_location | Python | nomic_cornstack_python_v1 |
function merge left_arr right_arr main_arr
begin
set left_length = length left_arr
set right_length = length right_arr
set i = 0
set j = 0
set k = 0
while i < left_length and j < right_length
begin
if left_arr at i <= right_arr at j
begin
set main_arr at k = left_arr at i
set i = i + 1
end
else
begin
set main_arr at k ... | def merge(left_arr, right_arr, main_arr):
left_length = len(left_arr)
right_length = len(right_arr)
i = 0
j = 0
k = 0
while i < left_length and j < right_length:
if left_arr[i] <= right_arr[j]:
main_arr[k] = left_arr[i]
i += 1
else:
main_arr[k]... | Python | zaydzuhri_stack_edu_python |
function slave_master_structure V slave_master_dict subspace_slave=none subspace_master=none
begin
set slaves = list
set masters = list
set coeffs = list
set offsets = list
set local_min = local_range at 0 * block_size
if subspace_slave is not none
begin
set Vsub_slave = call collapse
end
if subspace_master is not ... | def slave_master_structure(V: function.FunctionSpace, slave_master_dict:
typing.Dict[types.FunctionType,
typing.Dict[
types.FunctionType, float]],
subspace_slave=None,
... | Python | nomic_cornstack_python_v1 |
import math
import threading
comment Function to check if a number is prime
function is_prime n
begin
if n < 2
begin
return false
end
if n == 2
begin
return true
end
if n % 2 == 0
begin
return false
end
for i in range 3 integer square root n + 1 2
begin
if n % i == 0
begin
return false
end
end
return true
end function
... | import math
import threading
# Function to check if a number is prime
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
# Functi... | Python | greatdarklord_python_dataset |
import argparse , numpy as np
set parser = call ArgumentParser
call add_argument string --inFile type=str default=string ./day6Input.txt help=string file contianing input key
set args = call parse_args
with open inFile string r as f
begin
set commands = list comprehension strip x for x in read lines f
end
set grid = ze... | import argparse, numpy as np
parser = argparse.ArgumentParser()
parser.add_argument("--inFile", type=str, default="./day6Input.txt", help="file contianing input key")
args = parser.parse_args()
with open(args.inFile, "r") as f:
commands = [x.strip() for x in f.readlines()]
grid = np.zeros((1000,1000), dtype=np.i... | Python | zaydzuhri_stack_edu_python |
import urllib
import json
function parse_flickr photo_id
begin
set fp = url open string http://api.flickr.com/services/rest/ + string ?method=flickr.photos.getSizes + string &api_key=72b8c51a1f09f08bc9332fcf5ee65f03 + string &photo_id= + photo_id + string &format=json + string &nojsoncallback=1
set repl_str = read fp
s... | import urllib
import json
def parse_flickr(photo_id):
fp = urllib.urlopen(
"http://api.flickr.com/services/rest/" +
"?method=flickr.photos.getSizes" +
"&api_key=72b8c51a1f09f08bc9332fcf5ee65f03" +
"&photo_id=" + photo_id +
"&format=json" +
"&nojsoncallback=1");
repl_str = fp.read()
repl_j... | Python | zaydzuhri_stack_edu_python |
function _convert_raw_byte_data_to_dataframe raw_byte_data nomad_ids=none
begin
comment Each record contains 22 integers (4 byte). The schema is:
set schema = string ( 1) RA at 2000.0 in integer 0.001 arcsec ( 2) SPD at 2000.0 in integer 0.001 arcsec ( 3) std. dev. of RA*COS(dec) in integer 0.001 arcsec at central epoc... | def _convert_raw_byte_data_to_dataframe(raw_byte_data, nomad_ids=None):
# Each record contains 22 integers (4 byte). The schema is:
schema = """ ( 1) RA at 2000.0 in integer 0.001 arcsec
( 2) SPD at 2000.0 in integer 0.001 arcsec
( 3) std. dev. of RA*COS(dec) in integer 0.001 arcsec at ce... | Python | nomic_cornstack_python_v1 |
import sys
from collections import deque
function conquer arr
begin
set L = length arr
set A = L * L
set white = 0
set blue = 0
if A == 1
begin
return arr at 0 at 0
end
for i in range L
begin
for j in range L
begin
if arr at i at j == 0
begin
set white = white + 1
end
else
begin
set blue = blue + 1
end
end
end
if white... | import sys
from collections import deque
def conquer(arr):
L = len(arr)
A = L * L
white = 0
blue = 0
if A==1: return arr[0][0]
for i in range(L):
for j in range(L):
if arr[i][j] == 0: white += 1
else: blue += 1
if white==A: return 0
elif blue==A: ... | Python | zaydzuhri_stack_edu_python |
function create_detr num_classes num_queries backbone
begin
set model = call DETR num_classes num_queries backbone
return model
end function | def create_detr(num_classes: int, num_queries: int, backbone: str):
model = DETR(num_classes, num_queries, backbone)
return model | Python | nomic_cornstack_python_v1 |
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
class Utils
begin
function __init__ self
begin
pass
end function
function Ols self y x
begin
comment we times 10 on both x and y
set mx = call asmatrix x * 10
comment to avoid singular error,
comment which is mainly caused by
com... | import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
class Utils:
def __init__(self):
pass
def Ols(self, y, x):
mx = np.asmatrix(x)*10 # we times 10 on both x and y
# to avoid singular error,
... | Python | zaydzuhri_stack_edu_python |
class InsufficientBalanceError extends Exception
begin
function __init__ self balance amount
begin
set balance = balance
set amount = amount
end function
function difference self
begin
return amount - balance
end function
function __str__ self
begin
return string Insufficient balance [ { balance } ] for a withdraw of [... | class InsufficientBalanceError(Exception):
def __init__(self, balance, amount):
self.balance = balance
self.amount = amount
def difference(self):
return self.amount - self.balance
def __str__(self):
return f"Insufficient balance [{self.balance}] for a withdraw of [{self.amo... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import re
from sklearn.preprocessing import MultiLabelBinarizer , KBinsDiscretizer
from sklearn.impute import SimpleImputer
import ast
import numpy as np
class preprocessor
begin
string preprocessor Class 2 public methods, transform and fit_transform
function __init__ self number_of_bins=8 number_of... | import pandas as pd
import re
from sklearn.preprocessing import MultiLabelBinarizer, KBinsDiscretizer
from sklearn.impute import SimpleImputer
import ast
import numpy as np
class preprocessor:
"""
preprocessor Class
2 public methods, transform and fit_transform
"""
def __init__(self, number_of_bins=8, number_of... | Python | zaydzuhri_stack_edu_python |
function get_average_valid_marks
begin
set flag = true
set marks = list
set result = 0
while flag
begin
set user_input = input string Enter a mark between 0 and 100, or STOP to exit:
comment 如果用户输入 stop,我们把输入的转换成大写,然后跟 ‘STOP’比较,如果是 stop 就设置 flag 为 False,这样就会退出 while 循环
if upper user_input == string STOP
begin
set flag... | def get_average_valid_marks():
flag = True
marks = []
result = 0
while flag:
user_input = input("Enter a mark between 0 and 100, or STOP to exit: ")
# 如果用户输入 stop,我们把输入的转换成大写,然后跟 ‘STOP’比较,如果是 stop 就设置 flag 为 False,这样就会退出 while 循环
if user_input.upper() == 'STOP':
flag ... | Python | zaydzuhri_stack_edu_python |
function process_sample self sample
begin
comment Trim the sample data
call trim threshold
return sample
end function | def process_sample(self, sample):
# Trim the sample data
sample.trim(self.threshold)
return sample | Python | nomic_cornstack_python_v1 |
function useTool tool arguments=none
begin
if arguments is none
begin
set arguments = list none
end
if tool is not none and tool in keys TASK_OPTIONS
begin
try
begin
comment print(str("launching: " + tool))
call arguments
end
except Exception
begin
print string string WARNING - An error occured while + string handling ... | def useTool(tool, arguments=None):
if arguments is None:
arguments = [None]
if (tool is not None) and (tool in TASK_OPTIONS.keys()):
try:
# print(str("launching: " + tool))
TASK_OPTIONS[tool](arguments)
except Exception:
print(str(
"WARNING - An error occured while" +
"handling the shell. Casca... | Python | nomic_cornstack_python_v1 |
function y self
begin
return self at tuple slice : : 1
end function | def y(self):
return self[:, 1] | Python | nomic_cornstack_python_v1 |
string Created on Oct 12, 2016 @author: mwittie
import network_3 as network
import link_3 as link
import threading
from time import sleep
from rprint import print
comment configuration parameters
comment 0 means unlimited
set router_queue_size = 0
comment give the network sufficient time to transfer all packets before ... | '''
Created on Oct 12, 2016
@author: mwittie
'''
import network_3 as network
import link_3 as link
import threading
from time import sleep
from rprint import print
## configuration parameters
router_queue_size = 0 # 0 means unlimited
simulation_time = 10 # give the network sufficient time to transf... | Python | zaydzuhri_stack_edu_python |
function get_angle
begin
set tuple x y z = call getValues
return call angle_from_x
end function | def get_angle():
x, y, z = COMPASS.getValues()
return Vector(x, z).angle_from_x() | Python | nomic_cornstack_python_v1 |
function stop self
begin
call StopTask
call StopTask
end function | def stop(self):
self.initTH.StopTask()
self.pmpTH.StopTask() | Python | nomic_cornstack_python_v1 |
async function test_reauth_failed hass auth_error
begin
set entry = call MockConfigEntry domain=DOMAIN data=DEMO_USER_INPUT
call add_to_hass hass
set result = await call async_init DOMAIN context=dict string source SOURCE_REAUTH ; string entry_id entry_id data=DEMO_USER_INPUT
assert result at string type == string form... | async def test_reauth_failed(hass: HomeAssistant, auth_error) -> None:
entry = MockConfigEntry(
domain=DOMAIN,
data=DEMO_USER_INPUT,
)
entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={
"source": config_entries.SOURC... | Python | nomic_cornstack_python_v1 |
function getTimeSinceLastVsync self
begin
set fn = getTimeSinceLastVsync
set secondsSinceLastVsync = call c_float
set frameCounter = call c_uint64
set result = call fn call byref secondsSinceLastVsync call byref frameCounter
return tuple result value value
end function | def getTimeSinceLastVsync(self):
fn = self.function_table.getTimeSinceLastVsync
secondsSinceLastVsync = c_float()
frameCounter = c_uint64()
result = fn(byref(secondsSinceLastVsync), byref(frameCounter))
return result, secondsSinceLastVsync.value, frameCounter.value | Python | nomic_cornstack_python_v1 |
function check self control
begin
string Since the XOR constraint above handles only constraints with at least two literals, here the other two cases are handled. Empty conflicting constraints result in top-level conflicts and unit constraints will be propagated on the top-level.
if not __sat
begin
call add_clause list... | def check(self, control):
"""
Since the XOR constraint above handles only constraints with at least
two literals, here the other two cases are handled.
Empty conflicting constraints result in top-level conflicts and unit
constraints will be propagated on the top-level.
"... | Python | nomic_cornstack_python_v1 |
function get_reduction_method reduction_type
begin
set reduction_methods = dict string mean lambda x -> mean x ; string sum lambda x -> sum ; string none lambda x -> x
if reduction_type not in reduction_methods
begin
raise call KeyError string Invalid reduction type.
end
return reduction_methods at reduction_type
end f... | def get_reduction_method(reduction_type: str
) -> Callable[[Tensor], Union[Tensor, float]]:
reduction_methods = {
'mean': lambda x: x.mean(),
'sum': lambda x: x.sum(),
'none': lambda x: x
}
if reduction_type not in reduction_methods:
raise KeyError(... | Python | nomic_cornstack_python_v1 |
function add_tokens self sample
begin
comment Text
set inputs = call encode_plus sample at string text add_special_tokens=true max_length=_max_text_length padding=string max_length truncation=true return_attention_mask=true
comment TODO padding here or in model (together with item_glove)?
comment truncate to 512 (added... | def add_tokens(self, sample):
# Text
inputs = self._tokenizer.encode_plus(sample['text'],
add_special_tokens=True,
max_length=self._max_text_length,
padding='max_length', # TODO padding here or in model (together with item_glove)?
truncatio... | Python | nomic_cornstack_python_v1 |
function worst_rating self
begin
return _worst_rating
end function | def worst_rating(self) -> str:
return self._worst_rating | Python | nomic_cornstack_python_v1 |
import random
import string
function generate_password length
begin
set chars = ascii_letters + digits + string $#&
return join string generator expression random choice chars for _ in range length
end function
set length = 8
set password = call generate_password length
print password | import random
import string
def generate_password(length):
chars = string.ascii_letters + string.digits + '$#&'
return ''.join(random.choice(chars) for _ in range(length))
length = 8
password = generate_password(length)
print(password)
| Python | flytech_python_25k |
import numpy as np
import math
from matplotlib import pyplot as plt
from scipy.stats import norm
from Ploter import config_plot
class Robot
begin
string the robot class, we will use this to describe a robot
function __init__ self world_size=100
begin
string creating a robot object :param world_size: the world size in p... | import numpy as np
import math
from matplotlib import pyplot as plt
from scipy.stats import norm
from Ploter import config_plot
class Robot:
"""
the robot class, we will use this to describe a robot
"""
def __init__(self, world_size=100):
"""
creating a robot object
:param worl... | Python | zaydzuhri_stack_edu_python |
import os
import unittest
import matplotlib as mpl
call use string Agg
import matplotlib.pyplot as plt
import numpy as np
import random
from bhtsne import tsne
from sklearn.cluster import MeanShift , estimate_bandwidth
from sklearn.manifold import TSNE
from sklearn.datasets import load_iris
set PLOTS_DIR = directory na... | import os
import unittest
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import random
from bhtsne import tsne
from sklearn.cluster import MeanShift, estimate_bandwidth
from sklearn.manifold import TSNE
from sklearn.datasets import load_iris
PLOTS_DIR = os.path.dirname(os.pa... | Python | zaydzuhri_stack_edu_python |
string Program in Python to print numbers in a range (m,n) without using any loops.
function printNumbers start end
begin
if start == end
begin
return end
end
else
if start > end
begin
print string Incorrect range
end
if start < end
begin
print start
return call printNumbers start + 1 end
end
end function
set result = ... | """
Program in Python to print numbers in a range (m,n) without using any loops.
"""
def printNumbers(start,end):
if start == end:
return end
elif start > end:
print("Incorrect range")
if start < end:
print(start)
return printNumbers(start+1, end)
result = printNumbers(1,10)
print(result)
| Python | zaydzuhri_stack_edu_python |
function filter_lockdown self is_lockdown=false
begin
return if expression is_lockdown then query _obj string Lockdown == 1 else query _obj string Lockdown == 0
end function | def filter_lockdown(self, is_lockdown=False):
return (
self._obj.query("Lockdown == 1")
if is_lockdown
else self._obj.query("Lockdown == 0")
) | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
comment import BorderlineSMOTE
from imblearn.over_sampling import BorderlineSMOTE
from pandas import DataFrame
comment input data file
from sklearn.utils import compute_class_weight
set df = read csv string F:\undersampling.csv header=none sep=string , names=list string fault stri... | import pandas as pd
import numpy as np
from imblearn.over_sampling import BorderlineSMOTE # import BorderlineSMOTE
from pandas import DataFrame
# input data file
from sklearn.utils import compute_class_weight
df = pd.read_csv('F:\\undersampling.csv', header=None, sep=',',
names=['fault', ... | 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.