code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function reverse_odd_divisible_by_three arr
begin
comment Create a new array to store the reversed elements
set reversed_arr = list
comment Traverse the input array
for num in arr
begin
comment Check if the number is odd and divisible by 3
if num % 2 == 1 and num % 3 == 0
begin
comment Convert the number to a string a... | def reverse_odd_divisible_by_three(arr):
# Create a new array to store the reversed elements
reversed_arr = []
# Traverse the input array
for num in arr:
# Check if the number is odd and divisible by 3
if num % 2 == 1 and num % 3 == 0:
# Convert the number to a string an... | Python | jtatman_500k |
comment ch17_27.py
from PIL import Image
import pytesseract
set text = call image_to_string open string d:\Python\ch17\data17_27.jpg lang=string chi_sim
print text
with open string d:\Python\ch17\out17_27.txt string w encoding=string utf-8 as fn
begin
write fn text
end | # ch17_27.py
from PIL import Image
import pytesseract
text = pytesseract.image_to_string(Image.open('d:\\Python\\ch17\\data17_27.jpg'),
lang='chi_sim')
print(text)
with open('d:\\Python\\ch17\\out17_27.txt', 'w', encoding='utf-8') as fn:
fn.write(text)
| Python | zaydzuhri_stack_edu_python |
import subprocess
function checkStr s
begin
set p = popen list string wine string inctfchall.exe stdin=PIPE stdout=PIPE
write stdin encode s string utf-8
set h = split decode communicate p at 0 string utf-8 string at 0
print h
set h = split h string } at - 1
return integer h
end function
function checkStrBetter s
begin... | import subprocess
def checkStr(s):
p = subprocess.Popen(['wine', 'inctfchall.exe'], stdin=subprocess.PIPE,stdout=subprocess.PIPE)
p.stdin.write(s.encode('utf-8'))
h = p.communicate()[0].decode('utf-8').split('\r\n')[0]
print(h)
h = h.split('}')[-1]
return int(h)
def checkStrBetter(s):
p = ... | Python | zaydzuhri_stack_edu_python |
function __init__ self new_month new_day new_year
begin
set month = new_month
set day = new_day
set year = new_year
end function | def __init__(self, new_month, new_day, new_year):
self.month = new_month
self.day = new_day
self.year = new_year | Python | nomic_cornstack_python_v1 |
comment coding=utf-8
set name = string Zed A. Shaw
comment not a lie
set age = 35
comment inches
set height = 74.0
comment 英寸和厘米的转换
set height_cm = height * 2.54
comment lbs
set weight = 180
set eyes = string Blue
set teeth = string White
set hair = string Brown | #coding=utf-8
name = 'Zed A. Shaw'
age = 35 # not a lie
height = 74.0 # inches
height_cm = height * 2.54 # 英寸和厘米的转换
weight = 180 # lbs
eyes = "Blue"
teeth = 'White'
hair = 'Brown'
| Python | zaydzuhri_stack_edu_python |
comment lambda example
set d = lambda p -> p * 2
set t = lambda p -> p * 3
set x = 2
comment x=4 function call pointing to that anonymous fun p=2 : 2*2
set x = call d x
comment x= 12
set x = t dist x
comment x=24
set x = call d x
print x | #lambda example
d = lambda p: p * 2
t = lambda p: p * 3
x = 2
x = d(x) #x=4 function call pointing to that anonymous fun p=2 : 2*2
x = t(x) #x= 12
x = d(x) # x=24
print (x )
| Python | zaydzuhri_stack_edu_python |
function __del__ self
begin
if exclusive_lock
begin
close fd
end
end function | def __del__(self):
if self.exclusive_lock:
self.fd.close() | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string 消费者: group_id=None 测试结果: 1. 消费者可以大于分区数, 所有消费者都会收到消息 2. auto_offset_reset='earliest' 每次启动都会从最开始消费 3. auto_offset_reset='latest' 每次从最新的开始消费, 不会管哪些任务还没有消费
from kafka import KafkaConsumer
set topic = string demo
function main
begin
set consumer = call KafkaConsumer topic bootstrap_serve... | # -*- coding: utf-8 -*-
'''
消费者: group_id=None
测试结果:
1. 消费者可以大于分区数, 所有消费者都会收到消息
2. auto_offset_reset='earliest' 每次启动都会从最开始消费
3. auto_offset_reset='latest' 每次从最新的开始消费, 不会管哪些任务还没有消费
'''
from kafka import KafkaConsumer
topic = 'demo'
def main():
consumer = KafkaConsumer(
topic,
bootstrap_servers=... | Python | zaydzuhri_stack_edu_python |
import cv2
import numpy as np
from google.colab.patches import cv2_imshow
set carplate_img = call imread string a.jpg
set grayScale = call cvtColor carplate_img COLOR_BGR2GRAY
set x = call Sobel grayScale CV_16S 1 0
set absX = call convertScaleAbs x
set out = call threshold absX 127 255 THRESH_OTSU
set kernelX = ones t... | import cv2
import numpy as np
from google.colab.patches import cv2_imshow
carplate_img = cv2.imread("a.jpg")
grayScale = cv2.cvtColor(carplate_img, cv2.COLOR_BGR2GRAY)
x = cv2.Sobel(grayScale, cv2.CV_16S, 1, 0)
absX = cv2.convertScaleAbs(x)
out = cv2.threshold(absX, 127, 255, cv2.THRESH_OTSU)
kernelX = np.ones((1,3)... | Python | zaydzuhri_stack_edu_python |
import socket
from threading import Thread
from robologger.robologger import get_logger
from server.processor import Processor
set log = call get_logger string RoboCar control server
string Control server for receiving continuous control data (X, Y axis)
class ControlServer
begin
function __init__ self port host=string... | import socket
from threading import Thread
from robologger.robologger import get_logger
from server.processor import Processor
log = get_logger('RoboCar control server')
"""
Control server for receiving continuous control data (X, Y axis)
"""
class ControlServer:
def __init__(self, port, host="0.0.0.0"):
... | Python | zaydzuhri_stack_edu_python |
function __init__ self node partial=false namespaces=call frozenset aliases=false
begin
if not namespaces and not partial
begin
raise call ValueError string Either set partial to True or define some Python namespaces.
end
call __init__
set _aliases = aliases
set _node = node
set _partial = partial
set _namespaces = nam... | def __init__(self, node, partial=False, namespaces=frozenset(), aliases=False):
if not namespaces and not partial:
raise ValueError(
"Either set partial to True or define some Python namespaces."
)
super(BaseAdapter, self).__init__()
self._aliases = alia... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
import sys
append path string ../
from scaffolding import common
import copy
from collections import deque , defaultdict
class Solution extends object
begin
comment inputNumbers = common.pullNumbersFromList(inputList, True) #True = include signs, False: all numbers are positive
function __init... | #!/usr/bin/python3
import sys
sys.path.append('../')
from scaffolding import common
import copy
from collections import deque, defaultdict
class Solution(object):
#inputNumbers = common.pullNumbersFromList(inputList, True) #True = include signs, False: all numbers are positive
def __init__(self):
pass
def solu... | Python | zaydzuhri_stack_edu_python |
comment coding: utf-8
comment In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import re
comment In[23]:
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense , Embedding , LST... | # coding: utf-8
# In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import re
# In[23]:
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense, Embedding, LSTM, SpatialDro... | Python | zaydzuhri_stack_edu_python |
comment Definition for a binary tree node.
comment class TreeNode:
comment def __init__(self, x):
comment self.val = x
comment self.left = None
comment self.right = None
class Solution
begin
function subtreeWithAllDeepest self root
begin
if root == none
begin
return root
end
set tmp = list list root 0
set tmp2 = list r... | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
if root==None:return root
tmp = [... | Python | zaydzuhri_stack_edu_python |
comment You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatic... | # You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have a security system connected, and it will automatically c... | Python | zaydzuhri_stack_edu_python |
function test_get_embeddings_distances_with_numpy self
begin
if NUMPY_AVAILABLE
begin
set NUMPY_LOADED = true
set NUMPY_AVAILABLE = true
set emb1 = embedding string [ 0.0158451 -0.10712819 0.03863023 -0.03482883 -0.0824572 0.14168985 -0.09636037 0.19106716 -0.02492222 0.14210707 -0.01116645 -0.02843223 0.11468598 0.052... | def test_get_embeddings_distances_with_numpy(self):
if NUMPY_AVAILABLE:
EMB.NUMPY_LOADED = True
FACEREC.NUMPY_AVAILABLE = True
emb1 = Embedding("[ 0.0158451 -0.10712819 0.03863023 -0.03482883 -0.0824572 0.14168985 -0.09636037 0.19106716 -0.02492222 0.14210707 -0.011166... | Python | nomic_cornstack_python_v1 |
for line in f
begin
set s = split line string
if s at 8 == string 200
begin
set a = a + 1
end
else
if 300 <= integer s at 8 < 310
begin
set b = b + 1
end
else
begin
set c = c + 1
end
end
close f | for line in f:
s = line.split(' ')
if s[8] == '200':
a += 1
elif 300 <= (int)(s[8]) < 310:
b += 1
else:
c += 1
f.close() | Python | zaydzuhri_stack_edu_python |
import pygame , random
from constants import *
function draw_candy candy_pos
begin
call rect screen DARK_RED tuple candy_pos at 0 * SQUARE + 2 candy_pos at 1 * SQUARE + 2 + GAP SQUARE - 4 SQUARE - 4
end function
function new_candy possitions
begin
while true
begin
set candy_pos = list call randrange 0 NUMBER_OF_ROWS_AN... | import pygame, random
from .constants import *
def draw_candy(candy_pos):
pygame.draw.rect(screen, DARK_RED, (candy_pos[0] * SQUARE + 2, candy_pos[1] * SQUARE + 2 + GAP, SQUARE - 4, SQUARE - 4))
def new_candy(possitions):
while True:
candy_pos = [random.randrange(0, NUMBER_OF_ROWS_AND_COLUMNS), random... | Python | zaydzuhri_stack_edu_python |
function ts64 x u
begin
for i in range 7 - 1 - 1
begin
set x at i = call u8 u
set u = u ? 8
end
return x
end function | def ts64(x, u):
for i in range(7, -1, -1):
x[i] = u8(u)
u >>= 8
return x | Python | nomic_cornstack_python_v1 |
function subtract numero1 numero2
begin
set result = numero1 - numero2
return result
end function
set answer = call subtract 530 222 | def subtract (numero1, numero2):
result=numero1 - numero2
return result
answer = subtract(530, 222) | Python | zaydzuhri_stack_edu_python |
comment !/bin/env python
import matplotlib
call use string pdf
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import pickle
import numpy as np
import math
from scipy import optimize
from shapely.geometry import Polygon
class Helix
begin
function __init__ self center radius phi lam cha... | #!/bin/env python
import matplotlib
matplotlib.use('pdf')
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
import pickle
import numpy as np
import math
from scipy import optimize
from shapely.geometry import Polygon
class Helix:
def __init__(self, center, radius, phi, lam, charge)... | Python | zaydzuhri_stack_edu_python |
with open string input.txt string r as f
begin
set inp = strip read f string
end
function compute_score inp
begin
set garbage = false
set garb_n = 0
set score = 0
set nest = 0
set i = 0
while i < length inp
begin
if garbage
begin
if inp at i == string >
begin
set garbage = false
end
else
if inp at i == string !
begin
s... | with open('input.txt', 'r') as f:
inp = f.read().strip('\n')
def compute_score(inp):
garbage = False
garb_n = 0
score = 0
nest = 0
i = 0
while i < len(inp):
if garbage:
if inp[i] == '>':
garbage = False
elif inp[i] == '!':
i +=... | Python | zaydzuhri_stack_edu_python |
function post self
begin
set file = files at string file
set filename = call secure_filename filename
if file and call __allowed_file file
begin
set calced_hash = hex digest sha1 read stream
seek stream 0
set _filename = format string {}.{} calced_hash split filename string . at - 1
if not ends with _filename string .m... | def post(self):
file = request.files['file']
filename = secure_filename(file.filename)
if file and self.__allowed_file(file):
calced_hash = sha1(file.stream.read()).hexdigest()
file.stream.seek(0)
_filename = "{}.{}".format(calced_hash, file.filename.split('.'... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
from selenium import webdriver
import time
import json
set q_class = dict
function crawl u
begin
set browser = call Chrome
get browser u
set con = call find_elements_by_css_selector string #root > table:nth-child(5) > tbody > tr > td:nth-child(1) > table:nth-child(2)
set title_urls = list... | # -*- coding: utf-8 -*-
from selenium import webdriver
import time
import json
q_class = {}
def crawl(u):
browser = webdriver.Chrome()
browser.get(u)
con = browser.find_elements_by_css_selector(
"#root > table:nth-child(5) > tbody > tr > td:nth-child(1) > table:nth-child(2)")
title_urls = []... | Python | zaydzuhri_stack_edu_python |
comment <-
function push self value
begin
set top = call Node value next=top
end function | def push(self, value): ################# <-
self.top = Node(value, next=self.top) | Python | nomic_cornstack_python_v1 |
import numpy
from matplotlib import pyplot
function from_celestial_to_horizontal HA dec L
begin
comment Derive equations by writing down the sides of a triangle on a sphere, and the angles.
comment Use the cosine rule to relate Elevation/Altitude to the sides
comment Then use the cosine rule to relate Azimuthal angle t... | import numpy
from matplotlib import pyplot
def from_celestial_to_horizontal(HA, dec, L):
#Derive equations by writing down the sides of a triangle on a sphere, and the angles.
#Use the cosine rule to relate Elevation/Altitude to the sides
#Then use the cosine rule to relate Azimuthal angle to the sides
... | Python | zaydzuhri_stack_edu_python |
function __init__ self cost_func
begin
call __init__ cost_func
set support_for_bounds = true
set param_ranges = none
set _status = none
set _popt = none
set _options = dict
end function | def __init__(self, cost_func):
super().__init__(cost_func)
self.support_for_bounds = True
self.param_ranges = None
self._status = None
self._popt = None
self._options = {} | Python | nomic_cornstack_python_v1 |
function dsa_urlopen *args **kwargs
begin
set timeout = call setting string SOCIAL_AUTH_URLOPEN_TIMEOUT
if timeout and string timeout not in kwargs
begin
set kwargs at string timeout = timeout
end
return url open *args keyword kwargs
end function | def dsa_urlopen(*args, **kwargs):
timeout = setting('SOCIAL_AUTH_URLOPEN_TIMEOUT')
if timeout and 'timeout' not in kwargs:
kwargs['timeout'] = timeout
return urlopen(*args, **kwargs) | Python | nomic_cornstack_python_v1 |
function __call__ self func
begin
decorator call sage_wraps func
function wrapper *args **kwds
begin
set suboptions = copy options
update suboptions pop kwds name + string options dict
comment Collect all the relevant keywords in kwds
comment and put them in suboptions
for tuple key value in items kwds
begin
if starts ... | def __call__(self, func):
@sage_wraps(func)
def wrapper(*args, **kwds):
suboptions = copy(self.options)
suboptions.update(kwds.pop(self.name+"options", {}))
#Collect all the relevant keywords in kwds
#and put them in suboptions
for key, value ... | Python | nomic_cornstack_python_v1 |
import urllib.request
import json
from tkinter import *
set root = call Tk
set url = string http://api.openweathermap.org/data/2.5/forecast?q= + string input string enter city + string &appid=yourappid
set response = url open url
set data = read response
set js = loads data
set name = js at string city at string name
s... | import urllib.request
import json
from tkinter import *
root=Tk()
url="http://api.openweathermap.org/data/2.5/forecast?q="+str(input("enter city"))+"&appid=yourappid"
response=urllib.request.urlopen(url)
data=response.read()
js=json.loads(data)
name=js["city"]["name"]
country=js["city"]["country"]
temp=str(in... | Python | zaydzuhri_stack_edu_python |
function iou_ddd_distance atracks btracks frame_id=0 use_prediction=true
begin
if length atracks > 0 and is instance atracks at 0 ndarray or length btracks > 0 and is instance btracks at 0 ndarray
begin
set atlbrs = atracks
set btlbrs = btracks
end
else
begin
set atlbrs = list comprehension call convert_3dbox_to_8corne... | def iou_ddd_distance(atracks, btracks, frame_id=0, use_prediction=True):
if (len(atracks) > 0 and isinstance(atracks[0], np.ndarray)) or (
len(btracks) > 0 and isinstance(btracks[0], np.ndarray)
):
atlbrs = atracks
btlbrs = btracks
else:
atlbrs = [convert_3dbox_to_8corner(tr... | Python | nomic_cornstack_python_v1 |
comment Code from Chapter 6 of Machine Learning: An Algorithmic Perspective (2nd Edition)
comment by Stephen Marsland (http://stephenmonika.net)
comment You are free to use, change, or redistribute the code in any way you wish for
comment non-commercial purposes, but please maintain the name of the original author.
com... | # Code from Chapter 6 of Machine Learning: An Algorithmic Perspective (2nd Edition)
# by Stephen Marsland (http://stephenmonika.net)
# You are free to use, change, or redistribute the code in any way you wish for
# non-commercial purposes, but please maintain the name of the original author.
# This code comes with no ... | Python | zaydzuhri_stack_edu_python |
comment # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
comment The player class is an object that will allow me to access the same player multiple times without having to deal #
comment with the rate limit on looking up the same player endpoint mult... | # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# The player class is an object that will allow me to access the same player multiple times without having to deal #
# with the rate limit on looking up the same player endpoint multiple times. ... | Python | zaydzuhri_stack_edu_python |
function grapebot_control_cmd_callback self msg
begin
if robotStop
begin
set control_mode = control_mode
set linear_velocity = 0.0
set angular_velocity = 0.0
set steer_angle_command = 0.0
set stop = robotStop
end
else
if controlMode == 0
begin
set control_mode = 0
set linear_velocity_command = linearVelocity
set angula... | def grapebot_control_cmd_callback(self,msg):
if msg.robotStop:
self.robot_odom.control_mode = msg.control_mode
self.robot_odom.linear_velocity = 0.0
self.robot_odom.angular_velocity = 0.0
self.robot_odom.steer_angle_command = 0.0
self.robot_odom.stop =... | Python | nomic_cornstack_python_v1 |
function download_docs client output_filename=none expanded=false
begin
string Given a LuminosoClient pointing to a project and a filename to write to, retrieve all its documents in batches, and write them to a JSON lines (.jsons) file with one document per line.
if output_filename is none
begin
comment Find a default ... | def download_docs(client, output_filename=None, expanded=False):
"""
Given a LuminosoClient pointing to a project and a filename to write to,
retrieve all its documents in batches, and write them to a JSON lines
(.jsons) file with one document per line.
"""
if output_filename is None:
# ... | Python | jtatman_500k |
function add_points_strike_figures results points to_add=0 to_strike=string
begin
if 0 < to_add <= length results
begin
set points at results at to_add - 1 at 0 = results at to_add - 1 at 1
set message = string { results at to_add - 1 at 0 } for { results at to_add - 1 at 1 } added
end
else
if to_add == 0
begin
if to_s... | def add_points_strike_figures(results: list, points: dict,
to_add=0, to_strike='') -> tuple:
if 0 < to_add <= len(results):
points[results[to_add - 1][0]] = results[to_add - 1][1]
message = f'{results[to_add - 1][0]} for {results[to_add - 1][1]} added'
elif to_add... | Python | nomic_cornstack_python_v1 |
import math
function find_hypo ang1 ang2
begin
set hypo = ang1 * ang1 + ang2 * ang2
set hypo = hypo ^ 0.5
return hypo
end function
function is_rightangled list
begin
set list = sorted list
if call find_hypo list at 0 list at 1 == list at 2
begin
return true
end
else
begin
return false
end
end function
function main
beg... | import math
def find_hypo(ang1, ang2):
hypo = (ang1*ang1) + (ang2*ang2)
hypo = hypo ** 0.5
return (hypo)
def is_rightangled(list):
list = sorted(list)
if (find_hypo(list[0], list[1]) == list[2]):
return True
else:
return False
def main():
print(find_hypo(3, 4))
an... | Python | zaydzuhri_stack_edu_python |
function create
begin
with open string /root/create_db.sql string w encoding=string utf-8 as f
begin
write f string create database if not exists reactinfo charset='utf8';
end
sleep 2
call system string mysql -u%s -p%s < /root/create_db.sql % tuple mysql_account mysql_passwd
end function | def create():
with open("/root/create_db.sql", "w", encoding="utf-8") as f:
f.write("create database if not exists reactinfo charset='utf8';\n")
time.sleep(2)
os.system("mysql -u%s -p%s < /root/create_db.sql" % (mysql_account, mysql_passwd)) | Python | nomic_cornstack_python_v1 |
try
begin
print string Enter the year you want to check: -
comment by default your input function will take the value in string format)
set year = integer input
comment this will give yuo the type of the variable
print type year
print year
end
except ValueError
begin
print string please enter valid input, only numbers ... | try:
print("Enter the year you want to check: -")
year = int(input()) #by default your input function will take the value in string format)
print(type(year)) # this will give yuo the type of the variable
print(year)
except ValueError:
print('please enter valid input, only numbers are allo... | Python | zaydzuhri_stack_edu_python |
function descriptionDisplay category_name item_name
begin
set session = call DBSession
set categoryDisplay = call one
set item = call one
if string username in login_session
begin
set userUsername = login_session at string username
return call render_template string description.html loggedIn=true categoryDisplay=catego... | def descriptionDisplay(category_name, item_name):
session = DBSession()
categoryDisplay = session.query(
Categories).filter_by(name=category_name).one()
item = session.query(Items).filter_by(title=item_name).one()
if 'username' in login_session:
userUsername = login_session['username']
... | Python | nomic_cornstack_python_v1 |
comment ! /usr/bin/python3
import sys
import time
import socket
set host = argv at 1
set port = 8080
set Flag = string FLAG:YOU WIN!
set SleepTime = 15
set BUFFER_SIZE = 1024
set msg = b'Send back the word - Please\n'
while 1
begin
try
begin
comment print("Connecting to send Flag")
set s = call socket
call connect tupl... | #! /usr/bin/python3
import sys
import time
import socket
host =sys.argv[1]
port =8080
Flag="FLAG:YOU WIN!"
SleepTime=15
BUFFER_SIZE = 1024
msg = b"Send back the word - Please\n"
while 1:
try:
#print("Connecting to send Flag")
s = socket.socket()
s.connect((host,port))
s.send(m... | Python | zaydzuhri_stack_edu_python |
print string Olá, tudo bem?
set nome = input string Qual é o seu nome?
print string É um grande prazer te conhecer nome
set idade = input string Quantos anos você tem?
set peso = input string Qual é o seu peso?
print string Então nome string você já está pesando peso string com idade string anos tá na hora de tomar veg... | print('Olá, tudo bem?')
nome = input('Qual é o seu nome?')
print('É um grande prazer te conhecer', nome)
idade = input('Quantos anos você tem?')
peso = input('Qual é o seu peso?')
print('Então', nome, 'você já está pesando', peso,'com', idade,'anos tá na hora de tomar vegonha na cara né?') | Python | zaydzuhri_stack_edu_python |
string Created on 2016年4月12日 @author: Darren
import matplotlib.pyplot as plt
from random import random
from math import exp
class Feed_Forward_Neural_Network
begin
function __init__ self
begin
set data = list
set weight = list comprehension list 0 * 3 for _ in range 3
set output_weight = list 0 * 3
end function
functi... | '''
Created on 2016年4月12日
@author: Darren
'''
import matplotlib.pyplot as plt
from random import random
from math import exp
class Feed_Forward_Neural_Network():
def __init__(self):
self.data=[]
self.weight=[[0]*3 for _ in range(3)]
self.output_weight=[0]*3
def load_data(self,file... | Python | zaydzuhri_stack_edu_python |
function check_win secret_word old_letters_guessed
begin
if string _ in call show_hidden_word secret_word old_letters_guessed
begin
return false
end
return true
end function | def check_win(secret_word, old_letters_guessed):
if '_' in show_hidden_word(secret_word, old_letters_guessed):
return False
return True | Python | nomic_cornstack_python_v1 |
while i < count
begin
set numb = integer input
if numb == 1
begin
set oneTrue = true
end
set i = i + 1
end
print oneTrue | while i < count:
numb = int(input())
if numb == 1:
oneTrue = True
i += 1
print(oneTrue)
| Python | zaydzuhri_stack_edu_python |
import pandas as pd
from mlxtend.preprocessing import OnehotTransactions
from mlxtend.frequent_patterns import apriori , association_rules
set dataset = list list string A string C list string C string D string E list string A string C string D string E list string D string E list string A string B string E list string... | import pandas as pd
from mlxtend.preprocessing import OnehotTransactions
from mlxtend.frequent_patterns import apriori, association_rules
dataset = [['A', 'C'],
['C', 'D', 'E'],
['A', 'C', 'D', 'E'],
['D', 'E'],
['A', 'B', 'E'],
['A', 'B', 'C', 'D', 'E']]
def ma... | Python | zaydzuhri_stack_edu_python |
async function on_message self message
begin
if not guild and id == primary_guild
begin
return
end
if bot
begin
return
end
set data = dict string content content
await call create_event type=string message_create data=data channel=id category=if expression category then id else none user=id event_id=id
end function | async def on_message(self, message: Message):
if not (message.guild and message.guild.id == primary_guild):
return
if message.author.bot:
return
data = {
"content": message.content
}
await self.bot.db.create_event(
type="message... | Python | nomic_cornstack_python_v1 |
string : 1-31 : 1.0 : 16.py : 2021 .. , : CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru) : 23/05/2021 : 16. # Python: 3.9
import numpy as np
set N = 4
set M = 5
set L = random integer 1 3
set A = random integer low=- 9 high=10 size=tuple N M
print format string : {} A
print string L = + string L
... | """
: 1-31
: 1.0
: 16.py
: 2021 .. ,
: CC BY-NC 4.0 (https://creativecommons.org/licenses/by-nc/4.0/deed.ru)
: 23/05/2021
: 16.
# Python: 3.9
"""
import numpy as np
N = 4
M = 5
L = np.random.randint(1, 3)
A = np.random.randint(low=-9, high=10, size=(N, M))
print(":\r\n{}\n".format(A))
pri... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
string Local Outlier Factor (LOF): The anomaly score of each sample is called Local Outlier Factor. It measures the local deviation of density of a given sample with respect to its neighbors. It is local in that the anomaly sco... | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
'''Local Outlier Factor (LOF): The anomaly score of each sample is called Local Outlier Factor. It measures the local deviation of density of a given sample with respect to its neighbors. It is local in that the anomaly score ... | Python | zaydzuhri_stack_edu_python |
comment Note taking application
comment Author Evans
comment In the beginning...
comment Imports
import sqlite3
comment Start with connecting to db
set conn = call connect string Note.db
set c = call cursor
execute c string CREATE TABLE IF NOT EXISTS Notes (title, note, author)
comment Menu
function nameEntry
begin
pri... | # Note taking application
# Author Evans
# In the beginning...
# Imports
import sqlite3
# Start with connecting to db
conn = sqlite3.connect('Note.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS Notes (title, note, author)''')
# Menu
def nameEntry():
print(' Welcome to Note')
global author
... | Python | zaydzuhri_stack_edu_python |
function draw_binary img
begin
return call dstack tuple img * 255 img * 255 img * 255
end function | def draw_binary(img):
return np.dstack((img*255, img*255, img*255)) | Python | nomic_cornstack_python_v1 |
function list_local
begin
set cmd = string layman --quietness=1 --list-local --nocolor
set out = split call cmd python_shell=false string
set ret = list comprehension split line at 1 for line in out if length split line > 2
return ret
end function | def list_local():
cmd = "layman --quietness=1 --list-local --nocolor"
out = __salt__["cmd.run"](cmd, python_shell=False).split("\n")
ret = [line.split()[1] for line in out if len(line.split()) > 2]
return ret | Python | nomic_cornstack_python_v1 |
function __add_stack self span limit=none
begin
string Adds a backtrace to this span
set stack = list
set frame_count = 0
set tb = call extract_stack
reverse tb
for frame in tb
begin
if limit is not none and frame_count >= limit
begin
break
end
comment Exclude Instana frames unless we're in dev mode
if string INSTANA_... | def __add_stack(self, span, limit=None):
""" Adds a backtrace to this span """
span.stack = []
frame_count = 0
tb = traceback.extract_stack()
tb.reverse()
for frame in tb:
if limit is not None and frame_count >= limit:
break
# Exc... | Python | jtatman_500k |
function list_mc_servers self by_name=false all_data=false
begin
set tuple status data errors messages = call _make_get_request LIST
if status == 200
begin
if by_name
begin
set y = 0
set returnData = dictionary
for items in data at string servers
begin
set returnData at y = get items string id 0
set y = y + 1
set retur... | def list_mc_servers(self, by_name=False, all_data=False):
status, data, errors, messages = self._make_get_request(MCAPIRoutes.LIST)
if status == 200:
if by_name:
y = 0
returnData = dict()
for items in data['servers']:
... | Python | nomic_cornstack_python_v1 |
function status self
begin
if downloaded == 0
begin
return string n
end
else
if downloaded == - 1
begin
return string i
end
else
begin
return string
end
end function | def status(self):
if self.downloaded == 0:
return 'n'
elif self.downloaded == -1:
return 'i'
else:
return ' ' | Python | nomic_cornstack_python_v1 |
function test_models test_db
begin
execute call insert_many generator expression dictionary name=string Organisation #%d % i tuakiri_name=string Organisation #%d % i orcid_client_id=string client-%d % i orcid_secret=string secret-%d % i confirmed=i % 2 == 0 for i in range 10
execute call insert_many generator expressio... | def test_models(test_db):
Organisation.insert_many(
(
dict(
name="Organisation #%d" % i,
tuakiri_name="Organisation #%d" % i,
orcid_client_id="client-%d" % i,
orcid_secret="secret-%d" % i,
confirmed=(i % 2 == 0),
... | Python | nomic_cornstack_python_v1 |
function get_user self request
begin
set username = data at string username
set user = user
end function | def get_user(self, request):
username = request.data['username']
self.user = Account.objects.select_related('user') \
.get(Q(email=username) | Q(phone=username)).user | Python | nomic_cornstack_python_v1 |
function process self value
begin
return decimal value
end function | def process(self, value):
return float(value) | Python | nomic_cornstack_python_v1 |
comment https://www.hackerrank.com/challenges/even-tree
function find_tree_size node edge_list
begin
comment get the size of the tree from this node down
set all_children_found = false
set tree_list = list node
while not all_children_found
begin
set new_additions = 0
comment go through all the nodes in the tree list
fo... | #https://www.hackerrank.com/challenges/even-tree
def find_tree_size(node,edge_list):
#get the size of the tree from this node down
all_children_found = False
tree_list = [node]
while not all_children_found:
new_additions = 0
for i in range(len(tree_list)): #go through all the nodes in t... | Python | zaydzuhri_stack_edu_python |
function irt data val_data lr iterations
begin
comment TODO: Initialize theta and beta.
set theta = zeros 542
set beta = zeros 1774
set val_acc_lst = list
set train_loglik = list
set valid_loglik = list
for i in range iterations
begin
set neg_lld = call neg_log_likelihood data theta=theta beta=beta
set val_neg_lld =... | def irt(data, val_data, lr, iterations):
# TODO: Initialize theta and beta.
theta = np.zeros(542)
beta = np.zeros(1774)
val_acc_lst = []
train_loglik = []
valid_loglik = []
for i in range(iterations):
neg_lld = neg_log_likelihood(data, theta=theta, beta=beta)
val_neg_lld = ... | Python | nomic_cornstack_python_v1 |
function html_start_stuff title css=string style.css
begin
set start_stuff = string <!DOCTYPE html>
set start_stuff = start_stuff + string <html>
set start_stuff = start_stuff + head htags title=title css=css
set start_stuff = start_stuff + string <body>
set start_stuff = start_stuff + call heading title
return start_s... | def html_start_stuff(title, css="style.css"):
start_stuff = "<!DOCTYPE html>\n"
start_stuff += "<html>\n"
start_stuff += htags.head(title=title, css=css)
start_stuff += " <body>\n"
start_stuff += htags.heading(title)
return start_stuff | Python | nomic_cornstack_python_v1 |
function AppendStep self mol
begin
set n_steps = n_steps + 1
append coords zeros tuple n_atoms NUMDIM
append grad zeros tuple n_atoms NUMDIM
append energy e_total
for i in range n_atoms
begin
for j in range NUMDIM
begin
set coords at - 1 at i at j = coords at j
set grad at - 1 at i at j = g_total at i at j
end
end
end ... | def AppendStep(self, mol):
self.n_steps += 1
self.coords.append(numpy.zeros((self.n_atoms, const.NUMDIM)))
self.grad.append(numpy.zeros((self.n_atoms, const.NUMDIM)))
self.energy.append(mol.e_total)
for i in range(self.n_atoms):
for j in range(const.NUMDIM):
self.coords[-1][i][j] = mol... | Python | nomic_cornstack_python_v1 |
comment coding: utf-8
comment #Cufflinks
comment This library binds the power of [plotly](http://www.plot.ly) with the flexibility of [pandas](http://pandas.pydata.org/) for easy plotting.
comment This library is available on https://github.com/santosjorge/cufflinks
comment This tutorial assumes that the plotly user cr... | # coding: utf-8
# #Cufflinks
#
# This library binds the power of [plotly](http://www.plot.ly) with the flexibility of [pandas](http://pandas.pydata.org/) for easy plotting.
#
# This library is available on https://github.com/santosjorge/cufflinks
#
# This tutorial assumes that the plotly user credentials have alrea... | Python | zaydzuhri_stack_edu_python |
function to_be_less_than self expected_data
begin
if negate and actual_data < expected_data
begin
raise call ExpectationException actual_data expected_data string not_to_be_less_than
end
else
if not negate and not actual_data < expected_data
begin
raise call ExpectationException actual_data expected_data string to_be_l... | def to_be_less_than(self, expected_data):
if self.negate and self.actual_data < expected_data:
raise ExpectationException(self.actual_data, expected_data, 'not_to_be_less_than')
elif not self.negate and not self.actual_data < expected_data:
raise ExpectationException(self.actual_... | Python | nomic_cornstack_python_v1 |
for x in my_list
begin
write my_file string x + string
end
close my_file
set my_file = open string output.txt string r
print read my_file
close my_file
comment Leitura de um ficheiro linha a linha
set my_file = open string text.txt string r
print read line my_file
print read line my_file
print read line my_file
close m... | for x in my_list:
my_file.write(str(x)+'\n')
my_file.close()
my_file=open('output.txt', 'r')
print (my_file.read())
my_file.close()
# Leitura de um ficheiro linha a linha
my_file=open('text.txt', 'r')
print (my_file.readline())
print (my_file.readline())
print (my_file.readline())
my_file.close()
| Python | zaydzuhri_stack_edu_python |
function run_n_models dc_data hparams_tuple
begin
set tuple arr_n_hidden arr_n_layers arr_learning_rate arr_dropout_prob arr_n_epochs arr_batch_size arr_weight_positives = hparams_tuple
comment create empty arrays for output metrics
set n = length arr_n_hidden
set acc = zeros n
set prec = zeros n
set rec = zeros n
set ... | def run_n_models(dc_data, hparams_tuple):
(arr_n_hidden, arr_n_layers, arr_learning_rate,
arr_dropout_prob, arr_n_epochs, arr_batch_size, arr_weight_positives) = hparams_tuple
# create empty arrays for output metrics
n = len(arr_n_hidden)
acc = np.zeros(n)
prec = np.zeros(n)
rec = np.zer... | Python | nomic_cornstack_python_v1 |
comment -*-encoding=utf-8
set name = string baoqiang | #-*-encoding=utf-8
name='baoqiang'
| Python | zaydzuhri_stack_edu_python |
function vec2adjmat source target weight=none symmetric=true
begin
if length source != length target
begin
raise exception string [hnet] >Source and Target should have equal elements.
end
if weight is none
begin
set weight = list 1 * length source
end
set df = call DataFrame c_ at tuple source target columns=list strin... | def vec2adjmat(source, target, weight=None, symmetric=True):
if len(source)!=len(target): raise Exception('[hnet] >Source and Target should have equal elements.')
if weight is None: weight = [1]*len(source)
df = pd.DataFrame(np.c_[source, target], columns=['source','target'])
# Make adjacency matri... | Python | nomic_cornstack_python_v1 |
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from articulatedVehicle import ArticulatedVehicle
from probabilistic_roadmap import PRM
import numpy as np
import time
from improvedAstar import improved_astar , Node
function start_prm
begin
comment start and goal position
comment [m]
set sx = 100.0
comm... | import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from articulatedVehicle import ArticulatedVehicle
from probabilistic_roadmap import PRM
import numpy as np
import time
from improvedAstar import improved_astar, Node
def start_prm():
# start and goal position
sx = 100.0 # [m]
sy = 100.0 ... | Python | zaydzuhri_stack_edu_python |
import pdb
from base_sqlite_manager import BaseSQLiteManager
from sqlite_data_loadable import SQLiteDataLoadable
class EntailmentDBDataLoader extends BaseSQLiteManager SQLiteDataLoadable
begin
function __init__ self table_name=string entailment_ntriv
begin
call __init__ db_name=string entailment.sqlite table_name=table... | import pdb
from base_sqlite_manager import BaseSQLiteManager
from sqlite_data_loadable import SQLiteDataLoadable
class EntailmentDBDataLoader(BaseSQLiteManager, SQLiteDataLoadable):
def __init__(self, table_name='entailment_ntriv'):
super().__init__(db_name='entailment.sqlite', table_name=table_name)
... | Python | zaydzuhri_stack_edu_python |
function plot_on_rhombus R side alpha num_samp samples signal side_symbol=none plot_axes=true plot_cbar=true clim=none norm=call Normalize cmap=string jet plot_rhombus=false
begin
set side_neg = if expression side_symbol is none then string %.2f % - side / 2.0 else string - + side_symbol + string /2
set side_pos = if e... | def plot_on_rhombus(R,side,alpha,num_samp,samples,signal,side_symbol=None,plot_axes=True,plot_cbar=True,clim=None,norm=Normalize(),cmap='jet',plot_rhombus=False):
side_neg = '%.2f'%(-side/2.) if side_symbol is None else '-'+side_symbol+'/2'
side_pos = '%.2f'%(side/2.) if side_symbol is None else side_symbol+'/2'... | Python | nomic_cornstack_python_v1 |
function node self
begin
set session = call get_session
try
begin
set node = call one
commit session
end
comment FIXME 2022-03-03 BvB: the following errors are not currently
comment forwarded to the user as request response. Make that happen.
except NoResultFound
begin
warn string No node exists for organization_id { o... | def node(self) -> Node:
session = DatabaseSessionManager.get_session()
try:
node = session.query(Node)\
.join(Collaboration)\
.join(Organization)\
.join(Result)\
.join(Task)\
.filter(Result.id == self.id)\
... | Python | nomic_cornstack_python_v1 |
function estimate_mu self beta
begin
return call estimate_mu beta
end function | def estimate_mu(self, beta):
return self.tv.estimate_mu(beta) | Python | nomic_cornstack_python_v1 |
class Solution extends object
begin
function generateMatrix self n
begin
string :type n: int :rtype: List[List[int]]
comment 模拟行走的过程 注意初始化二维数组应该用列表生成式 如果用列表乘法只是复制了reference
set res = list comprehension list comprehension 0 for _ in range n for _ in range n
set tuple i j di dj = tuple 0 0 0 1
for num in range 1 n * n + ... | class Solution(object):
def generateMatrix(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
# 模拟行走的过程 注意初始化二维数组应该用列表生成式 如果用列表乘法只是复制了reference
res = [[0 for _ in range(n)] for _ in range(n)]
i, j, di, dj = 0, 0, 0, 1
for num in range(1, n * n + 1)... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Fri Feb 21 18:42:05 2020 @author: CEC
function address street city postalCode
begin
print string Your address is: street string St.,
end function
set s = input string Street:
set pC = input string Postal Code:
set c = input string City:
call address s c pC | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 21 18:42:05 2020
@author: CEC
"""
def address(street, city, postalCode):
print("Your address is:", street, "St.,")
s=input("Street: ")
pC=input("Postal Code: ")
c= input("City: ")
address(s, c, pC) | Python | zaydzuhri_stack_edu_python |
function cov x y=none rowvar=true bias=false allow_masked=true ddof=none
begin
comment Check inputs
if ddof is not none and ddof != integer ddof
begin
raise call ValueError string ddof must be an integer
end
comment Set up ddof
if ddof is none
begin
if bias
begin
set ddof = 0
end
else
begin
set ddof = 1
end
end
set tup... | def cov(x, y=None, rowvar=True, bias=False, allow_masked=True, ddof=None):
# Check inputs
if ddof is not None and ddof != int(ddof):
raise ValueError("ddof must be an integer")
# Set up ddof
if ddof is None:
if bias:
ddof = 0
else:
ddof = 1
(x, xnotma... | Python | nomic_cornstack_python_v1 |
import math
function square a b
begin
set a = square root a
set a = ceil a
set b = square root b
set b = floor b
return b - a + 1
end function
if __name__ == string __main__
begin
set q = integer input
for _ in range q
begin
set ab = split input
set a = integer ab at 0
set b = integer ab at 1
set result = call square a... | import math
def square(a, b):
a = math.sqrt(a)
a = math.ceil(a)
b = math.sqrt(b)
b = math.floor(b)
return (b-a+1)
if __name__ == "__main__":
q = int(input())
for _ in range(q):
ab = input().split()
a = int(ab[0])
b = int(ab[1])
result = square(a,b)
... | Python | zaydzuhri_stack_edu_python |
function encrypt translate
begin
comment Do uvozovek se zadava text
set text = string
comment Tento cyklus se obrati ke slovniku po kazdem stisknutim
comment tlacitek s pismeny a pak vypise zakodovany text
for letter in translate
begin
set text = text + Morse_dictionary at letter + string
end
return text
end function | def encrypt(translate):
# Do uvozovek se zadava text
text = ''
# Tento cyklus se obrati ke slovniku po kazdem stisknutim
# tlacitek s pismeny a pak vypise zakodovany text
for letter in translate:
text += Morse_dictionary[letter] + ' '
return text | Python | nomic_cornstack_python_v1 |
import numpy as np
from math import pi
import matplotlib.pyplot as plt
function u0 x
begin
return sin 4 * pi * x
end function
function con_flux u
begin
return 0.5 * u ^ 2
end function
function num_flux u v con_flux
begin
if u < v
begin
set theta = linear space u v
set flux = min call con_flux theta
end
else
begin
set t... | import numpy as np
from math import pi
import matplotlib.pyplot as plt
def u0(x):
return np.sin(4 * pi * x)
def con_flux(u):
return 0.5 * u ** 2
def num_flux(u, v, con_flux):
if u < v:
theta = np.linspace(u, v)
flux = np.min(con_flux(theta))
else:
theta = np.linspace(v, u)
... | Python | zaydzuhri_stack_edu_python |
function __exit__ self exc_type exc traceback
begin
if repo
begin
close repo
end
for tuple _ r in items __runners
begin
call __exit__ exc_type exc traceback
end
set __runners = dict
end function | def __exit__(self, exc_type, exc, traceback):
if self._config.repo:
self._config.repo.close()
for _, r in WorkflowRunner.__runners.items():
r.__exit__(exc_type, exc, traceback)
WorkflowRunner.__runners = {} | Python | nomic_cornstack_python_v1 |
from Bird import Bird
import random
comment Penguin class (child)
class Penguin extends Bird
begin
comment __init__ method for the Penguin object
function __init__ self name age
begin
comment call super().__init__() function
call __init__ name age
comment instance attributes
set name = name
set age = age
comment print ... | from Bird import Bird
import random
# Penguin class (child)
class Penguin(Bird):
# __init__ method for the Penguin object
def __init__(self, name, age):
# call super().__init__() function
super().__init__(name, age)
# instance attributes
self.name = name
self.age =... | Python | zaydzuhri_stack_edu_python |
function testBirdSchemaCreate self
begin
set startTime = time
write __lfh string Starting MyDbSqlGenTests testBirdSchemaCreate at %s % string format time time string %Y %m %d %H:%M:%S call localtime
try
begin
set msd = call BirdSchemaDef verbose=__verbose log=__lfh
set tableIdList = call getTableIdList
set myAd = call ... | def testBirdSchemaCreate(self):
startTime = time.time()
self.__lfh.write("\nStarting MyDbSqlGenTests testBirdSchemaCreate at %s\n" % time.strftime("%Y %m %d %H:%M:%S", time.localtime()))
try:
msd = BirdSchemaDef(verbose=self.__verbose, log=self.__lfh)
tableIdList = msd.ge... | Python | nomic_cornstack_python_v1 |
comment phrases =('nieko', 'nera')
function fcn phrases
begin
return join string , replace phrases string right string left
end function
set f = call fcn phrases
print f | #phrases =('nieko', 'nera')
def fcn(phrases):
return ','.join((phrases).replace('right', 'left'))
f = fcn(phrases)
print(f) | Python | zaydzuhri_stack_edu_python |
function get_concept_list
begin
call get_or_create name=string Concept A
call get_or_create name=string Concept B
call get_or_create name=string Concept C
call get_or_create name=string Concept D
return all
end function | def get_concept_list():
DummyConcept.objects.get_or_create(name='Concept A')
DummyConcept.objects.get_or_create(name='Concept B')
DummyConcept.objects.get_or_create(name='Concept C')
DummyConcept.objects.get_or_create(name='Concept D')
return DummyConcept.objects.all() | Python | nomic_cornstack_python_v1 |
function linear_trajectory_to self target_tf traj_len
begin
string Creates a trajectory of poses linearly interpolated from this tf to a target tf. Parameters ---------- target_tf : :obj:`RigidTransform` The RigidTransform to interpolate to. traj_len : int The number of RigidTransforms in the returned trajectory. Retur... | def linear_trajectory_to(self, target_tf, traj_len):
"""Creates a trajectory of poses linearly interpolated from this tf to a target tf.
Parameters
----------
target_tf : :obj:`RigidTransform`
The RigidTransform to interpolate to.
traj_len : int
The numbe... | Python | jtatman_500k |
function is_discordant term1 term2
begin
comment if (term1 not in CLINSIGS) or (term2 not in CLINSIGS):
comment raise Exception("bad clincical description input")
if string PATHO in upper term1 + upper term2
begin
if string PATHO in upper term1 and string PATHO in upper term2
begin
return false
end
else
begin
return tr... | def is_discordant(term1, term2):
# if (term1 not in CLINSIGS) or (term2 not in CLINSIGS):
# raise Exception("bad clincical description input")
if "PATHO" in (term1.upper() + term2.upper()):
if ("PATHO" in term1.upper()) and ("PATHO" in term2.upper()):
return False
else:
... | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Created on Thu Mar 15 14:41:40 2018 Assignment1
comment Data Loading
import pandas as pd
set data = read csv string C:\Users\김성제\Google Drive\공부\4학년 1학기\Business Analytics\Data set\Week2\\kc_house_data.csv
comment for scatter matrix
from pandas.plotting import scatter_matrix as sm
c... | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 15 14:41:40 2018
Assignment1
"""
# Data Loading
import pandas as pd
data = pd.read_csv(r"C:\Users\김성제\Google Drive\공부\4학년 1학기\Business Analytics\Data set\Week2\\kc_house_data.csv")
# for scatter matrix
from pandas.plotting import scatter_matrix as sm
sm... | Python | zaydzuhri_stack_edu_python |
function call self state num_quantiles
begin
set batch_size = call as_list at 0
set x = call net state
set state_vector_length = call as_list at - 1
set state_net_tiled = call tile x list num_quantiles 1
set quantiles_shape = list num_quantiles * batch_size 1
set quantiles = uniform quantiles_shape minval=0 maxval=1 dt... | def call(self, state, num_quantiles):
batch_size = state.get_shape().as_list()[0]
x = self.net(state)
state_vector_length = x.get_shape().as_list()[-1]
state_net_tiled = tf.tile(x, [num_quantiles, 1])
quantiles_shape = [num_quantiles * batch_size, 1]
quantiles = tf.random.uniform(
quan... | Python | nomic_cornstack_python_v1 |
from sys import stdin
set initialLocs = list
set grid = dictionary
set letter = string A
set min_x = - 1
set min_y = - 1
set max_x = - 1
set max_y = - 1
for line in stdin
begin
set coord = split line at slice : - 1 : string ,
set tuple x y = tuple integer coord at 0 integer coord at 1
append initialLocs tuple x y let... | from sys import stdin
initialLocs = list()
grid = dict()
letter = 'A'
min_x = min_y = max_x = max_y = -1
for line in stdin:
coord = line[:-1].split(', ')
x, y = int(coord[0]), int(coord[1])
initialLocs.append((x, y, letter))
grid[(x, y)] = letter
letter = chr(ord(letter) + 1) #incr letter
# Assign bounds
max_x... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3.6
import cv2
import copy as cp
import numpy as np
set input = call imread string ./input/p0-1-0.png
comment I know that the function cvtColor exists, however as we are new to OpenCV we prefered to learn the hand coded way.
function swapRedBlue img
begin
set aux = img at tuple slice : : slic... | #!/usr/bin/python3.6
import cv2
import copy as cp
import numpy as np
input = cv2.imread('./input/p0-1-0.png')
# I know that the function cvtColor exists, however as we are new to OpenCV we prefered to learn the hand coded way.
def swapRedBlue(img):
aux = img[:,:,0]
img[:,:,0] = img[:,:,2]
img[:,:,2] = a... | Python | zaydzuhri_stack_edu_python |
import datetime as dt
import math
class Validation
begin
decorator staticmethod
function is_valid_date date
begin
return is instance date datetime
end function
decorator staticmethod
function is_valid_turnaround_hours t_hours
begin
if is instance t_hours str or t_hours < 0 or call isnan t_hours
begin
return false
end
r... | import datetime as dt
import math
class Validation():
@staticmethod
def is_valid_date(date):
return isinstance(date, dt.datetime)
@staticmethod
def is_valid_turnaround_hours(t_hours):
if isinstance(t_hours, str) or t_hours < 0 or math.isnan(t_hours):
return False
r... | Python | zaydzuhri_stack_edu_python |
function tutorial_categories_from_rp_sitemap sitemap_url wrong_endpoints
begin
set soup = call BeautifulSoup text string lxml
set slugs_to_read = list
for loc in select soup string url > loc
begin
if any list comprehension string https://realpython.com/ { endpoint } in text for endpoint in wrong_endpoints
begin
contin... | def tutorial_categories_from_rp_sitemap(sitemap_url, wrong_endpoints):
soup = BeautifulSoup(requests.get(sitemap_url).text, "lxml")
slugs_to_read = []
for loc in soup.select("url > loc"):
if any([f"https://realpython.com/{endpoint}" in loc.text for endpoint in wrong_endpoints]):
continu... | Python | nomic_cornstack_python_v1 |
function _eval_question self question
begin
comment TODO contrived; needs tokenization, grammatical parse
for i in range 0 length all_properties - 1
begin
if find question all_properties at i >= 0
begin
if i in solutions at _solution
begin
return true
end
end
end
return false
end function | def _eval_question(self, question):
# TODO contrived; needs tokenization, grammatical parse
for i in range(0, len(db.all_properties)-1):
if question.find(db.all_properties[i]) >= 0:
if i in db.solutions[self._solution]: return True
return False | Python | nomic_cornstack_python_v1 |
function num_digits n
begin
set out = 0
while n
begin
set out = out + 1
set n = n // 10
end
return out - 1
end function | def num_digits(n):
out = 0
while n:
out += 1
n //= 10
return out - 1 | Python | nomic_cornstack_python_v1 |
function contexts self triple=none
begin
set uri = rest_services at string contexts
if not triple
begin
set r = get requests uri stream=true headers=dict string Accept string application/sparql-results+json ; string connection string keep-alive ; string Accept-Encoding string gzip,deflate
set decode_content = true
retu... | def contexts(self, triple=None):
uri = self.rest_services["contexts"]
if not triple:
r = requests.get(uri, stream=True,headers = {"Accept" : "application/sparql-results+json",
'connection': 'keep-alive',
... | Python | nomic_cornstack_python_v1 |
import datetime
function date_from_str s
begin
string >>> date_from_str('Sat Jun 06 12:09:03 +0000 2020') datetime.datetime(2020, 6, 6, 12, 9, 3, tzinfo=datetime.timezone.utc)
return string parse time s string %a %b %d %H:%M:%S %z %Y
end function | import datetime
def date_from_str(s: str) -> datetime.datetime:
"""
>>> date_from_str('Sat Jun 06 12:09:03 +0000 2020')
datetime.datetime(2020, 6, 6, 12, 9, 3, tzinfo=datetime.timezone.utc)
"""
return datetime.datetime.strptime(s, "%a %b %d %H:%M:%S %z %Y")
| Python | zaydzuhri_stack_edu_python |
for z in range k
begin
set inp = split input
set type = inp at 0
set num = integer inp at 1 - 1
if type == string R
begin
if num in r
begin
set r at num = r at num + 1
end
else
begin
set r at num = 1
end
if r at num % 2 != 0
begin
set r_on = r_on + 1
end
else
begin
set r_on = r_on - 1
end
end
else
begin
if num in c
beg... | for z in range(k):
inp = input().split()
type = inp[0]
num = int(inp[1]) - 1
if type == "R":
if num in r:
r[num] += 1
else:
r[num] = 1
if r[num] % 2 != 0:
r_on += 1
else:
r_on -= 1
else:
if num in c:
... | Python | zaydzuhri_stack_edu_python |
function default_props reset=false **kwargs
begin
string Return current default properties Parameters ---------- reset : bool if True, reset properties and return default: False
global _DEFAULT_PROPS
if _DEFAULT_PROPS is none or reset
begin
call reset_default_props keyword kwargs
end
return _DEFAULT_PROPS
end function | def default_props(reset=False, **kwargs):
"""Return current default properties
Parameters
----------
reset : bool
if True, reset properties and return
default: False
"""
global _DEFAULT_PROPS
if _DEFAULT_PROPS is None or reset:
reset_default_props(**kwargs)
... | Python | jtatman_500k |
function write_random_bits original n
begin
set o = open original string w
for _ in range n
begin
set r = uniform 0 1
comment create groups of zeroes and ones
for _ in range random integer 1 5
begin
if expression r < PROB then write o string 0 else write o string 1
end
end
close o
end function | def write_random_bits(original, n):
o = open(original, 'w')
for _ in range(n):
r = random.uniform(0, 1)
# create groups of zeroes and ones
for _ in range(random.randint(1,5)):
o.write('0') if r < PROB else o.write('1')
o.close() | Python | nomic_cornstack_python_v1 |
import math
set limit = decimal input string Enter the speed limit:
set speed = decimal input string Enter the recorded speed of the car:
set fine = 0
set overspeedlimit = speed - limit
if 0 < overspeedlimit <= 20
begin
set fine = 100
end
if 20 < overspeedlimit <= 30
begin
set fine = 270
end
if overspeedlimit > 30
begi... | import math
limit = float(input("Enter the speed limit: "))
speed = float(input("Enter the recorded speed of the car: "))
fine = 0
overspeedlimit = speed - limit
if 0 < overspeedlimit <= 20:
fine = 100
if 20 < overspeedlimit <= 30:
fine = 270
if overspeedlimit > 30:
fine = 500
if speed > limit:
print("You are... | Python | zaydzuhri_stack_edu_python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.