code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import sys
append path string ..
import os
import json
import requests
from constants import CHAIN_DIR , EXISTING_TXN_DIR
from functions.general_functions import make_block
function update_state_with_existing_transactions state txns
begin
string Takes an existing state and updates it using a list of transactions gather... | import sys
sys.path.append("..")
import os
import json
import requests
from constants import CHAIN_DIR, EXISTING_TXN_DIR
from functions.general_functions import make_block
def update_state_with_existing_transactions(state, txns):
'''
Takes an existing state and updates it using a list of transactions gathe... | Python | zaydzuhri_stack_edu_python |
import sys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
import openpyxl
from datetime import datetime
import pandas as pd
import time
import re
import json
set chrome_options = options
comment , executable_path ="C:\\Users\\... | import sys
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
import openpyxl
from datetime import datetime
import pandas as pd
import time
import re
import json
chrome_options=Options()
driver = webdriver.Chrome(options=chrome_o... | Python | zaydzuhri_stack_edu_python |
function gen_etag self pathname
begin
comment multiple hashes for multiple chunks of the files
set hashes = list
with open pathname string rb as f
begin
while true
begin
set data = read f CHUNK_SIZE
if not data
begin
break
end
append hashes call hash_data data
end
comment Analyze results: files larger than 5 MB will b... | def gen_etag(self, pathname):
# multiple hashes for multiple chunks of the files
hashes = []
with open(pathname, 'rb') as f:
while True:
data = f.read(self.CHUNK_SIZE)
if not data:
break
ha... | Python | nomic_cornstack_python_v1 |
function count tup num
begin
return count tup num
end function
set first = integer input string Enter first element
set second = integer input string Enter second element
set third = integer input string Enter third element
print first string occur count tup first string times
print second string occur count tup second... | def count(tup,num):
return tup.count(num)
first=int(input("Enter first element "))
second=int(input("Enter second element "))
third=int(input("Enter third element "))
print(first ,"occur",count(tup,first),"times")
print(second ,"occur",count(tup,second),"times")
print(third ,"occur",count(tup,third),"times")
| Python | zaydzuhri_stack_edu_python |
class Event extends object
begin
function __init__ self eTime servTime eType
begin
set eTime = eTime
set servTime = servTime
set eType = eType
end function
end class | class Event(object):
def __init__(self, eTime, servTime, eType):
self.eTime = eTime
self.servTime = servTime
self.eType = eType
| Python | zaydzuhri_stack_edu_python |
import sys
from merge_sort import execute_from_file
function valid_num_of_arguments
begin
if length argv != 3
begin
print string Please enter a valid number of arguments
exit 1
end
end function
function convert_num_of_processes_to_number num_of_processes
begin
if not is digit num_of_processes
begin
print string Please ... | import sys
from merge_sort import execute_from_file
def valid_num_of_arguments():
if len(sys.argv) != 3:
print("Please enter a valid number of arguments")
sys.exit(1)
def convert_num_of_processes_to_number(num_of_processes):
if not num_of_processes.isdigit():
print("Please enter a v... | Python | zaydzuhri_stack_edu_python |
string == Лото == Правила игры в лото. Игра ведется с помощью спе циальных карточек, на которых отмечены числа, и фишек (бочонков) с цифрами. Количество бочонков — 90 штук (с цифрами от 1 до 90). Каждая карточка содержит 3 строки по 9 клеток. В каждой строке по 5 случайных цифр, расположенных по возрастанию. Все цифры ... | """
== Лото ==
Правила игры в лото.
Игра ведется с помощью спе циальных карточек, на которых отмечены числа,
и фишек (бочонков) с цифрами.
Количество бочонков — 90 штук (с цифрами от 1 до 90).
Каждая карточка содержит 3 строки по 9 клеток. В каждой строке по 5 случайных цифр,
расположенных по возрастанию. Все цифры... | Python | zaydzuhri_stack_edu_python |
import sys
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class NewVisitorTest extends StaticLiveServerTestCase
begin
decorator classmethod
function setUpClass cls
begin
for arg in argv
begin
if string liveserver in ... | import sys
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class NewVisitorTest(StaticLiveServerTestCase):
@classmethod
def setUpClass(cls):
for arg in sys.argv:
if 'liveserver' in arg:
... | Python | zaydzuhri_stack_edu_python |
import cnn_ as c
import torch
import csv
import numpy as np
function write_csv name arcs accs
begin
with open name + string .csv mode=string w as arc_writer
begin
set arc_writer = writer arc_writer delimiter=string , quotechar=string " quoting=QUOTE_MINIMAL
set acc_names = list string architecture
for i in range length... | import cnn_ as c
import torch
import csv
import numpy as np
def write_csv(name, arcs, accs):
with open(name + ".csv", mode='w') as arc_writer:
arc_writer = csv.writer(arc_writer, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
acc_names = ["architecture"]
for i in range(len(accs... | Python | zaydzuhri_stack_edu_python |
function user_data self access_token *args **kwargs
begin
return call get_json PROFILE_URL params=dict string access_token access_token data=call auth_complete_params call validate_state headers=call auth_headers method=ACCESS_TOKEN_METHOD
end function | def user_data(self, access_token, *args, **kwargs):
return self.get_json(
self.PROFILE_URL,
params={'access_token': access_token},
data=self.auth_complete_params(self.validate_state()),
headers=self.auth_headers(),
method=self.ACCESS_TOKEN_METHOD... | Python | nomic_cornstack_python_v1 |
import operator
function append xs ys
begin
return xs + ys
end function
function concat lists
begin
return list comprehension i for sub in lists for i in sub
end function
function filter_clone function xs
begin
return list comprehension i for i in xs if call function i
end function
function length xs
begin
return sum g... | import operator
def append(xs, ys):
return xs + ys
def concat(lists):
return [i for sub in lists for i in sub]
def filter_clone(function, xs):
return [i for i in xs if function(i)]
def length(xs):
return sum(1 for x in xs)
def map_clone(function, xs):
return [function(x) for x in xs]
def foldl... | Python | zaydzuhri_stack_edu_python |
function test_partial_update_applicant_self self
begin
set data = dict string first_name string First ; string social_security_number string 1337 ; string password string 1337
set applicant_user = call create_user username=string applicant password=string pass
set applicant = call create user=applicant_user social_secu... | def test_partial_update_applicant_self(self):
data = {
'first_name': 'First',
'social_security_number': '1337',
'password': '1337',
}
applicant_user = User.objects.create_user(
username="applicant", password="pass")
applicant = Applicant.... | Python | nomic_cornstack_python_v1 |
comment Thepchai Srinoi 6130809121
import streamlit as st
import pandas as pd
import numpy as np
import altair as alt
import pydeck as pdk
comment SETTING PAGE CONFIG TO WIDE MODE
call set_page_config layout=string wide
comment LOADING DATA
set data1 = read csv string https://raw.githubusercontent.com/Maplub/odsample/m... | ## Thepchai Srinoi 6130809121
import streamlit as st
import pandas as pd
import numpy as np
import altair as alt
import pydeck as pdk
# SETTING PAGE CONFIG TO WIDE MODE
st.set_page_config(layout="wide")
# LOADING DATA
data1 = pd.read_csv('https://raw.githubusercontent.com/Maplub/odsample/master/20190101.... | Python | zaydzuhri_stack_edu_python |
import os
from os.path import join
function removeDuplicates nums
begin
if length nums == 0
begin
return 0
end
if length nums == 1
begin
return 1
end
set i = 1
set cur = nums at 0
set cur_count = 1
while i < length nums
begin
if cur != nums at i
begin
set cur = nums at i
set cur_count = 1
set i = i + 1
end
else
if cur ... | import os
from os.path import join
def removeDuplicates(nums):
if len(nums) == 0: return 0
if len(nums) == 1: return 1
i = 1
cur = nums[0]
cur_count = 1
while i < len(nums):
if cur != nums[i]:
cur = nums[i]
cur_count = 1
i += 1
elif cur == n... | Python | zaydzuhri_stack_edu_python |
function test_resume_scan_results self
begin
set records = 0
function callback part_id input_tuple
begin
nonlocal records
if records == 5
begin
return false
end
set records = records + 1
end function
set scan_obj = call scan test_ns test_set
call foreach callback dict string partition_filter dict string begin 1001 ; st... | def test_resume_scan_results(self):
records = 0
def callback(part_id, input_tuple):
nonlocal records
if records == 5:
return False
records += 1
scan_obj = self.as_connection.scan(self.test_ns, self.test_set)
scan_obj.foreach(callback... | Python | nomic_cornstack_python_v1 |
import string
import random
function generate_random_password length
begin
set characters = ascii_letters + digits + punctuation
return join string random sample characters length
end function
set password_length = 6
set password = call generate_random_password password_length
print password | import string
import random
def generate_random_password(length):
characters = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.sample(characters, length))
password_length = 6
password = generate_random_password(password_length)
print(password) | Python | jtatman_500k |
function gaussian_white z mu=0 sigma=0.7
begin
return 1 - call gaussian_black z mu sigma
end function | def gaussian_white(z, mu: 'normal' = 0, sigma: (0.4, 1) = 0.7):
return 1 - gaussian_black(z, mu, sigma) | Python | nomic_cornstack_python_v1 |
function add_files **kwargs
begin
set files = kwargs at string files
for filename in files
begin
set path = absolute path path filename
set relpath = call relpath path call getenv string HOME
comment Dotfile path without leading dot
set dotfilepath = join path kwargs at string dotfiles_dir left strip relpath string .
c... | def add_files(**kwargs):
files = kwargs['files']
for filename in files:
path = os.path.abspath(filename)
relpath = os.path.relpath(path, os.getenv('HOME'))
# Dotfile path without leading dot
dotfilepath = os.path.join(kwargs['dotfiles_dir'], relpath.lstrip('.'))
# Path m... | Python | nomic_cornstack_python_v1 |
function tsp_brute_force cities
begin
set shortest_route = none
set shortest_distance = decimal string inf
for route in permutations cities
begin
set distance = call calculate_distance route
if distance < shortest_distance
begin
set shortest_distance = distance
set shortest_route = route
end
end
return shortest_route
e... | def tsp_brute_force(cities):
shortest_route = None
shortest_distance = float('inf')
for route in permutations(cities):
distance = calculate_distance(route)
if distance < shortest_distance:
shortest_distance = distance
shortest_route = route
return shortest_route
| Python | greatdarklord_python_dataset |
function find_common_elements set1 set2
begin
set common_elements = set
set result = list
for element in set1
begin
add common_elements element
end
for element in set2
begin
if element in common_elements
begin
remove common_elements element
append result element
end
end
return result
end function
comment Example usage... | def find_common_elements(set1, set2):
common_elements = set()
result = []
for element in set1:
common_elements.add(element)
for element in set2:
if element in common_elements:
common_elements.remove(element)
result.append(element)
return result
... | Python | jtatman_500k |
comment Psi a kilos
function psi_kilos__cm2 psi
begin
set kilos_cm2 = psi / 14.22
return kilos_cm2
end function
comment Kilos a Psi
function kilos_cm2__psi kilos_cm2
begin
set psi = kilos_cm2 * 14.22
return psi
end function
comment Barriles a litros
function barriles__litros barriles
begin
set litros = barriles * 158.9... | def psi_kilos__cm2(psi): # Psi a kilos
kilos_cm2 = psi / 14.22
return kilos_cm2
def kilos_cm2__psi(kilos_cm2): # Kilos a Psi
psi = kilos_cm2 * 14.22
return psi
def barriles__litros(barriles): # Barriles a litros
litros = barriles * 158.99
return litros
def litros__barriles(litros): # L... | Python | zaydzuhri_stack_edu_python |
function wire_to_points wire
begin
set points = set
set pos = ORIGIN
for delta in wire
begin
set new_pos = pos + delta
for tuple i p in enumerate call line_segment pos new_pos
begin
if i > 0
begin
add points p
end
end
set pos = new_pos
end
return points
end function | def wire_to_points(wire: Wire) -> Set[Point]:
points = set()
pos = ORIGIN
for delta in wire:
new_pos = pos + delta
for i, p in enumerate(line_segment(pos, new_pos)):
if i > 0:
points.add(p)
pos = new_pos
return points | Python | nomic_cornstack_python_v1 |
function to_dict self
begin
return dict string type string genetic ; string params dict string timeout timeout
end function | def to_dict(self):
return {'type': 'genetic', 'params': {'timeout': self.timeout}} | Python | nomic_cornstack_python_v1 |
from db import db
class UserModel extends Model
begin
set __tablename__ = string Users
set id = call Column Integer primary_key=true
set username = call Column call String 50
set password = call Column call String 50
function __init__ self _id username password
begin
set id = _id
set username = username
set password = ... | from db import db
class UserModel(db.Model):
__tablename__ = "Users"
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(50))
password = db.Column(db.String(50))
def __init__(self, _id, username, password):
self.id = _id
self.username = username
sel... | Python | zaydzuhri_stack_edu_python |
set num = 5
set num = num + 1
print string The integer is num | num = 5
num +=1
print("The integer is ",num)
| Python | zaydzuhri_stack_edu_python |
function write_to_file data filename location=none
begin
if location
begin
set filename = call normpath string %s/%s % tuple location filename
end
set f = open filename string w
if type data == string
begin
write f data
end
else
begin
write lines f data
end
close f
end function | def write_to_file(data, filename, location=None):
if location:
filename = normpath("%s/%s" % (location, filename))
f = open(filename, "w")
if type(data) == str():
f.write(data)
else:
f.writelines(data)
f.close() | Python | nomic_cornstack_python_v1 |
comment импротируем модуль math
import math
set x = 3.265
comment целое число, ближайшее целое снизу, ближайшее целое сверху
print call trunc x floor x ceil x
comment константа пи
print pi
comment число Эйлера
print e
comment math.sin – синус
set y = sin pi / 4
print round y 2
comment math.sqrt – квадратный корень
set ... | import math # импротируем модуль math
x = 3.265
# целое число, ближайшее целое снизу, ближайшее целое сверху
print(math.trunc(x), math.floor(x), math.ceil(x))
print(math.pi) # константа пи
print(math.e) # число Эйлера
y = math.sin(math.pi / 4) # math.sin – синус
print(round(y, 2))
y = 1 / math.sqrt(2) # math.... | Python | zaydzuhri_stack_edu_python |
comment coding=utf-8
from appium import webdriver
import time
class HelloWorld extends object
begin
function test_enterFilter self
begin
set desired_caps = dictionary
comment 平台的名字,大小写无所谓,不能乱写
set desired_caps at string platformName = string andRoId
comment 平台的版本,(5.4.3 可以写 5.4.3,5.4,5)
set desired_caps at string platf... | #coding=utf-8
from appium import webdriver
import time
class HelloWorld(object):
def test_enterFilter(self):
desired_caps = dict()
# 平台的名字,大小写无所谓,不能乱写
desired_caps['platformName'] = 'andRoId'
# 平台的版本,(5.4.3 可以写 5.4.3,5.4,5)
desired_caps['platformVersion'] = '5'
# 设备的... | Python | zaydzuhri_stack_edu_python |
function get_files_in_folder folderid
begin
call authorize_google_drive
set file_list = call GetList
return file_list
end function | def get_files_in_folder(folderid):
authorize_google_drive()
file_list = DRIVE.ListFile(
{'q': "'{}' in parents and trashed=false".format(folderid)}
).GetList()
return file_list | Python | nomic_cornstack_python_v1 |
function __init__ self obj
begin
raise call NotImplementedError
end function | def __init__(self, obj):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
function dhcpcsvc6_Dhcpv6ReleasePrefix jitter
begin
set tuple ret_ad args = call func_args_stdcall list string adapterName string classId string prefixleaseInfo
raise call RuntimeError string API not implemented
call func_ret_stdcall ret_ad ret_value
end function | def dhcpcsvc6_Dhcpv6ReleasePrefix(jitter):
ret_ad, args = jitter.func_args_stdcall(["adapterName", "classId", "prefixleaseInfo"])
raise RuntimeError('API not implemented')
jitter.func_ret_stdcall(ret_ad, ret_value) | Python | nomic_cornstack_python_v1 |
function writefile_context fname mode leave_incomplete=false
begin
if string a in mode
begin
raise call ValueError string Can not use writefile_context to append.
end
if string r in mode
begin
raise call ValueError string Can not use writefile_context to read.
end
set fname_tmp = fname + string .new
set f = open fname_... | def writefile_context(fname, mode, leave_incomplete=False):
if 'a' in mode:
raise ValueError("Can not use writefile_context to append.")
if 'r' in mode:
raise ValueError("Can not use writefile_context to read.")
fname_tmp = fname+'.new'
f = open(fname_tmp, mode)
try:
yield f
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
class PriorityQueueList
begin
string A priority queue with a linked list as its underlying representation
class Node
begin
function __init__ self value priority
begin
set _value = value
set _priority = priority
set _next = none
end function
decorator property
f... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class PriorityQueueList:
""" A priority queue with a linked list as its underlying representation"""
class Node:
def __init__(self,value,priority):
self._value = value
self._priority = priority
self._next = None
... | Python | zaydzuhri_stack_edu_python |
string # Definition for a Node. class Node: def __init__(self, val, neighbors): self.val = val self.neighbors = neighbors
class Solution
begin
function cloneGraph self node
begin
comment 深度优先遍历 非递归
if node == none
begin
return none
end
set resNode2CopyNode = dict
set stack = list node
set copy = call Node val none
set... | """
# Definition for a Node.
class Node:
def __init__(self, val, neighbors):
self.val = val
self.neighbors = neighbors
"""
class Solution:
def cloneGraph(self, node: 'Node') -> 'Node':
# 深度优先遍历 非递归
if node == None :return None
resNode2CopyNode = {}
stack = [node]
... | Python | zaydzuhri_stack_edu_python |
function getFilePath self file
begin
log string getting path for file %r file
comment FIXME: file.directory_id seems unicode; does not work for url; handle
comment this in paisley internally ?
set d = map dbName call unicode directory_id Directory
function eb failure file
begin
call warningFailure failure
warning strin... | def getFilePath(self, file):
self.log('getting path for file %r', file)
# FIXME: file.directory_id seems unicode; does not work for url; handle
# this in paisley internally ?
d = self.db.map(self.dbName, unicode(file.directory_id), mappings.Directory)
def eb(failure, file):
... | Python | nomic_cornstack_python_v1 |
function parse_json_file json_file_path
begin
comment Set default values for the source (node_id) and the credential in case they are not specified
set remote_access_infos = dict string address string ; string type string ; string port string ; string credential_id string 4 ; string node_id string 1 ; string server_... | def parse_json_file(json_file_path):
# Set default values for the source (node_id) and the credential in case they are not specified
remote_access_infos = {
"address": "",
"type": "",
"port": "",
"credential_id": "4",
"node_id": "1",
"server_groups": ""
}
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
from cachelib.sessioncache import SessionCache
from cachelib.messagecache import MessageCache
import sqlalchemy
from sqlalchemy.orm import sessionmaker
from error import error
from models.chat import User
from sqlalchemy import and_
from models.chat import Message
from models.chat import F... | # -*- coding: utf-8 -*-
from cachelib.sessioncache import SessionCache
from cachelib.messagecache import MessageCache
import sqlalchemy
from sqlalchemy.orm import sessionmaker
from error import error
from models.chat import User
from sqlalchemy import and_
from models.chat import Message
from models.chat import Forbidd... | Python | zaydzuhri_stack_edu_python |
comment Ф-ия перевода температуры из шкалы Цельсия в фарангейты и наоборот
comment из input убираем все пробелы, проверяем последнюю букву шкалы с или f и можно ли преевести число без последнего символа в тип float
comment в зависимости от единицы измерения производится перевод
function to_F_or_C input_str
begin
set in... | #Ф-ия перевода температуры из шкалы Цельсия в фарангейты и наоборот
#из input убираем все пробелы, проверяем последнюю букву шкалы с или f и можно ли преевести число без последнего символа в тип float
#в зависимости от единицы измерения производится перевод
def to_F_or_C(input_str):
input_str="".join(input_str.spl... | Python | zaydzuhri_stack_edu_python |
function process_fact_parking sensordata_sdf dim_parkingbay_sdf dim_location_sdf dim_st_marker_sdf load_id loaded_on
begin
set dim_date_id = string format time loaded_on string %Y%m%d
set midnight = replace loaded_on hour=0 minute=0 second=0 microsecond=0
set dim_time_id = seconds
comment Build fact
set fact_parking = ... | def process_fact_parking(sensordata_sdf: DataFrame,
dim_parkingbay_sdf: DataFrame,
dim_location_sdf: DataFrame,
dim_st_marker_sdf: DataFrame,
load_id, loaded_on):
dim_date_id = loaded_on.strftime("%Y%m%d")
midni... | Python | nomic_cornstack_python_v1 |
string 어떤 파일 시스템에는 디스크 공간이 파일의 사이즈와 항상 같지는 않다. 이것은 디스크가 일정한 크기의 클러스터로 나누어져 있고, 한 클러스터는 오직 한 파일만 이용할 수 있기 때문이다. 예를 들어, 클러스터의 크기가 512바이트이고, 600바이트 파일을 저장하려고 한다면, 두 개의 클러스터에 저장하게 된다. 두 클러스터는 다른 파일과 공유할 수 없기 때문에, 디스크 사용 공간은 1024바이트가 된다. 파일의 사이즈와 클러스터의 크기가 주어질 때, 사용한 디스크 공간을 출력하는 프로그램을 작성하시오.
set N = integer input
set file_... | """
어떤 파일 시스템에는 디스크 공간이 파일의 사이즈와 항상 같지는 않다.
이것은 디스크가 일정한 크기의 클러스터로 나누어져 있고, 한 클러스터는 오직 한 파일만 이용할 수 있기 때문이다.
예를 들어, 클러스터의 크기가 512바이트이고, 600바이트 파일을 저장하려고 한다면, 두 개의 클러스터에 저장하게 된다.
두 클러스터는 다른 파일과 공유할 수 없기 때문에, 디스크 사용 공간은 1024바이트가 된다.
파일의 사이즈와 클러스터의 크기가 주어질 때, 사용한 디스크 공간을 출력하는 프로그램을 작성하시오.
"""
N = int(input())
file_size = ... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Mon Nov 19 18:27:55 2018 @author: user
import random
import math
import matplotlib.pyplot as plt
from statistics import mean , stdev
function trainingProgram1 launch_count
begin
string linear function modeling probability of successful bottle flip. It is based on informat... | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 19 18:27:55 2018
@author: user
"""
import random
import math
import matplotlib.pyplot as plt
from statistics import mean, stdev
def trainingProgram1(launch_count):
"""
linear function modeling probability of successful bottle flip.
It is based... | Python | zaydzuhri_stack_edu_python |
function all self **kwargs
begin
set path = string %s/all % path
set obj = call http_list path keyword kwargs
return list comprehension call _obj_cls self item for item in obj
end function | def all(self, **kwargs):
path = "%s/all" % self.path
obj = self.gitlab.http_list(path, **kwargs)
return [self._obj_cls(self, item) for item in obj] | Python | nomic_cornstack_python_v1 |
for itr in range 5
begin
for outr in range 0 itr + 1
begin
if expression itr % 2 == 0 then print string 0 end=string else print string 1 end=string
end
print string
end | for itr in range(5):
for outr in range(0,itr+1):
print("0",end=" ") if itr%2==0 else print("1",end = " ")
print(" ")
| Python | zaydzuhri_stack_edu_python |
class Tree
begin
function __init__ self entry branches=tuple
begin
set entry = entry
for branch in branches
begin
assert is instance branch Tree
end
set branches = list branches
end function
function __repr__ self
begin
if branches
begin
set branch_repr = string , + call repr branches
end
else
begin
set branch_repr = s... | class Tree:
def __init__(self,entry,branches=()):
self.entry = entry
for branch in branches :
assert isinstance(branch,Tree)
self.branches = list(branches)
def __repr__(self):
if self.branches :
branch_repr = "," + repr(self.branches)
else :
branch_repr = ""
return "Tree({0}{1})".format(self.ent... | Python | zaydzuhri_stack_edu_python |
function compute_flow self lqs
begin
set tuple n t c h w = size lqs
set lqs_1 = reshape lqs at tuple slice : : slice : - 1 : slice : : slice : : slice : : - 1 c h w
set lqs_2 = reshape lqs at tuple slice : : slice 1 : : slice : : slice : : slice : : - 1 c h w
set flows_backward = view call s... | def compute_flow(self, lqs):
n, t, c, h, w = lqs.size()
lqs_1 = lqs[:, :-1, :, :, :].reshape(-1, c, h, w)
lqs_2 = lqs[:, 1:, :, :, :].reshape(-1, c, h, w)
flows_backward = self.spynet(lqs_1, lqs_2).view(n, t - 1, 2, h, w)
if self.is_mirror_extended: # flows_forward = flows_ba... | Python | nomic_cornstack_python_v1 |
function parse_pypi_requires self eb_filename requires
begin
set sys_platform = string Linux
set python_version = python_version
set extra = string
set platform_python_implementation = string CPython
set require_re = string ^([A-Za-z0-9_\-\.]+)(?:.*)$
comment only if the
set extra_re = string and\sextra\s==\s'([A-Za-z... | def parse_pypi_requires(self, eb_filename, requires):
sys_platform = 'Linux'
python_version = self.python_version
extra = ''
platform_python_implementation = 'CPython'
require_re = '^([A-Za-z0-9_\-\.]+)(?:.*)$'
extra_re = "and\sextra\s==\s'([A-Za-z0-9_\-\.]+)'" # only if... | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import numpy as np
set emb_path = string data/sanfrancisco_combined_pca_traffic_labeled_multi_tsne.embeddings
set x_location = tuple - 80 65
set y_location = tuple - 80 80
set color_0 = string aliceblue
set color_1 = string brown
set color_2 = string cyan
set color_3 = string darkkhaki
s... | import matplotlib.pyplot as plt
import numpy as np
emb_path = 'data/sanfrancisco_combined_pca_traffic_labeled_multi_tsne.embeddings'
x_location = (-80, 65)
y_location = (-80, 80)
color_0 = 'aliceblue'
color_1 = 'brown'
color_2 = 'cyan'
color_3 = 'darkkhaki'
color_4 = 'darkviolet'
color_5 = 'greenyellow'
... | Python | zaydzuhri_stack_edu_python |
comment Store your first name in a variable with whitespace on both sides. Print as stored, without whitespace on left, on right, and from both sides.
set first_name = string Vikul
print first_name
print left strip first_name
print right strip first_name
print strip first_name | #Store your first name in a variable with whitespace on both sides. Print as stored, without whitespace on left, on right, and from both sides.
first_name = ' Vikul '
print (first_name)
print (first_name.lstrip())
print (first_name.rstrip())
print (first_name.strip())
| Python | zaydzuhri_stack_edu_python |
function set_source_variable self source_id variable value
begin
set source_id = integer source_id
return call _send_cmd string SET S[%d].%s="%s" % tuple source_id variable value
end function | def set_source_variable(self, source_id, variable, value):
source_id = int(source_id)
return self._send_cmd("SET S[%d].%s=\"%s\"" % (
source_id, variable, value)) | Python | nomic_cornstack_python_v1 |
function createDecimatedDict data adjacency_dict_GRID N_adj_threshold
begin
set boundaryPointsCounter = 0
set boundaryPointsDict = dict
set indexList = list keys data
for i in indexList
begin
set data at i at string E_adj = adjacency_dict_GRID at i
if length data at i at string E_adj >= N_adj_threshold
begin
set data ... | def createDecimatedDict(data, adjacency_dict_GRID, N_adj_threshold):
boundaryPointsCounter = 0
boundaryPointsDict = {}
indexList = list(data.keys())
for i in indexList:
data[i]['E_adj']= adjacency_dict_GRID[i]
if len(data[i]['E_adj']) >= N_adj_threshold:
data[i]['E_type'] = '... | Python | nomic_cornstack_python_v1 |
function get_dist dist_name lookup_dirs=none
begin
string Get dist for installed version of dist_name avoiding pkg_resources cache
comment note: based on pip/utils/__init__.py, get_installed_version(...)
comment Create a requirement that we'll look for inside of setuptools.
set req = parse Requirement dist_name
comment... | def get_dist(dist_name, lookup_dirs=None):
"""Get dist for installed version of dist_name avoiding pkg_resources cache
"""
# note: based on pip/utils/__init__.py, get_installed_version(...)
# Create a requirement that we'll look for inside of setuptools.
req = pkg_resources.Requirement.parse(dist_n... | Python | jtatman_500k |
function get_joystick self event
begin
comment NOTE: event.cdevice.which is the id for SDL_GameControllerOpen() and for SDL_GameControllerFromInstanceID()
return call Joystick instance_id=which
end function | def get_joystick(self, event):
# NOTE: event.cdevice.which is the id for SDL_GameControllerOpen() and for SDL_GameControllerFromInstanceID()
return Joystick(instance_id=event.cdevice.which) | Python | nomic_cornstack_python_v1 |
import os
import pygame
class SceneSuper
begin
set _image_library = dict
function __init__ self
begin
set next = self
end function
function handle_input self events keys
begin
raise call NotImplementedError string handle_input abstract method must be defined in subclass.
end function
function on_update self
begin
rais... | import os
import pygame
class SceneSuper():
_image_library = {}
def __init__(self):
self.next = self
def handle_input(self, events, keys):
raise NotImplementedError("handle_input abstract method must be defined in subclass.")
def on_update(self):
raise NotImplementedError("on... | Python | zaydzuhri_stack_edu_python |
function run argv=none save_main_session=true
begin
comment We use the save_main_session option because one or more DoFn's in this
comment workflow rely on global context (e.g., a module imported at module level).
set pipeline_options = call PipelineOptions
set save_main_session = save_main_session
info call get_all_op... | def run(argv=None, save_main_session=True):
# We use the save_main_session option because one or more DoFn's in this
# workflow rely on global context (e.g., a module imported at module level).
pipeline_options = PipelineOptions()
pipeline_options.view_as(SetupOptions).save_main_session = save_main_ses... | Python | nomic_cornstack_python_v1 |
comment Launch Deck Trellis M4
comment USB HID button box for launching applications, media control, camera switching and more
comment Use it with your favorite keyboard controlled launcher, such as Quicksilver and AutoHotkey
import time
import random
import adafruit_trellism4
from adafruit_hid.keyboard import Keyboard... | # Launch Deck Trellis M4
# USB HID button box for launching applications, media control, camera switching and more
# Use it with your favorite keyboard controlled launcher, such as Quicksilver and AutoHotkey
import time
import random
import adafruit_trellism4
from adafruit_hid.keyboard import Keyboard
from adafru... | Python | zaydzuhri_stack_edu_python |
function create_figure
begin
set tuple fig list list ax0 ax1 list ax2 ax3 = call subplots 2 2
call set_tight_layout true
show
call draw
comment get line objects
set tuple line0 = plot list list
set tuple line1 = plot list list
set tuple line2 = plot list list
set tuple line3 = plot list list
set lines = list line0 ... | def create_figure():
fig, [[ax0, ax1], [ax2, ax3]] = plt.subplots(2,2)
fig.set_tight_layout(True)
fig.show()
fig.canvas.draw()
# get line objects
line0, = ax0.plot([],[])
line1, = ax1.plot([],[])
line2, = ax2.plot([],[])
line3, = ax3.plot([],[])
lines = [line0, line1, line2... | Python | nomic_cornstack_python_v1 |
function get_all_metadata
begin
set entries = all
return dict string data list comprehension call as_dict for entry in entries
end function | def get_all_metadata():
entries = session.query(TableEntities.Metadata).all()
return {'data': [entry.as_dict() for entry in entries]} | Python | nomic_cornstack_python_v1 |
from collections import deque
import sys
set input = readline
class PersonLoc
begin
function __init__ self loc count left_broken_chance
begin
set loc = loc
set count = count
set left_broken_chance = left_broken_chance
end function
function __str__ self
begin
return string loc: { loc } count: { count } lbc: { left_broke... | from collections import deque
import sys
input = sys.stdin.readline
class PersonLoc():
def __init__(self, loc, count, left_broken_chance):
self.loc = loc
self.count = count
self.left_broken_chance = left_broken_chance
def __str__(self):
return f"loc: {self.loc} count: {self.co... | Python | zaydzuhri_stack_edu_python |
function solution phone_book
begin
set length = list map len phone_book
for tuple i v in enumerate phone_book
begin
for j in phone_book
begin
if v == j
begin
continue
end
if v == j at slice : length at i :
begin
return false
end
end
end
return true
end function
comment phone_book = ["12", "123", "1235", "567", "88"]
... | def solution(phone_book):
length = list(map(len, phone_book))
for i,v in enumerate(phone_book):
for j in phone_book:
if v == j:
continue
if v == j[:length[i]]:
return False
return True
# phone_book = ["12", "123", "1235", "567", "88"]
phone_b... | Python | zaydzuhri_stack_edu_python |
function _add_metadata bt md_key lines
begin
set taxonomy_md = call biom_taxonomy_formatter bt md_key
if taxonomy_md is not none
begin
comment one more line than OTU
for i in range length lines - 1
begin
comment skip header line in lines
set lines at i + 1 = lines at i + 1 + string + taxonomy_md at i
end
return lines
... | def _add_metadata(bt, md_key, lines):
taxonomy_md = biom_taxonomy_formatter(bt, md_key)
if taxonomy_md is not None:
for i in range(len(lines) - 1): # one more line than OTU
# skip header line in lines
lines[i + 1] = lines[i + 1] + '\t' + taxonomy_md[i]
return lines... | Python | nomic_cornstack_python_v1 |
import string
import random
function generate_password
begin
set password_characters = ascii_lowercase + ascii_uppercase + punctuation
return join string generator expression random choice password_characters for i in range 10
end function
print call generate_password | import string
import random
def generate_password():
password_characters = string.ascii_lowercase + string.ascii_uppercase + string.punctuation
return ''.join(random.choice(password_characters) for i in range(10))
print(generate_password()) | Python | jtatman_500k |
import socket
import re
import os
from datetime import datetime
class Server
begin
function serv self
begin
set sock = call socket AF_INET SOCK_STREAM
set host = string localhost
set port = 80
call bind tuple host port
print string waiting to connection
call listen 10
while true
begin
set tuple conn addr = call accept
... | import socket
import re
import os
from datetime import datetime
class Server:
def serv(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.host = 'localhost'
self.port = 80
self.sock.bind((self.host, self.port))
print('waiting to connection')... | Python | zaydzuhri_stack_edu_python |
comment Copyright 2014, Sandia Corporation. Under the terms of Contract
comment DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain
comment rights in this software.
from __future__ import absolute_import
from __future__ import division
function show canvas title=string Toyplot Figure
begin
st... | # Copyright 2014, Sandia Corporation. Under the terms of Contract
# DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain
# rights in this software.
from __future__ import absolute_import
from __future__ import division
def show(canvas, title="Toyplot Figure"):
"""Display a canvas in a web... | Python | zaydzuhri_stack_edu_python |
function website_publish_button self
begin
if website_published
begin
write self dict string website_published false
end
else
begin
write self dict string website_published true
end
end function | def website_publish_button(self):
if self.website_published:
self.write({'website_published': False})
else:
self.write({'website_published': True}) | Python | nomic_cornstack_python_v1 |
comment 웹크롤링 프로젝트
comment https://h-glacier.tistory.com/
import datetime
from bs4 import BeautifulSoup
import urllib.request
set now = now
print string 오늘의 주요 정보를 요약해 드리겠습니다.
comment 오늘의 날씨
print string ○>> #오늘의 #날씨 #요약
set webpage = url open string https://search.naver.com/search.naver?sm=top_hty&fbm=0&ie=utf8&query=%... | # 웹크롤링 프로젝트
# https://h-glacier.tistory.com/
import datetime
from bs4 import BeautifulSoup
import urllib.request
now = datetime.datetime.now()
print(' 오늘의 주요 정보를 요약해 드리겠습니다.\n')
# 오늘의 날씨
print(' ○>> #오늘의 #날씨 #요약 \n')
webpage = urllib.request.urlopen('https://search.naver.com/search.naver?sm=top_hty&fbm=0&ie=u... | Python | zaydzuhri_stack_edu_python |
function PP_SPF_AVGRW_DIST Dataframe HNAME_List Raceday
begin
set Feature_DF = loc at tuple slice : : list string HNAME string RARID
set Distance = values at 0
set Extraction = call Extraction_Database format string Select HNAME, RARID, BEYER_SPEED from Race_PosteriorDb where RADAT < {Raceday} and HNAME in {HNAME_Li... | def PP_SPF_AVGRW_DIST(Dataframe, HNAME_List, Raceday):
Feature_DF = Dataframe.loc[:,['HNAME','RARID']]
Distance = Dataframe.loc[:,'RADIS'].values[0]
Extraction = Extraction_Database("""
Select HNAME, RARID, BEYER_SPEED from Race_PosteriorDb
... | Python | nomic_cornstack_python_v1 |
function DownloadCodes url=string https://github.com/wuwenbin2/OnosSystemTest.git
begin
set downloadcode = string git clone + url + string + ONOSCI_PATH + string OnosSystemTest
debug string Download Onos Teston codes + url
call system downloadcode
end function | def DownloadCodes(url="https://github.com/wuwenbin2/OnosSystemTest.git"):
downloadcode = "git clone " + url + " " + ONOSCI_PATH + "OnosSystemTest"
logger.debug("Download Onos Teston codes " + url)
os.system(downloadcode) | Python | nomic_cornstack_python_v1 |
function make_dash_figure plot_content table_content table_id md
begin
set figure = call Col call Tabs children=list call Tab label=string Plot children=list plot_content call Tab label=string Table id=table_id children=list table_content md=md
return figure
end function | def make_dash_figure(plot_content, table_content, table_id, md):
figure = dbc.Col(
dbc.Tabs(
children=[
dbc.Tab(
label='Plot',
children=[
plot_content
]
),
dbc.Tab... | Python | nomic_cornstack_python_v1 |
for tuple i j in zip years price
begin
print i string --> $ j
end | for i,j in zip(years,price):
print(i,'--> $',j) | Python | zaydzuhri_stack_edu_python |
import os
import sys
set filenames = list directory argv at 1
call system string mkdir toolong
set longer = 0
set short = 0
set okfiles = list
for f in filenames
begin
if split f string . at - 1 == string c
begin
append okfiles f
with open argv at 1 + string / + f as fl
begin
set content = read lines fl
if length cont... | import os
import sys
filenames = os.listdir(sys.argv[1])
os.system("mkdir toolong")
longer = 0
short = 0
okfiles = []
for f in filenames:
if f.split(".")[-1] == "c":
okfiles.append(f)
with open(sys.argv[1] + "/" + f) as fl:
content = fl.readlines()
if len(content) == 0: print(f)
if len(cont... | Python | zaydzuhri_stack_edu_python |
from user import User
set users = list call User 1 string bob string asdf
set username_mapping = dictionary comprehension username : u for u in users
set userid_mapping = dictionary comprehension id : u for u in users
function authenticate username password
begin
set user = get username_mapping username none
if user an... | from user import User
users = [User(1,'bob','asdf')]
username_mapping = {u.username: u for u in users}
userid_mapping = {u.id: u for u in users}
def authenticate(username, password):
user = username_mapping.get(username, None)
if user and user.password == password:
return user | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python27
comment -*- coding: utf-8 -*-
comment @Time : 2021/6/23 12:13
comment @Author : handling
comment @File : 3.6_继承collection.abc以实现自定义的容器类型.py
comment @Software: PyCharm
comment python 提供了内置的 collection.abc 模块,该模块定义了一系列的抽象基类,
comment 提供了每一类容器类型所应该具备的常用用法, 如果有忘记实现的方法, 也会及时报错
from collections ... | #!/usr/bin/env python27
# -*- coding: utf-8 -*-
# @Time : 2021/6/23 12:13
# @Author : handling
# @File : 3.6_继承collection.abc以实现自定义的容器类型.py
# @Software: PyCharm
# python 提供了内置的 collection.abc 模块,该模块定义了一系列的抽象基类,
# 提供了每一类容器类型所应该具备的常用用法, 如果有忘记实现的方法, 也会及时报错
from collections import Sequence
class BadTy... | Python | zaydzuhri_stack_edu_python |
function process self source0
begin
comment Step Resize_Image0:
set __resize_image_input = source0
set resize_image_output = call __resize_image __resize_image_input __resize_image_width __resize_image_height __resize_image_interpolation
comment Step HSV_Threshold0:
set __hsv_threshold_input = resize_image_output
set h... | def process(self, source0):
# Step Resize_Image0:
self.__resize_image_input = source0
(self.resize_image_output) = self.__resize_image(self.__resize_image_input, self.__resize_image_width, self.__resize_image_height, self.__resize_image_interpolation)
# Step HSV_Threshold0:
self... | Python | nomic_cornstack_python_v1 |
function proceed_operation self
begin
comment <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
comment Store user entries into computer object.
call _store_user_entries
comment <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
comment Set proceed flag
set proceed = true
comment <><><><><><><><><>... | def proceed_operation(self):
# <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
# Store user entries into computer object.
self._store_user_entries()
# <><><><><><><><><><><><><><><><><><><><><><><><><><><><><><>
# Set proceed flag
self.proceed = True
... | Python | nomic_cornstack_python_v1 |
function inputs self
begin
return __inputs
end function | def inputs(self) -> List[RuleInput]:
return self.__inputs | Python | nomic_cornstack_python_v1 |
function annotations self
begin
return get pulumi self string annotations
end function | def annotations(self) -> Optional[Sequence[Any]]:
return pulumi.get(self, "annotations") | Python | nomic_cornstack_python_v1 |
import os
import numpy as np
import requests
import pickle
import base64
import json
import inspect
import copy
import gzip
import re
import types
set server_url = string https://mugrade.datasciencecourse.org/_/api/
function objects_equal value ref
begin
string Test if two objects are equal according to our autograding... | import os
import numpy as np
import requests
import pickle
import base64
import json
import inspect
import copy
import gzip
import re
import types
server_url = "https://mugrade.datasciencecourse.org/_/api/"
def objects_equal(value,ref):
""" Test if two objects are equal according to our autograding rules.
We... | Python | zaydzuhri_stack_edu_python |
function test_max_daily_profit_output_correct price_data
begin
set max_df = price_data
set res = call calculate_max_profit price_data
set max_df = loc at max_df at string ticker == string GOOGL
set max_df at string profit = max_df at string high - max_df at string low
set max_df = reset index sort values max_df by=stri... | def test_max_daily_profit_output_correct(price_data):
max_df = price_data
res = c.calculate_max_profit(price_data)
max_df = max_df.loc[(max_df['ticker'] == 'GOOGL')]
max_df['profit'] = max_df['high'] - max_df['low']
max_df = max_df.sort_values(by='profit', ascending=False).reset_index()
max_pro... | Python | nomic_cornstack_python_v1 |
import requests
function repos_list data
begin
for item in data
begin
set repo_type = tuple string public string private at item at string private
print string repo_name: { item at string name } _ { repo_type }
end
end function
set api_link = string https://api.github.com
set token = string a27af870100a05e47d831c2de446... | import requests
def repos_list(data):
for item in data:
repo_type = ('public', 'private')[item['private']]
print(f"repo_name: {item['name']} _{repo_type}")
api_link = 'https://api.github.com'
token = 'a27af870100a05e47d831c2de446cac4962b2172'
url = f'{api_link}/user/repos?access_token={token}'
... | Python | zaydzuhri_stack_edu_python |
function _toggleSectionActiveState self sectionName state skipList
begin
string Make an entire section (minus skipList items) either active or inactive. sectionName is the same as the param's scope.
comment Get model data, the list of pars
set theParamList = call getParList
comment Loop over their assoc. entries
for i ... | def _toggleSectionActiveState(self, sectionName, state, skipList):
""" Make an entire section (minus skipList items) either active or
inactive. sectionName is the same as the param's scope. """
# Get model data, the list of pars
theParamList = self._taskParsObj.getParList()
... | Python | jtatman_500k |
function session_count_to_total_count session session_count
begin
comment subtract 1 from session, since sessions are 1 index, but the
comment arrays are zero indexed.
set session = session - 1
if session_count < 0 or session_count >= session_counts at session
begin
raise call ValueError format string {0} is out of ran... | def session_count_to_total_count(session, session_count):
# subtract 1 from session, since sessions are 1 index, but the
# arrays are zero indexed.
session = session - 1
if session_count < 0 or session_count >= session_counts[session]:
raise ValueError("{0} is out of range for Session"
... | Python | nomic_cornstack_python_v1 |
comment Christian Poon 79555434
class Othello
begin
function __init__ self
begin
string Initializes a new customized Othello game by asking for the number of rows and columns on the board, the player that starts the game first, and the winning condition of the game. Once all of these conditions are met, a board will be... | # Christian Poon 79555434
class Othello:
def __init__(self):
'''
Initializes a new customized Othello game by asking for the number of rows
and columns on the board, the player that starts the game first,
and the winning condition of the game. Once all of these conditions are met,
... | Python | zaydzuhri_stack_edu_python |
for tc in range integer input
begin
set tuple n m = map int split input
set a = m
set b = m
set m = 0
set fl = 1
for tccc in range n
begin
set tuple t l h = map int split input
set a = a - t - m
set b = b + t - m
set m = t
if a < l
begin
set a = l
end
if b > h
begin
set b = h
end
if a > b
begin
set fl = 0
end
end
if ex... | for tc in range(int(input())):
n,m=map(int, input().split())
a=b=m
m=0
fl=1
for tccc in range(n):
t,l,h=map(int, input().split())
a-=(t-m)
b+=(t-m)
m=t
if a<l:
a=l
if b>h:
b=h
if a>b:
fl=0
print("YES") i... | Python | jtatman_500k |
comment math 라이브러리 활용 3
import math
comment 14, 21의 최대공약수 반환 # 인자(arguement)는 두 개까지만 허용됨. 세 개 이상 typeerror 발생
print call gcd 14 21 | # math 라이브러리 활용 3
import math
print(math.gcd(14, 21)) # 14, 21의 최대공약수 반환 # 인자(arguement)는 두 개까지만 허용됨. 세 개 이상 typeerror 발생 | Python | zaydzuhri_stack_edu_python |
function event_m10_19_4002000
begin
string State 0,3: [Lib] [BEST] [Preset] Bonfire SFX Management_SubState
set call = call event_m10_19_x91 z91=10192600 z92=10190700
if get call == 0
begin
string State 1: Finish
call EndMachine
call Quit
end
else
if get call == 1
begin
string State 2: Rerun
call RestartMachine
call Qu... | def event_m10_19_4002000():
"""State 0,3: [Lib] [BEST] [Preset] Bonfire SFX Management_SubState"""
call = event_m10_19_x91(z91=10192600, z92=10190700)
if call.Get() == 0:
"""State 1: Finish"""
EndMachine()
Quit()
elif call.Get() == 1:
"""State 2: Rerun"""
... | Python | nomic_cornstack_python_v1 |
function append self url
begin
append queue url
end function | def append(self, url):
self.queue.append(url) | Python | nomic_cornstack_python_v1 |
function decode_cookie encoded
begin
string params: encoded: formated as `var1=val1&var2=val2&...&varn=valn` returns: var to val dictionary
set res = dict
for e in split strip encoded string & string &
begin
try
begin
set tuple var val = split e string = at slice : 2 :
end
except ValueError
begin
set var = split e s... | def decode_cookie(encoded: str) -> dict:
"""
params:
encoded: formated as `var1=val1&var2=val2&...&varn=valn`
returns:
var to val dictionary
"""
res = {}
for e in encoded.strip('&').split('&'):
try:
var, val = e.split('=')[:2]
except (ValueError):
... | Python | zaydzuhri_stack_edu_python |
function sample_prob probs
begin
return relu call sign probs - call random_uniform call shape probs
end function | def sample_prob(probs):
return tf.nn.relu(
tf.sign(probs - tf.random_uniform(tf.shape(probs)))) | Python | nomic_cornstack_python_v1 |
from flask import Flask , request
from flask_json import FlaskJSON , as_json
from flask import abort
from Service.validform import Updater
from Service.statemachine import Stages
from Service.callback import hello_message , analyze_text_and_give_vacancy , goodbye_message
set state = dict 0 hello_message ; 1 analyze_tex... | from flask import Flask, request
from flask_json import FlaskJSON, as_json
from flask import abort
from Service.validform import Updater
from Service.statemachine import Stages
from Service.callback import hello_message, analyze_text_and_give_vacancy, goodbye_message
state = {0: hello_message, 1: analyze_text_and_give... | Python | zaydzuhri_stack_edu_python |
function set_display_set_order sender instance created **_
begin
if not created
begin
return
end
set order = next_display_set_order
save
end function | def set_display_set_order(sender, instance, created, **_):
if not created:
return
instance.order = instance.reader_study.next_display_set_order
instance.save() | Python | nomic_cornstack_python_v1 |
import tensorflow as tf
from kaldi_io import kaldi_io
import numpy as np
class MiscNN extends object
begin
string MiscNN object contains auxiliary functions which are needed for logging and to compute functions in the graph
function __init__ self settings
begin
string Init MiscNN :param codebook_size: size of the codeb... | import tensorflow as tf
from kaldi_io import kaldi_io
import numpy as np
class MiscNN(object):
"""
MiscNN object contains auxiliary functions which are needed for
logging and to compute functions in the graph
"""
def __init__(self, settings):
"""
Init MiscNN
:param codeboo... | Python | zaydzuhri_stack_edu_python |
function PlotTimes metadata data
begin
set gp = call Gnuplot persist=1
call gp string set data style impulses
call gp string set xtics 1
clear gp
x label string seconds
y label string duration in second
title gp call AsTitle
set styles = dict
set line_style = 1
for dataset in data
begin
set x = array time dtype=string... | def PlotTimes(metadata, data):
gp = Gnuplot.Gnuplot(persist=1)
gp('set data style impulses')
gp('set xtics 1')
gp.clear()
gp.xlabel('seconds')
gp.ylabel('duration in second')
gp.title(metadata.AsTitle())
styles = {}
line_style = 1
for dataset in data:
x = numpy.array(dataset.time, dtype='float... | Python | nomic_cornstack_python_v1 |
function describe_workteam WorkteamName=none
begin
pass
end function | def describe_workteam(WorkteamName=None):
pass | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import csv
function csv_combiner main others
begin
string takes in a filename, main and a list of filenames, others and copies the content of each file in others to a file located at main
set headings = list string link string name string desc string date string result string clr1 string c... | # -*- coding: utf-8 -*-
import csv
def csv_combiner(main,others):
"""
takes in a filename, main
and a list of filenames, others
and copies the content of each file in others to a file located at main
"""
headings = ['link','name','desc','date',
'result','clr... | Python | zaydzuhri_stack_edu_python |
comment !python
string This script intented to clone repositories from GitLab Pre-requisites: * Access-Token USAGE: python ListBuildRepos.py
from queue import Queue
import time
import os
import shutil
from threading import Thread
import requests
from git import Repo
from clint.textui import colored
set THREADS_COUNT = ... | #!python
'''
This script intented to clone repositories from GitLab
Pre-requisites:
* Access-Token
USAGE:
python ListBuildRepos.py
'''
from queue import Queue
import time
import os
import shutil
from threading import Thread
import requests
from git import Repo
from clint.textui import color... | Python | zaydzuhri_stack_edu_python |
class Hoge
begin
function index self
begin
set i = 1
comment 初期値、終点、増加値
for go in range 0 11 i
begin
print go
if go == 5
begin
print string 5いただきました!
return true
end
if go == 10
begin
print string いや5とか来ないでしょ、さすがに草
return false
end
end
end function
end class | class Hoge:
def index(self):
i = 1
#初期値、終点、増加値
for go in range(0,11,i):
print(go)
if go == 5:
print('5いただきました!')
return True
if go == 10:
print('いや5とか来ないでしょ、さすがに草')
return False
| Python | zaydzuhri_stack_edu_python |
function get_child_zones self
begin
set zones = set
if children is not none
begin
for space in children
begin
set zones = zones ? zones ? call get_child_zones
end
end
return zones
end function | def get_child_zones( self ):
zones = set()
if self.children is not None:
for space in self.children:
zones |= space.zones | space.get_child_zones()
return zones | Python | nomic_cornstack_python_v1 |
function get_hash_func self
begin
return call CosineHash call get_projection
end function | def get_hash_func(self):
return CosineHash(self.get_projection()) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment Created by: Jonathan Pasco-Arnone
comment Created on: November 2020
comment This program calculates the volume of a sphere
import math
function main
begin
comment This function gets the volume of the sphere and outputs it
set radius_Str = input string What is the radius of this sph... | #!/usr/bin/env python3
# Created by: Jonathan Pasco-Arnone
# Created on: November 2020
# This program calculates the volume of a sphere
import math
def main():
# This function gets the volume of the sphere and outputs it
radius_Str = input("What is the radius of this sphere: ")
radius = int(radius_Str)... | Python | zaydzuhri_stack_edu_python |
function _ball_ending self queue **kwargs
begin
del kwargs
if not active_modes
begin
return
end
set queue = queue
wait queue
set mode_stop_count = 0
for mode in active_modes
begin
if not is_game_mode
begin
continue
end
if auto_stop_on_ball_end
begin
call debug_log string Adding mode '%s' to ball ending queue name
set m... | def _ball_ending(self, queue, **kwargs):
del kwargs
if not self.active_modes:
return
self.queue = queue
self.queue.wait()
self.mode_stop_count = 0
for mode in self.active_modes:
if not mode.is_game_mode:
continue
if... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.