code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function _update_tmp_hosts self
begin
set lowest_metric_interface = none
for ifc in call interfaces
begin
set route = get call current_routes string default none
if route
begin
set metric = get route string metric 0
set candidate = tuple metric ifc
if lowest_metric_interface is none or candidate < lowest_metric_interfa... | def _update_tmp_hosts(self):
lowest_metric_interface = None
for ifc in self.interfaces():
route = ifc.current_routes().get('default', None)
if route:
metric = route.get('metric', 0)
candidate = (metric, ifc)
if (lowest_metric_interface is None or
candidate < lowes... | Python | nomic_cornstack_python_v1 |
function convs self x
begin
for tuple layer drop in zip convolutionals cnn_drop
begin
set x = call max_pool2d relu drop call layer x tuple 1 2
end
if _to_linear is none
begin
print shape
set _to_linear = shape at 0 * shape at 1 * shape at 2
end
return x
end function | def convs(self, x):
for layer, drop in zip(self.convolutionals, self.cnn_drop):
x = F.max_pool2d(F.relu(drop(layer(x))), (1, 2))
if self._to_linear is None:
print(x.shape)
self._to_linear = x[0].shape[0]*x[0].shape[1]*x[0].shape[2]
return x | Python | nomic_cornstack_python_v1 |
import os , sqlite3 , hashlib
class dataoutput
begin
function __init__ self method=none data_path=string data db_name=string data.db
begin
if not exists path data_path
begin
print string Process: Building data path
make directories data_path
end
print format string Data save in {}, path has been build data_path
set dat... | import os,sqlite3,hashlib
class dataoutput():
def __init__(self, method = None, data_path = 'data', db_name = 'data.db'):
if not os.path.exists(data_path):
print('Process: Building data path')
os.makedirs(data_path)
print('Data save in {}, path has been build'.format(data_pat... | Python | zaydzuhri_stack_edu_python |
function from_partial_factorization cls integer partial
begin
set partial_factor = 1
for tuple p e in items partial
begin
set partial_factor = partial_factor * p ^ e
end
assert not integer % partial_factor msg string wrong factorization
return call cls integer // partial_factor * call cls partial_factor partial
end fun... | def from_partial_factorization(cls, integer, partial):
partial_factor = 1
for p, e in partial.items():
partial_factor *= p**e
assert not integer % partial_factor, "wrong factorization"
return cls(integer // partial_factor) * cls(partial_factor, partial) | Python | nomic_cornstack_python_v1 |
set name = string Manny
set number = length name * 3
print format string this is {}'s lucky number {} name number | name = "Manny"
number = len(name) * 3
print ("this is {}'s lucky number {}".format(name, number));
| Python | zaydzuhri_stack_edu_python |
comment Write a class to hold player information, e.g. what room they are in
comment currently.
class Player
begin
string docstring for Player.
function __init__ self curr_location inventory=list
begin
set curr_location = curr_location
set inventory = inventory
end function
function check_inv self
begin
if inventory ==... | # Write a class to hold player information, e.g. what room they are in
# currently.
class Player:
"""docstring for Player."""
def __init__(self, curr_location, inventory=[]):
self.curr_location = curr_location
self.inventory = inventory
def check_inv(self):
if self.inventory == []:... | Python | zaydzuhri_stack_edu_python |
function onOutlineCanvasEvent self target eventType event p
begin
try
begin
set method = gtkMouseActionTable at target at eventType
end
except KeyError
begin
set method = none
end
end function | def onOutlineCanvasEvent(self, target, eventType, event, p):
try:
method = self.gtkMouseActionTable[target][eventType]
except KeyError:
method = None | Python | nomic_cornstack_python_v1 |
function add_product_to_basket
begin
set data = loads read body
comment Checking for validity of inputs if following keys exist
if not get data string name or not get data string amount
begin
call redirect string invalid_product.json
end
set product_name = data at string name
set purchase_amount = integer data at strin... | def add_product_to_basket():
data = json.loads(request.body.read())
#Checking for validity of inputs if following keys exist
if not data.get("name") or not data.get("amount"):
redirect('invalid_product.json')
product_name = data["name"]
purchase_amount = int(data["amount"])
if not __valid_product(product_nam... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import os
import subprocess
set num_correct = call string ./execute_submission_and_assess_output.sh shell=true
print string Score: + string num_correct + string out of 2 correct.
print string *************Original submission*************
with open string subtract.py string r as fs
begin
pri... | #!/usr/bin/env python
import os
import subprocess
num_correct = subprocess.call("./execute_submission_and_assess_output.sh", shell=True)
print ("Score: " + str(num_correct) + " out of 2 correct.")
print("*************Original submission*************")
with open('subtract.py','r') as fs:
print(fs.read())
| Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import copy
import seaborn as sns
set color_codes=true
import os
comment from scipy.stats import entropy as distance
from scipy.stats import entropy as DKL
from scipy.spatial.distance import jensenshannon as JSD
function data_probs ds bins_partition... | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import copy
import seaborn as sns
sns.set(color_codes=True)
import os
# from scipy.stats import entropy as distance
from scipy.stats import entropy as DKL
from scipy.spatial.distance import jensenshannon as JSD
def data_probs(ds,bins_partitio... | Python | zaydzuhri_stack_edu_python |
function show_models self tablename
begin
if not call check_if_table_exists tablename
begin
raise call BayesDBInvalidBtableError tablename
end
set models = call get_models tablename
set modelid_iteration_info = list
for tuple modelid model in sorted items models key=lambda t -> t at 0
begin
append modelid_iteration_inf... | def show_models(self, tablename):
if not self.persistence_layer.check_if_table_exists(tablename):
raise utils.BayesDBInvalidBtableError(tablename)
models = self.persistence_layer.get_models(tablename)
modelid_iteration_info = list()
for modelid, model in sorted(models.items(), key=lambd... | Python | nomic_cornstack_python_v1 |
comment We are given a linked list with head as the first node.
comment Let's number the nodes in the list: node_1, node_2, node_3, ... etc.
comment Each node may have a next larger value: for node_i, next_larger(node_i) is the node_j.val such that j > i, node_j.val > node_i.val,
comment and j is the smallest possible ... | # We are given a linked list with head as the first node.
# Let's number the nodes in the list: node_1, node_2, node_3, ... etc.
#
# Each node may have a next larger value: for node_i, next_larger(node_i) is the node_j.val such that j > i, node_j.val > node_i.val,
# and j is the smallest possible choice. If such a j d... | Python | zaydzuhri_stack_edu_python |
function planned_purge_date self planned_purge_date
begin
set _planned_purge_date = planned_purge_date
end function | def planned_purge_date(self, planned_purge_date):
self._planned_purge_date = planned_purge_date | Python | nomic_cornstack_python_v1 |
function password_min_number self
begin
return get pulumi self string password_min_number
end function | def password_min_number(self) -> pulumi.Output[Optional[int]]:
return pulumi.get(self, "password_min_number") | Python | nomic_cornstack_python_v1 |
function to_usd my_price
begin
return string $ { my_price }
end function | def to_usd(my_price):
return f"${my_price:,.2f}" | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
set x = integer input
set y = integer input
set z = integer input
set N = integer input
comment Breakdown:
set poplulated_list = list
for i in range x + 1
begin
for j in range y + 1
begin
for k in range z + 1
begin
if i + j + k != N
begin
append poplulated_list list i j k
end
end
end
end
prin... | #!/usr/bin/python3
x = int(input())
y = int(input())
z = int(input())
N = int(input())
# Breakdown:
poplulated_list = []
for i in range(x+1):
for j in range(y+1):
for k in range(z+1):
if i+j+k != N:
poplulated_list.append([i,j,k])
print(poplulated_list)
# By list comprehen... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Fri Apr 2 10:51:51 2021 @author: snetkova
import pandas as pd
import numpy as np
function prefilter_items data item_features
begin
comment Уберем самые популярные товары (их и так купят)
set popularity = reset index call nunique / call nunique
rename columns=dict string u... | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 2 10:51:51 2021
@author: snetkova
"""
import pandas as pd
import numpy as np
def prefilter_items(data, item_features):
# Уберем самые популярные товары (их и так купят)
popularity = data.groupby('item_id')['user_id'].nunique().reset_index() / data['user_id'].nun... | Python | zaydzuhri_stack_edu_python |
function start_stream self callback done mode=string blocking
begin
if mode == string blocking
begin
call start_blocking_stream callback done
end
if mode == string callback
begin
call start_callback_stream callback done
end
end function | def start_stream(self, callback, done, mode='blocking'):
if mode == 'blocking':
self.start_blocking_stream(callback, done)
if mode == 'callback':
self.start_callback_stream(callback, done) | Python | nomic_cornstack_python_v1 |
function do_list_rooms self arg
begin
print string | N° | COUCHAGES |
for room in rooms
begin
print string | { number } | { nb_bed } |
end
end function | def do_list_rooms(self, arg):
print('| N° | COUCHAGES |')
for room in self.hotel.rooms:
print(f"| {room.number:04} | {room.nb_bed:>9} |") | Python | nomic_cornstack_python_v1 |
class Student
begin
function __init__ self name age gender
begin
set name = name
set age = age
set gender = gender
end function
end class | class Student:
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender | Python | iamtarun_python_18k_alpaca |
function nextpow2 x
begin
return ceil call log2 absolute x
end function | def nextpow2(x):
return np.ceil(np.log2(abs(x))) | Python | nomic_cornstack_python_v1 |
import numpy as np
comment import sys
set s1 = input string Enter Word 1:
set s2 = input string Enter Word 2:
set insertion = integer input string Enter Insertion Cost:
set deletion = integer input string Enter Deletion Cost:
set substitution = insertion + deletion
set s_matrix = call ndarray shape=tuple length s1 + 1 ... | import numpy as np
#import sys
s1 = input("Enter Word 1:")
s2 = input("Enter Word 2:")
insertion=int(input('Enter Insertion Cost: '))
deletion=int(input('Enter Deletion Cost: '))
substitution = insertion+deletion
s_matrix = np.ndarray(shape=(len(s1)+1,len(s2)+1), dtype=int)
s_matrix.fill(0)
bt_matrix = np.ndarray(sha... | Python | zaydzuhri_stack_edu_python |
comment @lc app=leetcode.cn id=387 lang=python3
comment [387] 字符串中的第一个唯一字符
comment @lc code=start
class Solution
begin
function firstUniqChar self s
begin
set first_dict = dictionary
set more_set = set
for tuple index char in enumerate s
begin
if char in first_dict
begin
del first_dict at char
add more_set char
end
els... | #
# @lc app=leetcode.cn id=387 lang=python3
#
# [387] 字符串中的第一个唯一字符
#
# @lc code=start
class Solution:
def firstUniqChar(self, s: str) -> int:
first_dict = dict()
more_set = set()
for index, char in enumerate(s):
if char in first_dict:
del first_dict[char]
... | Python | zaydzuhri_stack_edu_python |
function photons self depth=1
begin
set dx at tuple slice : : slice : W - 1 : = z at tuple slice : : slice 1 : : - z at tuple slice : : slice : W - 1 :
set dy at tuple slice : H - 1 : slice : : = z at tuple slice 1 : : slice : : - z at tuple slice : H - 1 : slice : :
set px = xv - dx * dep... | def photons(self, depth=1):
self.dx[:,:self.W-1] = self.z[:,1:] - self.z[:,:self.W-1]
self.dy[:self.H-1,:] = self.z[1:,:] - self.z[:self.H-1,:]
px = self.xv - self.dx*depth
py = self.yv - self.dy*depth
return px,py | Python | nomic_cornstack_python_v1 |
from tkinter import *
set root = call Tk
set usernameLabel = call Label root text=string Name:
set passwordLabel = call Label root text=string Password:
set usernameEntry = call Entry root
set passwordEntry = call Entry root
grid row=0 sticky=E
grid row=1 sticky=E
grid row=0 column=1
grid row=1 column=1
set loggedInChe... | from tkinter import *
root = Tk()
usernameLabel = Label(root,text="Name:")
passwordLabel = Label(root,text="Password:")
usernameEntry = Entry(root)
passwordEntry = Entry(root)
usernameLabel.grid(row=0,sticky=E)
passwordLabel.grid(row=1,sticky=E)
usernameEntry.grid(row=0,column=1)
passwordEntry.grid(row=1,column=1)
... | Python | zaydzuhri_stack_edu_python |
function show_person_vcard login=none
begin
set person = first filter by query login=login
return call create_vcard
end function | def show_person_vcard(login=None):
person = Person.query.filter_by(login=login).first()
return person.create_vcard() | Python | nomic_cornstack_python_v1 |
function write_json self filename
begin
try
begin
with open filename string w+ as f
begin
write f to json self
end
end
except IOError
begin
error string Couldn't save data to %s % filename
end
end function | def write_json(self, filename):
try:
with open(filename, 'w+') as f:
f.write(self.to_json())
except IOError:
log.error("Couldn't save data to %s" % filename) | Python | nomic_cornstack_python_v1 |
function _is_fixed self row_id col_id
begin
return call build_fixed_val_key row_id col_id in _fixed_values
end function | def _is_fixed(self, row_id, col_id):
return s_utils.build_fixed_val_key(row_id, col_id) in self._fixed_values | Python | nomic_cornstack_python_v1 |
function prime_multiples num1 num2
begin
comment Check if both arguments are prime numbers
if not call is_prime num1 or not call is_prime num2
begin
raise call ValueError string Both arguments must be prime numbers
end
set product = num1 * num2
comment Create a table of the first 10 multiples of the product
set table =... | def prime_multiples(num1, num2):
# Check if both arguments are prime numbers
if not is_prime(num1) or not is_prime(num2):
raise ValueError("Both arguments must be prime numbers")
product = num1 * num2
# Create a table of the first 10 multiples of the product
table = []
for i in range(1... | Python | jtatman_500k |
string The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ?
import math
function intoPrime n
begin
set half = floor square root n
set l = list 0 0
for i in range 2 half + 1
begin
append l i
end
set i = 0
while i < length l
begin
set t = i
if 0 != l at i
begin
whi... | """
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
"""
import math
def intoPrime(n):
half = math.floor(math.sqrt(n))
l = [0, 0]
for i in range(2, half+1):
l.append(i)
i = 0
while (i < len(l)):
t = i
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment @Time : 2021/8/29 20:45
comment @File : 切片案例.py
comment @Software: PyCharm
comment 索引是通过下标取某一个元素
comment 切片是通过下标去某一段元素
set s = string Helmo5World!
comment 取下标为4的元素
print s at 4
print s
comment 取出所有元素(没有起始位和结束位之分),默认步长为1
print s at slice : :
comment 从下标为1开始,取出 后面所有的元素(没有结束位)
print... | # -*- coding: utf-8 -*-
# @Time : 2021/8/29 20:45
# @File : 切片案例.py
# @Software: PyCharm
# 索引是通过下标取某一个元素
# 切片是通过下标去某一段元素
s = 'Helmo5World!'
print(s[4]) # 取下标为4的元素
print(s)
print(s[:]) # 取出所有元素(没有起始位和结束位之分),默认步长为1
print(s[1:]) # 从下标为1开始,取出 后面所有的元素(没有结束位)
print(s[:5]) # 从起始位置开始,取到 下标为5的前一个元素(不包括结束位本身)
print(s[:... | Python | zaydzuhri_stack_edu_python |
function validate self
begin
if not call _on_detail_page
begin
call force_navigate string cloud_provider context=dict string provider self
end
set stats_to_match = list string num_template string num_vm
set client = call get_mgmt_system
comment Bail out here if the stats match.
if call _do_stats_match client stats_to_m... | def validate(self):
if not self._on_detail_page():
sel.force_navigate('cloud_provider', context={'provider': self})
stats_to_match = ['num_template', 'num_vm']
client = self.get_mgmt_system()
# Bail out here if the stats match.
if self._do_stats_match(client, stats_... | Python | nomic_cornstack_python_v1 |
import urllib.request
import http.cookiejar
from socket import timeout
import time
class timeout_error extends Exception
begin
pass
end class
class number_of_trains_convert_error extends Exception
begin
pass
end class
class Tcarriage_type
begin
set typ = type int
set free_seats = type int
set price = type float
set spr... | import urllib.request
import http.cookiejar
from socket import timeout
import time
class timeout_error(Exception): pass
class number_of_trains_convert_error(Exception): pass
class Tcarriage_type:
typ = type(int)
free_seats = type(int)
price = type(float)
sprice = type(str)
empty =... | Python | zaydzuhri_stack_edu_python |
function get_circle_area radius
begin
string Calculate and return the area of a circle with a given radius. Args: radius (float): The radius of the circle Returns: float: The area of the circle
return 3.14 * radius * radius
end function | def get_circle_area(radius):
"""Calculate and return the area of a circle with a given radius.
Args:
radius (float): The radius of the circle
Returns:
float: The area of the circle
"""
return 3.14 * (radius * radius)
| Python | flytech_python_25k |
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 |
function _read service spreadsheet_id sheet_id=0 cell_range=none
begin
if cell_range is none
begin
set cell_range = call a1_all service spreadsheet_id sheet_id=sheet_id
end
call _wait
set result = execute get values call spreadsheets spreadsheetId=spreadsheet_id range=cell_range valueRenderOption=string FORMULA
set val... | def _read(service, spreadsheet_id, sheet_id=0, cell_range=None):
if cell_range is None:
cell_range = a1_all(service, spreadsheet_id, sheet_id=sheet_id)
_wait()
result = (
service.spreadsheets()
.values()
.get(
spreadsheetId=spreadsheet_id,
range=cell_r... | Python | nomic_cornstack_python_v1 |
string This file defines the functions that will be used to explore the Actyx API. This script checks the list of machines and the environmental sensor after every 60 seconds to see the values of current drawn by each and every machine and the values of pressure, temperature, and humidity of the production environment ... | """
This file defines the functions that will be used to explore the Actyx API.
This script checks the list of machines and the environmental sensor after every 60 seconds to see the values of current
drawn by each and every machine and the values of pressure, temperature, and humidity of the production environment to
... | Python | zaydzuhri_stack_edu_python |
function create_regular_season_schedule self
begin
for team in all
begin
call reset
end
call reset
call create_regular_season all
end function | def create_regular_season_schedule(self):
for team in self.team_set.all():
team.reset()
self.schedule.reset()
self.schedule.create_regular_season(self.team_set.all()) | Python | nomic_cornstack_python_v1 |
comment 3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn.
comment Например, пользователь ввёл число 3.
comment Считаем 3 + 33 + 333 = 369.
set n = input string Введите число:
set nn = integer n + n
set nnn = integer n + n + n
set summ = integer n + nn + nnn
print summ | # 3. Узнайте у пользователя число n. Найдите сумму чисел n + nn + nnn.
# Например, пользователь ввёл число 3.
# Считаем 3 + 33 + 333 = 369.
n = input("Введите число: ")
nn = int(n+n)
nnn = int(n+n+n)
summ = int(n)+nn+nnn
print(summ)
| Python | zaydzuhri_stack_edu_python |
function bton b encoding
begin
return b
end function | def bton(b, encoding):
return b | Python | nomic_cornstack_python_v1 |
comment 참이나 거짓을 나타내는 True, False 두 상수를 갖는다
set a = 1
set b = a < 10
print b type b sep=string ,
set b1 = true
set b2 = false
comment c와 같이 true가 1이고, false가 0이란 것을 알 수 있음
print b1 + 10
print b2 + 10
print true + true
if a < 10
begin
comment if문 안에 쓸 내용이 없으면 pass를 사용!(비어놓으면 에러남)
pass
end
if a < 10
begin
print a
end | # 참이나 거짓을 나타내는 True, False 두 상수를 갖는다
a = 1
b = a < 10
print(b, type(b), sep=",")
b1 = True
b2 = False
# c와 같이 true가 1이고, false가 0이란 것을 알 수 있음
print(b1 + 10)
print(b2 + 10)
print(True + True)
if a < 10:
pass # if문 안에 쓸 내용이 없으면 pass를 사용!(비어놓으면 에러남)
if a < 10:
print(a) | Python | zaydzuhri_stack_edu_python |
function gbc2rgb c
begin
comment GBC format: 0bbbbbgggggrrrrr (b-blue, g-green, r-red)
set r = c % 1 ? 5 ? 3
set g = c / 1 ? 5 % 1 ? 5 ? 3
set b = c / 1 ? 10 % 1 ? 5 ? 3
return tuple r g b
end function | def gbc2rgb(c):
#GBC format: 0bbbbbgggggrrrrr (b-blue, g-green, r-red)
r = (c % (1 << 5)) << 3
g = ((c / (1 << 5)) % (1 << 5)) << 3
b = ((c / (1 << 10)) % (1 << 5)) << 3
return (r,g,b) | Python | nomic_cornstack_python_v1 |
string This script is for generating Level 1 genbank files using an excel sheet with maps showing which Level 0s belong in each Level 1, and in what order. Template: RDJ Plasmids.xlsx Post-processing: - A2 insulator annotation disappears (and probably others spanning an internal BsaI site too) - Annotations with spaces... | '''
This script is for generating Level 1 genbank files using an excel sheet with
maps showing which Level 0s belong in each Level 1, and in what order.
Template: RDJ Plasmids.xlsx
Post-processing:
- A2 insulator annotation disappears
(and probably others spanning an internal BsaI site too)
- Annotations with s... | Python | zaydzuhri_stack_edu_python |
function test_getReaders self
begin
set poller = call _ContinuousPolling call Clock
set reader = call object
call addReader reader
assert in reader call getReaders
end function | def test_getReaders(self):
poller = _ContinuousPolling(Clock())
reader = object()
poller.addReader(reader)
self.assertIn(reader, poller.getReaders()) | Python | nomic_cornstack_python_v1 |
import math
function value w
begin
set val = 0
for l in w
begin
set val = val + ordinal l - ordinal string A + 1
end
return val
end function
function is_triangle_number n
begin
set x = integer square root 2 * n
return x * x + 1 / 2 == n
end function
set hits = 0
with open string 042 - words.txt as f
begin
for w in spli... | import math
def value(w):
val = 0
for l in w:
val += ord(l) - ord("A") + 1
return val
def is_triangle_number(n):
x = int(math.sqrt(2 * n))
return x*(x+1)/2 == n
hits = 0
with open("042 - words.txt") as f:
for w in f.readline().replace('"',"").split(","):
if is_triangle_numbe... | Python | zaydzuhri_stack_edu_python |
function declare_variable var bound_variables
begin
set varname = name
set vartype = vartype
comment check if it is bound and has already been seen
if bound_variables is not none and varname in bound_variables
begin
set yvar = yices_term
set bound = true
return yvar
end
comment check if it has already been seen
set yva... | def declare_variable(var, bound_variables):
varname = var.name
vartype = var.vartype
# check if it is bound and has already been seen
if bound_variables is not None and varname in bound_variables:
yvar = bound_variables[varname].yices_term
var.bound = True
... | Python | nomic_cornstack_python_v1 |
function lorentz_metric self name signature=string positive latex_name=none
begin
from metric import LorentzMetric
return call LorentzMetric self name signature=signature latex_name=latex_name
end function | def lorentz_metric(self, name, signature='positive', latex_name=None):
from metric import LorentzMetric
return LorentzMetric(self, name, signature=signature,
latex_name=latex_name) | Python | nomic_cornstack_python_v1 |
function _find_axis_ self
begin
set __axis = where __nodes at tuple slice : : 0 == 0 at 0
end function | def _find_axis_(self) -> None:
self.__axis = np.where(self.__nodes[:, 0] == 0)[0] | Python | nomic_cornstack_python_v1 |
function get_novelty_rate seen_expressions unseen_expressions
begin
set num_seen_expressions = length seen_expressions
set num_unseen_expressions = length unseen_expressions
set num_total_expressions = num_seen_expressions + num_unseen_expressions
if num_total_expressions == 0
begin
raise call ValueError string Total n... | def get_novelty_rate(seen_expressions, unseen_expressions):
num_seen_expressions = len(seen_expressions)
num_unseen_expressions = len(unseen_expressions)
num_total_expressions = num_seen_expressions + num_unseen_expressions
if num_total_expressions == 0:
raise ValueError('Total number of expressions cannot ... | Python | nomic_cornstack_python_v1 |
import argparse
import string
set parser = call ArgumentParser
call add_argument string -s action=string store_true
set args = call parse_args
set filename = if expression s then string input_sample.txt else string input.txt
with open filename as file
begin
set lines = list comprehension right strip line for line in fi... | import argparse
import string
parser = argparse.ArgumentParser()
parser.add_argument('-s', action='store_true')
args = parser.parse_args()
filename = "input_sample.txt" if args.s else "input.txt"
with open(filename) as file:
lines = [line.rstrip() for line in file]
pairs = 0
for l in lines:
[e1, e2] = l.sp... | Python | zaydzuhri_stack_edu_python |
comment utility function for creating a custom trading environment
comment customise the trading environment signal features
function process_data df window_size frame_bound price_feature signal_features
begin
set start = frame_bound at 0 - window_size
set end = frame_bound at 1
set prices = call to_numpy at slice star... | # utility function for creating a custom trading environment
# customise the trading environment signal features
def process_data(df,window_size, frame_bound, price_feature, signal_features):
start = frame_bound[0] - window_size
end = frame_bound[1]
prices = df.loc[:, price_feature].to_numpy()[start:end]
... | Python | zaydzuhri_stack_edu_python |
function _set_id self v load=false
begin
if has attribute v string _utype
begin
set v = call _utype v
end
try
begin
set t = call YANGDynClass v base=unicode is_leaf=true yang_name=string id parent=self path_helper=_path_helper extmethods=_extmethods register_paths=true namespace=string http://openconfig.net/yang/qos de... | def _set_id(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=unicode, is_leaf=True, yang_name="id", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, namespace='http://openconfig.net/yang/qos', defining_module='op... | Python | nomic_cornstack_python_v1 |
function over self
begin
return _over
end function | def over(self):
return self._over | Python | nomic_cornstack_python_v1 |
function AddHorizontalDimension2 self X=defaultNamedNotOptArg Y=defaultNamedNotOptArg Z=defaultNamedNotOptArg
begin
set ret = call InvokeTypes 66210 LCID 1 tuple 9 0 tuple tuple 5 1 tuple 5 1 tuple 5 1 X Y Z
if ret is not none
begin
set ret = call Dispatch ret string AddHorizontalDimension2 none
end
return ret
end func... | def AddHorizontalDimension2(self, X=defaultNamedNotOptArg, Y=defaultNamedNotOptArg, Z=defaultNamedNotOptArg):
ret = self._oleobj_.InvokeTypes(66210, LCID, 1, (9, 0), ((5, 1), (5, 1), (5, 1)),X
, Y, Z)
if ret is not None:
ret = Dispatch(ret, u'AddHorizontalDimension2', None)
return ret | Python | nomic_cornstack_python_v1 |
function employment_agreement self employment_agreement
begin
if employment_agreement is not none and length employment_agreement > 1024
begin
comment noqa: E501
raise call ValueError string Invalid value for `employment_agreement`, length must be less than or equal to `1024`
end
set _employment_agreement = employment_... | def employment_agreement(self, employment_agreement):
if employment_agreement is not None and len(employment_agreement) > 1024:
raise ValueError("Invalid value for `employment_agreement`, length must be less than or equal to `1024`") # noqa: E501
self._employment_agreement = employment_agr... | Python | nomic_cornstack_python_v1 |
import pytest
from matcher import count , checksum , findDifference , compare
function test_count
begin
assert count string abcdef == tuple false false
assert count string bababc == tuple true true
assert count string abbcde == tuple true false
assert count string abcccd == tuple false true
assert count string aabcdd =... | import pytest
from matcher import count, checksum, findDifference, compare
def test_count():
assert count('abcdef') == (False, False)
assert count('bababc') == (True, True)
assert count('abbcde') == (True, False)
assert count('abcccd') == (False, True)
assert count('aabcdd') == (True, False)
as... | Python | zaydzuhri_stack_edu_python |
comment AbstractClass.py
comment example-01
comment This is not an abstract class because:
comment > we can instantiate an instance from
comment > we are not required to implement do_something in the class defintition of B
class AbstractClass
begin
function do_something self
begin
pass
end function
end class
class B ex... | #AbstractClass.py
# example-01
#
# This is not an abstract class because:
# > we can instantiate an instance from
# > we are not required to implement do_something in the class defintition of B
class AbstractClass:
def do_something(self):
pass
class B(AbstractClass):
pass
a = AbstractCl... | Python | zaydzuhri_stack_edu_python |
import pygame
import sys
import json
import draw_func
from draw_func_2 import draw
class Level
begin
set window_size = tuple 360 420
set tuple width height = tuple 360 420
set screen = call set_mode window_size
set colors = list tuple 0 191 255 tuple 201 160 115 tuple 110 75 41 tuple 255 255 254 tuple 255 255 255 tuple... | import pygame
import sys
import json
import draw_func
from draw_func_2 import draw
class Level:
window_size = width, height = 360, 420
screen = pygame.display.set_mode(window_size)
colors = [(0, 191, 255), (201, 160, 115), (110, 75, 41), (255, 255, 254), (255, 255, 255), (109, 200, 242), (24... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import math
import sys
import logging
import re
from collections import defaultdict
import tempfile
set testdata = string 8 4 2 5 2 6 2 1000 1000 1000 1 500000 281623 194724 19432 924213 445262
function readstr fhandle
begin
return strip read line fhandle
end function
function readone fhand... | #!/usr/bin/env python
import math
import sys
import logging
import re
from collections import defaultdict
import tempfile
testdata = '''8
4 2
5 2
6 2
1000 1000
1000 1
500000 281623
194724 19432
924213 445262
'''
def readstr(fhandle):
return fhandle.readline().strip()
def readone(fhandle):
return int(fhandle... | Python | zaydzuhri_stack_edu_python |
comment noqa: E501
function __init__ self message=none pod_name=none reason=none state=none
begin
set swagger_types = dict string message str ; string pod_name str ; string reason str ; string state str
set attribute_map = dict string message string message ; string pod_name string podName ; string reason string reason... | def __init__(self, message: str=None, pod_name: str=None, reason: str=None, state: str=None): # noqa: E501
self.swagger_types = {
'message': str,
'pod_name': str,
'reason': str,
'state': str
}
self.attribute_map = {
'message': 'messag... | Python | nomic_cornstack_python_v1 |
comment Using selenium Automated router with different IP
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from time ... | # Using selenium Automated router with different IP
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from time impor... | Python | zaydzuhri_stack_edu_python |
import re
import inspect
import types
function is_function obj
begin
return call is_method obj or call isfunction obj or is instance obj MethodWrapperType
end function
function is_primitive obj
begin
return is instance obj int or is instance obj float or is instance obj bool or is instance obj str or is instance obj ty... | import re
import inspect
import types
def is_function(obj) -> bool:
return (
is_method(obj)
or inspect.isfunction(obj)
or isinstance(obj, types.MethodWrapperType)
)
def is_primitive(obj) -> bool:
return (
isinstance(obj, int)
or isinstance(obj, float)
or i... | Python | zaydzuhri_stack_edu_python |
string BFS T: O(N) S: O(N) Success! Your code took 3 milliseconds — faster than 99.01% in Python
class Solution
begin
function solve self rooms
begin
set N = length rooms
set seen = set list 0
set q = deque list 0
while q
begin
set r0 = call popleft
for r in rooms at r0
begin
if r not in seen
begin
append q r
add seen ... | '''
BFS
T: O(N)
S: O(N)
Success!
Your code took 3 milliseconds — faster than 99.01% in Python
'''
class Solution:
def solve(self, rooms):
N = len(rooms)
seen = set([0])
q = deque([0])
while q:
r0 = q.popleft()
for r in rooms[r0]:
if r not in ... | Python | zaydzuhri_stack_edu_python |
comment dictionary -> class
set D = dict string course string python ; string dur 10 ; string loc string Blr
print D
print D at string course
comment Dictionary are unordered
comment add or update
set D at string course = list string c++ string java
print D
set E = copy D
comment remove from a dictionary
set r1 = pop D... | #dictionary -> class
D = { 'course' : 'python', 'dur':10, 'loc':'Blr'}
print(D)
print(D['course'])
# Dictionary are unordered
#add or update
D['course'] = ['c++', 'java']
print(D)
E = D.copy()
#remove from a dictionary
r1 = D.pop('course')
print('pop =', r1, D)
del D['dur']
print('After del =', D)
r... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
pass
end function | def __init__(self):
pass | Python | nomic_cornstack_python_v1 |
function calcul nb_part
begin
set nb_grp = 16 // integer nb_part
return nb_grp
end function | def calcul(nb_part):
nb_grp = 16 // int(nb_part)
return nb_grp | Python | nomic_cornstack_python_v1 |
import time
set link = string http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/
function test_guest_should_see_add_to_basket_button browser
begin
get browser link
comment time.sleep(30)
assert length call find_elements_by_class_name string btn-add-to-basket == 1 msg string Unable to locate element or ... | import time
link = "http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/"
def test_guest_should_see_add_to_basket_button(browser):
browser.get(link)
#time.sleep(30)
assert len(browser.find_elements_by_class_name("btn-add-to-basket")) == 1, "Unable to locate element or selector is n... | Python | zaydzuhri_stack_edu_python |
string bhch11exrc05.py: Repeatedly ask the user to enter a team name and the how many games the team won and how many they lost. Store this information in a dictionary where the keys are the team names and the values are lists of the form [wins, losses]. (a) Using the dictionary created above, allow the user to enter a... | """
bhch11exrc05.py: Repeatedly ask the user to enter a team name and the how many games the team won and how many they lost. Store this information in a dictionary where the keys are the team names and the values are lists of the form [wins, losses].
(a) Using the dictionary created above, allow the user to enter a ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
import math
import sys
import time
import kuimaze
class Node
begin
string Search node class g(n) is path cost from start node to the (current node) n (the cost to reach the node n) h(n) estimated cost of the cheapest path from the state at node n to a goal state f(n) = g(n) + h(n) estimated co... | #!/usr/bin/python3
import math
import sys
import time
import kuimaze
class Node:
"""
Search node class
g(n) is path cost from start node to the (current node) n (the cost to reach the node n)
h(n) estimated cost of the cheapest path from the state at node n to a goal state
f(n) =... | Python | zaydzuhri_stack_edu_python |
function test_no_claims self monkeypatch
begin
set app = call Flask __name__
set config at string FOCA = call Config
set attribute string jwt.decode lambda -> dict
with call app_context
begin
with raises Unauthorized
begin
call validate_token token=MOCK_TOKEN_INVALID
end
end
end function | def test_no_claims(self, monkeypatch):
app = Flask(__name__)
app.config['FOCA'] = Config()
monkeypatch.setattr(
'jwt.decode',
lambda *args, **kwargs: {},
)
with app.app_context():
with pytest.raises(Unauthorized):
validate_token... | Python | nomic_cornstack_python_v1 |
comment parse-sld.py
comment This script takes in an SLD file, and converts its output to MapServer
comment CLASS expressions. It understands the topographic SLD files from the
comment OSMM-Topography-Layer-stylesheets repository.
import sys
from lxml import objectify
set line_class = string CLASS EXPRESSION "%(express... | # parse-sld.py
#
# This script takes in an SLD file, and converts its output to MapServer
# CLASS expressions. It understands the topographic SLD files from the
# OSMM-Topography-Layer-stylesheets repository.
import sys
from lxml import objectify
line_class = '''
CLASS
EXPRESSION "%(expression)s"
STYLE
COLOR ... | Python | zaydzuhri_stack_edu_python |
import random
import math
class Node
begin
function __init__ self val
begin
set data = val
set left = none
set right = none
set parent = none
set int = none
set maxIdentical = false
set identical = false
set equivalent = false
set rep = string
end function
function __str__ self
begin
return format string Node {self.da... | import random
import math
class Node:
def __init__(self, val):
self.data = val
self.left = None
self.right = None
self.parent = None
self.int = None
self.maxIdentical = False
self.identical = False
self.equivalent = False
self.rep = ""
def __str__(self):
return 'Nod... | Python | zaydzuhri_stack_edu_python |
function new_labeled_email self context payload
begin
set access_token = call get_access_token context at string headers
set url = call get_url context + string messages/ { payload at string id }
set response = call rest string GET url access_token
return call get_email_data loads text
end function | def new_labeled_email(self, context, payload):
access_token = util.get_access_token(context['headers'])
url = util.get_url(context) + f"messages/{payload['id']}"
response = util.rest("GET", url, access_token)
return GmailApi.get_email_data(json.loads(response.text)) | Python | nomic_cornstack_python_v1 |
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
class TestMusic
begin
function setup self
begin
set driver = call Chrome
call maximize_window
call implicitly_wait 5
end function
function teardown self
begin
call ... | from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
class TestMusic:
def setup(self):
self.driver = webdriver.Chrome()
self.driver.maximize_window()
self.driver.implicitly_wait(5)
... | Python | zaydzuhri_stack_edu_python |
with open string corpus.utf as f
begin
set corpus = read lines f
end
for line in corpus
begin
for c in line
begin
if c not in hiragana and c not in katakana and c not in english and c not in greek and c not in numbers and c not in punctuation
begin
add kanji c
end
end
end
for line in corpus
begin
set word = string
set... | with open("corpus.utf") as f:
corpus = f.readlines()
for line in corpus:
for c in line:
if c not in hiragana and c not in katakana and c not in english and c not in greek and c not in numbers and c not in punctuation:
kanji.add(c)
for line in corpus:
word = ""
last = ""
for c i... | Python | zaydzuhri_stack_edu_python |
comment formFiller.py - fills in a form like:
comment autbor.com/form
comment If running as-is, will take a screenshot
import pyautogui , time
comment Set for each computer
set nameField = tuple 648 319
set submitButton = tuple 651 817
set submitButtonColor = tuple 75 141 249
set submitAnotherLink = tuple 760 224
set f... | # formFiller.py - fills in a form like:
# autbor.com/form
# If running as-is, will take a screenshot
import pyautogui, time
# Set for each computer
nameField = (648, 319)
submitButton = (651, 817)
submitButtonColor = (75, 141, 249)
submitAnotherLink = (760, 224)
formData = [{'name': 'Alice', 'fear': 'eavesdroppers'... | Python | zaydzuhri_stack_edu_python |
from keras.callbacks import ModelCheckpoint , EarlyStopping , TensorBoard
from time import time
import pickle
from model_improve import triplet_loss_embedding_graph
from data_generator import Data_generator
from Val_accuracy import val_accuracy
comment import tensorflow as tf
comment run_options = tf.RunOptions(report_... | from keras.callbacks import ModelCheckpoint, EarlyStopping, TensorBoard
from time import time
import pickle
from model_improve import triplet_loss_embedding_graph
from data_generator import Data_generator
from Val_accuracy import val_accuracy
#import tensorflow as tf
#run_options = tf.RunOptions(report_tensor_alloca... | Python | zaydzuhri_stack_edu_python |
function test_ignored_inputs_outputs self ignores
begin
set tuple recipyrc_key log_key = ignores
set recipyrc = call get_recipyrc
call execute_python list script input_file output_file
set tuple log _ = call get_log call get_recipydb
assert length log at log_key > 0 msg string Expected functions to be logged
call updat... | def test_ignored_inputs_outputs(self, ignores):
(recipyrc_key, log_key) = ignores
recipyrc = recipyenv.get_recipyrc()
helpers.execute_python([self.script, self.input_file,
self.output_file])
log, _ = helpers.get_log(recipyenv.get_recipydb())
assert... | Python | nomic_cornstack_python_v1 |
import re
import json
from db_interactions.get_issues_by_userid import get_issues_by_userid , get_issues_by_uid_and_status
from fb_api_interactions.respond_message import respond_message
from db_interactions.save_message import save_message
from datetime import datetime
from django.utils.timezone import make_aware
from... | import re
import json
from ..db_interactions.get_issues_by_userid import get_issues_by_userid, get_issues_by_uid_and_status
from ..fb_api_interactions.respond_message import respond_message
from ..db_interactions.save_message import save_message
from datetime import datetime
from django.utils.timezone import make_awa... | Python | zaydzuhri_stack_edu_python |
function _get_platform_name ncattr
begin
string Determine name of the platform
set match = match string G-(\d+) ncattr
if match
begin
return get SPACECRAFTS integer call groups at 0
end
return none
end function | def _get_platform_name(ncattr):
"""Determine name of the platform"""
match = re.match(r'G-(\d+)', ncattr)
if match:
return SPACECRAFTS.get(int(match.groups()[0]))
return None | Python | jtatman_500k |
import db_access
import db_change
set values = dict string first_name string John ; string last_name string Doe ; string email string abc@k.e ; string store_id 20 ; string address_id 30
set resp = call new_customer values
if resp at 0 == string K
begin
set id = resp at 1
print string response resp
set cust = call get_c... | import db_access
import db_change
values = {
'first_name': 'John', 'last_name': 'Doe', 'email': 'abc@k.e',
'store_id': 20, 'address_id': 30,
}
resp = db_change.new_customer(values)
if resp[0] == 'K':
id = resp[1]
print("response", resp)
cust = db_access.get_customer_by_id(id)
... | Python | zaydzuhri_stack_edu_python |
import argparse
import os
from engines.vulnerability.cve import CVE
from tools.loghandler import *
from tools.configfile import *
from tools.database import *
from tools.emails import *
from tools.telegram import Telegram
class VulnAlert
begin
function __init__ self
begin
set parser = call ArgumentParser prog=string Vu... | import argparse
import os
from engines.vulnerability.cve import CVE
from tools.loghandler import *
from tools.configfile import *
from tools.database import *
from tools.emails import *
from tools.telegram import Telegram
class VulnAlert:
def __init__(self):
parser = argparse.ArgumentParser(
... | Python | zaydzuhri_stack_edu_python |
import os
function gradingStudents grades
begin
return map lambda x -> if expression x < 38 or x % 5 < 3 then x else if expression x % 5 == 4 then x + 1 else x + 2 grades
end function
if __name__ == string __main__
begin
set f = open environ at string OUTPUT_PATH string w
set n = integer input
set grades = list
for _ ... | import os
def gradingStudents(grades):
return map(lambda x: x if x < 38 or x % 5 < 3 else x + 1 if x % 5 == 4 else x + 2, grades)
if __name__ == '__main__':
f = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
grades = []
for _ in range(n):
grades_item = int(input())
grad... | Python | zaydzuhri_stack_edu_python |
set name = input string hello, what is your name?
print string hi { name } . lets start.
print
set holiday = input string enter a name of a holiday:
set place = input string enter a place:
set hero = input string give me a hero:
set outfit = input string wat do you want to where:
set bad_guy = input string enter a bad ... | name = input ("hello, what is your name?")
print (f"hi {name}. lets start." )
print()
holiday = input ("enter a name of a holiday:" )
place = input("enter a place:")
hero = input("give me a hero:")
outfit= input("wat do you want to where:")
bad_guy= input("enter a bad guy:")
power = input("what power do you want:")
n... | Python | zaydzuhri_stack_edu_python |
import math
function f x
begin
return x ^ 5 - 4 * x ^ 2 + 2
end function
function bissecao f a b eps
begin
if f dist a * f dist b > 0
begin
return string Nenhuma raiz: os valores da função no estado inicial devem ser um sinal oposto.
end
else
begin
comment print("n", " a", " b", " m", " f(a)*f(m)", "|dx/2|")
while true... | import math
def f(x):
return x**5 - 4*(x**2) + 2
def bissecao(f,a,b,eps):
if f(a) * f(b) > 0:
return ("Nenhuma raiz: os valores da função no estado inicial devem ser um sinal oposto.")
else:
#print("n", " a", " b", " m", " f(a)*f(m)", "|dx/2|")
while True:
x = (... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python
from __future__ import print_function
import datetime
import csv
import io
import os.path
import pickle
from os import path
class Bin
begin
function __init__ self bin_num=0
begin
set cap = 500
set cards = list
set bin_num = bin_num
set now = string format time now string %Y-%m-%d-%H-%M
set... | #! /usr/bin/env python
from __future__ import print_function
import datetime
import csv
import io
import os.path
import pickle
from os import path
class Bin:
def __init__(self, bin_num=0):
self.cap = 500
self.cards = list()
self.bin_num = bin_num
self.now = datetime.datetime.now().... | Python | zaydzuhri_stack_edu_python |
function create_user
begin
set post_body = loads data
if string text not in post_body or string username not in post_body
begin
return tuple dumps dict string success false ; string error string Needs text or username 404
end
set user = call User id=user_id username=post_body at string username
comment g_user = post_da... | def create_user():
post_body = json.loads(request.data)
if 'text' not in post_body or 'username' not in post_body:
return json.dumps({'success': False, 'error': 'Needs text or username'}), 404
user = User(
id=user_id,
username=post_body['username'],
#g_user = post_data['gid']... | Python | nomic_cornstack_python_v1 |
function ot_alice socket msgs
begin
comment Create the prime group and send it to Bob
set G = call PrimeGroup
call send_wait G
comment OT protocol based on
comment Nigel Smart’s "Cryptography Made Simple" implementation
set c = call gen_pow call rand_int
set h0 = call send_wait c
set h1 = call mul c call inv h0
set k =... | def ot_alice(socket, msgs):
# Create the prime group and send it to Bob
G = util.PrimeGroup()
socket.send_wait(G)
# OT protocol based on
# Nigel Smart’s "Cryptography Made Simple" implementation
c = G.gen_pow(G.rand_int())
h0 = socket.send_wait(c)
h1 = G... | Python | nomic_cornstack_python_v1 |
function nth_qasmline self n
begin
return if expression n < length qasmsourcelines then qasmsourcelines at n else none
end function | def nth_qasmline(self, n):
return self.qasmsourcelines[n] if n < len(self.qasmsourcelines) else None | Python | nomic_cornstack_python_v1 |
set numbers = list 3 5 7 9 11
set result = list
for num in numbers
begin
comment Exclude numbers divisible by 2
if num % 2 != 0
begin
append result num
end
end
print result | numbers = [3, 5, 7, 9, 11]
result = []
for num in numbers:
if num % 2 != 0: # Exclude numbers divisible by 2
result.append(num)
print(result)
| Python | jtatman_500k |
function longest_substring string k
begin
set tuple start distinct max_length = tuple 0 0 0
set frequency = dict
for end in range length string
begin
set frequency at string at end = get frequency string at end 0 + 1
if frequency at string at end == 1
begin
set distinct = distinct + 1
end
while distinct > k
begin
set ... | def longest_substring(string, k):
start, distinct, max_length = 0, 0, 0
frequency = {}
for end in range(len(string)):
frequency[string[end]] = frequency.get(string[end], 0) + 1
if frequency[string[end]] == 1:
distinct += 1
while distinct > k:
frequency[strin... | Python | iamtarun_python_18k_alpaca |
function vectorized_gaussian_variable_mutation population std=1.0
begin
return population + reshape call rvs size=product shape scale=std shape
end function | def vectorized_gaussian_variable_mutation(population: np.array, std: float = 1.0) -> np.array:
return population + stats.norm.rvs(size=np.product(population.shape), scale=std).reshape(population.shape) | Python | nomic_cornstack_python_v1 |
function perform_inference test_loader model cfg
begin
comment Enable eval mode.
eval
set feat_arr = none
for inputs in call tqdm test_loader
begin
comment Transfer the data to the current GPU device.
if is instance inputs tuple list
begin
for i in range length inputs
begin
set inputs at i = cuda inputs at i non_blocki... | def perform_inference(test_loader, model, cfg):
# Enable eval mode.
model.eval()
feat_arr = None
for inputs in tqdm(test_loader):
# Transfer the data to the current GPU device.
if isinstance(inputs, (list,)):
for i in range(len(inputs)):
inputs[i] = inputs[i... | Python | nomic_cornstack_python_v1 |
import random
set board = list string * 10
set game_state = true
set announce = string
function display_board
begin
print board at 7 + string | + board at 8 + string | + board at 9
print string -----
print board at 4 + string | + board at 5 + string | + board at 6
print string -----
print board at 1 + string | + boar... | import random
board = [' ']*10
game_state = True
announce = ''
def display_board():
print(board[7] + '|' + board[8] + '|' + board[9])
print('-----')
print(board[4] + '|' + board[5] + '|' + board[6])
print('-----')
print(board[1] + '|' + board[2] + '|' + board[3])
def player_input():
"""
O... | Python | zaydzuhri_stack_edu_python |
import random
import copy
set HIDDEN = 0
set MOTOR = 1
set SENSOR = 2
class Synapse extends object
begin
function __init__ self to_ID from_ID weight
begin
set to_ID = to_ID
set from_ID = from_ID
set weight = weight
end function
function Mutate self sigma=- 1
begin
if sigma <= 0
begin
set sigma = weight
if sigma < 0.05
... | import random
import copy
HIDDEN = 0
MOTOR = 1
SENSOR = 2
class Synapse(object):
def __init__(self,to_ID,from_ID,weight):
self.to_ID = to_ID
self.from_ID = from_ID
self.weight = weight
def Mutate(self,sigma=-1):
if sigma<=0:
sigma = self.weight
if sigma<0.05:
sigma = 0.05
self.weight = self.w... | Python | zaydzuhri_stack_edu_python |
from sklearn.cluster import KMeans
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
import matplotlib.pyplot as plt
comment import seaborn as sns
comment sns.set(style="white", color_codes=True)
import warnings
filter warnings string ignore
set train = read csv string CC.csv
comment... | from sklearn.cluster import KMeans
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
import matplotlib.pyplot as plt
#import seaborn as sns
#sns.set(style="white", color_codes=True)
import warnings
warnings.filterwarnings("ignore")
train = pd.read_csv('CC.csv')
#print(pd.... | Python | zaydzuhri_stack_edu_python |
function writeVTKBlock self fname=string turbulence_box.vtk outputdir=none step=1 scaled=true
begin
if outputdir is none
begin
set outputdir = string .
end
else
if not is directory path outputdir
begin
print string Creating output dir : outputdir
make directories outputdir
end
set fname = join path outputdir fname
prin... | def writeVTKBlock(self,
fname='turbulence_box.vtk',
outputdir=None,
step=1,
scaled=True):
if outputdir is None:
outputdir = '.'
elif not os.path.isdir(outputdir):
print('Creating output dir :',outputdir)
os.makedirs(outp... | Python | nomic_cornstack_python_v1 |
function repeat_string num string boolean arr
begin
if boolean
begin
set repeated_string = list string * num
set lengths = list length string * num
extend arr repeated_string + lengths
end
return arr
end function | def repeat_string(num, string, boolean, arr):
if boolean:
repeated_string = [string] * num
lengths = [len(string)] * num
arr.extend(repeated_string + lengths)
return arr
| Python | jtatman_500k |
comment -*- coding: utf-8 -*-
string Created on Sat Oct 20 10:47:06 2018 @author: Una
import numpy as np
import matplotlib.pyplot as plt
from proj1_helpers import *
from lib_dataPreprocessing import *
from lib_MLmodels import *
comment PARAMETERS THAT ARE NEEDED AT SOME POINT FOR THIS FUNCTIONS
comment best to specify ... | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 20 10:47:06 2018
@author: Una
"""
import numpy as np
import matplotlib.pyplot as plt
from proj1_helpers import *
from lib_dataPreprocessing import *
from lib_MLmodels import *
# PARAMETERS THAT ARE NEEDED AT SOME POINT FOR THIS FUNCTIONS
# best to specify them at the b... | Python | zaydzuhri_stack_edu_python |
string algorithm - find the
import requests
import pandas as pd
from bs4 import BeautifulSoup
class CMC extends object
begin
string docstring for CMC
function __init__ self
begin
set cmc_url = string https://coinmarketcap.com/
set cmc_html = string C:\Users\TAN\Desktop\Cryptocurrency Market Capitalizations _ CoinMarket... | """
algorithm
- find the
"""
import requests
import pandas as pd
from bs4 import BeautifulSoup
class CMC(object):
"""docstring for CMC"""
def __init__(self):
cmc_url = "https://coinmarketcap.com/"
cmc_html = r"C:\Users\TAN\Desktop\Cryptocurrency Market Capitalizations _ CoinMarketCap.html"
cmc_page = requ... | 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.