code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import numpy as np
from similarity_searching_sketches.log_utils import IterationLogger
function sort_ids_by_distance ids database queries dist_f log_by=5000
begin
string Sorts objects from database by distances to query objects for all given queries. :param ids: Object ID's :param database: Objects :param queries: Quer... | import numpy as np
from similarity_searching_sketches.log_utils import IterationLogger
def sort_ids_by_distance(ids, database, queries, dist_f, log_by=5000):
"""
Sorts objects from database by distances to query objects for all given queries.
:param ids: Object ID's
:param database: Objects
:param... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment Script to send SMS via way2sms
comment @author Vishesh Yadav
comment @license BSD License
comment TODO: Phonebook
comment TODO: Logs
comment TODO: More abstract API so that can be ported to others
comment TODO: Error checking and handling
comment TODO: Various options on command lin... | #!/usr/bin/env python
#
# Script to send SMS via way2sms
#
# @author Vishesh Yadav
# @license BSD License
#
#TODO: Phonebook
#TODO: Logs
#TODO: More abstract API so that can be ported to others
#TODO: Error checking and handling
#TODO: Various options on command line to work directly with configurations
import url... | Python | zaydzuhri_stack_edu_python |
function do_bootstrap kc args
begin
set tenant = call create tenant_name=tenant
set role = call create name=role
set user = call create name=user password=passwd email=none
call add_user_role user=user role=role tenant=tenant
comment verify the result
set user_client = call Client username=user password=passwd tenant_n... | def do_bootstrap(kc, args):
tenant = kc.tenants.create(tenant_name=args.tenant)
role = kc.roles.create(name=args.role)
user = kc.users.create(name=args.user, password=args.passwd, email=None)
kc.roles.add_user_role(user=user, role=role, tenant=tenant)
# verify the result
user_client = client.Cl... | Python | nomic_cornstack_python_v1 |
function __init__ self rg secs
begin
set secs = secs + 1
call self rg
end function | def __init__( self, rg, secs ) :
self.secs = secs + 1
self( rg ) | Python | nomic_cornstack_python_v1 |
comment imports ####
from flask import render_template , Blueprint , session , abort , jsonify
from flask_login import login_required
from project.models import User
comment config ####
set object_list_blueprint = call Blueprint string object_list __name__ template_folder=string templates
decorator call route string /l... | #################
#### imports ####
#################
from flask import render_template, Blueprint,session,abort,jsonify
from flask_login import login_required
from project.models import User
################
#### config ####
################
object_list_blueprint = Blueprint('object_list', __name__, template_f... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Fri Apr 8 21:03:48 2016 @author: Huang Hongye <qrqiuren@users.noreply.github.com>
import numpy as np
from numpy import random
from numpy import sin , cos , tan , arctan , log , pi
function salphas alpha gamma beta=0.0 size=none
begin
string Generate random variables under... | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 8 21:03:48 2016
@author: Huang Hongye <qrqiuren@users.noreply.github.com>
"""
import numpy as np
from numpy import random
from numpy import sin, cos, tan, arctan, log, pi
def salphas(alpha, gamma, beta=0., size=None):
"""
Generate random variables under S-alph... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
import subprocess
function getNarray
begin
return list 1 * 10 ^ 4 1 * 10 ^ 5 2 * 10 ^ 7 5 * 10 ^ 7
end function
function get_time n m
begin
if m == 1
begin
set out = communicate popen list string ./sieve_unith string n stdout=PIPE
end
else
begin
set out = communicate popen list string ./si... | #!/usr/bin/env python3
import subprocess
def getNarray():
return [1 * 10**4, 1 * 10**5, 2 * 10**7, 5 * 10**7]
def get_time(n, m):
if m == 1:
out = subprocess.Popen(['./sieve_unith', str(n)], stdout=subprocess.PIPE).communicate()
else:
out = subprocess.Popen(['./sieve_multith', str(n), st... | Python | zaydzuhri_stack_edu_python |
import gym
set env = call make string gym_pathfinder:PathFinder-v0
call add_map_path string horizontal string /home/nader/workspace/rl/gym-pathfinder/agents/maps/vertical_map/ string vertical
call add_map_path string diagonal string /home/nader/workspace/rl/gym-pathfinder/agents/maps/diagonal_map/
set obs = call reset ... | import gym
env = gym.make('gym_pathfinder:PathFinder-v0')
env.add_map_path('horizontal', '/home/nader/workspace/rl/gym-pathfinder/agents/maps/vertical_map/', 'vertical')
env.add_map_path('diagonal', '/home/nader/workspace/rl/gym-pathfinder/agents/maps/diagonal_map/')
obs = env.reset(map_name='vertical')
env.render()
d... | Python | zaydzuhri_stack_edu_python |
string 1217. Minimum Cost to Move Chips to The Same Position https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/ vim缩进:crtl+v 按列选择 然后操作即可
function minCostToMoveChips self position
begin
string :type position: List[int] :rtype: int
set odd = 0
set even = 0
for pos in position
begin
if pos ? 1
... | '''
1217. Minimum Cost to Move Chips to The Same Position
https://leetcode.com/problems/minimum-cost-to-move-chips-to-the-same-position/
vim缩进:crtl+v 按列选择 然后操作即可
'''
def minCostToMoveChips(self, position):
"""
:type position: List[int]
:rtype: int
"""
odd = 0
even = 0
for ... | Python | zaydzuhri_stack_edu_python |
function init_app self app
begin
call __init__ aws_access_key_id=get config string SES_AWS_ACCESS_KEY aws_secret_access_key=get config string SES_AWS_SECRET_KEY region=get config string SES_REGION string us-east-1 sender=get config string SES_SENDER none reply_to=get config string SES_REPLY_TO none template=get config ... | def init_app(self, app):
self.__init__(aws_access_key_id=app.config.get("SES_AWS_ACCESS_KEY"),
aws_secret_access_key=app.config.get("SES_AWS_SECRET_KEY"),
region=app.config.get("SES_REGION", "us-east-1"),
sender=app.config.get("SES_SENDER", None)... | Python | nomic_cornstack_python_v1 |
function remainder_when_square_of_odd_number_divided_by_8 n
begin
comment Check if n is an odd number
if n % 2 == 0
begin
raise call ValueError string The input must be an odd number.
end
comment Calculate the square of n
set n_squared = n ^ 2
comment Calculate the remainder when n_squared is divided by 8
set remainder... | def remainder_when_square_of_odd_number_divided_by_8(n):
# Check if n is an odd number
if n % 2 == 0:
raise ValueError("The input must be an odd number.")
# Calculate the square of n
n_squared = n ** 2
# Calculate the remainder when n_squared is divided by 8
remainder = n_squar... | Python | dbands_pythonMath |
function send_text body=string test from 424 twilio number
begin
set message = call create from_=SECOND_NUMBER to=PRIVATE_NUMBER body=body
print sid to body
end function | def send_text(body='test from 424 twilio number'):
message = client.messages.create(
from_=SECOND_NUMBER,
to=PRIVATE_NUMBER,
body=body
)
print(message.sid, message.to, message.body) | Python | nomic_cornstack_python_v1 |
function get_user_rankings self request
begin
set users = call fetch
set users = sorted users key=lambda x -> win_percentage reverse=true
return call UserForms items=list comprehension call to_form for user in users
end function | def get_user_rankings(self, request):
users = User.query(User.total_games > 0).fetch()
users = sorted(users, key=lambda x: x.win_percentage, reverse=True)
return UserForms(items=[user.to_form() for user in users]) | Python | nomic_cornstack_python_v1 |
import numpy as np
import main.read_file as rf
import main.write_file as wf
import main.eva_all as ea
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
comment 卡方分布
from scipy.stats import chi2
string origin a 6 b 1.4 c 0.5
function get_socre x a b c
begin
return a / ... | import numpy as np
import main.read_file as rf
import main.write_file as wf
import main.eva_all as ea
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
from scipy.stats import chi2 # 卡方分布
"""
origin a 6
b 1.4
c 0.5
"""
def get_socre(x, a, b ,c):
... | Python | zaydzuhri_stack_edu_python |
function power_numbers *numbers
begin
string функция, которая принимает N целых чисел, и возвращает список квадратов этих чисел
return list comprehension number ^ 2 for number in numbers
end function
comment filter types
set ODD = string odd
set EVEN = string even
set PRIME = string prime
function is_prime numbers
begi... | def power_numbers(*numbers):
"""
функция, которая принимает N целых чисел,
и возвращает список квадратов этих чисел
"""
return [number ** 2 for number in numbers]
# filter types
ODD = "odd"
EVEN = "even"
PRIME = "prime"
def is_prime(numbers):
prime_list = []
for num in numbers:
i... | Python | zaydzuhri_stack_edu_python |
function test_no_blacks self
begin
set image_before = call camera
set tuple y_size x_size = shape
set augmenter = call ImageAugmenter x_size y_size scale_to_percent=1.5 scale_axis_equally=false rotation_deg=90 shear_deg=20 translation_x_px=10 translation_y_px=10
set image_black = zeros shape dtype=float32
set nb_augmen... | def test_no_blacks(self):
image_before = data.camera()
y_size, x_size = image_before.shape
augmenter = ImageAugmenter(x_size, y_size,
scale_to_percent=1.5,
scale_axis_equally=False,
rotation_... | Python | nomic_cornstack_python_v1 |
function draw self win
begin
comment for dot in self.path:
comment pygame.draw.circle(win, (255,0,0), dot, 5, 1)
set img = imgs at animation_count
set ice = ices at ice_count
call blit img tuple x - call get_width / 2 y - call get_height / 2 - 35
comment draw ice when hit by OuhonTower
if frozen
begin
call blit ice tup... | def draw(self, win):
# for dot in self.path:
# pygame.draw.circle(win, (255,0,0), dot, 5, 1)
self.img = self.imgs[self.animation_count]
ice = ices[self.ice_count]
win.blit(self.img, (self.x - self.img.get_width() / 2, self.y - self.img.get_height() / 2 - 35))
# draw ice... | Python | nomic_cornstack_python_v1 |
import cv2
import numpy as np
set img = call imread string mark.jpg
image show string Mark img
set tuple height width = shape at slice : 2 :
set rotation_mat = call getRotationMatrix2D tuple width / 2 height / 2 90 1
set rotated_img = call warpAffine img rotation_mat tuple width height
image show string rotated img r... | import cv2
import numpy as np
img=cv2.imread('mark.jpg')
cv2.imshow('Mark',img)
height,width=img.shape[:2]
rotation_mat=cv2.getRotationMatrix2D((width/2,height/2),90,1)
rotated_img=cv2.warpAffine(img,rotation_mat,(width,height))
cv2.imshow('rotated img',rotated_img)
cv2.waitKey(0)
cv2.destroyAllWindows() | Python | zaydzuhri_stack_edu_python |
string Como se crea una lista nombre de la lista = [contenido separado por comas]
comment 0 1 2 3 4
set palabras = list string rango string mapa string ocupar string dentista string entero
set numeros = list 1 2 3 4 5 6 7 8 9 5
comment TODO: metodos de lista
comment navegación dentro de la lista
print format string La ... | '''
Como se crea una lista
nombre de la lista = [contenido separado por comas]
'''
# 0 1 2 3 4
palabras = ['rango', 'mapa', 'ocupar', 'dentista', 'entero']
numeros = [1, 2, 3, 4, 5, 6, 7, 8, 9, 5]
# TODO: metodos de lista
# navegación dentro de la lista
print('La palabra en ... | Python | zaydzuhri_stack_edu_python |
function SGD self training_data epochs mini_batch_size eta test_data=none
begin
if test_data
begin
set n_test = length test_data
end
end function | def SGD(self, training_data, epochs, mini_batch_size, eta,
test_data=None):
if test_data:
n_test = len(test_data) | Python | nomic_cornstack_python_v1 |
function C0BSplineToArrayOfC1BSplineCurve *args
begin
return call geomconvert_C0BSplineToArrayOfC1BSplineCurve *args
end function | def C0BSplineToArrayOfC1BSplineCurve(*args):
return _GeomConvert.geomconvert_C0BSplineToArrayOfC1BSplineCurve(*args) | Python | nomic_cornstack_python_v1 |
set length = decimal input string Give me the lenth of your rectangle
set width = decimal input string Give me the width of your rectangle
set area = length * width
print format string {0:.1f} is the area of your rectangle area | length=float(input("Give me the lenth of your rectangle"))
width=float(input("Give me the width of your rectangle"))
area=(length) * (width)
print("{0:.1f} is the area of your rectangle".format(area))
| Python | zaydzuhri_stack_edu_python |
string Домашнее задание №2 Работа с файлами 1. Скачайте файл по ссылке https://www.dropbox.com/s/sipsmqpw1gwzd37/referat.txt?dl=0 2. Прочитайте содержимое файла в перменную, подсчитайте длину получившейся строки 3. Подсчитайте количество слов в тексте 4. Замените точки в тексте на восклицательные знаки 5. Сохраните рез... | """
Домашнее задание №2
Работа с файлами
1. Скачайте файл по ссылке https://www.dropbox.com/s/sipsmqpw1gwzd37/referat.txt?dl=0
2. Прочитайте содержимое файла в перменную, подсчитайте длину получившейся строки
3. Подсчитайте количество слов в тексте
4. Замените точки в тексте на восклицательные знаки
5. Сохраните рез... | Python | zaydzuhri_stack_edu_python |
function update_account self accid account_name=none overdraft_limit=none interest_rate=none
begin
if account_name is none and overdraft_limit is none and interest_rate is none
begin
return tuple false string No new data has been provided. none
end
else
begin
set sql = string UPDATE accounts SET
if account_name is not ... | def update_account(self, accid, account_name: str = None, overdraft_limit: int = None,
interest_rate: float = None) -> tuple:
if account_name is None and overdraft_limit is None and interest_rate is None:
return False, "No new data has been provided.", None
else:
... | Python | nomic_cornstack_python_v1 |
function suspend self instance
begin
debug string Suspend instance instance=instance
call _set_vm_state instance HYPERV_VM_STATE_SUSPENDED
end function | def suspend(self, instance):
LOG.debug("Suspend instance", instance=instance)
self._set_vm_state(instance,
os_win_const.HYPERV_VM_STATE_SUSPENDED) | Python | nomic_cornstack_python_v1 |
set s = input
set a = find s string h
set b = reverse find s string h
set d = s at slice a : b + 1 :
print s at slice : a : + d at slice : : - 1 + s at slice b + 1 : : | s = input()
a = s.find("h")
b = s.rfind("h")
d = s[a:b+1]
print(s[:a]+d[::-1]+s[b+1:]) | Python | zaydzuhri_stack_edu_python |
function read_matrix n
begin
comment nested comprehension
set result = list comprehension list comprehension integer num for num in split input string , for _ in range n
return result
end function
set n = integer input
set matrix = call read_matrix n
set first_diagonal = list comprehension matrix at i at i for i in ran... | def read_matrix(n):
# nested comprehension
result = [[int(num) for num in input().split(', ')] for _ in range(n)]
return result
n = int(input())
matrix = read_matrix(n)
first_diagonal = [matrix[i][i] for i in range(len(matrix))]
second_diagonal = [matrix[i][len(matrix) - i-1] for i in range(len(matrix))]... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function isValid self s
begin
set end_map = dict string ( string ) ; string [ string ] ; string { string }
set stack = list
for x in s
begin
if x in end_map
begin
append stack end_map at x
end
else
if not stack or stack at - 1 != x
begin
break
end
else
begin
pop stack
end
end
for else
begin
if not... | class Solution:
def isValid(self, s: str) -> bool:
end_map = {
'(': ')',
'[': ']',
'{': '}'
}
stack = []
for x in s:
if x in end_map:
stack.append(end_map[x])
elif not stack or stack[-1] != x:
... | Python | zaydzuhri_stack_edu_python |
function ConstCommonExcelAddPassiveSkillLevelMax builder PassiveSkillLevelMax
begin
return call AddPassiveSkillLevelMax builder PassiveSkillLevelMax
end function | def ConstCommonExcelAddPassiveSkillLevelMax(builder, PassiveSkillLevelMax):
return AddPassiveSkillLevelMax(builder, PassiveSkillLevelMax) | Python | nomic_cornstack_python_v1 |
import numpy as np
from keras.models import Sequential
from keras.layers import Dense , Activation
from keras.optimizers import RMSprop
import matplotlib.pyplot as plt
comment 生成数据
set X1 = random tuple 2000 1
set X2 = random tuple 2000 1
set X = horizontal stack tuple X1 X2
print X at slice : 10 :
set XX1 = 0.5 * X1
... | import numpy as np
from keras.models import Sequential
from keras.layers import Dense,Activation
from keras.optimizers import RMSprop
import matplotlib.pyplot as plt
# 生成数据
X1=np.random.random((2000,1))
X2=np.random.random((2000,1))
X=np.hstack((X1,X2))
print(X[:10])
XX1=0.5*X1
XX2=1.4*X2
Y=XX1+XX2+2
# Y=Y+np.random.n... | Python | zaydzuhri_stack_edu_python |
import turtle
from math import cos , sin , gcd
from time import sleep
function draw
begin
string Spirograph ref: www.101computing.net/python-turtle-spirograph/
call tracer 0
set window = call Screen
call bgcolor string #FFFFFF
set mySpirograph = call Turtle
call hideturtle
call speed 0
call pensize 2
set myPen = call T... | import turtle
from math import cos, sin, gcd
from time import sleep
def draw():
"""
Spirograph
ref:
www.101computing.net/python-turtle-spirograph/
"""
turtle.tracer(0)
window = turtle.Screen()
window.bgcolor("#FFFFFF")
mySpirograph = turtle.Turtle()
mySpirograph.hideturtl... | Python | zaydzuhri_stack_edu_python |
function _Offsets *args
begin
return dictionary generator expression tuple a none for a in args
end function | def _Offsets(*args):
return dict((a, None) for a in args) | Python | nomic_cornstack_python_v1 |
function keypaths self
begin
set sep = _keypath_separator or string .
return call keypaths self separator=sep
end function | def keypaths(self):
sep = self._keypath_separator or '.'
return dict_util.keypaths(self, separator=sep) | Python | nomic_cornstack_python_v1 |
function get_token self
begin
string Get a token from the input stream (or from stack if it's nonempty)
if pushback
begin
set tok = call popleft
return tok
end
comment No pushback. Get a token.
set raw = call read_token
comment Handle inclusions
if source is not none
begin
while raw == source
begin
set spec = call sour... | def get_token(self):
"Get a token from the input stream (or from stack if it's nonempty)"
if self.pushback:
tok = self.pushback.popleft()
return tok
# No pushback. Get a token.
raw = self.read_token()
# Handle inclusions
if self.source is not None... | Python | jtatman_500k |
comment Infinite LOOP w/While condition###
while true
begin
print string You're stuck in a loop!
end | ###Infinite LOOP w/While condition###
while True:
print("You're stuck in a loop! ")
| Python | zaydzuhri_stack_edu_python |
function word_break s wordDict
begin
set word_dict = set wordDict
set memo = dict length s list string
function sentences start
begin
if start not in memo
begin
set memo at start = list comprehension s at slice start : j + 1 : + tail and string + tail for j in range start length s if s at slice start : j + 1 : in w... | def word_break(s, wordDict):
word_dict = set(wordDict)
memo = {len(s): ['']}
def sentences(start):
if start not in memo:
memo[start] = [
s[start:j+1] + (tail and ' ' + tail)
for j in range(start, len(s))
if s[start:j+1] in word_dict
... | Python | nomic_cornstack_python_v1 |
function user_get_foreign_groups self
begin
comment todo: maybe cache this query
set user_group_ids = call values_list string id flat=true
return call exclude id__in=user_group_ids
end function | def user_get_foreign_groups(self):
#todo: maybe cache this query
user_group_ids = self.get_groups().values_list('id', flat = True)
return Group.objects.exclude(id__in = user_group_ids) | Python | nomic_cornstack_python_v1 |
function groups self
begin
return _groups
end function | def groups(self):
return self._groups | Python | nomic_cornstack_python_v1 |
function event_m10_14_x92 z30=10143101 z32=500000 z33=10143100
begin
string State 0,4: Disable key guide for switch
call DisableObjKeyGuide z33 1
string State 1: Scaffold animation playback descending with a switch
call ChangeObjState z30 70
string State 3: Has the animation of the scaffold finished playing?
call Compa... | def event_m10_14_x92(z30=10143101, z32=500000, z33=10143100):
"""State 0,4: Disable key guide for switch"""
DisableObjKeyGuide(z33, 1)
"""State 1: Scaffold animation playback descending with a switch"""
ChangeObjState(z30, 70)
"""State 3: Has the animation of the scaffold finished playing?"""
Co... | Python | nomic_cornstack_python_v1 |
comment Definition for a binary tree node.
from tkinter.tix import Tree
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 subtreeWithAllDeepest self root
begin
if not left and not right
begin
... | # Definition for a binary tree node.
from tkinter.tix import Tree
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
if not root.left ... | Python | zaydzuhri_stack_edu_python |
function alerts self
begin
return get pulumi self string alerts
end function | def alerts(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['AppSpecWorkerAlertArgs']]]]:
return pulumi.get(self, "alerts") | Python | nomic_cornstack_python_v1 |
string Configlet implementation
from zope import interface
from memphis import storage
from memphis.controlpanel.interfaces import IConfiglet , IConfigletData
class BehaviorFactory extends object
begin
function __init__ self id bid
begin
set id = id
set bid = bid
end function
function __call__ self item
begin
raise cal... | """ Configlet implementation """
from zope import interface
from memphis import storage
from memphis.controlpanel.interfaces import IConfiglet, IConfigletData
class BehaviorFactory(object):
def __init__(self, id, bid):
self.id = id
self.bid = bid
def __call__(self, item):
raise Runti... | Python | zaydzuhri_stack_edu_python |
function test_queue_peek
begin
set test_case = queue TEST_QUEUE_DATA
assert call peek == list 1 2 3 4 5
end function | def test_queue_peek():
test_case = Queue(TEST_QUEUE_DATA)
assert test_case.peek() == [1, 2, 3, 4, 5] | Python | nomic_cornstack_python_v1 |
function available_results self model_run_name
begin
set available = call available_results model_run_name
set model_run = call read_model_run model_run_name
set results = dict string model_run model_run_name ; string sos_model model_run at string sos_model ; string sector_models dictionary ; string scenarios dictionar... | def available_results(self, model_run_name):
available = self._store.available_results(model_run_name)
model_run = self._store.read_model_run(model_run_name)
results = {
"model_run": model_run_name,
"sos_model": model_run["sos_model"],
"sector_models": dict(... | Python | nomic_cornstack_python_v1 |
function host_lte self host_lte
begin
set _host_lte = host_lte
end function | def host_lte(self, host_lte):
self._host_lte = host_lte | Python | nomic_cornstack_python_v1 |
function scrape_chrono24 csv_main_details
begin
with open csv_main_details as result_page
begin
next result_page
set page_nr = length read lines open string spacy_pages.csv
print format string Scraping {0} pages. page_nr
set start = time
for tuple idx line in enumerate result_page
begin
if idx % 1000 == 0 and idx != 0
... | def scrape_chrono24(csv_main_details):
with open(csv_main_details) as result_page:
next(result_page)
page_nr = len(open('spacy_pages.csv').readlines())
print('Scraping {0} pages.'.format(page_nr))
start = time.time()
for idx, line in enumerate(result_page):
if... | Python | nomic_cornstack_python_v1 |
function output_mb self
begin
set total_output_size = sum list comprehension shuffle_mb_written for t in tasks
return total_output_size
end function | def output_mb(self):
total_output_size = sum([t.shuffle_mb_written for t in self.tasks])
return total_output_size | Python | nomic_cornstack_python_v1 |
from bs4 import BeautifulSoup
import requests
import validators
import json
import sys
set home = string https://news.ycombinator.com/
set data = list
function validate_uri uri
begin
string Check if a url is valid :param uri: string The url of a post :return: bool True means valid url and False is invalid url
try
begi... | from bs4 import BeautifulSoup
import requests
import validators
import json
import sys
home = 'https://news.ycombinator.com/'
data = []
def validate_uri(uri):
"""
Check if a url is valid
:param uri: string
The url of a post
:return: bool
True means valid url and False is invalid url
... | Python | zaydzuhri_stack_edu_python |
class Queue
begin
function __init__ self
begin
set listElements = list
end function
function enqueue self element
begin
append listElements element
end function
function dequeue self
begin
return pop listElements 0
end function
function peek self
begin
return listElements at 0
end function
function isEmpty self
begin
... | class Queue():
def __init__(self):
self.listElements = []
def enqueue(self, element):
self.listElements.append(element)
def dequeue(self):
return self.listElements.pop(0)
def peek(self):
return self.listElements[0]
def isEmpty(self):
return self.listElemen... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import numpy as np
set tuple xdata ydata = tuple 100 * list 0 100 * list 0
comment Your code goes here
comment This will draw the graph
plot xdata ydata string bo
plot list 0 1 list 0.5 1.5 string k-
plot list 0 1 list - 0.5 0.5 string k-
save figure string correlated_variables.png | import matplotlib.pyplot as plt
import numpy as np
xdata, ydata = 100*[0], 100*[0]
# Your code goes here
# This will draw the graph
plt.plot( xdata, ydata, 'bo')
plt.plot( [0,1], [0.5,1.5], 'k-' )
plt.plot( [0,1], [-0.5,0.5], 'k-' )
plt.savefig("correlated_variables.png")
| Python | zaydzuhri_stack_edu_python |
function profile func
begin
function wrap *args **kwargs
begin
global pr
call enable
set result = call func *args keyword kwargs
call disable
call print_stats sort=string tottime
return result
end function
return wrap
end function | def profile(func):
def wrap(*args, **kwargs):
global pr
pr.enable()
result = func(*args, **kwargs)
pr.disable()
pr.print_stats(sort="tottime")
return result
return wrap | Python | nomic_cornstack_python_v1 |
function taxon_label self
begin
if parent is none
begin
return string Root
end
else
begin
comment numpy ints cause indexing errors; convert to native int
comment uid field necessary to distinguish colliding allele originations
return string Inner+r= { _rank } +d= { call render_to_base64url integer _differentia } +uid= ... | def taxon_label(self: "TrieInnerNode") -> str:
if self.parent is None:
return "Root"
else:
# numpy ints cause indexing errors; convert to native int
# uid field necessary to distinguish colliding allele originations
return f"""Inner+r={self._rank}+d={
... | Python | nomic_cornstack_python_v1 |
function sanitize_filename x
begin
set out = string
for c in x
begin
if c in ascii_letters + digits + string _-.
begin
set out = out + c
end
else
begin
set out = out + string _
end
end
string Prevent long filenames such as files named by hash as some malware checks for this.
if length out >= 32
begin
set out = call ge... | def sanitize_filename(x):
out = ""
for c in x:
if c in string.ascii_letters + string.digits + " _-.":
out += c
else:
out += "_"
"""Prevent long filenames such as files named by hash
as some malware checks for this."""
if len(out) >= 32:
out = generate... | Python | nomic_cornstack_python_v1 |
function get_device arn=none
begin
pass
end function | def get_device(arn=None):
pass | Python | nomic_cornstack_python_v1 |
comment Import libraries necessary for this project
import numpy as np
import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import accuracy_score
from sklearn.metrics import r2_score
from sklearn.decomposition import PCA
from sklea... | # Import libraries necessary for this project
import numpy as np
import pandas as pd
from sklearn.cross_validation import train_test_split
from sklearn.tree import DecisionTreeRegressor
from sklearn.metrics import accuracy_score
from sklearn.metrics import r2_score
from sklearn.decomposition import PCA
from sklearn.cl... | Python | zaydzuhri_stack_edu_python |
from tkinter import *
import _thread
import time
function GUI
begin
class Gui extends Frame
begin
function __init__ self
begin
comment creating the window and setting its characteristics
comment Initialise the frame
call __init__ self
grid
call createWidgets
end function
function createWidgets self
begin
comment creati... | from tkinter import *
import _thread
import time
def GUI():
class Gui(Frame):
def __init__(self):
#creating the window and setting its characteristics
# Initialise the frame
Frame.__init__(self)
self.grid()
self.createWidgets()
def crea... | Python | zaydzuhri_stack_edu_python |
function today
begin
return today
end function | def today():
return datetime.date.today() | Python | nomic_cornstack_python_v1 |
function secret_key self
begin
return get pulumi self string secret_key
end function | def secret_key(self) -> str:
return pulumi.get(self, "secret_key") | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding:utf-8
comment Copyright (C) dirlt
class Solution extends object
begin
function candy self ratings
begin
string :type ratings: List[int] :rtype: int
comment n = len(ratings)
comment ss = [1] * n
comment while True:
comment changed = False
comment for i in range(n):
comment L =... | #!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
class Solution(object):
def candy(self, ratings):
"""
:type ratings: List[int]
:rtype: int
"""
# n = len(ratings)
# ss = [1] * n
# while True:
# changed = False
# for i in ran... | Python | zaydzuhri_stack_edu_python |
class Classifier
begin
function __init__ self config cloud prediction_schema
begin
set config = config
set cloud = cloud
set schema = prediction_schema
end function
function load_model self cluster_number
begin
set model_name = schema at string cluster_number
set model = call load_model model_name
return model
end func... | class Classifier:
def __init__(self, config, cloud, prediction_schema):
self.config = config
self.cloud = cloud
self.schema = prediction_schema
def load_model(self, cluster_number):
model_name = self.schema[str(cluster_number)]
model = self.cloud.load_model(model_name)
... | Python | zaydzuhri_stack_edu_python |
function compute_similarity self seq_node **kwargs
begin
pass
end function | def compute_similarity(self, seq_node, **kwargs):
pass | Python | nomic_cornstack_python_v1 |
function __dNdlog2dN self Dp dNdlogDp
begin
set x = call log10 Dp
set y = x at slice 1 : : + x at slice : - 1 : / 2.0
set y = call pad y 1 string constant constant_values=tuple x at 0 - y at 0 - x at 0 x at - 1 + x at - 1 - y at - 1
set dlogDp = diff np y
comment cm-3
return dNdlogDp * dlogDp
end function | def __dNdlog2dN(self,Dp,dNdlogDp):
x = np.log10(Dp)
y = (x[1:]+x[:-1])/2.
y = np.pad(y,1,'constant',constant_values=(x[0]-(y[0]-x[0]),x[-1]+(x[-1]-y[-1])))
dlogDp = np.diff(y)
return dNdlogDp*dlogDp # cm-3 | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import operator
from collections import defaultdict
from data_tools import get_objects
from dataloaders.data_loader import CITY_KEY , AIRLINE_KEY , TIME_KEY , COUNTRY_KEY , SOURCES_KEY , DESTINATION_KEY
from dataloaders.json_data_loader import JsonDataLoader
from time_analysis import make_... | # -*- coding: utf-8 -*-
import operator
from collections import defaultdict
from data_tools import get_objects
from dataloaders.data_loader import CITY_KEY, AIRLINE_KEY, TIME_KEY, COUNTRY_KEY, SOURCES_KEY, DESTINATION_KEY
from dataloaders.json_data_loader import JsonDataLoader
from time_analysis import make_time_histo... | Python | zaydzuhri_stack_edu_python |
function start_bot self
begin
if call rtm_connect
begin
print string EpicsBot connected and running!
comment bot = EpicsBot()
while true
begin
try
begin
set tuple command channel = call parse_slack_output call rtm_read
if command and channel
begin
set res = call handle_command command channel
if res is not none
begin
c... | def start_bot(self):
if self.slack.rtm_connect():
print("EpicsBot connected and running!")
# bot = EpicsBot()
while True:
try:
command, channel = self.parse_slack_output(self.slack.rtm_read())
if command and channel:
... | Python | nomic_cornstack_python_v1 |
function remove self key
begin
comment 这里需要单向删除单向链表的某一个元素。需要将上一个链表的next,指向当前链表的next
set index = key % capacity
if list at index is not none
begin
set ptr = list at index
set next_ptr = next
comment 比较第一个链表
if pair at 0 == key
begin
set list at index = next_ptr
end
else
begin
while next_ptr is not none
begin
set tuple s... | def remove(self, key: int) -> None:
# 这里需要单向删除单向链表的某一个元素。需要将上一个链表的next,指向当前链表的next
index = key % self.capacity
if self.list[index] is not None:
ptr = self.list[index]
next_ptr = ptr.next
if ptr.pair[0] == key: # 比较第一个链表
self.list[index] = next... | Python | nomic_cornstack_python_v1 |
function gradient_check_n parameters gradients X Y epsilon=1e-07
begin
string Checks if backward_propagation_n computes correctly the gradient of the cost output by forward_propagation_n Arguments: parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3": grad -- output of backward_... | def gradient_check_n(parameters, gradients, X, Y, epsilon = 1e-7):
"""
Checks if backward_propagation_n computes correctly the gradient of the cost output by forward_propagation_n
Arguments:
parameters -- python dictionary containing your parameters "W1", "b1", "W2", "b2", "W3", "b3":
grad -- o... | Python | zaydzuhri_stack_edu_python |
comment 题目:利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来。
comment 程序分析:无。
set i = input string 輸入 :
set l = length i
function opposite i l
begin
if l == 0
begin
return
end
print i at l - 1
call opposite i l - 1
end function
call opposite i l | #题目:利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来。
#程序分析:无。
i = input('輸入 : ')
l = len(i)
def opposite(i,l) :
if l == 0 :
return
print(i[l-1])
opposite(i,l-1)
opposite(i,l) | Python | zaydzuhri_stack_edu_python |
comment AUTHOR ShenShen shs2016f@bu.edu
comment AUTHOR Patrick Dyer pddyer21@bu.edu
comment unit:g
set mass_earth = decimal 5.972e+27
comment the whole number of neu and pro
set neu_add_pro = mass_earth * 6.02e+23
comment E per P means electron per particle
set EperP1 = 0.5
set EperP2 = 0.4
set EperP3 = 1
comment how m... | # AUTHOR ShenShen shs2016f@bu.edu
# AUTHOR Patrick Dyer pddyer21@bu.edu
mass_earth=float(5.972e27) #unit:g
neu_add_pro=mass_earth*6.02e23 #the whole number of neu and pro
EperP1=0.5 #E per P means electron per particle
EperP2=0.4
EperP3=1
a1=neu_add_pro*EperP1 #how much bits
a2=neu_add_pro*EperP2
a3=neu_add_... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from Variable import *
class Function
begin
function __call__ self input
begin
set x = data
set y = call forward x
set output = call Variable y
call set_creator self
set input = input
set output = output
return output
end function
function forward self x
begin
raise NotImplementedError
end function
f... | import numpy as np
from .Variable import *
class Function:
def __call__(self, input):
x = input.data
y = self.forward(x)
output = Variable(y)
output.set_creator(self)
self.input = input
self.output = output
return output
def forward(self, x):
rai... | Python | zaydzuhri_stack_edu_python |
comment print(a)
comment print(b)
if a == string This is a book. and b == string I i d
begin
print string This dis a book.
end
else
if a == string This is a book. and b == string R w i
begin
print string no exist
print string This is a book.
end
else
if a == string This is a book. and b == string R t i
begin
print stri... | #print(a)
#print(b)
if(a=="This is a book. " and b=="I i d"):
print("This dis a book. ")
elif(a=="This is a book. " and b=="R w i "):
print("no exist")
print("This is a book. ")
elif(a=="This is a book. " and b=="R t i "):
print("no exist")
print("This is a book. ")
elif(a=="This is a book. " ... | Python | zaydzuhri_stack_edu_python |
import time
import datetime
class Parset extends dict
begin
string A pure Python parameterset parser. Original version by Gijs Molenaar for LOFAR Transients Pipeline.
function __init__ self filename=none
begin
string Create a parameterset object.
set filename = filename
if filename
begin
call adoptFile filename
end
end... | import time
import datetime
class Parset(dict):
"""
A pure Python parameterset parser.
Original version by Gijs Molenaar for LOFAR Transients Pipeline.
"""
def __init__(self, filename=None):
"""Create a parameterset object."""
self.filename = filename
if filename:
... | Python | zaydzuhri_stack_edu_python |
function list_folders self name=string parentId=string
begin
if not service
begin
return
end
set ROOT_ID = string root
set query = string mimeType=' { MIME_TYPE_FOLDER } '
if name
begin
set query = query + string and name=' { name } '
end
if parentId and parentId != string /
begin
set query = query + string and ' { pa... | def list_folders(self, name = '', parentId = ''):
if not self.service: return
ROOT_ID = 'root'
query = f"mimeType='{self.MIME_TYPE_FOLDER}'"
if name: query += f" and name='{name}'"
if parentId and parentId != '/':
query += f" and '{parentId}' in parents"
els... | Python | nomic_cornstack_python_v1 |
from flask import Flask , request , render_template
from random import choice , sample
set app = call Flask __name__
set horoscopes = list string awesome string terrific string fantastic string neato string fantabulous string wowza string oh-so-not-meh string brilliant string ducky string coolio string incredible strin... | from flask import Flask, request, render_template
from random import choice, sample
app = Flask(__name__)
horoscopes = [
'awesome', 'terrific', 'fantastic', 'neato', 'fantabulous', 'wowza',
'oh-so-not-meh', 'brilliant', 'ducky', 'coolio', 'incredible',
'wonderful', 'smashing', 'lovely', 'tenacious', 'Pyth... | Python | zaydzuhri_stack_edu_python |
function update_editor_item self event
begin
comment If this is not a simple, single item update, rebuild entire editor:
if length removed != 1 or length added != 1
begin
call update_editor
end
comment Otherwise, find the proxy for this index and update it with the
comment changed value:
for control in call GetChildren... | def update_editor_item ( self, event ):
# If this is not a simple, single item update, rebuild entire editor:
if (len( event.removed ) != 1) or (len( event.added ) != 1):
self.update_editor()
# Otherwise, find the proxy for this index and update it with the
# change... | Python | nomic_cornstack_python_v1 |
function webobify fn
begin
decorator wraps fn
function munger self environ start
begin
return call fn self call Request environ start
end function
return munger
end function | def webobify(fn):
@functools.wraps(fn)
def munger(self, environ, start):
return fn(self, webob.Request(environ), start)
return munger | Python | nomic_cornstack_python_v1 |
function _split_mod_var_names resource_name
begin
try
begin
set dot_index = call rindex string .
end
except ValueError
begin
comment no dot found
return tuple string resource_name
end
return tuple resource_name at slice : dot_index : resource_name at slice dot_index + 1 : :
end function | def _split_mod_var_names(resource_name):
try:
dot_index = resource_name.rindex('.')
except ValueError:
# no dot found
return '', resource_name
return resource_name[:dot_index], resource_name[dot_index + 1:] | Python | nomic_cornstack_python_v1 |
function current_duration self
begin
return call MONOTONIC_TICKS - _state_changed_ticks / TICKS_PER_SEC
end function | def current_duration(self):
return (MONOTONIC_TICKS() - self._state_changed_ticks) / TICKS_PER_SEC | Python | nomic_cornstack_python_v1 |
import core.gui as gui
from core.gui import HOR_SEP
from core.on_off import on_off_left_upper , OnOffPatch , OnOffWorld
from core.sim_engine import SimEngine
from core.utils import bin_str
from random import choice
class CA_World extends OnOffWorld
begin
set ca_left_extension_length = 0
set ca_display_size = 225
functi... | import core.gui as gui
from core.gui import HOR_SEP
from core.on_off import on_off_left_upper, OnOffPatch, OnOffWorld
from core.sim_engine import SimEngine
from core.utils import bin_str
from random import choice
class CA_World(OnOffWorld):
ca_left_extension_length = 0
ca_display_size = 225
... | Python | zaydzuhri_stack_edu_python |
function __contains__ self item
begin
if item == profile_id
begin
return true
end
end function | def __contains__(self, item):
if item == self.profile_id:
return True | Python | nomic_cornstack_python_v1 |
from selenium import webdriver
from selenium.webdriver import ActionChains
from time import sleep
from password import username , pw
set option = call ChromeOptions
call add_argument string --incognito
class CodingForE
begin
function __init__ self
begin
set driver = call Chrome options=option
end function
function logi... | from selenium import webdriver
from selenium.webdriver import ActionChains
from time import sleep
from password import username, pw
option = webdriver.ChromeOptions()
option.add_argument("--incognito")
class CodingForE():
def __init__(self):
self.driver = webdriver.Chrome(options = option )
def login(s... | Python | zaydzuhri_stack_edu_python |
function toCustomHSV self oldImg newH newS newV
begin
comment to make sure it isn't in a different type and won't throw an error later
set oldImg = call convert string RGB
set pixels = load oldImg
for i in range size at 0
begin
for j in range size at 1
begin
set tuple r g b = pixels at tuple i j
set tuple h s v = call ... | def toCustomHSV(self, oldImg, newH, newS, newV):
oldImg = oldImg.convert("RGB") #to make sure it isn't in a different type and won't throw an error later
pixels = oldImg.load()
for i in range(oldImg.size[0]):
for j in range(oldImg.size[1]):
r, g, b = pixels[i,j]
... | Python | nomic_cornstack_python_v1 |
string Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
set sumsquare = 0
set squaresum = 0
set diff = 0
for i in range 1 101
begin
set squaresum = squaresum + i * i
set sumsquare = sumsquare + i
end
set sumsquare = sumsquare * sumsquare
set diff = s... | '''
Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.
'''
sumsquare = 0
squaresum = 0
diff = 0
for i in range(1,101):
squaresum = squaresum + (i*i)
sumsquare = sumsquare + i
sumsquare = sumsquare*sumsquare
diff = (sumsquare - squaresum) | Python | zaydzuhri_stack_edu_python |
function ISetAttachedEntities self Count=defaultNamedNotOptArg LpArr=defaultNamedNotOptArg
begin
return call InvokeTypes 61 LCID 1 tuple 11 0 tuple tuple 3 1 tuple 16393 1 Count LpArr
end function | def ISetAttachedEntities(self, Count=defaultNamedNotOptArg, LpArr=defaultNamedNotOptArg):
return self._oleobj_.InvokeTypes(61, LCID, 1, (11, 0), ((3, 1), (16393, 1)),Count
, LpArr) | Python | nomic_cornstack_python_v1 |
comment A perfect number is a number for which the sum of its proper divisors is exactly equal to the number.
comment For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
comment A number n is called deficient if the sum of its proper divisors is l... | #A perfect number is a number for which the sum of its proper divisors is exactly equal to the number.
#For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.
#
#A number n is called deficient if the sum of its proper divisors is less than n and it i... | Python | zaydzuhri_stack_edu_python |
function test_response self
begin
set document = call create slug=string hello-world file=call File open files at string hello-world.txt
set download_url = reverse string download_document_nginx kwargs=dict string slug string hello-world
set response = get client download_url
call assertEquals status_code 200
comment V... | def test_response(self):
document = Document.objects.create(
slug='hello-world',
file=File(open(self.files['hello-world.txt'])),
)
download_url = reverse('download_document_nginx',
kwargs={'slug': 'hello-world'})
response = self.clie... | Python | nomic_cornstack_python_v1 |
from UserString import MutableString
set key = call MutableString string a * 72
set k1 = split read open string key1 string at slice : - 1 :
set k2 = split read open string key2 string at slice : - 1 :
for tuple i j in zip k1 k2
begin
set key at integer j = character integer i
end | from UserString import MutableString
key = MutableString('a'*72)
k1 = open('key1').read().split('\n')[:-1]
k2 = open('key2').read().split('\n')[:-1]
for i,j in zip(k1,k2):
key[int(j)] = chr(int(i))
| Python | zaydzuhri_stack_edu_python |
function change_screen_name user_id
begin
set user = call _get_user_or_404 user_id
set form = call ChangeScreenNameForm form
if not call validate
begin
return call change_screen_name_form id form
end
set old_screen_name = screen_name
set new_screen_name = strip data
set initiator_id = id
set reason = strip data
set eve... | def change_screen_name(user_id):
user = _get_user_or_404(user_id)
form = ChangeScreenNameForm(request.form)
if not form.validate():
return change_screen_name_form(user.id, form)
old_screen_name = user.screen_name
new_screen_name = form.screen_name.data.strip()
initiator_id = g.user.id
... | Python | nomic_cornstack_python_v1 |
function custom_score_3 game player
begin
if call is_loser player
begin
return decimal string -inf
end
if call is_winner player
begin
return decimal string inf
end
set player_legal_moves = call get_legal_moves player
set opponent = call get_opponent player
set opponent_legal_moves = call get_legal_moves opponent
set tu... | def custom_score_3(game, player):
if game.is_loser(player):
return float("-inf")
if game.is_winner(player):
return float("inf")
player_legal_moves = game.get_legal_moves(player)
opponent = game.get_opponent(player)
opponent_legal_moves = game.get_legal_moves(oppon... | Python | nomic_cornstack_python_v1 |
from PyQt5.QtWidgets import QCalendarWidget
set calendar = call QCalendarWidget
show | from PyQt5.QtWidgets import QCalendarWidget
calendar = QCalendarWidget()
calendar.show()
| Python | flytech_python_25k |
comment COPIED ### VERIFIED
string Given a list of array, return a list of arrays, each array is a combination of one element in each given array. Let me give you an example to help you understand the question Suppose the input is [[1, 2, 3], [4], [5, 6]], the output should be [[1, 4, 5], [1, 4, 6], [2, 4, 5], [2, 4, 6... | ### COPIED ### VERIFIED
"""
Given a list of array, return a list of arrays, each array is a combination of one element in each given array.
Let me give you an example to help you understand the question Suppose the input is
[[1, 2, 3], [4], [5, 6]],
the output should be
[[1, 4, 5], [1, 4, 6], [2, 4, 5], [2, 4, 6], [3,... | Python | zaydzuhri_stack_edu_python |
function xgcd a b
begin
set tuple x old_x = tuple 0 1
set tuple y old_y = tuple 1 0
while b != 0
begin
set quotient = a // b
set tuple a b = tuple b a - quotient * b
set tuple old_x x = tuple x old_x - quotient * x
set tuple old_y y = tuple y old_y - quotient * y
end
return tuple a old_x old_y
end function | def xgcd(a, b):
x, old_x = 0, 1
y, old_y = 1, 0
while (b != 0):
quotient = a // b
a, b = b, a - quotient * b
old_x, x = x, old_x - quotient * x
old_y, y = y, old_y - quotient * y
return a, old_x, old_y | Python | nomic_cornstack_python_v1 |
import cv2
set image_path = string example_image.jpg
set image = call imread image_path
set tuple blue green red = split cv2 image
set merged = merge list blue green red
image show string Original image
image show string Blue Channel blue
image show string Green Channel green
image show string Red Channel red
image sho... | import cv2
image_path = 'example_image.jpg'
image = cv2.imread(image_path)
blue, green, red = cv2.split(image)
merged = cv2.merge([blue, green, red])
cv2.imshow('Original', image)
cv2.imshow('Blue Channel', blue)
cv2.imshow('Green Channel', green)
cv2.imshow('Red Channel', red)
cv2.imshow('Merged', merged)
cv2.waitKey... | Python | flytech_python_25k |
from base_page import BasePage
from locators import LoginPageLocators
import re
class LoginPage extends BasePage
begin
function should_be_login_page self
begin
call should_be_login_url
call should_be_login_form
call should_be_register_form
end function
function should_be_login_url self
begin
set result = find all strin... | from .base_page import BasePage
from .locators import LoginPageLocators
import re
class LoginPage(BasePage):
def should_be_login_page(self):
self.should_be_login_url()
self.should_be_login_form()
self.should_be_register_form()
def should_be_login_url(self):
result = re.findall(... | Python | zaydzuhri_stack_edu_python |
import inflect
import requests
from bs4 import BeautifulSoup
comment Pull from www.thelatinlibrary.com/decl.html
comment https://en.wiktionary.org/wiki/Category:Latin_appendices
comment Not currently working.
function declenFunc
begin
set dec_choice = input string Declension Number [1-5] :
if integer dec_choice <= 5
be... | import inflect
import requests
from bs4 import BeautifulSoup
# Pull from www.thelatinlibrary.com/decl.html
# https://en.wiktionary.org/wiki/Category:Latin_appendices
# Not currently working.
def declenFunc():
dec_choice = input("Declension Number [1-5] : ")
if int(dec_choice) <= 5:
inflect_... | Python | zaydzuhri_stack_edu_python |
if b == string A
begin
print string T
end
else
if b == string T
begin
print string A
end
else
if b == string C
begin
print string G
end
else
begin
print string C
end | if b=="A": print("T")
elif b=="T": print("A")
elif b=="C": print("G")
else: print("C") | Python | zaydzuhri_stack_edu_python |
function getPendingOrders self
begin
set getPendingOrdersResponse = call list_pending _account_id
return get getPendingOrdersResponse string orders string 200
end function | def getPendingOrders(self):
getPendingOrdersResponse = self._api.order.list_pending(self._account_id)
return getPendingOrdersResponse.get("orders", "200") | Python | nomic_cornstack_python_v1 |
function device_class self
begin
return DEVICE_CLASS_TV
end function | def device_class(self):
return DEVICE_CLASS_TV | Python | nomic_cornstack_python_v1 |
comment encoding=utf8
class TcpClient extends object
begin
string TCP 客户端
function __init__ self timeout logger
begin
import connector , loop , system_service
set _logger = logger
set loop = call EventLoop timeout _logger
comment 一个客户端也可以维持多个tcp连接
set tcpconnection_map = dict
set connector = call Connector loop _logge... | # encoding=utf8
class TcpClient(object):
'''
TCP 客户端
'''
def __init__(self, timeout, logger):
import connector, loop, system_service
self._logger = logger
self.loop = loop.EventLoop(timeout, self._logger)
self.tcpconnection_map = {} # 一个客户端也可以维持多个tcp连接
self.connector = connector.Connector(self.loop, sel... | Python | zaydzuhri_stack_edu_python |
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 findSecondMinimumValue self root
begin
string :type root: TreeNode :rtype: int
comment the second... | # 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 findSecondMinimumValue(self, root):
"""
:type root: TreeNode
:rtype: int
"""
... | Python | zaydzuhri_stack_edu_python |
function people
begin
print string in gplus people...
set credentials = get session string credentials
comment Only fetch a list of people for connected users.
if credentials is none
begin
set response = call make_response dumps string Current user not connected. 401
set headers at string Content-Type = string applicat... | def people():
print ("in gplus people...")
credentials = session.get('credentials')
# Only fetch a list of people for connected users.
if credentials is None:
response = make_response(json.dumps('Current user not connected.'), 401)
response.headers['Content-Type'] = 'application/json'
print ("in gpl... | 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.