code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import Skype4Py
import time
import sys
import random
import requests
class SkypeBot extends object
begin
function __init__ self
begin
set skype = call Skype Events=self
set name = string Skype Bot
call Attach
end function
end class | import Skype4Py
import time
import sys
import random
import requests
class SkypeBot(object):
def __init__(self):
self.skype = Skype4Py.Skype(Events=self)
self.skype.name = "Skype Bot"
self.skype.Attach()
| Python | zaydzuhri_stack_edu_python |
function __check_access self
begin
debug string checking access-rights
for i in list savedir listdir blacklistdir scoresdir logdir confdir
begin
if not call access i R_OK ? W_OK
begin
debug string no r/w-access to all savedir-directories!
end
end
end function | def __check_access(self):
log.debug("checking access-rights")
for i in [self.savedir, self.listdir, self.blacklistdir, self.scoresdir, self.logdir, self.confdir]:
if not os.access(i, os.R_OK | os.W_OK):
log.debug("no r/w-access to all savedir-directories!") | Python | nomic_cornstack_python_v1 |
function dot v w
begin
assert length v == length w msg string vectors must be same length
return sum generator expression v_i * w_i for tuple v_i w_i in zip v w
end function | def dot(v: Vector, w: Vector) -> float:
assert len(v) == len(w), "vectors must be same length"
return sum(v_i * w_i for v_i, w_i in zip(v, w)) | Python | nomic_cornstack_python_v1 |
function test_discretize_negatives self
begin
set expected_result = list 1 1 0 0
set result = call discretize list - 0.1 - 0.2 - 0.3 - 0.4
assert equal expected_result result
end function | def test_discretize_negatives(self):
expected_result=[1, 1, 0, 0]
result=stats.discretize([-0.1, -0.2, -0.3, -0.4])
self.assertEqual(expected_result,result) | Python | nomic_cornstack_python_v1 |
import tensorflow as tf
set a = call constant 100 name=string a
set b = call constant 200 name=string b
set c = call constant 300 name=string c
set v = call Variable 0 name=string v
set calc_op = a + b * c
set assign_op = call assign v calc_op
set sess = call Session
set tw = call FileWriter string log_dir graph=graph
... | import tensorflow as tf
a= tf.constant(100, name="a")
b= tf.constant(200, name="b")
c= tf.constant(300, name="c")
v= tf.Variable(0, name="v")
calc_op = a+b*c
assign_op = tf.assign(v, calc_op)
sess = tf.Session()
tw = tf.summary.FileWriter("log_dir", graph=sess.graph)
sess.run(assign_op)
print(sess.run(v)) | Python | zaydzuhri_stack_edu_python |
if b <= a + 1
begin
print res + k
end
else
if k < a - 1 + 2
begin
print res + k
end
else
begin
set res = res + b - 1
set k = k - a + 1
print res + k // 2 * b - a + k % 2
end | if b <= a + 1:
print(res + k)
else:
if k < a - 1 + 2:
print(res + k)
else:
res += b - 1
k -= a + 1
print(res + k//2 * (b - a) + k % 2) | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment encoding: utf-8
string @version: 1.0 @author: panfeng @license: Apache Licence @file: 总结.py @time: 2018/12/19 14:56
string 1、什么是面向对象编程? 以前使用函数 类 + 对象 2、什么是类,什么是对象,又有什么关系 class 类 def 函数1(): pass def 函数2(): pass # obj是对象,实例化的过程 obj = 类() obj.函数1() 3、什么时候适合用面向对象 1、根据一个模版来创建某些东西,例如批量生成人... | #!/usr/bin/env python
# encoding: utf-8
"""
@version: 1.0
@author: panfeng
@license: Apache Licence
@file: 总结.py
@time: 2018/12/19 14:56
"""
"""
1、什么是面向对象编程?
以前使用函数
类 + 对象
2、什么是类,什么是对象,又有什么关系
class 类
def 函数1():
pass
def 函数2():
pass
# obj是对象,实例化的过程
obj = 类()
... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
comment @Time : 2019/12/19 16:26
comment @Author : Tom Chen
comment @Email : chenbaocun@emails.bjut.edu.cn
comment @File : r_&c_.py
comment @Software: PyCharm
import numpy as np
set a = array list 1 2 3 4
set b = array list 5 6 7 8
comment print(np.concatenate((a,b),axis=0))
comment print(... | # -*- coding: utf-8 -*-
# @Time : 2019/12/19 16:26
# @Author : Tom Chen
# @Email : chenbaocun@emails.bjut.edu.cn
# @File : r_&c_.py
# @Software: PyCharm
import numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
# print(np.concatenate((a,b),axis=0))
# print(np.r_[np.arange(0, 5, 1), a, b])
# ... | Python | zaydzuhri_stack_edu_python |
function test_bytes_to_pretty_hexinvalid_data
begin
try
begin
call _bytes_to_pretty_hex data=list 1 2 3 4 string 500
end
except Exception
begin
comment The exception that bubbles up from IntelHex is implementation detail
comment from that library, so it could be anything
assert true msg string Exception raised
end
try ... | def test_bytes_to_pretty_hexinvalid_data():
try:
cmds._bytes_to_pretty_hex(data=[1, 2, 3, 4, "500"])
except Exception:
# The exception that bubbles up from IntelHex is implementation detail
# from that library, so it could be anything
assert True, "Exception raised"
else:
... | Python | nomic_cornstack_python_v1 |
function parent
begin
function input_number number
begin
set number = integer input string Please, insert the number:
return number
end function
function correct_number number
begin
set a = integer input string Please, insert the lower border:
set b = integer input string Please, insert the upper border:
if not a < b
b... | def parent():
def input_number(number):
number = int(input("Please, insert the number: "))
return(number)
def correct_number(number):
a = int(input("Please, insert the lower border: "))
b = int(input("Please, insert the upper border: "))
if not a < b:
raise ... | Python | zaydzuhri_stack_edu_python |
function test_use_case_disconnect create
begin
set uc1 = call create UseCaseItem UseCase
set uc2 = call create UseCaseItem UseCase
set extend = call create ExtendItem
call connect extend head uc1
call connect extend tail uc2
call disconnect extend head
assert call get_connected extend head is none
assert subject is non... | def test_use_case_disconnect(create):
uc1 = create(UseCaseItem, UML.UseCase)
uc2 = create(UseCaseItem, UML.UseCase)
extend = create(ExtendItem)
connect(extend, extend.head, uc1)
connect(extend, extend.tail, uc2)
disconnect(extend, extend.head)
assert get_connected(extend, extend.head) is N... | Python | nomic_cornstack_python_v1 |
function _separate_masks mask threshold=0.025
begin
string Returns a list of segmentation masks each of the same dimension as the input one, but where they each have exactly one segment in them and all other samples in them are zeroed. Only bothers to return segments that are larger in total area than `threshold * mask... | def _separate_masks(mask, threshold=0.025):
"""
Returns a list of segmentation masks each of the same dimension as the input one,
but where they each have exactly one segment in them and all other samples in them
are zeroed.
Only bothers to return segments that are larger in total area than `thresh... | Python | jtatman_500k |
function get self provider_id
begin
return call _invoke string get dict string provider_id provider_id
end function | def get(self,
provider_id,
):
return self._invoke('get',
{
'provider_id': provider_id,
}) | Python | nomic_cornstack_python_v1 |
function countGoodTriplets arr a b c
begin
set N = length arr
set count = 0
for i in range N
begin
for j in range i + 1 N
begin
for k in range j + 1 N
begin
if absolute arr at i - arr at j <= a and absolute arr at j - arr at k <= b and absolute arr at i - arr at k <= c
begin
set count = count + 1
end
end
end
end
return... | def countGoodTriplets(arr, a, b, c):
N = len(arr)
count = 0
for i in range(N):
for j in range(i + 1, N):
for k in range(j + 1, N):
if abs(arr[i] - arr[j]) <= a and abs(arr[j] - arr[k]) <= b and abs(arr[i] - arr[k]) <= c:
count += 1
return count
p... | Python | zaydzuhri_stack_edu_python |
function predict self
begin
return
end function | def predict(self):
return | Python | nomic_cornstack_python_v1 |
import re
class Solution
begin
function checkRecord_MK1 self s
begin
set tuple absent contin_late = tuple 0 0
for ch in s
begin
if ch == string L
begin
set contin_late = contin_late + 1
end
else
begin
set contin_late = 0
if ch == string A
begin
set absent = absent + 1
end
end
if absent > 1 or contin_late > 2
begin
retu... | import re
class Solution:
def checkRecord_MK1(self, s: str) -> bool:
absent, contin_late = 0, 0
for ch in s:
if ch == 'L':
contin_late += 1
else:
contin_late = 0
if ch == 'A':
absent += 1
if abs... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Tue Sept 17 09:48:52 2019 @author: ronald kongi
import os
import math
import matplotlib.pyplot as plt
class Point
begin
string Point Class with three proprieties
function __init__ self x y num
begin
comment x coordinate
set long = x
comment y coordinate
set lat = y
commen... | # -*- coding: utf-8 -*-
"""
Created on Tue Sept 17 09:48:52 2019
@author: ronald kongi
"""
import os
import math
import matplotlib.pyplot as plt
class Point():
'''Point Class with three proprieties'''
def __init__(self, x, y, num):
self.long = x # x coordinate
self.lat = y # y ... | Python | zaydzuhri_stack_edu_python |
function preprocess
begin
comment coinbase = './coinbaseUSD_1-min_data_2014-12-01_to_2019-01-09.csv'
set bitstamp = string ./bitstampUSD_1-min_data_2012-01-01_to_2020-04-22.csv
comment df = pd.read_csv(coinbase)
set df = read csv bitstamp
set df at string Timestamp = call to_datetime df at string Timestamp unit=string ... | def preprocess():
# coinbase = './coinbaseUSD_1-min_data_2014-12-01_to_2019-01-09.csv'
bitstamp = './bitstampUSD_1-min_data_2012-01-01_to_2020-04-22.csv'
# df = pd.read_csv(coinbase)
df = pd.read_csv(bitstamp)
df['Timestamp'] = pd.to_datetime(df['Timestamp'], unit='s')
df = df[df['Timestamp']... | Python | nomic_cornstack_python_v1 |
import random
import socket
import time
from _thread import *
import threading
from datetime import datetime
import json
import urllib
import urllib.parse
import urllib.request
import random
set playerInQueue = list
function connectionLoop sock
begin
while true
begin
set tuple data addr = call recvfrom 1024
set res = ... | import random
import socket
import time
from _thread import *
import threading
from datetime import datetime
import json
import urllib
import urllib.parse
import urllib.request
import random
playerInQueue=[]
def connectionLoop(sock):
while True:
data, addr = sock.recvfrom(1024)
res=j... | Python | zaydzuhri_stack_edu_python |
string Test Dashboard (Route Manager) Basic operations accessible to the user Tested using the frontend functions
from django.test import TestCase
from route_manager.forms import PostForm
class RouteManagerTest extends TestCase
begin
string Test elements of the route manager
set correct_ip = string 192.168.1.1/30
set c... | """
Test Dashboard (Route Manager)
Basic operations accessible to the user
Tested using the frontend functions
"""
from django.test import TestCase
from route_manager.forms import PostForm
class RouteManagerTest(TestCase):
"""
Test elements of the route manager
"""
correct_ip = '192.168.1.1/30'
... | Python | zaydzuhri_stack_edu_python |
import array as arr
set a = array string I list 3 4 6
print type a
print a | import array as arr
a = arr.array("I",[3,4,6])
print(type(a))
print(a)
| Python | zaydzuhri_stack_edu_python |
function rollback self
begin
if changed
begin
rollback device
end
set changed = false
end function | def rollback(self):
if self.changed:
self.device.rollback()
self.changed = False | Python | nomic_cornstack_python_v1 |
function qryptbufferjson lon lat ptradius
begin
set query = string select ST_AsGeoJSON(ST_Transform(ST_Buffer(ST_Transform(
set query = query + string ST_SetSRID(ST_Point(%s, %s),4326), 32119), %s)
set query = query + string , 4326))
debug lon
debug lat
set buffmeters = 1000 * decimal ptradius
comment logger.debug(quer... | def qryptbufferjson(lon, lat, ptradius):
query = "select ST_AsGeoJSON(ST_Transform(ST_Buffer(ST_Transform("
query += "ST_SetSRID(ST_Point(%s, %s),4326), 32119), %s)"
query += ", 4326))"
logger.debug(lon)
logger.debug(lat)
buffmeters = 1000 * float(ptradius)
# logger.debug(query % (lon, lat,... | Python | nomic_cornstack_python_v1 |
import asyncio
import websockets
async function handler websocket path
begin
set message = await call recv
print string Received { message }
await call send message
end function
set start_server = call serve handler string localhost 8765
call run_until_complete start_server
call run_forever | import asyncio
import websockets
async def handler(websocket, path):
message = await websocket.recv()
print(f"Received {message}")
await websocket.send(message)
start_server = websockets.serve(handler, 'localhost', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().r... | Python | flytech_python_25k |
function get_scene self scenename
begin
return get scenes scenename
end function | def get_scene(self, scenename):
return self.scenes.get(scenename) | Python | nomic_cornstack_python_v1 |
import os
from telegram import Bot
class Telegram
begin
function __init__ self token=none chat_id=none
begin
if not token
begin
set token = get environ string TELEGRAM_TOKEN
end
if not chat_id
begin
set chat_id = get environ string TELEGRAM_CHAT_ID
end
set chat_id = chat_id
set bot = call Bot token
end function
functio... | import os
from telegram import Bot
class Telegram:
def __init__(self, token: str = None, chat_id: str = None):
if not token:
token = os.environ.get("TELEGRAM_TOKEN")
if not chat_id:
chat_id = os.environ.get("TELEGRAM_CHAT_ID")
self.chat_id = chat_id
self.bo... | Python | zaydzuhri_stack_edu_python |
comment -------------------------------------------------------------------------------
comment Name: problem243
comment Purpose:
comment Author: Adrian
comment Created: 05/03/2013
comment Copyright: (c) Adrian 2013
comment Licence: <your licence>
comment ----------------------------------------------------------------... | #-------------------------------------------------------------------------------
# Name: problem243
# Purpose:
#
# Author: Adrian
#
# Created: 05/03/2013
# Copyright: (c) Adrian 2013
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/b... | Python | zaydzuhri_stack_edu_python |
function close self
begin
call disconnect
end function | def close(self):
self.device.disconnect() | Python | nomic_cornstack_python_v1 |
function test_attempt_bc_correction_no_barcode self
begin
set curr_bc = string
set all_bcs = list string
set barcode_type = 0
set tuple actual_bc actual_errs = call attempt_bc_correction curr_bc all_bcs barcode_type
set expected_bc = string
set expected_errs = 0
assert equal actual_bc expected_bc
assert equal actual... | def test_attempt_bc_correction_no_barcode(self):
curr_bc = ""
all_bcs = [""]
barcode_type = 0
actual_bc, actual_errs = attempt_bc_correction(curr_bc,
all_bcs, barcode_type)
expected_bc = ""
expected_errs = ... | Python | nomic_cornstack_python_v1 |
function config
begin
yield call read_yaml_file TEST_DATA
end function | def config():
yield read_yaml_file(TEST_DATA) | Python | nomic_cornstack_python_v1 |
from human import *
function main
begin
set a = call Human
set b = call Female string El
set c = a
set sex = MALE
set sex = MALE
print a
print b
print c
if a == c
begin
print string a and c are same person
end
else
begin
print string a and c are different person
end
end function
if __name__ == string __main__
begin
cal... | from human import *
def main():
a = Human()
b = Female('El')
c = a
c.sex = Sex.MALE
b.sex = Sex.MALE
print(a)
print(b)
print(c)
if a == c:
print('a and c are same person')
else:
print('a and c are different person')
if __name__ == '__main__':
main()
| Python | zaydzuhri_stack_edu_python |
function dump_error self msg **kwargs
begin
set dump_folder = get attribute self string dump_folder string .
if not exists path dump_folder
begin
comment pragma: no cover
make directories dump_folder
end
set pattern = join path dump_folder format string BENCH-ERROR-{0}-%d.pkl __name__
set err = 0
set name = pattern % e... | def dump_error(self, msg, **kwargs):
dump_folder = getattr(self, "dump_folder", '.')
if not os.path.exists(dump_folder):
os.makedirs(dump_folder) # pragma: no cover
pattern = os.path.join(
dump_folder, "BENCH-ERROR-{0}-%d.pkl".format(
self.__class__.__nam... | Python | nomic_cornstack_python_v1 |
function decorator function
begin
function test numbers
begin
set n = call function numbers
if n == 0
begin
print string Нет
end
if n > 10
begin
print string Очень много
end
return
end function
return test
end function
decorator decorator
function even numbers
begin
set n = 0
for i in range length numbers
begin
if numb... | def decorator(function):
def test(numbers):
n = function(numbers)
if n == 0:
print('Нет')
if n > 10:
print('Очень много')
return
return test
@decorator
def even(numbers):
n = 0
for i in range(len(numbers)):
if numbers[i] % 2 == 0:
... | Python | zaydzuhri_stack_edu_python |
from collections import defalutdict , deque
set tuple n m = list map int split strip input
if n - m > 1
begin
print - 1 - 1
end
else
begin
set indegrees = list 0 * n + 1
set graph_set = set
for _ in range m
begin
set tuple in_ out_ = list map int split input
set indegrees at out_ = indegrees at out_ + 1
add graph_set i... | from collections import defalutdict, deque
n, m = list(map(int, input().strip().split()))
if n - m > 1: print(-1, -1)
else:
indegrees = [0] * (n+1)
graph_set = set()
for _ in range(m):
in_, out_ = list(map(int, input().split()))
indegrees[out_] += 1
graph_set.add(in_)
... | Python | zaydzuhri_stack_edu_python |
import traceback
from flask_restful import Resource , reqparse
from flask_jwt import jwt_required
from models.squad import SquadModel
from models.player import PlayerModel
from utils.firebase import FireBase
class Squad extends Resource
begin
comment tid,cid,pid,number
set parser = call RequestParser
call add_argument ... | import traceback
from flask_restful import Resource,reqparse
from flask_jwt import jwt_required
from models.squad import SquadModel
from models.player import PlayerModel
from utils.firebase import FireBase
class Squad(Resource):
# tid,cid,pid,number
parser = reqparse.RequestParser()
parser.add_argument('t... | Python | zaydzuhri_stack_edu_python |
comment DFS explicit stack implementation is faster to implement and much performant
comment overall runtime is O(m+n)
comment recursive implementation is
comment easiest to implement but slower
comment it uses callstack which has a limit of 1000 frames in python
class Node
begin
function __init__ self value left=none ... | # DFS explicit stack implementation is faster to implement and much performant
# overall runtime is O(m+n)
# recursive implementation is
# easiest to implement but slower
# it uses callstack which has a limit of 1000 frames in python
class Node:
def __init__(self, value, left=None, right=None):
self.value = val... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python3
comment coding=utf-8
comment 12306抢票软件
comment 实际上就是个爬虫,
import requests , base64 , json
comment import matplot
from PIL import Image
function loginByQrCode session data
begin
string @description: 通过扫描二维码登陆12306 @param {type} @return: True:登陆成功,False:登陆失败
set qrcodeUrl = data at string qrc... | #!/usr/bin/env python3
#coding=utf-8
# 12306抢票软件
# 实际上就是个爬虫,
import requests,base64,json
# import matplot
from PIL import Image
def loginByQrCode(session,data):
'''
@description: 通过扫描二维码登陆12306
@param {type}
@return: True:登陆成功,False:登陆失败
'''
qrcodeUrl = data["qrcode"]["Url"]
headers ... | Python | zaydzuhri_stack_edu_python |
string Module used to access information
import re
import os
from urllib.error import HTTPError
from bs4 import BeautifulSoup
import requests
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from joblib import dump , load
import db
comment functi... | """ Module used to access information"""
import re
import os
from urllib.error import HTTPError
from bs4 import BeautifulSoup
import requests
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from joblib import dump, load
import db
# function to... | Python | zaydzuhri_stack_edu_python |
comment Devido à existência de capcha no fluxo de cadastro de usuários. Será necessário fazer o cadastro
comment manualmente antes da execução deste teste. Altere o usuário e senha (linhas 19 e 22) pelo usuário
comment e senha que você criou manualmente para poder executar este script com sucesso
from selenium import w... | #Devido à existência de capcha no fluxo de cadastro de usuários. Será necessário fazer o cadastro
#manualmente antes da execução deste teste. Altere o usuário e senha (linhas 19 e 22) pelo usuário
#e senha que você criou manualmente para poder executar este script com sucesso
from selenium import webdriver
from selen... | Python | zaydzuhri_stack_edu_python |
function module_get_ self
begin
for p in parameters self
begin
call get_
end
end function | def module_get_(self):
for p in self.parameters():
p.get_() | Python | nomic_cornstack_python_v1 |
async function remove_role self ctx message reaction
begin
if is instance reaction str
begin
set reaction = call emojize reaction
end
await call remove_role_reaction id reaction
set message_reaction : Optional at Reaction = get utils reactions emoji=string reaction
if message_reaction
begin
await clear message_reaction... | async def remove_role(self, ctx: "IceTeaContext", message: discord.Message, *,
reaction: typing.Union[discord.Emoji, str]):
if isinstance(reaction, str):
reaction = emoji.emojize(reaction)
await ctx.guild_data.remove_role_reaction(message.id, reaction)
messa... | Python | nomic_cornstack_python_v1 |
from http.server import BaseHTTPRequestHandler , HTTPServer
import requests
from _datetime import datetime
import cv2
import numpy as np
import os.path
from datetime import datetime
import time
import sys
function log message
begin
print string today + string + string message
end function
comment API documentation:
co... | from http.server import BaseHTTPRequestHandler, HTTPServer
import requests
from _datetime import datetime
import cv2
import numpy as np
import os.path
from datetime import datetime
import time
import sys
def log(message):
print(str(datetime.today()) + ' ' + str(message))
# API documentation:
#
# Server receives ... | Python | zaydzuhri_stack_edu_python |
function _generate_id self
begin
set highest = 0
for b in bookmarks
begin
set highest = max highest integer b at string id at slice 2 : :
end
set highest = highest + 1
return string bk { highest }
end function | def _generate_id(self):
highest = 0
for b in self.bookmarks:
highest = max(highest, int(b['id'][2:]))
highest += 1
return f'bk{highest:05d}' | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python
function is_sorted l
begin
if l == sorted l
begin
return true
end
return false
end function
function solve n
begin
set l = list string n
set last = integer l at 0
set index = 0
set s = string n
set t = string
for i in range 1 length l
begin
set current = integer l at i
if current < last
begin
... | #!/usr/bin/python
def is_sorted(l):
if(l==sorted(l)):
return True
return False
def solve(n):
l = list(str(n))
last = int(l[0])
index = 0
s = str(n)
t = ""
for i in range(1,len(l)):
current = int(l[i])
if(current<last):
t = s[i:]
break
last = current
if(t==""):
return n
else:
if(is_s... | Python | zaydzuhri_stack_edu_python |
function __init__ self
begin
set this_dir = directory name path absolute path path __file__
set db_path = call _discover_in_dir this_dir
end function | def __init__(self):
self.this_dir = os.path.dirname(os.path.abspath(__file__))
self.db_path = self._discover_in_dir(self.this_dir) | Python | nomic_cornstack_python_v1 |
string Group-wise distance learner Author: Yi Zhang <beingzy@gmail.com> Date: 2016/MM/DD
import numpy as np
from numpy.random import choice
from pandas import DataFrame
from math import floor
from datetime import datetime
from copy import deepcopy
from groupwise_distance_learning.util_functions import user_grouped_dist... | """ Group-wise distance learner
Author: Yi Zhang <beingzy@gmail.com>
Date: 2016/MM/DD
"""
import numpy as np
from numpy.random import choice
from pandas import DataFrame
from math import floor
from datetime import datetime
from copy import deepcopy
from groupwise_distance_learning.util_functions import user_grouped_di... | Python | zaydzuhri_stack_edu_python |
function refresh self section_path_str
begin
info string Refreshing config for { section_path_str }
call refresh section_path_str
debug string Finished refreshing config for { section_path_str }
end function | def refresh(self, section_path_str: str):
logger.info(f'Refreshing config for {section_path_str}')
self.runner.refresh(section_path_str)
logger.debug(f'Finished refreshing config for {section_path_str}') | Python | nomic_cornstack_python_v1 |
function adicionar self
begin
call addWidget foto_label
call addWidget label
end function | def adicionar(self):
self.vbox.addWidget(self.foto_label)
self.vbox.addWidget(self.label) | Python | nomic_cornstack_python_v1 |
function level self percent_duty set_default=false
begin
if not is instance percent_duty list
begin
set percent_duty = list comprehension percent_duty for i in range length CanIDs
end
if set_default == true
begin
set Default_Duty = percent_duty
set controller at string default = percent_duty
end
try
begin
return call c... | def level(self, percent_duty, set_default = False):
if not isinstance(percent_duty, list):
percent_duty = [percent_duty for i in range(len(self.CanIDs))]
if set_default == True:
self.Default_Duty = percent_duty
self.controller['default'] = percent_duty
try:
... | Python | nomic_cornstack_python_v1 |
import requests
import json
set OWNER = string glass-bead-labs
set REPO = string sensor-group
set parameters = dict string state string all ; string per_page 100
set request = json get requests string https://api.github.com/repos/ + OWNER + string / + REPO + string /issues params=parameters
comment request is a list fi... | import requests
import json
OWNER = 'glass-bead-labs'
REPO = 'sensor-group'
parameters = {'state': 'all', 'per_page': 100}
request = requests.get('https://api.github.com/repos/' + OWNER + '/' + REPO + '/issues', params=parameters).json()
# request is a list filled with dictionaries that represent each issue
# liste... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
import requests
set url = string http://acadmin/findMyBCD.php
set BSNs = list string 8FA000001F4B3 string 846000123E71F string 84600013415B
set payload = dict string bsn string 8FA000001FBA3
set success_str = string is connected
set failure_str = string could not find
for BSN in BSNs
begin
comm... | #!/usr/bin/python
import requests
url = 'http://acadmin/findMyBCD.php'
BSNs = ['8FA000001F4B3', '846000123E71F', '84600013415B']
payload = {'bsn': '8FA000001FBA3'}
success_str = "is connected"
failure_str = "could not find"
for BSN in BSNs:
# POST with form-encoded data
r = requests.post(url, data={'bsn':BSN} )
... | Python | zaydzuhri_stack_edu_python |
function addListaCategorias catalog categoria
begin
set cat = call newCategoria categoria at string name categoria at string id
call addLast catalog at string categorias cat
end function | def addListaCategorias(catalog, categoria):
cat = newCategoria(categoria['name'], categoria['id'])
lt.addLast(catalog['categorias'], cat) | Python | nomic_cornstack_python_v1 |
import urllib.request
from bs4 import BeautifulSoup
import re
import csv
import time
import datetime
set active_listings = list
comment NOTES #############################
comment item number of listings increments down by 1 every new listing -- weird
comment HAS A 5 MINUTE SNIPE TIMER. If ends at 10PM, and a bid is p... | import urllib.request
from bs4 import BeautifulSoup
import re
import csv
import time
import datetime
active_listings = []
############################# NOTES #############################
# item number of listings increments down by 1 every new listing -- weird
# HAS A 5 MINUTE SNIPE TIMER. If ends at 10PM, a... | Python | zaydzuhri_stack_edu_python |
class Result
begin
function __init__ self
begin
set indicator_name = string
set indicator_description = string
set value = string
set type = string
set data = string
end function
function __init__ self indicator_name indicator_description value type
begin
set indicator_name = indicator_name
set indicator_descripti... | class Result():
def __init__(self):
self.indicator_name = ""
self.indicator_description = ""
self.value = ""
self.type = ""
self.data = ""
def __init__(self, indicator_name, indicator_description, value, type):
self.indicator_name = indicator_name
... | Python | zaydzuhri_stack_edu_python |
function uncamelcase name
begin
set s1 = sub string (.)([A-Z][a-z]+) string \1_\2 name
return lower sub string ([a-z0-9])([A-Z]) string \1_\2 s1
end function | def uncamelcase(name):
s1 = sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower() | Python | nomic_cornstack_python_v1 |
from sys import argv
set CARDS = list string 2 string 3 string 4 string 5 string 6 string 7 string 8 string 9 string T string J string Q string K string A
set VALUES = list string 2 string 3 string 4 string 5 string 6 string 7 string 8 string 9 string A string B string C string D string E
function compare a b
begin
ret... | from sys import argv
CARDS = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']
VALUES = ['2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E']
def compare(a, b):
return VALUES.index(a) - VALUES.index(b)
class Hand(object):
def __init__(self, cards, name):
self.name = nam... | Python | zaydzuhri_stack_edu_python |
comment def solution(A):
comment # write your code in Python 2.7
comment max_sum = 0
comment max_end = 0
comment neg_count = 0
comment for i in xrange(0,len(A)):
comment if A[i] <= 0:
comment neg_count+=1
comment max_end = max(0, max_end + A[i])
comment max_sum = max(max_sum, max_end)
comment if neg_count == len(A):
co... | # def solution(A):
# # write your code in Python 2.7
# max_sum = 0
# max_end = 0
# neg_count = 0
# for i in xrange(0,len(A)):
# if A[i] <= 0:
# neg_count+=1
# max_end = max(0, max_end + A[i])
# max_sum = max(max_sum, max_end)
# if neg_count == len(A):
# ... | Python | zaydzuhri_stack_edu_python |
from logging import INFO , getLogger
from unittest import TestCase
from pathseeker.src.logging.logging_manager import LoggingManager
class TestLoggingManager extends TestCase
begin
function test_logger_sets_level self
begin
call get_logger __name__
assert equal level INFO
end function
function test_logger_adds_handlers... | from logging import INFO, getLogger
from unittest import TestCase
from pathseeker.src.logging.logging_manager import LoggingManager
class TestLoggingManager(TestCase):
def test_logger_sets_level(self):
LoggingManager.get_logger(__name__)
self.assertEqual(getLogger("pathseeker").level, INFO)
... | Python | zaydzuhri_stack_edu_python |
with open string ../../inputs/day5.txt as f
begin
set polymer = right strip read f
end
function will_react i j
begin
return is lower i and upper i == j or is lower j and upper j == i
end function
set stack = list
for c in polymer
begin
if length stack == 0
begin
append stack c
continue
end
if call will_react stack at ... | with open("../../inputs/day5.txt") as f:
polymer = f.read().rstrip()
def will_react(i,j):
return (i.islower() and i.upper() == j) or (j.islower() and j.upper() == i)
stack = []
for c in polymer:
if len(stack) == 0:
stack.append(c)
continue
if will_react(stack[-1],c):
stack.pop(... | Python | zaydzuhri_stack_edu_python |
function __init__ self topic_id gains costs max_gain=1.0 min_gain=0.0 max_cost=1.0 min_cost=1.0 max_n=1000
begin
set topic_id = topic_id
set _gains = gains
set _costs = costs
set total_qrel_gain = 0.0
set total_qrel_rels = 0.0
set max_gain = max_gain
set min_gain = min_gain
set max_cost = max_cost
set min_cost = min_co... | def __init__(self, topic_id, gains, costs, max_gain=1.0, min_gain=0.0, max_cost=1.0, min_cost=1.0, max_n=1000):
self.topic_id = topic_id
self._gains = gains
self._costs = costs
self.total_qrel_gain = 0.0
self.total_qrel_rels = 0.0
self.max_gain = max_gain
s... | Python | nomic_cornstack_python_v1 |
import sqlite3
class Database
begin
function __init__ self file=none
begin
call db_initialize file
call make_table
end function
function __del__ self
begin
close cursor
close db
end function
function db_initialize self file
begin
set file_name = file
if file_name is none
begin
set file_name = string result.db
end
set d... | import sqlite3
class Database():
def __init__(self, file=None):
self.db_initialize(file)
self.make_table()
def __del__(self):
self.cursor.close()
self.db.close()
def db_initialize(self, file):
file_name = file
if file_name is None:
file_name = ... | Python | zaydzuhri_stack_edu_python |
import math
function prove_AP_equals_BC A B C P
begin
comment Calculate midpoints M and N
set M = tuple A at 0 + C at 0 / 2 A at 1 + C at 1 / 2
set N = tuple A at 0 + B at 0 / 2 A at 1 + B at 1 / 2
comment AKBP construction (assuming P is on median BM)
comment Translated K to maintain condition
set K = tuple P at 0 + N... | import math
def prove_AP_equals_BC(A, B, C, P):
# Calculate midpoints M and N
M = ((A[0] + C[0]) / 2, (A[1] + C[1]) / 2)
N = ((A[0] + B[0]) / 2, (A[1] + B[1]) / 2)
# AKBP construction (assuming P is on median BM)
K = (P[0] + (N[0] - A[0]), P[1] + (N[1] - A[1])) # Translated K to maintain cond... | Python | dbands_pythonMath |
if length s < length t
begin
print string UNRESTORABLE
exit
end
for i in range length s - length t - 1 - 1
begin
for j in range length t
begin
if s at i + j != string ? and s at i + j != t at j
begin
break
end
end
for else
begin
print replace s at slice : i : string ? string a + t + replace s at slice i + length t : ... | if len(s)<len(t):
print('UNRESTORABLE')
exit()
for i in range(len(s)-len(t),-1,-1):
for j in range(len(t)):
if s[i+j]!='?' and s[i+j]!=t[j]:
break
else:
print(s[:i].replace('?','a')+t+s[i+len(t):].replace('?','a'))
break
else:
print('UNRESTORABLE') | Python | zaydzuhri_stack_edu_python |
comment importing all necessary packages
import cv2
import numpy as np
import pyautogui
import keyboard
from pynput.mouse import Controller as Controller
from pynput.mouse import Button
import time
comment start of the actual script
if __name__ == string __main__
begin
print string Starting...
comment setting up a view... | # importing all necessary packages
import cv2
import numpy as np
import pyautogui
import keyboard
from pynput.mouse import Controller as Controller
from pynput.mouse import Button
import time
# start of the actual script
if __name__ == '__main__':
print('Starting...')
# setting up a view parameters
mouse ... | Python | zaydzuhri_stack_edu_python |
function FindCoinsByVins self vins
begin
string Looks through the current collection of coins in a wallet and chooses coins that match the specified CoinReference objects. Args: vins: A list of ``neo.Core.CoinReference`` objects. Returns: list: A list of ``neo.Wallet.Coin`` objects.
set ret = list
for coin in call Get... | def FindCoinsByVins(self, vins):
"""
Looks through the current collection of coins in a wallet
and chooses coins that match the specified CoinReference objects.
Args:
vins: A list of ``neo.Core.CoinReference`` objects.
Returns:
list: A list of ``neo.Wall... | Python | jtatman_500k |
function tostring self
begin
if length text_spans == 0
begin
return string
end
return join string $$ generator expression join string : tuple string start string end for tuple start end in text_spans
end function | def tostring(self):
if len(self.text_spans) == 0:
return ""
return '$$'.join(':'.join((str(start), str(end))) for (start, end) in self.text_spans) | Python | nomic_cornstack_python_v1 |
function get_install_name some_file
begin
set cmd = list OTOOL string -D some_file
set output_lines = call splitlines
if length output_lines > 1
begin
return output_lines at 1
end
return string
end function | def get_install_name(some_file):
cmd = [OTOOL, "-D", some_file]
output_lines = subprocess.check_output(cmd).decode("utf-8").splitlines()
if len(output_lines) > 1:
return output_lines[1]
return "" | Python | nomic_cornstack_python_v1 |
function add_tag self transaction citation_handle tag_handle
begin
set citation = call get_citation_from_handle citation_handle
call add_tag tag_handle
call commit_citation citation transaction
end function | def add_tag(self, transaction, citation_handle, tag_handle):
citation = self.dbstate.db.get_citation_from_handle(citation_handle)
citation.add_tag(tag_handle)
self.dbstate.db.commit_citation(citation, transaction) | Python | nomic_cornstack_python_v1 |
function bubble_sort arr
begin
set n = length arr
comment Traverse through all array elements
for i in range n
begin
comment Last i elements are already in place
for j in range 0 n - i - 1
begin
comment Traverse the array from 0 to n-i-1
comment Swap if the element found is greater than the next element
if arr at j > a... | def bubble_sort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n):
# Last i elements are already in place
for j in range(0, n-i-1):
# Traverse the array from 0 to n-i-1
# Swap if the element found is greater than the... | Python | jtatman_500k |
import requests
import csv
import json
import pandas as pd
import os
from sklearn.preprocessing import LabelEncoder
function insertion_sort list color
begin
if length list < 1
begin
append list color
return list
end
else
begin
append list color
set i = length list - 1
if list at i < list at i - 1
begin
set key = color
... | import requests
import csv
import json
import pandas as pd
import os
from sklearn.preprocessing import LabelEncoder
def insertion_sort(list, color):
if(len(list) < 1):
list.append(color)
return list
else:
list.append(color)
i = len(list)-1
if(list[i]<list[i-1]):
... | Python | zaydzuhri_stack_edu_python |
import os
import pandas as pd
from paths import sam_scenario_path , pwc_scenario_path
function create_dir out_path
begin
string Create a directory for a file name if it doesn't exist
if not exists path directory name path out_path
begin
make directories directory name path out_path
end
end function
function scenarios s... | import os
import pandas as pd
from paths import sam_scenario_path, pwc_scenario_path
def create_dir(out_path):
""" Create a directory for a file name if it doesn't exist """
if not os.path.exists(os.path.dirname(out_path)):
os.makedirs(os.path.dirname(out_path))
def scenarios(scenario_matrix, mode, ... | Python | zaydzuhri_stack_edu_python |
import sys
from copy import deepcopy
from common import load_input
function c2b c
begin
return c == string #
end function
function preprocess raw
begin
set tuple init_raw _ *rules_raw = call splitlines
set init_raw = split init_raw at - 1
set init_state = tuple generator expression i for tuple i c in enumerate map c2b ... | import sys
from copy import deepcopy
from common import load_input
def c2b(c):
return c == "#"
def preprocess(raw):
init_raw, _, *rules_raw = raw.splitlines()
init_raw = init_raw.split()[-1]
init_state = tuple(i for i, c in enumerate(map(c2b, init_raw)) if c)
rules = dict()
for line in rule... | Python | zaydzuhri_stack_edu_python |
function fill_motion self
begin
while length x_values < num_points
begin
set x_direction = random choice list 1 - 1
set x_distance = random choice list 0 1 2 3 4
set x_movement = x_direction * x_distance
set y_direction = random choice list 1 - 1
set y_distance = random choice list 0 1 2 3 4
set y_movement = y_directio... | def fill_motion(self):
while len(self.x_values) < self.num_points:
x_direction = choice([1, -1])
x_distance = choice([0, 1, 2, 3, 4])
x_movement = x_direction * x_distance
y_direction = choice([1, -1])
y_distance = choice([0, 1, 2, 3, 4])
... | Python | nomic_cornstack_python_v1 |
function _openExemplar self
begin
return call Dataset string %s_%d.nc % tuple _basename _year
end function | def _openExemplar(self) :
return nc.Dataset('%s_%d.nc' % ( self._basename, self._year ) ) | Python | nomic_cornstack_python_v1 |
function Save_input_in_file
begin
comment author W. Mercier
try
begin
set f = open saveinput_file string w
end
except IOError
begin
raise call IOError string cannot open file saveinput_file
end
set dict = dict string verbosity verbosity ; string mock_dir mock_dir ; string galaxy_dir galaxy_dir ; string detection_dir de... | def Save_input_in_file():
#author W. Mercier
try:
f = open(saveinput_file,'w')
except IOError:
raise IOError("cannot open file", saveinput_file)
dict = {"verbosity":verbosity, "mock_dir":mock_dir, "galaxy_dir":galaxy_dir, "detection_dir":detection_dir, "association_dir":association_... | Python | nomic_cornstack_python_v1 |
import numpy as np
import matplotlib.pyplot as plt
set x = array range - 3 20 0.1
set y = 2 * x + 5
plot x y color=string b | import numpy as np
import matplotlib.pyplot as plt
x=np.arange(-3, 20, 0.1)
y=2*x+5
plt.plot(x,y,color='b')
| Python | zaydzuhri_stack_edu_python |
set str = string hello world
comment string ki lenth
print length str
comment print karo 5va character
print str at 4
comment 0,1,2,3,4 char ko print karo
print str at slice 0 : 5 :
comment skip one character
print str at slice 0 : 5 : 2
comment by default zero char skip, pura lega
print str at slice : :
comment pura... | str="hello world"
print(len(str))#string ki lenth
print(str[4])#print karo 5va character
print(str[0:5])#0,1,2,3,4 char ko print karo
print(str[0:5:2])#skip one character
print(str[::])#by default zero char skip, pura lega
print(str[0:56])#pura le le ga
print(str[:])#pura le le ga , by default pura
print(str[:5])#by de... | Python | zaydzuhri_stack_edu_python |
comment 3
function getbaraidxinfo self idx_
begin
set tuple res resargs = call getbaraidxinfo idx_
if res != 0
begin
set tuple result msg = call __getlasterror res
raise error call rescode res msg
end
set _num_return_value = resargs
return _num_return_value
end function | def getbaraidxinfo(self,idx_): # 3
res,resargs = self.__obj.getbaraidxinfo(idx_)
if res != 0:
result,msg = self.__getlasterror(res)
raise Error(rescode(res),msg)
_num_return_value = resargs
return _num_return_value | Python | nomic_cornstack_python_v1 |
function uncommented lines
begin
for line in lines
begin
if not starts with line string #
begin
yield line
end
end
end function | def uncommented (lines):
for line in lines:
if not line.startswith('#'):
yield line | Python | nomic_cornstack_python_v1 |
from flask import Flask , render_template , abort
import data
set app = call Flask __name__
decorator call route string /
function render_index
begin
set output = call render_template string index.html title=title subtitle=subtitle description=description departures=departures tours=tours
return output
end function
dec... | from flask import Flask, render_template, abort
import data
app = Flask(__name__)
@app.route("/")
def render_index():
output = render_template('index.html',
title=data.title,
subtitle=data.subtitle,
description=data.descripti... | Python | zaydzuhri_stack_edu_python |
class Solution extends object
begin
function isIsomorphic self s t
begin
string :type s: str :type t: str :rtype: bool
if length s != length t
begin
return false
end
set m1 = dict
set m2 = dict
for tuple i val in enumerate s
begin
set m1 at val = get m1 val list + list i
end
for tuple i val in enumerate t
begin
set m... | class Solution(object):
def isIsomorphic(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) != len(t):
return False
m1 = {}
m2 = {}
for i, val in enumerate(s):
m1[val] = m1.get(val, []) + [i]
f... | Python | zaydzuhri_stack_edu_python |
function get_ftp_start_node dataset table start_url
begin
if dataset in list string SIASUS string SIHSUS
begin
set url = join path string 200801_ string Dados
end
else
if dataset in list string SIM
begin
set suffix = if expression table == string DO then string DORES else string DOFET
set url = join path string CID10 s... | def get_ftp_start_node(dataset, table, start_url):
if dataset in ['SIASUS', 'SIHSUS']:
url = os.path.join('200801_', 'Dados')
elif dataset in ['SIM']:
suffix = 'DORES' if table == 'DO' else 'DOFET'
url = os.path.join('CID10', suffix)
elif dataset in ['CMD']:
url = os.path.j... | Python | nomic_cornstack_python_v1 |
function compile_func arg_names statements name=string _the_func debug=false
begin
set args_fields = dict string args list comprehension call arg arg=n annotation=none for n in arg_names ; string kwonlyargs list ; string kw_defaults list ; string defaults list comprehension call ex_literal none for _ in arg_names
com... | def compile_func(arg_names, statements, name='_the_func', debug=False):
args_fields = {
'args': [ast.arg(arg=n, annotation=None) for n in arg_names],
'kwonlyargs': [],
'kw_defaults': [],
'defaults': [ex_literal(None) for _ in arg_names],
}
if 'posonlyargs' in ast.arguments._f... | Python | nomic_cornstack_python_v1 |
function cluster_name self
begin
return get pulumi self string cluster_name
end function | def cluster_name(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "cluster_name") | Python | nomic_cornstack_python_v1 |
function get_pos self
begin
set flow = FlowView
return values call GetPosTable _reference
end function | def get_pos(self):
flow = comp.CurrentFrame.FlowView
return flow.GetPosTable(self._reference).values() | Python | nomic_cornstack_python_v1 |
import numpy as np
import cv2
set image = call imread string images/bit_test.jpg IMREAD_COLOR
set logo = call imread string images/logo.jpg IMREAD_COLOR
if image is none or logo is none
begin
raise exception string 영상파일 읽기 오류
end
set masks = call threshold logo 220 255 THRESH_BINARY at 1
set masks = split cv2 masks
set... | import numpy as np
import cv2
image = cv2.imread("images/bit_test.jpg", cv2.IMREAD_COLOR)
logo = cv2.imread("images/logo.jpg", cv2.IMREAD_COLOR)
if image is None or logo is None: raise Exception("영상파일 읽기 오류")
masks = cv2.threshold(logo, 220, 255, cv2.THRESH_BINARY)[1]
masks = cv2.split(masks)
fg_pass_mask ... | Python | zaydzuhri_stack_edu_python |
function compute_partial_decryption encrypted_message key_share
begin
set yC1 = C1 * y
return call PartialDecryption x yC1 curve_params
end function | def compute_partial_decryption(encrypted_message: EncryptedMessage, key_share: KeyShare) -> PartialDecryption:
yC1 = encrypted_message.C1 * key_share.y
return PartialDecryption(key_share.x, yC1, key_share.curve_params) | Python | nomic_cornstack_python_v1 |
function getTemperature self
begin
return __temperature
end function | def getTemperature(self):
return self.__temperature | Python | nomic_cornstack_python_v1 |
import random
import time
set w = list string cat string dog string fox string monkey string mouse string panda string frog string snake string wolf
comment 문제 번호
set n = 1
print string [타자게임]준비하면 엔터!
input
comment 시작시간 기록
set start = time
set q = random choice w
while n <= 5
begin
print string 문제 n
print q
comment 사용자... | import random
import time
w = ["cat","dog","fox","monkey","mouse","panda","frog","snake","wolf"]
n = 1 #문제 번호
print("[타자게임]준비하면 엔터!")
input()
start = time.time() # 시작시간 기록
q = random.choice(w)
while n <= 5:
print("문제",n)
print(q)
x = input() #사용자 입력
if q == x:
print("통과!")
... | Python | zaydzuhri_stack_edu_python |
from scipy.special import kn
import numpy as np
from odeintw import odeintw
function my_kn1 x
begin
string Convenience wrapper for kn(1, x)
return if expression x <= 600 then call kn 1 x else 1e-100
end function
function my_kn2 x
begin
string Convenience wrapper for kn(2, x)
return if expression x <= 600 then call kn 2... | from scipy.special import kn
import numpy as np
from odeintw import odeintw
def my_kn1(x):
"""
Convenience wrapper for kn(1, x)
"""
return kn(1, x) if x<=600 else 1e-100
def my_kn2(x):
"""
Convenience wrapper for kn(2, x)
"""
return kn(2, x) if x<=600 else 1e-100
class LeptoCalc(obje... | Python | zaydzuhri_stack_edu_python |
function GetTradeUsingOptionalKey optionalKey
begin
comment pylint: disable=no-member
set trades = select FTrade string optionalKey="%s" % optionalKey
if length trades == 1
begin
return trades at 0
end
else
begin
return string -
end
end function | def GetTradeUsingOptionalKey(optionalKey):
# pylint: disable=no-member
trades = acm.FTrade.Select('optionalKey="%s"' % optionalKey)
if len(trades) == 1:
return trades[0]
else:
return ' - ' | Python | nomic_cornstack_python_v1 |
comment Question: 56
comment Define a custom exception class which takes a string message as attribute.
class Error extends Exception
begin
function __init__ self message
begin
set message = message
end function
end class
set error = error string Error occured! | # Question: 56
# Define a custom exception class which takes a string message as attribute.
class Error(Exception):
def __init__(self, message):
self.message = message
error = Error("Error occured!") | Python | zaydzuhri_stack_edu_python |
function __init__ self tensor_slice_dict
begin
set _tensor_slice_dict = tensor_slice_dict
end function | def __init__(self, tensor_slice_dict):
self._tensor_slice_dict = tensor_slice_dict | Python | nomic_cornstack_python_v1 |
function makemycv filename=string cv.bib silent=true bibtex_types=tuple string inbook string article string periodical string techreport string inproceedings writeout=true indent=string author=none outpath=none entrytypes=none
begin
if entrytypes is not none
begin
print string entrytypes will be deprecated in future r... | def makemycv(filename='cv.bib',
silent=True,
bibtex_types=('inbook', 'article', 'periodical',
'techreport', 'inproceedings'),
writeout=True,
indent=' ',
author=None,
outpath=None,
entrytypes=None):
... | Python | nomic_cornstack_python_v1 |
function __init__ self url
begin
set response_dict = json get requests url
comment p(self.response_dict['data'])
set data = response_dict at string data
set header_field = list keys response_dict at string data at 0
end function | def __init__(self, url):
self.response_dict = requests.get(url).json()
# p(self.response_dict['data'])
self.data = self.response_dict['data']
self.header_field = list(self.response_dict['data'][0].keys()) | Python | nomic_cornstack_python_v1 |
function get_response self offset e_true e_reco=none
begin
set e_true = call Energy e_true
comment Default: e_reco nodes = migra nodes * e_true nodes
if e_reco is none
begin
set e_reco = call from_lower_and_upper_bounds migra_lo * e_true migra_hi * e_true
set migra = migra
end
else
begin
comment Translate given e_reco ... | def get_response(self, offset, e_true, e_reco=None):
e_true = Energy(e_true)
# Default: e_reco nodes = migra nodes * e_true nodes
if e_reco is None:
e_reco = EnergyBounds.from_lower_and_upper_bounds(
self.migra_lo * e_true, self.migra_hi * e_true)
migra ... | Python | nomic_cornstack_python_v1 |
function create_xarray_list filelist
begin
comment Create lat/long np.arrays for creation of xarrays
set lats = call flip array range - 43.95 - 10.05 0.05 axis=0
set lons = array range 112.05 153.96 0.05
print string now string : Creating xarray of files.
set xarray_list = list
for file in call progressbar filelist
be... | def create_xarray_list(filelist):
#Create lat/long np.arrays for creation of xarrays
lats = np.flip(np.arange(-43.95, -10.05, 0.05), axis = 0)
lons = np.arange(112.05, 153.96, 0.05)
print(str(datetime.datetime.now()), ": Creating xarray of files.")
xarray_list = []
for file i... | Python | nomic_cornstack_python_v1 |
comment 문자열 뒤집기
comment 1.투 포인터 사용
function reverseString1 self s
begin
set tuple left right = tuple 0 length s - 1
while left < right
begin
set tuple s at left s at right = tuple s at right s at left
set left = left + 1
set right = right - 1
end
end function
comment 2.파이썬 다운 방식
function reverseString2 self s
begin
rev... | # 문자열 뒤집기
## 1.투 포인터 사용
def reverseString1(self, s):
left, right = 0, len(s) - 1
while left < right:
s[left], s[right] = s[right], s[left]
left += 1
right -= 1
## 2.파이썬 다운 방식
def reverseString2(self, s):
s.reverse
| Python | zaydzuhri_stack_edu_python |
function binary_search my_list val
begin
comment if len(my_list) < 2:
comment return my_list
set mid = length my_list // 2
set left = my_list at slice : mid :
set right = my_list at slice mid : :
if val == mid
begin
for i in range length my_list
begin
if my_list at i == mid
begin
return i
end
end
end
else
begin
for... | def binary_search(my_list, val):
# if len(my_list) < 2:
# return my_list
mid = len(my_list) // 2
left = my_list[:mid]
right = my_list[mid:]
if val == mid:
for i in range(len(my_list)):
if my_list[i] == mid:
return i
else:
for i in range(0, len(... | Python | zaydzuhri_stack_edu_python |
function populate_metadata case config
begin
return dict string Type string Summary ; string Title string Verification ; string Headers list string Bit for Bit string Configurations string Std. Out Files
end function | def populate_metadata(case, config):
return {"Type": "Summary",
"Title": "Verification",
"Headers": ["Bit for Bit", "Configurations", "Std. Out Files"]} | 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.