code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
from rest_framework import serializers
from import repository
from auth_system.utils import check_if_new_password_valid
from users.models import User
function validate_email_is_already_used email
begin
set already_in = exists filter email=email
if already_in
begin
raise call ValidationError string The email is already... | from rest_framework import serializers
from . import repository
from auth_system.utils import check_if_new_password_valid
from users.models import User
def validate_email_is_already_used(email):
already_in = User.objects.filter(email=email).exists()
if already_in:
raise serializers.ValidationError(
... | Python | zaydzuhri_stack_edu_python |
set tuple n k = map int split input
set tuple c m = tuple 0 n
while n != 0
begin
set n = n // k
set c = c + 1
end
print if expression k ^ c - 1 == m then string yes else string no | n,k=map(int,input().split())
c,m=0,n
while(n!=0):
n=n//k
c+=1
print("yes" if k**(c-1)==m else "no")
| Python | zaydzuhri_stack_edu_python |
function is_proper_superset self other
begin
if is instance other Set
begin
return self != other and call is_superset other
end
else
begin
raise call ValueError string Unknown argument '%s' % other
end
end function | def is_proper_superset(self, other):
if isinstance(other, Set):
return self != other and self.is_superset(other)
else:
raise ValueError("Unknown argument '%s'" % other) | Python | nomic_cornstack_python_v1 |
function subscribe self member_id card_number expiration_date cvv
begin
set TYPE = TYPES at string SUBSCRIBER_SUBSCRIBE
set response = call _request TYPE=TYPE MONTANT=1 REFABONNE=member_id PORTEUR=card_number DATEVAL=expiration_date CVV=cvv
return response at string PORTEUR at 0
end function | def subscribe(self, member_id, card_number, expiration_date, cvv):
TYPE = TYPES['SUBSCRIBER_SUBSCRIBE']
response = self._request(
TYPE=TYPE, MONTANT=1, REFABONNE=member_id, PORTEUR=card_number,
DATEVAL=expiration_date, CVV=cvv
)
return response['PORTEUR'][0] | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/python
import Map , troy
class Creature extends object
begin
string All living things should inherit from this class
set __state = string alive
set __age = none
comment __position = []
set x = 0
set y = 0
set direction = string up
function __init__ self connection
begin
pass
end function
function mov... | #! /usr/bin/python
import Map, troy
class Creature(object):
"""All living things should inherit from this class"""
__state = "alive"
__age = None
#__position = []
x = 0
y = 0
direction = "up"
def __init__(self, connection):
pass
def move(self, direction):
"""""... | Python | zaydzuhri_stack_edu_python |
function start self
begin
call __parse_model
call __start_server
end function | def start(self):
self.__parse_model()
self.__start_server() | Python | nomic_cornstack_python_v1 |
comment Python3
class ListNode
begin
function __init__ self val=0 next=none
begin
set val = 0
set next = next
end function
end class
class Solution
begin
function reverseBetween self head left right
begin
if not head or not next or left == right
begin
return head
end
set dummy = call ListNode 0 head
set hair = dummy
se... | # Python3
class ListNode:
def __init__(self, val=0, next=None):
self.val = 0
self.next = next
class Solution:
def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode:
if not head or not head.next or left == right:
return head
dummy = Lis... | Python | zaydzuhri_stack_edu_python |
function secure self
begin
set status = call MSP430_Secure
if status != STATUS_OK
begin
raise call IOError string Could not secure device: %s % call MSP430_Error_String call MSP430_Error_Number
end
end function | def secure(self):
status = MSP430_Secure()
if status != STATUS_OK:
raise IOError("Could not secure device: %s" % MSP430_Error_String(MSP430_Error_Number())) | Python | nomic_cornstack_python_v1 |
function parseDate self dateStr
begin
raise call NotImplementedError string subclasses must override
end function | def parseDate(self, dateStr):
raise NotImplementedError('subclasses must override') | Python | nomic_cornstack_python_v1 |
function secret_present name namespace=string default data=none source=none template=none **kwargs
begin
string Ensures that the named secret is present inside of the specified namespace with the given data. If the secret exists it will be replaced. name The name of the secret. namespace The namespace holding the secre... | def secret_present(
name,
namespace='default',
data=None,
source=None,
template=None,
**kwargs):
'''
Ensures that the named secret is present inside of the specified namespace
with the given data.
If the secret exists it will be replaced.
name
... | Python | jtatman_500k |
function MSGP self
begin
raise NotImplementedError
end function | def MSGP(self):
raise NotImplementedError | Python | nomic_cornstack_python_v1 |
function get_data_from_tag_name xml tag class_mapping=str index=0
begin
set tags = call get_xml_from_tag_name xml=xml tag=tag
if tags
begin
set data = list comprehension call class_mapping nodeValue for tag in tags
return if expression index is not none then data at index else data
end
end function
function get_xml_fro... | def get_data_from_tag_name(xml, tag, class_mapping=str, index=0):
tags = get_xml_from_tag_name(xml=xml, tag=tag)
if tags:
data = [class_mapping(tag.firstChild.nodeValue) for tag in tags]
return data[index] if index is not None else data
def get_xml_from_tag_name(xml, tag):
return xml.getEl... | Python | zaydzuhri_stack_edu_python |
comment ok this program find a number
string multiple comment print("parshnat" + "pandit")
for n in range 101
begin
if n is Number
begin
print n string is the number !
break
end
else
begin
print n
end
end
comment Find the numbers whıch can dive 4 and 4 multiple(tetragenous) in from 0 to 100
for n in range 101
begin
if ... | # ok this program find a number
'''
multiple comment
print("parshnat" + "pandit")
'''
for n in range(101):
if n is Number:
print(n, "is the number ! ")
break
else:
print(n)
#Find the numbers whıch can dive 4 and 4 multiple(tetragenous) in from 0 to 100
for n in range(101):
if n %... | Python | zaydzuhri_stack_edu_python |
function toJson self
begin
return loads call serialize string json list self at 0
end function | def toJson(self):
return json.loads(serializers.serialize('json', [self]))[0] | Python | nomic_cornstack_python_v1 |
import sqlite3
set conn = call connect string emaildb.sqlite
set db = call cursor
execute db string DROP TABLE IF EXISTS Counts
execute db string CREATE TABLE Counts ('org' TEXT, 'count' INTEGER)
set info = execute db string SELECT * FROM Counts
set file = open string sample.txt
for line in file
begin
if not starts wit... | import sqlite3
conn=sqlite3.connect("emaildb.sqlite")
db=conn.cursor()
db.execute("DROP TABLE IF EXISTS Counts")
db.execute("CREATE TABLE Counts ('org' TEXT, 'count' INTEGER)")
info=db.execute("SELECT * FROM Counts")
file=open("sample.txt")
for line in file:
if not line.startswith("From "):
c... | Python | zaydzuhri_stack_edu_python |
function last_digit n1 n2
begin
return power n1 n2 10
end function | def last_digit(n1, n2):
return pow( n1, n2, 10 ) | Python | zaydzuhri_stack_edu_python |
function getAllFiles self
begin
return list pathString
end function | def getAllFiles(self):
return [self.pathString] | Python | nomic_cornstack_python_v1 |
function evaluationFunction self currentGameState action
begin
comment Useful information you can extract from a GameState (pacman.py)
set successorGameState = call generatePacmanSuccessor action
set pos = call getPacmanPosition
set newPos = call getPacmanPosition
set food = call getFood
set newFood = call getFood
set ... | def evaluationFunction(self, currentGameState, action):
# Useful information you can extract from a GameState (pacman.py)
successorGameState = currentGameState.generatePacmanSuccessor(action)
pos = currentGameState.getPacmanPosition()
newPos = successorGameState.getPacmanPosition()
... | Python | nomic_cornstack_python_v1 |
function test_classifier_pipeline self
begin
set model = pipeline list tuple string reduce_dim principal component analysis tuple string linreg logistic regression
assert true call is_classifier model
end function | def test_classifier_pipeline(self):
model = Pipeline([
('reduce_dim', PCA()),
('linreg', LogisticRegression())
])
self.assertTrue(is_classifier(model)) | Python | nomic_cornstack_python_v1 |
function swap data fmt
begin
set swap_fmt = join string list string > fmt
try
begin
set swap_iter = call iter_unpack fmt data
end
except error as error
begin
print string ERROR: error string CLOSING file=stderr
raise error
end
try
begin
set swapped = list comprehension call pack swap_fmt *i for i in swap_iter
end
exce... | def swap(data, fmt):
swap_fmt = ''.join(['>', fmt])
try:
swap_iter = struct.iter_unpack(fmt, data)
except struct.error as error:
print('ERROR:', error, 'CLOSING', file=sys.stderr)
raise error
try:
swapped = [struct.pack(swap_fmt, *i) for i in swap_iter]
except struc... | Python | nomic_cornstack_python_v1 |
function add_item self *item
begin
if length store < max_length
begin
append store none
end
set store at current_position = call Transition *item
set current_position = current_position + 1 % max_length
end function | def add_item(self, *item):
if len(self.store) < self.max_length:
self.store.append(None)
self.store[self.current_position] = Transition(*item)
self.current_position = (self.current_position + 1) % self.max_length | Python | nomic_cornstack_python_v1 |
comment Create by MrZhang on 2019-11-29
import numpy as np
import operator
comment cos相似度计算公式
function cos_sim colA colB
begin
return dot T colB / norm colA * norm colB
end function
comment 获取词典
function get_vocab vocab_path
begin
set vocab_array = load np vocab_path
set vocab_list = call tolist
return vocab_list
end f... | # Create by MrZhang on 2019-11-29
import numpy as np
import operator
# cos相似度计算公式
def cos_sim(colA, colB):
return np.dot(colA.T, colB) / (np.linalg.norm(colA) * np.linalg.norm(colB))
# 获取词典
def get_vocab(vocab_path):
vocab_array = np.load(vocab_path)
vocab_list = vocab_array.tolist()
return vocab_lis... | Python | zaydzuhri_stack_edu_python |
import cv2
function Take_SnapShot
begin
set videoCaptureQbject = call VideoCapture 0
set result = true
while result
begin
set tuple ret frame = read videoCaptureQbject
call imwrite string newPicture1.jpg frame
set result = false
end
release videoCaptureQbject
call destroyAllWindows
end function
call Take_SnapShot | import cv2
def Take_SnapShot():
videoCaptureQbject=cv2.VideoCapture(0)
result=True
while (result):
ret,frame=videoCaptureQbject.read()
cv2.imwrite("newPicture1.jpg",frame)
result=False
videoCaptureQbject.release()
cv2.destroyAllWindows()
Take_SnapShot()
... | Python | zaydzuhri_stack_edu_python |
function afficher
begin
set liste = list string . * N ^ 2
for i in range length HISTORIQUE
begin
set tuple x y = HISTORIQUE at i
set liste at x + y * N = i
end
set Espace = string * 15
set Titre = format string TOUR {}. Cavalier en {}. length HISTORIQUE tuple x y
set L1 = string + string |{:2} * N at slice 1 : : + ... | def afficher():
liste = [' .'] * (N**2)
for i in range(len(HISTORIQUE)):
(x,y) = HISTORIQUE[i]
liste[x + y * N] = i
Espace = "\n" * 15
Titre = "TOUR {}. Cavalier en {}.\n\n".format(len(HISTORIQUE), (x,y))
L1 = " " + ("|{:2} " * N)[1:] + "\n"
L2 = " " + ("+---" * N)[1:] + "\n"
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import rospy
import tf
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Twist
from turtlesim.msg import Pose
import math
class point
begin
function __init__ self x y
begin
set x = x
set y = y
end function
end class
comment lista pnktow do ktorych zolw ma dotrzec
set points_li... | #!/usr/bin/env python
import rospy
import tf
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Twist
from turtlesim.msg import Pose
import math
class point:
def __init__(self,x,y):
self.x=x
self.y=y
# lista pnktow do ktorych zolw ma dotrzec
points_list=[point(-1,-1), point(1,0), point(0,0), point(... | Python | zaydzuhri_stack_edu_python |
function post_order access_token json_request
begin
set orders_url = format string https://api.tdameritrade.com/v1/accounts/{}/orders account_num
comment The header for placing in order needs to define the input type (json)
set headers = dict string Authorization format string Bearer {} access_token ; string Content-Ty... | def post_order(access_token,json_request):
orders_url = 'https://api.tdameritrade.com/v1/accounts/{}/orders'.format(TDAuth_Info.account_num)
#The header for placing in order needs to define the input type (json)
headers = {'Authorization':'Bearer {}'.format(access_token),
'Content-Type'... | Python | nomic_cornstack_python_v1 |
function generate_tracking_game_logs measure_type player_or_team date_from date_to **kwargs
begin
set team_id_game_id_map = get kwargs string team_id_game_id_map
set team_id_opponent_team_id_map = get kwargs string team_id_opponent_team_id_map
set player_id_team_id_map = get kwargs string player_id_team_id_map
set get_... | def generate_tracking_game_logs(
measure_type: TrackingMeasureType,
player_or_team: PlayerOrTeam,
date_from: date,
date_to: date,
**kwargs,
) -> List[Any]:
team_id_game_id_map = kwargs.get("team_id_game_id_map")
team_id_opponent_team_id_map = kwargs.get("team_id_opponent_team_id_map")
pl... | Python | nomic_cornstack_python_v1 |
function __str__ self
begin
set display = string
for i in range length board
begin
if i + 1 % 3 != 0
begin
set display = display + board at i + string
end
else
if i + 1 % 3 != 3
begin
set display = display + board at i + string
end
end
return display
end function | def __str__(self):
self.display = ''
for i in range(len(self.board)):
if (i + 1) % 3 != 0:
self.display += self.board[i] + ' '
elif (i + 1) % 3 != 3:
self.display += self.board[i] + '\n'
return self.display | Python | nomic_cornstack_python_v1 |
function getTotal costs items tax
begin
set items1 = list comprehension ch for ch in items if ch in costs
return round sum list comprehension costs at word for word in items1 * 1 + tax 2
end function | def getTotal(costs, items, tax):
items1 = [ch for ch in items if ch in costs]
return round(sum([costs[word] for word in items1])*(1+tax),2)
| Python | zaydzuhri_stack_edu_python |
function virtual_machine self
begin
return get pulumi self string virtual_machine
end function | def virtual_machine(self) -> pulumi.Output['outputs.VirtualMachineResponse']:
return pulumi.get(self, "virtual_machine") | Python | nomic_cornstack_python_v1 |
function search_engine data prefixes suffixes length
begin
set results = list
for word in data
begin
if length word == length and all generator expression lower prefix in lower word for prefix in prefixes and any generator expression lower suffix in lower word for suffix in suffixes
begin
append results word
end
end
r... | def search_engine(data, prefixes, suffixes, length):
results = []
for word in data:
if len(word) == length and all(prefix.lower() in word.lower() for prefix in prefixes) and any(suffix.lower() in word.lower() for suffix in suffixes):
results.append(word)
return results
data = ["mobile",... | Python | greatdarklord_python_dataset |
function list_blobs_with_prefix bucket_name prefix delimiter=none
begin
comment storage_client = storage.Client()
set bucket = call get_bucket bucket_name
set blobs = call list_blobs prefix=prefix delimiter=delimiter
print string Blobs:
for blob in blobs
begin
print name
end
if delimiter
begin
print string Prefixes:
fo... | def list_blobs_with_prefix(bucket_name, prefix, delimiter=None):
#storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blobs = bucket.list_blobs(prefix=prefix, delimiter=delimiter)
print('Blobs:')
for blob in blobs:
print(blob.name)
if delimiter:
p... | Python | nomic_cornstack_python_v1 |
function get_gpu_info **kwargs
begin
comment Set GPU info fields
set conn_gpu_count = none
set source_db_gpu_count = none
set source_db_gpu_mem = none
set source_db_gpu_driver_ver = string
set source_db_gpu_name = string
if kwargs at string no_gather_conn_gpu_info
begin
debug string --no-gather-conn-gpu-info passed, ... | def get_gpu_info(**kwargs):
# Set GPU info fields
conn_gpu_count = None
source_db_gpu_count = None
source_db_gpu_mem = None
source_db_gpu_driver_ver = ""
source_db_gpu_name = ""
if kwargs["no_gather_conn_gpu_info"]:
logging.debug(
"--no-gather-conn-gpu-info passed, "
... | Python | nomic_cornstack_python_v1 |
function _get_template querystring_key mapping
begin
string Return the template corresponding to the given ``querystring_key``.
set default = none
try
begin
set template_and_keys = items mapping
end
except AttributeError
begin
set template_and_keys = mapping
end
for tuple template key in template_and_keys
begin
if key ... | def _get_template(querystring_key, mapping):
"""Return the template corresponding to the given ``querystring_key``."""
default = None
try:
template_and_keys = mapping.items()
except AttributeError:
template_and_keys = mapping
for template, key in template_and_keys:
if key is ... | Python | jtatman_500k |
import sys
import time
import schedule
import subprocess
import threading
import RPi.GPIO as GPIO
set gpio_pin = 26
call setmode BCM
setup GPIO gpio_pin IN pull_up_down=PUD_UP
class ClockSchedule
begin
function __init__ self player=string aplay
begin
set player = player
set sound = none
end function
function play_sound... | import sys
import time
import schedule
import subprocess
import threading
import RPi.GPIO as GPIO
gpio_pin = 26
GPIO.setmode(GPIO.BCM)
GPIO.setup(gpio_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
class ClockSchedule:
def __init__(self, player='aplay'):
self.player = player
self.sound = None
... | Python | zaydzuhri_stack_edu_python |
function cleanuplocs dirtystring
begin
set dirtystring = replace dirtystring string ( string
set dirtystring = replace dirtystring string ) string
set cleanstring = strip dirtystring
return cleanstring
end function | def cleanuplocs(dirtystring):
dirtystring = dirtystring.replace("(", "")
dirtystring = dirtystring.replace(")", "")
cleanstring = dirtystring.strip()
return cleanstring | Python | nomic_cornstack_python_v1 |
function test_create_table_5
begin
call print_test_separator string Starting test_create_table_5
comment DO NOT CALL CLEANUP. Want to access preexisting table.
set cat = call CSVCatalog
set t = call get_table string batting
print string Initial status of table = dumps call describe_table indent=2
call add_column_defini... | def test_create_table_5():
print_test_separator("Starting test_create_table_5")
# DO NOT CALL CLEANUP. Want to access preexisting table.
cat = CSVCatalog.CSVCatalog()
t = cat.get_table("batting")
print("Initial status of table = \n", json.dumps(t.describe_table(), indent=2))
t.add_column_defini... | Python | nomic_cornstack_python_v1 |
while length value > 1
begin
set value_0 = value at 0 + value at 1 / 2
set new = list value_0
for i in range 2 length value
begin
append new value at i
end
set value = new
end
print value at 0 | while len(value) > 1:
value_0 = (value[0] + value[1]) / 2
new = [value_0]
for i in range(2,len(value)):
new.append(value[i])
value = new
print(value[0])
| Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment -*- coding: utf-8 -*-
string Created on Mon Feb 25 15:17:40 2019 @author: aiqiangyun
import re
set p = compile string [.*?]
set f = open string 括号替换—分子生物学综述.txt string r
set str = read f
close f
set str2 = sub string str
with open string 替换后.txt string w as f
begin
write f str2
en... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 25 15:17:40 2019
@author: aiqiangyun
"""
import re
p = re.compile(r'[.*?]')
f = open('括号替换—分子生物学综述.txt','r')
str = f.read()
f.close()
str2=p.sub('', str)
with open('替换后.txt','w') as f:
f.write(str2) | Python | zaydzuhri_stack_edu_python |
comment N进制转10进制
from array import array
class Solution
begin
function BaseNToBase10 charnum iBase
begin
if iBase > 35 or iBase < 2
begin
print string 输入的进制数需要在2-35之间
return
end
comment 如果输入的进制小于数据,则提示输入异常,
set product = 1
set deca = 0
set length = length charnum
if iBase <= 10
begin
for a in range length
begin
if ordi... | #N进制转10进制
from array import array
class Solution:
def BaseNToBase10(charnum, iBase):
if (iBase>35 or iBase<2):
print('输入的进制数需要在2-35之间')
return
# 如果输入的进制小于数据,则提示输入异常,
product = 1
deca = 0
length = len(charnum)
if iBase <= 10:
for a... | Python | zaydzuhri_stack_edu_python |
function bulkAccept self request access_type page_name=none params=none **kwargs
begin
set program_keyname = kwargs at string scope_path
return call _bulkReview request params string pre-accepted string accepted program_keyname
end function | def bulkAccept(self, request, access_type,
page_name=None, params=None, **kwargs):
program_keyname = kwargs['scope_path']
return self._bulkReview(request, params, 'pre-accepted', 'accepted',
program_keyname) | Python | nomic_cornstack_python_v1 |
import urllib.request , urllib.parse , urllib.error
import xml.etree.ElementTree as ET
import ssl
set url = input string Enter URL:
comment ignore SSL certificate errors
set ctx = call create_default_context
set check_hostname = false
set verify_mode = CERT_NONE
comment open url with urllib
set uh = url open url contex... | import urllib.request, urllib.parse, urllib.error
import xml.etree.ElementTree as ET
import ssl
url = input('Enter URL: ')
#ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
uh = urllib.request.urlopen(url, context=ctx) #open url with u... | Python | zaydzuhri_stack_edu_python |
function value_iteration mdp state_values=none gamma=0.9 num_iter=1000 min_difference=1e-05
begin
set state_values = state_values or dictionary comprehension s : 0 for s in call get_all_states
for i in range num_iter
begin
comment Compute new state values using the functions you defined above
comment It must be a dict ... | def value_iteration(mdp, state_values=None, gamma=0.9, num_iter=1000,
min_difference=1e-5):
state_values = state_values or {s: 0 for s in mdp.get_all_states()}
for i in range(num_iter):
# Compute new state values using the functions you defined above
# It must be a d... | Python | nomic_cornstack_python_v1 |
for d in range lb ub + 1 17
begin
set is_prime = 1
for e in range 2 d
begin
if d % e == 0
begin
set is_prime = 0
end
end
set not_prime_count = not_prime_count + 1 - is_prime
end
print not_prime_count | for d in range(lb, ub+1, 17):
is_prime = 1
for e in range(2, d):
if d % e == 0:
is_prime = 0
not_prime_count += (1-is_prime)
print(not_prime_count) | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
set x = call genfromtxt string ../../data/x.csv
set y = call genfromtxt string ../../data/y.csv
print x
print y
plot x y
show | import numpy as np
import matplotlib.pyplot as plt
x = np.genfromtxt("../../data/x.csv")
y = np.genfromtxt("../../data/y.csv")
print(x)
print(y)
plt.plot(x,y)
plt.show()
| Python | zaydzuhri_stack_edu_python |
import pytest
from helpers.parsing.lexer_error import LexerError
from helpers.parsing.word import Word , Raw , Quoted , Variable
decorator call parametrize list string input string expected list call param string test call Word list call Raw string test id=string simple call param string "test" call Word list call Quot... | import pytest
from helpers.parsing.lexer_error import LexerError
from helpers.parsing.word import Word, Raw, Quoted, Variable
@pytest.mark.parametrize(['input', 'expected'], [
pytest.param('test', Word([Raw('test')]), id="simple"),
pytest.param('"test"', Word([Quoted([Raw('test')])]), id="simple quotes"),
... | Python | zaydzuhri_stack_edu_python |
import logging
import sys
comment 創建日誌的實例
set logger = call getLogger string testLogger
comment 定制Logger的輸出格市
set formatter = call Formatter string %(asctime)s %(levelname)s %(message)s
comment 創建日誌:文件日誌
set file_handler = call FileHandler string testLogger.log
call setFormatter formatter
comment 創建日誌:終端機的日誌
set consle... | import logging
import sys
# 創建日誌的實例
logger = logging.getLogger("testLogger")
#定制Logger的輸出格市
formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s")
# 創建日誌:文件日誌
file_handler = logging.FileHandler('testLogger.log')
file_handler.setFormatter(formatter)
#創建日誌:終端機的日誌
consle_handler = logging.StreamHandle... | Python | zaydzuhri_stack_edu_python |
function make_new_row old_row
begin
if old_row == list
begin
return list 1
end
else
if old_row == list 1
begin
return list 1 1
end
else
begin
set new_row = list
append new_row 1
set n = length old_row
for i in range n
begin
append new_row old_row at i - 1 + old_row at i
end
append new_row 1
remove new_row 2
return ne... | def make_new_row(old_row):
if old_row==[]:
return [1]
elif old_row==[1]:
return [1,1]
else:
new_row=[]
new_row.append(1)
n = len(old_row)
for i in range(n):
new_row.append(old_row[i-1]+old_row[i])
new_row.append(1)
new_r... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
import os
import argparse
import cv2
import psycopg2 as pg
function rect_contains rect point
begin
if point at 0 < rect at 0
begin
return false
end
else
if point at 1 < rect at 1
begin
return false
end
else
if point at 0 > rect at 2
begin
return false
end
else
if point at 1 > rect at 3
begi... | #!/usr/bin/env python
import os
import argparse
import cv2
import psycopg2 as pg
def rect_contains(rect, point) :
if point[0] < rect[0] :
return False
elif point[1] < rect[1] :
return False
elif point[0] > rect[2] :
return False
elif point[1] > rect[3] :
return False
... | Python | zaydzuhri_stack_edu_python |
function get_rule words words_eol prefixless
begin
for rule in if expression prefixless then _prefixless_rules else _rules
begin
if full_message
begin
set match = match words_eol at 0
end
else
begin
set match = match words at 0
end
if match is not none
begin
if pass_match
begin
return tuple underlying tuple match
end
r... | def get_rule(words: List[str], words_eol: List[str],
prefixless: bool) -> Tuple[Optional[Callable], tuple]:
for rule in _prefixless_rules if prefixless else _rules:
if rule.full_message:
match = rule.pattern.match(words_eol[0])
else:
match = rule.pattern.match(wo... | Python | nomic_cornstack_python_v1 |
function reportMatch tid winner_id loser_id draw=string False
begin
if draw == string TRUE
begin
set w_points = 1
set l_points = 1
end
else
begin
set w_points = 3
set l_points = 0
end
set DB = call connect
set c = call cursor
set ins = string INSERT INTO matches (t_id, winner_id, loser_id, draw) VALUES (%s,%s,%s,%s)
se... | def reportMatch(tid, winner_id, loser_id, draw = 'False'):
if draw == 'TRUE':
w_points = 1
l_points = 1
else:
w_points = 3
l_points = 0
DB = connect()
c = DB.cursor()
ins = "INSERT INTO matches (t_id, winner_id, loser_id, draw) VALUES (%s,%s,%s,%s)"
wi... | Python | nomic_cornstack_python_v1 |
string Created on 21 de fev de 2017 @author: Alexandre Yukio Yamashita
import numpy as np
from models.nifti import Nifti
function normalize_min_max input_path output_path
begin
string Normalize brain intensity with min-max.
end function | '''
Created on 21 de fev de 2017
@author: Alexandre Yukio Yamashita
'''
import numpy as np
from models.nifti import Nifti
def normalize_min_max(input_path, output_path):
'''
Normalize brain intensity with min-max.
'''
| Python | zaydzuhri_stack_edu_python |
function hierarchical_clustering cluster_list num_clusters
begin
sort cluster_list key=lambda x -> call horiz_center
set dist_list = list comprehension call horiz_center for ele in cluster_list
while length cluster_list > num_clusters
begin
comment print dist_list
set tuple _ idx_1 idx_2 = call fast_closest_pair cluste... | def hierarchical_clustering(cluster_list, num_clusters):
cluster_list.sort(key = lambda x: x.horiz_center())
dist_list = [ ele.horiz_center() for ele in cluster_list ]
while len(cluster_list) > num_clusters:
# print dist_list
(_, idx_1, idx_2) = fast_closest_pair(cluster_list)
cluster... | Python | nomic_cornstack_python_v1 |
function check_data_dict self data_dict schema=none
begin
return
end function | def check_data_dict(self, data_dict, schema=None):
return | Python | nomic_cornstack_python_v1 |
import numpy as np
set x = array list list 2 3 list 4 5
set y = 5
set x1 = x + y
print type x
print type y
print x1
set x2 = array list list 2 3 list 7 8
set y2 = array list list 5 10
set x3 = x2 + y2
print string x2 shape shape
print string y2 shape shape
print string x3 shape shape
print string x3 x3 | import numpy as np
x = np.array([[2,3,],[4,5]])
y = 5
x1 = x + y
print(type(x))
print(type(y))
print(x1)
x2 = np.array([[2,3,],[7,8]])
y2 = np.array([[5,10]])
x3 = x2 + y2
print('x2 shape', x2.shape)
print('y2 shape', y2.shape)
print('x3 shape', x3.shape)
print('x3', x3) | Python | zaydzuhri_stack_edu_python |
function numberOfSteps num
begin
set steps = 0
while num != 0
begin
if num % 2 == 0
begin
set num = num / 2
set steps = steps + 1
end
else
begin
set num = num - 1
set steps = steps + 1
end
end
return steps
end function
print call numberOfSteps 8 | def numberOfSteps(num):
steps = 0
while num != 0:
if num % 2 == 0:
num /= 2
steps += 1
else:
num -= 1
steps += 1
return steps
print(numberOfSteps(8))
| Python | zaydzuhri_stack_edu_python |
function l_ordered_grad centre sample
begin
set seen_px = list
comment for r, row in enumerate(sample):
for tuple y row in enumerate sample
begin
if not any row
begin
comment Ignore rows not in sample (i.e. all RGBA=[0,0,0,0])
continue
end
for tuple x px in enumerate row
begin
comment Pick the non-blank pixel leftmost... | def l_ordered_grad(centre, sample):
seen_px = []
# for r, row in enumerate(sample):
for y, row in enumerate(sample):
if not np.any(row):
# Ignore rows not in sample (i.e. all RGBA=[0,0,0,0])
continue
for x, px in enumerate(row):
# Pick the non-blank pixel ... | Python | nomic_cornstack_python_v1 |
from typing import Dict , Iterable
import minio
from django.conf import settings
from minio import Minio
set s3 = call Minio S3_HOST access_key=S3_ACCESS_KEY secret_key=S3_SECRET_KEY secure=false
function get_object bucket_name object_name
begin
set response = none
try
begin
set response = call get_object bucket_name o... | from typing import Dict, Iterable
import minio
from django.conf import settings
from minio import Minio
s3 = Minio(
settings.S3_HOST,
access_key=settings.S3_ACCESS_KEY,
secret_key=settings.S3_SECRET_KEY,
secure=False
)
def get_object(bucket_name: str, object_name: str) -> str:
response = None
... | Python | zaydzuhri_stack_edu_python |
function validate self value
begin
if value is not none and not is instance value data_type
begin
try
begin
set value = read file
end
except AttributeError
begin
set value = none
end
end
set value = call validate value
return value
end function | def validate(self,value):
if value is not None and not isinstance(value, self.data_type):
try:
value = value.file.read()
except AttributeError:
value = None
value = super(FileTypeBlobProperty, self).validate(value)
retu... | Python | nomic_cornstack_python_v1 |
function sort_012 input_list
begin
set input_list_len = length input_list - 1
if input_list_len == 0
begin
return input_list
end
set mid_index = 0
set start_index = 0
set end_index = input_list_len - start_index
while mid_index <= end_index
begin
if input_list at mid_index == 0
begin
set tuple input_list at start_index... | def sort_012(input_list):
input_list_len = len(input_list) - 1
if input_list_len == 0:
return input_list
mid_index = 0
start_index = 0
end_index = input_list_len - start_index
while mid_index <= end_index:
if input_list[mid_index] == 0:
input_list[start_index], inpu... | Python | nomic_cornstack_python_v1 |
function writeFile filename data
begin
string Writes data to a file
with open filename string wb as f
begin
write f encode data string utf-8
end
end function | def writeFile(filename, data):
"""
Writes data to a file
"""
with open(filename, 'wb') as f:
f.write(data.encode('utf-8')) | Python | jtatman_500k |
import signalp , config , mysqlpop , output
string step4 Runs SignalP on step 3 output (CDS). Outputs results to .csv file and updates the seqreads table in the SQLite DB.
function CDS file
begin
set First_line = true
set seqs = list
with open file as f
begin
for l in f
begin
set ll = split strip l string ,
if First_l... | import signalp,config,mysqlpop,output
"""
step4
Runs SignalP on step 3 output (CDS).
Outputs results to .csv file and updates the seqreads table in the SQLite DB.
"""
def CDS(file):
First_line = True
seqs = []
with open(file) as f:
for l in f:
ll = l.strip().split(',')
i... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
class Solution extends object
begin
comment def hammingWeight(self, n):
comment bitcnt = 0
comment while(n):
comment if n & 1:
comment bitcnt += 1
comment n >>= 1
comment return bitcnt
function hammingWeight self n
begin
set bitcnt = 0
while n
begin
set n = n ? n - 1
set bitcnt = bitcnt + 1... | #!/usr/bin/env python
class Solution(object):
# def hammingWeight(self, n):
# bitcnt = 0
# while(n):
# if n & 1:
# bitcnt += 1
# n >>= 1
#
# return bitcnt
def hammingWeight(self, n: int) -> int:
bitcnt = 0
while(n):
n = n & (n - 1)
bitcnt += 1
return bitcnt
if __name__ == '__main__':
sol = ... | Python | zaydzuhri_stack_edu_python |
function number_in_list number
begin
set my_list = list 1 2 3 4
assert number in my_list msg format string Number {} not in {} number call __repr__
return format string Number {} is in list. number
end function
string Output: Traceback (most recent call last): File "/project/Python_Exceptions/asserting_using_AssertionE... | def number_in_list(number):
my_list = [1, 2, 3, 4]
assert (number in my_list), "Number {} not in {}".format(number,
my_list.__repr__())
return "Number {} is in list.".format(number)
"""
Output:
Traceback (most recent call last):
File "/project... | Python | zaydzuhri_stack_edu_python |
for i in range length list1
begin
if list2 at i % 2 == 0
begin
set dictionary at list1 at i = list2 at i
end
end
print dictionary | for i in range(len(list1)):
if list2[i] % 2 == 0:
dictionary[list1[i]] = list2[i]
print(dictionary) | Python | jtatman_500k |
function rightOrWrong playerAnswer realAnswer
begin
if realAnswer != playerAnswer
begin
return print string You are incorrect! try again!
end
else
begin
return print string You are correct! Play again!
end
end function | def rightOrWrong(playerAnswer, realAnswer):
if realAnswer != playerAnswer:
return print("You are incorrect! try again!")
else:
return print("You are correct! Play again!") | Python | nomic_cornstack_python_v1 |
from keras.preprocessing import image
from keras.layers import Conv2D , Dense , Dropout , MaxPool2D , Flatten
from keras.models import Sequential
from keras.callbacks import TensorBoard
comment preprocess all image in batch, This task is kind of CPU intensive, beginners, be aware!!
print string Processing...
set genera... | from keras.preprocessing import image
from keras.layers import Conv2D, Dense, Dropout, MaxPool2D, Flatten
from keras.models import Sequential
from keras.callbacks import TensorBoard
#preprocess all image in batch, This task is kind of CPU intensive, beginners, be aware!!
print('Processing...')
generator = image.Imag... | Python | zaydzuhri_stack_edu_python |
function pickle_tester file_name
begin
set english_file = open file_name string rb
set reloaded_english_words = load pickle english_file
set hist = call histogram join string reloaded_english_words
set couples = list
set end_string = string
for item in hist
begin
append couples tuple hist at item item
end
comment so... | def pickle_tester(file_name):
english_file = open(file_name, 'rb')
reloaded_english_words = pickle.load(english_file)
hist = histogram(''.join(reloaded_english_words))
couples = []
end_string = ''
for item in hist:
couples.append((hist[item], item))
couples.sort(key=lambda tup: tup[... | Python | nomic_cornstack_python_v1 |
import click
import requests
import random
import logging
import pandas as pd
from time import sleep
from itertools import cycle
from bs4 import BeautifulSoup
from fake_useragent import UserAgent , FakeUserAgentError
from pprint import pprint
import multipage
import itemspreview
import singleitem
from helpers import ra... | import click
import requests
import random
import logging
import pandas as pd
from time import sleep
from itertools import cycle
from bs4 import BeautifulSoup
from fake_useragent import UserAgent, FakeUserAgentError
from pprint import pprint
import multipage
import itemspreview
import singleitem
from helpers import r... | Python | zaydzuhri_stack_edu_python |
import urllib.request
import json
set url = string http://data.fixer.io/api/latest?access_key=c5ce8bfc38506d2f66aed4fcf0847053&format=1
set req = call Request url
comment parsing response
set r = read url open req
set cont = loads decode r string utf-8
set rates = cont at string rates
function getcurrency amount_money ... | import urllib.request
import json
url = 'http://data.fixer.io/api/latest?access_key=c5ce8bfc38506d2f66aed4fcf0847053&format=1'
req = urllib.request.Request(url)
##parsing response
r = urllib.request.urlopen(req).read()
cont = json.loads(r.decode('utf-8'))
rates = cont['rates']
def getcurrency(amount_money, currency_i... | Python | zaydzuhri_stack_edu_python |
import math
from controllers import *
from dc_motor import *
class MotionSystem
begin
function __init__ self _M _wheelbase _wheel_mass _wheel_radius _kp_speed _ki_speed x=0 y=0 theta=0
begin
set friction = 7e-05
set __left_w = call Motor2642_with_gearbox _wheel_mass _wheel_radius _M / 2.0 friction
set __right_w = call ... | import math
from controllers import *
from dc_motor import *
class MotionSystem:
def __init__(self, _M, _wheelbase, _wheel_mass, _wheel_radius, _kp_speed, _ki_speed, x=0, y=0, theta = 0):
friction = 7e-5
self.__left_w = Motor2642_with_gearbox( _wheel_mass,
... | Python | zaydzuhri_stack_edu_python |
from django.shortcuts import render , HttpResponse , redirect
import random
comment Create your views here.
function index request
begin
return call render request string wordGen/index.html
end function
function generator request
begin
if string counter in session
begin
set session at string counter = session at string... | from django.shortcuts import render, HttpResponse, redirect
import random
# Create your views here.
def index(request):
return render(request, 'wordGen/index.html')
def generator(request):
if 'counter' in request.session:
request.session['counter'] += 1
else:
request.session['counter'] = 1
word = ''
chars... | Python | zaydzuhri_stack_edu_python |
function status self
begin
return get pulumi self string status
end function | def status(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "status") | Python | nomic_cornstack_python_v1 |
function test_compare_difference_string_faster self
begin
set test_algorithm = string bubble
set test_algorithm_time = 2
set test_sorted_time = 4
set result = call calculate_compare_time_difference test_algorithm_time test_sorted_time test_algorithm
assert equal string bubble was 2 seconds faster. result
end function | def test_compare_difference_string_faster(self):
test_algorithm = 'bubble'
test_algorithm_time = 2
test_sorted_time = 4
result = calculate_compare_time_difference(test_algorithm_time, test_sorted_time, test_algorithm)
self.assertEqual('bubble was 2 seconds faster.', result) | Python | nomic_cornstack_python_v1 |
function create_json_list_file_if_not_exits file_name
begin
try
begin
close open file_name string x
with open file_name string w encoding=string UTF-8 as f
begin
dump list f
end
end
except FileExistsError
begin
pass
end
end function | def create_json_list_file_if_not_exits(file_name):
try:
open(file_name, "x").close()
with open(file_name, 'w', encoding='UTF-8') as f:
json.dump([], f)
except FileExistsError:
pass | Python | nomic_cornstack_python_v1 |
string this code is based on Publisher-Subscriber pattern of: https://github.com/madhur2511/Publisher-Subscriber-ImplementationThis is a simple implementation of Publisher/Subscriber implementation in Python on a single machine and not over the network.
import logging
from collections import defaultdict
class Broker
be... | """this code is based on Publisher-Subscriber pattern of: https://github.com/madhur2511/Publisher-Subscriber-Implementation\
This is a simple implementation of Publisher/Subscriber implementation in Python on a single machine and not over the network."""
import logging
from collections import defaultdict
class Broker... | Python | zaydzuhri_stack_edu_python |
function adding queue_items_creation_function=none queue_name=none other_args=none
begin
function decorator decorated_function
begin
decorator wraps decorated_function
function wrapper *args **kwargs
begin
set handler = call QueuesHandler
set real_queue_name = if expression queue_name is none then default_queue_name el... | def adding(queue_items_creation_function: Callable[..., List[Tuple[Any, Dict]]] = None,
queue_name: Union[str, None] = None,
other_args: Union[None, Dict[str, Any]] = None) -> Callable:
def decorator(decorated_function: Callable) -> Callable:
@wraps(decorated_function)
def wra... | Python | nomic_cornstack_python_v1 |
from pathlib import Path , PurePath
from import util
function test_reroot_path
begin
set tuple relative absolute = call reroot_path call PurePath string /foo/bar/baz.rst call PurePath string /foo/dir/test.txt call Path string foo
assert call is_absolute
assert relative == call PurePath string foo/bar/baz.rst
assert ca... | from pathlib import Path, PurePath
from . import util
def test_reroot_path() -> None:
relative, absolute = util.reroot_path(
PurePath('/foo/bar/baz.rst'),
PurePath('/foo/dir/test.txt'),
Path('foo'))
assert absolute.is_absolute()
assert relative == PurePath('foo/bar/baz.rst')
as... | Python | zaydzuhri_stack_edu_python |
comment python3
comment Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
comment Note: The solution set must not contain duplicate subsets.
comment For example,
comment If nums = [1,2,2], a solution is:
comment [
comment [2],
comment [1],
comment [1,2,2],
... | # python3
# Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).
# Note: The solution set must not contain duplicate subsets.
# For example,
# If nums = [1,2,2], a solution is:
# [
# [2],
# [1],
# [1,2,2],
# [2,2],
# [1,2],
# []
#... | Python | zaydzuhri_stack_edu_python |
function groupLogsByType logs filterState
begin
if not logs
begin
return list
end
comment Define the possible severity levels and their order
set severity_levels = dict string critical 0 ; string error 1 ; string warning 2 ; string info 3
comment Filter logs by severity level
if filterState in severity_levels
begin
se... | def groupLogsByType(logs, filterState):
if not logs:
return []
# Define the possible severity levels and their order
severity_levels = {
'critical': 0,
'error': 1,
'warning': 2,
'info': 3
}
# Filter logs by severity level
if filterState in s... | Python | jtatman_500k |
function has_queued_messages self
begin
return boolean mqueue
end function | def has_queued_messages(self):
return bool(self.mqueue) | Python | nomic_cornstack_python_v1 |
function get_illustrator verbose=false
begin
if expression verbose then print string Targeting or opening Illustrator... else none
try
begin
set app = call GetActiveObject string Illustrator.Application
end
except com_error
begin
set app = call Dispatch string Illustrator.Application
end
return app
end function | def get_illustrator(verbose=False):
print('Targeting or opening Illustrator...') if verbose else None
try:
app = GetActiveObject('Illustrator.Application')
except pywintypes.com_error:
app = Dispatch('Illustrator.Application')
return app | Python | nomic_cornstack_python_v1 |
function update_row self row_id update_data
begin
comment Check to make sure all the column names given by user match the column names in the table.
set data = call __scrub_data update_data
set path = call __data_file_for_row_id row_id
if data
begin
comment Create a temp data file with the updated row data.
if call __m... | def update_row(self, row_id, update_data):
#Check to make sure all the column names given by user match the column names in the table.
data = self.__scrub_data(update_data)
path = self.__data_file_for_row_id(row_id)
if data:
#Create a temp data file with the updated row data.... | Python | nomic_cornstack_python_v1 |
import sublime , sublime_plugin
import re
class EditableReplaceCommand extends TextCommand
begin
function __init__ self arg
begin
call __init__ arg
set path_regex = compile string ^([^#]\S+):
set repl_regex = compile string ^\s+(\d+): (.*?)$
end function
function is_visible self
begin
return call file_name == none and ... | import sublime, sublime_plugin
import re
class EditableReplaceCommand(sublime_plugin.TextCommand):
def __init__(self, arg):
super(EditableReplaceCommand, self).__init__(arg)
self.path_regex = re.compile(r"^([^#]\S+):")
self.repl_regex = re.compile(r"^\s+(\d+): (.*?)$")
def is_visible(s... | Python | zaydzuhri_stack_edu_python |
function add_item self item
begin
append __items_list item
end function | def add_item(self, item: Item):
self.__items_list.append(item) | Python | nomic_cornstack_python_v1 |
if n > 0
begin
with open string hightemp.txt as data_file
begin
set lines = read lines data_file
end
for line in lines at slice : n :
begin
print right strip line
end
end
string head -n 1 hightemp.txt | if n > 0:
with open("hightemp.txt") as data_file:
lines = data_file.readlines()
for line in lines[:n]:
print(line.rstrip())
"""
head -n 1 hightemp.txt
"""
| Python | zaydzuhri_stack_edu_python |
function survival grids
begin
set tuple grid grid_a grid_b = grids
for i in range length grid
begin
for j in range length grid at 0
begin
comment if empty cell, continue
if grid_a at i at j == 0
begin
continue
end
comment get chance
if not grid at i at j == grid_a at i at j
begin
set chance = 1 - SURVIVAL at grid_a at ... | def survival(grids):
grid, grid_a, grid_b = grids
for i in range(len(grid)):
for j in range(len(grid[0])):
# if empty cell, continue
if grid_a[i][j] == 0:
continue
# get chance
if not grid[i][j] == grid_a[i][j]:
chance = ... | Python | nomic_cornstack_python_v1 |
function skim_generator lines file
begin
set total_length = 0
set count = 0
set seekable = true
end function
comment Try and seek in the file. If it's a stream, we can't do it | def skim_generator(lines, file):
total_length = 0
count = 0
seekable = True
# Try and seek in the file. If it's a stream, we can't do it | Python | nomic_cornstack_python_v1 |
for i in range 1 tries + 1
begin
set tuple p q r s w = map int split input
set a_fare = p * w
set b_fare = if expression w <= r then q else q + s * w - r
set best_fare = if expression a_fare >= b_fare then b_fare else a_fare
print format string #{} {} i best_fare
end | for i in range(1, tries + 1):
p, q, r, s, w = map(int, input().split())
a_fare = p * w
b_fare = q if w <= r else q + s * (w - r)
best_fare = b_fare if a_fare >= b_fare else a_fare
print('#{} {}'.format(i, best_fare))
| Python | zaydzuhri_stack_edu_python |
function testLabels self
begin
call _UpdateOrAllocateDBObject User user_id=user_id labels=list STAGING REGISTERED
set response_dict = call QueryUsers _cookie list user_id
assert equal response_dict at string users at 0 at string labels list REGISTERED string friend
end function | def testLabels(self):
self._UpdateOrAllocateDBObject(User,
user_id=self._andy_user.user_id,
labels=[User.STAGING, User.REGISTERED])
response_dict = self._tester.QueryUsers(self._cookie, [self._andy_user.user_id])
self.assertEqual(r... | Python | nomic_cornstack_python_v1 |
function test_docstring_mandatory self
begin
assert is not none __doc__
assert is not none __doc__
end function | def test_docstring_mandatory(self):
self.assertIsNotNone(models.place.__doc__)
self.assertIsNotNone(Place.__doc__) | Python | nomic_cornstack_python_v1 |
function startup self
begin
set enable = false
call _set_channels list false false false
call update_do_channels
end function | def startup(self):
self.enable = False
self._set_channels([False, False, False])
self.daqcontroller.update_do_channels() | Python | nomic_cornstack_python_v1 |
import random
import pdb
import math
import pylab as pl
from matplotlib.patches import Ellipse
from scipy.stats import multivariate_normal
from scipy.misc import logsumexp
import numpy as np
import copy
comment Mixture Of Gaussians
comment A simple class for a Mixture of Gaussians
class MOG
begin
function __init__ self... | import random
import pdb
import math
import pylab as pl
from matplotlib.patches import Ellipse
from scipy.stats import multivariate_normal
from scipy.misc import logsumexp
import numpy as np
import copy
#############################
# Mixture Of Gaussians
#############################
# A simple class for a Mixture... | Python | zaydzuhri_stack_edu_python |
function handle_template self template subdir
begin
if template is none
begin
return join path __path__ at 0 string conf subdir
end
else
begin
set template = call removeprefix string file://
set expanded_template = expand user path template
set expanded_template = call normpath expanded_template
if is directory path ex... | def handle_template(self, template, subdir):
if template is None:
return os.path.join(django.__path__[0], "conf", subdir)
else:
template = template.removeprefix("file://")
expanded_template = os.path.expanduser(template)
expanded_template = os.path.normpat... | Python | nomic_cornstack_python_v1 |
function get_revision_sha self dest rev
begin
string Return (sha_or_none, is_branch), where sha_or_none is a commit hash if the revision names a remote branch or tag, otherwise None. Args: dest: the repository directory. rev: the revision name.
comment Pass rev to pre-filter the list.
set output = call run_command list... | def get_revision_sha(self, dest, rev):
"""
Return (sha_or_none, is_branch), where sha_or_none is a commit hash
if the revision names a remote branch or tag, otherwise None.
Args:
dest: the repository directory.
rev: the revision name.
"""
# Pass rev t... | Python | jtatman_500k |
function input_names self
begin
return _input_names
end function | def input_names(self) -> List[str]:
return self._input_names | Python | nomic_cornstack_python_v1 |
string HACKERRANK PYTHON FINDING THE PERCENTAGE URL: https://www.hackerrank.com/challenges/finding-the-percentage/problem TASK: You have a record of N students. Each record contains the student's name, and their percent marks in Maths, Physics and Chemistry. The marks can be floating values. The user enters some intege... | """
HACKERRANK PYTHON FINDING THE PERCENTAGE
URL: https://www.hackerrank.com/challenges/finding-the-percentage/problem
TASK: You have a record of N students. Each record contains the student's name, and their percent marks in Maths, Physics and Chemistry. The marks can be floating values. The user ... | Python | zaydzuhri_stack_edu_python |
comment Compute velocity and acceleration from 1D position data
import numpy as np
function kinematics x i dt=1e-06
begin
set n = length x
set t = list 0
set v_list = list
set a_list = list
for i in range 1 n
begin
append t t at - 1 + dt
end
for i in range 1 n - 1
begin
set v_num = x at i + 1 - x at i - 1
set v_den =... | # Compute velocity and acceleration from 1D position data
import numpy as np;
def kinematics(x, i, dt=1E-6):
n = len(x)
t = [0]
v_list = []
a_list = []
for i in range(1, n):
t.append(t[-1]+dt)
for i in range(1, n-1):
v_num = x[i + 1] - x[i-1]
v_den = t[i+1] - t[i-1]
vi = v_num ... | Python | zaydzuhri_stack_edu_python |
class Score
begin
function __init__ self goals=0 points=0
begin
set goals = goals
set points = points
end function
function abs_score self
begin
return points + goals * 3
end function
function greater_than self other
begin
return call abs_score < call abs_score
end function
function less_than self other
begin
return ca... | class Score:
def __init__(self, goals=0, points=0):
self.goals = goals
self.points = points
def abs_score(self):
return self.points + self.goals * 3
def greater_than(self, other):
return other.abs_score() < self.abs_score()
def less_than(self, other):
... | Python | zaydzuhri_stack_edu_python |
function user_consent_description self
begin
return get pulumi self string user_consent_description
end function | def user_consent_description(self) -> str:
return pulumi.get(self, "user_consent_description") | 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.