code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function compute_mrcnn_mask_loss gt_mask gt_class_id mrcnn_mask
begin
set positive_index = squeeze call nonzero gt_class_id 1
set class_ids = gt_class_id at positive_index
set targets = gt_mask at tuple positive_index slice : :
set predicts = mrcnn_mask at tuple positive_index class_ids slice : :
return call bina... | def compute_mrcnn_mask_loss(gt_mask, gt_class_id, mrcnn_mask):
positive_index = torch.nonzero(gt_class_id).squeeze(1)
class_ids = gt_class_id[positive_index]
targets = gt_mask[positive_index, :]
predicts = mrcnn_mask[positive_index, class_ids, :]
return F.binary_cross_entropy(predicts, targets) | Python | nomic_cornstack_python_v1 |
set tuple N A B = generator expression integer x for x in split input
print if expression B - A % 2 then string Borys else string Alice | N,A,B = (int(x) for x in input().split())
print("Borys" if (B - A) % 2 else "Alice") | Python | zaydzuhri_stack_edu_python |
import sharedValues
import threading
import time
import math
comment flag to exit the program
set exitFlag = 0
import RPi.GPIO as GPIO
import time
call setwarnings false
call setmode BOARD
comment e d dp c g b f a
set segments = tuple 7 21 12 23 15 18 31 32
comment 1 2 3 4
set digits = tuple 33 29 22 16
set ON = 0
set ... | import sharedValues
import threading
import time
import math
# flag to exit the program
exitFlag = 0
import RPi.GPIO as GPIO
import time
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
# e d dp c g b f a
segments = (7, 21, 12, 23, 15, 18, 31, 32)
# 1 2 3 4
digits = (33,29,22,16)
ON = ... | Python | zaydzuhri_stack_edu_python |
string Your function should take in a single parameter (a string `word`) Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters. Your function must utilize recursion. It cannot contain any loops.
function count_th word n=0 x=0
begin
if word == string
begin
return x
e... | '''
Your function should take in a single parameter (a string `word`)
Your function should return a count of how many occurences of ***"th"*** occur within `word`. Case matters.
Your function must utilize recursion. It cannot contain any loops.
'''
def count_th(word, n=0, x=0):
if word == '':
return x
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import unittest
from random import randint
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoA... | #!/usr/bin/env python
import unittest
from random import randint
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPr... | Python | zaydzuhri_stack_edu_python |
function bpki_cross_certify self keypair source_cert serial notAfter now=none pathLenConstraint=0
begin
return call bpki_certify keypair=keypair subject_name=call getSubject subject_key=call getPublicKey serial=serial notAfter=notAfter now=now pathLenConstraint=pathLenConstraint is_ca=true
end function | def bpki_cross_certify(self, keypair, source_cert, serial, notAfter,
now = None, pathLenConstraint = 0):
return self.bpki_certify(
keypair = keypair,
subject_name = source_cert.getSubject(),
subject_key = source_cert.getPublicKey(),
... | Python | nomic_cornstack_python_v1 |
import connect_db as db
function query_table db_name
begin
comment get connection instance
set conn = call connect_db db_name
comment Open a cursor to perform database operations
set cur = call cursor
comment Execute a query
execute cur string SELECT * FROM EMPLOYEE
comment Retrieve query results
set records = call fet... | import connect_db as db
def query_table(db_name):
# get connection instance
conn = db.connect_db(db_name)
# Open a cursor to perform database operations
cur = conn.cursor()
# Execute a query
cur.execute("SELECT * FROM EMPLOYEE")
# Retrieve query results
records = cur.fetchall()
p... | Python | zaydzuhri_stack_edu_python |
function main
begin
set tuple n k = map int split input
set s = 0
if k == 0
begin
set s = n * n
end
else
begin
for k_ in range k n
begin
for q in range n - k_ // k_ + 1 + 1
begin
if q == 0
begin
set s = s + n - k_
end
else
begin
set s = s + n - k_ // q - k_
end
end
end
end
print s
end function
if __name__ == string __m... | def main():
n,k = map(int,input().split())
s = 0
if k==0:
s = n*n
else:
for k_ in range(k,n):
for q in range((n-k_)//(k_+1)+1):
if q==0:
s += n-k_
else:
s += (n-k_)//q-k_
print(s)
if __na... | Python | zaydzuhri_stack_edu_python |
function get_all_activemanagementservers
begin
try
begin
debug format string logger output: {} ) string this is to get all active resources
set activeresources = call get_all_activemgmtServers
if not activeresources
begin
raise call ValueError NO_ACTIVE_MGMTSERVER_MSG
end
set mgmtserverdata = mgmtserverdata
debug forma... | def get_all_activemanagementservers():
try:
logging.debug("logger output: {} )".format("this is to get all active resources"))
activeresources = db_validations.get_all_activemgmtServers()
if not activeresources:
raise ValueError(Constants.NO_ACTIVE_MGMTSERVER_MSG)
m... | Python | nomic_cornstack_python_v1 |
function malthusian food_growth pop_mult
begin
set YC = 0
set tuple P F = tuple 100 * pop_mult 100 + food_growth
while P < F
begin
set F = F + food_growth
set P = P * pop_mult
set YC = YC + 1
end
return YC + 1
end function | def malthusian(food_growth, pop_mult):
YC = 0
P, F = 100*pop_mult,100+food_growth
while P < F:
F += food_growth
P *= pop_mult
YC += 1
return YC+1
| Python | zaydzuhri_stack_edu_python |
function demote self mode
begin
string Demote PostgreSQL running as master. :param mode: One of offline, graceful or immediate. offline is used when connection to DCS is not available. graceful is used when failing over to another node due to user request. May only be called running async. immediate is used when we det... | def demote(self, mode):
"""Demote PostgreSQL running as master.
:param mode: One of offline, graceful or immediate.
offline is used when connection to DCS is not available.
graceful is used when failing over to another node due to user request. May only be called running async.
... | Python | jtatman_500k |
import numpy as np
call set_printoptions precision=4 floatmode=string fixed suppress=true
class Tree
begin
function __init__ self
begin
set is_leaf = false
end function
function __call__ self X
begin
if is_leaf
begin
comment return majority class label (from training data)
return call full length X value
end
else
begin... | import numpy as np
np.set_printoptions(precision=4, floatmode='fixed', suppress=True)
class Tree:
def __init__(self):
self.is_leaf = False
def __call__(self, X):
if self.is_leaf:
# return majority class label (from training data)
return np.full(len(... | Python | zaydzuhri_stack_edu_python |
from PIL import Image
from pylab import *
set im = array call convert string L
comment 对图像进行反相处理
set im2 = 255 - im
comment 将图像像素值变换到100-200之间
set im3 = 100.0 / 255 * im + 100
comment 对图像像素值求平方后得到的图像
set im4 = 255.0 * im / 255 ^ 2
comment print(int(im.min()), int(im.max()))
comment 绘制图像
figure
subplot 2 2 1
image show ... | from PIL import Image
from pylab import *
im = array(Image.open('tim2.jpg').convert('L'))
# 对图像进行反相处理
im2 = 255 - im
# 将图像像素值变换到100-200之间
im3 = (100.0 / 255) * im + 100
# 对图像像素值求平方后得到的图像
im4 = 255.0 * (im / 255) ** 2
# print(int(im.min()), int(im.max()))
# 绘制图像
figure()
subplot(2, 2, 1)
imshow(im, cmap="gray")... | Python | zaydzuhri_stack_edu_python |
function get_locator self key
begin
set name = call _normalize key
set path = split name string .
try
begin
set locatorlist = _locators
for part in path
begin
set locatorlist = locatorlist at part
end
return locatorlist
end
except any
begin
raise exception string LOCATOR ERROR: no locator found with name %s % name
end
... | def get_locator(self, key):
name = self._normalize(key)
path = name.split(".")
try:
locatorlist = self._locators
for part in path:
locatorlist = locatorlist[part]
return locatorlist
except:
raise Exception("LOCATOR ERROR: no... | Python | nomic_cornstack_python_v1 |
function forward self s_t_1 z_t_1
begin
if z_t_1 is none
begin
set s_t = softmax call fc_s s_t_1
end
else
begin
set s_t = relu call fc1_z z_t_1
set s_t = relu call fc2_z s_t
set s_t = softmax call fc3_z s_t
end
return s_t
end function | def forward(self, s_t_1, z_t_1):
if z_t_1 is None:
s_t = self.softmax(self.fc_s(s_t_1))
else:
s_t = self.relu(self.fc1_z(z_t_1))
s_t = self.relu(self.fc2_z(s_t))
s_t = self.softmax(self.fc3_z(s_t))
return s_t | Python | nomic_cornstack_python_v1 |
function one_exerciseJSON category exercise
begin
set category = call one
set exercise = call one
return call jsonify Exercise=list serialize
end function | def one_exerciseJSON(category, exercise):
category = db_session.query(Category).filter_by(name=category).one()
exercise = db_session.query(
Exercise).filter_by(name=exercise, category=category).one()
return jsonify(Exercise=[exercise.serialize]) | Python | nomic_cornstack_python_v1 |
import serial
import time
import test_map
import data_send
comment ser=serial.Serial("/dev/ttyUSB0",115200,timeout=0.5)
set ser = call Serial string COM4 115200 timeout=0.5
comment 设置波特率
set baudrate = 115200
comment 字节大小
set bytesize = 8
comment 无校验
set parity = PARITY_NONE
comment 停止位
set stopbits = 1
comment 读超时设置
s... | import serial
import time
import test_map
import data_send
#ser=serial.Serial("/dev/ttyUSB0",115200,timeout=0.5)
ser=serial.Serial("COM4",115200,timeout=0.5)
ser.baudrate=115200 #设置波特率
ser.bytesize=8 #字节大小
ser.parity=serial.PARITY_NONE #无校验
ser.stopbits=1 #停止位
ser.timeout=0.5 #读超时设置
position = 90
print(data_send.che... | Python | zaydzuhri_stack_edu_python |
function show_pole
begin
print string 0 1 2
for i in range 3
begin
set row = join string pole at i
print string { i } { row }
end
end function
function ask
begin
while true
begin
set coords = split input string Ведите координаты через пробел:
if length coords != 2
begin
print string Неверные координаты!!!!
continue
en... | def show_pole():
print(f' 0 1 2')
for i in range(3):
row = " ".join(pole[i])
print(f"{i} {row}")
def ask():
while True:
coords = input("Ведите координаты через пробел: ").split()
if len(coords) !=2:
print("Неверные координаты!!!!")
continue
... | Python | zaydzuhri_stack_edu_python |
function close self
begin
info string Closing SshTransport to host '%s'... % remote_frontend
if sftp is not none and call get_channel is not none
begin
close sftp
info string ... sftp connection to '%s' closed remote_frontend
end
if ssh is not none and call get_transport is not none
begin
close ssh
info string ... ssh ... | def close(self):
gc3libs.log.info(
"Closing SshTransport to host '%s'... " % self.remote_frontend)
if self.sftp is not None and self.sftp.get_channel() is not None:
self.sftp.close()
gc3libs.log.info("... sftp connection to '%s' closed",
s... | Python | nomic_cornstack_python_v1 |
from csv import DictReader , DictWriter
comment Ex2
function address_register person_id street number complement neighborhood city state
begin
string Register an address in the adresses list
comment Validating parameters
for tuple key value in items locals
begin
if value is none or value == string
begin
raise call Val... | from csv import DictReader, DictWriter
# Ex2
def address_register(person_id: int,
street: str,
number: str,
complement: str,
neighborhood: str,
city: str,
state: str) -> None:
"""Register ... | Python | zaydzuhri_stack_edu_python |
function gaussian_log_likelihood x mu sigma
begin
if is instance x int or is instance x float
begin
set n = 1
end
else
begin
set n = length x
end
return - n / 2 * log 2 * pi - n / 2 * log sigma ^ 2 - 1 / 2 * sigma ^ 2 * sum call square x - mu
end function | def gaussian_log_likelihood(x, mu, sigma):
if isinstance(x, int) or isinstance(x, float):
n = 1
else:
n = len(x)
return -(n/2)*np.log(2*np.pi) - (n/2)*np.log(sigma**2) - (1 / (2*sigma**2))*np.sum(np.square(x - mu)) | Python | nomic_cornstack_python_v1 |
comment real signature unknown; restored from __doc__
function child self p_int p_int_1
begin
return QModelIndex
end function | def child(self, p_int, p_int_1): # real signature unknown; restored from __doc__
return QModelIndex | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Thu Sep 20 13:34:00 2018 @author: mehdisenoussi
import matplotlib as mpl
comment mpl.use('TkAgg')
comment mpl.get_backend()
from matplotlib import cm
import pylab as pl
import numpy as np
comment import time
function quad_func x
begin
return ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 20 13:34:00 2018
@author: mehdisenoussi
"""
import matplotlib as mpl
#mpl.use('TkAgg')
#mpl.get_backend()
from matplotlib import cm
import pylab as pl
import numpy as np
#import time
def quad_func(x):
return 3 * x**2 - 2 * x + 4
def other_fu... | Python | zaydzuhri_stack_edu_python |
import requests
from bs4 import BeautifulSoup
import re
comment global variables
set bfs_crawled_links = list
set dfs_crawled_links = list
set bfs_in_links = dict
set bfs_out_links = dict
set dfs_in_links = dict
set dfs_out_links = dict
string Given: a file name and list to store the unique crawled links Effect: ... | import requests
from bs4 import BeautifulSoup
import re
# global variables
bfs_crawled_links = []
dfs_crawled_links = []
bfs_in_links = {}
bfs_out_links = {}
dfs_in_links = {}
dfs_out_links = {}
'''
Given: a file name and list to store the unique crawled links
Effect: populates the given list with the links e... | Python | zaydzuhri_stack_edu_python |
import csv
import itertools
import operator
from prettytable import PrettyTable
set data = dictionary
set candidates = string
with open string lab_3_data.csv newline=string as csv_file
begin
set reader = reader csv_file delimiter=string , skipinitialspace=true
set first = true
for line in reader
begin
if first
begin
se... | import csv
import itertools
import operator
from prettytable import PrettyTable
data = dict()
candidates = str()
with open('lab_3_data.csv', newline='') as csv_file:
reader = csv.reader(csv_file, delimiter=',', skipinitialspace=True)
first = True
for line in reader:
if first:
candidate... | Python | zaydzuhri_stack_edu_python |
function _get_delimiter item
begin
set delimiters = tuple string := string =
for delimiter in delimiters
begin
if delimiter in item
begin
if starts with item delimiter or ends with item delimiter
begin
raise call UsageError string { delimiter } must not starts or ends an item like in { item }
end
if count item delimite... | def _get_delimiter(item: str) -> Optional[str]:
delimiters = (':=', '=')
for delimiter in delimiters:
if delimiter in item:
if item.startswith(delimiter) or item.endswith(delimiter):
raise click.UsageError(f'{delimiter} must not starts or ends an item like in {item}')
... | Python | nomic_cornstack_python_v1 |
import re
from urllib import request
from reptile import Reptile
set urls = list comprehension format string https://book.douban.com/top250?start={} string i for i in range 175 226 25
print urls
for url in urls
begin
call go url
end | import re
from urllib import request
from reptile import Reptile
urls = ['https://book.douban.com/top250?start={}'.format(str(i)) for i in range(175,226,25)]
print(urls)
for url in urls:
Reptile().go(url)
| Python | zaydzuhri_stack_edu_python |
function get_cost self q_distribution next_q_distribution reward values next_values
begin
raise call NotImplementedError
end function | def get_cost(self, q_distribution, next_q_distribution, reward, values,
next_values):
raise NotImplementedError() | Python | nomic_cornstack_python_v1 |
from collections import defaultdict
class Solution
begin
function containsNearbyDuplicate self nums k
begin
string :type nums: List[int] :type k: int :rtype: bool
set n = length nums
if n < 2
begin
return false
end
set d = default dictionary list
for i in range n
begin
if nums at i not in d
begin
set d at nums at i = l... | from collections import defaultdict
class Solution:
def containsNearbyDuplicate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
n=len(nums)
if n<2:
return False
d=defaultdict(list)
for i in range(... | Python | zaydzuhri_stack_edu_python |
function find_common_elements list1 list2
begin
if not list1 or not list2
begin
return list
end
set set1 = set list1
set set2 = set list2
set common_elements = intersection set1 set2
return list common_elements
end function
set list1 = list 1 2 3 4 5 6 7 8 9 10
set list2 = list 10 20 30 40 50 60 70 80 90 100
set commo... | def find_common_elements(list1, list2):
if not list1 or not list2:
return []
set1 = set(list1)
set2 = set(list2)
common_elements = set1.intersection(set2)
return list(common_elements)
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
list2 = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
comm... | Python | jtatman_500k |
comment ! /usr/bin/python
comment -*- coding: utf-8 -*-
string Rank sentences based on cosine similarity and a query.
from argparse import ArgumentParser
import numpy as np
function get_sentences file_path
begin
string Return a list of sentences from a file.
with open file_path encoding=string utf-8 as hfile
begin
retu... | #! /usr/bin/python
# -*- coding: utf-8 -*-
"""Rank sentences based on cosine similarity and a query."""
from argparse import ArgumentParser
import numpy as np
def get_sentences(file_path):
"""Return a list of sentences from a file."""
with open(file_path, encoding='utf-8') as hfile:
return hfile.r... | Python | zaydzuhri_stack_edu_python |
function serialize self root
begin
if not root
begin
return string
end
set queue = list tuple 1 root
set seq_val_tuples = list
while queue
begin
set tuple seq node = pop queue 0
append seq_val_tuples string { seq } _ { val }
if left
begin
append queue tuple seq * 2 left
end
if right
begin
append queue tuple seq * 2 +... | def serialize(self, root):
if not root:
return ""
queue = [(1, root)]
seq_val_tuples = []
while queue:
seq, node = queue.pop(0)
seq_val_tuples.append(f"{seq}_{node.val}")
if node.left:
queue.append((seq * 2, node.left))
... | Python | nomic_cornstack_python_v1 |
function __pushStatic self arg2
begin
call __writeLine string @ + __currentFileName + string . + string arg2
call __writeLine string D=M
call __writeLine string @SP
call __writeLine string A=M
call __writeLine string M=D
call __writeLine string @SP
call __writeLine string M=M+1
end function | def __pushStatic(self, arg2):
self.__writeLine("@" + self.__currentFileName + "." + str(arg2))
self.__writeLine("D=M")
self.__writeLine("@SP")
self.__writeLine("A=M")
self.__writeLine("M=D")
self.__writeLine("@SP")
self.__writeLine("M=M+1") | Python | nomic_cornstack_python_v1 |
function set_survey survey
begin
import os
set environ at string OBZTAK_SURVEY = survey
return call get_survey
end function | def set_survey(survey):
import os
os.environ['OBZTAK_SURVEY'] = survey
return get_survey() | Python | nomic_cornstack_python_v1 |
function collate_fn batch
begin
if length tuple zip *batch == 4
begin
set tuple image_features caps caplens orig_caps = zip *batch
set r = tuple stack image_features stack caps stack caplens orig_caps at 0
end
else
begin
set tuple obj rel caps caplens orig_caps obj_mask rel_mask pair_idx = zip *batch
set r = tuple stac... | def collate_fn(batch):
if len(tuple(zip(*batch))) == 4:
image_features, caps, caplens, orig_caps = zip(*batch)
r = (torch.stack(image_features), torch.stack(caps), torch.stack(caplens), orig_caps[0])
else:
(obj, rel, caps, caplens, orig_caps, obj_mask, rel_mask, pair_idx) = zip(*batch)
... | Python | nomic_cornstack_python_v1 |
function convert_time time_str
begin
try
begin
comment Splitting the time string into hours, minutes, and AM/PM
set time_parts = split time_str string :
set hours = integer time_parts at 0
set minutes = integer time_parts at 1 at slice : 2 :
set am_pm = upper strip time_parts at 1 at slice 2 : :
comment Validating in... | def convert_time(time_str):
try:
# Splitting the time string into hours, minutes, and AM/PM
time_parts = time_str.split(':')
hours = int(time_parts[0])
minutes = int(time_parts[1][:2])
am_pm = time_parts[1][2:].strip().upper()
# Validating input
if hours < 1 ... | Python | jtatman_500k |
from numpy import random
from scipy.fftpack import fft
from celery import shared_task
from proj import celery_app
from celery.utils.log import get_task_logger
from celery_progress.backend import ProgressRecorder
set logger = call get_task_logger __name__
decorator call shared_task ignore_result=true
comment The @shared... | from numpy import random
from scipy.fftpack import fft
from celery import shared_task
from proj import celery_app
from celery.utils.log import get_task_logger
from celery_progress.backend import ProgressRecorder
logger = get_task_logger(__name__)
# The @shared_task decorator lets you create tasks without having an... | Python | zaydzuhri_stack_edu_python |
function test_get_total_cost_each_drug self
begin
set list1 = test_total_cost_each_drug
set list2 = call get_total_cost_each_drug test_sorted_tuple test_dict
assert equal list1 list2
end function | def test_get_total_cost_each_drug(self):
list1 = self.test_total_cost_each_drug
list2 = get_total_cost_each_drug(self.test_sorted_tuple, self.test_dict)
self.assertEqual(list1, list2) | Python | nomic_cornstack_python_v1 |
function test_data_object_untrash self
begin
pass
end function | def test_data_object_untrash(self):
pass | Python | nomic_cornstack_python_v1 |
class Employee
begin
function __init__ self first last pay
begin
set first = first
set las = last
set email = first + string . + last + string @gmail.com
set pay = pay
end function
function fullname self
begin
return format string {} {} first last
end function
function apply_raise self
begin
set pay = integer pay * rai... | class Employee:
def __init__(self, first, last, pay):
self.first = first
self.las = last
self.email = first + '.' + last + '@gmail.com'
self.pay = pay
def fullname(self):
return '{} {}'.format(self.first, self.last)
def apply_raise(self):
self.p... | Python | zaydzuhri_stack_edu_python |
function customer_rental rental_items
begin
set customer = partial add_furniture invoice_file=invoice_file customer_name=customer_name
with open rental_items string r as rental_csv
begin
for row in reader rental_csv
begin
call customer item_code=row at 0 item_description=row at 1 item_monthly_price=row at 2
end
end
end... | def customer_rental(rental_items):
customer = partial(add_furniture, invoice_file=invoice_file, customer_name=customer_name)
with open(rental_items, "r") as rental_csv:
for row in csv.reader(rental_csv):
customer(item_code=row[0], item_description=row[1], item_monthly_price=r... | Python | nomic_cornstack_python_v1 |
for i in l
begin
set xor = xor ? i
end
print 2 * xor | for i in l:
xor = xor ^ i
print(2*xor) | Python | zaydzuhri_stack_edu_python |
import time
from firebase.firebase import FirebaseApplication
set url = string https://crosseat-d9388.firebaseio.com/
set firebase = call FirebaseApplication url none
set x = 0
function add
begin
set firebase = call FirebaseApplication url none
set name = string input string New Employee's name:
set check = get firebas... | import time
from firebase.firebase import FirebaseApplication
url = "https://crosseat-d9388.firebaseio.com/"
firebase = FirebaseApplication(url, None)
x = 0
def add():
firebase = FirebaseApplication(url, None)
name = str(input("New Employee's name: "))
check = firebase.get('/Employee/{}' .forma... | Python | zaydzuhri_stack_edu_python |
function pisagor_bul
begin
set pisagor_list = list
for i in range 1 101
begin
for j in range 1 101
begin
set c = i ^ 2 + j ^ 2 ^ 0.5
if c == integer c
begin
append pisagor_list tuple i j integer c
end
end
end
return pisagor_list
end function
for i in call pisagor_bul
begin
print i
end | def pisagor_bul():
pisagor_list = []
for i in range(1,101):
for j in range(1,101):
c = (i ** 2 + j ** 2) ** 0.5
if(c == int(c)):
pisagor_list.append((i,j,int(c)))
return pisagor_list
for i in pisagor_bul():
print(i)
| Python | zaydzuhri_stack_edu_python |
function test_filesystem_not_available self MockPreview MockFilesystem
begin
set mock_preview = call MagicMock
set return_value = tuple MagicMock dict string ETag checksum
set mock_filesystem = call MagicMock
set side_effect = call raise_http_exception RequestFailed INTERNAL_SERVER_ERROR
set return_value = mock_preview... | def test_filesystem_not_available(self, MockPreview, MockFilesystem):
mock_preview = mock.MagicMock()
mock_preview.get_preview.return_value = \
(mock.MagicMock, {'ETag': self.checksum})
mock_filesystem = mock.MagicMock()
mock_filesystem.deposit_preview.side_effect = \
... | Python | nomic_cornstack_python_v1 |
function exclude self *args **kwargs
begin
call _not_support_combined_queries string exclude
return call _filter_or_exclude true args kwargs
end function | def exclude(self, *args, **kwargs):
self._not_support_combined_queries("exclude")
return self._filter_or_exclude(True, args, kwargs) | Python | nomic_cornstack_python_v1 |
function get_environment self
begin
call get_workspace
if environment_name in keys list ws
begin
set environment = get Environment ws environment_name
end
else
begin
set environment = call Environment environment_name
end
set environment = call _set_environment_properties environment
return environment
end function | def get_environment(self) -> Environment:
self.get_workspace()
if self.environment_name in Environment.list(self.ws).keys():
self.environment = Environment.get(self.ws, self.environment_name)
else:
self.environment = Environment(self.environment_name)
self.environ... | Python | nomic_cornstack_python_v1 |
function route self **options
begin
return call route keyword options
end function | def route(self, **options):
return self.app.route(**options) | Python | nomic_cornstack_python_v1 |
comment Did not get in the contest. The key insight is in the end, the optimal solution involves taking X books from the front of A and Y books from the front of B. The intermediate transitions from one stack to another do not matter in the big picture.
from sys import stdin
set tuple n m k = map int split read line st... | # Did not get in the contest. The key insight is in the end, the optimal solution involves taking X books from the front of A and Y books from the front of B. The intermediate transitions from one stack to another do not matter in the big picture.
from sys import stdin
n, m, k = map(int, stdin.readline().split())
... | Python | zaydzuhri_stack_edu_python |
function _setting self name default
begin
from django.conf import settings
set settings_dict = get attribute settings string REST_EMAIL_AUTH dict
return get settings_dict name default
end function | def _setting(self, name, default):
from django.conf import settings
settings_dict = getattr(settings, "REST_EMAIL_AUTH", {})
return settings_dict.get(name, default) | Python | nomic_cornstack_python_v1 |
function secondary_training_status_changed current_job_description prev_job_description
begin
set current_secondary_status_transitions = get current_job_description string SecondaryStatusTransitions
if current_secondary_status_transitions is none or length current_secondary_status_transitions == 0
begin
return false
en... | def secondary_training_status_changed(current_job_description, prev_job_description):
current_secondary_status_transitions = current_job_description.get("SecondaryStatusTransitions")
if (
current_secondary_status_transitions is None
or len(current_secondary_status_transitions) == 0
):
... | Python | nomic_cornstack_python_v1 |
function _get_links network_id template_id=none
begin
string Get all the links in a network
set extras = dict string types list ; string attributes list
set link_qry = options call noload string network
if template_id is not none
begin
set link_qry = filter link_id == id id == type_id template_id == template_id
end
s... | def _get_links(network_id, template_id=None):
"""
Get all the links in a network
"""
extras = {'types':[], 'attributes':[]}
link_qry = db.DBSession.query(Link).filter(
Link.network_id==network_id,
Link.status=='A').o... | Python | jtatman_500k |
function run self line
begin
set tuple input_ids input_mask segment_ids label_ids = call convert_line lower line label2id max_seq_length tokenizer
with call as_default as g
begin
with call as_default
begin
set feed_dict = dict input_ids_p input_ids ; input_mask_p input_mask ; segment_ids_p segment_ids ; label_ids_p lab... | def run(self, line):
input_ids, input_mask, segment_ids, label_ids = self.__class__.convert_line(line.lower(), self.label2id,
self.__class__.max_seq_length,
... | Python | nomic_cornstack_python_v1 |
function update_with_template_args args list_args=none
begin
if not get args string --template
begin
return
end
set list_args = list_args or list
set template_path = pop args string --template
if not exists path template_path
begin
raise call ArgumentError string File does not exist [-t | --template] = %s % template_p... | def update_with_template_args(args, list_args=None):
if not args.get('--template'):
return
list_args = list_args or []
template_path = args.pop('--template')
if not os.path.exists(template_path):
raise ArgumentError(
'File does not exist [-t | --template] = %s'
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Mon Dec 9 16:58:55 2019 @author: AhmadRam
import libtext as my
set fileteks = string /root/PycharmProject/PemrogamanTingkatLanjut/ramli/TAplaintext.txt
set pesan = call readTextFile fileteks
set kun = 10
set bit = list string 0 string 0 string 0 string 0 string 0 string 0... | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 9 16:58:55 2019
@author: AhmadRam
"""
import libtext as my
fileteks = '/root/PycharmProject/PemrogamanTingkatLanjut/ramli/TAplaintext.txt'
pesan = my.readTextFile(fileteks)
kun=10
bit=['0','0','0','0','0','0','0','0']
jmlbit=cypher=''
for ch in pesan:
bits = format(... | Python | zaydzuhri_stack_edu_python |
function to_str self
begin
return call pformat call to_dict
end function | def to_str(self):
return pprint.pformat(self.to_dict()) | Python | nomic_cornstack_python_v1 |
function naked_twins values
begin
comment display(values)
comment Find all instances of naked twins
set naked_twins = list
for unit in unitlist
begin
for box in unit
begin
if length values at box == 2
begin
for other_box in peers at box
begin
if values at box == values at other_box
begin
append naked_twins tuple box o... | def naked_twins(values):
#display(values)
# Find all instances of naked twins
naked_twins = []
for unit in unitlist:
for box in unit:
if len(values[box]) == 2:
for other_box in peers[box]:
if values[box] == values[other_box]:
... | Python | nomic_cornstack_python_v1 |
string Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. Example 1: Input: nums = [-4,-1,0,3,10] Output: [0,1,9,16,100] Explanation: After squaring, the array becomes [16,1,0,9,100]. After sorting, it becomes [0,1,9,16,100]. Example... | """
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Example 1:
Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].
Example ... | Python | zaydzuhri_stack_edu_python |
from xml.dom import minidom
comment 打开xml文件 打印元素节点
set dom = parse minidom string Class_info.xml
comment 获取文档对象的所有标签元素
set root = documentElement
comment 根标签名称
print nodeName
comment 根标签中的值
print nodeValue
comment 根标签类型 节点是元素节点返回1 是属性节点返回2
print nodeType | from xml.dom import minidom
#打开xml文件 打印元素节点
dom = minidom.parse('Class_info.xml')
root = dom.documentElement#获取文档对象的所有标签元素
print(root.nodeName)#根标签名称
print(root.nodeValue)#根标签中的值
print(root.nodeType)#根标签类型 节点是元素节点返回1 是属性节点返回2
| Python | zaydzuhri_stack_edu_python |
function reverse self
begin
call _handleReverseAction
end function | def reverse(self):
self._handleReverseAction() | Python | nomic_cornstack_python_v1 |
function run_command_with_code self cmd redirect_output=true check_exit_code=true
begin
if redirect_output
begin
set stdout = PIPE
end
else
begin
set stdout = none
end
set proc = popen cmd cwd=root stdout=stdout
set output = communicate proc at 0
if check_exit_code and returncode != 0
begin
call die string Command "%s"... | def run_command_with_code(self, cmd, redirect_output=True,
check_exit_code=True):
if redirect_output:
stdout = subprocess.PIPE
else:
stdout = None
proc = subprocess.Popen(cmd, cwd=self.root, stdout=stdout)
output = proc.commu... | Python | nomic_cornstack_python_v1 |
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.tokenize import sent_tokenize
from nltk.stem import PorterStemmer
function create_frequency_table text_string
begin
set stopWords = set call words string english
set words = call word_tokenize text_string
set ps = call PorterStemmer
set... | from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.tokenize import sent_tokenize
from nltk.stem import PorterStemmer
def create_frequency_table(text_string) -> dict:
stopWords = set(stopwords.words("english"))
words = word_tokenize(text_string)
ps = PorterStemmer()
... | Python | zaydzuhri_stack_edu_python |
comment 람다 표현식으로 함수 만들기
function plus_ten x
begin
return x + 10
end function
print call plus_ten 1
comment 람다 표현식을 인수로 사용하기
function plus_ten x
begin
return x + 10
end function
print list map plus_ten list 1 2 3
comment 람다 표현식에 조건부 표현식 사용하기
set a = list 1 2 3 4 5 6 7 8 9 10
print list map lambda x -> if expression x % ... | #람다 표현식으로 함수 만들기
def plus_ten(x):
return x + 10
print(plus_ten(1))
#람다 표현식을 인수로 사용하기
def plus_ten(x):
return x +10
print(list(map(plus_ten,[1,2,3])))
#람다 표현식에 조건부 표현식 사용하기
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(list(map(lambda x: str(x) if x % 3 == 0 else x, a)))
#map에 객체를 여러 개 넣기
a = [1,2,3,4,5]
b = [... | Python | zaydzuhri_stack_edu_python |
function save_model model model_filepath
begin
dump model open model_filepath string wb
end function
comment loaded_model = pickle.load(open(model_filepath, 'rb')) | def save_model(model, model_filepath):
pickle.dump(model, open(model_filepath, 'wb'))
#loaded_model = pickle.load(open(model_filepath, 'rb'))
| Python | nomic_cornstack_python_v1 |
class TreeNode
begin
function __init__ self val=0 left=none right=none
begin
set val = val
set left = left
set right = right
end function
end class
class Solution
begin
function addOneRow self root v d
begin
function addRow node depth isLeft
begin
if depth == d
begin
set newNode = call TreeNode v
if isLeft
begin
set le... | class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def addOneRow(self, root: TreeNode, v: int, d: int) -> TreeNode:
def addRow(node, depth, isLeft):
if depth == d:
newNo... | Python | zaydzuhri_stack_edu_python |
function preprocessing_text table
begin
comment Put everything in lowercase.
set table at string tweet = lower str
comment Replace rt indicating that was a retweet.
set table at string tweet = replace str string rt string
comment Replace occurences of mentioning @UserNames.
set table at string tweet = replace table at ... | def preprocessing_text(table):
# Put everything in lowercase.
table["tweet"] = table["tweet"].str.lower()
# Replace rt indicating that was a retweet.
table["tweet"] = table["tweet"].str.replace("rt", "")
# Replace occurences of mentioning @UserNames.
table["tweet"] = table["tweet"].replace(r"@\w... | Python | nomic_cornstack_python_v1 |
if l at 0 >= soma * 0.45 or l at 0 >= soma * 0.4 and l at 0 >= l at 1 + soma * 0.1
begin
print 1
end
else
begin
print 2
end | if l[0] >= soma*0.45 or (l[0] >= soma*0.4 and l[0] >= l[1]+soma*0.1):
print(1)
else:
print(2)
| Python | zaydzuhri_stack_edu_python |
function finalize self
begin
debug string finalize: %s _lockfile
call unlock unconditionally=true
end function | def finalize(self):
log.debug('finalize: %s', self._lockfile)
self.unlock(unconditionally=True) | Python | nomic_cornstack_python_v1 |
function findsubintervals t x
begin
set tuple k m = tuple length t length x
if k < 2
begin
return zeros m 1
end
else
begin
set j = call argsort
set i = call nonzero j >= k
set arr = array range 0 m
set arr = i - arr - 1
set arr = arr at 0
return arr
end
end function | def findsubintervals (t ,x):
k, m = len(t), len(x)
if k<2:
return zeros(m,1)
else:
j = concatenate([t, x]).argsort()
i = nonzero(j >= k)
arr = arange(0,m)
arr = i - arr - 1
arr = arr[0]
return arr | Python | nomic_cornstack_python_v1 |
from jackfrank.utils.txt_utils import reserve_chinese
from jackfrank.utils.txt_utils import read_name
function clear_txt list
begin
for i in range 10
begin
set name = list at i
set path = string ./t/ + string name + string .txt
set fp1 = open string ./coms/ + string name + string .txt string r encoding=string utf-8
set... | from jackfrank.utils.txt_utils import reserve_chinese
from jackfrank.utils.txt_utils import read_name
def clear_txt(list):
for i in range(10):
name = list[i]
path = './t/' + str(name) + '.txt'
fp1 = open('./coms/' + str(name) + '.txt','r',encoding='utf-8')
lines = fp1.readlines()
... | Python | zaydzuhri_stack_edu_python |
string 5*5 2차 배열에 무작위로 25개의 숫자로 초기화한 후, 25개의 각 요소에 대해서 그 요소와 이수한 요소와의 차의 절대값을 구하라. ex. n 2 n 6 7 8 n 12 n -> 12 25개 요소에 대해서 모두 조사하여 총합을 구하라.
string import random N = list(range(1, 26)) matrix = [] # 랜덤 1~25 매트릭스 작성 # for i in range(5): # list_i = [] # for j in range(5): # rdm = random.choice(N) # N.remove(rdm) # list_i... | '''
5*5 2차 배열에 무작위로 25개의 숫자로 초기화한 후,
25개의 각 요소에 대해서 그 요소와 이수한 요소와의 차의 절대값을 구하라.
ex.
n 2 n
6 7 8
n 12 n
-> 12
25개 요소에 대해서 모두 조사하여 총합을 구하라.
'''
'''
import random
N = list(range(1, 26))
matrix = []
# 랜덤 1~25 매트릭스 작성
# for i in range(5):
# list_i = []
# for j in range(5):
# rdm = random.choice(N)
# ... | Python | zaydzuhri_stack_edu_python |
function area self
begin
return x1 - x0 * y1 - y0
end function | def area(self):
return (self.x1 - self.x0) * (self.y1 - self.y0) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
set __author__ = string asim
comment myList = list()
comment print myList
comment myCollection = dict()
comment print myCollection
comment myCollection[1] = 'World'
comment print myCollection
comment print len(myCollection)
comment myCollection1 = {1:"Hello Wor... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'asim'
# myList = list()
# print myList
#
# myCollection = dict()
#
# print myCollection
# myCollection[1] = 'World'
# print myCollection
# print len(myCollection)
#
# myCollection1 = {1:"Hello World", 2 : "HOw are you"}
# print "My Second Colleciton", myCollec... | Python | zaydzuhri_stack_edu_python |
import boto3
import pandas as pd
import numpy as np
import json
import psycopg2 as pg
from io import StringIO
import helpers as h
function get_objects bucket_name
begin
string get all objects from s3 bucket
set s3_resource = call resource string s3
set bucket = call Bucket bucket_name
set objects = list
for obj in all... | import boto3
import pandas as pd
import numpy as np
import json
import psycopg2 as pg
from io import StringIO
import helpers as h
def get_objects(bucket_name):
'''
get all objects from s3 bucket
'''
s3_resource = boto3.resource('s3')
bucket = s3_resource.Bucket(bucket_name)
objects = []
f... | Python | zaydzuhri_stack_edu_python |
from collections import Counter
function iter_layer img width height
begin
for n in range length img // width * height
begin
yield img at slice n * width * height : n + 1 * width * height :
end
end function
function first_non_two s
begin
for ch in s
begin
if ch != string 2
begin
return ch
end
end
return string 2
end f... | from collections import Counter
def iter_layer(img, width, height):
for n in range(len(img) // (width * height)):
yield img[n * width * height: (n + 1) * width * height]
def first_non_two(s):
for ch in s:
if ch != '2':
return ch
return '2'
IMG = open('./data/input.txt', 'r').r... | Python | zaydzuhri_stack_edu_python |
function default_group_visibility self
begin
return get pulumi self string default_group_visibility
end function | def default_group_visibility(self) -> pulumi.Output[str]:
return pulumi.get(self, "default_group_visibility") | Python | nomic_cornstack_python_v1 |
function get self key
begin
try
begin
set hashed_key = call _hash_key key
set kvp = list at hashed_key
if list at hashed_key is none
begin
print string That package ID does NOT exist
return false
end
else
begin
return kvp at 1
end
end
except IndexError
begin
print string That package ID does NOT exist
return false
end
... | def get(self, key):
try:
hashed_key = self._hash_key(key)
kvp = self.list[hashed_key]
if self.list[hashed_key] is None:
print('\nThat package ID does NOT exist')
return False
else:
return kvp[1]
except Index... | Python | nomic_cornstack_python_v1 |
from typing import List
class Solution
begin
function wiggleSort self nums
begin
string Do not return anything, modify nums in-place instead.
function swap nums i j
begin
set t = nums at i
set nums at i = nums at j
set nums at j = t
end function
for tuple i num in enumerate nums
begin
if i % 2 == 1 and nums at i - 1 > ... | from typing import List
class Solution:
def wiggleSort(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
def swap(nums, i, j):
t = nums[i]
nums[i] = nums[j]
nums[j] = t
for i, num in enumerate(nums):
if i % 2 == 1 and nums[i - ... | Python | zaydzuhri_stack_edu_python |
comment Given a digit string, return all possible letter combinations that the number could represent.
comment A mapping of digit to letters (just like on the telephone buttons) is given below.
comment Input:Digit string "23"
comment Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
class Solution
begin
f... | # Given a digit string, return all possible letter combinations that the number could represent.
# A mapping of digit to letters (just like on the telephone buttons) is given below.
# Input:Digit string "23"
# Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
class Solution:
def letterCombinations(... | Python | zaydzuhri_stack_edu_python |
function validate_listeners self
begin
string Validates that some listeners are actually registered
if exception
begin
comment pylint: disable=raising-bad-type
raise exception
end
set listeners = __listeners_for_thread
if not sum generator expression length l for l in listeners
begin
raise call ValueError string No act... | def validate_listeners(self):
"""Validates that some listeners are actually registered"""
if self.exception:
# pylint: disable=raising-bad-type
raise self.exception
listeners = self.__listeners_for_thread
if not sum(len(l) for l in listeners):
raise ... | Python | jtatman_500k |
function num_blocks_above_holes board
begin
set c = 0
for tuple hole_x hole_y in call _holes_in_board board
begin
for y in range hole_y - 1 0 - 1
begin
if call _is_block board at y at hole_x
begin
set c = c + 1
end
else
begin
break
end
end
end
return c
end function | def num_blocks_above_holes(board):
c = 0
for hole_x, hole_y in _holes_in_board(board):
for y in range(hole_y-1, 0, -1):
if _is_block(board[y][hole_x]):
c += 1
else:
break
return c | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Tue Jun 2 07:45:31 2020 @author: jp
from scipy import *
from numpy import *
from numpy.linalg import norm
from matplotlib.pyplot import plot
function smooth x a0 a1 a2
begin
set y = a0 + a1 * sin a2 * x
return y
end function
function db x q0 ... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 2 07:45:31 2020
@author: jp
"""
from scipy import *
from numpy import *
from numpy.linalg import norm
from matplotlib.pyplot import plot
def smooth(x,a0,a1,a2):
y = a0 + a1*sin(a2*x)
return y
def db(x,q0,q1):
n = len(x)
y = ze... | Python | zaydzuhri_stack_edu_python |
function accuracy output target topk=tuple 1
begin
set maxk = max topk
set batch_size = size target 0
set tuple _ pred = call topk maxk 1 true true
set pred = t dist
set correct = call eq call expand_as pred
set res = list
for k in topk
begin
set correct_k = sum 0
append res call mul_ 100.0 / batch_size
end
return res... | def accuracy(output, target, topk=(1,)):
maxk = max(topk)
batch_size = target.size(0)
_, pred = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.reshape(1, -1).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:k].reshape(-1).float().sum(0)
... | Python | nomic_cornstack_python_v1 |
function buildSettlement self player node_index
begin
string Checks to perform: 1) Node isn't occupied 2) Player has resources OR game is in setup phase 3) Player has enough settlement pieces to place 4) Node is at least two edges away from another city 5) Node is connected to a relevant road OR game is in setup phase ... | def buildSettlement(self, player, node_index):
"""
Checks to perform:
1) Node isn't occupied
2) Player has resources OR game is in setup phase
3) Player has enough settlement pieces to place
4) Node is at least two edges away from another city
5) Node is... | Python | nomic_cornstack_python_v1 |
function ptp_startup_two_port e grandmaster user
begin
set slave_seq = list
if grandmaster and call get_avb_id user e != call get_avb_id user grandmaster
begin
comment The length of time to sync will depend on the total number of endpoints
set sync_lock_time = 3 * length call get_all
set slave_seq = list call Sequence... | def ptp_startup_two_port(e, grandmaster, user):
slave_seq = []
if grandmaster and (endpoints.get_avb_id(user, e) != endpoints.get_avb_id(user, grandmaster)):
# The length of time to sync will depend on the total number of endpoints
sync_lock_time = 3 * len(endpoints.get_all())
slave_seq = [Sequence(
... | Python | nomic_cornstack_python_v1 |
import random
import numpy as np
from mpl_toolkits import mplot3d
from data_manager import *
from Models.adaline import *
from Dataset.datasets import Datasets
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
call interactive true
comment ['GTK3Agg', 'GTK3Cairo', 'MacOSX', 'nbAg... | import random
import numpy as np
from mpl_toolkits import mplot3d
from data_manager import *
from Models.adaline import *
from Dataset.datasets import Datasets
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib
matplotlib.interactive(True)
# ['GTK3Agg', 'GTK3Cairo', 'MacOSX', 'nb... | Python | zaydzuhri_stack_edu_python |
function get_rho_and_T P Pc rhoc Tc gamma=default_gamma
begin
comment fill these in
set rho = rhoc * P / Pc ^ 1 / gamma
set T = Tc * P / Pc ^ 1.0 - 1.0 / gamma
return tuple rho T
end function | def get_rho_and_T(P,Pc,rhoc,Tc,gamma=default_gamma):
# fill these in
rho = rhoc*(P/Pc)**(1/gamma)
T = Tc*(P/Pc)**(1.0-(1.0/gamma))
return rho,T | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding: utf-8 -*-
string © Copyright 2015-2016, 3D Robotics. simple_goto.py: GUIDED mode "simple goto" example (Copter Only) Demonstrates how to arm and takeoff in Copter and how to navigate to points using Vehicle.simple_goto. Full documentation is provided at http://python.dro... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
© Copyright 2015-2016, 3D Robotics.
simple_goto.py: GUIDED mode "simple goto" example (Copter Only)
Demonstrates how to arm and takeoff in Copter and how to navigate to points using Vehicle.simple_goto.
Full documentation is provided at http://python.dronekit.io/exam... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Oct 10 11:25:15 2017 Holds the various functions for processsing the game @author: David Butler
class gameBoard
begin
function __init__ self
begin
set board = list list string string string list string string string list string string string
set turnCount = 0... | # -*- coding: utf-8 -*-
"""
Created on Tue Oct 10 11:25:15 2017
Holds the various functions for processsing the game
@author: David Butler
"""
class gameBoard:
def __init__(self):
self.board = [[' ', ' ', ' '],[' ', ' ', ' '],[' ', ' ', ' ']]
self.turnCount = 0;
self.player = 'x'
def updateBoard(self, x, y):... | Python | zaydzuhri_stack_edu_python |
function topics self
begin
return call Topics self
end function | def topics(self):
return topics.Topics(self) | Python | nomic_cornstack_python_v1 |
function strip_cmd_prefix self key all_keys
begin
if key and key at 0 in CMD_IGNORE_PREFIXES and key at slice 1 : : not in all_keys
begin
comment filter out e.g. `@` prefixes from display if there is duplicate
comment with the prefix in the set (such as @open/open)
return key at slice 1 : :
end
return key
end funct... | def strip_cmd_prefix(self, key, all_keys):
if key and key[0] in CMD_IGNORE_PREFIXES and key[1:] not in all_keys:
# filter out e.g. `@` prefixes from display if there is duplicate
# with the prefix in the set (such as @open/open)
return key[1:]
return key | Python | nomic_cornstack_python_v1 |
import json
import requests
import csv
string Contains functions that manipulate csv in any given way
comment check if symbol already exists in csv
function symbol_exists_in_csv stock_symbol
begin
with open string stock_info.csv string r as f
begin
set csvreader = reader f delimiter=string ,
for row in csvreader
begin
... | import json
import requests
import csv
"""
Contains functions that manipulate csv in any given way
"""
#check if symbol already exists in csv
def symbol_exists_in_csv(stock_symbol):
with open('stock_info.csv', "r") as f:
csvreader = csv.reader(f, delimiter=",")
for row in csvreader:
... | Python | zaydzuhri_stack_edu_python |
function update self resource_group_name service_name gateway_id if_match location_data=none description=none custom_headers=none raw=false **operation_config
begin
set parameters = call GatewayContract location_data=location_data description=description
comment Construct URL
set url = metadata at string url
set path_f... | def update(
self, resource_group_name, service_name, gateway_id, if_match, location_data=None, description=None, custom_headers=None, raw=False, **operation_config):
parameters = models.GatewayContract(location_data=location_data, description=description)
# Construct URL
url = self.... | Python | nomic_cornstack_python_v1 |
function macbytes2str mac
begin
return string %02x:%02x:%02x:%02x:%02x:%02x % call unpack string BBBBBB mac at slice : 6 :
end function | def macbytes2str(mac: bytes) -> str:
return "%02x:%02x:%02x:%02x:%02x:%02x" % struct.unpack("BBBBBB", mac[:6]) | Python | nomic_cornstack_python_v1 |
function write_shadhorc prefix shadho_dir
begin
comment Set up the default config values
set default_config = dict string global dict string wrapper string shadho_worker.py ; string utils string shadho_utils.py ; string output string out.tar.gz ; string result_file string performance.json ; string optimize string loss ... | def write_shadhorc(prefix, shadho_dir):
# Set up the default config values
default_config = {
'global': {
'wrapper': 'shadho_worker.py',
'utils': 'shadho_utils.py',
'output': 'out.tar.gz',
'result_file': 'performance.json',
'optimize': 'loss',
... | Python | nomic_cornstack_python_v1 |
function pwm_scan_all self fa cutoff=0.9 nreport=50 scan_rc=true
begin
set c = call pwm_min_score + call pwm_max_score - call pwm_min_score * cutoff
set pwm = pwm
set matches = dict
for tuple name seq in items fa
begin
set matches at name = list
set result = call pfmscan upper seq pwm c nreport scan_rc
for tuple scor... | def pwm_scan_all(self, fa, cutoff=0.9, nreport=50, scan_rc=True):
c = self.pwm_min_score() + (self.pwm_max_score() - self.pwm_min_score()) * cutoff
pwm = self.pwm
matches = {}
for name, seq in fa.items():
matches[name] = []
result = pfmscan(seq.upper(), p... | Python | nomic_cornstack_python_v1 |
function forced_checkout_with_faux_obstructions sbox
begin
comment Make a local tree that partially obstructs the paths coming from the
comment repos but has no true differences.
set expected_output = call make_local_tree sbox false false
set expected_wc = copy greek_state
call run_and_verify_checkout repo_url wc_dir e... | def forced_checkout_with_faux_obstructions(sbox):
# Make a local tree that partially obstructs the paths coming from the
# repos but has no true differences.
expected_output = make_local_tree(sbox, False, False)
expected_wc = svntest.main.greek_state.copy()
svntest.actions.run_and_verify_checkout(sbox.repo... | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
comment In[1]:
import pandas as pd
set df = call DataFrame list list 1 2 list 4 5 list 7 8 index=list string cobra string viper string sidewinder columns=list string max_speed string shield
df
comment In[2]:
comment df.iloc[0]
loc at string viper
comment In[6]:
loc at 0
comment In[5]:
loc at list ... | # coding: utf-8
# In[1]:
import pandas as pd
df=pd.DataFrame([[1,2],[4,5],[7,8]],
index=['cobra','viper','sidewinder'],
columns=['max_speed','shield'])
df
# In[2]:
df.loc['viper'] # df.iloc[0]
# In[6]:
df.loc[0]
# In[5]:
df.loc[['viper', 'sidewinder']]
# In[7]:
df.... | Python | zaydzuhri_stack_edu_python |
function WGM_freq R r L T pol q=1 p=0 MgO=0 MgO_th=5.0 n=nLNO1 E=0
begin
import math
comment from WGM_lib import nLNO1
from scipy.special import ai_zeros
set q = q - 1
comment redefine the rim radius to spheroid semi-axis
set r = square root r * R
comment >0
set AiRoots = - call ai_zeros 40 at 0
set geom_term = 2 * p *... | def WGM_freq(R,r,L,T,pol,q = 1,p = 0,MgO=0,MgO_th=5.0,n = nLNO1,E = 0):
import math
#from WGM_lib import nLNO1
from scipy.special import ai_zeros
q -= 1
r = math.sqrt(r*R) # redefine the rim radius to spheroid semi-axis
AiRoots = -ai_zeros(40)[0] # >0
geom_term = (2*p*(R-r)+R)... | Python | nomic_cornstack_python_v1 |
function decide_asset_ratios self
begin
for position in positions
begin
if position at string is_holding and call _check_signal position at string sell_signal
begin
set position at string is_holding = false
add assets_to_trade position at string ticker
try
begin
set desired_ratios at position at string ticker = desired... | def decide_asset_ratios(self):
for position in self.positions:
if (position['is_holding']
and self._check_signal(position['sell_signal'])):
position['is_holding'] = False
self.assets_to_trade.add(position['ticker'])
try:
... | Python | nomic_cornstack_python_v1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.