code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function __make_group_by_res self group_name name_list
begin
if group_name not in groups
begin
set res_group = call getChildGrps
set groups = list comprehension res for res in res_groups if name in name_list
set new_group = call Group parent=list id=- 1 type=group_name childs=groups
set groups at group_name = new_grou... | def __make_group_by_res(self, group_name, name_list):
if group_name not in self.groups:
res_group = self.group['Residue'].getChildGrps()
groups = [ res for res in res_groups if res.name in name_list ]
new_group = Group(parent=[], id=-1, type=group_name, childs=groups)
... | Python | nomic_cornstack_python_v1 |
function get_attachment_versions_by_filter self drawer id version=none creator_user_id=none accessor_user_id=none min_access_time=none max_access_time=none min_creation_time=none max_creation_time=none min_modification_time=none max_modification_time=none page=none page_size=none sort_order=none sort_by=none custom_hea... | def get_attachment_versions_by_filter(
self, drawer, id, version=None, creator_user_id=None, accessor_user_id=None, min_access_time=None, max_access_time=None, min_creation_time=None, max_creation_time=None, min_modification_time=None, max_modification_time=None, page=None, page_size=None, sort_order=None, ... | Python | nomic_cornstack_python_v1 |
import sqlite3
function recuperarTodo
begin
set conexion = call connect string AgendaTelefonica.db
set cursor = execute conexion string SELECT codigo,nombre,telefono FROM agenda
print string Orden | Nombres |Telefonos
print string --------------------------------------------
for fila in cursor
begin
print string No. { ... | import sqlite3
def recuperarTodo():
conexion = sqlite3.connect("AgendaTelefonica.db")
cursor = conexion.execute("SELECT codigo,nombre,telefono FROM agenda")
print("Orden | Nombres |Telefonos")
print("--------------------------------------------")
for fila in cursor:
print... | Python | zaydzuhri_stack_edu_python |
function formathtml blocks
begin
set out = list
set headernest = b''
set listnest = list
function escape s
begin
return call escape s true
end function
function openlist start level
begin
if not listnest or listnest at - 1 at 0 != start
begin
append listnest tuple start level
append out b'<%s>\n' % start
end
end func... | def formathtml(blocks):
out = []
headernest = b''
listnest = []
def escape(s):
return url.escape(s, True)
def openlist(start, level):
if not listnest or listnest[-1][0] != start:
listnest.append((start, level))
out.append(b'<%s>\n' % start)
blocks = [b... | Python | nomic_cornstack_python_v1 |
function update self **kwargs
begin
set context = copy call to_dict
set data = dict none context ; none kwargs
call update_transfer data
end function | def update(self, **kwargs):
context = self.to_dict().copy()
data = {**context, **kwargs}
self.client.update_transfer(data) | Python | nomic_cornstack_python_v1 |
function get_sigla self work
begin
string Returns a list of all of the sigla for `work`. :param work: name of work :type work: `str` :rtype: `list` of `str`
return list comprehension call splitext base name path path at 0 for path in glob glob join path _path work string *.txt
end function | def get_sigla(self, work):
"""Returns a list of all of the sigla for `work`.
:param work: name of work
:type work: `str`
:rtype: `list` of `str`
"""
return [os.path.splitext(os.path.basename(path))[0]
for path in glob.glob(os.path.join(self._path, work, ... | Python | jtatman_500k |
function scatter_matrix frame alpha=0.5 figsize=none ax=none grid=false diagonal=string hist marker=string . density_kwds=none hist_kwds=none range_padding=0.05 **kwargs
begin
set plot_backend = call _get_plot_backend string matplotlib
return call scatter_matrix frame=frame alpha=alpha figsize=figsize ax=ax grid=grid d... | def scatter_matrix(
frame: DataFrame,
alpha: float = 0.5,
figsize: tuple[float, float] | None = None,
ax: Axes | None = None,
grid: bool = False,
diagonal: str = "hist",
marker: str = ".",
density_kwds: Mapping[str, Any] | None = None,
hist_kwds: Mapping[str, Any] | None = None,
... | Python | nomic_cornstack_python_v1 |
function lista_roles request
begin
set grupos = all
return call render_to_response string roles/listar_roles.html dict string datos grupos context_instance=call RequestContext request
end function | def lista_roles(request):
grupos = Group.objects.all()
return render_to_response('roles/listar_roles.html', {'datos': grupos}, context_instance=RequestContext(request)) | Python | nomic_cornstack_python_v1 |
function parseSpineXout ofname
begin
comment 0 1 2 3 4 5 6 7 8 9 10 11 12
comment # index AA SS phi1 psi1 P_E P_C P_H phi0 psi0 ASA S_pk S_SS pk_phi pk_psi pkc_phi pkc_ps
comment 1 E C -85.6 141.3 0.0527 0.8784 0.0689 -87.5 143.0 130.5 0.6941 0.4126 -5.0000 5.0000 0.9924 0.2499
set ss = list
set phi = list
set psi = ... | def parseSpineXout(ofname):
# 0 1 2 3 4 5 6 7 8 9 10 11 12
# # index AA SS phi1 psi1 P_E P_C P_H phi0 psi0 ASA S_pk S_SS pk_phi pk_psi pkc_phi pkc_ps
# ... | Python | nomic_cornstack_python_v1 |
comment This code does the following:
comment 1. imports required data
comment 2. Finds statistical results like min., max., etc for the daily exchange rates with respect to USD
comment 3. Finds statistical results like min., max., etc for the log returns of daily exchange rates with respect to USD
comment 4. Finds and... | ############################################################
#This code does the following:
#1. imports required data
#2. Finds statistical results like min., max., etc for the daily exchange rates with respect to USD
#3. Finds statistical results like min., max., etc for the log returns of daily exchange rates with re... | Python | zaydzuhri_stack_edu_python |
set n = 5
comment Create an empty list
set array = list
comment Iterate from 0 to n (inclusive)
for i in range n + 1
begin
comment Check if the number is odd
if i % 2 != 0
begin
comment Convert the number to a string and append it to the array
append array string i
end
end
comment Print the resulting array
print array | n = 5
# Create an empty list
array = []
# Iterate from 0 to n (inclusive)
for i in range(n + 1):
# Check if the number is odd
if i % 2 != 0:
# Convert the number to a string and append it to the array
array.append(str(i))
# Print the resulting array
print(array)
| Python | jtatman_500k |
function del_punc s keep_under=false keep_space=false
begin
set s = call keep_ascii s
set repl = string
set punc = list string !"#$%&'()*+,-./:;<=>?@[\]^`{|}~
if keep_under
begin
append punc string _
end
if not keep_space
begin
append punc string
set repl = string
end
set s = join string list comprehension list i re... | def del_punc(s, keep_under=False, keep_space=False):
s = keep_ascii(s)
repl = ' '
punc = list('!"#$%&\'()*+,-./:;<=>?@[\\]^`{|}~')
if keep_under:
punc.append('_')
if not keep_space:
punc.append(' ')
repl = ''
s = "".join([[i, repl][i in punc] for i in s])
re... | Python | nomic_cornstack_python_v1 |
function square num
begin
return num ^ 2
end function
print call square 2
print call square 3 | def square(num):
return num ** 2
print(square(2))
print(square(3)) | Python | zaydzuhri_stack_edu_python |
function __eq__ self other
begin
if not is instance other IpamsvcAddress
begin
return false
end
return __dict__ == __dict__
end function | def __eq__(self, other):
if not isinstance(other, IpamsvcAddress):
return False
return self.__dict__ == other.__dict__ | Python | nomic_cornstack_python_v1 |
function clean_parent_topic self
begin
set parent_topic = cleaned_data at string parent_topic
if parent_topic and parent_topic
begin
raise call ValidationError string This topic is also a sub-topic. Sub-topics of sub-topics are not allowed.
end
if parent_topic and slug == cleaned_data at string slug
begin
raise call Va... | def clean_parent_topic(self):
parent_topic = self.cleaned_data["parent_topic"]
if parent_topic and parent_topic.parent_topic:
raise forms.ValidationError("This topic is also a sub-topic. "
"Sub-topics of sub-topics are not "
... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
import sys
import cv2
function record
begin
print string writing output.avi
print string press any key to stop recording
set cap = call VideoCapture 0
set fourcc = call VideoWriter_fourcc *'XVID'
set out = call VideoWriter string output.avi fourcc 20.0 tuple 640 480
for i in range 300
begin... | #!/usr/bin/env python
import sys
import cv2
def record():
print("writing output.avi")
print("press any key to stop recording")
cap = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
for i in range(300):
success, ... | Python | zaydzuhri_stack_edu_python |
function _is_valid_job self
begin
for _ in range 10
begin
try
begin
call _get_job_summary
return true
end
except SDKException as excp
begin
if exception_module == string Job and exception_id == string 104
begin
sleep 1.5
continue
end
else
begin
raise excp
end
end
end
return false
end function | def _is_valid_job(self):
for _ in range(10):
try:
self._get_job_summary()
return True
except SDKException as excp:
if excp.exception_module == 'Job' and excp.exception_id == '104':
time.sleep(1.5)
... | Python | nomic_cornstack_python_v1 |
with open string sum.in string r as f_in
begin
set digits = sum list comprehension integer i for i in split read line f_in string
with open string sum.out string w as f_out
begin
write f_out string digits
end
end | with open('sum.in', 'r') as f_in:
digits = sum([int(i) for i in f_in.readline().split(' ')])
with open('sum.out', 'w') as f_out:
f_out.write(str(digits))
| Python | zaydzuhri_stack_edu_python |
function get_minibatch roidb num_classes
begin
set num_images = length roidb
comment Sample random scales to use for each image in this batch
set random_scale_inds = random integer 0 high=length SCALES size=num_images
assert BATCH_SIZE % num_images == 0 msg format string num_images ({}) must divide BATCH_SIZE ({}) num_... | def get_minibatch(roidb, num_classes):
num_images = len(roidb)
# Sample random scales to use for each image in this batch
random_scale_inds = npr.randint(0, high=len(cfg.TRAIN.SCALES),
size=num_images)
assert(cfg.TRAIN.BATCH_SIZE % num_images == 0), \
'num_ima... | Python | nomic_cornstack_python_v1 |
from media import Movie
import fresh_tomatoes
comment Create Toy Story Movie
set toy_story = call Movie string Toy Story string Toys Come to Life string 1995-11-22 string G string http://cdn.collider.com/wp-content/uploads/toy-story-poster1.jpg string https://www.youtube.com/watch?v=KYz2wyBy3kc
comment Create Martian M... | from media import Movie
import fresh_tomatoes
# Create Toy Story Movie
toy_story = Movie(
"Toy Story",
"Toys Come to Life",
"1995-11-22",
"G",
"http://cdn.collider.com/wp-content/uploads/toy-story-poster1.jpg",
"https://www.youtube.com/watch?v=K... | Python | zaydzuhri_stack_edu_python |
import mysql.connector
from api import voicekit
import os
set cnx = call connect user=string joe83830 password=string 123123 host=string 140.113.144.78 database=string DJH
set cursor = call cursor
function create_store_list
begin
set query = string CREATE TABLE IF NOT EXISTS DJH.store_list (storeID INT AUTO_INCREMENT,s... | import mysql.connector
from api import voicekit
import os
cnx = mysql.connector.connect(user='joe83830', password='123123',
host='140.113.144.78',
database='DJH')
cursor = cnx.cursor()
def create_store_list():
query = "CREATE TABLE IF NOT EXISTS DJH.s... | Python | zaydzuhri_stack_edu_python |
from VigenereCracker import VigenereCracker
set filePath = call raw_input string Enter the location of a dictionary:
call readDictionary filePath
set userContinue = true
while userContinue
begin
set codedMessage = call raw_input string Enter a coded message:
set keyLength = call raw_input string Enter a key length:
set... | from VigenereCracker import VigenereCracker
filePath = raw_input('Enter the location of a dictionary:')
VigenereCracker.readDictionary(filePath)
userContinue = True
while userContinue:
codedMessage = raw_input('Enter a coded message:')
keyLength = raw_input('Enter a key length:')
keyLength = int(keyLengt... | Python | zaydzuhri_stack_edu_python |
comment a task: Stadium Seating
comment global constants
set CLASS_A_SEATS = 20
set CLASS_B_SEATS = 15
set CLASS_C_SEATS = 10
comment main function
function main
begin
print string How many tickets were sold?
set countAtickets = integer input string Class A:
set countBtickets = integer input string Class B:
set countCt... | # a task: Stadium Seating
# global constants
CLASS_A_SEATS = 20
CLASS_B_SEATS = 15
CLASS_C_SEATS = 10
# main function
def main():
print('How many tickets were sold?')
countAtickets = int(input('Class A: '))
countBtickets = int(input('Class B: '))
countCtickets = int(input('Class C: '))
incomeAtick... | Python | zaydzuhri_stack_edu_python |
comment Snackdown 2019 is coming! Since Snackdown is a contest of teams with up to two members, everyone is looking for a teammate. There are N contestants (numbered 1 through N) who want to participate in Snackdown; let's denote the skill level of the i-th contestant by Si. These people want to pair up in N/2 teams; e... | #Snackdown 2019 is coming! Since Snackdown is a contest of teams with up to two members, everyone is looking for a teammate. There are N contestants (numbered 1 through N) who want to participate in Snackdown; let's denote the skill level of the i-th contestant by Si. These people want to pair up in N/2 teams; each tea... | Python | zaydzuhri_stack_edu_python |
function RLE S
begin
string 入力をランレングス圧縮したリストを返す. [(value1,length1),(value2,length2),...] Parameters ----------- S:list Examples -------- >>> RLE('aaabbc') [('a', 3), ('b', 2), ('c', 1)]
from itertools import groupby
set res = list comprehension tuple k length list g for tuple k g in group by S
return res
end function
s... | def RLE(S: list) -> list:
'''
入力をランレングス圧縮したリストを返す.
[(value1,length1),(value2,length2),...]
Parameters
-----------
S:list
Examples
--------
>>> RLE('aaabbc')
[('a', 3), ('b', 2), ('c', 1)]
'''
from itertools import groupby
res = [(k, len(list(g))) for k, g in groupby... | Python | zaydzuhri_stack_edu_python |
for c in range 1 501 2
begin
if c % 3 == 0
begin
set s = s + c
set n = n + 1
end
end
print format string São {} numeros multiplos por 3 e impar e sua soma é {} n s | for c in range(1, 501, 2):
if c % 3 == 0:
s += c
n += 1
print("São {} numeros multiplos por 3 e impar e sua soma é {}".format(n, s))
| Python | zaydzuhri_stack_edu_python |
function p_topic_given_document self topic d alpha=0.1
begin
return document_topic_counts at d at topic + alpha / document_lengths at d + nr_topics * alpha
end function | def p_topic_given_document(self, topic, d, alpha=0.1):
return ((self.document_topic_counts[d][topic] + alpha) /
(self.document_lengths[d] + self.nr_topics * alpha)) | Python | nomic_cornstack_python_v1 |
comment do :
comment pip install InstagramApi
comment then change the image path
comment image can be downloaded with wget
comment change the username and pass
comment and finally change the caption variable to tag all the fadders
from InstagramAPI import InstagramAPI
set InstagramAPI = call InstagramAPI string usernam... | #do :
# pip install InstagramApi
# then change the image path
# image can be downloaded with wget
# change the username and pass
# and finally change the caption variable to tag all the fadders
from InstagramAPI import InstagramAPI
InstagramAPI = InstagramAPI("username", "password")
InstagramAPI.log... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment script sends otp to user via whatsapp
comment 3 chances are given to the user to enter correct opt
comment after 3 tries a message is sent to the admin
import pywhatkit
import random
import rospy
from std_msgs.msg import String , Bool
class pswd_gen
begin
function __init__ self
begi... | #!/usr/bin/env python
# script sends otp to user via whatsapp
# 3 chances are given to the user to enter correct opt
# after 3 tries a message is sent to the admin
import pywhatkit
import random
import rospy
from std_msgs.msg import String, Bool
######################################################################... | Python | zaydzuhri_stack_edu_python |
function remove_from_gallery self
begin
string Remove this image from the gallery.
set url = _base_url + format string /3/gallery/{0} id
call _send_request url needs_auth=true method=string DELETE
if is instance self Image
begin
set item = call get_image id
end
else
begin
set item = call get_album id
end
call _change_o... | def remove_from_gallery(self):
"""Remove this image from the gallery."""
url = self._imgur._base_url + "/3/gallery/{0}".format(self.id)
self._imgur._send_request(url, needs_auth=True, method='DELETE')
if isinstance(self, Image):
item = self._imgur.get_image(self.id)
e... | Python | jtatman_500k |
function set_params net concurrency timeout
begin
set set_net = net
if concurrency is none
begin
set set_concurrency = 1
end
else
begin
set set_concurrency = concurrency
end
if timeout is none
begin
set set_timeout = 5.0
end
else
begin
set set_timeout = timeout
end
return tuple set_net set_concurrency set_timeout
end f... | def set_params(net: str, concurrency: int, timeout: float) -> typing.Tuple[str, int, float]:
set_net = net
if concurrency is None:
set_concurrency = 1
else:
set_concurrency = concurrency
if timeout is None:
set_timeout = 5.0
else:
set_timeout = timeout
return (set... | Python | nomic_cornstack_python_v1 |
function get_snapshot_clone_chain self snapshot
begin
debug string get_snapshot_clone_chain starts.
set volume_name = string volume-%s % call safe_encode snapshot at string volume_id
set snap_name = string snapshot-%s % call safe_encode snapshot at string id
set pool_name = rbd_pool
set clone_chain = call _get_full_clo... | def get_snapshot_clone_chain(self, snapshot):
LOG.debug('get_snapshot_clone_chain starts.')
volume_name = 'volume-%s' % \
encodeutils.safe_encode(snapshot["volume_id"])
snap_name = 'snapshot-%s' % encodeutils.safe_encode(snapshot['id'])
pool_name = self.configuratio... | Python | nomic_cornstack_python_v1 |
function set_log_to_file logger filename
begin
call remove_handlers logger
call addHandler call StreamHandler
end function | def set_log_to_file(logger, filename):
remove_handlers(logger)
logger.addHandler(logging.StreamHandler()) | Python | nomic_cornstack_python_v1 |
function westwall self hot normal cold
begin
set wall = normal * ones cols
for i in range integer cols / 2 cols - integer cols / 10
begin
if oven == true
begin
set wall at i = hot
end
else
begin
set wall at i = cold
end
end
return wall
end function | def westwall(self, hot, normal, cold):
wall = normal*np.ones(self.cols)
for i in range(int((self.cols)/2),(self.cols)-int(self.cols/10)):
if self.oven == True:
wall[i] = hot
else:
wall[i] = cold
return wall | Python | nomic_cornstack_python_v1 |
function get_basename cls filename
begin
comment split into (directory, basename)
return split path filename at 1
end function | def get_basename(cls, filename):
# split into (directory, basename)
return os.path.split(filename)[1] | Python | nomic_cornstack_python_v1 |
for i in range 1 inNum + 1
begin
set sumNum = sumNum + i
print i end=string
if i < inNum
begin
print string + end=string
end
end
print string = sumNum | for i in range(1, inNum + 1):
sumNum += i
print(i, end="")
if i < inNum:
print("+", end="")
print(" =", sumNum)
| Python | zaydzuhri_stack_edu_python |
import pygame
from pygame.locals import *
call init
set font = call SysFont string Arial 40
set clock = call Clock
set ancho = 900
set alto = 600
set pantalla = call set_mode tuple ancho alto
string COLORES
set blanco = tuple 255 255 255
set negro = tuple 0 0 0
set rojo = tuple 255 0 0
set verde = tuple 0 255 0
set azu... | import pygame
from pygame.locals import *
pygame.init()
font = pygame.font.SysFont("Arial", 40)
clock = pygame.time.Clock()
ancho = 900
alto = 600
pantalla = pygame.display.set_mode((ancho, alto))
""" COLORES """
blanco = (255, 255, 255)
negro = (0, 0, 0)
rojo = (255, 0, 0)
verde = (0, 255, 0)
azul = (0, 0, 255)
ama... | Python | zaydzuhri_stack_edu_python |
comment vim: set fileencoding=utf-8 :
comment (C) 2017 Guido Guenther <agx@sigxcpu.org>
comment This program is free software; you can redistribute it and/or modify
comment it under the terms of the GNU General Public License as published by
comment the Free Software Foundation; either version 2 of the License, or
comm... | # vim: set fileencoding=utf-8 :
#
# (C) 2017 Guido Guenther <agx@sigxcpu.org>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) a... | Python | zaydzuhri_stack_edu_python |
from __future__ import unicode_literals , print_function , division , absolute_import
from bin.read_mnist import read_num
import numpy as np
import matplotlib.pyplot as plt
function main
begin
set tuple model totals = train
call produce_heatmap model true true
set tuple right wrong = predict model totals true
print str... | from __future__ import unicode_literals, print_function, division, absolute_import
from bin.read_mnist import read_num
import numpy as np
import matplotlib.pyplot as plt
def main():
model, totals = train()
produce_heatmap(model, True, True)
right, wrong = predict(model, totals, True)
print("Accuracy:... | Python | zaydzuhri_stack_edu_python |
comment listas
set lista1 = list 1 2 3 4 5
set lista2 = list string dog string car string ball string apple string cat
for tuple numero nome in zip lista1 lista2
begin
print numero nome
end | #listas
lista1 = [1, 2, 3, 4, 5]
lista2 = ["dog", "car", "ball", "apple", "cat"]
for numero, nome in zip(lista1, lista2):
print (numero, nome)
| Python | zaydzuhri_stack_edu_python |
string Python wrappers around TensorFlow ops. This file is MACHINE GENERATED! Do not edit. Original C++ source file: boosted_trees_ops.cc
import collections as _collections
import six as _six
from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
from tensorflow.python.eager import context as _context
fr... | """Python wrappers around TensorFlow ops.
This file is MACHINE GENERATED! Do not edit.
Original C++ source file: boosted_trees_ops.cc
"""
import collections as _collections
import six as _six
from tensorflow.python import pywrap_tensorflow as _pywrap_tensorflow
from tensorflow.python.eager import context as _context... | Python | jtatman_500k |
function set_up self
begin
comment This test suite IGNORES datastore inconsistency because it is only
comment interested in what content eventually gets into the search index.
comment Consequently, this suite should only contain tests where this
comment assumption is both valid and required. Any other test should use t... | def set_up(self):
# This test suite IGNORES datastore inconsistency because it is only
# interested in what content eventually gets into the search index.
#
# Consequently, this suite should only contain tests where this
# assumption is both valid and required. Any other test sho... | Python | nomic_cornstack_python_v1 |
import pygame as pg
comment from game.model.player import Player
from game.model.desintegrator import Desintegrator
from game.ia import SelecaoNatural
class DefaultLevelIA
begin
string Default Level IA Class who represents the level will be used to traning a IA
function __init__ self
begin
set IA = call SelecaoNatural ... | import pygame as pg
# from game.model.player import Player
from game.model.desintegrator import Desintegrator
from game.ia import SelecaoNatural
class DefaultLevelIA:
"""
Default Level IA Class who represents the level will be used to traning a IA
"""
def __init__(self):
self.IA = SelecaoNatu... | Python | zaydzuhri_stack_edu_python |
comment Getting input from user using while loop
from array import *
set a = array string i list
set n = integer input string Enter number:
set b = 0
while b < n
begin
append a integer input string Enter roll.
set b = b + 1
end
print a
set d = 0
while d < length a
begin
print a at d
set d = d + 1
end | #Getting input from user using while loop
from array import *
a= array('i',[])
n=int(input("Enter number:"))
b=0
while b<n:
a.append(int(input("Enter roll. ")))
b+=1
print(a)
d=0
while d<len(a):
print(a[d])
d+=1 | Python | zaydzuhri_stack_edu_python |
function neff_circ area list_vgm
begin
set psill_tot = 0
for vario in list_vgm
begin
set psill_tot = psill_tot + vario at 2
end
function hcov_sum h
begin
set fn = 0
for vario in list_vgm
begin
set tuple crange model psill = vario
set fn = fn + h * call cov h crange model=model psill=psill
end
return fn
end function
set... | def neff_circ(area: float, list_vgm: list[Union[float, str, float]]) -> float:
psill_tot = 0
for vario in list_vgm:
psill_tot += vario[2]
def hcov_sum(h):
fn = 0
for vario in list_vgm:
crange, model, psill = vario
fn += h*(cov(h, crange, model=model, psill=ps... | Python | nomic_cornstack_python_v1 |
function save_entry self key_lang1 key_lang2
begin
comment To prevent accidental empty entry
if not key_lang1 or not key_lang2
begin
return
end
comment If first entry, initialize new database
if empty
begin
call initialize_db key_lang1 key_lang2
call save_entry key_lang1 key_lang2
end
else
begin
print string Found Data... | def save_entry(self, key_lang1, key_lang2):
if not key_lang1 or not key_lang2: #To prevent accidental empty entry
return
if self.db.empty: #If first entry, initialize new database
self.initialize_db(key_lang1, key_lang2)
self.save_entry(key_lang1, key_lang2)
e... | Python | nomic_cornstack_python_v1 |
function test_ceiling_when_not_provided self
begin
set heightmap = call HeightMap 10 terrain_type=string mountains
set apex = call get_highest_point call get_non_negative_heights
assert equal _CEILING apex + _WALL_VARIANCE
end function | def test_ceiling_when_not_provided(self):
heightmap = HeightMap(10, terrain_type='mountains')
apex = heightmap.get_highest_point(heightmap.get_non_negative_heights())
self.assertEqual(heightmap._CEILING, apex + heightmap._WALL_VARIANCE) | Python | nomic_cornstack_python_v1 |
string Owl challenge Sololearn.com Asks a matrix of numbers and checks if the matrix can be folded horizontally and vertically. Input must be rules of numbers, separated by commas. By: Dick Stada, NL October 2018 TODO: input control
function make_matrix
begin
print string Give a rule of numbers, separated by a comma
se... | '''Owl challenge Sololearn.com
Asks a matrix of numbers
and checks if the matrix can be folded
horizontally and vertically.
Input must be rules of numbers, separated by commas.
By: Dick Stada, NL
October 2018
TODO: input control
'''
def make_matrix():
print("Give a rule of numbers, separa... | Python | zaydzuhri_stack_edu_python |
import json
comment import nested_lookup
from nested_lookup import nested_lookup
from collections import Counter
import re
import math
function name_fixer string
begin
set new = list
set bad_chars = list string string , string . string / string - string ( string ) string : string ' string ;
function checker char
begi... | import json
#import nested_lookup
from nested_lookup import nested_lookup
from collections import Counter
import re
import math
def name_fixer(string):
new = []
bad_chars = [" ",",",".","/","-","(",")",":","'", ";"]
def checker(char):
if char in bad_chars:
return "_"
else:
... | Python | zaydzuhri_stack_edu_python |
import random
class Player
begin
set health = 10
set max_health = 10
set default_damage = 10
set position = list 0 0
function was_hitted self hid
begin
set health = health - hid
end function
function get_clear_position self map
begin
set map_height = length split map string
set map_width = length split map string at 0
... | import random
class Player:
health = 10
max_health = 10
default_damage = 10
position = [0, 0]
def was_hitted(self, hid):
self.health -= hid
def get_clear_position(self, map):
map_height = len(map.split("\n"))
map_width = len(map.split("\n")[0])
while True:
... | Python | zaydzuhri_stack_edu_python |
import xlrd
from Connection.DBConnection import Mongodb
class Person extends object
begin
function __init__ self id arabic_name english_name wikidata_match
begin
set id = id
set arabic_name = arabic_name
set english_name = english_name
set wikidata_match = wikidata_match
end function
function __str__ self
begin
return ... | import xlrd
from Connection.DBConnection import Mongodb
class Person(object):
def __init__(self, id, arabic_name, english_name, wikidata_match):
self.id = id
self.arabic_name = arabic_name
self.english_name = english_name
self.wikidata_match = wikidata_match
def __str__(self):... | Python | zaydzuhri_stack_edu_python |
string Ejercicio 9. Unifique los ejercicios 6 y 7 en un solo programa que te deje elegir al principio cuál de las dos operaciones hacer, o no hacer ninguna. Después de dar el resultado te volverá a ese menú inicial. (Ejercicio 6. Escriba un programa que calcule la cantidad total de segundos a partir de horas, minutos y... | '''Ejercicio 9. Unifique los ejercicios 6 y 7
en un solo programa que te deje elegir al principio
cuál de las dos operaciones hacer, o no hacer ninguna.
Después de dar el resultado te volverá a ese menú inicial.
(Ejercicio 6. Escriba un programa que calcule la cantidad
total de segundos a partir de horas, minutos y se... | Python | zaydzuhri_stack_edu_python |
import random
function dibujar tablero
begin
print string | |
print string + tablero at 7 + string | + tablero at 8 + string | + tablero at 9
print string | |
print string -----------
print string | |
print string + tablero at 4 + string | + tablero at 5 + string | + tablero at 6
print string | |
print string -------... | import random
def dibujar(tablero):
print(' | |')
print(' ' + tablero[7] + ' | ' + tablero[8] + ' | ' + tablero[9])
print(' | |')
print('-----------')
print(' | |')
print(' ' + tablero[4] + ' | ' + tablero[5] + ' | ' + tablero[6])
print(' | |')
print('-----------')
... | Python | zaydzuhri_stack_edu_python |
with open string cats.txt string a as file_object
begin
print string If you want to quit , please entert "q".
while true
begin
set cats_name = input string Please enter your cat's name:
if cats_name == string q
begin
break
end
write file_object cats_name + string
end
end
with open string dogs.txt string a as file_objec... | with open('cats.txt', 'a') as file_object:
print ('If you want to quit , please entert "q".')
while True:
cats_name = input('Please enter your cat\'s name:')
if cats_name == 'q':
break
file_object.write(cats_name + '\n')
with open('dogs.txt', 'a') as file_object:
print (... | Python | zaydzuhri_stack_edu_python |
function mask_annular m bound
begin
set tuple rmin rmax cmin cmax = bound
set m at tuple slice : rmin : slice : : = true
set m at tuple slice rmax : : slice : : = true
set m at tuple slice : : slice : cmin : = true
set m at tuple slice : : slice cmax : : = true
return m
end function | def mask_annular(m, bound):
rmin, rmax, cmin, cmax = bound
m[:rmin,:] = True
m[rmax:,:] = True
m[:,:cmin] = True
m[:,cmax:] = True
return m | Python | nomic_cornstack_python_v1 |
string Created on 28.02.2013 @author: Vladimir
import httplib
set body = string <?xml version="1.0"?> <methodCall> <methodName>phone</methodName> <params> <param> <value><string>555-ITALY</string></value> </param> </params> </methodCall>
set cli = call HTTPConnection string www.pythonchallenge.com
call request string P... | '''
Created on 28.02.2013
@author: Vladimir
'''
import httplib
body = '''<?xml version="1.0"?>
<methodCall>
<methodName>phone</methodName>
<params>
<param>
<value><string>555-ITALY</string></value>
</param>
</params>
</methodCall>'''
cli = httplib.HTTPConnection("www.pythonchallenge.com")
... | Python | zaydzuhri_stack_edu_python |
class Node
begin
function __init__ self val
begin
set val = val
set next = none
end function
function traverse self
begin
set node = self
while node != none
begin
print val
set node = next
end
end function
end class | class Node:
def __init__(self, val):
self.val = val
self.next = None
def traverse(self):
node = self
while node != None:
print(node.val)
node = node.next
| Python | zaydzuhri_stack_edu_python |
comment GISDelaunay.py
comment Created by Daniel Citron on 8/4/11.
comment Copyright (c) 2011 __MyCompanyName__. All rights reserved.
function CorrLength loc land_use binsize=1.0
begin
string (H, L) = CorrLength(loc, land_use), Returns a histogram of nearest neighbor distances loc = locations data; land_use = land use ... | #
# GISDelaunay.py
#
#
# Created by Daniel Citron on 8/4/11.
# Copyright (c) 2011 __MyCompanyName__. All rights reserved.
#
def CorrLength(loc, land_use, binsize = 1.):
"""
(H, L) = CorrLength(loc, land_use),
Returns a histogram of nearest neighbor distances
loc = locations data; land_use... | Python | zaydzuhri_stack_edu_python |
function generate_gaussian_random_number mean=0.0 variance=1.0 size=1
begin
set gaussian_array = call normal mean variance size
return gaussian_array
end function | def generate_gaussian_random_number(mean=0.0, variance=1.0, size=1):
gaussian_array = np.random.normal(mean, variance, size)
return gaussian_array | Python | nomic_cornstack_python_v1 |
function from_midi cls midi_note
begin
string Construct a :class:`Tone` from a MIDI note, which must be an integer in the range 0 to 127. For reference, A4 (`concert A`_ typically used for tuning) is MIDI note #69. .. _concert A: https://en.wikipedia.org/wiki/Concert_pitch
set midi = integer midi_note
if 0 <= midi_note... | def from_midi(cls, midi_note):
"""
Construct a :class:`Tone` from a MIDI note, which must be an integer
in the range 0 to 127. For reference, A4 (`concert A`_ typically used
for tuning) is MIDI note #69.
.. _concert A: https://en.wikipedia.org/wiki/Concert_pitch
"""
... | Python | jtatman_500k |
comment !/usr/bin/env python3
comment coding: utf-8
import re
import argparse
import difflib
set parser = call ArgumentParser
comment parser.add_argument( "STUDENT_FILE", help="担当する学生の学籍番号(\d{10})を改行区切りのtxtファイルでまとめたもの")
call add_argument string ANSWER_FILE help=string 正答例
call add_argument string NOTE_FILE help=string ... | #!/usr/bin/env python3
# coding: utf-8
import re
import argparse
import difflib
parser = argparse.ArgumentParser()
# parser.add_argument( "STUDENT_FILE", help="担当する学生の学籍番号(\d{10})を改行区切りのtxtファイルでまとめたもの")
parser.add_argument("ANSWER_FILE", help="正答例")
parser.add_argument("NOTE_FILE", help="ログファイル。")
parser.add_argu... | Python | zaydzuhri_stack_edu_python |
function Step recurrent_theta state0 inputs
begin
if use_recurrent
begin
del inputs
end
with call name_scope string single_sampler_step
begin
comment Compute logits and states.
set tuple bs_result bs_state1 = call pre_step_callback decoder_theta encoder_outputs call expand_dims ids 1 bs_state num_hyps_per_beam 0
commen... | def Step(recurrent_theta, state0, inputs):
if p.use_recurrent:
del inputs
with tf.name_scope('single_sampler_step'):
# Compute logits and states.
bs_result, bs_state1 = pre_step_callback(
decoder_theta,
recurrent_theta.encoder_outputs,
tf.expand_di... | Python | nomic_cornstack_python_v1 |
function __init__ self thing
begin
set thing = thing
set next_keys = list
set key_dic = dict K_SPACE string ; K_MINUS string - ; K_0 string 0 ; K_1 string 1 ; K_2 string 2 ; K_3 string 3 ; K_4 string 4 ; K_5 string 5 ; K_6 string 6 ; K_7 string W ; K_8 string 8 ; K_9 string 9 ; K_a string A ; K_b string B ; K_c strin... | def __init__(self,thing):
self.thing = thing
self.next_keys = []
self.key_dic = { K_SPACE : " ", K_MINUS : "-",
K_0 : "0", K_1 : "1", K_2 : "2", K_3 : "3", K_4 : "4",
K_5 : "5", K_6 : "6", K_7 : "W", K_8 : "8", K_9 : "9 ",
K... | Python | nomic_cornstack_python_v1 |
from datetime import datetime
from datetime import timedelta
import time
import os
import requests
from bs4 import BeautifulSoup
print call date
comment ultimo dia executado - 2018-06-26
comment laço para percorrer do dia x até data de hoje
comment somar dia
set data_atual = call date - time delta days=2
set data_inici... | from datetime import datetime
from datetime import timedelta
import time
import os
import requests
from bs4 import BeautifulSoup
print (datetime.now().date())
#ultimo dia executado - 2018-06-26
#laço para percorrer do dia x até data de hoje
#somar dia
data_atual = datetime.now().date() - timedelta(days=2)
data_in... | Python | zaydzuhri_stack_edu_python |
function __eq__ self other
begin
if not call data_are_equal attrs attrs
begin
print string here
return false
end
return call data_are_equal components components
end function | def __eq__(self, other):
if not tools.data_are_equal(self.attrs, other.attrs):
print('here')
return False
return tools.data_are_equal(self.components, other.components) | Python | nomic_cornstack_python_v1 |
function contiguous self n_level
begin
set db = dict
comment length for each sample level
set all_sample_len = list comprehension dictionary for _ in range n_level
for tuple k v in items _data
begin
if length v > 0
begin
set sample_len = list comprehension list for _ in range n_level + 1
set db at k = concatenate cal... | def contiguous(self, n_level):
db = {}
# length for each sample level
all_sample_len = [dict() for _ in range(n_level)]
for k, v in self._data.items():
if len(v) > 0:
sample_len = [[] for _ in range((n_level + 1))]
db[k] = np.concatenate(self._... | Python | nomic_cornstack_python_v1 |
import os
from glob import glob
for folder_name in glob join path directory name path absolute path path __file__ string final string *
begin
print string ' + split folder_name string \ at - 1 + string ':'',\
for file_name in list directory folder_name
begin
set original_name = join path directory name path absolute pa... | import os
from glob import glob
for folder_name in glob(os.path.join(os.path.dirname(os.path.abspath(__file__)),"final","*")):
print("'" + folder_name.split("\\")[-1] + "':'',\\")
for file_name in os.listdir(folder_name):
original_name = os.path.join(os.path.dirname(os.path.abspath(__file__)... | Python | zaydzuhri_stack_edu_python |
comment !/bin/python
import sys
function angryChildren k arr
begin
sort arr
set min = arr at k - 1 - arr at 0
for i in range 1 length arr - k + 1
begin
if arr at i + k - 1 - arr at i < min
begin
set min = arr at i + k - 1 - arr at i
end
end
return min
end function
if __name__ == string __main__
begin
set n = integer st... | #!/bin/python
import sys
def angryChildren(k, arr):
arr.sort()
min = arr[k - 1] - arr[0]
for i in range(1, len(arr) - k + 1):
if arr[i + k - 1] - arr[i] < min:
min = arr[i + k - 1] - arr[i]
return min
if __name__ == "__main__":
n = int(raw_input().strip())
k = int(raw... | Python | zaydzuhri_stack_edu_python |
function from_client_secrets_file cls client_secrets_file scopes **kwargs
begin
string Creates a :class:`Flow` instance from a Google client secrets file. Args: client_secrets_file (str): The path to the client secrets .json file. scopes (Sequence[str]): The list of scopes to request during the flow. kwargs: Any additi... | def from_client_secrets_file(cls, client_secrets_file, scopes, **kwargs):
"""Creates a :class:`Flow` instance from a Google client secrets file.
Args:
client_secrets_file (str): The path to the client secrets .json
file.
scopes (Sequence[str]): The list of scopes... | Python | jtatman_500k |
function get_cloudify_version
begin
set cloudify_version = none
comment Loop through each blueprint file.
for blueprint_file in blueprint_list
begin
comment Load the blueprint YAML as a dictionary.
with open blueprint_file string r as stream
begin
try
begin
set blueprint_yaml = call yaml_load stream
end
except YAMLErro... | def get_cloudify_version():
cloudify_version = None
# Loop through each blueprint file.
for blueprint_file in blueprint_list:
# Load the blueprint YAML as a dictionary.
with open(blueprint_file, 'r') as stream:
try:
blueprint_yaml = yaml_load(stream)
... | Python | nomic_cornstack_python_v1 |
function _parse_version version
begin
return split version string . at 0
end function | def _parse_version(version):
return version.split(".")[0] | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python3
import collections
import fractions
import functools
import operator
class FishingGameAnalysis
begin
set FULL_NET = tuple 12 10 10 8 6 4
function __init__ self
begin
set optimal_choices = dict
set net_pdf_memo = dict
set subset_sum_memo = dict
end function
function net_pdf self net
begi... | #!/usr/bin/env python3
import collections
import fractions
import functools
import operator
class FishingGameAnalysis:
FULL_NET = (12, 10, 10, 8, 6, 4)
def __init__(self):
self.optimal_choices = {}
self.net_pdf_memo = {}
self.subset_sum_memo = {}
def net_pdf(self, net):
"... | Python | zaydzuhri_stack_edu_python |
function get_product_quantity_from_cart self index=0
begin
call until call visibility_of_all_elements_located tuple XPATH string //label[contains(text(), 'QTY')]
set quantities = call find_elements_by_xpath string //label[contains(text(), 'QTY')]
if index < 0 or type index != int
begin
set index = 0
end
else
if index >... | def get_product_quantity_from_cart(self, index=0):
WebDriverWait(self.driver, 10).until(EC.visibility_of_all_elements_located \
((By.XPATH, "//label[contains(text(), 'QTY')]")))
quantities = self.driver.find_elements_by_xpath("//label[contains(text(), 'QT... | Python | nomic_cornstack_python_v1 |
import pyshtools
import numpy as np
import fortranformat as ff
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
from os import path
from sys import argv
from copy import deepcopy
from scipy.interpolate import interp1d , RegularGridInterpolator
set n_splines = 21
function read_splines par=string S40RTS
begin
s... | import pyshtools
import numpy as np
import fortranformat as ff
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
from os import path
from sys import argv
from copy import deepcopy
from scipy.interpolate import interp1d,RegularGridInterpolator
n_splines = 21
def read_splines(par='S40RTS'):
'''
Read rad... | Python | zaydzuhri_stack_edu_python |
comment Continued
set alien_color = string green
if alien_color == string green
begin
set message = string You just earned 5 points!
end
else
if alien_color == string yellow
begin
set message = string You just earned 10 points!
end
else
if alien_color == string red
begin
set message = string You just earned 15 points!
... | #Continued
alien_color = 'green'
if alien_color == 'green':
message = 'You just earned 5 points!'
elif alien_color == 'yellow':
message = 'You just earned 10 points!'
elif alien_color == 'red':
message = 'You just earned 15 points!'
print(message) | Python | zaydzuhri_stack_edu_python |
import pytest
from solution import encode
from solution import decode
set tests_encode = list tuple string hello string h2ll4 tuple string How are you today? string H4w 1r2 y45 t4d1y? tuple string This is an encoding test. string Th3s 3s 1n 2nc4d3ng t2st.
decorator call parametrize string st, expected tests_encode
func... | import pytest
from solution import encode
from solution import decode
tests_encode = [
('hello', 'h2ll4'),
('How are you today?', 'H4w 1r2 y45 t4d1y?'),
('This is an encoding test.', 'Th3s 3s 1n 2nc4d3ng t2st.'),
]
@pytest.mark.parametrize(
"st, expected", tests_encode
)
def test_encoding(st, expec... | Python | zaydzuhri_stack_edu_python |
import json
with open string questions.json as json_file
begin
set dump_data = load json json_file
end
comment codigo para exportacao de questoes em csv
set csv = string question, A, B, C, D
for line in dump_data
begin
if line at string text is none
begin
set line at string text = string
end
set question = strip strin... | import json
with open('questions.json') as json_file:
dump_data = json.load(json_file)
#codigo para exportacao de questoes em csv
csv = "question, A, B, C, D\n"
for line in dump_data:
if line['text'] is None:
line['text'] = ''
question = str(line['text']).strip()
question = question.replace('... | Python | zaydzuhri_stack_edu_python |
string author : Ankita Code for using SVM linear kernel for setting up Structure-Property Linkages Input Files : python_50_corr.csv
import os
import numpy as np
import pandas as pd
from scipy import stats
import statsmodels.api as sm
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_sp... | """
author : Ankita
Code for using SVM linear kernel for setting up Structure-Property Linkages
Input Files : python_50_corr.csv
"""
import os
import numpy as np
import pandas as pd
from scipy import stats
import statsmodels.api as sm
from matplotlib import pyplot as plt
from sklearn.model_selection import... | Python | zaydzuhri_stack_edu_python |
function as_dict self
begin
string Serialize the context as a dictionnary from a given request.
set data = dict
if JS_CONTEXT_ENABLED
begin
for context in call RequestContext request
begin
for tuple key value in call iteritems context
begin
if JS_CONTEXT and key not in JS_CONTEXT
begin
continue
end
if JS_CONTEXT_EXCLU... | def as_dict(self):
'''
Serialize the context as a dictionnary from a given request.
'''
data = {}
if settings.JS_CONTEXT_ENABLED:
for context in RequestContext(self.request):
for key, value in six.iteritems(context):
if settings.JS_... | Python | jtatman_500k |
import re
set text = string
for _ in range integer input
begin
set text = text + input + string
end
for _ in range integer input
begin
set uk_spelling = input
set uk_us_spelling = sub string our string ou?r uk_spelling
set regex = string \b + uk_us_spelling + string \b
print length find all regex text
end | import re
text = ''
for _ in range(int(input())):
text += input() + '\n'
for _ in range(int(input())):
uk_spelling = input()
uk_us_spelling = re.sub('our', 'ou?r', uk_spelling)
regex = r'\b' + uk_us_spelling + r'\b'
print(len(re.findall(regex, text)))
| Python | zaydzuhri_stack_edu_python |
function process_own_command self value parameter measure
begin
comment Generic commands
if parameter is none and measure is none
begin
comment Publish status
if value == value
begin
call publish_status
end
comment Reset status
if value == value
begin
set period = none
set log = string Device reset
warning log
end
end
... | def process_own_command(self,
value: str,
parameter: Optional[str],
measure: Optional[str]) -> NoReturn:
# Generic commands
if parameter is None and measure is None:
# Publish status
if value == m... | Python | nomic_cornstack_python_v1 |
comment Modulo
from tkinter import *
comment Aba
set aba = call Tk
comment Title
title aba string Fill
comment Geometry
call geometry string 400x400+100+100
comment Background
set aba at string bg = string Black
comment Label
set lb1 = call Label aba text=string LB1 bg=string white
set lb2 = call Label aba text=string ... | #Modulo
from tkinter import *
#Aba
aba = Tk()
#Title
aba.title('Fill')
#Geometry
aba.geometry('400x400+100+100')
#Background
aba['bg'] = "Black"
#Label
lb1 = Label(aba, text="LB1", bg="white")
lb2 = Label(aba, text="LB2", bg="red")
lb3 = Label(aba, text="LB3", bg="yellow")
lb4 = Label(aba, text="LB4", bg="blue")
... | Python | zaydzuhri_stack_edu_python |
from gensim.models import Word2Vec
from gensim.models.callbacks import CallbackAny2Vec
from tqdm import tqdm
import allfname as fn
class callback extends CallbackAny2Vec
begin
string Callback to print loss after each epoch.
function __init__ self
begin
set epoch = 0
set loss_to_be_subed = 0
end function
function on_epo... | from gensim.models import Word2Vec
from gensim.models.callbacks import CallbackAny2Vec
from tqdm import tqdm
import allfname as fn
class callback(CallbackAny2Vec):
"""Callback to print loss after each epoch."""
def __init__(self):
self.epoch = 0
self.loss_to_be_subed = 0
def o... | Python | zaydzuhri_stack_edu_python |
function device_state_attributes self
begin
set attr = dict string interface_type interface_type
return attr
end function | def device_state_attributes(self) -> Dict[str, Any]:
attr = {"interface_type": self._device.interface_type}
return attr | Python | nomic_cornstack_python_v1 |
import math
import random
import copy
import time
import sys
string Point class. property of xPos and yPos represent the coordinate of pick up and drop off positions, id, identify which package it belongs
class Point
begin
function __init__ self
begin
set xPos = 0
set yPos = 0
set id = 0
end function
function getParren... | import math
import random
import copy
import time
import sys
'''
Point class. property of xPos and yPos represent the coordinate of pick up and drop off positions, id, identify which package
it belongs
'''
class Point:
def __init__(self):
self.xPos = 0
self.yPos = 0
self.id = 0
def get... | Python | zaydzuhri_stack_edu_python |
function prepare_outputs self job
begin
string Called before job is started. If output is a `FileSystemTarget`, create parent directories so the hive command won't fail
set outputs = flatten call output
for o in outputs
begin
if is instance o FileSystemTarget
begin
set parent_dir = directory name path path
if parent_di... | def prepare_outputs(self, job):
"""
Called before job is started.
If output is a `FileSystemTarget`, create parent directories so the hive command won't fail
"""
outputs = flatten(job.output())
for o in outputs:
if isinstance(o, FileSystemTarget):
... | Python | jtatman_500k |
comment 24 March 2014
comment Jaren Hendricks
comment Program to print a frame around a message
function main
begin
set message = input string Enter the message:
set count = eval input string Enter the message repeat count:
set frame = eval input string Enter the frame thickness:
set message = string + message + strin... | # 24 March 2014
# Jaren Hendricks
# Program to print a frame around a message
def main():
message = input("Enter the message:\n")
count = eval(input("Enter the message repeat count:\n"))
frame = eval(input("Enter the frame thickness:\n"))
message = " "+message+" "
lentop= len(message)
... | Python | zaydzuhri_stack_edu_python |
comment coding=utf-8
string 正则表达式匹配 请实现一个函数用来匹配包含'. '和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(含0次)。在本题中,匹配是指字符串的所有字符匹配整个模式。 定义一个二维数组dp,dp[i][j]表示s的前i个字符和p的前j个字符是匹配的 dp[i][j]的计算方式如下 首先设置dp[0][0]为true,因为两个空字符是匹配的 如果i = 0, 那么表示以空字符串去匹配p的前j个字符,我们期望p[j] == , 这样之前的字符不用出现,dp[i][j] = p[j] == * and dp[i][j-2] 如果s[i] == ... | # coding=utf-8
"""
正则表达式匹配
请实现一个函数用来匹配包含'. '和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(含0次)。在本题中,匹配是指字符串的所有字符匹配整个模式。
定义一个二维数组dp,dp[i][j]表示s的前i个字符和p的前j个字符是匹配的
dp[i][j]的计算方式如下
首先设置dp[0][0]为true,因为两个空字符是匹配的
如果i = 0, 那么表示以空字符串去匹配p的前j个字符,我们期望p[j] == , 这样之前的字符不用出现,dp[i][j] = p[j] == * and dp[i][j-2]
如果s[i] == p[j]那么,直... | Python | zaydzuhri_stack_edu_python |
from kivy.uix.label import Label
from kivy.properties import ListProperty , ObservableList
from kivy.factory import Factory
from kivy.lang import Builder
from kivy.graphics import Color , Rectangle , Line
comment Builder.load_string(f"""
comment <LabelX>:
comment bcolor: 1, 1, 1, 1
comment canvas.before:
comment Color:... | from kivy.uix.label import Label
from kivy.properties import ListProperty, ObservableList
from kivy.factory import Factory
from kivy.lang import Builder
from kivy.graphics import Color, Rectangle, Line
# Builder.load_string(f"""
# <LabelX>:
# bcolor: 1, 1, 1, 1
# canvas.before:
# Color:
# rgba: 1, 0, 0, ... | Python | zaydzuhri_stack_edu_python |
for tuple i v in enumerate map int split input
begin
set k = k - min 8 s + v
set s = s + v - min 8 s + v
if k <= 0
begin
print i + 1
exit
end
end
print - 1 | for i, v in enumerate(map(int, input().split())):
k -= min(8, s + v)
s += v - min(8, s + v)
if k <= 0:
print(i + 1)
exit()
print(-1)
| Python | zaydzuhri_stack_edu_python |
string Don't Throw Out That Winter Coat Yet Finally, you will forecast the temperature over the next 30 years using an ARMA(1,1) model, including confidence bands around that estimate. Keep in mind that the estimate of the drift will have a much bigger impact on long range forecasts than the ARMA parameters. Earlier, y... | '''
Don't Throw Out That Winter Coat Yet
Finally, you will forecast the temperature over the next 30 years using an ARMA(1,1) model, including confidence bands around that estimate. Keep in mind that the estimate of the drift will have a much bigger impact on long range forecasts than the ARMA parameters.
Earlier, yo... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
comment coding: utf-8
comment In[4]:
import numpy as np
from scipy.optimize import minimize
comment In[5]:
function objective x
begin
set x1 = x at 0
set x2 = x at 1
set x3 = x at 2
set x4 = x at 3
return x1 * x4 * x1 + x2 + x3 + x3
end function
function constraint1 x
begin
return x at 0 * ... | #!/usr/bin/env python
# coding: utf-8
# In[4]:
import numpy as np
from scipy.optimize import minimize
# In[5]:
def objective(x):
x1 = x[0]
x2 = x[1]
x3 = x[2]
x4 = x[3]
return x1 * x4 * (x1 + x2 + x3) + x3
def constraint1(x):
return x[0] * x[1] * x[2] * x[3] - 25.0
def constraint2(x):... | Python | zaydzuhri_stack_edu_python |
import unittest
comment from app import create_app, db
from app.main_app import create_app , db
from base import BaseTestCase
class UsersModelTestCase extends BaseTestCase
begin
string Testcase for the users model
function test_valid_user_registration self
begin
string Test for a user registration
set response = call u... | import unittest
# from app import create_app, db
from app.main_app import create_app, db
from base import BaseTestCase
class UsersModelTestCase(BaseTestCase):
'''Testcase for the users model'''
def test_valid_user_registration(self):
'''Test for a user registration'''
response = self.user_r... | Python | zaydzuhri_stack_edu_python |
import matplotlib
call use string Agg
import sqlite3
from datetime import date , datetime , timedelta
comment Graph curselection
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from dateutil import parser
from matplotlib import style
call use string fivethirtyeight
function connect
begin
set conn = ca... | import matplotlib
matplotlib.use('Agg')
import sqlite3
from datetime import date,datetime,timedelta
# Graph curselection
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from dateutil import parser
from matplotlib import style
style.use('fivethirtyeight')
def connect():
conn=sqlite3.... | Python | zaydzuhri_stack_edu_python |
from collections import Counter
import re
function count_words sentence
begin
set answer = lower sentence
set answer = split re string [\s,.?!&@$%^&:_] answer
set answer = generator expression x for x in answer if x is not string
set answer = generator expression strip a string ' for a in answer
return counter answer
... | from collections import Counter
import re
def count_words(sentence):
answer = sentence.lower()
answer = re.split('[\s,.?!&@$%^&:_]', answer)
answer = (x for x in answer if x is not '')
answer = (a.strip("'") for a in answer)
return Counter(answer)
| Python | zaydzuhri_stack_edu_python |
function set_params self **params
begin
comment Need to override the params to set max depth
comment Need to export visualization
set depth_threshold = params at string max_depth
set params at string max_depth = none
return call set_params keyword params
end function | def set_params(self, **params):
#### Need to override the params to set max depth
#### Need to export visualization
self.depth_threshold = params['max_depth']
params['max_depth'] = None
return self.learner().set_params(**params) | Python | nomic_cornstack_python_v1 |
from funcoesJSON import *
set inventario = call ler_arquivo string inventario_json.json
set opcao = call chamarMenu
while opcao > 0 and opcao < 3
begin
if opcao == 1
begin
print call registrar inventario string inventario_json.json
end
else
if opcao == 2
begin
call exibir string inventario_json.json
end
set opcao = cal... | from funcoesJSON import *
inventario = ler_arquivo("inventario_json.json")
opcao = chamarMenu()
while opcao > 0 and opcao < 3:
if opcao == 1:
print(registrar(inventario, "inventario_json.json"))
elif opcao == 2:
exibir("inventario_json.json")
opcao = chamarMenu()
"""
Pronto, agora temos o ... | Python | zaydzuhri_stack_edu_python |
function getEventFilterFormByID request tuningID
begin
set logger = call getLogger __name__
set context = dict
set context at string edit = true
try
begin
comment Get a complete list of sensors.
set context at string allsensors = all
end
except DoesNotExist
begin
warning string No sensors found.
raise Http404
end
try
... | def getEventFilterFormByID(request, tuningID):
logger = logging.getLogger(__name__)
context = {}
context['edit'] = True
try:
# Get a complete list of sensors.
context['allsensors'] = Sensor.objects.all()
except Sensor.DoesNotExist:
logger.warning("No sensors found.")
raise Http404
try:
# Get... | Python | nomic_cornstack_python_v1 |
function add_mobile_task
begin
comment mount task object
set mobile_task_form = json
set session = call Session
set user = first filter username == mobile_task_form at string task at string user at string username
set task = call Task id mobile_task_form at string task at string name mobile_task_form at string task at ... | def add_mobile_task():
# mount task object
mobile_task_form = f.request.json
session = Session()
user = \
session.query(User).filter(User.username ==
mobile_task_form['task']['user']['username']).first()
task = Task(user.id, mobile_task_form['task']['name'... | Python | nomic_cornstack_python_v1 |
import datetime
function validate_age age
begin
try
begin
comment Handle textual representations of age
if is instance age str
begin
set age = call parse_age_text age
end
comment Check if age is within the specified range
if not 18 <= age <= 65
begin
return false
end
comment Check if age is negative or exceeds maximum ... | import datetime
def validate_age(age):
try:
# Handle textual representations of age
if isinstance(age, str):
age = parse_age_text(age)
# Check if age is within the specified range
if not (18 <= age <= 65):
return False
# Check if age... | Python | jtatman_500k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.