code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function mod_config
begin
comment Loading in configuration data from either basic_config or override_config
set config_data = call load_config
comment A loop to modify values in the configuration file
set input_check = false
while input_check == false
begin
print string Enter "q" to exit modifying the configuration
com... | def mod_config():
## Loading in configuration data from either basic_config or override_config
config_data = load_config()
## A loop to modify values in the configuration file
input_check = False
while input_check == False:
print("\nEnter \"q\" to exit modifying the configuration")
... | Python | nomic_cornstack_python_v1 |
function import_datapackage filedata dry_run=true all_data=false
begin
set ext = lower split filename string . at - 1
if ext not in list string json
begin
return dict string errors list string Invalid format (allowed: JSON)
end
with temporary directory as tmpdir
begin
set filepath = join path tmpdir call secure_filenam... | def import_datapackage(filedata, dry_run=True, all_data=False):
ext = filedata.filename.split('.')[-1].lower()
if ext not in ['json']:
return {'errors': ['Invalid format (allowed: JSON)']}
with tempfile.TemporaryDirectory() as tmpdir:
filepath = path.join(tmpdir, secure_filename(filedata.fil... | Python | nomic_cornstack_python_v1 |
function test_update_iam_permission self
begin
pass
end function | def test_update_iam_permission(self):
pass | Python | nomic_cornstack_python_v1 |
comment !/usr/local/adyen/python3/bin/python3
import json , os , sys , datetime , configparser
import time , logging
comment HMAC
import base64 , binascii , hmac , hashlib
from collections import OrderedDict
comment HTTP parsing
from urllib.parse import parse_qs , urlencode
from urllib.request import Request , urlopen
... | #!/usr/local/adyen/python3/bin/python3
import json, os, sys, datetime, configparser
import time, logging
# HMAC
import base64, binascii, hmac, hashlib
from collections import OrderedDict
# HTTP parsing
from urllib.parse import parse_qs, urlencode
from urllib.request import Request, urlopen
from urllib.error import HT... | Python | zaydzuhri_stack_edu_python |
from userSystem.models import *
from userSystem.cache.datacache import DataCache2
from userSystem.serialzer import PermissionsSerializer
function checkUserNmaeTool userName
begin
string 查询 user_name -> user_id 的缓存 :param userName: :return:
set cacheTool = call DataCache2 cacheName=string user_id_cache timeout=60 * 60 *... | from userSystem.models import *
from userSystem.cache.datacache import DataCache2
from userSystem.serialzer import PermissionsSerializer
def checkUserNmaeTool(userName: str):
"""
查询 user_name -> user_id 的缓存
:param userName:
:return:
"""
cacheTool = DataCache2(cacheName='user_id_cache', timeout... | Python | zaydzuhri_stack_edu_python |
import re
import networkx as nx
import numpy as np
from collections import defaultdict , Counter
from operator import itemgetter
set INPUT_FILE_PATH = string input.txt
set MAX_SUMMARIZE_SENTENCES = 2
set START_WORD_MAX_POSITION = 10
set MAX_GAP = 3
set MIN_REDUNDANCY = 3
set DO_COLLAPSE = true
function create_graph
beg... | import re
import networkx as nx
import numpy as np
from collections import defaultdict, Counter
from operator import itemgetter
INPUT_FILE_PATH = 'input.txt'
MAX_SUMMARIZE_SENTENCES = 2
START_WORD_MAX_POSITION = 10
MAX_GAP = 3
MIN_REDUNDANCY = 3
DO_COLLAPSE = True
def create_graph():
edges = []
nodes_pri = d... | Python | zaydzuhri_stack_edu_python |
function iterator self dirs
begin
comment add files in reverse order because we pop entries
set l_queue = list comprehension tuple string d encode u_dir string iso-8859-1 for u_dir in reversed dirs
if params at string old_cleanup
begin
call prepare_files list dirs
end
function result
begin
string Returns iterator's res... | def iterator(self, dirs):
# add files in reverse order because we pop entries
l_queue = [('d', u_dir.encode('iso-8859-1')) for u_dir in reversed(dirs)]
if self.params['old_cleanup']:
self.__ftpdb.prepare_files(list(dirs))
def result():
"""Returns iterator's res... | Python | nomic_cornstack_python_v1 |
function test_log_extra_no_func test_df
begin
with raises ValueError as e
begin
decorator call log_step_extra
function do_nothing df *args **kwargs
begin
return df
end function
call pipe do_nothing
assert string log_function in string e
end
end function | def test_log_extra_no_func(test_df):
with pytest.raises(ValueError) as e:
@log_step_extra()
def do_nothing(df, *args, **kwargs):
return df
test_df.pipe(do_nothing)
assert "log_function" in str(e) | Python | nomic_cornstack_python_v1 |
function solve_2x2 matrix rhs
begin
call _validate_matrix_shape matrix tuple 2 2
set tuple a b = matrix at 0
set tuple c d = matrix at 1
set tuple e f = rhs
set inv_factor = call det_2x2 matrix
return list call map_structure divide_no_nan call det_2x2 list list e b list f d inv_factor call map_structure divide_no_nan c... | def solve_2x2(matrix: FieldMatrix,
rhs: Fields) -> OutputFields:
_validate_matrix_shape(matrix, (2, 2))
a, b = matrix[0]
c, d = matrix[1]
e, f = rhs
inv_factor = det_2x2(matrix)
return [
tf.nest.map_structure(tf.math.divide_no_nan, det_2x2([
[e, b],
[f, d],
]... | Python | nomic_cornstack_python_v1 |
function has_unique_together_changed self old_model_sig
begin
set old_unique_together = unique_together
set new_unique_together = unique_together
return old_unique_together != new_unique_together or old_unique_together or new_unique_together and _unique_together_applied is not _unique_together_applied
end function | def has_unique_together_changed(self, old_model_sig):
old_unique_together = old_model_sig.unique_together
new_unique_together = self.unique_together
return (old_unique_together != new_unique_together or
((old_unique_together or new_unique_together) and
old_model... | Python | nomic_cornstack_python_v1 |
function build_tree lines
begin
set key_regex = compile string (?P<key_val>^.*) bags contain(?P<contents>.*$)
set values_regex = compile string (?P<count>\d) (?P<color>.+?(?= bag))
set bag_map = dict
for line in lines
begin
set match = match line
set key = match at string key_val
set bag_map at key = dict
set content... | def build_tree(lines: []) -> {}:
key_regex = re.compile(r"(?P<key_val>^.*) bags contain(?P<contents>.*$)")
values_regex = re.compile(r"(?P<count>\d) (?P<color>.+?(?= bag))")
bag_map = {}
for line in lines:
match = key_regex.match(line)
key = match['key_val']
bag_map[key] = {}
... | Python | nomic_cornstack_python_v1 |
function contains self Vobj
begin
try
begin
comment assume we were passed a point
if call is_vector
begin
return call _is_nonneg eval Vobj
end
end
except AttributeError
begin
pass
end
if call is_line
begin
return call _is_zero eval Vobj
end
else
begin
return call _is_nonneg eval Vobj
end
end function | def contains(self, Vobj):
try:
if Vobj.is_vector(): # assume we were passed a point
return self.polyhedron()._is_nonneg( self.eval(Vobj) )
except AttributeError:
pass
if Vobj.is_line():
return self.polyhedron()._is_zero( self.eval(Vobj) )
... | Python | nomic_cornstack_python_v1 |
function all_game_logs player_ids season season_type
begin
set df = concat list comprehension call game_logs pid season season_type for pid in player_ids
set df at string SEASON_ID = call to_numeric df at string SEASON_ID errors=string coerce
set df at string GAME_DATE = call to_datetime df at string GAME_DATE
set colu... | def all_game_logs(player_ids, season, season_type):
df = pd.concat( [game_logs(pid, season, season_type) for pid in player_ids] )
df['SEASON_ID'] = pd.to_numeric(df['SEASON_ID'], errors='coerce')
df['GAME_DATE'] = pd.to_datetime(df['GAME_DATE'])
df.columns = df.columns.str.lower()
df.drop('video_a... | Python | nomic_cornstack_python_v1 |
function makeAggregateNTasksGrid filelist intensify=false
begin
if intensify
begin
set data = call loadAggregateGridData filelist string nTasks-intensify
end
else
begin
set data = call loadAggregateGridData filelist string nTasks
end
return call colorGrid data
end function | def makeAggregateNTasksGrid(filelist, intensify=False):
if intensify:
data = loadAggregateGridData(filelist, "nTasks-intensify")
else:
data = loadAggregateGridData(filelist, "nTasks")
return colorGrid(data) | Python | nomic_cornstack_python_v1 |
string 生成斐波拉切数列 version:0.1 author:小雨 date:2019.09.19
function fib n
begin
assert n > 0
if n <= 2
begin
return n
end
else
begin
return call fib n - 1 + call fib n - 2
end
end function
for i in range 1 20
begin
print call fib i end=string
end | '''
生成斐波拉切数列
version:0.1
author:小雨
date:2019.09.19
'''
def fib(n):
assert n > 0
if(n <= 2):
return n
else:
return fib(n - 1) + fib(n - 2)
for i in range(1,20):
print(fib(i),end='\t') | Python | zaydzuhri_stack_edu_python |
function chunk self rdd
begin
set tuple kmask vmask slices = tuple mask mask slices
set labeled_slices = list product *[list(enumerate(s)) for s in slices]
set scheme = list comprehension list zip *s for s in labeled_slices
function _chunk record
begin
set tuple k v = tuple record at 0 record at 1
set k = call asarray ... | def chunk(self, rdd):
kmask, vmask, slices = self.key.mask, self.value.mask, self.slices
labeled_slices = list(product(*[list(enumerate(s)) for s in slices]))
scheme = [list(zip(*s)) for s in labeled_slices]
def _chunk(record):
k, v = record[0], record[1]
k = as... | Python | nomic_cornstack_python_v1 |
import json
from model.tariff import Tariff
from model.user import User
from model.ride import Ride
from model.car import Car
from model.invoice import Invoice
function main
begin
call create name=string Базовый description=string Бронирование: Бесплатно Аренда: 8 Р/мин Ожидание: 2.5 Р/мин
with open string fixture/user... | import json
from model.tariff import Tariff
from model.user import User
from model.ride import Ride
from model.car import Car
from model.invoice import Invoice
def main():
Tariff.create(name='Базовый',
description="Бронирование: Бесплатно \nАренда: 8 Р/мин\nОжидание: 2.5 Р/мин")
with open(... | Python | zaydzuhri_stack_edu_python |
function __giveSem self
begin
if call activeCount > 1
begin
global _logSemList
release _logSemList at call getLogFile
end
end function | def __giveSem(self):
if (threading.activeCount() > 1):
global _logSemList
_logSemList[self.getLogFile()].release() | Python | nomic_cornstack_python_v1 |
comment readlines() wczytuje linijki jako elementy listy
set linijki = read lines plik
print linijki
print linijki at 0
close plik | # readlines() wczytuje linijki jako elementy listy
linijki = plik.readlines()
print(linijki)
print(linijki[0])
plik.close()
| Python | zaydzuhri_stack_edu_python |
import os
from tkinter import *
from tkinter import filedialog
import file_precheck
set WEBBROWSER = right strip read lines open string config/config.txt at 1
set xsize = 800
set ysize = 300
function add_file
begin
set directory = call askopenfilenames
for i in directory
begin
insert box END i
end
end function
function... | import os
from tkinter import *
from tkinter import filedialog
import file_precheck
WEBBROWSER = open('config/config.txt').readlines()[1].rstrip()
xsize = 800
ysize = 300
def add_file():
directory = filedialog.askopenfilenames()
for i in directory:
box.insert(END, i)
def remove_file():
try:
... | Python | zaydzuhri_stack_edu_python |
import sympy as sp
function main
begin
global Roots
set Roots = list
comment We need a list to store the roots we've fonud, and it needs to be a global variable.
comment First, use Bisection Method.
print string Bisection Method:
if type call Bisection == string list
begin
comment Bisection() will return a list when i... | import sympy as sp
def main():
global Roots
Roots = []
# We need a list to store the roots we've fonud, and it needs to be a global variable.
# First, use Bisection Method.
print('Bisection Method:')
if type(Bisection()) == 'list':
# Bisection() will return a list when it fin... | Python | zaydzuhri_stack_edu_python |
function fusion_api_create_network_set self body api=none headers=none
begin
return call create body api headers
end function | def fusion_api_create_network_set(self, body, api=None, headers=None):
return self.network_set.create(body, api, headers) | Python | nomic_cornstack_python_v1 |
function test_main_exit_convert_type self mock_convert_type mock_module mock_client
begin
set PARAMS_FOR_PRESENT = dict string storage_system_ip string 192.168.0.1 ; string storage_system_name string 3PAR ; string storage_system_username string USER ; string storage_system_password string PASS ; string volume_name stri... | def test_main_exit_convert_type(self, mock_convert_type, mock_module, mock_client):
PARAMS_FOR_PRESENT = {
'storage_system_ip': '192.168.0.1',
'storage_system_name': '3PAR',
'storage_system_username': 'USER',
'storage_system_password': 'PASS',
'volume_... | Python | nomic_cornstack_python_v1 |
comment Given a sorted array of numbers, find if a given number ‘key’ is present in the array.
comment Though we know that the array is sorted, we don’t know if it’s sorted in ascending or descending order.
comment You should assume that the array can have duplicates.
comment Write a function to return the index of the... | # Given a sorted array of numbers, find if a given number ‘key’ is present in the array.
# Though we know that the array is sorted, we don’t know if it’s sorted in ascending or descending order.
# You should assume that the array can have duplicates.
# Write a function to return the index of the ‘key’ if it is present ... | Python | zaydzuhri_stack_edu_python |
function shift_selection_right local_state
begin
set tuple px py pt = call get_visual_anchors
set tuple nx ny nt = call get_page_state
set td = length c_map at string Tab
set tuple start end = tuple tuple py + pt ny + nt tuple ny + nt py + pt at ny + nt < py + pt
for n in range start end + 1
begin
set l = call get_line... | def shift_selection_right(local_state):
px, py, pt = local_state.get_visual_anchors()
nx, ny, nt = local_state.get_page_state()
td = len(c_map['Tab'])
start, end = (
(py + pt, ny + nt), (ny + nt, py + pt))[(ny + nt) < (py + pt)]
for n in range(start, end + 1):
l = local_stat... | Python | nomic_cornstack_python_v1 |
import inspect
import sha
class PatchException extends Exception
begin
pass
end class
function verify target *signatures
begin
set source = get source target
set signature = hex digest call new source
if signature not in signatures
begin
raise call PatchException string %s is not a valid signature for %s % tuple signat... | import inspect
import sha
class PatchException(Exception):
pass
def verify(target, *signatures):
source = inspect.getsource(target)
signature = sha.new(source).hexdigest()
if signature not in signatures:
raise PatchException(
"%s is not a valid signature for %s" % (signature, targ... | Python | zaydzuhri_stack_edu_python |
if x < 0 and y < 0
begin
if absolute x < absolute y
begin
print absolute x - y + 2
end
else
begin
print absolute x - y
end
end
else
if x > 0 and y > 0
begin
if absolute x > absolute y
begin
print x - y + 2
end
else
begin
print y - x
end
end
else
if x < 0 and y > 0
begin
print absolute y + x + 1
end
else
if x > 0 and y ... | if x < 0 and y < 0:
if abs(x) < abs(y):
print(abs(x-y)+2)
else:
print(abs(x-y))
elif x > 0 and y > 0:
if abs(x) > abs(y):
print(x-y+2)
else:
print(y-x)
elif x < 0 and y > 0:
print(abs(y+x)+1)
elif x > 0 and y < 0:
print(abs(y+x)+1)
elif x > 0 and y == 0:
prin... | Python | zaydzuhri_stack_edu_python |
function translate_rule pfilter **fields
begin
comment Load existing or create new rule
if fields at string id or fields at string id == 0
begin
set ruleset = call get_ruleset
set rule = rules at fields at string id
end
else
begin
set rule = call PFRule
end
comment Set action attribute
if fields at string action == str... | def translate_rule(pfilter, **fields):
# Load existing or create new rule
if fields['id'] or fields['id'] == 0:
ruleset = pfilter.get_ruleset()
rule = ruleset.rules[fields['id']]
else:
rule = pf.PFRule()
# Set action attribute
if fields['action'] == 'pass':
rule.act... | Python | nomic_cornstack_python_v1 |
comment list of dictionaries
set mattan = dict string name string Mattan ; string height 70 ; string shoe size 10.5 ; string hair string Brown ; string eyes string Brown ; string favorite movies list string Pulp Fiction string Magnolia string The Royal Tenenbaums
set chris = dict string name string Chris ; string heigh... | # list of dictionaries
mattan = {'name': 'Mattan',
'height': 70,
'shoe size': 10.5,
'hair': 'Brown',
'eyes': 'Brown',
'favorite movies': ['Pulp Fiction',
'Magnolia',
'The Royal Tenenbaums']}
chris = {'name': ... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
comment Author:Brent
comment Date :2020/6/13 4:14 PM
comment Tool :PyCharm
comment Describe :给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。
comment 说明:
comment 初始化 nums1 和 nums2 的元素数量分别为 m 和 n 。
comment 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
comment 示例:
comment 输入:
co... | # coding: utf-8
# Author:Brent
# Date :2020/6/13 4:14 PM
# Tool :PyCharm
# Describe :给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。
#
#
#
# 说明:
#
# 初始化 nums1 和 nums2 的元素数量分别为 m 和 n 。
# 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。
#
#
# 示例:
#
# 输入:
# nums1 = [1,2,3,0,0,0], m = 3
# nums2 = [2,... | Python | zaydzuhri_stack_edu_python |
function test_reactor_thread_disallowed self
begin
patch threadable string isInIOThread lambda -> true
set f = call make_wrapped_function
assert raises RuntimeError f none
end function | def test_reactor_thread_disallowed(self):
self.patch(threadable, "isInIOThread", lambda: True)
f = self.make_wrapped_function()
self.assertRaises(RuntimeError, f, None) | Python | nomic_cornstack_python_v1 |
import pickle as pickle
import os
import pandas as pd
import torch
comment convert to torch Dataset
class RE_Dataset extends Dataset
begin
function __init__ self tokenized_dataset labels
begin
set tokenized_dataset = tokenized_dataset
set labels = labels
end function
function __getitem__ self idx
begin
set item = dicti... | import pickle as pickle
import os
import pandas as pd
import torch
# convert to torch Dataset
class RE_Dataset(torch.utils.data.Dataset):
def __init__(self, tokenized_dataset, labels):
self.tokenized_dataset = tokenized_dataset
self.labels = labels
def __getitem__(self, idx):
... | Python | zaydzuhri_stack_edu_python |
function is_scalene self
begin
if not call is_isosceles
begin
return true
end
else
begin
return false
end
end function | def is_scalene( self ):
if not self.is_isosceles():
return True
else:
return False | Python | nomic_cornstack_python_v1 |
function get_random_secret_key
begin
set chars = string abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)
return call get_random_string 50 chars
end function | def get_random_secret_key():
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
return get_random_string(50, chars) | Python | nomic_cornstack_python_v1 |
function ICreatePlaneAtSurface2 self InterIndex=defaultNamedNotOptArg ProjOpt=defaultNamedNotOptArg ReverseDir=defaultNamedNotOptArg NormalPlane=defaultNamedNotOptArg Angle=defaultNamedNotOptArg
begin
set ret = call InvokeTypes 66135 LCID 1 tuple 9 0 tuple tuple 3 1 tuple 11 1 tuple 11 1 tuple 11 1 tuple 5 1 InterIndex... | def ICreatePlaneAtSurface2(self, InterIndex=defaultNamedNotOptArg, ProjOpt=defaultNamedNotOptArg, ReverseDir=defaultNamedNotOptArg, NormalPlane=defaultNamedNotOptArg
, Angle=defaultNamedNotOptArg):
ret = self._oleobj_.InvokeTypes(66135, LCID, 1, (9, 0), ((3, 1), (11, 1), (11, 1), (11, 1), (5, 1)),InterIndex
, P... | Python | nomic_cornstack_python_v1 |
function run self verbose=false
begin
if verbose
begin
from sage.combinat.rigged_configurations.tensor_product_kr_tableaux_element import TensorProductOfKirillovReshetikhinTableauxElement
end
for cur_crystal in reversed tp_krt
begin
set r = call r
comment Check if it is a spinor
if r == n
begin
comment Perform the spin... | def run(self, verbose=False):
if verbose:
from sage.combinat.rigged_configurations.tensor_product_kr_tableaux_element \
import TensorProductOfKirillovReshetikhinTableauxElement
for cur_crystal in reversed(self.tp_krt):
r = cur_crystal.parent().r()
# Ch... | Python | nomic_cornstack_python_v1 |
function to_json_string list_dictionaries
begin
if list_dictionaries is none
begin
return string []
end
else
begin
return dumps list_dictionaries
end
end function | def to_json_string(list_dictionaries):
if list_dictionaries is None:
return "[]"
else:
return json.dumps(list_dictionaries) | Python | nomic_cornstack_python_v1 |
comment Do some imports
comment Postgres connection
import psycopg2
import psycopg2.extras
from datetime import datetime
comment Let's create a function to calculate the permutations P(n,r) = n!/(n-r)!
function calc_permutations total_set number_selected
begin
comment n will be the length of the input string
set n = le... | #Do some imports
#Postgres connection
import psycopg2
import psycopg2.extras
from datetime import datetime
#Let's create a function to calculate the permutations P(n,r) = n!/(n-r)!
def calc_permutations (total_set, number_selected):
# n will be the length of the input string
n = len(total_set)
#then work o... | Python | zaydzuhri_stack_edu_python |
function reset self
begin
pass
end function | def reset(self):
pass | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import requests
import re
import io
from progress.bar import Bar
set header = dict string User-Agent string Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36
set url = string https://en.wikipedi... | # -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
import requests
import re
import io
from progress.bar import Bar
header = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36'
}
url = "https://en.wikipedia.org/wiki/Mia_Khalifa"... | Python | zaydzuhri_stack_edu_python |
import itchat
from echarts import Echart , Legend , Pie
comment login wechat
call login
comment 获取好友列表
set friends = call get_friends update=true at slice 0 : :
set male = 0
set female = 0
set other = 0
comment 遍历列表
comment 1 = male 2 = female
for i in friends at slice 1 : :
begin
set sex = i at string Sex
if sex =... | import itchat
from echarts import Echart, Legend, Pie
#login wechat
itchat.login()
#获取好友列表
friends = itchat.get_friends(update=True)[0:]
male = female = other = 0
#遍历列表
#1 = male 2 = female
for i in friends[1:]:
sex = i["Sex"]
if sex == 1:
male += 1
elif sex == 2:
female += 1
else:
... | Python | zaydzuhri_stack_edu_python |
function __ne__ self other
begin
return not self == other
end function | def __ne__(self, other):
return not self == other | Python | nomic_cornstack_python_v1 |
import logging
from concurrent.futures import ProcessPoolExecutor , as_completed
function get i
begin
import os
print call getpid
function f
begin
print string hai
end function
return f
import time
sleep 10
return i * i
end function
try
begin
with call ProcessPoolExecutor 10 as e
begin
set futs = list
for i in range 2... | import logging
from concurrent.futures import ProcessPoolExecutor, as_completed
def get(i):
import os
print(os.getpid())
def f():
print("hai")
return f
import time
time.sleep(10)
return i * i
try:
with ProcessPoolExecutor(10) as e:
futs = []
for i in range(2... | Python | zaydzuhri_stack_edu_python |
function p_expression_binop p
begin
string expression : expression PLUS expression | expression MINUS expression | expression TIMES expression | expression DIVIDE expression | expression EQUAL expression | expression CONCAT expression | expression SPLIT expression
set v = p at 2
if v == string +
begin
set p at 0 = call... | def p_expression_binop(p):
'''expression : expression PLUS expression
| expression MINUS expression
| expression TIMES expression
| expression DIVIDE expression
| expression EQUAL expression
| expression CONCAT expressio... | Python | jtatman_500k |
function factorial x
begin
if x == 1
begin
return 1
end
else
begin
return x * call factorial x - 1
end
end function | def factorial(x):
if x == 1:
return 1
else:
return x * factorial(x-1)
| Python | flytech_python_25k |
function raw_body self
begin
string Encoded Body
if _raw_body is none and original_body is not none
begin
if is instance original_body dict
begin
set _raw_body = encode parser original_body
if is instance _raw_body str
begin
set _raw_body = encode _raw_body
end
end
else
if is instance original_body str
begin
set _raw_b... | def raw_body(self) -> bytes:
""" Encoded Body """
if self._raw_body is None and self.original_body is not None:
if isinstance(self.original_body, dict):
self._raw_body = self.parser.encode(self.original_body)
if isinstance(self._raw_body, str):
... | Python | jtatman_500k |
function SetDirectionTolerance self _arg
begin
return call itkSLICImageFilterVISS3IULL3_Superclass_SetDirectionTolerance self _arg
end function | def SetDirectionTolerance(self, _arg: 'double const') -> "void":
return _itkSLICImageFilterPython.itkSLICImageFilterVISS3IULL3_Superclass_SetDirectionTolerance(self, _arg) | Python | nomic_cornstack_python_v1 |
import socket
import cv2
import numpy as np
set UDP_IP = string 127.0.0.1
set UDP_PORT = 5005
comment Internet
set sock = call socket AF_INET SOCK_DGRAM
comment UDP
call bind tuple UDP_IP UDP_PORT
set message = string
while true
begin
comment buffer size is 1024 bytes
set tuple data addr = call recvfrom 2048
while leng... | import socket
import cv2
import numpy as np
UDP_IP = "127.0.0.1"
UDP_PORT = 5005
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
message = str()
while True:
data, addr = sock.recvfrom(2048) # buffer size is 1024 bytes
while(len(data)!... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
import seaborn as sns
import re
from matplotlib import pyplot as plt
comment 解决中文乱码
set rcParams at string font.sans-serif = list string SimHei
comment 读取原数据
set df_raw = call read_excel string raw_data.xlsx
comment 数据预处理
set df = df_raw
comment 删掉排名这一列
del df at string 排名
comment... | import numpy as np
import pandas as pd
import seaborn as sns
import re
from matplotlib import pyplot as plt
plt.rcParams['font.sans-serif'] = ['SimHei'] # 解决中文乱码
df_raw = pd.read_excel('raw_data.xlsx') # 读取原数据
# 数据预处理
df = df_raw
del df['排名'] # 删掉排名这一列
# 将年度票房改为亿美元,数据格式为浮点格式
def tranTickNum(s):
s = re.sub(r'... | Python | zaydzuhri_stack_edu_python |
function welcomeToPython
begin
print string My first method without inputs or outputs
end function
function welcomeWithInput name
begin
print string { name } 's first method without one inputs and no output
end function
function welcomeWithOutput
begin
return string First method with output.
end function
function welco... | def welcomeToPython():
print("My first method without inputs or outputs")
def welcomeWithInput(name):
print(f"{name}'s first method without one inputs and no output")
def welcomeWithOutput():
return "First method with output."
def welcome2Input1Output(name,grade):
... | Python | zaydzuhri_stack_edu_python |
import random
set n = 25
set a = list comprehension random integer 0 100 for i in range n
print a
set N = 1
while N < n - 1
begin
for i in range n - N
begin
if a at i > a at i + 1
begin
set tuple a at i a at i + 1 = tuple a at i + 1 a at i
end
end
set N = N + 1
end
print a
import random
set N = 10
set A = list comprehe... | import random
n = 25
a = [random.randint(0, 100) for i in range(n)]
print(a)
N = 1
while N < n - 1:
for i in range(n - N):
if a[i] > a[i + 1]:
a[i], a[i + 1] = a[i + 1], a[i]
N += 1
print(a)
import random
N = 10
A = [random.randint(0, 100) for i in range(N)]
print(A... | Python | zaydzuhri_stack_edu_python |
import requests
set headers = dict string user-agent string Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36 ; string Connection string Keep-Alive ; string Referer string http://www.mzitu.com/
set urls = list string https://www.mzitu.com/xinggan/ string https://w... | import requests
headers = {
'user-agent': "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36",
'Connection': 'Keep-Alive',
'Referer': "http://www.mzitu.com/"
}
urls = [
# 性感妹子
"https://www.mzitu.com/xinggan/",
# 日本妹子
"http... | Python | zaydzuhri_stack_edu_python |
function delete_endpoint_config self endpoint_config_name
begin
string Delete an Amazon SageMaker endpoint configuration. Args: endpoint_config_name (str): Name of the Amazon SageMaker endpoint configuration to delete.
info format string Deleting endpoint configuration with name: {} endpoint_config_name
call delete_end... | def delete_endpoint_config(self, endpoint_config_name):
"""Delete an Amazon SageMaker endpoint configuration.
Args:
endpoint_config_name (str): Name of the Amazon SageMaker endpoint configuration to delete.
"""
LOGGER.info('Deleting endpoint configuration with name: {}'.form... | Python | jtatman_500k |
function on_buttonBox_clicked self button
begin
if button == bTest
begin
call on_bTest_clicked
end
end function | def on_buttonBox_clicked(self, button):
if button == self.bTest:
self.on_bTest_clicked() | Python | nomic_cornstack_python_v1 |
comment from file import class
from PersonClass import Person
set person1 = call Person string James string McLeod string 11/30/2000
print first_name
print call get_age | #from file import class
from PersonClass import Person
person1 = Person("James", "McLeod", "11/30/2000")
print(person1.first_name)
print (person1.get_age()) | Python | zaydzuhri_stack_edu_python |
from fractions import Fraction
class Fractions
begin
function __init__ self nominator denominator
begin
set fraction_element = call Fraction nominator denominator
set nominator = numerator
set denominator = denominator
end function
function __add__ self other
begin
set x1 = nominator
set x2 = nominator
set y1 = denomin... | from fractions import Fraction
class Fractions:
def __init__(self, nominator, denominator):
fraction_element = Fraction(nominator, denominator)
self.nominator = fraction_element.numerator
self.denominator = fraction_element.denominator
def __add__(self, other):
x1 = self.nomina... | Python | zaydzuhri_stack_edu_python |
from collections import Counter
class Solution extends object
begin
function canDivideIntoSubsequences self nums K
begin
return max values counter nums <= length nums // K
end function
end class | from collections import Counter
class Solution(object):
def canDivideIntoSubsequences(self, nums, K):
return max(Counter(nums).values()) <= len(nums) // K
| Python | zaydzuhri_stack_edu_python |
function SplitUnspentCoin wallet asset_id from_addr index divisions fee=call Zero prompt_passwd=true
begin
string Split unspent asset vins into several vouts Args: wallet (neo.Wallet): wallet to show unspent coins from. asset_id (UInt256): a bytearray (len 32) representing an asset on the blockchain. from_addr (UInt160... | def SplitUnspentCoin(wallet, asset_id, from_addr, index, divisions, fee=Fixed8.Zero(), prompt_passwd=True):
"""
Split unspent asset vins into several vouts
Args:
wallet (neo.Wallet): wallet to show unspent coins from.
asset_id (UInt256): a bytearray (len 32) representing an asset on the blo... | Python | jtatman_500k |
import gzip
import cPickle
import numpy as np
comment Formatted data due to http://neuralnetworksanddeeplearning.com
comment The data loading functions here are mostly from there as well.
function load_data
begin
string Return the MNIST data as a tuple containing the training data, the validation data, and the test dat... | import gzip
import cPickle
import numpy as np
# Formatted data due to http://neuralnetworksanddeeplearning.com
# The data loading functions here are mostly from there as well.
def load_data():
"""Return the MNIST data as a tuple containing the training data,
the validation data, and the test data.
The ``... | Python | zaydzuhri_stack_edu_python |
function is_available self cmd
begin
set num_qubits = 0
for qureg in all_qubits
begin
set num_qubits = num_qubits + length qureg
end
return num_qubits <= 2
end function | def is_available(self, cmd):
num_qubits = 0
for qureg in cmd.all_qubits:
num_qubits += len(qureg)
return num_qubits <= 2 | Python | nomic_cornstack_python_v1 |
for i in range 1 n + 1
begin
set cnt at i % k = cnt at i % k + 1
end
if k % 2 == 0
begin
set ans = 0
set ans = ans + cnt at 0 * cnt at 0 * cnt at 0
if k // 2 <= n
begin
set ans = ans + cnt at k // 2 * cnt at k // 2 * cnt at k // 2
end
print ans
end
else
begin
print cnt at 0 * cnt at 0 * cnt at 0
end | for i in range(1, n + 1):
cnt[i % k] += 1
if k % 2 == 0:
ans = 0
ans += cnt[0] * cnt[0] * cnt[0]
if k // 2 <= n:
ans += cnt[k // 2] * cnt[k // 2] * cnt[k // 2]
print(ans)
else:
print(cnt[0] * cnt[0] * cnt[0])
| Python | zaydzuhri_stack_edu_python |
function make_sub_sport_list sport_list name
begin
set slist = call get_sub_sport_list name
set nlist = list
for i in sport_list
begin
if i not in slist ? i == string
begin
append nlist name
end
else
begin
append nlist i
end
end
return nlist
end function | def make_sub_sport_list(sport_list, name):
slist = get_sub_sport_list(name)
nlist = []
for i in sport_list:
if (i not in slist) | (i == ""):
nlist.append(name)
else:
nlist.append(i)
return nlist | Python | nomic_cornstack_python_v1 |
function test_non_abstract_children
begin
from ctapipe.core import non_abstract_children
class AbstractBase extends ABC
begin
decorator abstractmethod
function method self
begin
pass
end function
end class
class Child1 extends AbstractBase
begin
function method self
begin
print string method of Child1
end function
end ... | def test_non_abstract_children():
from ctapipe.core import non_abstract_children
class AbstractBase(ABC):
@abstractmethod
def method(self):
pass
class Child1(AbstractBase):
def method(self):
print("method of Child1")
class Child2(AbstractBase):
... | Python | nomic_cornstack_python_v1 |
function __init__ self *args
begin
call __init__ *args
set hottest_recommender = call HottestRecommender *args
end function | def __init__(self, *args):
super(KeywordRecommenderHottestFallback, self).__init__(*args)
self.hottest_recommender = HottestRecommender(*args) | Python | nomic_cornstack_python_v1 |
comment Superman
comment sun
comment sun
comment sun
comment sun
comment Superman
comment stature
comment Superman
comment from
comment yellow
comment of
comment Earth.
comment Forced
comment akin
comment to
comment of
comment homeworld,
comment Krypton,
comment or
comment to
comment radiation,
comment Superman
comment... | # Superman
# sun
# sun
# sun
# sun
# Superman
# stature
# Superman
# from
# yellow
# of
# Earth.
# Forced
# akin
# to
# of
# homeworld,
# Krypton,
# or
# to
# radiation,
# Superman
# to
# of
# normal
# human.
#
# ['S', 'd', 'h', 'p', 'f', 't', 'y', 's', 'o', 'E', 'F', 'u',
# 'a', 'r', 's', 'a', 't', 't', 'r', 's', '... | Python | zaydzuhri_stack_edu_python |
function f
begin
set s = input
for i in range length s
begin
if i % 2 == 1
begin
if s at i == string L or s at i == string U or s at i == string D
begin
continue
end
else
begin
return string No
end
end
else
if s at i == string R or s at i == string U or s at i == string D
begin
continue
end
else
begin
return string No
... | def f():
s = input()
for i in range(len(s)):
if i%2 == 1:
if s[i] == "L" or s[i] == "U" or s[i] == "D":
continue
else:
return "No"
else:
if s[i] == "R" or s[i] == "U" or s[i] == "D":
continue
else:
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Thu Aug 28 19:43:03 2014 The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17. Find the sum of all the primes below two million. @author: tenz
function is_prime m
begin
set isprime = true
for i in range 2 call long m ^ 0.5 + 1
begin
if m % i == 0 or m % call long m ^ 0.5 ... | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 28 19:43:03 2014
The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
Find the sum of all the primes below two million.
@author: tenz
"""
def is_prime(m):
isprime = True
for i in range(2,long(m**.5) + 1):
if m % i == 0 or m % long(m**.5) == 0:
... | Python | zaydzuhri_stack_edu_python |
function compute_loss_logreg_regl2 y tx w lambda_
begin
set loss = call compute_loss_logreg y tx w
set penal_loss = loss + lambda_ * dot w
return penal_loss
end function | def compute_loss_logreg_regl2(y, tx, w, lambda_):
loss = compute_loss_logreg(y, tx, w)
penal_loss = loss + lambda_ * w.dot(w)
return penal_loss | Python | nomic_cornstack_python_v1 |
function evaluate queue individual validation=false
begin
import tensorflow as tf
import tensorflow.keras as keras
import logging
import time
try
begin
call setLevel ERROR
set sess = call Session config=config
call set_session sess
if validation
begin
set train_x = train_x
set train_y = train_y
end
else
begin
set train... | def evaluate(queue, individual, validation=False):
import tensorflow as tf
import tensorflow.keras as keras
import logging
import time
try:
logging.getLogger('tensorflow').setLevel(logging.ERROR)
sess = tf.compat.v1.Session(config=ModelUtils.config)... | Python | nomic_cornstack_python_v1 |
comment Importing the relevant packages
import numpy as np
import cv2
set freq = 20000
set nm = 2
set c0 = tuple 346.13 0
set rho = tuple 1.2 1000000.0
set wavelmin = c0 at 0 / freq
comment The main class that defines all constants, variables, and functions
class fdtdVar
begin
function __init__ self rs cs
begin
comment... | # Importing the relevant packages
import numpy as np
import cv2
freq = 20000
nm = 2
c0 = (346.13, 0)
rho = (1.2, 1.0e6)
wavelmin = c0[0] / freq
# The main class that defines all constants, variables, and functions
class fdtdVar:
def __init__(self, rs, cs):
# Constants
cn = 0.9 / np.sqrt(2.0) # C... | Python | zaydzuhri_stack_edu_python |
function reset_nodes self nodes check=true wait_reboot=true
begin
call reset
if check
begin
call check_nodes_tcp_availability nodes must_available=false
end
if wait_reboot
begin
call check_nodes_tcp_availability nodes timeout=NODE_REBOOT_TIMEOUT
end
end function | def reset_nodes(self, nodes, check=True, wait_reboot=True):
nodes.reset()
if check:
self.check_nodes_tcp_availability(nodes, must_available=False)
if wait_reboot:
self.check_nodes_tcp_availability(
nodes, timeout=config.NODE_REBOOT_TIMEOUT) | Python | nomic_cornstack_python_v1 |
comment from bengali import Bengali
class English extends object
begin
function __init__ self learn=none
begin
set _learn = learn
end function
comment print self._learn
comment return self._learn
function learn_english self letter
begin
set letter = letter
return letter
end function
end class
string def import_bengali(... | #from bengali import Bengali
class English(object):
def __init__(self, learn=None):
self._learn = learn
#print self._learn
#return self._learn
def learn_english(self, letter):
self.letter = letter
return self.letter
'''
def import_bengali(self):
from bengali import Bengali
return B... | Python | zaydzuhri_stack_edu_python |
function get_module self label
begin
return get _registry label get _modules label none
end function | def get_module(self, label):
return self._registry.get(label, self._modules.get(label, None)) | Python | nomic_cornstack_python_v1 |
string Faça um Programa que peça as 4 notas bimestrais e mostre a média
set soma = integer input string Digite a primeira nota:
set soma = soma + integer input string Digite a segunda nota:
set soma = soma + integer input string Digite a terceira nota:
set soma = soma + integer input string Digite a quarta nota:
commen... | """
Faça um Programa que peça as 4 notas bimestrais e mostre a média
"""
soma = int(input("Digite a primeira nota: "))
soma = soma + int(input("Digite a segunda nota: "))
soma = soma + int(input("Digite a terceira nota: "))
soma = soma + int(input("Digite a quarta nota: "))
soma = soma/4 #queremos um numero real
print(... | Python | zaydzuhri_stack_edu_python |
function test_version_option_z runner
begin
set result = call invoke main list string -z
assert not exception
assert exit_code == 0
assert IDENT in output
end function | def test_version_option_z(runner):
result = runner.invoke(cctconvert.main, ['-z'])
assert not result.exception
assert result.exit_code == 0
assert IDENT in result.output | Python | nomic_cornstack_python_v1 |
function getCheckState self handle
begin
if handle not in entry_contexts_
begin
return none
end
set context = entry_contexts_ at handle
return check_state
end function | def getCheckState(self, handle):
if handle not in self.entry_contexts_:
return None
context = self.entry_contexts_[handle]
return context.check_state | Python | nomic_cornstack_python_v1 |
comment Даны 2 действительных числа a и b. Получить их сумму, разность и произведение.
set tuple a b = tuple decimal input string Введите a: decimal input string Введите b:
comment float - вещественные числа (действительные)
print string Сумма a и b: a + b
print string Разность a и b: a - b
print string Произведение a ... | # Даны 2 действительных числа a и b. Получить их сумму, разность и произведение.
a, b = float(input('Введите a: ')), float(input('Введите b: '))
# float - вещественные числа (действительные)
print('Сумма a и b: ', (a + b))
print('Разность a и b: ', (a - b))
print('Произведение a и b: ', (a * b))
| Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python3
import re
import sys
from shutil import copyfile
function create_service domain
begin
set service_name = replace domain string . string -
call copyfile string templates/service.yaml string services/ { service_name } .yaml
set sentry_dsn = strip input string What's the SENTRY_DSN string?
c... | #! /usr/bin/env python3
import re
import sys
from shutil import copyfile
def create_service(domain):
service_name = domain.replace('.', '-')
copyfile('templates/service.yaml', f'services/{service_name}.yaml')
sentry_dsn = input("What's the SENTRY_DSN string? ").strip()
update_file(
f'services... | Python | zaydzuhri_stack_edu_python |
function res_add_variant res
begin
if call has_children
begin
comment or raise an error
set count_val = res at string Number
try
begin
set count = integer count_val
end
except tuple TypeError ValueError
begin
raise call ValueError string Invalid variant count { count_val } !
end
set weighting = call parse_weights count... | def res_add_variant(res: Property):
if res.has_children():
count_val = res['Number'] # or raise an error
try:
count = int(count_val)
except (TypeError, ValueError):
raise ValueError(f'Invalid variant count {count_val}!')
weighting = rand.parse_weights(count, ... | Python | nomic_cornstack_python_v1 |
import datetime
set current_hour = now
print string Current hour is
if hour < 10
begin
print string 0 end=string
end | import datetime
current_hour = datetime.now()
print("Current hour is")
if current_hour.hour < 10:
print("0", end="") | Python | greatdarklord_python_dataset |
import cv2
comment LOOPING VIDEO
set video = call VideoCapture 0
set a = 0
while true
begin
set a = a + 1
set tuple check frame = read video
set face_cascade = call CascadeClassifier string C://Users//lenovo//Desktop//OpenCV//haarcascade_frontalface_default.xml
set gray_img = call cvtColor frame COLOR_BGR2GRAY
set blur... | import cv2
# LOOPING VIDEO
video = cv2.VideoCapture(0)
a=0
while True:
a+=1
check , frame = video.read()
face_cascade = cv2.CascadeClassifier("C://Users//lenovo//Desktop//OpenCV//haarcascade_frontalface_default.xml")
gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
blur_img = cv2.GaussianBlur(gr... | Python | zaydzuhri_stack_edu_python |
function max_even_seq n
begin
set count = 0
set maxx = 0
while n > 0
begin
if n % 10 % 2 == 0
begin
set count = count + 1
end
else
begin
if maxx < count
begin
set maxx = count
end
set count = 0
end
set n = n // 10
end
if count < maxx
begin
return maxx
end
else
begin
return count
end
end function | def max_even_seq(n):
count = 0
maxx = 0
while n>0 :
if ((n%10)%2 == 0):
count += 1
else:
if maxx < count :
maxx = count
count = 0
n = n//10
if (count<maxx):
return(maxx)
else:
return(count)
| Python | zaydzuhri_stack_edu_python |
function mse_function target_tensor prediction_tensor
begin
set tuple target_coeff_tensor predicted_coeff_tensor = call _filter_fields target_tensor=target_tensor prediction_tensor=prediction_tensor spatial_coeff_matrix=spatial_coeff_matrix frequency_coeff_matrix=frequency_coeff_matrix orig_num_rows=orig_num_rows orig_... | def mse_function(target_tensor, prediction_tensor):
target_coeff_tensor, predicted_coeff_tensor = _filter_fields(
target_tensor=target_tensor, prediction_tensor=prediction_tensor,
spatial_coeff_matrix=spatial_coeff_matrix,
frequency_coeff_matrix=frequency_coeff_matrix,
... | Python | nomic_cornstack_python_v1 |
from datetime import datetime
import dateutil.relativedelta as rd
import dateutil.rrule as dr
from dateutil.parser import parse
set now = now
print now
set delta = call relativedelta weeks=+ 1 hour=10
print now + delta
set birthdate = call datetime 1991 11 20 0 0
print call relativedelta now birthdate
set episodes = ca... | from datetime import datetime
import dateutil.relativedelta as rd
import dateutil.rrule as dr
from dateutil.parser import parse
now = datetime.now()
print(now)
delta = rd.relativedelta(weeks=+1, hour=10)
print(now + delta)
birthdate = datetime(1991, 11, 20, 0, 0)
print(rd.relativedelta(now, birthdate))
episodes = ... | Python | zaydzuhri_stack_edu_python |
function period_string self
begin
return string format time start_date PERIOD_STRING_FORMAT
end function | def period_string(self):
return self.start_date.strftime(DuesPaymentPeriod.PERIOD_STRING_FORMAT) | Python | nomic_cornstack_python_v1 |
function __idiv__ self value
begin
return call itkMatrixF34___idiv__ self value
end function | def __idiv__(self, value: 'float const &') -> "void":
return _itkMatrixPython.itkMatrixF34___idiv__(self, value) | Python | nomic_cornstack_python_v1 |
function parse_log input_file regexes
begin
set rejection_warnings = list
set report_legend = string "Datestamp","Remote Host","Reason","Claimed sender","Recipient","Helo greeting"
end function | def parse_log(input_file, regexes):
rejection_warnings = []
report_legend = '"Datestamp","Remote Host","Reason","Claimed sender","Recipient","Helo greeting"'
| Python | nomic_cornstack_python_v1 |
comment one thousand = 11
set sum = 11
for i in range 1 1000
begin
set s = string
set h = i // 100
if h > 0
begin
set s = s + singles at h - 1
set s = s + string hundred
end
set i = i - h * 100
set t = i // 10
set o = i % 10
if t > 1
begin
if h > 0
begin
set s = s + string and
end
set s = s + tenths at t - 1
if o > 0
... | # one thousand = 11
sum = 11
for i in range(1,1000):
s = ""
h = i//100
if h > 0:
s += singles[h-1]
s += "hundred"
i -= h*100
t = i//10
o = i%10
if t > 1:
if h > 0:
s += "and"
s += tenths[t-1]
if o > 0:
s += singles[o-1]
eli... | Python | zaydzuhri_stack_edu_python |
string moveForward(100); turnRight(90); moveForward(100); turnRight(180);
from turtle import Turtle
set jay = call Turtle
call pensize 7
call pencolor string gold
call forward 100
call right 90
call forward 100
call right 50
call left 20
call left 67
call right 0
call forward 50
call left 25 | '''
moveForward(100);
turnRight(90);
moveForward(100);
turnRight(180);
'''
from turtle import Turtle
jay = Turtle()
jay.pensize(7)
jay.pencolor('gold')
jay.forward(100)
jay.right(90)
jay.forward(100)
jay.right(50)
jay.left(20)
jay.left(67)
jay.right(00)
jay.forward(50)
jay.left(25)
| Python | zaydzuhri_stack_edu_python |
function account_set_up self
begin
set tuple text_from_xml ids eng_list = call get_text_from_xml string_xml string AccountsetUp string trans-unit strip selected_language
set xpath = call read_xpath_list_from_xml object_repo string AccountsetUp my_object
set len_main = length xpath
comment index to the actual text
set t... | def account_set_up(self):
text_from_xml, ids, eng_list = self.util.get_text_from_xml(self.string_xml, "AccountsetUp", "trans-unit",
Config.selected_language.strip())
xpath = self.util.read_xpath_list_from_xml(self.object_repo, "Accountse... | Python | nomic_cornstack_python_v1 |
class SenderObj
begin
function __init__ self char_id name access_level
begin
set char_id = char_id
set name = name
set access_level = access_level
end function
function __str__ self
begin
return call __str__
end function
end class | class SenderObj:
def __init__(self, char_id, name, access_level):
self.char_id = char_id
self.name = name
self.access_level = access_level
def __str__(self):
return self.__dict__.__str__()
| Python | zaydzuhri_stack_edu_python |
for i in range tc
begin
set a = list
set a = split input
for i in range 1 2
begin
set a at i = integer a at i
end
append c a
end
set maxi = - 1
for i in range length c
begin
set m = c at i at 1
if length c at i at 0 <= 20
begin
if m > maxi
begin
set maxi = m
set order = c at i at 0
end
else
if c at i at 1 == maxi
begi... | for i in range(tc):
a = []
a = input().split()
for i in range(1,2):
a[i] = int(a[i])
c.append(a)
maxi =- 1
for i in range(len(c)):
m = c[i][1]
if len(c[i][0]) <= 20:
if m > maxi:
maxi = m
order = c[i][0]
elif c[i][1] == maxi:
order = mi... | Python | zaydzuhri_stack_edu_python |
import os
from flask import Flask , request , abort , jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from models import setup_db , Actor , Movie
from auth import AuthError , requires_auth
function create_app test_config=none
begin
comment create and configure the app
set app = call Flask __... | import os
from flask import Flask, request, abort, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS
from models import setup_db, Actor, Movie
from auth import AuthError, requires_auth
def create_app(test_config=None):
# create and configure the app
app = Flask(__name__)
setup_db(app)
... | Python | zaydzuhri_stack_edu_python |
function lognorm_params mode stddev
begin
set p = call poly1d list 1 - 1 0 0 - stddev / mode ^ 2
set r = roots
set sol = real
set shape = square root log sol
set scale = mode * sol
return tuple shape scale
end function | def lognorm_params(mode, stddev):
p = np.poly1d([1, -1, 0, 0, -(stddev/mode)**2])
r = p.roots
sol = r[(r.imag == 0) & (r.real > 0)].real
shape = np.sqrt(np.log(sol))
scale = mode * sol
return shape, scale | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string ------------------------------------------------------- Created on Mon Nov 6 14:45:23 2017 @author: Cedric Bezy -------------------------------------------------------
string ============================================================================ Importation of Packages =======... | # -*- coding: utf-8 -*-
"""-------------------------------------------------------
Created on Mon Nov 6 14:45:23 2017
@author: Cedric Bezy
-------------------------------------------------------"""
"""============================================================================
Importation of Packages
==... | Python | zaydzuhri_stack_edu_python |
function insert cls pgconn email_address raw_password display_name
begin
set cursor = call cursor
execute cursor string insert into people (email_address, display_name, salted_hashed_password, person_status) values ( %(email_address)s, %(display_name)s, crypt(%(raw_password)s, gen_salt('bf')), 'confirmed' ) returning (... | def insert(cls, pgconn, email_address, raw_password,
display_name):
cursor = pgconn.cursor()
cursor.execute("""
insert into people
(email_address, display_name,
salted_hashed_password, person_status)
values
(
%(email... | Python | nomic_cornstack_python_v1 |
comment Definition for a binary tree node.
comment class TreeNode(object):
comment def __init__(self, x):
comment self.val = x
comment self.left = None
comment self.right = None
class Solution extends object
begin
function lowestCommonAncestor self root p q
begin
string 给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。 百度百科中最近公共祖先的定义为:“对于有... | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。
百度百科中最近公共祖先的定义为:“对于... | Python | zaydzuhri_stack_edu_python |
import time
import RPi.GPIO as GPIO
set login_btn = 37
set logout_btn = 36
set arrival_btn = 31
set departure_btn = 29
function log_in name
begin
if input login_btn == 1
begin
print name
end
end function
function log_out name
begin
if input logout_btn == 1
begin
print name
end
end function
function arrival name
begin
i... | import time
import RPi.GPIO as GPIO
login_btn = 37
logout_btn = 36
arrival_btn = 31
departure_btn = 29
def log_in(name):
if GPIO.input(login_btn) == 1:
print(name)
def log_out(name):
if GPIO.input(logout_btn) == 1:
print(name)
def arrival(name):
if GPIO.input(arrival_btn) == 1:
print(name)
def... | Python | zaydzuhri_stack_edu_python |
function is_prime number
begin
for iterator in range 2 number // 2
begin
if number % iterator == 0
begin
return 0
end
end
return 1
end function
function prime list_param
begin
set x = list
for iterator in list_param
begin
if call is_prime iterator == 1
begin
append x iterator
end
end
return x
end function
set x = list ... | def is_prime(number):
for iterator in range(2, number // 2):
if number % iterator == 0:
return 0;
return 1;
def prime(list_param):
x = list()
for iterator in list_param:
if is_prime(iterator) == 1:
x.append(iterator)
return x
x = [1, 12, 13, 17]
print(p... | Python | zaydzuhri_stack_edu_python |
function test_form_works_with_table_pagination_on_second_page self
begin
set n_traits = TABLE_PER_PAGE + 2
call create_batch n_traits i_description=string lorem ipsum
set response = get client call get_url dict string description string lorem ; string page 2
set context = context
assert in string form context
assert tr... | def test_form_works_with_table_pagination_on_second_page(self):
n_traits = TABLE_PER_PAGE + 2
factories.SourceTraitFactory.create_batch(n_traits, i_description='lorem ipsum')
response = self.client.get(self.get_url(), {'description': 'lorem', 'page': 2})
context = response.context
... | 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.