code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
import logging
from models import Column , Row , DataType , db
set logger = call getLogger string FS
class Cell extends object
begin
set array = dict
function __init__ self row column data=none
begin
set id = length array
set row_id = row
set column_id = column
set _data = data
set column_obj = get Column column
set r... | import logging
from models import Column, Row, DataType, db
logger = logging.getLogger("FS")
class Cell(object):
array = {}
def __init__(self, row, column, data=None):
self.id = len(Cell.array)
self.row_id = row
self.column_id = column
self._data = data
... | Python | zaydzuhri_stack_edu_python |
function get_max_period self
begin
set wing_cross_section_movement_max_periods = list
for wing_cross_section_movement in wing_cross_section_movements
begin
append wing_cross_section_movement_max_periods call get_max_period
end
set max_wing_cross_section_movement_period = max wing_cross_section_movement_max_periods
set... | def get_max_period(self):
wing_cross_section_movement_max_periods = []
for wing_cross_section_movement in self.wing_cross_section_movements:
wing_cross_section_movement_max_periods.append(
wing_cross_section_movement.get_max_period()
)
max_wing_cross_sect... | Python | nomic_cornstack_python_v1 |
comment Program to Calculate the Future Value of the Specific Months
comment Creating a Function For getting Future Value
function Future_value
begin
comment Taking the Input from the user of present value , Monthly intrest and Number of Months
set Present_Val = decimal input string Enter the present value of the accou... | # Program to Calculate the Future Value of the Specific Months
# Creating a Function For getting Future Value
def Future_value():
#Taking the Input from the user of present value , Monthly intrest and Number of Months
Present_Val = float(input("Enter the present value of the account in dollars : "))
... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import matplotlib.pyplot as plt
import os
import pandas as pd
class Perceptron extends object
begin
function __init__ self eta=0.01 n_iter=50 random_state=1
begin
set eta = eta
set n_iter = n_iter
set random_state = random_state
end function
function fit self X y
begin
set rgen = call RandomState ran... | import numpy as np
import matplotlib.pyplot as plt
import os
import pandas as pd
class Perceptron(object):
def __init__(self, eta=0.01, n_iter=50, random_state=1):
self.eta = eta
self.n_iter = n_iter
self.random_state = random_state
def fit(self, X, y):
rgen = np.random.Random... | Python | zaydzuhri_stack_edu_python |
comment carrera de tortugas
import turtle
import random
class Circuito
begin
set corredores = list
set __posStartY = tuple - 30 - 10 10 30
set __colorTurtle = tuple string red string blue string green string orange
function __init__ self width height
begin
set __screen = call Screen
setup __screen width height
call bg... | #carrera de tortugas
import turtle
import random
class Circuito():
corredores = []
__posStartY = (-30,-10,10,30)
__colorTurtle = ('red','blue','green','orange')
def __init__(self,width,height):
self.__screen = turtle.Screen()
self.__screen.setup(width,height)
self.__screen.... | Python | zaydzuhri_stack_edu_python |
class UserAccounts
begin
string Blue print for creating and managing users Contains user accounts attributes method It will be responsible for displaying all events
function __init__ self
begin
set users = dict
set events = dict
end function
comment Add a new user into the database
function create_user self user
begi... | class UserAccounts:
"""
Blue print for creating and managing users
Contains user accounts attributes method
It will be responsible for displaying all events
"""
def __init__(self):
self.users = {}
self.events = {}
# Add a new user into the database
def create_user(self,... | Python | zaydzuhri_stack_edu_python |
function set_cookie self name value domain=none expires=none path=string / expires_days=none **kwargs
begin
set name = call native_str name
set value = call native_str value
if search string [\x00-\x20] name + value
begin
raise call ValueError string Invalid cookie %r: %r % tuple name value
end
if not has attribute sel... | def set_cookie(self, name, value, domain=None, expires=None, path="/",
expires_days=None, **kwargs):
name = native_str(name)
value = native_str(value)
if re.search(r"[\x00-\x20]", name + value):
raise ValueError("Invalid cookie %r: %r" % (name, value))
... | Python | nomic_cornstack_python_v1 |
function get_name_cost db name
begin
string Get the cost of a name, given the fully-qualified name. Do so by finding the namespace it belongs to (even if the namespace is being imported). Return {'amount': ..., 'units': ...} on success Return None if the namespace has not been declared
set lastblock = lastblock
set nam... | def get_name_cost( db, name ):
"""
Get the cost of a name, given the fully-qualified name.
Do so by finding the namespace it belongs to (even if the namespace is being imported).
Return {'amount': ..., 'units': ...} on success
Return None if the namespace has not been declared
"""
lastblock... | Python | jtatman_500k |
function bfs_traversal graph s goals=list
begin
set visited = list
set boundary = deque list s
while length boundary > 0
begin
set v = call popleft
set visited = visited + list v
if v in goals
begin
return visited
end
for w in call neighbours v graph
begin
if w not in visited and w not in boundary
begin
append boundar... | def bfs_traversal(graph, s, goals=[]):
visited = []
boundary = deque([s])
while len(boundary) > 0:
v = boundary.popleft()
visited += [v]
if v in goals:
return visited
for w in neighbours(v, graph):
if w not in visited and w not in boundary:
... | Python | nomic_cornstack_python_v1 |
import math
import time
while true
begin
set sayi = integer input string Sayi gir:
print format string {}! = {} sayi call factorial sayi
print string Devam etmek için herhangi bir tuşa basınız!! Çıkmak için c tuşuna basınız!!
set press = input
if press == string c or press == string C
begin
print string GÜLE GÜLE :)))
... | import math
import time
while(True):
sayi=int(input("Sayi gir:"))
print("{}! = {}".format(sayi,math.factorial(sayi)))
print("Devam etmek için herhangi bir tuşa basınız!!\nÇıkmak için c tuşuna basınız!!")
press=input()
if(press=="c" or press=="C"):
print("GÜLE GÜLE :)))")
time.sleep(2... | Python | zaydzuhri_stack_edu_python |
function watch
begin
import watch
call watch
end function | def watch():
import watch
watch.watch() | Python | nomic_cornstack_python_v1 |
function _process_kinase_domain self kinase_structure uniprot_id
begin
from openeye import oechem
from core.sequences import KinaseDomainAminoAcidSequence
from modeling.OEModeling import mutate_structure , renumber_structure , prepare_protein
debug string Retrieving kinase domain sequence details for UniProt entry { un... | def _process_kinase_domain(
self, kinase_structure: oechem.OEGraphMol, uniprot_id: str
) -> oechem.OEGraphMol:
from openeye import oechem
from ..core.sequences import KinaseDomainAminoAcidSequence
from ..modeling.OEModeling import mutate_structure, renumber_structure, prepare_protei... | Python | nomic_cornstack_python_v1 |
function get_pid_threads_count pid
begin
set process = process pid
assert call is_running msg string PID %d is not running % pid
set threads_count = call num_threads
return threads_count
end function | def get_pid_threads_count(pid):
process = psutil.Process(pid)
assert process.is_running(), 'PID %d is not running' % pid
threads_count = process.num_threads()
return threads_count | Python | nomic_cornstack_python_v1 |
function _open_file self path
begin
if version_info at 0 < 3
begin
return open path string rb
end
else
begin
return open path string r newline=string
end
end function | def _open_file(self, path):
if sys.version_info[0] < 3:
return open(path, 'rb')
else:
return open(path, 'r', newline='') | Python | nomic_cornstack_python_v1 |
comment word shifter V(idk like 20) by bobtie
set debug = input string enable debug mode?
comment debug mode is identical to normal mode, however it displays all of the variables whenever they are changed
comment in debug mode, there will be lines of code which look like [print("{variable name}: "+{variable name})]
com... | # word shifter V(idk like 20) by bobtie
debug = input("enable debug mode? ")
# debug mode is identical to normal mode, however it displays all of the variables whenever they are changed
# in debug mode, there will be lines of code which look like [print("{variable name}: "+{variable name})]
# these lines o... | Python | zaydzuhri_stack_edu_python |
function test_tags_recently_used_count self
begin
set po = call load_pageobject string TagsPage
call goto_page
set tags = call get_recently_used_tags
assert length tags <= 25 msg string # tags is %s, which is greater than 25 % length tags
end function | def test_tags_recently_used_count(self):
po = self.catalog.load_pageobject('TagsPage')
po.goto_page()
tags = po.get_recently_used_tags()
assert len(tags) <= 25, \
"# tags is %s, which is greater than 25" % (len(tags)) | Python | nomic_cornstack_python_v1 |
function model y p
begin
set tuple kappa mu = p
if kappa == 0.0
begin
set mod = ones length y
end
else
begin
set mod = kappa / call sinh kappa * exp kappa * y * cos mu + square root 1 - y ^ 2 * sin mu
end
set norm = call quad cosine_fisher_integrand 0 1.0 args=tuple kappa mu at 0
return mod / norm
end function | def model(y, p):
kappa, mu = p
if kappa == 0.0:
mod = np.ones(len(y))
else:
mod = kappa / np.sinh(kappa) * np.exp(kappa*(y*np.cos(mu) + np.sqrt(1-y**2)*np.sin(mu)))
norm = quad(cosine_fisher_integrand, 0, 1.0, args=(kappa, mu))[0]
return mod / norm | Python | nomic_cornstack_python_v1 |
import sys
append path string ../src/org
from display import DrawingGenerics
import testMapCoordinator as mc
from maps import Map1 as map1
from maps import Map2 as map2
from maps import Map3 as map3
import unittest | import sys
sys.path.append('../src/org')
from display import DrawingGenerics
import testMapCoordinator as mc
from maps import Map1 as map1
from maps import Map2 as map2
from maps import Map3 as map3
import unittest
| Python | zaydzuhri_stack_edu_python |
function change_copies self book_id
begin
set book = first filter by query id=book_id
if book
begin
set copies = copies + 1
commit session
end
end function | def change_copies(self, book_id):
book = Book.query.filter_by(id=book_id).first()
if book:
self.copies += 1
db.session.commit() | Python | nomic_cornstack_python_v1 |
for i in range 1 11
begin
append list i ^ 2
end
print list | for i in range(1,11):
list.append(i**2)
print(list) | Python | zaydzuhri_stack_edu_python |
comment Exercicio 3
comment Crie 3 variáveis
comment Cada variável deve conter um número
comment Imprima na tela a soma dos 3 números | # Exercicio 3
#
# Crie 3 variáveis
#
# Cada variável deve conter um número
#
# Imprima na tela a soma dos 3 números
| Python | zaydzuhri_stack_edu_python |
function __enter__ self
begin
call connect
comment will handle the database context ourselves
return self
end function | def __enter__(self):
self.connect()
# will handle the database context ourselves
return self | Python | nomic_cornstack_python_v1 |
comment Reading a file
set f = open string abc.txt
comment reading all the lines
comment data=f.read()
comment reading first 10 characters
comment data=f.read(10)
comment reading line by line.By default print method will add the /n
set data = read line f
print data end=string
set data = read line f
print data end=strin... | # Reading a file
f=open('abc.txt')
# reading all the lines
# data=f.read()
# reading first 10 characters
#data=f.read(10)
# reading line by line.By default print method will add the /n
data=f.readline()
print(data,end='')
data=f.readline()
print(data,end='') | Python | zaydzuhri_stack_edu_python |
function phases self params=none
begin
set url = get _data string phases
set data = call request url string GET params=params
return call get_items
end function | def phases(self, params=None):
url = self._data.get('phases')
data = self._api.request(url, 'GET', params=params)
return self.__class_phase__(self._api, data).get_items() | Python | nomic_cornstack_python_v1 |
function conv_transpose lhs rhs strides padding rhs_dilation=none dimension_numbers=none transpose_kernel=false precision=none
begin
assert length shape == length shape and length shape > 2
set ndims = length shape
set one = tuple 1 * ndims - 2
comment Set dimensional layout defaults if not specified.
if dimension_numb... | def conv_transpose(lhs, rhs, strides, padding,
rhs_dilation=None, dimension_numbers=None,
transpose_kernel=False, precision=None):
assert len(lhs.shape) == len(rhs.shape) and len(lhs.shape) > 2
ndims = len(lhs.shape)
one = (1,) * (ndims - 2)
# Set dimensional layout default... | Python | nomic_cornstack_python_v1 |
function _goDaemon
begin
call _doFork
change directory string /
call setsid
call umask 0
call _doFork
end function | def _goDaemon():
_doFork()
os.chdir("/")
os.setsid()
os.umask(0)
_doFork() | Python | nomic_cornstack_python_v1 |
function smooth_sources self heights=list tavg_window=600.0 dt=1.0 verbose=true
begin
try
begin
from scipy.ndimage import uniform_filter
end
except ImportError
begin
print string Moving average calculation uses scipy.ndimage
return
end
if length heights == 0
begin
set heights = hLevelsCell
end
set Nout = length height... | def smooth_sources(self,
heights=[],
tavg_window=600.0,
dt=1.0,
verbose=True):
try:
from scipy.ndimage import uniform_filter
except ImportError:
print('Moving average calculation uses scipy.ndimag... | Python | nomic_cornstack_python_v1 |
function share_name self
begin
return get pulumi self string share_name
end function | def share_name(self) -> str:
return pulumi.get(self, "share_name") | Python | nomic_cornstack_python_v1 |
from pdfminer.pdfinterp import PDFResourceManager , PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO
comment import datefinder
import pandas as pd
comment from pandas.tseries.offsets import CustomBusinessDay... | from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO
# import datefinder
import pandas as pd
# from pandas.tseries.offsets import CustomBusinessDay
import datet... | Python | zaydzuhri_stack_edu_python |
function align shape target
begin
set translated = call translate_to_origin shape
set scaled = call normalize translated
set aligned = call rotate_to_target scaled target
return aligned
end function | def align(shape, target):
translated = translate_to_origin(shape)
scaled = normalize(translated)
aligned = rotate_to_target(scaled, target)
return aligned | Python | nomic_cornstack_python_v1 |
from flask import Flask
comment __name__ tells the name of package where the class lies
set app = call Flask __name__
decorator call route string /
comment decorator referrring to the root dir
function hello_world
begin
return string Hello World!
end function
decorator call route string /hello/<name>
function index_fun... | from flask import Flask
# __name__ tells the name of package where the class lies
app = Flask(__name__)
# decorator referrring to the root dir
@app.route('/')
def hello_world():
return 'Hello World!'
@app.route('/hello/<name>')
def index_function(name):
return ('Hello ' + name)
| Python | zaydzuhri_stack_edu_python |
from bs4 import BeautifulSoup
import requests
set url = string https://knewone.com/discover?page=7
set wb_data = get requests url
set soup = call BeautifulSoup text string lxml
string 通过检查 selector中选取的原始数据为 div > section > div:nth-child > div.hits_group-things.clearfix > article:nth-child > header > a > img div > secti... | from bs4 import BeautifulSoup
import requests
url = 'https://knewone.com/discover?page=7'
wb_data = requests.get(url)
soup = BeautifulSoup(wb_data.text,'lxml')
'''
通过检查 selector中选取的原始数据为
div > section > div:nth-child > div.hits_group-things.clearfix > article:nth-child > header > a > img
div > section > div:nth-child ... | Python | zaydzuhri_stack_edu_python |
comment task4
import md5
import time
set counter = 1
set md5_hash = call raw_input string Please Enter your md5 Hash:
set pwdfile = call raw_input string please enter your wordlist path:
try
begin
set pwdfile = open pwdfile string r
end
except any
begin
print string File not found
call quit
end
for password in pwdfile
... | #task4
import md5
import time
counter = 1
md5_hash = raw_input("Please Enter your md5 Hash: ")
pwdfile = raw_input("please enter your wordlist path: ")
try:
pwdfile = open(pwdfile,"r")
except:
print ("\nFile not found")
quit()
for password in pwdfile:
filemd5 = md5.new(password.strip()).hexdigest()... | Python | zaydzuhri_stack_edu_python |
from datetime import datetime
set Da = integer input
set Conta = 0
for i in range Da
begin
set C = input
set B = split C
set F = string parse time B at 0 string %Y/%m/%d
set M = month
set D = day
set T = integer B at 1
set y = year
for i in range 1 T + 1
begin
set A = y + i
set Ft = call datetime A M D
set L = string f... | from datetime import datetime
Da=int(input())
Conta=0
for i in range (Da):
C=input()
B=C.split()
F=datetime.strptime(B[0], '%Y/%m/%d')
M=F.month
D=F.day
T=int(B[1])
y=F.year
for i in range(1,T+1):
A=y+i
Ft=datetime(A,M,D)
L=Ft.strftime('%A')
#prin... | Python | zaydzuhri_stack_edu_python |
function _display_metadata self
begin
set header = string <xskillscore. { __name__ } >
set summary = header + join string split string table string at slice 1 : : + string
return summary
end function | def _display_metadata(self) -> str:
header = f"<xskillscore.{type(self).__name__}>\n"
summary = header + "\n".join(str(self.table).split("\n")[1:]) + "\n"
return summary | Python | nomic_cornstack_python_v1 |
function block_bicgstab A B x0=none tol=1e-10 maxiter=none M=none
begin
comment TODO: (IMPORTANT!) use more effecient block linear solver,
comment consider blocked Bicgrq
return call spsolve A B
end function | def block_bicgstab(A, B, x0=None, tol=1e-10, maxiter=None, M=None):
# TODO: (IMPORTANT!) use more effecient block linear solver,
# consider blocked Bicgrq
return scipy.sparse.linalg.spsolve(A, B) | Python | nomic_cornstack_python_v1 |
comment Union-Find based solution
comment Time complexity - O(m*n) to traverse through the entire grid | Space complexity - O(m*n) as required by UnionFind data-structure where m=number of rows, n=number of cols
class UnionFind
begin
comment This step will initialize the parent and rank arrays of the UnionFind data-str... | # Union-Find based solution
# Time complexity - O(m*n) to traverse through the entire grid | Space complexity - O(m*n) as required by UnionFind data-structure where m=number of rows, n=number of cols
class UnionFind:
# This step will initialize the parent and rank arrays of the UnionFind data-structure and set numb... | Python | zaydzuhri_stack_edu_python |
function onStart tag keywords
begin
set c = get keywords string c
if c
begin
set log = log
comment Replace frame.put with newPut.
call funcToMethod newPut log string put
comment Replace frame.putnl with newPutNl.
call funcToMethod newPutNl log string putnl
end
end function | def onStart(tag, keywords):
c = keywords.get('c')
if c:
log = c.frame.log
# Replace frame.put with newPut.
g.funcToMethod(newPut, log, "put")
# Replace frame.putnl with newPutNl.
g.funcToMethod(newPutNl, log, "putnl") | Python | nomic_cornstack_python_v1 |
class Zwierze
begin
function __init__ self gatunek
begin
set gatunek = gatunek
end function
function printgatunek self
begin
print string Tutaj: + gatunek
end function
end class
class kot extends Zwierze
begin
function miaucze self
begin
print string miaucze
end function
end class
class pies extends Zwierze
begin
funct... | class Zwierze:
def __init__(self, gatunek):
self.gatunek = gatunek
def printgatunek(self):
print("Tutaj:" + self.gatunek)
class kot(Zwierze):
def miaucze(self):
print("miaucze")
class pies(Zwierze):
def szczekam(self):
print("szczekam")
class ptak(Zwier... | Python | zaydzuhri_stack_edu_python |
function share_instances_get_all_by_host context host with_share_data=false status=none session=none
begin
set session = session or call get_session
set instances = filter call or_ host == host call like format string {0}#% host
if status is not none
begin
set instances = filter status == status
end
comment Returns lis... | def share_instances_get_all_by_host(context, host, with_share_data=False,
status=None, session=None):
session = session or get_session()
instances = (
model_query(context, models.ShareInstance).filter(
or_(
models.ShareInstance.host == host... | Python | nomic_cornstack_python_v1 |
import numpy as np
import scipy.stats
import scipy.optimize
function std_CL A two_bounds=false ignore_nans=false
begin
string Calculate standard deviation estimate with bound for confidence level 1 sigma. TODO
set cl = call cdf 1 - call cdf - 1
set S = array A
if ignore_nans
begin
set S = S at ? call isnan S
end
set st... | import numpy as np
import scipy.stats
import scipy.optimize
def std_CL(A, two_bounds=False, ignore_nans=False):
"""Calculate standard deviation estimate with bound for
confidence level 1 sigma.
TODO
"""
cl = scipy.stats.norm.cdf(1) - scipy.stats.norm.cdf(-1)
S = np.array(A)
if ignore_na... | Python | zaydzuhri_stack_edu_python |
from handler import Handler
from log import log
class Printer extends Handler
begin
string print the document
function __init__ self
begin
pass
end function
function handle self doc
begin
write log string Printer: + string doc
end function
end class | from handler import Handler
from ..log import log
class Printer(Handler):
'''print the document'''
def __init__(self):
pass
def handle(self, doc):
log.write('Printer: ' + str(doc))
| Python | zaydzuhri_stack_edu_python |
set tuple x1 k1 = split input string Enter string and a char: string
set c = count x1 k1
print c | x1,k1=input("Enter string and a char:").split(' ')
c=x1.count(k1)
print(c)
| Python | zaydzuhri_stack_edu_python |
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
set consumer_object_list = list
comment 用户列表
class ChatConsumer extends WebsocketConsumer
begin
comment 监听事件 自动触发
function websocket_connect self message
begin
comment 请求连接
call accept
comment 建立链接
append consumer_obj... | from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
consumer_object_list = []
# 用户列表
class ChatConsumer(WebsocketConsumer):
# 监听事件 自动触发
def websocket_connect(self, message):
# 请求连接
self.accept()
# 建立链接
consumer_object_list.append(self)
... | Python | zaydzuhri_stack_edu_python |
function replace_image_point_labels image labels
begin
set img = copy image
for tuple label point in labels
begin
set tuple row col = point
comment Find the existing label at the point
set index = img at tuple integer row integer col
comment Replace the existing label with new, excluding background
if index > 0
begin
s... | def replace_image_point_labels(image, labels):
img = image.copy()
for label, point in labels:
row, col = point
# Find the existing label at the point
index = img[int(row), int(col)]
# Replace the existing label with new, excluding background
if index > 0:
img[... | Python | nomic_cornstack_python_v1 |
function export_traces log root
begin
for tr in log
begin
set trace = call SubElement root TAG_TRACE
call export_attributes_element tr trace
call export_traces_events tr trace
end
end function | def export_traces(log, root):
for tr in log:
trace = etree.SubElement(root, xes_util.TAG_TRACE)
export_attributes_element(tr, trace)
export_traces_events(tr, trace) | Python | nomic_cornstack_python_v1 |
function test_create_a_cooperation_for_another_user_is_invalid self
begin
set payload = dict string user id ; string name string Rapped Cooperation ; string project id
set res = post COOPERATION_URL payload
assert equal status_code HTTP_400_BAD_REQUEST
end function | def test_create_a_cooperation_for_another_user_is_invalid(self):
payload = {'user': self.user2.id,
'name': 'Rapped Cooperation',
'project': self.project2.id}
res = self.client.post(COOPERATION_URL, payload)
self.assertEqual(res.status_code, status.HTTP_400_... | Python | nomic_cornstack_python_v1 |
function print_inventory self
begin
for item in _inventory
begin
print item string
end
end function | def print_inventory(self):
for item in self._inventory:
print(item, '\n') | Python | nomic_cornstack_python_v1 |
string 035- Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triangulo
set reta1 = decimal input string Escreva o comprimento da primeira reta:
set reta2 = decimal input string Escreva o comprimento da segunda reta:
set reta3 = decimal input string Escreva o c... | """035- Desenvolva um programa que leia o comprimento
de três retas e diga ao usuário se elas podem ou não formar um triangulo
"""
reta1=float(input('Escreva o comprimento da primeira reta: '))
reta2=float(input('Escreva o comprimento da segunda reta: '))
reta3=float(input('Escreva o comprimento da terceira reta: '))
... | Python | zaydzuhri_stack_edu_python |
import sys
function main number
begin
if number == 0
begin
return string INSOMNIA
end
set answer = set
set current = number
while true
begin
set answer = union answer set string current
if length answer == 10
begin
return string current
end
set current = current + number
end
end function
set T = integer call raw_input | import sys
def main(number):
if number == 0:
return "INSOMNIA"
answer = set()
current = number
while True:
answer = answer.union(set(str(current)))
if len(answer) == 10:
return str(current)
current = current + number
T = int(raw_input()) | Python | zaydzuhri_stack_edu_python |
function test_defaults_with_data self
begin
set return_value = transform MWSSTransformer dict string 40 string 33
assert is instance return_value OrderedDict
assert equal 33 return_value at string 40
assert equal 4 length return_value
end function | def test_defaults_with_data(self):
return_value = MWSSTransformer.transform({"40": "33"})
self.assertIsInstance(return_value, OrderedDict)
self.assertEqual(33, return_value["40"])
self.assertEqual(4, len(return_value)) | Python | nomic_cornstack_python_v1 |
function empty self
begin
if queue is not none and length queue > 0
begin
print string len > 0
return false
end
else
begin
print string len = 0
return true
end
end function | def empty(self) -> bool:
if(self.queue is not None and len(self.queue) > 0):
print("len > 0" )
return False
else:
print("len = 0" )
return True | Python | nomic_cornstack_python_v1 |
from bs4 import BeautifulSoup
import requests
function get_list what
begin
set xlist = list
set page = get requests string https://www.nhs.uk/ + what + string /
set soup = call BeautifulSoup text string html.parser
set name_list = find all soup string a set literal string nhsuk-list-panel__link
for item in name_list
b... | from bs4 import BeautifulSoup
import requests
def get_list(what):
xlist = []
page = requests.get('https://www.nhs.uk/' + what + '/')
soup = BeautifulSoup(page.text, 'html.parser')
name_list = soup.find_all('a', {'nhsuk-list-panel__link'})
for item in name_list:
xlist.append(item.getText().l... | Python | zaydzuhri_stack_edu_python |
function to_accept_without_log x x_new
begin
if x_new > x
begin
return true
end
else
begin
set accept = uniform 0 1
return accept < x_new / x + TOLERANCE
end
end function | def to_accept_without_log(x, x_new):
if x_new>x:
return True
else:
accept=np.random.uniform(0,1)
return (accept < x_new/(x+TOLERANCE)) | Python | nomic_cornstack_python_v1 |
function matrix self data
begin
set matrix_keys = list string cmap string vmin string vmax
set matrix_config = filter keys=matrix_keys prefix=string matrix_
set tuple vmin vmax = call _parse_vrange data
set matrix_config at string vmin = vmin
set matrix_config at string vmax = vmax
set matrix = call matshow data keywor... | def matrix(self, data):
matrix_keys = ['cmap', 'vmin', 'vmax']
matrix_config = self.config.filter(keys=matrix_keys, prefix='matrix_')
vmin, vmax = self._parse_vrange(data)
matrix_config['vmin'] = vmin
matrix_config['vmax'] = vmax
matrix = self.ax.matshow(data, **matrix_... | Python | nomic_cornstack_python_v1 |
from day13.day13.yichang import AgeException
class person
begin
set __name = none
set __age = none
function __init__ self name age
begin
set __name = name
if age > 0
begin
print string 正确!
end
else
begin
raise call AgeException string 年龄输入错误!
end
set __age = age
end function
function setName self name
begin
set __name ... | from day13.day13.yichang import AgeException
class person:
__name = None
__age = None
def __init__(self,name,age):
self.__name = name
if age > 0:
print("正确!")
else:
raise AgeException("年龄输入错误!")
self.__age = age
def setName(self,name):
... | Python | zaydzuhri_stack_edu_python |
string Functions used in preparing Guido's gorgeous lasagna. Learn about Guido, the creator of the Python language: https://en.wikipedia.org/wiki/Guido_van_Rossum
set EXPECTED_BAKE_TIME = 40
set PREPARATION_TIME = 2
function bake_time_remaining elapsed_bake_time
begin
string Calculate the bake time remaining. :param el... | """Functions used in preparing Guido's gorgeous lasagna.
Learn about Guido, the creator of the Python language: https://en.wikipedia.org/wiki/Guido_van_Rossum
"""
EXPECTED_BAKE_TIME = 40
PREPARATION_TIME = 2
def bake_time_remaining(elapsed_bake_time):
"""Calculate the bake time remaining.
:param elapsed_bak... | Python | zaydzuhri_stack_edu_python |
function prec_recall_1d nms_pos_o nms_prob_o gt_pos_o durations detection_overlap win_size remove_eof=true
begin
if remove_eof
begin
comment filter out the detections in both ground truth and predictions that are too
comment close to the end of the file - dont count them during eval
set tuple nms_pos nms_prob gt_pos = ... | def prec_recall_1d(nms_pos_o, nms_prob_o, gt_pos_o, durations, detection_overlap, win_size, remove_eof=True):
if remove_eof:
# filter out the detections in both ground truth and predictions that are too
# close to the end of the file - dont count them during eval
nms_pos, nms_prob, gt_pos =... | Python | nomic_cornstack_python_v1 |
comment ax^2+bx+c
set arg = b ^ 2 - 4 * a * c
if arg < 0 or a == 0
begin
print string Impossivel calcular
end
else
begin
set r1 = - b + arg ^ 1 / 2 / 2 * a
set r2 = - b - arg ^ 1 / 2 / 2 * a
print format string R1 = {:.5f} r1
print format string R2 = {:.5f} r2
end | #ax^2+bx+c
arg = b**2-4*a*c
if arg < 0 or a == 0:
print('Impossivel calcular')
else:
r1 = (-b+(arg)**(1/2))/(2*a)
r2 = (-b-(arg)**(1/2))/(2*a)
print('R1 = {:.5f}'.format(r1))
print('R2 = {:.5f}'.format(r2)) | Python | zaydzuhri_stack_edu_python |
class parent
begin
function first self
begin
print string hello
end function
end class
class child extends parent
begin
function second self
begin
print string hai
end function
end class
set object = call child
first object
call second | class parent:
def first(self):
print("hello")
class child(parent):
def second(self):
print("hai")
object=child()
object.first()
object.second() | Python | zaydzuhri_stack_edu_python |
comment this script implements functions of musicnet input pipeline.
comment IO pipeline is as follows:
comment 1. We start with a list of files and their labels.
comment Files are represented by fileids,
comment and labels are represented by list of start, end, instrument and note.
comment So we have list({fileid,x,in... | # this script implements functions of musicnet input pipeline.
# IO pipeline is as follows:
# 1. We start with a list of files and their labels.
# Files are represented by fileids,
# and labels are represented by list of start, end, instrument and note.
# So we have list({fileid,x,intervaltree[list(start,end,{instru... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: UTF-8 -*-
string 应对任务4进行的开发
import os
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
function lag_analysis i j lag_min lag_max res img_show=false draw_range=string small
begin
string i: 控制参数的序号 j: 生产参数的序号 lag_min: 最小滞后时间 lag_max: 最大滞后时间 res: 数据表 img_show: 是否展示图像, 默认False... | # -*- coding: UTF-8 -*-
"""
应对任务4进行的开发
"""
import os
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
def lag_analysis(i, j, lag_min, lag_max, res, img_show=False, draw_range='small'):
"""
i: 控制参数的序号
j: 生产参数的序号
lag_min: 最小滞后时间
lag_max: 最大滞后时间
res: 数据表
img_show: ... | Python | zaydzuhri_stack_edu_python |
comment Definition for a binary tree node.
class TreeNode extends object
begin
function __init__ self x
begin
set val = x
set left = none
set right = none
end function
end class
comment pay attention to the question requirement. The sum of "leaves" not all left nodes.
class Solution extends object
begin
function sumOfL... | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# pay attention to the question requirement. The sum of "leaves" not all left nodes.
class Solution(object):
def sumOfLeftLeaves(self, root):
... | Python | zaydzuhri_stack_edu_python |
import requests
import datetime
function get_date_number_of_days_ago date
begin
return today - time delta days=date
end function
function get_trending_repositories top_size date
begin
set url = string https://api.github.com/search/repositories
set formated_date = format string {}{} string created:>= date
set parameters... | import requests
import datetime
def get_date_number_of_days_ago(date):
return datetime.date.today() - datetime.timedelta(days=date)
def get_trending_repositories(top_size, date):
url = "https://api.github.com/search/repositories"
formated_date = "{}{}".format("created:>=", date)
parameter... | Python | zaydzuhri_stack_edu_python |
function __post_init__ self
begin
call __post_init__
if type source_format is str
begin
set source_format = format SubmissionContent source_format
end
end function | def __post_init__(self) -> None:
super(SetUploadPackage, self).__post_init__()
if type(self.source_format) is str:
self.source_format = SubmissionContent.Format(self.source_format) | Python | nomic_cornstack_python_v1 |
function download dltype num
begin
comment This function needs refactoring!
comment pylint: disable=R0912
comment pylint: disable=R0914
if browse_mode == string ytpl and dltype in tuple string da string dv
begin
set plid = ytpls at integer num - 1 at string link
call down_plist dltype plid
return
end
else
if browse_mod... | def download(dltype, num):
# This function needs refactoring!
# pylint: disable=R0912
# pylint: disable=R0914
if g.browse_mode == "ytpl" and dltype in ("da", "dv"):
plid = g.ytpls[int(num) - 1]["link"]
down_plist(dltype, plid)
return
elif g.browse_mode == "ytpl":
g.m... | Python | nomic_cornstack_python_v1 |
function merge_sorted_lists list1 list2
begin
set result = list
while length list1 > 0 and length list2 > 0
begin
if list1 at 0 < list2 at 0
begin
append result pop list1 0
end
else
begin
append result pop list2 0
end
end
if length list1 > 0
begin
set result = result + list1
end
else
begin
set result = result + list2
... | def merge_sorted_lists(list1, list2):
result = []
while len(list1) > 0 and len(list2) > 0:
if list1[0] < list2[0]:
result.append(list1.pop(0))
else:
result.append(list2.pop(0))
if len(list1) > 0:
result += list1
else:
result += list2
return result
list1 = [1, 5, 11, 15]
list2 = ... | Python | flytech_python_25k |
function __init__ self board led_number
begin
comment Store a reference to the parent board.
set board = board
comment Store which of the four(?) LEDs we refer to.
comment TODO: Validate this?
set led_number = led_number
end function | def __init__(self, board, led_number):
# Store a reference to the parent board.
self.board = board
# Store which of the four(?) LEDs we refer to.
# TODO: Validate this?
self.led_number = led_number | Python | nomic_cornstack_python_v1 |
function bigramCount myText
begin
set bigrams = list
set words = call wordSplitClean myText
comment note that we need to use enumerate or an index counter to avoid unwanted duplicates
for tuple ndx word in enumerate words at slice : - 1 :
begin
append bigrams tuple words at ndx - 1 words at ndx
end
comment this alter... | def bigramCount(myText):
bigrams = []
words = wordSplitClean(myText)
## note that we need to use enumerate or an index counter to avoid unwanted duplicates
for ndx, word in enumerate(words[:-1]):
bigrams.append((words[ndx-1],words[ndx]))
##this alternative produced duplicates but is com... | Python | nomic_cornstack_python_v1 |
function XY_split train_set test_set
begin
set X_train = iloc at tuple slice : : slice : - 1 :
set Y_train = iloc at tuple slice : : - 1
set X_test = iloc at tuple slice : : slice : - 1 :
set Y_test = iloc at tuple slice : : - 1
return tuple X_train Y_train X_test Y_test
end function | def XY_split(train_set,test_set):
X_train = train_set.iloc[:,:-1]
Y_train = train_set.iloc[:,-1]
X_test = test_set.iloc[:,:-1]
Y_test = test_set.iloc[:,-1]
return X_train, Y_train, X_test, Y_test | Python | nomic_cornstack_python_v1 |
function is_empty message
begin
comment Takes all whitespace characters out of 'message'
set message = join string list comprehension char for char in message if char not in whitespace
comment Convert 'message' to a boolean value and return it
return not boolean message
end function | def is_empty(message):
# Takes all whitespace characters out of 'message'
message = ''.join([char for char in message if char not in string.whitespace])
# Convert 'message' to a boolean value and return it
return not bool(message) | Python | nomic_cornstack_python_v1 |
import openpyxl
import json
set wb = call load_workbook string unis.xlsx
set sheet = worksheets at 0
set year = 2007
set infolist = list
set infodict = dict
for row in range 4 54
begin
set num = 67
for i in range 2007 2018
begin
set infodict at string uni = string value
set infodict at string state = string value
set... | import openpyxl
import json
wb = openpyxl.load_workbook('unis.xlsx')
sheet = wb.worksheets[0]
year = 2007
infolist = []
infodict = {}
for row in range(4, 54):
num = 67
for i in range(2007,2018):
infodict["uni"] = str(sheet['A' + str(row)].value)
infodict["state"] = str(sheet['B' + str(row)].val... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python
comment Richard Park
comment richpk21@gmail.com
comment Olimex Weekend Challenge #20 Anagrams
import re
class Word
begin
function __init__ self text=string
begin
set histogram = dict
set text = text
end function
end class | #!/usr/bin/python
# Richard Park
# richpk21@gmail.com
# Olimex Weekend Challenge #20 Anagrams
import re
class Word:
def __init__(self, text=""):
self.histogram = {}
self.text=text
| Python | zaydzuhri_stack_edu_python |
import os
import json
from tqdm import tqdm
set directory_path = string /home/andrei/Data/Datasets/ScalesDetector/detector-261018/
for file in call tqdm list directory directory_path
begin
if ends with file string .jpg
begin
set image_file = directory_path + file
set json_file = directory_path + file + string .json
set... | import os
import json
from tqdm import tqdm
directory_path = '/home/andrei/Data/Datasets/ScalesDetector/detector-261018/'
for file in tqdm(os.listdir(directory_path)):
if file.endswith('.jpg'):
image_file = directory_path + file
json_file = directory_path + file + ".json"
text_file = direc... | Python | zaydzuhri_stack_edu_python |
function stock_shelve request
begin
if method == string POST
begin
try
begin
set stock_count = get POST string stock_count
set hqlocation = get call checkin headquarters=true
set washlocation = get call checkin washing_location=true
set new_wash_count = call get_estimated_stock - integer stock_count
call create count=n... | def stock_shelve(request):
if request.method == 'POST':
try:
stock_count = request.POST.get('stock_count')
hqlocation = Location.objects.checkin().get(headquarters=True)
washlocation = Location.objects.checkin().get(washing_location=True)
new_wash_count = wash... | Python | nomic_cornstack_python_v1 |
function initCentralUic self
begin
call initFileTableWidget
call initViewerStack
call setSizes list 150 850
end function | def initCentralUic(self):
self.initFileTableWidget()
self.initViewerStack()
self.splitter.setSizes([150, 850]) | Python | nomic_cornstack_python_v1 |
function _dm_handshake_success self
begin
set read_success = true
set return_value = none
try
begin
set file_handle = open string ..\dm\DMcom.out string r
end
except any
begin
comment Try once more:
sleep 1
try
begin
set file_handle = open string ..\dm\DMcom.out string r
end
except any
begin
set read_success = false
en... | def _dm_handshake_success(self):
read_success = True
return_value = None
try:
file_handle = open('..\\dm\\DMcom.out', 'r')
except:
# Try once more:
sleep(1)
try:
file_handle = open('..\\dm\\DMcom.out', 'r')
excep... | Python | nomic_cornstack_python_v1 |
import json
import jieba
set data = read open string D:/Python Codes/igcontext/abc.json string r
comment print (type(data))
set jsload = loads data
comment print (jsload[0]['context'])
print type jsload
print length jsload
set context = list
string for text in range(len(jsload)): seg_list = jieba.cut(jsload[text]['con... | import json
import jieba
data = open( "D:/Python Codes/igcontext/abc.json",'r').read()
#print (type(data))
jsload = json.loads(data)
#print (jsload[0]['context'])
print (type(jsload))
print (len(jsload))
context = []
'''
for text in range(len(jsload)):
seg_list = jieba.cut(jsload[text]['context'].replace('\n',''... | Python | zaydzuhri_stack_edu_python |
function _get_formatted_feature_dependencies data
begin
set conditions = list
for tuple k v in items data
begin
for feature in get v string after list
begin
append conditions dictionary name=k subject=feature ctype=string after
end
if get v string first false
begin
append conditions dictionary name=k subject=none ctype... | def _get_formatted_feature_dependencies(data):
conditions = list()
for k, v in data.items():
for feature in v.get('after', list()):
conditions.append(dict(
name=k,
subject=feature,
ctype='after'
))
if v.get('first', False):
... | Python | nomic_cornstack_python_v1 |
function process_int_instructions int_instructions_original noun verb
begin
comment Reset memory
set int_instructions = copy int_instructions_original
set int_instructions at 1 = noun
set int_instructions at 2 = verb
set i = 0
while i < length int_instructions
begin
set instr = int_instructions at i
set input_pos_1 = i... | def process_int_instructions(int_instructions_original, noun, verb):
int_instructions = int_instructions_original.copy() # Reset memory
int_instructions[1] = noun
int_instructions[2] = verb
i = 0
while i < len(int_instructions):
instr = int_instructions[i]
input_pos_1 = int_instr... | Python | zaydzuhri_stack_edu_python |
import yt_dlp
import csv
import os
string Uses either a list from a csv or from input to download youtube video to MP3 in HQ
comment Debuggers and a custom hook
class MyLogger extends object
begin
function debug self msg
begin
pass
end function
function warning self msg
begin
pass
end function
function error self msg
b... | import yt_dlp
import csv
import os
""" Uses either a list from a csv or from input to download youtube video to MP3 in HQ"""
#Debuggers and a custom hook
class MyLogger(object):
def debug(self, msg):
pass
def warning(self, msg):
pass
def error(self,msg):
print(msg)
def done... | Python | zaydzuhri_stack_edu_python |
class Solution
begin
function hIndex self citations
begin
string :type citations: List[int] :rtype: int
if length citations == 0
begin
return 0
end
set citations = sorted citations
set max_c = 0
for index in range length citations - 1 - 1 - 1
begin
for i in range min length citations citations at index - 1 - 1
begin
if... | class Solution:
def hIndex(self, citations):
"""
:type citations: List[int]
:rtype: int
"""
if len(citations) == 0: return 0
citations = sorted(citations)
max_c = 0
for index in range(len(citations) - 1, -1, -1):
for i in range(min(len(cita... | Python | zaydzuhri_stack_edu_python |
import tensorflow as tf
set digits = call constant list list 3 1 4 1 list list 5 9 2 list 6 list
set words = call constant list list string Bye string now list string thank string you string again string sir
print add tf digits 3
print call reduce_mean digits axis=1
print concat list digits list list 5 3 axis=0
print ... | import tensorflow as tf
digits = tf.ragged.constant([[3, 1, 4, 1], [], [5, 9, 2], [6], []])
words = tf.ragged.constant([["Bye", "now"], ["thank", "you", "again", "sir"]])
print(tf.add(digits, 3))
print(tf.reduce_mean(digits, axis=1))
print(tf.concat([digits, [[5, 3]]], axis=0))
print(tf.tile(digits, [1, 2]))
print(tf... | Python | zaydzuhri_stack_edu_python |
import numpy as np
set randn = randn
import pandas as pd
set s = call Series array range 5 index=list string a string b string c string d string e | import numpy as np
randn = np.random.randn
import pandas as pd
s = pd.Series(np.arange(5), index=['a', 'b', 'c', 'd', 'e']) | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
string Created on Mon Sep 10 09:49:37 2018 @author: oscar
string Checks if the input has balanced parenthesis, brackets and square brackets
function is_balanced string
begin
set arr = list string
set stack = list
set dict = dict string ( string ) ; string [ string ] ; string { string }
fo... | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 10 09:49:37 2018
@author: oscar
"""
"""
Checks if the input has balanced parenthesis, brackets and square brackets
"""
def is_balanced(string):
arr = list(string)
stack = []
dict = {
"(" : ")",
"[" : "]",
"{" : "}"
... | Python | zaydzuhri_stack_edu_python |
function allow_relation self obj1 obj2 **hints
begin
if app_label == string eotrts_student or app_label == string eotrts_student
begin
return true
end
return none
end function | def allow_relation(self, obj1, obj2, **hints):
if obj1._meta.app_label == 'eotrts_student' or \
obj2._meta.app_label == 'eotrts_student':
return True
return None | Python | nomic_cornstack_python_v1 |
comment python package
import csv
import time
import random
import sys
comment selenium package
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.support.ui import WebDriverWait
from selen... | # python package
import csv
import time
import random
import sys
# selenium package
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriv... | Python | zaydzuhri_stack_edu_python |
comment Author: Jake Bringham
import discord
import subprocess as sp
import re
import os
comment Inheritance in Python
class TerrariaClient extends Client
begin
function __init__ self ops
begin
call __init__
set ops = ops
end function
comment This likely isn't perfect but it'll stop the normal user
comment Nitro users ... | # Author: Jake Bringham
import discord
import subprocess as sp
import re
import os
class TerrariaClient(discord.Client): # Inheritance in Python
def __init__(self, ops):
super().__init__()
self.ops = ops
# This likely isn't perfect but it'll stop the normal user
# Nitro users may be able to circumvent by nami... | Python | zaydzuhri_stack_edu_python |
string Created on Jul 30, 2014 This file contains the tasks to retrieve apps from appstores daily. @author: Kristian
from __future__ import absolute_import
from celery import shared_task
from celery.utils.log import get_task_logger
import json , requests
from unidecode import unidecode
from decimal import Decimal
from ... | """
Created on Jul 30, 2014
This file contains the tasks to retrieve apps from appstores daily.
@author: Kristian
"""
from __future__ import absolute_import
from celery import shared_task
from celery.utils.log import get_task_logger
import json, requests
from unidecode import unidecode
from decimal import Decimal
fr... | Python | zaydzuhri_stack_edu_python |
function extractWords filePath
begin
return list comprehension split line at slice : - 1 : string for line in call readFile filePath
end function | def extractWords(filePath):
return [line[:-1].split(' ') for line in readFile(filePath)] | Python | nomic_cornstack_python_v1 |
function unsign_data self data url_safe=true
begin
if url_safe
begin
return call unsign_url_safe data secret_key=secret_key salt=user_salt
end
else
begin
return call unsign_data data secret_key=secret_key salt=user_salt
end
end function | def unsign_data(self, data, url_safe=True):
if url_safe:
return utils.unsign_url_safe(data,
secret_key=self.secret_key,
salt=self.user_salt)
else:
return utils.unsign_data(data,
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
comment version: 0.2
comment -*- coding: utf-8 -*-
comment Author: YeonJoo Oh, Chanel Caratti
comment imported modules
import nltk
from nltk.tokenize import sent_tokenize
import sys
import re
function read_file file_name
begin
with open file_name as f
begin
set token_string = read f
set to... | #!/usr/bin/env python3
#version: 0.2
# -*- coding: utf-8 -*-
#Author: YeonJoo Oh, Chanel Caratti
# imported modules
import nltk
from nltk.tokenize import sent_tokenize
import sys
import re
#######################################################################
def read_file(file_name):
with o... | Python | zaydzuhri_stack_edu_python |
async function bl ctx *args
begin
for member in mentions
begin
set dbmember = call get_db_member db member
for role in call get_db_roles db *ctx.message.role_mentions
begin
set blentry = first filter by filter by query db BlacklistEntry memberid=id roleid=id
if blentry is none
begin
add db call BlacklistEntry roleid=id... | async def bl(ctx, *args):
for member in ctx.message.mentions:
dbmember = get_db_member(db, member)
for role in get_db_roles(db, *ctx.message.role_mentions):
blentry = db.query(BlacklistEntry).filter_by(memberid=dbmember.id).filter_by(roleid=role.id).... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
string This module encompasses everything needed to parse a Tersoff ForceField in the original Format, as well as convert it to the Lammps readable format. ForceField_Tersoff.py author: Tobias Kroll created: 9/1/2020 py version: 3.7
import subprocess
from src.FileReading import FileReadingU... | #!/usr/bin/env python
'''
This module encompasses everything needed to parse a Tersoff ForceField in the original Format,
as well as convert it to the Lammps readable format.
ForceField_Tersoff.py
author: Tobias Kroll
created: 9/1/2020
py version: 3.7
'''
import subprocess
from src.FileReading import FileReadingUtils... | Python | zaydzuhri_stack_edu_python |
function flatten self order=string C defrag=false
begin
if fragmented
begin
if defrag
begin
set out = call empty size dtype order
comment fragmentation index
set k = product shape at slice 1 : : * _capacity - _begin
set out at slice : k : = flat
set out at slice k : : = flat
end
else
begin
set out = flatten view s... | def flatten(self, order='C', defrag=False):
if self.fragmented:
if defrag:
out = empty(self.size, self.dtype, order)
# fragmentation index
k = np.product(self.shape[1:]) * (self._capacity - self._begin)
out[:k] = (self[self._begin:].v... | Python | nomic_cornstack_python_v1 |
function get_create_payment_args self order_number total user language=none description=none profile=none **kwargs
begin
set billingaddress = kwargs at string billingaddress
if not profile
begin
set profile = DOCDATA_PROFILE
end
set shopper_name = call Name first=first_name last=last_name
set bill_to_name = call Name f... | def get_create_payment_args(self, order_number, total, user, language=None, description=None, profile=None, **kwargs):
billingaddress = kwargs['billingaddress']
if not profile:
profile = appsettings.DOCDATA_PROFILE
shopper_name = Name(
first=user.first_name,
... | Python | nomic_cornstack_python_v1 |
function __repr__ self
begin
return string Fact-Sheet: ' { title } '
end function | def __repr__(self):
return f"Fact-Sheet: '{self.title}'" | Python | nomic_cornstack_python_v1 |
function partition_text text
begin
if length text < 3500
begin
yield text
end
else
begin
set text_list = split text string
comment length iterator of current block
set l = 0
comment start position of block
set i = 0
comment end position of block
set j = 0
comment j scans through list of lines from start position i l tr... | def partition_text(text):
if len(text) < 3500:
yield text
else:
text_list = text.split('\n')
l = 0 # length iterator of current block
i = 0 # start position of block
j = 0 # end position of block
# j scans thr... | Python | nomic_cornstack_python_v1 |
function sum_of_positive_integers arr
begin
return sum list comprehension num for num in arr if num > 0
end function | def sum_of_positive_integers(arr):
return sum([num for num in arr if num > 0])
| Python | jtatman_500k |
function update self request pk=none
begin
return call Response dict string http_method string PUT
end function | def update(self, request, pk=None):
return Response({'http_method': 'PUT'}) | 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.