code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
async function execute self params
begin
return call CommentResult
end function | async def execute(self, params: CommentParams) -> CommentResult:
return CommentResult() | Python | nomic_cornstack_python_v1 |
import boto3
set s3 = call client string s3
set s3_resource = call resource string s3
function list_Folder bucket
begin
set all_objects = call list_objects Bucket=bucket
for object in all_objects at string Contents
begin
print object at string Key
end
end function
call list_Folder string <<bucket-name>> | import boto3
s3 = boto3.client('s3')
s3_resource = boto3.resource('s3')
def list_Folder(bucket):
all_objects = s3.list_objects(Bucket=bucket)
for object in all_objects['Contents']:
print(object['Key'])
list_Folder("<<bucket-name>>")
| Python | zaydzuhri_stack_edu_python |
function to_str self
begin
return call pformat call to_dict
end function | def to_str(self):
return pprint.pformat(self.to_dict()) | Python | nomic_cornstack_python_v1 |
function video_list_sorted self pathitems
begin
set menu_data = get MAIN_MENU_ITEMS pathitems at 1
comment Dynamic menus
if not menu_data
begin
set menu_data = call get_value pathitems at 1 table=TABLE_MENU_DATA data_type=dict
end
set call_args = dict string pathitems pathitems ; string menu_data menu_data ; string sub... | def video_list_sorted(self, pathitems):
menu_data = G.MAIN_MENU_ITEMS.get(pathitems[1])
if not menu_data: # Dynamic menus
menu_data = G.LOCAL_DB.get_value(pathitems[1], table=TABLE_MENU_DATA, data_type=dict)
call_args = {
'pathitems': pathitems,
'menu_data': ... | Python | nomic_cornstack_python_v1 |
function find_max numbers
begin
set max_num = numbers at 0
for num in numbers
begin
if num > max_num
begin
set max_num = num
end
end
return max_num
end function
set numbers = list 1 5 23 9
set max_num = call find_max numbers
comment Output is 23
print max_num | def find_max(numbers):
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
return max_num
numbers = [1, 5, 23, 9]
max_num = find_max(numbers)
print(max_num) # Output is 23
| Python | flytech_python_25k |
function mUd_closed T Z
begin
set sq2 = square root 2
set A = + exp - Z ^ 2 / 2 * T * call wofz - 1j * Z / square root 2 * T + square root T
comment A = +np.exp(-T+1j*Z*sq2)*erfc(-Z/np.sqrt(2*T) - 1j*np.sqrt(T))
return imag / sq2
end function | def mUd_closed(T, Z):
sq2 = np.sqrt(2)
A = +np.exp(-Z**2/(2*T))*wofz(-1j*Z/np.sqrt(2*T) + np.sqrt(T))
# A = +np.exp(-T+1j*Z*sq2)*erfc(-Z/np.sqrt(2*T) - 1j*np.sqrt(T))
return A.imag/sq2 | Python | nomic_cornstack_python_v1 |
import problem
import math
import utility
class Problem extends Problem
begin
function __init__ self
begin
set number = 52
set question = string Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits in some order.
call __init__ self number question
end function
function getAns... | import problem
import math
import utility
class Problem(problem.Problem):
def __init__(self):
number = 52
question = 'Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits in some order.'
problem.Problem.__init__(self, number, question)
def getAnswer(self):
def ... | Python | zaydzuhri_stack_edu_python |
comment Definition for singly-linked list.
comment class ListNode:
comment def __init__(self, x):
comment self.val = x
comment self.next = None
class Solution
begin
function reverseBetween self head m n
begin
set sum1 = 0
set x = head
set flag = call ListNode 0
set next = head
set res = 0
while x != none
begin
set sum1... | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
sum1 = 0
x = head
flag = ListNode(0)
flag.... | Python | zaydzuhri_stack_edu_python |
function create_s256_code_challenge code_verifier
begin
set data = call digest
return call to_unicode call urlsafe_b64encode data
end function | def create_s256_code_challenge(code_verifier):
data = hashlib.sha256(to_bytes(code_verifier, 'ascii')).digest()
return to_unicode(urlsafe_b64encode(data)) | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function subsets self nums
begin
string :type nums: List[int] :rtype: List[List[int]]
if length nums < 1
begin
return nums
end
set NewSum = sorted nums
set result = list
call helper NewSum result list list
return result
end function
function helper self nums ret temp index
begin
if... | class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) < 1:
return nums
NewSum = sorted(nums)
result = []
self.helper(NewSum, result, [], [])
return result
def helper... | Python | zaydzuhri_stack_edu_python |
function save_data df database_filename
begin
set engine = call create_engine string sqlite:/// + database_filename
call to_sql string DisasterResponse engine index=false if_exists=string replace
end function | def save_data(df, database_filename):
engine = create_engine('sqlite:///' + database_filename)
df.to_sql('DisasterResponse', engine, index=False, if_exists='replace') | Python | nomic_cornstack_python_v1 |
string Verify if the function find_date correctly parses and returns the month, day, and year of a date found in a given string.
import make_european
function test_find_date
begin
string Assert correct return order and values of the find_date function.
comment Expected input.
assert call find_date string 01/25/1984:coi... | """Verify if the function find_date correctly parses and returns the
month, day, and year of a date found in a given string.
"""
import make_european
def test_find_date():
"""Assert correct return order and values of the find_date
function.
"""
# Expected input.
assert make_european.find_date('01/2... | Python | zaydzuhri_stack_edu_python |
import random
print string Go Fish
set cpile = 60
set suits = list string spades string diamonds string clubs string hearts
set faces = list string two string three string four string five string six string seven string eight string nine string ten string jack string queen string king string ace
set pcards = list
set ... | import random
print("Go Fish")
cpile = 60
suits = ["spades", "diamonds", "clubs", "hearts"]
faces = ["two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "jack", "queen", "king", "ace"]
pcards = []
ccards = []
for x in range(8):
pface = random.choice(faces)
psuit = random.choice(suits)
pc... | Python | zaydzuhri_stack_edu_python |
function _get_next_waypoint self tolerance_step
begin
print string Getting new nav plan.
for i in range 4
begin
try
begin
set plan = call get_plan goal tolerance=tolerance use_home_layer=avoid_home
comment plan received
break
end
except ServiceException
begin
print string ServiceException.
if i < 3
begin
print string E... | def _get_next_waypoint(self, tolerance_step):
print('\nGetting new nav plan.')
for i in range(4):
try:
self.plan = self.swarmie.get_plan(
self.goal,
tolerance=self.tolerance,
use_home_layer=self.avoid_home
... | Python | nomic_cornstack_python_v1 |
comment 测试call可调用对象方法
class SalaryAccount
begin
string 计算工资
function __call__ self salary
begin
print string 算工资啦-----
set yearSalary = salary * 12
comment 国家规定平均每月工作日
set daySalary = salary // 22.5
set hourSalary = daySalary // 8
comment 可以返回元组,列表,字典
return dictionary yearSalary=yearSalary monthSalary=salary daySalary... | #测试call可调用对象方法
class SalaryAccount:
"""计算工资"""
def __call__(self, salary):
print("算工资啦-----")
yearSalary = salary*12
daySalary = salary//22.5 #国家规定平均每月工作日
hourSalary = daySalary//8
return dict(yearSalary=yearSalary,monthSalary=salary,daySalary=daySalary,hourSalary=hour... | Python | zaydzuhri_stack_edu_python |
function find_usage self
begin
string Determine the current usage for each limit of this service, and update corresponding Limit via :py:meth:`~.AwsLimit._add_current_usage`.
set ignore_statuses = list string DELETE_COMPLETE
debug string Checking usage for service %s service_name
call connect
for lim in values limits
b... | def find_usage(self):
"""
Determine the current usage for each limit of this service,
and update corresponding Limit via
:py:meth:`~.AwsLimit._add_current_usage`.
"""
ignore_statuses = [
'DELETE_COMPLETE'
]
logger.debug("Checking usage for serv... | Python | jtatman_500k |
comment RANJAN02 - Tower Of Hanoi - Revisited
comment Author: Tarun Kumar
comment E-mail: tarunkumar281200@gmail.com
set t = integer input
while t > 0
begin
set n = integer input
set n = 3 ^ n - 1
print n
set t = t - 1
end | # RANJAN02 - Tower Of Hanoi - Revisited
# Author: Tarun Kumar
# E-mail: tarunkumar281200@gmail.com
t=int(input())
while t>0:
n=int(input())
n=(3**n)-1
print (n)
t=t-1
| Python | zaydzuhri_stack_edu_python |
function _create_traffic_graph self metric
begin
if field_name != string tx_bytes or string traffic not in AUTO_GRAPHS
begin
return
end
set graph = call Graph metric=metric description=format call _ string {0} traffic (GB) key query=string SELECT SUM(tx_bytes) / 1000000000 AS upload, SUM(rx_bytes) / 1000000000 AS downl... | def _create_traffic_graph(self, metric):
if (metric.field_name != 'tx_bytes' or 'traffic' not in monitoring_settings.AUTO_GRAPHS):
return
graph = Graph(metric=metric,
description=_('{0} traffic (GB)').format(metric.key),
query="SELECT SUM(tx_bytes)... | Python | nomic_cornstack_python_v1 |
function count self
begin
Ellipsis
end function | def count(self) -> jsii.Number:
... | Python | nomic_cornstack_python_v1 |
from tkinter import *
class DefinitionLayout
begin
set frame = none
set entries = none
function __init__ self master
begin
set master = master
set frame = call Frame master width=600 height=400 padx=20 pady=30
call pack
set entries = list
set promptText = call pack pady=30
set continueButton = call pack pady=5
set add... | from tkinter import *
class DefinitionLayout:
frame = None
entries = None
def __init__(self, master):
self.master = master
self.frame = Frame(master, width = 600, height=400, padx=20, pady=30)
self.frame.pack()
self.entries = []
promptText = Label(
se... | Python | zaydzuhri_stack_edu_python |
comment program sprawdzajacy po wprowadzeniu imienia
comment czy jestes women czy men ?
set imie = string anna
set slowo = imie at - 1
if slowo != string a or imie == string kuba
begin
print string Jesteś MEN
end
else
begin
print string Jeteś WOMEN
end | #program sprawdzajacy po wprowadzeniu imienia
#czy jestes women czy men ?
imie = "anna"
slowo = imie[-1]
if slowo != 'a' or imie == 'kuba':
print("Jesteś MEN")
else:
print("Jeteś WOMEN")
| Python | zaydzuhri_stack_edu_python |
comment 定义三角形类,实现求三角形周长和面积的方法,属性为三个边长
import math
set a = decimal input string a=
set b = decimal input string b=
set c = decimal input string c=
if a + b > c and a + c > b and b + c > a
begin
set d = a + b + c
set e = a + b + c / 2
set f = square root e * e - a * e - b * e - c
print string 三角形的周长为: + string d
print st... | # 定义三角形类,实现求三角形周长和面积的方法,属性为三个边长
import math
a=float(input('a='))
b=float(input('b='))
c=float(input('c='))
if a+b>c and a+c>b and b+c>a:
d=a+b+c
e=(a+b+c)/2
f=math.sqrt(e*(e-a)*(e-b)*(e-c))
print('三角形的周长为:'+str(d))
print('三角形的面积为:%f' % f)
else:
print('三条变得长度不能构成三角形') | Python | zaydzuhri_stack_edu_python |
import math
import numpy as np
import pandas as pd
from collections import deque
import sys
import time
function load_graph graph_file
begin
string The graph is stored in a .csv file in the form of an adjacency matrix. :param graph_file: the name of the graph .csv file :type graph_file: String :return: the graph as adj... | import math
import numpy as np
import pandas as pd
from collections import deque
import sys
import time
def load_graph(graph_file):
"""
The graph is stored in a .csv file in the form of an adjacency matrix.
:param graph_file: the name of the graph .csv file
:type graph_file: String
:return: the graph as adjacenc... | Python | zaydzuhri_stack_edu_python |
class Fibonacci extends object
begin
function __init__ self all_num
begin
set allNum = all_num
set currentNum = 0
set a = 0
set b = 1
end function
function __iter__ self
begin
return self
end function
function __next__ self
begin
if currentNum < allNum
begin
set ret = a
set tuple a b = tuple b a + b
set currentNum = cu... | class Fibonacci(object):
def __init__(self , all_num):
self.allNum = all_num;
self.currentNum = 0;
self.a=0;
self.b=1;
def __iter__(self):
return self;
def __next__(self):
if self.currentNum<self.allNum:
ret = self.a;
self.a , sel... | Python | zaydzuhri_stack_edu_python |
function _get_parser
begin
set parser = call ArgumentParser prog=string bids
set subparsers = call add_subparsers help=string BIDS workflows
comment show()
set show_parser = call add_parser string show help=string Print out the schema
call set_defaults func=show
call add_argument string schema_path type=Path help=strin... | def _get_parser():
parser = argparse.ArgumentParser(prog='bids')
subparsers = parser.add_subparsers(help='BIDS workflows')
# show()
show_parser = subparsers.add_parser(
'show',
help=('Print out the schema'),
)
show_parser.set_defaults(func=show)
show_parser.add_argument(
... | Python | nomic_cornstack_python_v1 |
function __init__ self mjdCol=string observationStartMJD units=string surveyLength=10.0 **kwargs
begin
set mjdCol = mjdCol
call __init__ col=mjdCol units=units keyword kwargs
set surveyLength = surveyLength
end function | def __init__(self, mjdCol='observationStartMJD', units='',
surveyLength=10., **kwargs):
self.mjdCol = mjdCol
super(UniformityMetric, self).__init__(col=self.mjdCol, units=units, **kwargs)
self.surveyLength = surveyLength | Python | nomic_cornstack_python_v1 |
function total_amortization self
begin
return sum table at string amortization
end function | def total_amortization(self):
return sum(self.table["amortization"]) | Python | nomic_cornstack_python_v1 |
comment *************************---DAY 20---***********************************
set numbers = list 7 5 1 3
set first = numbers at 0
print first
set last = numbers at 3
print last
set firstTwo = numbers at slice 0 : 2 :
print firstTwo | #########################################################################
#*************************---DAY 20---***********************************
numbers = [7, 5, 1, 3]
first = numbers[0]
print (first)
last = numbers [3]
print (last)
firstTwo = numbers[0:2]
print (firstTwo)
| Python | zaydzuhri_stack_edu_python |
function mylinearsvm X Y lamb cost_values=none clf_errors=none val_errors=none X_val=none Y_val=none max_iter=20
begin
set t = 0
comment Sensible default
set epsilon = 0.001
comment Initialize to small values
set beta = reshape call normal size=shape at 1 - 1 1 * 0.01
set theta = zeros shape
set grad = none
for i in ra... | def mylinearsvm(X, Y, lamb, cost_values=None, clf_errors=None, val_errors=None, X_val=None, Y_val=None, max_iter=20):
t = 0
epsilon = 0.001 # Sensible default
# Initialize to small values
beta = np.random.normal(size=X.shape[1]).reshape(-1, 1) * 0.01
theta = np.zeros(beta.shape)
grad = None
... | Python | nomic_cornstack_python_v1 |
import bcrypt
class HashPassword
begin
string Hash password, compare hash with bcrypt, salt and pepper
function __init__ self pepper
begin
set pepper = pepper
end function
function create_hashed self plaintext
begin
string Return hashed password from plain text password
return call hashpw plaintext + pepper call gensal... | import bcrypt
class HashPassword:
'''Hash password, compare hash with bcrypt, salt and pepper'''
def __init__(self, pepper):
self.pepper = pepper
def create_hashed(self, plaintext):
'''Return hashed password from plain text password'''
return bcrypt.hashpw(plaintext + sel... | Python | zaydzuhri_stack_edu_python |
function titles_generator self movies_world world
begin
for movie in movies_world
begin
set movie at string world = world
yield movie
end
end function | def titles_generator(self, movies_world, world):
for movie in movies_world:
movie['world'] = world
yield movie | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
import sys , re , itertools
import numpy as np
import matplotlib as mlp
call use string Agg
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from keras.utils import plot_model
from keras import activations
... | # -*- coding: utf-8 -*-
import sys, re, itertools
import numpy as np
import matplotlib as mlp
mlp.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
from keras.utils import plot_model
from keras import activations
from sklearn.... | Python | zaydzuhri_stack_edu_python |
function addTwoNumbers self l1 l2
begin
function fetchValueFromListNode node
begin
string Traverse given linked list and generate 1 integer. If given list is something like this (2 -> 4 -> 3), this function returns 3 * 100 + 4 * 10 + 2.
set curNode = node
set result = val
set loopCount = 1
while next is not none
begin
... | def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
def fetchValueFromListNode(node: ListNode) -> int:
"""
Traverse given linked list and generate 1 integer.
If given list is something like this (2 -> 4 -> 3),
this function returns 3 * 100 + 4 * 10 +... | Python | nomic_cornstack_python_v1 |
import numpy as np
import chess
import chess.pgn
from tqdm import tqdm
from collections import deque
from random import shuffle
from network import Network
from mctsv2 import Mcts
import adapter
set end_states = dict string 1-0 1 ; string 0-1 - 1 ; string 1/2-1/2 0
class Coach
begin
string docstring
function __init__ s... | import numpy as np
import chess
import chess.pgn
from tqdm import tqdm
from collections import deque
from random import shuffle
from network import Network
from mctsv2 import Mcts
import adapter
end_states = {'1-0': 1, '0-1': -1, '1/2-1/2' : 0}
class Coach():
"""
docstring
"""
def __init__(self, nnet... | Python | zaydzuhri_stack_edu_python |
import json
import requests
set preurl = string http://apis.is/car?number=
set url = string http://apis.is/car?number=zz690
set upl = json get requests url
set abc = string abcdefghijklmnopqrstuvwxyz
set char1 = string a
set char2 = string b
set platechars = string something
set numberplatecount = 0 | import json
import requests
preurl = "http://apis.is/car?number="
url = "http://apis.is/car?number=zz690"
upl = requests.get(url).json()
abc = "abcdefghijklmnopqrstuvwxyz"
char1 = "a"
char2 = "b"
platechars = "something"
numberplatecount = 0
| Python | zaydzuhri_stack_edu_python |
function elapsed_time_in_hours start end email customer_time rt_time
begin
set td = call from_utimestamp end - call from_utimestamp start
set total_seconds = microseconds + seconds + days * 24 * 3600 * 10 ^ 6 / 10 ^ 6
set elapsed = total_seconds / 3600.0
if email and string redturtle in email or false
begin
set rt_time... | def elapsed_time_in_hours(start, end, email, customer_time, rt_time):
td = from_utimestamp(end) - from_utimestamp(start)
total_seconds = (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
elapsed = total_seconds / 3600.0
if email and 'redturtle' in email or False:
rt_time +=... | Python | nomic_cornstack_python_v1 |
comment pylint:skip-file
import sys , random , time , math
insert path 0 string ../../python
import mxnet as mx
import numpy as np
from collections import namedtuple
from nce import *
from operator import itemgetter
from optparse import OptionParser
from numpy import linalg as la
call set_printoptions threshold=nan
fun... | # pylint:skip-file
import sys, random, time, math
sys.path.insert(0, "../../python")
import mxnet as mx
import numpy as np
from collections import namedtuple
from nce import *
from operator import itemgetter
from optparse import OptionParser
from numpy import linalg as la
np.set_printoptions(threshold=np.nan)
def ge... | Python | zaydzuhri_stack_edu_python |
function __create_log_file
begin
if not log_file_location == string
begin
if not ends with log_file_location string /
begin
raise exception string Invalid location of log file.
end
if not exists path log_file_location
begin
make directories log_file_location
end
end
comment Needed for creating the file
with open log_f... | def __create_log_file():
if not log_file_location == '':
if not log_file_location.endswith('/'):
raise Exception('Invalid location of log file.')
if not os.path.exists(log_file_location):
os.makedirs(log_file_location)
# Needed for creating the file
with open(log_fil... | Python | nomic_cornstack_python_v1 |
from tests.apiTesting.api.project_api import ProjectApi
function test_6_update_work_package
begin
set new_description = string new description 13
set work_package_id = string 34
comment Get Lock Version for update
set response = call get_work_package_by_id work_package_id
set response_json = json response
set lock_vers... | from tests.apiTesting.api.project_api import ProjectApi
def test_6_update_work_package():
new_description = "new description 13"
work_package_id = "34"
# Get Lock Version for update
response = ProjectApi().get_work_package_by_id(work_package_id)
response_json = response.json()
lock_version =... | Python | zaydzuhri_stack_edu_python |
function get_layout_template_slug self layout_section_slug
begin
set layout_object = call _get_layout_object layout_section_slug
if layout_object
begin
return template
end
else
begin
return LAYOUT_DEFAULT
end
end function | def get_layout_template_slug(self, layout_section_slug):
layout_object = self._get_layout_object(layout_section_slug)
if layout_object:
return layout_object.template
else:
return settings.LAYOUT_DEFAULT | Python | nomic_cornstack_python_v1 |
function calculateRandIndex original cluster
begin
set N1 = length original
set N2 = length cluster
if N1 != N2
begin
raise call ValueEroor string input length not the same
end
set count = 0
for i in range N2
begin
for j in range i + 1 N2
begin
if cluster at i == cluster at j and original at i == original at j
begin
se... | def calculateRandIndex(original,cluster):
N1=len(original)
N2=len(cluster)
if N1 != N2:
raise ValueEroor("input length not the same")
count=0
for i in range(N2):
for j in range(i+1,N2):
if cluster[i]==cluster[j] and original[i]==original[j]:
count=count+1
... | Python | zaydzuhri_stack_edu_python |
import urllib
import urllib.request
from bs4 import BeautifulSoup
import os
function make_soup url
begin
set page = url open url
set soupdata = call BeautifulSoup page string html.parser
return soupdata
end function
string print("Enter the term to be searched") term= input()
set soup = call make_soup string https://www... | import urllib
import urllib.request
from bs4 import BeautifulSoup
import os
def make_soup(url):
page= urllib.request.urlopen(url)
soupdata = BeautifulSoup(page, "html.parser")
return soupdata
"""
print("Enter the term to be searched")
term= input()
"""
soup = make_soup("https://www.google.co.in/searc... | Python | zaydzuhri_stack_edu_python |
comment True = read, False = write
set INSTRUCTIONS = dict 1 tuple string ADD tuple true true false ; 2 tuple string MUL tuple true true false ; 3 tuple string INP tuple false none none ; 4 tuple string OUT tuple true none none ; 5 tuple string JZ tuple true true none ; 6 tuple string JNZ tuple true true none ; 7 tuple... | # True = read, False = write
INSTRUCTIONS = {
1: ('ADD', (True, True, False)),
2: ('MUL', (True, True, False)),
3: ('INP', (False, None, None)),
4: ('OUT', (True, None, None)),
5: ('JZ ', (True, True, None)),
6: ('JNZ', (True, True, None)),
7: ('LT ', (True, True, False)),
8: ('EQ ', (Tr... | Python | zaydzuhri_stack_edu_python |
function spyCoder n s
begin
set a = list
for i in range 0 length n
begin
if ordinal n at i + s >= 90 or ordinal n at i >= 90
begin
set code = replace n n at i character s + ordinal n at i - 90 + 64
append a code at i
end
else
if n at i == string
begin
append a n at i
end
else
begin
set code = replace n n at i charact... | def spyCoder(n,s):
a = []
for i in range (0,len(n)):
if (ord(n[i])+s)>= 90 or ord(n[i]) >= 90:
code = n.replace(n[i],chr(s+ord(n[i])-90+64))
a.append(code[i])
elif n[i] == ' ':
a.append(n[i])
else:
code = n.replace(n[i],chr(s+ord(n[i])))
a.append(cod... | Python | zaydzuhri_stack_edu_python |
from typing import Annotated , get_type_hints
comment Alias to annotation
set LENGTH = Annotated at tuple int string Length of object
function rect_area length breadth
begin
return length * breadth
end function
function square_area length
begin
return length * length
end function
comment Provides metadata
print __annot... | from typing import Annotated, get_type_hints
LENGTH = Annotated[int, 'Length of object'] # Alias to annotation
def rect_area(length: Annotated[int, 'Length of rectangle'],
breadth: Annotated[int, 'Breadth of rectangle']) \
-> Annotated[int, 'Area of rectangle']:
return length * bread... | Python | zaydzuhri_stack_edu_python |
function load_model model *params
begin
set results = list
for x in params
begin
try
begin
comment Parse only the added parameters
set path_obj = model keyword x
append results path_obj
end
except ValidationError as ve
begin
raise call ProtGraphException HTTP_400 json ve
end
end
return if expression length results == ... | def load_model(model: BaseModel, *params: dict):
results = []
for x in params:
try:
# Parse only the added parameters
path_obj = model(**x)
results.append(path_obj)
except ValidationError as ve:
raise ProtGraphException(falcon.HTTP_400, ve.json())
... | Python | nomic_cornstack_python_v1 |
comment -------------------------------------------------------------------------------
comment Name: module1
comment Purpose:
comment Author: ufu1
comment Created: 08/02/2017
comment Copyright: (c) ufu1 2017
comment Licence: <your licence>
comment -----------------------------------------------------------------------... | #-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: ufu1
#
# Created: 08/02/2017
# Copyright: (c) ufu1 2017
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
... | Python | zaydzuhri_stack_edu_python |
function convert_bytes bytes_ K=1 ? 10 M=1 ? 20 G=1 ? 30 T=1 ? 40
begin
set fn = decimal bytes_
if bytes_ >= T
begin
return string %.1fT % fn / T
end
else
if bytes_ >= G
begin
return string %.1fG % fn / G
end
else
if bytes_ >= M
begin
return string %.1fM % fn / M
end
else
if bytes_ >= K
begin
return string %.1fK % fn /... | def convert_bytes(bytes_, K=1 << 10, M=1 << 20, G=1 << 30, T=1 << 40):
fn = float(bytes_)
if bytes_ >= T:
return '%.1fT' % (fn / T)
elif bytes_ >= G:
return '%.1fG' % (fn / G)
elif bytes_ >= M:
return '%.1fM' % (fn / M)
elif bytes_ >= K:
return '%.1fK' % (fn ... | Python | nomic_cornstack_python_v1 |
function _validate self
begin
string Validate the class entries.
set checker = tuple _check0 _check1 _check2 _check3 _check4 _check5
if not 0 <= field_type <= 5
begin
raise call NotImplementedError string unsupported widget type
end
if type rect is not Rect
begin
raise call ValueError string invalid rect
end
if isInfin... | def _validate(self):
"""Validate the class entries.
"""
checker = (self._check0, self._check1, self._check2, self._check3,
self._check4, self._check5)
if not 0 <= self.field_type <= 5:
raise NotImplementedError("unsupported widget type")
if type(sel... | Python | jtatman_500k |
comment Name: James Sherman
comment Student ID: 900114
comment Assignment Problem Set 1
comment Due Date: September 25, 2018 1:15
print string a string b string c sep=string --- end=string ---
print string d string e string f sep=string end=string ***
print string g string h string i sep=string --- | ###########################################
### Name: James Sherman
### Student ID: 900114
### Assignment Problem Set 1
### Due Date: September 25, 2018 1:15
###########################################
print("a","b","c",sep = "---", end = "---")
print("d","e","f",sep = "", end = "***")
print("g","h","i",sep =... | Python | zaydzuhri_stack_edu_python |
function define self n_inputs n_classes
begin
set n_inputs = n_inputs
set n_classes = n_classes
set model = sequential list dense 32 activation=relu input_shape=tuple n_inputs dense 16 activation=relu dense n_classes activation=softmax
debug string Defined model layers.
compile optimizer=string adam loss=string sparse_... | def define(self, n_inputs, n_classes):
self.n_inputs = n_inputs
self.n_classes = n_classes
self.model = tf.keras.Sequential([
tf.keras.layers.Dense(32,
activation=tf.nn.relu,
input_shape=(self.n_inputs,)
... | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import numpy as np
comment Fixing random state for reproducibility
seed 19680801
comment the bar
set x = call rand 500 > 0.7
set barprops = dictionary aspect=string auto cmap=string binary interpolation=string nearest
set fig = figure
comment a vertical barcode
set ax1 = call add_axes li... | import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
# the bar
x = np.random.rand(500) > 0.7
barprops = dict(aspect='auto', cmap='binary', interpolation='nearest')
fig = plt.figure()
# a vertical barcode
ax1 = fig.add_axes([0.1, 0.1, 0.1, 0.8])
ax1.s... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Mon Apr 30 15:14:12 2018 @author: InfiniteJest
import os
import re
change directory string C:\Users\InfiniteJest\Documents\Python_Scripts\Physics
import subprocess
import shutil
from scipy.optimize import minimize
import numpy as np
class DAS
begin
function __init__ self ... | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 30 15:14:12 2018
@author: InfiniteJest
"""
import os
import re
os.chdir("C:\\Users\\InfiniteJest\\Documents\\Python_Scripts\\Physics")
import subprocess
import shutil
from scipy.optimize import minimize
import numpy as np
class DAS:
def __init__(self, ... | Python | zaydzuhri_stack_edu_python |
function check_title x
begin
return all generator expression is upper i at 0 for i in split x
end function | def check_title(x):
return all(i[0].isupper() for i in x.split())
| Python | zaydzuhri_stack_edu_python |
comment Parts of the eval function were from Bryce Matsuda
from Building import Building
from Inventory import Inventory
from Player import *
from Construction import Construction
from Ant import Ant
from GameState import GameState
from AIPlayerUtils import *
comment establishing weights for the weighted linear equatio... | ##
# Parts of the eval function were from Bryce Matsuda
##
from Building import Building
from Inventory import Inventory
from Player import *
from Construction import Construction
from Ant import Ant
from GameState import GameState
from AIPlayerUtils import *
# establishing weights for the weighted li... | Python | zaydzuhri_stack_edu_python |
function is_valid_move self entity direction
begin
set tuple t_row t_col = call get_targeted_cell entity direction
comment Valid move = target inside the map and the cell is not water
if t_row < 0 or t_row >= rows or t_col < 0 or t_col >= cols or surface == WATER
begin
return false
end
return true
end function | def is_valid_move(self, entity, direction):
t_row, t_col = self.get_targeted_cell(entity, direction)
# Valid move = target inside the map and the cell is not water
if t_row < 0 or t_row >= self.rows or \
t_col < 0 or t_col >= self.cols or \
self.arena[t_row][t_col].surface... | Python | nomic_cornstack_python_v1 |
comment Задачи на циклы и оператор условия------
comment ----------------------------------------
string Задача 1 Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована.
comment a = 0
comment b = str(0)
comment c = 10
comment while a < 6:
comment print(a,b*c)
comment a = a + 1
strin... | #Задачи на циклы и оператор условия------
#----------------------------------------
'''
Задача 1
Вывести на экран циклом пять строк из нулей, причем каждая строка должна быть пронумерована.
'''
# a = 0
# b = str(0)
# c = 10
# while a < 6:
# print(a,b*c)
# a = a + 1
'''
Задача 2
Пользователь в цикле вводит 1... | Python | zaydzuhri_stack_edu_python |
function _from_name cls name
begin
if name is none
begin
raise call OnnxExporterError string Scalar type name cannot be None
end
if call valid_scalar_name name
begin
comment type: ignore[index]
return _SCALAR_NAME_TO_TYPE at name
end
if call valid_torch_name name
begin
comment type: ignore[index]
return _TORCH_NAME_TO_... | def _from_name(
cls, name: Union[ScalarName, TorchName, Optional[str]]
) -> JitScalarType:
if name is None:
raise errors.OnnxExporterError("Scalar type name cannot be None")
if valid_scalar_name(name):
return _SCALAR_NAME_TO_TYPE[name] # type: ignore[index]
i... | Python | nomic_cornstack_python_v1 |
function is_valid value
begin
if value is none
begin
return not is_required
end
return value in call get_all_class_attr_values constant_cls
end function | def is_valid(value: str) -> bool:
if value is None:
return not is_required
return value in get_all_class_attr_values(constant_cls) | Python | nomic_cornstack_python_v1 |
string если число содержится в списке
if used_number in my_list
begin
set ind = 0
if count my_list used_number == 1
begin
set ind = index my_list used_number
end
else
begin
for i in range count my_list used_number
begin
set ind = index my_list used_number ind + 1
end
set ind = ind - 1
end
insert my_list ind used_number... | """если число содержится в списке"""
if used_number in my_list:
ind = 0
if my_list.count(used_number) == 1:
ind = my_list.index(used_number)
else:
for i in range (my_list.count(used_number)):
ind = my_list.index(used_number, ind) + 1
ind -= 1
my_list.insert(ind, used_... | Python | zaydzuhri_stack_edu_python |
function test_iwv self
begin
set p = linear space 1000 10 10
set T = 300 * ones shape
set z = linear space 0 75000 10
set vmr = 0.1 * ones shape
set iwv = call iwv vmr p T z
assert call allclose iwv 27.3551036
end function | def test_iwv(self):
p = np.linspace(1000, 10, 10)
T = 300 * np.ones(p.shape)
z = np.linspace(0, 75000, 10)
vmr = 0.1 * np.ones(p.shape)
iwv = atmosphere.iwv(vmr, p, T, z)
assert np.allclose(iwv, 27.3551036) | Python | nomic_cornstack_python_v1 |
function a_star_search problem heuristic=null_heuristic
begin
string *** YOUR CODE HERE ***
call raiseNotDefined
end function | def a_star_search(problem, heuristic=null_heuristic):
"*** YOUR CODE HERE ***"
util.raiseNotDefined() | Python | nomic_cornstack_python_v1 |
function test_basis_fem_simple self
begin
set testtrimesh = call TriMesh list list 0 1 2 list list 1.0 0.0 0.0 list 0.0 2.0 0.0 list 0.0 0.0 3.0
set sb_fem = call SpharaBasis testtrimesh mode=string fem
set tuple sb_fem_fun sb_fem_freq = call basis
assert true call allclose sb_fem_fun list list 0.53452248 - 0.49487166 ... | def test_basis_fem_simple(self):
testtrimesh = tm.TriMesh([[0, 1, 2]],
[[1., 0., 0.], [0., 2., 0.], [0., 0., 3.]])
sb_fem = sb.SpharaBasis(testtrimesh, mode='fem')
sb_fem_fun, sb_fem_freq = sb_fem.basis()
self.assertTrue(
np.allclose(
... | Python | nomic_cornstack_python_v1 |
comment 斐波那契数列低效递归
function fib n
begin
if n < 2
begin
return n
end
return call fib n - 1 + call fib n - 2
end function
print call fib 4
comment 斐波那契数列高效递归(记忆化储存)
function fib_m n
begin
function helper n memo=dict
begin
if n < 2
begin
return n
end
try
begin
return memo at n
end
except KeyError
begin
set result = call f... | #斐波那契数列低效递归
def fib(n):
if n<2:
return n
return fib(n-1)+fib(n-2)
print(fib(4))
#斐波那契数列高效递归(记忆化储存)
def fib_m(n):
def helper(n,memo={}):
if n<2:
return n
try:
return memo[n]
except KeyError:
result = fib_m(n-1) + fib_m(n-2)
mem... | Python | zaydzuhri_stack_edu_python |
comment Coding Challenge 4
comment Create a BMI calculator, BMI which stands for Body Mass Index can be calculated using the formula:
comment BMI = (weight in Kg)/(Height in Meters)^2.
comment Write python code which can accept the weight and height of a person and calculate his BMI.
comment note: Make sure to use a fu... | #Coding Challenge 4
# Create a BMI calculator, BMI which stands for Body Mass Index can be calculated using the formula:
# BMI = (weight in Kg)/(Height in Meters)^2.
# Write python code which can accept the weight and height of a person and calculate his BMI.
# note: Make sure to use a function which accepts the heig... | Python | zaydzuhri_stack_edu_python |
function to_unix_sec self
begin
set ts_type = ts_types at string unix_sec
try
begin
set dt_obj = parse duparser timestamp
if has attribute tzinfo string _offset
begin
set dt_tz = call total_seconds
set dt_obj = parse duparser timestamp ignoretz=true
end
else
begin
set dt_tz = 0
end
set out_unix_sec = string integer cal... | def to_unix_sec(self):
ts_type = self.ts_types['unix_sec']
try:
dt_obj = duparser.parse(self.timestamp)
if hasattr(dt_obj.tzinfo, '_offset'):
dt_tz = dt_obj.tzinfo._offset.total_seconds()
dt_obj = duparser.parse(self.timestamp, ignoretz=True)
... | Python | nomic_cornstack_python_v1 |
function add_gcp_views apps schema_editor
begin
set views = tuple string reporting_gcp_network_summary string reporting_gcp_database_summary
for view in views
begin
set view_sql = call get_data string reporting.provider.gcp string sql/views/ { view } .sql
set view_sql = decode view_sql string utf-8
with call cursor as ... | def add_gcp_views(apps, schema_editor):
views = ("reporting_gcp_network_summary", "reporting_gcp_database_summary")
for view in views:
view_sql = pkgutil.get_data("reporting.provider.gcp", f"sql/views/{view}.sql")
view_sql = view_sql.decode("utf-8")
with connection.cursor() as cursor:
... | Python | nomic_cornstack_python_v1 |
function apply self raw_data
begin
set sigma_data = call default_raw call GetName
for bin_radius in range 1 call GetNbinsY + 1
begin
for bin_energy in range 1 call GetNbinsX + 1
begin
call SetBinContent bin_energy bin_radius call get_sigma call GetBinCenter bin_energy call GetBinCenter bin_radius
end
end
comment In MeV... | def apply(self, raw_data):
sigma_data = spectrum_util.default_raw(raw_data.GetName())
for bin_radius in range(1, raw_data.GetNbinsY() + 1):
for bin_energy in range(1, raw_data.GetNbinsX() + 1):
sigma_data.SetBinContent(bin_energy, bin_radius,
... | Python | nomic_cornstack_python_v1 |
function _api_response response
begin
if status_code == 404
begin
set __context__ at string retcode = SALT_BUILD_FAIL
raise call CommandExecutionError string Element doesn't exists
end
if status_code == 401
begin
set __context__ at string retcode = SALT_BUILD_FAIL
raise call CommandExecutionError string Bad username or... | def _api_response(response):
if response.status_code == 404:
__context__["retcode"] = salt.defaults.exitcodes.SALT_BUILD_FAIL
raise CommandExecutionError("Element doesn't exists")
if response.status_code == 401:
__context__["retcode"] = salt.defaults.exitcodes.SALT_BUILD_FAIL
rai... | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.linear_model import LinearRegression
comment Generate random datasets
set dataset1 = randn 1000 3
set dataset2 = randn 1000 3
set dataset3 = randn 1000 3
comment Generate random fourth attribute values
set attribute_values = call rand ... | import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.linear_model import LinearRegression
# Generate random datasets
dataset1 = np.random.randn(1000, 3)
dataset2 = np.random.randn(1000, 3)
dataset3 = np.random.randn(1000, 3)
# Generate random fourth attribute values
attribute_values = ... | Python | greatdarklord_python_dataset |
function get_input_features
begin
set examples = call placeholder dtype=string shape=tuple none name=string input_example
set features = call parse_features metadata examples keep_target=false
set features at EXAMPLES_PLACEHOLDER_KEY = examples
comment The target feature column is not used for prediction so return None... | def get_input_features():
examples = tf.placeholder(
dtype=tf.string,
shape=(None,),
name='input_example')
features = ml.features.FeatureMetadata.parse_features(metadata, examples,
keep_target=False)
features[EXAMPLES_PLACEHOL... | Python | nomic_cornstack_python_v1 |
function HandleGetTypes
begin
set names = call _GetNames
set use_re = call _GetUseRegularExpresions
set types = call GetTypes names use_re
comment Render the types depending on the Accept header.
set accept = call _GetAccept
if accept == JSON
begin
yield encode cjson types
end
else
begin
for tuple name type in sorted c... | def HandleGetTypes():
names = _GetNames()
use_re = _GetUseRegularExpresions()
types = model_provider.GetFrontend().GetTypes(names, use_re)
# Render the types depending on the Accept header.
accept = _GetAccept()
if accept == RenderMode.JSON:
yield cjson.encode(types)
else:
for name, type in so... | Python | nomic_cornstack_python_v1 |
from schema import UserSchema , FarmSchema , CropSchema , CropPartSchema , PositionSchema
from pprint import pprint
from bson import ObjectId
from datetime import datetime , timedelta
class ModelErrorBase extends Exception
begin
function __init__ self msg
begin
set message = msg
end function
end class
class ValueError ... | from schema import UserSchema,FarmSchema,CropSchema,CropPartSchema,PositionSchema
from pprint import pprint
from bson import ObjectId
from datetime import datetime,timedelta
class ModelErrorBase(Exception):
def __init__(self,msg):
self.message = msg
class ValueError(ModelErrorBase):pass
class User():
... | Python | zaydzuhri_stack_edu_python |
function set_actions self actions
begin
set actions = list actions
comment for a in self.actions:
comment a.set_scope(self)
set name2action = none
end function | def set_actions(self, actions):
self.actions = list(actions)
#for a in self.actions:
# a.set_scope(self)
self.name2action = None | Python | nomic_cornstack_python_v1 |
import sqlalchemy
from sqlalchemy import Column , Integer , String , Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session
comment Criar Conexão com Banco SQLITE
comment caso o arquivo não exista, ele será criado
set engine = call create_engine string sqlite:///server.db
set c... | import sqlalchemy
from sqlalchemy import Column, Integer, String, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session
# Criar Conexão com Banco SQLITE
# caso o arquivo não exista, ele será criado
engine = sqlalchemy.create_engine("sqlite:///server.db")
connection ... | Python | zaydzuhri_stack_edu_python |
import random
from django.core.management import BaseCommand
from apitests.models import Bakery , Owner
class Command extends BaseCommand
begin
function handle self *args **options
begin
set bakeries = list string La Petite string Sanketh Sweets string Cater to U
set owners = list dict string first_name string Sanketh ... | import random
from django.core.management import BaseCommand
from apitests.models import Bakery, Owner
class Command(BaseCommand):
def handle(self, *args, **options):
bakeries = [
'La Petite',
'Sanketh Sweets',
'Cater to U'
]
owners = [
{
... | Python | zaydzuhri_stack_edu_python |
function reset_challenge_instances request
begin
call defer reset_challenges
return call HttpResponse string Ok
end function | def reset_challenge_instances(request):
deferred.defer(tasks.reset_challenges)
return HttpResponse('Ok') | Python | nomic_cornstack_python_v1 |
comment import basic libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
comment load dataset
set dataset = read csv string HousingData.csv
set X = values
set y = values
comment handling missing data
from sklearn.impute import SimpleImputer
set imputer = call SimpleImputer missing_values=na... | #import basic libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#load dataset
dataset = pd.read_csv('HousingData.csv')
X = dataset.iloc[:,:-1].values
y = dataset.iloc[:,13].values
#handling missing data
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(missing_values=np... | Python | zaydzuhri_stack_edu_python |
from scipy import io
import pickle
import numpy as np
function main
begin
set x300 = call loadmat string knock_x300 at string x300
with open string ./pickles/t_dict string rb as f
begin
set t_dict = load pickle f
end
set vec1 = x300 at t_dict at string United_States_of_America
set vec2 = x300 at t_dict at string U.S.A
... | from scipy import io
import pickle
import numpy as np
def main():
x300 = io.loadmat('knock_x300')['x300']
with open('./pickles/t_dict', 'rb') as f:
t_dict = pickle.load(f)
vec1 = x300[t_dict['United_States_of_America']]
vec2 = x300[t_dict['U.S.A']]
# np.linalg.norm(vec)でvecの大きさを取ってこれる
... | Python | zaydzuhri_stack_edu_python |
function testForNonExistingSurvey self
begin
set user = call seedNDBUser host_for=list program
call loginNDB user
set response = get self string /gsoc/eval/student/preview/%s/fakesurvey % call name
call assertResponseNotFound response
end function | def testForNonExistingSurvey(self):
user = profile_utils.seedNDBUser(host_for=[self.program])
profile_utils.loginNDB(user)
response = self.get('/gsoc/eval/student/preview/%s/fakesurvey' %
self.program.key().name())
self.assertResponseNotFound(response) | Python | nomic_cornstack_python_v1 |
comment Int his script, we will learn about R dataframes
comment Reading csv file in R
set df = call csv string recent-grads.csv
print df
comment Previewing the first few rows
head df
tail df
comment Examining the internal structure
string df
comment Numeric Vs. Integer
petro_eng_med_salary < - 110000
finance_med_salar... | ## Int his script, we will learn about R dataframes
## Reading csv file in R
df = read.csv("recent-grads.csv")
print(df)
## Previewing the first few rows
head(df)
tail(df)
## Examining the internal structure
str(df)
## Numeric Vs. Integer
petro_eng_med_salary <- 110000
finance_med_salary <- 47000
| Python | zaydzuhri_stack_edu_python |
from BinarySearch import BinarySearch
function three_sum list
begin
set n = length list
set cnt = 0
for i in range n
begin
for j in range i + 1 n
begin
for k in range j + 1 n
begin
if list at i + list at j + list at k == 0
begin
set cnt = cnt + 1
end
end
end
end
return cnt
end function
function three_sum_fast list
begi... | from BinarySearch import BinarySearch
def three_sum(list):
n = len(list)
cnt = 0
for i in range(n):
for j in range(i+1, n):
for k in range(j+1, n):
if list[i] + list[j] + list[k] == 0:
cnt += 1
return cnt
def three_sum_fast(list):
n = len(li... | Python | zaydzuhri_stack_edu_python |
function _default_tensor_from_file tm hd5 dependents=dict
begin
if call is_categorical and not call is_discretized
begin
set index = 0
set missing = true
set categorical_data = zeros shape dtype=float32
if call hd5_key_guess in hd5
begin
set data = call hd5_first_dataset_in_group hd5 call hd5_key_guess
if storage_type ... | def _default_tensor_from_file(tm, hd5, dependents={}):
if tm.is_categorical() and not tm.is_discretized():
index = 0
missing = True
categorical_data = np.zeros(tm.shape, dtype=np.float32)
if tm.hd5_key_guess() in hd5:
data = tm.hd5_first_dataset_in_group(hd5, tm.hd5_key_g... | Python | nomic_cornstack_python_v1 |
function pearson input1 input2
begin
set input1 = flatten call atleast_1d as type input1 bool
set input2 = flatten call atleast_1d as type input2 bool
return call corrcoef input1 input2 at tuple 0 1
end function | def pearson(input1, input2):
input1 = np.atleast_1d(input1.astype(bool)).flatten()
input2 = np.atleast_1d(input2.astype(bool)).flatten()
return np.corrcoef(input1, input2)[0, 1] | Python | nomic_cornstack_python_v1 |
from django.db import models
class Todo extends Model
begin
comment Refer to https://docs.djangoproject.com/en/1.8/ref/models/fields/#choices
comment for the best practice of defining `choices`.
set HIGH_PRI = 0
set MID_PRI = 1
set LOW_PRI = 2
comment The first element in each tuple is the actual value to be set on the... | from django.db import models
class Todo(models.Model):
# Refer to https://docs.djangoproject.com/en/1.8/ref/models/fields/#choices
# for the best practice of defining `choices`.
HIGH_PRI = 0
MID_PRI = 1
LOW_PRI = 2
# The first element in each tuple is the actual value to be set on the model,
... | Python | zaydzuhri_stack_edu_python |
function norm_image self img
begin
set tuple img_y img_b img_r = split call convert string YCbCr
set img_y_np = as type call asarray img_y float
set img_y_np = img_y_np / 255
set img_y_np = img_y_np - mean img_y_np
set img_y_np = img_y_np / standard deviation img_y_np
set scale = max list absolute call percentile img_y... | def norm_image(self, img):
img_y, img_b, img_r = img.convert('YCbCr').split()
img_y_np = np.asarray(img_y).astype(float)
img_y_np /= 255
img_y_np -= img_y_np.mean()
img_y_np /= img_y_np.std()
scale = np.max([np.abs(np.percentile(img_y_np, 1.0)),
np.abs(np.percentile(img_y_n... | Python | nomic_cornstack_python_v1 |
function info self
begin
return info + string : My major data structure is a + __name__
end function | def info(self):
return (
super(WordFrequencyManager, self).info()
+ ": My major data structure is a "
+ self._word_freqs.__class__.__name__
) | Python | nomic_cornstack_python_v1 |
import numpy as np
from utility.util import convert_position
class EmitterProperties
begin
string Class containing all emitter properties.
function __init__ self s r0=8 phi0=0 omega=1 P=0 T=pi / 2 rho=0.2 rotation=string positive
begin
string :param s: float; spin of the object, perpendicular to the angular momentum of... | import numpy as np
from utility.util import convert_position
class EmitterProperties:
"""
Class containing all emitter properties.
"""
def __init__(self, s, r0=8, phi0=0, omega=1, P=0, T=np.pi/2, rho=0.2, rotation='positive'):
"""
:param s: float; spin of the object, perpendicular ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
from tkinter import *
from tkinter.messagebox import *
from tkinter.filedialog import *
import os
class Notepad
begin
set root = call Tk
comment Win:root.wm_iconbitmap("notepad.ico")
comment Linux:root.wm_iconbitmap("notepad.xbm")
title root string Untitled - Notepad
call geometry string 70... | #!/usr/bin/env python
from tkinter import *
from tkinter.messagebox import *
from tkinter.filedialog import *
import os
class Notepad:
root = Tk()
#Win:root.wm_iconbitmap("notepad.ico")
#Linux:root.wm_iconbitmap("notepad.xbm")
root.title("Untitled - Notepad")
root.geometry("700x400")
TextArea ... | Python | zaydzuhri_stack_edu_python |
import unittest
class c_02_test extends TestCase
begin
function test_8 self
begin
comment 建议8:利用assert语句来发现问题
print string
end function
function test_9 self
begin
comment 建议9:数据交换值的时候不推荐使用中间变量
print string
end function
function test_10 self
begin
comment 建议10:充分利用Lazyevaluation的特性
print string
end function
function tes... | import unittest
class c_02_test(unittest.TestCase):
def test_8(self):
#建议8:利用assert语句来发现问题
print("")
def test_9(self):
#建议9:数据交换值的时候不推荐使用中间变量
print("")
def test_10(self):
#建议10:充分利用Lazyevaluation的特性
print("")
def test_11(self):
#建议11:理解枚举替代实现的缺陷
print("")
def test_12(self):
#建议12:不推荐使用type来进... | Python | zaydzuhri_stack_edu_python |
function download_and_prepare_dmipy_example_dataset self
begin
set subject_ID = 100307
call download_subject subject_ID
call prepare_example_slice subject_ID
end function | def download_and_prepare_dmipy_example_dataset(self):
subject_ID = 100307
self.download_subject(subject_ID)
self.prepare_example_slice(subject_ID) | Python | nomic_cornstack_python_v1 |
import json
comment using the urllib built in module, we are importing urlopen
from urllib.request import urlopen
from collections import namedtuple
with url open string https://assist.org/api/institutions as response
begin
set source = read response
end
comment setting source variable as response upon which read is be... | import json
from urllib.request import urlopen # using the urllib built in module, we are importing urlopen
from collections import namedtuple
with urlopen("https://assist.org/api/institutions") as response:
source = response.read()
# setting source variable as response upon which read is being called, not ver... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Fri Mar 6 18:30:02 2020 @author: olivia
string Exercise 2.5
set pi = 3.1416
set r = 2
print string Diameter = 2 * r string Circumference = 2 * pi * r string Area= pi * r ^ 2
string Exercise 2.6
set integer = integer input string Please provide and integer:
if integer % 2 ... | # -*- coding: utf-8 -*-
"""
Created on Fri Mar 6 18:30:02 2020
@author: olivia
"""
"""Exercise 2.5"""
pi = 3.1416
r = 2
print ('Diameter =', 2*r,'\nCircumference =',2*pi*r,'\nArea=',pi*r**2)
"""Exercise 2.6"""
integer = int(input('Please provide and integer: '))
if integer % 2 == 0 :
print ('The integer is even'... | Python | zaydzuhri_stack_edu_python |
set str_input = input string 태어난 해를 입력해주세요>
set birth_year = integer str_input % 12
set lst = list string 원숭이 string 닭 string 개 string 돼지 string 쥐 string 소 string 범 string 토끼 string 용 string 뱀 string 말 string 양
print lst at birth_year string 띠입니다. | str_input = input('태어난 해를 입력해주세요> ')
birth_year = int(str_input) % 12
lst = ['원숭이','닭','개','돼지','쥐','소','범','토끼','용','뱀','말','양']
print(lst[birth_year], "띠입니다.")
| Python | zaydzuhri_stack_edu_python |
for i in range 10
begin
append arr arr at i + arr at i + 1
end
print string reference arr
comment basic
function fib n
begin
if n == 0
begin
return 0
end
else
if n == 1
begin
return 1
end
else
begin
set res = call fib n - 1 + call fib n - 2
return res
end
end function
comment dynamic programming
function fib_dp n
begin... | for i in range(10):
arr.append(arr[i]+arr[i+1])
print('reference',arr)
def fib(n): #basic
if n==0:
return 0
elif n==1:
return 1
else:
res=fib(n-1)+fib(n-2)
return res
def fib_dp(n): #dynamic programming
arr=[0,1]
if n ==0:
return arr[n]
elif n==1:... | Python | zaydzuhri_stack_edu_python |
function index self sub_category
begin
string The offset of *sub_category* in the overall sequence of leaf categories.
set index = index _parent self
for this_sub_category in _sub_categories
begin
if sub_category is this_sub_category
begin
return index
end
set index = index + leaf_count
end
raise call ValueError string... | def index(self, sub_category):
"""
The offset of *sub_category* in the overall sequence of leaf
categories.
"""
index = self._parent.index(self)
for this_sub_category in self._sub_categories:
if sub_category is this_sub_category:
return index
... | Python | jtatman_500k |
comment -*- coding: utf-8 -*-
string Spyder Editor This is a temporary script file.
import yfinance as yf
import pandas as pd
set datos = read csv string SPY500.csv
print size
set df2 = call DataFrame
set year = string 2020
set yearend = string 2018
set month = string -11-
set day = string 26
comment ==================... | # -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import yfinance as yf
import pandas as pd
datos = pd.read_csv('SPY500.csv')
print(datos.size)
df2 = pd.DataFrame()
year = '2020'
yearend = '2018'
month = '-11-'
day = '26'
# ===========================================... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding: utf-8
comment In[1]:
set str = string hello
str
comment In[2]:
set str = string dfgf55
str
comment In[3]:
string String built with double quotes
comment In[4]: | #!/usr/bin/env python
# coding: utf-8
# In[1]:
str = 'hello'
str
# In[2]:
str = 'dfgf55'
str
# In[3]:
"String built with double quotes"
# In[4]:
| Python | zaydzuhri_stack_edu_python |
import string
function count_words text
begin
comment Remove punctuation marks and special characters
set text = call translate call maketrans string string punctuation
comment Split the text into words
set words = split text
comment Count the number of words
set word_count = length words
return word_count
end functi... | import string
def count_words(text):
# Remove punctuation marks and special characters
text = text.translate(str.maketrans('', '', string.punctuation))
# Split the text into words
words = text.split()
# Count the number of words
word_count = len(words)
return word_count
# Ex... | Python | jtatman_500k |
function tally_opponent_filesizes opponents
begin
set sizes = dict
for opp in opponents
begin
set opp_path = call joinpath string opponents opp
set sizes at opp = call recursive_folder_size opp_path
end
return sizes
end function | def tally_opponent_filesizes(opponents):
sizes = {}
for opp in opponents:
opp_path = SPNATI_BASE_DIR.joinpath('opponents', opp)
sizes[opp] = recursive_folder_size(opp_path)
return sizes | 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.