code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function sequence self
begin
return __seq
end function | def sequence(self) -> Any:
return self.__seq | Python | nomic_cornstack_python_v1 |
string Virtual Gang Combination Generator The purpose of this class is to create a generator object which can be used to create virtual-gang combinations given a taskset; for a pre-specified number of cores. It also estimates the execution time of each virtual-gang as per our task model. Copyright (C) 2019 KU-CSL 09-07... | '''
Virtual Gang Combination Generator
The purpose of this class is to create a generator object which can be used to
create virtual-gang combinations given a taskset; for a pre-specified number of
cores. It also estimates the execution time of each virtual-gang as per our
task model.
Copyright (C) 2019 KU-CSL
09-07-... | Python | zaydzuhri_stack_edu_python |
function __init__ self signatures network structure
begin
comment First, call the Formula constructor
call __init__ self
comment Replace the network with the active components of the network
set network = call active_graph
comment Create variable tables
comment self.assignment_variables is a dictionary where the keys a... | def __init__(self, signatures, network, structure):
# First, call the Formula constructor
Formula.__init__(self)
# Replace the network with the active components of the network
network = network.active_graph()
# Create variable tables
#
# self.assignment_variab... | Python | nomic_cornstack_python_v1 |
function _trigger_tryjobs changelist jobs options patchset
begin
print string Scheduling jobs on:
for tuple project bucket builder in jobs
begin
print string %s/%s: %s % tuple project bucket builder
end
print string To see results here, run: git cl try-results
print string To see results in browser, run: git cl web
set... | def _trigger_tryjobs(changelist, jobs, options, patchset):
print('Scheduling jobs on:')
for project, bucket, builder in jobs:
print(' %s/%s: %s' % (project, bucket, builder))
print('To see results here, run: git cl try-results')
print('To see results in browser, run: git cl web')
requests = _mak... | Python | nomic_cornstack_python_v1 |
function sub_x_y x y
begin
return x - y
end function
function testsub_x_y
begin
assert call sub_x_y 10 8 == 2
assert call sub_x_y 8 7 == 1
assert call sub_x_y 21 7 == 14
end function | def sub_x_y(x, y):
return x - y
def testsub_x_y():
assert sub_x_y(10, 8) == 2
assert sub_x_y(8, 7) == 1
assert sub_x_y(21, 7) == 14
| Python | zaydzuhri_stack_edu_python |
function test_post_delete topic
begin
set post_middle = post content=string Test Content Middle
save topic=topic user=user
comment post_middle + first_post
assert post_count == 2
set post_last = post content=string Test Content Last
save topic=topic user=user
comment first post + post_middle + post_last
assert post_cou... | def test_post_delete(topic):
post_middle = Post(content="Test Content Middle")
post_middle.save(topic=topic, user=topic.user)
assert topic.post_count == 2 # post_middle + first_post
post_last = Post(content="Test Content Last")
post_last.save(topic=topic, user=topic.user)
# first post + post_... | Python | nomic_cornstack_python_v1 |
function next_boards bd
begin
set lobd = list
for value in values
begin
set lobd = lobd + list call fill_spot call find_blank bd bd value
end
return lobd
end function | def next_boards(bd):
lobd = []
for value in values:
lobd += [fill_spot(find_blank(bd), bd, value)]
return lobd | Python | nomic_cornstack_python_v1 |
function ledger_storage_account self
begin
return get pulumi self string ledger_storage_account
end function | def ledger_storage_account(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "ledger_storage_account") | Python | nomic_cornstack_python_v1 |
import re
from io import StringIO
from discord import File
class Message_Info
begin
function __init__ self message
begin
set message = message
set content = content
set channel = channel
set author = author
set name = name
set discriminator = discriminator
set tag = format string {0}#{1} name discriminator
end function... | import re
from io import StringIO
from discord import File
class Message_Info:
def __init__(self, message):
self.message = message
self.content = message.content
self.channel = message.channel
self.author = message.author
self.name = self.author.name
self.discrimina... | Python | zaydzuhri_stack_edu_python |
function register cls typ
begin
function register_impl func
begin
function add key val
begin
if key in polygraphy_registered
begin
critical string Duplicate serialization function for type: { key } . Note: Existing function: { polygraphy_registered at key } , New function: { func }
end
set polygraphy_registered at key ... | def register(cls, typ):
def register_impl(func):
def add(key, val):
if key in cls.polygraphy_registered:
G_LOGGER.critical(
f"Duplicate serialization function for type: {key}.\nNote: Existing function: {cls.polygraphy_registered[key]}, New... | Python | nomic_cornstack_python_v1 |
function __init__ self parent=none label=string
begin
set parent = parent
set children = none
set data = none
set label = label
set dist = none
comment The sequence after an alignment have been mapped (leaf) or the most parsimonous sequence (ancestral)
set sequence = none
comment The scores propagated from leaves via c... | def __init__(self, parent = None, label=''):
self.parent = parent
self.children = None
self.data = None
self.label = label
self.dist = None
self.sequence = None # The sequence after an alignment have been mapped (leaf) or the most parsimonous sequence (ancestral)
... | Python | nomic_cornstack_python_v1 |
import requests
import re
from urllib.parse import urlsplit
from lxml.html import fromstring
set URL = string http://www.mosigra.ru/
function getHtml url
begin
set parts = call urlsplit url
set path = if expression string / in path then url at slice : reverse find url string / + 1 : else url
if path at slice : 4 : ... | import requests
import re
from urllib.parse import urlsplit
from lxml.html import fromstring
URL = 'http://www.mosigra.ru/'
def getHtml(url):
parts = urlsplit(url)
path = url[:url.rfind('/') + 1] if '/' in parts.path else url
if path[:4] != 'http':
path = URL + path
html = requests.get(path).c... | Python | zaydzuhri_stack_edu_python |
string --enqueue --dequeue --size --is_empty -- use linkedlist to implement it
from linkedList_crwd import ListNode
from queue import Queue
class MyQueue
begin
function __init__ self
begin
set count = 0
set head = none
set tail = none
end function
function put self value
begin
set node = call ListNode value
if head is ... | '''
--enqueue
--dequeue
--size
--is_empty
-- use linkedlist to implement it
'''
from linkedList_crwd import ListNode
from queue import Queue
class MyQueue:
def __init__(self):
self.count = 0
self.head = None
self.tail = None
def put(self, value):
node = ListNode(value)
... | Python | zaydzuhri_stack_edu_python |
import pprint
set dragonLoot = list string gold coin string dagger string gold coin string gold coin string ruby
set stuff = dict string rope 1 ; string torch 6 ; string gold coin 42 ; string dagger 1 ; string arrow 12
comment function for displaying inventory
function displayInventory inventory
begin
print string Inve... | import pprint
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
#function for displaying inventory
def displayInventory(inventory):
print("Inventory:")
item_total = 0
#iterate through the given dictionary totali... | Python | zaydzuhri_stack_edu_python |
function from_argv argv
begin
set args = list
set kwargs = dict
set arguments = argv at slice 1 : :
while length arguments
begin
set arg = pop arguments 0
if starts with arg string -
begin
if string = in arg
begin
set tuple key value = call groups
end
else
begin
set tuple key value = tuple replace arg string - stri... | def from_argv(argv):
args = []
kwargs = {}
arguments = argv[1:]
while len(arguments):
arg = arguments.pop(0)
if arg.startswith('-'):
if '=' in arg:
key, value = re.match('--?(\w+)=(.+)', arg).groups()
else:
... | Python | nomic_cornstack_python_v1 |
string 最短経路問題の解法の実装
function printPath path
begin
string pathはNodeのList
set result = string
for i in range length path
begin
set result = result + string path at i
if i != length path - 1
begin
set result = result + string ->
end
end
return result
end function
function printWeightedPath path
begin
string pathは(Node, w... | """最短経路問題の解法の実装"""
def printPath(path):
"""pathはNodeのList"""
result = ''
for i in range(len(path)):
result = result + str(path[i])
if i != len(path)-1:
result = result + '->'
return result
def printWeightedPath(path):
"""pathは(Node, weight)のtupleのList"""
result = ''... | Python | zaydzuhri_stack_edu_python |
function search self val
begin
set current_node = head
while current_node
begin
if data == val
begin
return current_node
end
set current_node = next_node
end
return none
end function | def search(self, val):
current_node = self.head
while current_node:
if current_node.data == val:
return current_node
current_node = current_node.next_node
return None | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import argparse
import sys
import json
import gocept.pseudonymize
comment one alternative:
comment from cryptopan import CryptoPan
from yacryptopan import CryptoPAn
set debug = false
set config = dictionary
set replace_keys = list
set cp = none
function load_config_and_init filename
begin
... | #!/usr/bin/env python
import argparse
import sys
import json
import gocept.pseudonymize
# one alternative:
# from cryptopan import CryptoPan
from yacryptopan import CryptoPAn
debug=False
config = dict()
replace_keys = []
cp = None
def load_config_and_init(filename: str):
global replace_keys
global cp
... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
from datetime import datetime , timedelta
function plot_dashboard
begin
set checklist_data = call read_excel string ./construction_updates/checklist.ods
set checklist_data at string Checklist = replace checklist_data at string ... | import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
def plot_dashboard():
checklist_data = pd.read_excel("./construction_updates/checklist.ods")
checklist_data['Checklist'] = checklist_data['Checklist'].replace('✓', 1)
checkl... | Python | zaydzuhri_stack_edu_python |
string Special functions.
from util import validate as val
import time
comment Moves the cursor up one line
set CURSOR_UP_ONE = string [1A
set ERASE_LINE = string [2K
class bcolors
begin
string A class that lets you use colors in the console. HEADER is purple. OKBLUE is dark blue. OKGREEN is green. WARNING is yellow.... | """
Special functions.
"""
from util import validate as val
import time
CURSOR_UP_ONE = '\x1b[1A' # Moves the cursor up one line
ERASE_LINE = '\x1b[2K'
class bcolors:
"""
A class that lets you use colors in the console.
HEADER is purple.
OKBLUE is dark blue.
OKGREEN is green.
WARNING is ye... | Python | zaydzuhri_stack_edu_python |
string The puzzle is composed of many tiles, each tile can be rotated and flipped, which gives 8 configurations per tile, each config has four sides and each side has a set of matching (tile_id, config_id, side_id) The puzzle is a square grid A corner has only two matching sides There are four corners Can start from to... | """The puzzle is composed of many tiles, each tile can be rotated and flipped,
which gives 8 configurations per tile, each config has four sides and each side
has a set of matching (tile_id, config_id, side_id)
The puzzle is a square grid
A corner has only two matching sides
There are four corners
Can start from top le... | Python | zaydzuhri_stack_edu_python |
function from_file filename delimiter
begin
return read csv filename delimiter=delimiter
end function | def from_file(filename, delimiter):
return pd.read_csv(filename, delimiter=delimiter) | Python | nomic_cornstack_python_v1 |
function get_incidents_with_pagination client max_fetch query modification_date_start=none modification_date_end=none creation_date_start=none creation_date_end=none fields=none
begin
set incidents = list
set max_incidents = integer max_fetch
set number_of_requests = ceil max_incidents / MAX_API_PAGE_SIZE
if max_incid... | def get_incidents_with_pagination(client: Client, max_fetch: int, query: str,
modification_date_start: Optional[str] = None,
modification_date_end: Optional[str] = None,
creation_date_start: Optional[str] = None,
... | Python | nomic_cornstack_python_v1 |
function plot_observer population num_generations num_evaluations args
begin
import pylab
import numpy
set stats = call fitness_statistics population
set best_fitness = stats at string best
set worst_fitness = stats at string worst
set median_fitness = stats at string median
set average_fitness = stats at string mean
s... | def plot_observer(population, num_generations, num_evaluations, args):
import pylab
import numpy
stats = inspyred.ec.analysis.fitness_statistics(population)
best_fitness = stats['best']
worst_fitness = stats['worst']
median_fitness = stats['median']
average_fitness = stats['mean... | Python | nomic_cornstack_python_v1 |
import re
set num = compile string \(\d\d\) (\d\d\d) (\d\d \d\d)
set mo = search string ble ble njhsvhihvsohi (59) 811 32 68
print call group
comment print(mo.group(1))
call groups
print call groups
set tuple areaCode mainNumber = call groups
print areaCode
print mainNumber | import re
num = re.compile(r'\(\d\d\) (\d\d\d) (\d\d \d\d)')
mo = num.search('ble ble njhsvhihvsohi (59) 811 32 68')
print(mo.group())
#print(mo.group(1))
mo.groups()
print(mo.groups())
areaCode, mainNumber = mo.groups()
print(areaCode)
print(mainNumber)
| Python | zaydzuhri_stack_edu_python |
set arr = list 1 2 3 4 5
comment reversing the array
reverse arr
comment print the reversed array
print arr
comment Output:
list 5 4 3 2 1 | arr = [1, 2, 3, 4, 5]
# reversing the array
arr.reverse()
# print the reversed array
print(arr)
# Output:
[5, 4, 3, 2, 1]
| Python | flytech_python_25k |
function XCAFDoc_ShapeTool_GetComponents *args
begin
return call XCAFDoc_ShapeTool_GetComponents *args
end function | def XCAFDoc_ShapeTool_GetComponents(*args):
return _XCAFDoc.XCAFDoc_ShapeTool_GetComponents(*args) | Python | nomic_cornstack_python_v1 |
class Problem
begin
function __init__ self filename
begin
set __filename = filename
set __n = call __load_problem
end function
function __load_problem self
begin
set file = open __filename string r
set n = integer read line file
close file
return n
end function
function get_size self
begin
return __n
end function
end c... | class Problem:
def __init__(self, filename):
self.__filename = filename
self.__n = self.__load_problem()
def __load_problem(self):
file = open(self.__filename, 'r')
n = int(file.readline())
file.close()
return n
def get_size(self):
return self.__... | Python | zaydzuhri_stack_edu_python |
comment all 입력된 요소중에 하나라도 거짓이면 False리턴 / abs 입력받은 숫자의 절댓값 리턴
print all list 1 2 absolute - 3 - 3
comment chr 아스키코드를 입력받아 문자리턴 / ord 문자를 입력받아 아스키코드리턴
print character ordinal string a == string a | print(all([1, 2, abs(-3)-3])) #all 입력된 요소중에 하나라도 거짓이면 False리턴 / abs 입력받은 숫자의 절댓값 리턴
print(chr(ord('a')) == 'a') #chr 아스키코드를 입력받아 문자리턴 / ord 문자를 입력받아 아스키코드리턴 | Python | zaydzuhri_stack_edu_python |
function __init__ self ai_game
begin
call __init__
set screen = screen
set settings = settings
comment Load image and get its rect.
set image = load image string images/alien.bmp
set image = call scale image tuple 45 45
set rect = call get_rect
comment Set starting position at top left while keeping a space.
set x = wi... | def __init__(self, ai_game):
super().__init__()
self.screen = ai_game.screen
self.settings = ai_game.settings
# Load image and get its rect.
self.image = pygame.image.load("images/alien.bmp")
self.image = pygame.transform.scale(self.image, (45, 45))
self.rect = se... | Python | nomic_cornstack_python_v1 |
function fusion_api_delete_sdi_system_profiles self name=none uri=none api=none headers=none
begin
return delete name=name uri=uri api=api headers=headers
end function | def fusion_api_delete_sdi_system_profiles(self, name=None, uri=None, api=None, headers=None):
return self.sdi_system_profiles.delete(name=name, uri=uri, api=api, headers=headers) | Python | nomic_cornstack_python_v1 |
function _parse_title self item
begin
return strip call extract_first
end function | def _parse_title(self, item):
return item.css("div.eventtitle::text").extract_first().strip() | Python | nomic_cornstack_python_v1 |
function __repr__ self
begin
return call to_str
end function | def __repr__(self):
return self.to_str() | Python | nomic_cornstack_python_v1 |
function _get_judges self
begin
return none
end function | def _get_judges(self):
return None | Python | nomic_cornstack_python_v1 |
function _perform_replacements self chars
begin
string Performs simple key/value string replacements that require no logic. This is used to convert the fullwidth rōmaji, several ligatures, and the punctuation characters.
for n in range length chars
begin
set char = chars at n
if char in repl
begin
set chars at n = repl... | def _perform_replacements(self, chars):
'''
Performs simple key/value string replacements that require no logic.
This is used to convert the fullwidth rōmaji, several ligatures,
and the punctuation characters.
'''
for n in range(len(chars)):
char = chars[n]
... | Python | jtatman_500k |
function get_consistent_edges graph
begin
for tuple u v in call _iter_pairs graph
begin
if call pair_is_consistent graph u v
begin
yield tuple u v
end
end
end function | def get_consistent_edges(graph):
for u, v in _iter_pairs(graph):
if pair_is_consistent(graph, u, v):
yield u, v | Python | nomic_cornstack_python_v1 |
comment -------------------------------------------------------------------------------
comment Name: module1
comment Purpose:
comment Author: Nathan
comment Created: 02/09/2013
comment Copyright: (c) Nathan 2013
comment Licence: <your licence>
comment -------------------------------------------------------------------... | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Nathan
#
# Created: 02/09/2013
# Copyright: (c) Nathan 2013
# Licence: <your licence>
#-------------------------------------------------------------------------------
import gam... | Python | zaydzuhri_stack_edu_python |
from socket import *
set server_port = 3933
set server_socket = call socket AF_INET SOCK_DGRAM
call bind tuple string server_port
print string Server is ready to receive
while true
begin
set buf_size = 2048
set tuple message clientAddress = call recvfrom buf_size
set modified_message = upper decode message
set data = ... | from socket import *
server_port = 3933
server_socket = socket(AF_INET,SOCK_DGRAM)
server_socket.bind(('',server_port))
print("Server is ready to receive")
while True:
buf_size = 2048
message, clientAddress = server_socket.recvfrom(buf_size)
modified_message = message.decode().upper()
data = modified_m... | Python | zaydzuhri_stack_edu_python |
function __ge__ self *args
begin
return call cfor_t___ge__ self *args
end function | def __ge__(self, *args):
return _ida_hexrays.cfor_t___ge__(self, *args) | Python | nomic_cornstack_python_v1 |
function wrap_xblock runtime_class block view frag context usage_id_serializer request_token display_name_only=false extra_data=none
begin
comment pylint: disable=redefined-outer-name
if extra_data is none
begin
set extra_data = dict
end
comment If any mixins have been applied, then use the unmixed class
set class_nam... | def wrap_xblock(
runtime_class,
block,
view,
frag,
context,
usage_id_serializer,
request_token, # pylint: disable=redefined-outer-name
display_name_only=False,
extra_data=None
):
if extra_data is None:
extra_data = {}
... | Python | nomic_cornstack_python_v1 |
function delete_table db table_name
begin
global DB_CONNECTIONS
set con = get DB_CONNECTIONS db none
if con is not none
begin
set db_name = name
info string >>> Deleting stale table ` { table_name } ` from database ` { db_name } ` <<<
execute con string DROP TABLE IF EXISTS { table_name }
end
end function | def delete_table(db, table_name):
global DB_CONNECTIONS
con = DB_CONNECTIONS.get(db, None)
if con is not None:
db_name = Path(db).name
logging.info(f">>> Deleting stale table `{table_name}` from database `{db_name}` <<<")
con.execute(f"DROP TABLE IF EXISTS {table_name}") | Python | nomic_cornstack_python_v1 |
comment DFS
comment 7 8
comment 1 2 1 3 2 4 2 5 4 6 5 6 6 7 3 7
function dfs n v
begin
set stack = list
comment V번 노드까지 방문표시
set visited = list 0 * V + 1
set visited at n = 1
append stack n
comment 스택이 비어있지 않으면
while length stack != 0
begin
set n = pop stack
print n end=string
for i in range V 0 - 1
begin
comment for ... | # DFS
# 7 8
# 1 2 1 3 2 4 2 5 4 6 5 6 6 7 3 7
def dfs(n, v):
stack = []
visited = [0]*(V+1) # V번 노드까지 방문표시
visited[n] = 1
stack.append(n)
while len(stack) != 0: # 스택이 비어있지 않으면
n = stack.pop()
print(n, end=" ")
for i in range(V, 0, -1):
# for i in range(1, v+1):
... | Python | zaydzuhri_stack_edu_python |
import tensorflow as tf
import numpy as np
import pickle
import matplotlib
call use string Agg
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
set mnist = call read_data_sets string MNIST_data/ reshape=false
function get_inputs real_size noise_size
begin
string real image and ... | import tensorflow as tf
import numpy as np
import pickle
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", reshape=False)
def get_inputs(real_size, noise_size):
"""
real image an... | Python | zaydzuhri_stack_edu_python |
function form_get self str_verb
begin
return call FieldStorage fp=rfile headers=headers environ=dict string REQUEST_METHOD str_verb ; string CONTENT_TYPE headers at string Content-Type
end function | def form_get(self, str_verb):
return cgi.FieldStorage(
fp = self.rfile,
headers = self.headers,
environ =
{
'REQUEST_METHOD': str_verb,
'CONTENT_TYPE': self.headers['Content-Type'],
}
) | Python | nomic_cornstack_python_v1 |
function test_reduce_custom_dtype self
begin
comment We try multiple axis combinations even though axis should not matter.
set idx = 0
for method in methods
begin
for input_dtype in call imap str all_types
begin
set x = call matrix dtype=input_dtype
for output_dtype in call imap str all_types
begin
comment If the outpu... | def test_reduce_custom_dtype(self):
# We try multiple axis combinations even though axis should not matter.
idx = 0
for method in self.methods:
for input_dtype in imap(str, theano.scalar.all_types):
x = tensor.matrix(dtype=input_dtype)
for output... | Python | nomic_cornstack_python_v1 |
import numpy as np
import math , random , pickle
import constants as cons
comment Function to get initial parameters
function starting_positions
begin
set tuple startx starty = tuple random integer 5 width - 4 random integer 5 height - 4
set snakeCoords = list list startx starty list startx - 1 starty list startx - 2 s... | import numpy as np
import math, random, pickle
import constants as cons
def starting_positions(): # Function to get initial parameters
(startx, starty) = (random.randint(5, cons.width - 4), random.randint(5, cons.height - 4))
snakeCoords = [[startx, starty],[startx-1, starty],[startx-2, starty]]
food = get... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
import regression_lwlr as lw
function plot_lwlr X_test X_train y_train x1_test x1_train y1_test y1_train k
begin
string 加权线性回归函数可视化
figure
comment 六个子图,可视化不同k值时的数据拟合状况
for i in range 1 7
begin
comment 调用局部加权回归算法得到预测值
set c = call lwlrTest X_test X_train y_train k at i ... | import numpy as np
import matplotlib.pyplot as plt
import regression_lwlr as lw
def plot_lwlr(X_test,X_train,y_train,x1_test,x1_train,y1_test,y1_train,k):
"""加权线性回归函数可视化"""
plt.figure()
for i in range(1,7):#六个子图,可视化不同k值时的数据拟合状况
c = lw.lwlrTest(X_test, X_train, y_train,k[i-1])#调用局部加权回归算法得到预测值
... | Python | zaydzuhri_stack_edu_python |
from django.shortcuts import render
from django.http import HttpResponse
comment Create your views here.
function index request
begin
comment return HttpResponse("<p>hello Word, Hello, Django!</p>")
return call render request string index.html dict string user string hello Django
end function
function list request
begi... | from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
# return HttpResponse("<p>hello Word, Hello, Django!</p>")
return render(request, 'index.html', {'user':'hello Django'})
def list(request):
# return HttpResponse('lisfffft')
classname... | Python | zaydzuhri_stack_edu_python |
function testSlopeFromDict self
begin
function setSlope
begin
set slope = dict string r 1.3782 ; string g 278.32 ; string b 2
end function
assert raises TypeError setSlope
end function | def testSlopeFromDict(self):
def setSlope():
self.node.slope = {'r': 1.3782, 'g': 278.32, 'b': 2}
self.assertRaises(
TypeError,
setSlope
) | Python | nomic_cornstack_python_v1 |
function concat_matfiles exp_code exp_ids pathname subject_names exp_num=0
begin
comment Create a DataFrame from mat files by looping over subjects (subject_names)
set file_names = list directory pathname
set df = call DataFrame
for exp_id in exp_ids
begin
set temp2 = call DataFrame
for subject_name in subject_names
be... | def concat_matfiles(exp_code,exp_ids,pathname,subject_names,exp_num=0):
# Create a DataFrame from mat files by looping over subjects (subject_names)
file_names = os.listdir(pathname)
df = DataFrame()
for exp_id in exp_ids:
temp2 = DataFrame()
for subject_name in subject_names:
... | Python | zaydzuhri_stack_edu_python |
function adq aval
begin
if not aval
begin
comment None-in/None-out. This special keyword shouldn't be quoted.
return none
end
else
begin
comment ALMOST everything else should be quoted
return string '%s' % aval
end
end function | def adq(aval):
if not aval:
return None #None-in/None-out. This special keyword shouldn't be quoted.
else:
return "'%s'" % (aval) #ALMOST everything else should be quoted
| Python | nomic_cornstack_python_v1 |
function testInitialize self
begin
set dependencies_file = call _GetTestFilePath list string dependencies.ini
call _SkipIfPathNotExists dependencies_file
set dependency_helper = call DependencyHelper dependencies_file=dependencies_file
assert is not none dependency_helper
set dependencies_file = call _GetTestFilePath l... | def testInitialize(self):
dependencies_file = self._GetTestFilePath(['dependencies.ini'])
self._SkipIfPathNotExists(dependencies_file)
dependency_helper = dependencies.DependencyHelper(
dependencies_file=dependencies_file)
self.assertIsNotNone(dependency_helper)
dependencies_file = self._G... | Python | nomic_cornstack_python_v1 |
class InvalidYearError extends Exception
begin
pass
end class
function is_leap_year year
begin
if year % 4 == 0
begin
if year % 100 == 0
begin
if year % 400 == 0
begin
return true
end
else
begin
return false
end
end
else
begin
return true
end
end
else
begin
return false
end
end function
function get_valid_year
begin
wh... | class InvalidYearError(Exception):
pass
def is_leap_year(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
def get_valid_year():
... | Python | jtatman_500k |
string Unit tests for the water-regulation module
import unittest
from unittest.mock import MagicMock
from pump import Pump
from sensor import Sensor
from controller import Controller
from decider import Decider
class DeciderTests extends TestCase
begin
string Unit tests for the Decider class
set actions = dict string ... | """
Unit tests for the water-regulation module
"""
import unittest
from unittest.mock import MagicMock
from pump import Pump
from sensor import Sensor
from .controller import Controller
from .decider import Decider
class DeciderTests(unittest.TestCase):
"""
Unit tests for the Decider class
"""
acti... | Python | zaydzuhri_stack_edu_python |
function zone_transfer_request_id self
begin
return get pulumi self string zone_transfer_request_id
end function | def zone_transfer_request_id(self) -> pulumi.Input[str]:
return pulumi.get(self, "zone_transfer_request_id") | Python | nomic_cornstack_python_v1 |
function plot_lim x1 x2 log=false
begin
set tuple x1 x2 = tuple min x1 x2 max x1 x2
if not log
begin
set x1_lim = x1 * 100 // 1 / 100
set x2_lim = x2 * 100 // 1 + 1 / 100
end
else
begin
set x1_lim = 10 ^ floor call log10 x1
set x2_lim = 10 ^ floor call log10 x2 + 1
end
return tuple x1_lim x2_lim
end function | def plot_lim(x1, x2, log=False):
x1, x2 = min(x1, x2), max(x1, x2)
if not log:
x1_lim = (x1*100//1)/100
x2_lim = (x2*100//1+1)/100
else:
x1_lim = 10**np.floor(np.log10(x1))
x2_lim = 10**(np.floor(np.log10(x2))+1)
return x1_lim, x2_lim | Python | nomic_cornstack_python_v1 |
comment pylint: disable-msg=C6409
function find_module self fullname path=none
begin
comment The path arg is always going to be None because we aren't installed
comment on the meta_path.
comment keep pylint happy
set unused_path = path
return call FindModule self fullname
end function | def find_module(self, fullname, path=None): # pylint: disable-msg=C6409
# The path arg is always going to be None because we aren't installed
# on the meta_path.
unused_path = path # keep pylint happy
return self.env.FindModule(self, fullname) | Python | nomic_cornstack_python_v1 |
async function process_signalling self description
begin
await wait aio_allow_init
if call is_set
begin
debug string Reset called. Returning on coroutine
return none
end
set remote_description = call RTCSessionDescription description at string sdp description at string type
set sdp_type = description at string type
com... | async def process_signalling(
self, description: Dict[str, str]
) -> Optional[RTCSessionDescription]:
await self.sync_events.aio_allow_init.wait()
if self.sync_events.reset_event.is_set():
self.log.debug("Reset called. Returning on coroutine")
return None
re... | Python | nomic_cornstack_python_v1 |
comment Interview Bit: https://www.interviewbit.com/problems/longest-consecutive-sequence/
comment Given an unsorted array of integers,
comment find the length of the longest consecutive elements sequence.
class Solution
begin
comment @param A : tuple of integers
comment @return an integer
function longestConsecutive s... | # Interview Bit: https://www.interviewbit.com/problems/longest-consecutive-sequence/
# Given an unsorted array of integers,
# find the length of the longest consecutive elements sequence.
class Solution:
# @param A : tuple of integers
# @return an integer
def longestConsecutive(self, A):
if len(A) ... | Python | zaydzuhri_stack_edu_python |
import numpy as np
from sklearn.svm import SVC
comment X represents the 20 records with 4 numerical features
set X = array list list list list Ellipsis list
comment y represents the 4 categories
set y = array list 1 2 3 4
comment Create a svm classifier with linear kernel
set classifier = support vector classifier k... | import numpy as np
from sklearn.svm import SVC
# X represents the 20 records with 4 numerical features
X = np.array([[], [], [], ..., []])
# y represents the 4 categories
y = np.array([1, 2, 3, 4])
# Create a svm classifier with linear kernel
classifier = SVC(kernel='linear', random_state=0)
# Fit the data
classifi... | Python | flytech_python_25k |
comment The Hashtag Generator
comment The marketing team is spending way too much time typing in hashtags.
comment Let's help them with out own Hashtag Generator!
comment Here's the deal:
comment It must start with a hashtag (#).
comment All words must have their first letter capitalized.
comment If the final result is... | #The Hashtag Generator
#The marketing team is spending way too much time typing in hashtags.
#Let's help them with out own Hashtag Generator!
#Here's the deal:
#It must start with a hashtag (#).
#All words must have their first letter capitalized.
#If the final result is longer than 140 chars it must return false.
#... | Python | zaydzuhri_stack_edu_python |
function test_004_check_new_game self mock_input
begin
comment pylint: disable = unused-variable
set test_storage = call ChessStorage
set test_game = call ActiveGame string Test1 string Test2 string Test_Game none test_storage
set side_effect = GAME_MODE at string SAVE
with call captured_std as tuple out err inp
begin
... | def test_004_check_new_game(self, mock_input):
# pylint: disable = unused-variable
test_storage = ChessStorage()
test_game = ActiveGame("Test1", "Test2", "Test_Game", None, test_storage)
mock_input.side_effect = consts.GAME_MODE["SAVE"]
with captured_std() as (out, err, inp):
... | Python | nomic_cornstack_python_v1 |
function xsvgbranches self c1 c2
begin
set a1 = call vaxis
set a2 = call vaxis
set branches = filter lambda b l r -> l < call vaxis < r values _svgbranches
sort branches
return branches
end function | def xsvgbranches(self, c1, c2):
a1 = c1.branch().vaxis()
a2 = c2.branch().vaxis()
branches = filter(lambda b,l=a1,r=a2: l<b.vaxis()<r,
self._svgbranches.values())
branches.sort()
return branches | Python | nomic_cornstack_python_v1 |
function plot_model_results model_results_df x y hue=none xlabel=string ylabel=string title=string null_accuracy=none plot_max=true text_lift=1.03
begin
comment font to be used in axes labels
set font = dict string family string serif ; string color string darkred ; string weight string normal ; string size 16
comme... | def plot_model_results(model_results_df,
x, y, hue=None,
xlabel="", ylabel="",
title="",
null_accuracy=None,
plot_max=True,
text_lift=1.03):
# font to be used in axes labels
... | Python | nomic_cornstack_python_v1 |
function handleMarketDepth self msg
begin
string https://www.interactivebrokers.com/en/software/api/apiguide/java/updatemktdepth.htm https://www.interactivebrokers.com/en/software/api/apiguide/java/updatemktdepthl2.htm
comment make sure symbol exists
if tickerId not in keys marketDepthData
begin
set marketDepthData at ... | def handleMarketDepth(self, msg):
"""
https://www.interactivebrokers.com/en/software/api/apiguide/java/updatemktdepth.htm
https://www.interactivebrokers.com/en/software/api/apiguide/java/updatemktdepthl2.htm
"""
# make sure symbol exists
if msg.tickerId not in self.marke... | Python | jtatman_500k |
from math import *
from tkinter import *
from PIL import ImageTk , Image
import matplotlib.pyplot as plt
function not_all_the_time
begin
import nltk , re , pprint , json , datetime , ftfy , pandas , numpy as np
call download list string words string punkt string vader_lexicon string stopwords
from nltk.sentiment import... | from math import *
from tkinter import *
from PIL import ImageTk,Image
import matplotlib.pyplot as plt
def not_all_the_time():
import nltk, re, pprint, json, datetime, ftfy, pandas, numpy as np
nltk.download([
"words",
"punkt",
"vader_lexicon",
... | Python | zaydzuhri_stack_edu_python |
function dynamo_create_bearer_token_validator dynamo
begin
from authlib.oauth2.rfc6750 import BearerTokenValidator
class _BearerTokenValidator extends BearerTokenValidator
begin
function authenticate_token self token_string
begin
return call get_token token_string
end function
function request_invalid self request
begi... | def dynamo_create_bearer_token_validator(dynamo):
from authlib.oauth2.rfc6750 import BearerTokenValidator
class _BearerTokenValidator(BearerTokenValidator):
def authenticate_token(self, token_string):
return dynamo.get_token(token_string)
def request_invalid(self, request):
... | Python | nomic_cornstack_python_v1 |
comment programa para colocar el número de RUC
import libreria
import os
set x = string argv at 1
set m = call ruc x
set msg = string EL NÚMERO DE RUC ES:{}
print format msg x m | #programa para colocar el número de RUC
import libreria
import os
x=str(os.sys.argv[1])
m=libreria.ruc(x)
msg="EL NÚMERO DE RUC ES:{}"
print(msg.format(x,m))
| Python | zaydzuhri_stack_edu_python |
function _get_quarter dmin dmax
begin
return dmax - dmax - dmin * factor
end function | def _get_quarter(dmin, dmax):
return dmax - ((dmax - dmin) * factor) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment snarfs data from open s3 buckets
import xml.etree.ElementTree as ET
import requests
import sys
set url = argv at 1
comment get the s3 list if available
set r = get requests url
comment set the root element
set root = call fromstring text
comment this doesn't work, not sure why sinc... | #!/usr/bin/env python3
# snarfs data from open s3 buckets
import xml.etree.ElementTree as ET
import requests
import sys
url = sys.argv[1]
r = requests.get(url) # get the s3 list if available
root = ET.fromstring(r.text) # set the root element
# this doesn't work, not sure why since the
# ListBucketResult has... | Python | zaydzuhri_stack_edu_python |
function dtype self
begin
return dtype
end function | def dtype(self) -> torch.dtype:
return self._backend.dtype | Python | nomic_cornstack_python_v1 |
function test_default_cypher_file_extensions_recognised self
begin
set dummy_files = list join path string dir1 string queries1.cypher join path string dir1 string queries2.cql join path string dir2 string queries3.cyp join path string dir2 string exclude_queries.notcypher
call make_empty_dummy_files test_dir dummy_fil... | def test_default_cypher_file_extensions_recognised(self):
dummy_files = [
path.join("dir1", "queries1.cypher"),
path.join("dir1", "queries2.cql"),
path.join("dir2", "queries3.cyp"),
path.join("dir2", "exclude_queries.notcypher"),
]
self.make_empty... | Python | nomic_cornstack_python_v1 |
import sqlite3
set conn = call connect string database.db
set c = call cursor
execute c string SELECT * FROM table
set rows = call fetchall
for row in rows
begin
print row
end
comment This will connect to a SQLite database, execute a SQL query, and print the results. | import sqlite3
conn = sqlite3.connect('database.db')
c = conn.cursor()
c.execute('SELECT * FROM table')
rows = c.fetchall()
for row in rows:
print(row)
# This will connect to a SQLite database, execute a SQL query, and print the results.
| Python | flytech_python_25k |
function element_to_be_invisible self target timeout=DEFAULT_TIMEOUT
begin
function wrapped_webelement_disappears
begin
try
begin
comment init web_element within wait's timeout, not web_element's
call get_web_element_by_timeout PULL_FREQUENCY
if call is_displayed
begin
return false
end
comment return True if element is... | def element_to_be_invisible(self, target: ElementType, timeout: TimeoutType = DEFAULT_TIMEOUT):
def wrapped_webelement_disappears():
try:
# init web_element within wait's timeout, not web_element's
target.get_web_element_by_timeout(self.PULL_FREQUENCY)
... | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function meeting_rooms self intervals
begin
string [meet_time_slots] check whether there's overlap :return: bool
sort intervals
for i in range 1 length intervals
begin
if intervals at i at 0 < intervals at i - 1 at 1
begin
return false
end
end
return true
end function
end class | class Solution(object):
def meeting_rooms(self, intervals):
"""
[meet_time_slots]
check whether there's overlap
:return: bool
"""
intervals.sort()
for i in range(1, len(intervals)):
if intervals[i][0] < intervals[i - 1][1]:
return F... | Python | zaydzuhri_stack_edu_python |
import pygame
set WINDOW_HEIGHT = 300
set WINDOW_WIDTH = 300
set BLACK = tuple 0 0 0
set WHITE = tuple 255 255 255
set BLUE = tuple 100 100 250
set RED = tuple 255 80 80
set DISPLAY_KEYS = list K_a K_b K_c K_d K_e K_f K_g K_h K_i K_j K_k K_l K_m K_n K_o K_p K_q K_r K_s K_t K_u K_v K_w K_x K_y K_z K_SPACE K_PERIOD K_COM... | import pygame
WINDOW_HEIGHT = 300
WINDOW_WIDTH = 300
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (100, 100, 250)
RED = (255, 80, 80)
DISPLAY_KEYS = [pygame.K_a, pygame.K_b, pygame.K_c, pygame.K_d,
pygame.K_e, pygame.K_f, pygame.K_g, pygame.K_h,
pygame.K_i, pygame.K_j, pygame.K_k,... | Python | zaydzuhri_stack_edu_python |
comment https://github.com/rmit-s3492633-josh-caratelli/AI-2017-S1/blob/17ba9eba44e6b1566c2624dc367fbbfb11fc9481/contest/myTeam.py
comment myTeam.py
comment ---------
comment Licensing Information: You are free to use or extend these projects for
comment educational purposes provided that (1) you do not distribute or p... | #https://github.com/rmit-s3492633-josh-caratelli/AI-2017-S1/blob/17ba9eba44e6b1566c2624dc367fbbfb11fc9481/contest/myTeam.py
# myTeam.py
# ---------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you r... | Python | zaydzuhri_stack_edu_python |
function create_non_data_file self params file_data
begin
string Creates a new file-based dataset with the name provided in the files tuple. A valid file input would be: files = ( {'file': ("gtfs2", open('myfile.zip', 'rb'))} )
set api_prefix = string /api/imports2/
if not get params string method none
begin
set params... | def create_non_data_file(self, params, file_data):
'''
Creates a new file-based dataset with the name provided in the files
tuple. A valid file input would be:
files = (
{'file': ("gtfs2", open('myfile.zip', 'rb'))}
)
'''
api_prefix = '/api/imports2/'... | Python | jtatman_500k |
import numpy as np
from keras.models import Sequential
from keras.layers.core import Dense , Dropout , Flatten , Reshape
from keras.layers.convolutional import Conv2D , MaxPooling2D
from keras.utils import np_utils
import matplotlib.pyplot as plt
from sklearn.metrics import roc_auc_score
comment Load the data
set X = l... | import numpy as np
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Flatten, Reshape
from keras.layers.convolutional import Conv2D, MaxPooling2D
from keras.utils import np_utils
import matplotlib.pyplot as plt
from sklearn.metrics import roc_auc_score
# Load the data
X = np.load('... | Python | zaydzuhri_stack_edu_python |
from codegen import gen_source
from tkmlparser import Parser
from tokenizer import Tokenizer
from exceptionlib import TokenException , BrokenFrameException
from widget_type import WidgetType
import re
function main
begin
comment Parse tkml file
set p = call Parser string test.tkml
set t = call Tokenizer
comment Parse t... | from codegen import gen_source
from tkmlparser import Parser
from tokenizer import Tokenizer
from exceptionlib import TokenException, BrokenFrameException
from widget_type import WidgetType
import re
def main():
# Parse tkml file
p = Parser('test.tkml')
t = Tokenizer()
# Parse till EOF
tokens = [... | Python | zaydzuhri_stack_edu_python |
comment real signature unknown
function ConnectRegistry *args **kwargs
begin
pass
end function | def ConnectRegistry(*args, **kwargs): # real signature unknown
pass | Python | nomic_cornstack_python_v1 |
function add_forbidden_user self x
begin
if x not in forbidden_users
begin
with open string forbidden_users.txt string a+ as f_file
begin
write f_file string { x }
append forbidden_users x
end
close f_file
end
else
begin
pass
end
end function | def add_forbidden_user(self, x):
if x not in self.forbidden_users:
with open("forbidden_users.txt", "a+") as f_file:
f_file.write(f"{x}\n")
self.forbidden_users.append(x)
f_file.close()
else:
pass | Python | nomic_cornstack_python_v1 |
class AnimalShelter
begin
set dogs = list
set cats = list
set count = 0
function print self
begin
print string Dogs:
print dogs
print string Cats:
print cats
end function
function enqueueDog self dog
begin
append dogs tuple dog count
set count = count + 1
end function
function dequeueDog self
begin
set dog = dogs at ... | class AnimalShelter:
dogs = []
cats = []
count = 0
def print(self):
print("Dogs:")
print(self.dogs)
print("Cats:")
print(self.cats)
def enqueueDog(self, dog):
self.dogs.append((dog, self.count))
self.count = self.count + 1
def dequeueDog(self):
... | Python | zaydzuhri_stack_edu_python |
from tkinter import Tk
import tkinter as tk
from PIL import Image , ImageTk
import functions
function main_window
begin
string Строит главное окно.
set root = call Tk
title root string Распознавание голоса
call resizable false false
set width = call winfo_screenwidth // 2
set height = call winfo_screenheight // 2
call ... | from tkinter import Tk
import tkinter as tk
from PIL import Image, ImageTk
import functions
def main_window():
"""Строит главное окно."""
root = Tk()
root.title('Распознавание голоса')
root.resizable(False, False)
root.width = root.winfo_screenwidth() // 2
root.height = root.winfo_screenheight... | Python | zaydzuhri_stack_edu_python |
function set_tn_type self
begin
set tn_info at string type = string cp
end function | def set_tn_type(self):
self.tn_info["type"] = "cp" | Python | nomic_cornstack_python_v1 |
function is_prime n
begin
if n <= 1
begin
return false
end
for i in range 2 integer n ^ 0.5 + 1
begin
if n % i == 0
begin
return false
end
end
return true
end function
function count_primes n
begin
set count = 0
set total = 0
set primes = list
for i in range 2 n + 1
begin
if call is_prime i
begin
set count = count + 1... | def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def count_primes(n):
count = 0
total = 0
primes = []
for i in range(2, n + 1):
if is_prime(i):
count += 1
total +=... | Python | jtatman_500k |
class Dumbbell
begin
set total_weight = 0
function __init__ self material=string metal color=string black weight=10 price=200 type=string Adjustable dumbbell
begin
set material = material
set color = color
set weight = weight
set price = price
set type = type
set total_weight = total_weight + weight
end function
functi... | class Dumbbell:
total_weight = 0
def __init__(self, material="metal",color="black",weight=10,price=200,type="Adjustable dumbbell"):
self.material = material
self.color = color
self.weight = weight
self.price = price
self.type = type
Dumbbell.total_weight += self... | Python | zaydzuhri_stack_edu_python |
while g <= 50
begin
print g
set g = g + 2
end | while g <=50:
print(g)
g = g + 2 | Python | zaydzuhri_stack_edu_python |
function compare list_of_fingerprints parsedDHCP
begin
set hitlist = list
set option_list = parsedDHCP at 12
set tuple option53 option50 option12 option55 option60 = list comprehension call get_dhcp_option_value option_list i for i in list 53 50 12 55 60
set dhcptype = dhcp_types1 at encode option53 string hex
for x i... | def compare(list_of_fingerprints, parsedDHCP):
hitlist = []
option_list = parsedDHCP[12]
option53, option50, option12, option55, option60 = \
[get_dhcp_option_value(option_list, i) for i in [53, 50, 12, 55, 60]]
dhcptype = dhcp_types1[option53.encode('hex')]
for x in range(len(list_... | Python | nomic_cornstack_python_v1 |
function forward self X labels
begin
set features = call get_conv_feats X
set W = W
set T = T
set log_prob = apply CRFautograd W T features labels
return log_prob
end function | def forward(self, X, labels):
features = self.get_conv_feats(X)
W = self.W
T = self.T
log_prob = CRFautograd.apply(W, T, features, labels)
return log_prob | Python | nomic_cornstack_python_v1 |
function server name=string proxy-server headers_middleware=none server_software=none **kwargs
begin
string Function to Create a WSGI Proxy Server.
if headers_middleware is none
begin
set headers_middleware = list x_forwarded_for
end
set wsgi_proxy = call ProxyServerWsgiHandler headers_middleware
set kwargs at string s... | def server(name='proxy-server', headers_middleware=None,
server_software=None, **kwargs):
'''Function to Create a WSGI Proxy Server.'''
if headers_middleware is None:
headers_middleware = [x_forwarded_for]
wsgi_proxy = ProxyServerWsgiHandler(headers_middleware)
kwargs['server_software... | Python | jtatman_500k |
function deleteMenuItem restaurant_id menu_id
begin
set itemToDelete = call one
if method == string POST
begin
if itemToDelete != list
begin
delete itemToDelete
commit session
call flash string Menu item deleted
return call redirect call url_for string restaurantMenu restaurant_id=restaurant_id
end
end
else
begin
retu... | def deleteMenuItem(restaurant_id, menu_id):
itemToDelete = session.query(MenuItem).filter_by(id=menu_id).one()
if request.method == 'POST':
if itemToDelete != []:
session.delete(itemToDelete)
session.commit()
flash("Menu item deleted")
return redirect(url_for('restaurantMenu', restaurant_id=restaurant_i... | Python | nomic_cornstack_python_v1 |
comment real signature unknown; restored from __doc__
function getUseInitialFlow self
begin
pass
end function | def getUseInitialFlow(self): # real signature unknown; restored from __doc__
pass | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Sat Sep 15 20:23:41 2018 @author: Pshypher
import turtle
function drawRuler x y height=50 width=300
begin
if height <= 1
begin
call penup
call goto x y
call pendown
return
end
else
begin
call penup
call goto x y
call pendown
call forward width
backward turtle width / 2
ca... | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 15 20:23:41 2018
@author: Pshypher
"""
import turtle
def drawRuler(x,y,height=50,width=300):
if height <= 1:
turtle.penup()
turtle.goto(x,y)
turtle.pendown()
return
else:
turtle.penup()
turtle.goto(x,y... | Python | zaydzuhri_stack_edu_python |
set ma = decimal input string ma:
set mb = decimal input string mb:
set v0 = decimal input string v0:
set vf = 2 * ma + mb / ma + mb * v0
print vf | ma=float(input("ma:"))
mb=float(input("mb:"))
v0=float(input("v0:"))
vf=(((2*ma)+mb)/(ma+mb))*v0
print(vf) | Python | zaydzuhri_stack_edu_python |
comment slider-crank linkage
comment Newton - Raphson
comment Isaac Sanchez - UGTO
import numpy as np
from math import cos , sin , pi , sqrt
comment Parameters of the mechanism
set e = 0
set a2 = 3
set a3 = 8
set theta_e = 0
set theta_2 = 40 * pi / 180
set w2 = 209.43951
set alpha_2 = 0
comment Set initial Values
set t... | ## slider-crank linkage
## Newton - Raphson
## Isaac Sanchez - UGTO
import numpy as np
from math import cos, sin, pi, sqrt
# Parameters of the mechanism
e = 0
a2 = 3
a3 = 8
theta_e = 0
theta_2 = (40 * pi) / 180
w2 = 209.43951
alpha_2 = 0
#Set initial Values
theta3_s = np.array([[(300 * pi) / 180], [5]])
w3_s = np.a... | Python | zaydzuhri_stack_edu_python |
comment 在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。
comment 计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。
comment 示例 1:
comment 输入: [3,2,3,null,3,null,1]
comment 3
comment / \
comment 2 3
comment \ \
comment 3 1
comment 输出: 7
co... | # 在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 除了“根”之外,每栋房子有且只有一个“父“房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。
#
# 计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。
#
# 示例 1:
#
# 输入: [3,2,3,null,3,null,1]
#
# 3
# / \
# 2 3
# \ \
# 3 1
#
# 输出: 7
# 解释: 小偷一晚能够盗取的最高金额 = 3 + 3 + ... | Python | zaydzuhri_stack_edu_python |
import time
set time1 = time
function func
begin
set input_f = open string input_9.1.txt string r
set input_d = list comprehension integer i for i in split read input_f
set found = false
set i = 0
while not found
begin
set found = true
for tuple j num1 in enumerate input_d at slice i : i + 25 :
begin
for tuple k num2 i... | import time
time1 = time.time()
def func():
input_f = open('input_9.1.txt', 'r')
input_d = [int(i) for i in input_f.read().split()]
found = False
i = 0
while not found:
found = True
for j, num1 in enumerate(input_d[i:i+25]):
for k, num2 in enumerate(input_d[i:i+25]):
... | Python | zaydzuhri_stack_edu_python |
import sys
import pymongo
import requests
from bs4 import BeautifulSoup
import utils.config as config
from ACLUrlsCrawler import ACLUrlsCrawler
append path string ./utils/
class ContentManager
begin
string 爬取论文的基本内容
set database = db
set collection = string basicInfo
set urlCollection = collection
function __init__ sel... | import sys
import pymongo
import requests
from bs4 import BeautifulSoup
import utils.config as config
from ACLUrlsCrawler import ACLUrlsCrawler
sys.path.append('./utils/')
class ContentManager():
'''
爬取论文的基本内容
'''
database = config.db
collection = "basicInfo"
urlCollection = ACLUrlsCrawler.col... | Python | zaydzuhri_stack_edu_python |
function validateWebsites self list_of_websites
begin
if list_of_websites
begin
set checked_urls = list
for site in list_of_websites
begin
if not is instance site at string url str or is space site at string url or site at string url == string
begin
raise call ValueError string Invalid url value: + string site at str... | def validateWebsites(self, list_of_websites):
if list_of_websites:
checked_urls = []
for site in list_of_websites:
if not isinstance(site['url'], str) or site['url'].isspace() or site['url'] == "":
raise ValueError("Invalid url value: " + str(site['url... | 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.