code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function _query self msg size=- 1
begin
return call ask msg num=size
end function | def _query(self, msg, size=-1):
return self._inst.ask(msg, num=size) | Python | nomic_cornstack_python_v1 |
function seek self n
begin
string Gets to a certain marker position in the BED file. Args: n (int): The index of the marker to seek to.
if _mode != string r
begin
raise call UnsupportedOperation string not available in 'w' mode
end
if 0 <= n < _nb_markers
begin
set _n = n
seek _bed call _get_seek_position n
end
else
be... | def seek(self, n):
"""Gets to a certain marker position in the BED file.
Args:
n (int): The index of the marker to seek to.
"""
if self._mode != "r":
raise UnsupportedOperation("not available in 'w' mode")
if 0 <= n < self._nb_markers:
self.... | Python | jtatman_500k |
function extract_close_keywords keywords tokenized_string minDistance
begin
set closeWords = list
for keyword in keywords
begin
set keywordSyn = call synset keyword
for word in tokenized_string
begin
for wordSyn in call synsets word
begin
set distance = call shortest_path_distance wordSyn
if distance != none and dista... | def extract_close_keywords(keywords, tokenized_string, minDistance):
closeWords = []
for keyword in keywords:
keywordSyn = wordnet.synset(keyword)
for word in tokenized_string:
for wordSyn in wordnet.synsets(word):
distance = keywordSyn.shortest_path_distance(wordSyn)... | Python | nomic_cornstack_python_v1 |
function testOpen
begin
comment load net
set net = call loadNet model_path
comment output feature
set feature = true
set predicts = list
set ground_truth = list
set threshold = 0.25
with open string ../data/test/open_landmark.txt string r as f
begin
set landmark_lines = read lines f
end
set landmark_lines = array lis... | def testOpen():
# load net
net = loadNet(args.model_path)
# output feature
net.feature = True
predicts = []
ground_truth = []
threshold = 0.25
with open('../data/test/open_landmark.txt', 'r') as f:
landmark_lines = f.readlines()
landmark_lines = np.array([ l[:-1].split('\t... | Python | nomic_cornstack_python_v1 |
function test_aromatics self
begin
set mol1 = call from_adjacency_list string 1 O u0 p2 c0 {6,S} {9,S} 2 C u0 p0 c0 {3,D} {5,S} {11,S} 3 C u0 p0 c0 {2,D} {4,S} {12,S} 4 C u0 p0 c0 {3,S} {6,D} {13,S} 5 C u0 p0 c0 {2,S} {7,D} {10,S} 6 C u0 p0 c0 {1,S} {4,D} {7,S} 7 C u0 p0 c0 {5,D} {6,S} {8,S} 8 C u0 p0 c0 {7,S} {14,S} {... | def test_aromatics(self):
mol1 = Molecule().from_adjacency_list("""
1 O u0 p2 c0 {6,S} {9,S}
2 C u0 p0 c0 {3,D} {5,S} {11,S}
3 C u0 p0 c0 {2,D} {4,S} {12,S}
4 C u0 p0 c0 {3,S} {6,D} {13,S}
5 C u0 p0 c0 {2,S} {7,D} {10,S}
6 C u0 p0 c0 {1,S} {4,D} {7,S}
7 C u0 p0 c0 {5,D} {6,S} {8,S}
8 C u0 p0 c0 {7,S} {1... | Python | nomic_cornstack_python_v1 |
comment New Bird Watcher IoT Client
comment Date: March 22nd 2020
comment Author: Marek Tyrpa
comment This program will attempt to identify 12 common species of birds in the
comment US Midwest, and will send a positive ID to the BirdwatcherBackEnd API.
comment It is implemented using Tensorflow.
comment The framework i... | #######################################################
# New Bird Watcher IoT Client
# Date: March 22nd 2020
# Author: Marek Tyrpa
#
# This program will attempt to identify 12 common species of birds in the
# US Midwest, and will send a positive ID to the BirdwatcherBackEnd API.
# It is implemented using Tensorflow.
... | Python | zaydzuhri_stack_edu_python |
from graphics import *
import math
set clr1 = string red
set clr2 = string green
set f = open string file.txt string r
set c = integer read line f
set vertex1 = list
set vertex2 = list
for i in range c
begin
set number_string = split read line f string
set number_Array = list comprehension integer i for i in number_s... | from graphics import *
import math
clr1="red"
clr2="green"
f=open("file.txt","r")
c=int(f.readline())
vertex1=[]
vertex2=[]
for i in range(c):
number_string=f.readline().split(' ')
number_Array=[int(i) for i in number_string]
point=[]
point.append(number_Array[0])
point.append(number_Ar... | Python | zaydzuhri_stack_edu_python |
function write_end fname
begin
with open fname string a as f
begin
write f string } + linesep
end
end function | def write_end(fname):
with open(fname, 'a') as f:
f.write("}" + os.linesep) | Python | nomic_cornstack_python_v1 |
comment Question 1
set naira = 200
set dollar = naira * 30
print dollar
comment Question 2
set x = 7
set G = 2 * x ^ 3 - 4 * x
print G | #Question 1
naira = 200
dollar = naira *30
print(dollar)
#Question 2
x = 7
G = 2*(x**3) - 4*x
print(G)
| Python | zaydzuhri_stack_edu_python |
from pylab import *
import numpy as np
comment Enter your values. Example:
set x = array list 3 4 5 6 7
set y = array list 13.6 12 11.2 10 9.6
set A = array list list 5 25 135 list 25 135 775 list 135 775 4659
set b = array list 56.4 272 1424.8
print call solve A b
set m = T
set s = call lstsq m y rcond=1 at 0
set x_ =... | from pylab import *
import numpy as np
# Enter your values. Example:
x = np.array([3, 4, 5, 6, 7])
y = np.array([13.6, 12, 11.2, 10, 9.6])
A = np.array([[5, 25, 135], [25, 135, 775], [135, 775, 4659]])
b = np.array([56.4, 272, 1424.8])
print(np.linalg.solve(A, b))
m = vstack((x**2, x, ones(len(x)))).T
s = lstsq(m, ... | Python | zaydzuhri_stack_edu_python |
from Lab2.functions import *
if __name__ == string __main__
begin
print string Лабораторная работа №3, вариант #14
set a = 0
set b = 10
set eps = 10 ^ - 4
print string a = + string a
print string b = + string b
print string Точность = + string eps
print string Первое задание ---------
set h = call define_step a b eps
p... | from Lab2.functions import *
if __name__ == "__main__":
print("Лабораторная работа №3, вариант #14")
a = 0
b = 10
eps = 10 ** (-4)
print("a = " + str(a))
print("b = " + str(b))
print("Точность = " + str(eps))
print("Первое задание ---------")
h = define_step(a, b, eps)
print("Ш... | Python | zaydzuhri_stack_edu_python |
string THIS ALGORITHM WITHIN THE TRIAL-BASED HEURISTIC TREE-SEARCH METHOD FRAMEWORK HEURISTIC: Rollout legacy from plain UCT ACTION SELECTION STRATEGY: enhanced UCB with adaptive exploration coefficient based on entropy. 3 different options are provided BACK-UP : classical Monte Carlo planning OUTCOME SELECTION : succe... | """
THIS ALGORITHM WITHIN THE TRIAL-BASED HEURISTIC TREE-SEARCH METHOD FRAMEWORK
HEURISTIC: Rollout legacy from plain UCT
ACTION SELECTION STRATEGY: enhanced UCB with adaptive exploration coefficient
based on entropy. 3 different options are provided
BACK-UP : classical Monte Carlo pl... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
function main
begin
set N = integer input
set H = list map int split input
set ans = 0
set tmp = 0
set tmp_h = H at 0
for i in range 1 N
begin
if H at i <= tmp_h
begin
set tmp = tmp + 1
end
else
begin
set ans = max ans tmp
set tmp = 0
end
set tmp_h = H at i
end
set ans = max ans tmp
print ans
end ... | # coding: utf-8
def main():
N = int(input())
H = list(map(int, input().split()))
ans = 0
tmp = 0
tmp_h = H[0]
for i in range(1, N):
if H[i] <= tmp_h:
tmp += 1
else :
ans = max(ans, tmp)
tmp = 0
tmp_h = H[i]
ans = max(ans, tmp)
... | Python | zaydzuhri_stack_edu_python |
function predict self X clf
begin
set y_pred = call predict_classes X batch_size=32
return y_pred
end function | def predict(self, X, clf):
y_pred = clf.predict_classes(X, batch_size = 32)
return y_pred | Python | nomic_cornstack_python_v1 |
function _process_non_state_changed_event_into_session self event
begin
set session = event_session
assert session is not none
set dbevent = call from_event event
comment Map the event_type to the EventTypes table
set event_type_manager = event_type_manager
if pending_event_types := call get_pending event_type
begin
se... | def _process_non_state_changed_event_into_session(self, event: Event) -> None:
session = self.event_session
assert session is not None
dbevent = Events.from_event(event)
# Map the event_type to the EventTypes table
event_type_manager = self.event_type_manager
if pending_... | Python | nomic_cornstack_python_v1 |
function eig_vals self
begin
return exp - 1 / dis_param * call sorted_eigvalsh rate_matrix
end function | def eig_vals(self):
return exp(-1/self.dis_param)*sparsedl.sorted_eigvalsh(self.rate_matrix) | Python | nomic_cornstack_python_v1 |
function logging_in request
begin
set username = POST at string username
set password = POST at string password
if username == string or password == string
begin
return call render request string landing/login.html
end
set user = call authenticate request username=username password=password
print user
if user is not ... | def logging_in(request):
username = request.POST['username']
password = request.POST['password']
if username == '' or password == '':
return render(request,'landing/login.html')
user = authenticate(request, username=username, password=password)
print(user)
if user is not None:
... | Python | nomic_cornstack_python_v1 |
function home self
begin
set angle = call Q_ 0 string degrees
end function | def home(self):
rot.angle = Q_(0, 'degrees') | Python | nomic_cornstack_python_v1 |
for i in range 1 21
begin
if i % 2 == 1
begin
if i == 13
begin
print string Unlicky
end
else
begin
print string Odd Number
end
end
else
if i % 2 == 0
begin
if i == 4
begin
print string Unlicky
end
else
begin
print string Even Number
end
end
end | for i in range(1,21):
if i%2==1:
if i==13:
print("Unlicky")
else:
print("Odd Number")
elif i%2==0:
if i==4:
print("Unlicky")
else:
print("Even Number") | Python | zaydzuhri_stack_edu_python |
function draw_word_map prob_predict countries output_file=string word_map.svg
begin
set worldmap_chart = call World
set title = string World Map
set accending = dict
set descending = dict
for tuple prob country in zip prob_predict countries
begin
set country_code = call get_country_code country
if not country_code
be... | def draw_word_map(prob_predict: List[float], countries: List[str], output_file: str = 'word_map.svg'):
worldmap_chart = World()
worldmap_chart.title = 'World Map'
accending = {}
descending = {}
for prob, country in zip(prob_predict, countries):
country_code = get_country_code(country)
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import pdb
import pickle
function myFunc e
begin
return e at string score
end function
set filename = string NUCLE_List.txt
set lstBigram = list
with open filename string r as f
begin
for line_of_text in f
begin
comment remove the last '\n' and split by '\t'
set tokens = split line_of_tex... | # -*- coding: utf-8 -*-
import pdb
import pickle
def myFunc(e):
return e['score']
filename='NUCLE_List.txt'
lstBigram=[]
with open(filename,'r') as f:
for line_of_text in f:
tokens=line_of_text[:-1].split('\t') # remove the last '\n' and split by '\t'
strBigram=tokens[0]+' '+tokens... | Python | zaydzuhri_stack_edu_python |
function find_parent_class fpath funcname lineno readlines=none
begin
if readlines is none
begin
function readlines fpath
begin
return call readfrom fpath aslines=true
end function
end
try
begin
set line_list = read lines fpath
set row = integer lineno - 1
set funcline = line_list at row
set indent = length funcline - ... | def find_parent_class(fpath, funcname, lineno, readlines=None):
if readlines is None:
def readlines(fpath):
return ub.readfrom(fpath, aslines=True)
try:
line_list = readlines(fpath)
row = int(lineno) - 1
funcline = line_list[row]
indent = len(funcline) - len(... | Python | nomic_cornstack_python_v1 |
function get_mask_image self optional_image=none
begin
comment type: (np.array) -> np.array
if optional_image is not none
begin
comment Mask of optional image
set mask = call _mask_image optional_image
end
else
begin
comment Mask of default cached image
if _mask is none or not _caching
begin
set _mask = call _mask_imag... | def get_mask_image(self, optional_image=None):
# type: (np.array) -> np.array
if optional_image is not None:
# Mask of optional image
mask = self._mask_image(optional_image)
else:
# Mask of default cached image
if self._mask is None or not self._ca... | Python | nomic_cornstack_python_v1 |
import unittest
import sure
from models.user import User
class TestUser extends TestCase
begin
function test_for_default_properties self
begin
set user = call User 1 string Matheus string Sampaio rating=3.0
call equal 1
call equal string Matheus
call equal string Sampaio
call equal 3.0
true
true
end function
function t... | import unittest
import sure
from models.user import User
class TestUser(unittest.TestCase):
def test_for_default_properties(self):
user = User(1, "Matheus", "Sampaio", rating=3.0)
user.uid.should.be.equal(1)
user.first_name.should.be.equal("Matheus")
user.last_name.should.be.equal... | Python | zaydzuhri_stack_edu_python |
function _load_model self
begin
set model = call load_model call __get_model_path custom_objects=dict string KerasLayer KerasLayer
info string Successfully Loaded model
return model
end function | def _load_model(self):
model = tf.keras.models.load_model(self.__get_model_path(), custom_objects={
"KerasLayer": hub.KerasLayer})
Logger.info(f"Successfully Loaded model")
return model | Python | nomic_cornstack_python_v1 |
class BinaryTreeNode
begin
function __init__ self data
begin
set data = data
set left = none
set right = none
end function
end class
function printTreeDetailed root
begin
if root == none
begin
return
end
print data end=string :
if left != none
begin
print string L data end=string ,
end
if right != none
begin
print stri... | class BinaryTreeNode:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
def printTreeDetailed(root):
if root == None:
return
print(root.data,end=":")
if root.left !=None:
print("L",root.left.data, end=",")
if root.right !=None:
... | Python | zaydzuhri_stack_edu_python |
function clean_branches self
begin
set git = which string git
for branch in call collect string branch --merged | grep -v '*' | grep -v master
begin
call git string branch -d %s % branch
end
end function | def clean_branches(self):
git = which("git")
for branch in git.collect("branch --merged | grep -v '*' | grep -v master"):
git("branch -d %s" % branch) | Python | nomic_cornstack_python_v1 |
function test_config_true self
begin
call pyscript_run string <py-config> terminal = true </py-config> <py-script> print('hello world') </py-script>
set term = call locator string py-terminal
call to_be_visible
assert call inner_text == string hello world
end function | def test_config_true(self):
self.pyscript_run(
"""
<py-config>
terminal = true
</py-config>
<py-script>
print('hello world')
</py-script>
"""
)
term = self.page.locator("py-terminal")
... | Python | nomic_cornstack_python_v1 |
if data at 0 == data at 1 and data at 0 == data at 1 != 0
begin
print string Even { data at 0 * 2 }
end
else
if data at 0 == data at 1 == 0
begin
print string Not a moose
end
else
begin
print string Odd max data * 2
end | if data[0]==data[1] and data[0]==data[1]!=0:
print(F"Even {data[0]*2}")
elif data[0]==data[1]==0:
print("Not a moose")
else:
print("Odd",max(data)*2)
| Python | zaydzuhri_stack_edu_python |
string Creates a list of sequentially named folders. Prompts the user to select a destionation folder under which to create sub-folders, as well as the number of sub-folders to create and the suffixes for the folder names.
import os
import tkinter as tk
from tkinter import filedialog , simpledialog
set application_wind... | """
Creates a list of sequentially named folders.
Prompts the user to select a destionation folder under which to create sub-folders,
as well as the number of sub-folders to create and the suffixes for the folder names.
"""
import os
import tkinter as tk
from tkinter import filedialog, simpledialog
applicat... | Python | zaydzuhri_stack_edu_python |
function shift_point_circ mutated_genome index
begin
set Xval = random integer - integer imagewidth * 0.1 integer imagewidth * 0.1
set Yval = random integer - integer imageheight * 0.1 integer imageheight * 0.1
set circle = mutated_genome at index at 2
set newcircle = tuple circle at 0 + Xval circle at 1 + Yval circle ... | def shift_point_circ(mutated_genome,index):
Xval = random.randint(-int(imagewidth*0.1),int(imagewidth*0.1))
Yval = random.randint(-int(imageheight*0.1),int(imageheight*0.1))
circle = mutated_genome[index][2]
newcircle = (circle[0]+Xval,circle[1]+Yval,circle[2])
mutated_genome[index][2] = newcircle | Python | nomic_cornstack_python_v1 |
string Convert single particle patterns into hdf5 format file. The structure of the output h5 file is as follows: 'data'(3d array): 3D data with shape (Np, Nx, Ny) where Np is the number of patters, and Nx, Ny are the size of first and second axis. 'labels'(list of int): classification results of the data with shape (N... | """
Convert single particle patterns into hdf5 format file. The structure of the output h5 file is as follows:
'data'(3d array):
3D data with shape (Np, Nx, Ny) where Np is the number of patters, and Nx, Ny are the size of first and second axis.
'labels'(list of int):
classification results of... | Python | zaydzuhri_stack_edu_python |
function deriv_intensity_wrt_transformation_rigid image_data translation rotation center_rotation sform=none use_gpu=1
begin
if sform is none
begin
set sform = call eye 4 dtype=float32
end
set descriptor = list dict string name string image_data ; string type string array ; string value image_data ; string dtype float3... | def deriv_intensity_wrt_transformation_rigid(image_data,translation,rotation,center_rotation,sform=None,use_gpu=1):
if sform is None:
sform=numpy.eye(4,dtype=float32)
descriptor = [{'name':'image_data', 'type':'array', 'value':image_data, 'dtype':float32},
{... | Python | nomic_cornstack_python_v1 |
function comp str1 str2
begin
set i = 0
set j = 0
set count = 0
while true
begin
set flag = 0
if str1 at i == str2 at j
begin
if i + 1 < length str1 and j + 1 < length str2
begin
set i = i + 1
set j = j + 1
set flag = 1
end
else
if i + 1 < length str1
begin
set i = i + 1
set count = count + 1
set flag = 1
end
else
if j... | def comp(str1, str2):
i = 0;
j = 0;
count = 0
while True:
flag = 0
if str1[i] == str2[j]:
if i+1<len(str1) and j+1<len(str2):
i += 1
j += 1
flag = 1
elif i+1 < len(str1):
i +=1
count +=1
flag =1
elif j+1 < len(str2):
j += 1
count += 1
flag = 1
else:
if str1[i]... | Python | zaydzuhri_stack_edu_python |
from collections import deque
class TreeNode
begin
function __init__ self left right value
begin
set left = left
set right = right
set value = value
end function
end class
function tnode value left=none right=none
begin
return call TreeNode left right value
end function
comment Calculates the depth of the tree
function... | from collections import deque
class TreeNode:
def __init__(self, left, right, value):
self.left = left
self.right = right
self.value = value
def tnode(value, left=None, right=None):
return TreeNode(left, right, value)
# Calculates the depth of the tree
def depth(node... | Python | zaydzuhri_stack_edu_python |
function get_admin_ids bot chat_id
begin
return list comprehension id for admin in call get_chat_administrators chat_id
end function | def get_admin_ids(bot, chat_id):
return [admin.user.id for admin in bot.get_chat_administrators(chat_id)] | Python | nomic_cornstack_python_v1 |
function get_variable self identifier
begin
if not has attribute self string __sdvcache
begin
set __sdvcache = dict
set buffer = string variables
set buffer = call StringIO buffer
set token = read buffer 1
while token
begin
if token == string $
begin
set variable = call __read_until buffer string =
set value = strip c... | def get_variable(self, identifier):
if not hasattr(self, "__sdvcache"):
self.__sdvcache = {}
buffer = str(self.obj.description_variables.variables)
buffer = StringIO(buffer)
token = buffer.read(1)
while token:
if token == "$":
variable = self.__read_until(buffer, "=")
value = self.__read_... | Python | nomic_cornstack_python_v1 |
class SampleName
begin
function __init__ self menuItemId number
begin
set menuItemId = menuItemId
set number = number
end function
decorator classmethod
function fromFilename cls filename
begin
set pieces : List at str = split filename string -
set menuItemId : int = integer pieces at 0
set number : int = integer split... | class SampleName:
def __init__(self, menuItemId: int, number: int):
self.menuItemId = menuItemId
self.number = number
@classmethod
def fromFilename(cls, filename: str):
pieces: List[str] = filename.split("-")
menuItemId: int = int(pieces[0])
number: int = int(pieces... | Python | zaydzuhri_stack_edu_python |
from random import randint
set tuple n m = map int split input
for i in range n
begin
print random integer 1 1000000001 end=string
end
print
for i in range m
begin
print random integer 1 1000000001 end=string
end | from random import randint
n, m = map(int, input().split())
for i in range(n):
print(randint(1,1000000001), end = " ")
print()
for i in range(m):
print(randint(1,1000000001), end = " ")
| Python | zaydzuhri_stack_edu_python |
function generate_token key user_id action_id=string when=none
begin
string Generates a URL-safe token for the given user, action, time tuple. Args: key: secret key to use. user_id: the user ID of the authenticated user. action_id: a string identifier of the action they requested authorization for. when: the time in s... | def generate_token(key, user_id, action_id='', when=None):
"""Generates a URL-safe token for the given user, action, time tuple.
Args:
key: secret key to use.
user_id: the user ID of the authenticated user.
action_id: a string identifier of the action they requested
a... | Python | jtatman_500k |
comment -*- coding: utf-8 -*-
string Created on Sat May 22 16:26:34 2021 @author: 이창현
function solution arr
begin
set i = index arr min arr
pop arr i
return arr or list - 1
end function
print call solution list 4 3 2 1
print call solution list 10 | # -*- coding: utf-8 -*-
"""
Created on Sat May 22 16:26:34 2021
@author: 이창현
"""
def solution(arr):
i = arr.index(min(arr))
arr.pop(i)
return arr or [-1]
print(solution([4,3,2,1]))
print(solution([10]))
| Python | zaydzuhri_stack_edu_python |
function __init__ self action_size buffer_size batch_size seed
begin
set action_size = action_size
set memory = deque maxlen=buffer_size
set batch_size = batch_size
set experience = named tuple string Experience field_names=list string state string action string reward string next_state string done
set seed = seed seed... | def __init__(self, action_size, buffer_size, batch_size, seed):
self.action_size = action_size
self.memory = deque(maxlen=buffer_size)
self.batch_size = batch_size
self.experience = namedtuple("Experience", field_names=["state", "action", "reward", "next_state", "done"])
self.s... | Python | nomic_cornstack_python_v1 |
function restart_savepoint session transaction
begin
if nested and not nested
begin
call begin_nested
end
end function | def restart_savepoint(session, transaction):
if transaction.nested and not transaction._parent.nested:
session.begin_nested() | Python | nomic_cornstack_python_v1 |
function nflleagueleaders self irc msg args optlist optcategory optstat optyear
begin
set statsCategories = dict string Passing dict string qbr string 49 ; string comp string 1 ; string att string 2 ; string comp% string 41 ; string yards string 4 ; string yards/gm string 42 ; string td string 5 ; string int string 3 ;... | def nflleagueleaders(self, irc, msg, args, optlist, optcategory, optstat, optyear):
statsCategories = {
'Passing': {
'qbr':'49',
'comp':'1',
'att':'2',
'comp%':'41',
'yards':'4',
... | Python | nomic_cornstack_python_v1 |
function _handleSelectAction self
begin
call setSelected true
call maybePrintTagsToStatusBar
end function | def _handleSelectAction(self):
self.setSelected(True)
self.maybePrintTagsToStatusBar() | Python | nomic_cornstack_python_v1 |
string M. Частоты А теперь помогите Васе решить задачу по информатике. Он снова томится дома в хорошую погоду. На вход подается строка длиной от 1 до 10000 символов. Нужно отсортировать её в порядке частот букв по встречаемости. Заглавные и строчные буквы считаются разными. Если частота одинаковая, нужно применить втор... | """
M. Частоты
А теперь помогите Васе решить задачу по информатике. Он снова томится дома в
хорошую погоду.
На вход подается строка длиной от 1 до 10000 символов. Нужно отсортировать её в
порядке частот букв по встречаемости. Заглавные и строчные буквы считаются
разными. Если частота одинаковая, нужно применить втори... | Python | zaydzuhri_stack_edu_python |
set params = call Params json_path
print learning_rate
comment change the value of learning_rate in params
set learning_rate = 0.5 | params = Params(json_path)
print(params.learning_rate)
params.learning_rate = 0.5 # change the value of learning_rate in params
| Python | zaydzuhri_stack_edu_python |
import math
import pandas as pd
from keras.callbacks import Callback , EarlyStopping , ModelCheckpoint
from model import *
set RATINGS_CSV_FILE = string data/train.csv
set MODEL_FILE = string model_nobias_256
set K_FACTORS = 256
set normalize = true
set bias = false
set ratings = read csv RATINGS_CSV_FILE encoding=stri... | import math
import pandas as pd
from keras.callbacks import Callback, EarlyStopping, ModelCheckpoint
from model import *
RATINGS_CSV_FILE = 'data/train.csv'
MODEL_FILE = 'model_nobias_256'
K_FACTORS = 256
normalize = True
bias = False
ratings = pd.read_csv(RATINGS_CSV_FILE, encoding='utf-8')
max_userid = ratings['Use... | Python | zaydzuhri_stack_edu_python |
function name self
begin
return _name
end function | def name(self):
return self._name | Python | nomic_cornstack_python_v1 |
function delete_znodes cluster_name path recursive=false del_snapshots=true
begin
set del_znode_query = none
set del_snapshot_query = none
if recursive
begin
comment monkey patch for delete znodes recursively
set target_path = right strip path string / + string /
set del_znode_query = where cluster_name == cluster_name... | def delete_znodes(cluster_name, path, recursive=False, del_snapshots=True):
del_znode_query = del_snapshot_query = None
if recursive:
# monkey patch for delete znodes recursively
target_path = path.rstrip("/") + "/"
del_znode_query = ZdZnode.delete().where(
(ZdZnode.cluster_n... | Python | nomic_cornstack_python_v1 |
comment Lesson 4: Understand Data with Descriptive Statistics
comment Once you have loaded your data into Python you need to be able to understand it.
comment The better you can understand your data, the better and more accurate the models that you can build.
comment The first step to understanding your data is to use ... | # Lesson 4: Understand Data with Descriptive Statistics
# Once you have loaded your data into Python you need to be able to understand it.
# The better you can understand your data, the better and more accurate the models that you can build.
# The first step to understanding your data is to use descriptive statistics.
... | Python | zaydzuhri_stack_edu_python |
function clear_user self e
begin
if get user == string Enter Enovia Username
begin
clear user
end
end function | def clear_user(self, e):
if self.user.get() == 'Enter Enovia Username':
self.user.clear() | Python | nomic_cornstack_python_v1 |
function sample_cond_on_subtree_nodes new tree subtree_nodes subtree_edges subtree_adjlist
begin
set new_separators = dict
set new_cliques = set
set old_cliques = set
set subtree_order = length subtree_nodes
comment print("subtree nodes:" + str(subtree_nodes))
if subtree_order == 0
begin
comment If the tree, tree is e... | def sample_cond_on_subtree_nodes(new, tree, subtree_nodes, subtree_edges, subtree_adjlist):
new_separators = {}
new_cliques = set()
old_cliques = set()
subtree_order = len(subtree_nodes)
#print("subtree nodes:" + str(subtree_nodes))
if subtree_order == 0:
# If the tree, tree is empty (n... | Python | nomic_cornstack_python_v1 |
function generate_iou_map bboxes gt_boxes
begin
set tuple bbox_y1 bbox_x1 bbox_y2 bbox_x2 = split tf bboxes 4 axis=2
set tuple gt_y1 gt_x1 gt_y2 gt_x2 = split tf gt_boxes 4 axis=2
comment Calculate bbox and ground truth boxes areas
set gt_area = squeeze tf gt_y2 - gt_y1 * gt_x2 - gt_x1 axis=2
set bbox_area = squeeze tf... | def generate_iou_map(bboxes, gt_boxes):
bbox_y1, bbox_x1, bbox_y2, bbox_x2 = tf.split(bboxes, 4, axis=2)
gt_y1, gt_x1, gt_y2, gt_x2 = tf.split(gt_boxes, 4, axis=2)
# Calculate bbox and ground truth boxes areas
gt_area = tf.squeeze((gt_y2 - gt_y1) * (gt_x2 - gt_x1), axis=2)
bbox_area = tf.squeeze((bb... | Python | nomic_cornstack_python_v1 |
import asyncio
import subprocess
async function run_cmd when
begin
print string Start sleep { when }
set cmd = string sleep { when }
run cmd shell=true check=false universal_newlines=true stdout=PIPE stderr=PIPE
print string End sleep { when }
end function
async function say what when
begin
await sleep when
print what
... | import asyncio
import subprocess
async def run_cmd(when):
print(f'Start sleep {when}')
cmd = f'sleep {when}'
subprocess.run(cmd, shell=True, check=False, universal_newlines=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(f'End sleep {when}')
async def say(what, when):
await asyncio.sle... | Python | zaydzuhri_stack_edu_python |
import os
import base64
set b64e = lambda s -> right strip call encodestring s
set b64d = decodestring
from functools import partial
from Crypto.Cipher import AES , Blowfish
try
begin
from md5 import md5 as hash_func
end
except ImportError
begin
from hashlib import md5 as hash_func
end
function _cipher algo secret
begi... | import os
import base64
b64e = lambda s: base64.encodestring(s).rstrip()
b64d = base64.decodestring
from functools import partial
from Crypto.Cipher import AES, Blowfish
try:
from md5 import md5 as hash_func
except ImportError:
from hashlib import md5 as hash_func
def _cipher(algo, secret):
h = hash_fun... | Python | zaydzuhri_stack_edu_python |
while sport != string yes and sport != string no
begin
set sport = input string do you sport? yes/no
if sport == string yes
begin
print string well
end
else
if sport == string no
begin
print string go to gym ASAP!
end
end
print string finish | while sport != 'yes' and sport != 'no':
sport = input('do you sport? yes/no ')
if sport == 'yes':
print('well')
elif sport == 'no':
print("go to gym ASAP!")
print("finish") | Python | zaydzuhri_stack_edu_python |
function sign self plaintext
begin
if not priv
begin
call readKeys
end
set digest = call Digest MD5_DIGEST
update digest plaintext
return call encodestring call sign call digest MD5_DIGEST
end function | def sign(self, plaintext):
if not self.priv: self.readKeys()
digest = POW.Digest(POW.MD5_DIGEST)
digest.update(plaintext)
return base64.encodestring(
self.priv.sign(digest.digest(), POW.MD5_DIGEST)) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Mon Jul 23 22:41:40 2018 @author: Alicia
string Pandas Series use Create a Series from a dictionary containning student name subject and grade Create a DataFrame from previous Series indexing by Course
import numpy as np
import pandas as pd
s... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 23 22:41:40 2018
@author: Alicia
"""
"""
Pandas Series use
Create a Series from a dictionary containning student name subject and grade
Create a DataFrame from previous Series indexing by Course
"""
import numpy as np
import pandas as pd
student_... | Python | zaydzuhri_stack_edu_python |
comment Imports
import sys
import os
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data import Dataset
from skimage import io
impo... | # Imports
import sys
import os
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
import torchvision.datasets as datasets
import torchvision.transforms as transforms
from torch.utils.data import Dataset
from skimage import io
import to... | Python | zaydzuhri_stack_edu_python |
function world_to_pixel_np self location
begin
set min_x = min_x
set min_y = min_y
set loc = _pixels_per_meter * location - array list list min_x min_y dtype=float32
return loc
end function | def world_to_pixel_np(self, location: np.array):
min_x = self._map_boundaries.min_x
min_y = self._map_boundaries.min_y
loc = self._pixels_per_meter * (
location - np.array([[min_x, min_y]], dtype=np.float32))
return loc | Python | nomic_cornstack_python_v1 |
import csv
import logging
import sys
import time
function setup_default_logging
begin
string logging: default logging
set fname = format string train_{}.log string format time time string %Y%m%d-%H%M
call basicConfig filename=fname filemode=string w format=string %(asctime)s - %(name)s - %(levelname)s - %(message)s lev... | import csv
import logging
import sys
import time
def setup_default_logging():
"""logging: default logging"""
fname = 'train_{}.log'.format(time.strftime('%Y%m%d-%H%M'))
logging.basicConfig(filename=fname,
filemode='w',
format="%(asctime)s - %(name)s - %(level... | Python | zaydzuhri_stack_edu_python |
import pygame
import sys
from pygame.sprite import Sprite
from timer import Timer
from random import choice
class Alien extends Sprite
begin
function __init__ self ai_settings screen image_path1 image_path2
begin
call __init__
set screen = screen
set ai_settings = ai_settings
set images = list
call create_animate_imag... | import pygame
import sys
from pygame.sprite import Sprite
from timer import Timer
from random import choice
class Alien(Sprite):
def __init__(self, ai_settings, screen, image_path1, image_path2):
super(Alien, self).__init__()
self.screen = screen
self.ai_settings = ai_settings
... | Python | zaydzuhri_stack_edu_python |
function on_time_or_not total_minutes_exam total_minutes_arrival
begin
set difference = absolute total_minutes_exam - total_minutes_arrival
if total_minutes_exam > total_minutes_arrival
begin
if difference <= 30
begin
return string On time { difference } minutes before the start
end
else
if 30 < difference <= 59
begin
... | def on_time_or_not(total_minutes_exam, total_minutes_arrival):
difference = abs(total_minutes_exam - total_minutes_arrival)
if total_minutes_exam > total_minutes_arrival:
if difference <= 30:
return f"On time\n{difference} minutes before the start"
elif 30 < difference <= 59:
... | Python | zaydzuhri_stack_edu_python |
function getNegativeSamples target dataset K
begin
set indices = list none * K
for k in call xrange K
begin
set newidx = call sampleTokenIdx
while newidx == target
begin
set newidx = call sampleTokenIdx
end
set indices at k = newidx
end
return indices
end function | def getNegativeSamples(target, dataset, K):
indices = [None] * K
for k in xrange(K):
newidx = dataset.sampleTokenIdx()
while newidx == target:
newidx = dataset.sampleTokenIdx()
indices[k] = newidx
return indices | Python | nomic_cornstack_python_v1 |
comment import the python datetime module to help us create a timestamp
from datetime import date
comment the pond
class Psyduck
begin
function __init__ self name species
begin
comment Establish the properties of each animal
comment with a default value
set name = name
set species = species
set date_added = today
set s... | # import the python datetime module to help us create a timestamp
from datetime import date
# the pond
class Psyduck:
def __init__(self, name, species):
# Establish the properties of each animal
# with a default value
self.name = name
self.species = species
self.date_added =... | Python | zaydzuhri_stack_edu_python |
function ST_Contains a b
begin
return call _call_predicate_function string ST_Contains tuple a b
end function | def ST_Contains(a: ColumnOrName, b: ColumnOrName) -> Column:
return _call_predicate_function("ST_Contains", (a, b)) | Python | nomic_cornstack_python_v1 |
import unittest
from mantid.api import AlgorithmID , AlgorithmManager
from testhelpers import run_algorithm
class AlgorithmTest extends TestCase
begin
set _load = none
function setUp self
begin
if _load is none
begin
set _load = call createUnmanaged string Load
call initialize
end
end function
function test_alg_attrs_a... | import unittest
from mantid.api import AlgorithmID, AlgorithmManager
from testhelpers import run_algorithm
###########################################################
class AlgorithmTest(unittest.TestCase):
_load = None
def setUp(self):
if self._load is None:
self.__class__._load = Algor... | Python | zaydzuhri_stack_edu_python |
function create
begin
print string Create your account
set file = open string userdata.txt string r
comment print(len(file.readline()))
seek file length read line file + 1
set name = input string Enter your username :
for i in file
begin
set temp = split i string ,
append userlist temp at 0
end
close file
while name in... | def create():
print("\nCreate your account ")
file=open("userdata.txt","r")
#print(len(file.readline()))
file.seek(len(file.readline())+1)
name=input("Enter your username : ")
for i in file:
temp=i.split(',')
userlist.append(temp[0])
file.close()
while name in userlist:
... | Python | zaydzuhri_stack_edu_python |
function get_agenda_limit
begin
set agendas = call get_agenda_limit
set ser_agendas = data
set res = call response_message 200 string Success url none ser_agendas
return call jsonify res
end function | def get_agenda_limit():
agendas = AgendaModel.get_agenda_limit()
ser_agendas = agenda_schema.dump(agendas, many=True).data
res = response_message(200, 'Success', request.url, None, ser_agendas)
return jsonify(res) | Python | nomic_cornstack_python_v1 |
import pandas as pd
import numpy as np
from sklearn.feature_selection import mutual_info_classif
from sklearn.preprocessing import LabelEncoder
from sklearn.tree import DecisionTreeClassifier as DTC
from sklearn.ensemble import RandomForestClassifier as RFC , AdaBoostClassifier as ABC , ExtraTreesClassifier as ETC , Gr... | import pandas as pd
import numpy as np
from sklearn.feature_selection import mutual_info_classif
from sklearn.preprocessing import LabelEncoder
from sklearn.tree import DecisionTreeClassifier as DTC
from sklearn.ensemble import RandomForestClassifier as RFC, AdaBoostClassifier as ABC, ExtraTreesClassifier as ETC, Gradi... | Python | zaydzuhri_stack_edu_python |
function get_pps self
begin
return string round growth_value * 15 3
end function | def get_pps(self):
return(str(round(self.growth_value * 15, 3))) | Python | nomic_cornstack_python_v1 |
function degree_to_radian degree
begin
set radian = degree * pi / 180
return round radian 4
end function | def degree_to_radian(degree):
radian = degree * (math.pi / 180)
return round(radian, 4) | Python | nomic_cornstack_python_v1 |
function image_create name location=none profile=none visibility=none container_format=string bare disk_format=string raw protected=none
begin
string Create an image (glance image-create) CLI Example, old format: .. code-block:: bash salt '*' glance.image_create name=f16-jeos \ disk_format=qcow2 container_format=ovf CL... | def image_create(name,
location=None,
profile=None,
visibility=None,
container_format='bare',
disk_format='raw',
protected=None,):
'''
Create an image (glance image-create)
CLI Example, old format:
..... | Python | jtatman_500k |
function test_fma_invalid_param_str_intnum_intarray_intarray_1394 self
begin
comment This version is expected to pass.
call fma floatarrayx floatnumy floatarrayz floatarrayout
comment This is the actual test.
with assert raises TypeError
begin
call fma strx intnumy intarrayz intarrayout
end
end function | def test_fma_invalid_param_str_intnum_intarray_intarray_1394(self):
# This version is expected to pass.
arrayfunc.fma(self.floatarrayx, self.floatnumy, self.floatarrayz, self.floatarrayout)
# This is the actual test.
with self.assertRaises(TypeError):
arrayfunc.fma(self.strx, self.intnumy, self.intarrayz, s... | Python | nomic_cornstack_python_v1 |
set num = integer input string enter number to display table :
print string ................. Multiplication table of num string .................
set a = 1
while a <= 10
begin
print num string * a string = num * a
set a = a + 1
end | num=int(input("enter number to display table : "))
print(".................\nMultiplication table of ",num,"\n.................")
a=1
while(a<=10):
print(num,"*",a,"=",num*a)
a+=1 | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/python3
comment -*-coding:utf-8-*-
from html.parser import HTMLParser
import urllib.request
class ImgParser extends HTMLParser
begin
function __init__ self
begin
call __init__ self
comment 保存图片链接地址
set links = list
end function
function handle_starttag self tag attrs
begin
if tag == string img and t... | #! /usr/bin/python3
# -*-coding:utf-8-*-
from html.parser import HTMLParser
import urllib.request
class ImgParser(HTMLParser):
def __init__(self):
HTMLParser.__init__(self)
self.links = [] # 保存图片链接地址
def handle_starttag(self, tag, attrs):
if tag == "img" and ('class','BDE_Image') i... | Python | zaydzuhri_stack_edu_python |
for i in range 0 n
begin
set tuple a b = map int split input
set tmp = list a b
print tmp
end | for i in range(0,n):
a,b=map(int,input().split())
tmp=[a,b]
print(tmp) | Python | zaydzuhri_stack_edu_python |
comment Usage:
comment python3 anagram.py <dictionary_file> <vocabulary1> <vocabulary2>...
comment Example:
comment python3 anagram.py ../american-english foo bar etc
import sys
from collections import deque
set arg_length = length argv
if arg_length > 2
begin
set dic = dict
set file_path = argv at 1
print string Read... | # Usage:
# python3 anagram.py <dictionary_file> <vocabulary1> <vocabulary2>...
# Example:
# python3 anagram.py ../american-english foo bar etc
import sys
from collections import deque
arg_length = len(sys.argv)
if(arg_length>2):
dic = {}
file_path = sys.argv[1]
print("Reading file: "+file_path)
... | Python | zaydzuhri_stack_edu_python |
function test_print_progress_flag self capsys
begin
set file = join path string tests string data string geolife string geolife_staypoints.csv
set staypoints = call read_staypoints_csv file tz=string utc index_col=string id crs=string epsg:4326
call generate_locations print_progress=true
set captured_print = call reado... | def test_print_progress_flag(self, capsys):
file = os.path.join("tests", "data", "geolife", "geolife_staypoints.csv")
staypoints = ti.read_staypoints_csv(file, tz="utc", index_col="id", crs="epsg:4326")
staypoints.as_staypoints.generate_locations(print_progress=True)
captured_print = ca... | Python | nomic_cornstack_python_v1 |
function get_blotches self user_name=none without_users=none
begin
return call filter_data string blotch user_name without_users
end function | def get_blotches(self, user_name=None, without_users=None):
return self.filter_data('blotch', user_name, without_users) | Python | nomic_cornstack_python_v1 |
for i in range n
begin
set x = x - children at i
if i < n - 1
begin
if x >= 0
begin
set ans = ans + 1
end
end
else
if x == 0
begin
set ans = ans + 1
end
end
print ans | for i in range(n):
x = x - children[i]
if i < n - 1:
if x >= 0:
ans += 1
else:
if x == 0:
ans += 1
print(ans) | Python | zaydzuhri_stack_edu_python |
function string_compression s
begin
comment Keep track of the current character in order to make a comparison with the "next" or "previous" element.
set current_char = s at 0
set result = string
set counter = 1
comment Loop through the rest of the list. If the same character found, increment counter. Otherwise, append... | def string_compression(s):
# Keep track of the current character in order to make a comparison with the "next" or "previous" element.
current_char = s[0]
result = ""
counter = 1
# Loop through the rest of the list. If the same character found, increment counter. Otherwise, append the letter and count to the resul... | Python | zaydzuhri_stack_edu_python |
comment Definition for a binary tree node.
comment class TreeNode:
comment def __init__(self, x):
comment self.val = x
comment self.left = None
comment self.right = None
class Solution
begin
function insertIntoMaxTree self root val
begin
if not root
begin
return
end
function get_nums root
begin
if not root
begin
return... | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def insertIntoMaxTree(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return
def get_nums(root):
... | Python | zaydzuhri_stack_edu_python |
comment Solicite ingresar al usuario la medida de 3 lados de un tríangulo, el sistema debe mostrar:
comment 1.- Perímetro del triangulo
comment 2.- Tipo de triangulo (Equilátero, isósceles o escaleno).
function perimetro l1 l2 l3
begin
return l1 + l2 + l3
end function
function esIsosceles l1 l2 l3
begin
return l1 == l2... | #Solicite ingresar al usuario la medida de 3 lados de un tríangulo, el sistema debe mostrar:
#1.- Perímetro del triangulo
#2.- Tipo de triangulo (Equilátero, isósceles o escaleno).
def perimetro(l1, l2, l3):
return l1 + l2 + l3
def esIsosceles(l1, l2, l3):
return l1 == l2 or l1 == l3 or l2 == l3
def esEquil... | Python | zaydzuhri_stack_edu_python |
from typing import *
class Solution
begin
function combinationSum2 self candidates target
begin
sort candidates
function backtrack arr lower upper total
begin
if total == target
begin
append res arr
end
comment not in range of candidates[i]
set prev = 51
for i in range lower upper
begin
if prev == candidates at i
begin... | from typing import *
class Solution:
def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
candidates.sort()
def backtrack(arr,lower,upper,total):
if total==target:
res.append(arr)
# not in range of candidates[i]
... | Python | zaydzuhri_stack_edu_python |
function filter_properties_target namespaces_iter resource_types properties_target
begin
string Filter metadata namespaces. Filtering is done based ongiven resource types and a properties target. :param namespaces_iter: Metadata namespaces iterable. :param resource_types: List of resource type names. :param properties_... | def filter_properties_target(namespaces_iter,
resource_types,
properties_target):
"""Filter metadata namespaces.
Filtering is done based ongiven resource types and a properties target.
:param namespaces_iter: Metadata namespaces iterable.
:para... | Python | jtatman_500k |
function binarize_array numpy_array threshold=200
begin
for i in range length numpy_array
begin
for j in range length numpy_array at 0
begin
if numpy_array at i at j > threshold
begin
set numpy_array at i at j = 255
end
else
begin
set numpy_array at i at j = 0
end
end
end
return numpy_array
end function | def binarize_array(numpy_array, threshold=200):
for i in range(len(numpy_array)):
for j in range(len(numpy_array[0])):
if numpy_array[i][j] > threshold:
numpy_array[i][j] = 255
else:
numpy_array[i][j] = 0
return numpy_ar... | Python | nomic_cornstack_python_v1 |
function hidden_half_face image bbox p=0.1
begin
if length bbox >= 2
begin
return tuple image bbox
end
set tuple heigth width _ = shape
set a_bbox = bbox at 0
set tuple x1 y1 x2 y2 = a_bbox
set cx = x1 + x2 / 2
comment ---人脸的中线
set cx = integer cx
comment -1, 左边涂黑; 0,右边涂黑
set flag = if expression random > 0.5 then 1 el... | def hidden_half_face(image, bbox, p=0.1):
if len(bbox)>=2: return image, bbox
heigth, width, _ = image.shape
a_bbox = bbox[0]
x1, y1, x2, y2 = a_bbox
cx = (x1+x2)/2
cx = int(cx) #---人脸的中线
flag = 1 if random.random()>0.5 else 0 #-1, 左边涂黑; 0,右边涂黑
if flag:
image[:,:cx] = 0
... | Python | nomic_cornstack_python_v1 |
function call self *args **kwargs
begin
with semaphore
begin
return call *args keyword kwargs
end
end function | def call(self, *args, **kwargs):
with self.semaphore:
return subprocess.call(*args, **kwargs) | Python | nomic_cornstack_python_v1 |
function rsvp event_id
begin
comment TODO: Get the event with the given id from the database
set is_returning_guest = get form string returning
set guest_name = get form string guest_name
if is_returning_guest
begin
comment TODO: Look up the guest by name. If the guest doesn't exist in the
comment database, render the ... | def rsvp(event_id):
# TODO: Get the event with the given id from the database
is_returning_guest = request.form.get('returning')
guest_name = request.form.get('guest_name')
if is_returning_guest:
# TODO: Look up the guest by name. If the guest doesn't exist in the
# database, re... | Python | nomic_cornstack_python_v1 |
function find_squared n niter
begin
if niter == 0
begin
return 0
end
set total = n
set count = 1
while count + count <= niter
begin
set total = total + total
set count = count + count
end
set rem = niter - count
return total + call find_squared n rem
end function
function find_squared_faster n total count
begin
if coun... | def find_squared(n, niter):
if niter == 0:
return 0
total = n
count = 1
while count + count <= niter:
total += total
count += count
rem = niter - count
return total + find_squared(n, rem)
def find_squared_faster(n, total, count):
if count + count > n:
retu... | Python | zaydzuhri_stack_edu_python |
function _normalize self course
begin
set course_key = string course_id
set course = strip course
try
begin
call valid_academic_course_sis_id course
end
except CoursePolicyException
begin
try
begin
call valid_adhoc_course_sis_id course
set course = lower course
end
except CoursePolicyException
begin
call valid_canvas_c... | def _normalize(self, course):
course_key = 'course_id'
course = course.strip()
try:
valid_academic_course_sis_id(course)
except CoursePolicyException:
try:
valid_adhoc_course_sis_id(course)
course = course.lower()
except... | Python | nomic_cornstack_python_v1 |
function wrapMain func
begin
function handleError error
begin
if type == SystemExit
begin
call msg string SystemExit: %s % value
end
else
if type == UsageError
begin
call msg value
end
else
begin
call printTraceback
end
end function
call startLoggingWithObserver logObserver setStdout=0
set d = call maybeDeferred func
c... | def wrapMain(func):
def handleError(error):
if error.type == SystemExit:
log.msg('SystemExit: %s' % error.value)
elif error.type == usage.UsageError:
log.msg(error.value)
else:
error.printTraceback()
log.startLoggingWithObserver(logObserver, setStdout... | Python | nomic_cornstack_python_v1 |
class Solution
begin
function isPowerOfTwo self n
begin
string :type n: int :rtype: bool
return n > 0 and n ? n - 1 == 0
end function
end class
class Solution2
begin
function isPowerOfTwo self n
begin
string :type n: int :rtype: bool
if n < 1
begin
return false
end
while n % 2 == 0
begin
set n = n / 2
end
return if exp... | class Solution:
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and (n & (n-1)) == 0
class Solution2:
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n < 1:
return False
... | Python | zaydzuhri_stack_edu_python |
from __future__ import print_function
import argparse
import tarfile
from os.path import realpath
import sys
set parser = call ArgumentParser fromfile_prefix_chars=string @ description=string Description
call add_argument string --input_tar action=string append default=list nargs=2 metavar=tuple string modulepath stri... | from __future__ import print_function
import argparse
import tarfile
from os.path import realpath
import sys
parser = argparse.ArgumentParser(
fromfile_prefix_chars='@',
description='Description')
parser.add_argument(
'--input_tar', action='append', default=[], nargs=2, metavar=('modulepath', 'tar'),
... | Python | zaydzuhri_stack_edu_python |
async function run self
begin
try
begin
set hook = call _get_async_hook
while true
begin
set res = await call _object_exists hook=hook bucket_name=bucket object_name=object_name
if res == string success
begin
yield call TriggerEvent dict string status string success ; string message res
end
await sleep poke_interval
en... | async def run(self) -> AsyncIterator["TriggerEvent"]:
try:
hook = self._get_async_hook()
while True:
res = await self._object_exists(
hook=hook, bucket_name=self.bucket, object_name=self.object_name
)
if res == "success"... | Python | nomic_cornstack_python_v1 |
function dist var_series var_to_bin_against=none bins=none bin_labels=none x_label=none max_y_value=none aggregation_method=string %frequency return_data=false
begin
if var_to_bin_against is none
begin
set var_to_bin_against = copy var_series deep=false
end
set var_series = call _convert_df_to_series var_series
set var... | def dist(var_series, var_to_bin_against=None, bins=None, bin_labels=None, x_label=None,
max_y_value=None, aggregation_method='%frequency', return_data=False):
if var_to_bin_against is None:
var_to_bin_against = var_series.copy(deep=False)
var_series = _convert_df_to_series(var_series)
var_t... | Python | nomic_cornstack_python_v1 |
function maximum_flow_example
begin
set network = call FlowNetwork string s string t dict tuple string s string a 3 ; tuple string s string b 2 ; tuple string a string d 2 ; tuple string b string a 3 ; tuple string b string c 3 ; tuple string c string d 3 ; tuple string c string t 2 ; tuple string d string b 1 ; tuple ... | def maximum_flow_example():
network = FlowNetwork('s', 't', {
('s', 'a'): 3,
('s', 'b'): 2,
('a', 'd'): 2,
('b', 'a'): 3,
('b', 'c'): 3,
('c', 'd'): 3,
('c', 't'): 2,
('d', 'b'): 1,
('d', 't'): 3,
})
c = {
v: -1 for u, v in network.flows
if u == network.src
}
for u ... | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/env python
import rospy
from laser_subscriber import LaserSub
from odom_subscriber import OdomSub
from geometry_msgs.msg import Twist
class CMDPub extends object
begin
function __init__ self
begin
set vel_pub = call Publisher string /cmd_vel Twist queue_size=1
set cmd = call Twist
set ctrl_c = false
... | #! /usr/bin/env python
import rospy
from laser_subscriber import LaserSub
from odom_subscriber import OdomSub
from geometry_msgs.msg import Twist
class CMDPub(object):
def __init__(self):
self.vel_pub = rospy.Publisher('/cmd_vel', Twist, queue_size=1)
self.cmd = Twist()
self.ctrl_c = Fals... | 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.