code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
comment Module - File Handling for the Bot
import random
comment Function: Retrieve the Previous ID
function RetrieveID FileName
begin
set ReadPreviousID = open FileName string r
comment Use .strip() to ensure it's only the numeric ID value stored
set PreviousID = integer strip read ReadPreviousID
close ReadPreviousID
... | # Module - File Handling for the Bot
import random
# Function: Retrieve the Previous ID
def RetrieveID (FileName):
ReadPreviousID = open(FileName, "r")
#Use .strip() to ensure it's only the numeric ID value stored
PreviousID = int(ReadPreviousID.read().strip())
ReadPreviousID.close(... | Python | zaydzuhri_stack_edu_python |
comment coding:utf8
import itertools
from optparse import OptionParser
comment itertools.permutations(arr)
comment itertools.combinations(arr)
comment itertools.product(arr,[2,1])
function get_input
begin
set usage = decode string python grouping_set.py -i "platform,province_id#province_name>city_id#city_name,item_id#i... | #coding:utf8
import itertools
from optparse import OptionParser
# itertools.permutations(arr)
# itertools.combinations(arr)
# itertools.product(arr,[2,1])
def get_input():
usage= """
python grouping_set.py -i "platform,province_id#province_name>city_id#city_name,item_id#item_name,factory_id#factory_name, brand_... | Python | zaydzuhri_stack_edu_python |
string Read content of tables
from pg_manager import Database
from models import SQLShowRequest
import re
from cli_helpers.tabular_output import TabularOutputFormatter
class Reader
begin
string Read records from tables
set MATCH_MEMORY = compile string ^<memory at .*>
function __init__ self table inline=false
begin
set... | """Read content of tables"""
from pg_manager import Database
from models import SQLShowRequest
import re
from cli_helpers.tabular_output import TabularOutputFormatter
class Reader:
"""Read records from tables"""
MATCH_MEMORY = re.compile(r'^<memory at .*>')
def __init__(self, table, inline=False):
... | Python | zaydzuhri_stack_edu_python |
function getStatPerEighty self stat
begin
set statValue = call getStat stat
if statValue is not none
begin
set statValue = decimal statValue * 80.0 / decimal minutesPlayed
end
return statValue
end function | def getStatPerEighty(self, stat):
statValue = self.getStat(stat)
if statValue is not None:
statValue = float(statValue) * (80.0/float(self.minutesPlayed))
return statValue | Python | nomic_cornstack_python_v1 |
comment Import necessary packages for csv generartion
import matplotlib.pyplot as plt
import pandas as pd
import h5py
import numpy as np
import os
import glob
set scale_x = 1e-09
set title = list
set time_window = 3e-09
for files in glob glob string Documents/*.out
begin
set f = call File files
comment this base conta... | # Import necessary packages for csv generartion
import matplotlib.pyplot as plt
import pandas as pd
import h5py
import numpy as np
import os
import glob
scale_x = 1e-9
title = []
time_window = 3e-9
for files in glob.glob("Documents/*.out"):
f = h5py.File(files)
base = os.path.basename(files) # this base cont... | Python | zaydzuhri_stack_edu_python |
function CountSpikes brainname rn thresh=28.0
begin
if brainname == string
begin
set fn = rn
end
else
begin
set fn = brainname + TXTSEP + rn + string .txt
end
set f = open fn
set sp = list
set l = read line f
set d = split l
set d = d at slice 1 : :
for v in d
begin
set v = decimal v
if v > thresh
begin
append sp 1... | def CountSpikes(brainname, rn, thresh=28.0):
if brainname=="":
fn=rn
else:
fn=brainname+TXTSEP+rn+".txt"
f=open(fn)
sp=[]
l=f.readline()
d=l.split()
d=d[1:]
for v in d:
v=float(v)
if v > thresh:
sp.append(1)
else:
sp.append(... | Python | nomic_cornstack_python_v1 |
import numpy as np
from scipy.integrate import romberg
import math
import matplotlib.pyplot as plt
function f x
begin
return sin x * x + 1 * power e - power x 2
end function
set precision = 1e-08
set init = 0
set bound_1 = - 100
set bound_2 = 100
comment Znajdowanie górnej granicy całkowania
while true
begin
set init =... | import numpy as np
from scipy.integrate import romberg
import math
import matplotlib.pyplot as plt
def f(x):
return math.sin(x*(x+1))*pow(math.e,-pow(x,2))
precision = 1.0e-8
init = 0
bound_1 = -100
bound_2 = 100
#Znajdowanie górnej granicy całkowania
while True:
init = pow(math.e,-pow(bound_2,2))
if in... | Python | zaydzuhri_stack_edu_python |
from student import Student
from nss_person import NSSPerson
class Instructor extends Student NSSPerson
begin
function __init__ self first last slack cohort specialty
begin
call __init__ first last slack cohort
set specialty = specialty
end function
function set_exercises self student exercises
begin
extend exercises e... | from student import Student
from nss_person import NSSPerson
class Instructor(Student, NSSPerson):
def __init__(self, first, last, slack, cohort, specialty):
super().__init__(first, last, slack, cohort)
self.specialty = specialty
def set_exercises(self, student, exercises):
student.ex... | Python | zaydzuhri_stack_edu_python |
comment 66 Set.clear()
set cities = set literal string Taipei string Tokyo string New York
print cities string sep=string
clear cities
print cities string sep=string | #66 Set.clear()
cities = {'Taipei', 'Tokyo','New York'}
print(cities,'\n',sep="")
cities.clear()
print(cities,'\n',sep="")
| Python | zaydzuhri_stack_edu_python |
function leave self
begin
set p = call GameOverPopup self
open
end function | def leave(self):
p = GameOverPopup(self)
p.open() | Python | nomic_cornstack_python_v1 |
import json
comment import time
comment import matplotlib.pyplot as plt
comment import numpy as np
comment import networkx as nx
comment from serial_rw import Serial
comment class NodeMapping:
comment meshTopo = """[
comment {
comment "nodeId" : 2147321731,
comment "subs" : [
comment {
comment "nodeId" : 2147319552,
co... | import json
# import time
# import matplotlib.pyplot as plt
# import numpy as np
# import networkx as nx
#
# from serial_rw import Serial
# class NodeMapping:
#
# meshTopo = """[
# {
# "nodeId" : 2147321731,
# "subs" : [
# {
# "nodeId" : 2147319552,
# ... | Python | zaydzuhri_stack_edu_python |
function categorize_columns DbClass
begin
set copy_vals = list
set set_vals = dict
for col in keys columns
begin
comment never copy the id
if col == string id
begin
continue
end
set to_copy = input string Would you like to copy values of { col } to from src to dest DB? (y/n):
if lower to_copy == string y
begin
append... | def categorize_columns(DbClass):
copy_vals = []
set_vals = {}
for col in DbClass.__table__.columns.keys():
# never copy the id
if col == "id":
continue
to_copy = input(
f"Would you like to copy values of {col} to from src to dest DB? (y/n): "
)
... | Python | nomic_cornstack_python_v1 |
function write_mt self msg
begin
if protocol_debug is true
begin
debug format string write-que-entry {} msg
end
put msg
end function | def write_mt(self, msg):
if self.protocol_debug is True:
self.log.debug('write-que-entry {}'.format(msg))
self.wrque.put(msg) | Python | nomic_cornstack_python_v1 |
function extract_colors image palette_size=5 resize=true mode=string KM sort_mode=none
begin
comment open the image
set img = call convert string RGB
if resize
begin
set img = call resize tuple 256 256
end
set tuple width height = size
set arr = call asarray img
if mode is string KM
begin
set colors = call k_means_extr... | def extract_colors(image, palette_size=5, resize=True, mode="KM", sort_mode=None):
# open the image
img = Image.open(image).convert("RGB")
if resize:
img = img.resize((256, 256))
width, height = img.size
arr = np.asarray(img)
if mode is "KM":
colors = k_means_extraction(arr, he... | Python | nomic_cornstack_python_v1 |
comment Travis Dean - tjd2qj
comment CS 3240 Homework 1
from item import Item
from collections import Counter
set __author__ = string Travis Dean
set debug = false
function prompt
begin
set k = integer call raw_input string Enter the value of k:
set m = integer call raw_input string Enter the number of values to be rea... | # Travis Dean - tjd2qj
# CS 3240 Homework 1
from item import Item
from collections import Counter
__author__ = 'Travis Dean'
debug = False
def prompt():
k = int(raw_input("Enter the value of k: "))
m = int(raw_input("Enter the number of values to be read: "))
filename = raw_input("Data file name: ")
#... | Python | zaydzuhri_stack_edu_python |
comment for step in txt: potem po wcięciu print("-", step)
set txt = string input string podaj słowo:
for letter in txt
begin
print string - letter
end
set names = list string Ada string Julia string Ruby
for e in range length names
begin
print string id: e string name: names at e
end | #for step in txt: potem po wcięciu print("-", step)
txt = str(input("podaj słowo: "))
for letter in txt:
print("-", letter)
names = ["Ada", "Julia", "Ruby"]
for e in range(len(names)):
print("id:", e, "name:", names[e]) | Python | zaydzuhri_stack_edu_python |
function _resolve_value self name
begin
string Returns an appropriate value for the given name.
set name = string name
if name in elements
begin
set element = elements at name
comment Look in instances for an explicit value
if editable
begin
set value = get attribute self name
if value
begin
return value
end
end
commen... | def _resolve_value(self, name):
""" Returns an appropriate value for the given name. """
name = str(name)
if name in self._metadata._meta.elements:
element = self._metadata._meta.elements[name]
# Look in instances for an explicit value
if element.editable:
... | Python | jtatman_500k |
function remove_extra_empty_lines self input_model
begin
string Removes superfluous newlines from a YANG model that was extracted from a draft or RFC text. Newlines are removed whenever 2 or more consecutive empty lines are found in the model. This function is a part of the model post-processing pipeline. :param input_... | def remove_extra_empty_lines(self, input_model):
"""
Removes superfluous newlines from a YANG model that was extracted
from a draft or RFC text. Newlines are removed whenever 2 or more
consecutive empty lines are found in the model. This function is a
part of the model post-proce... | Python | jtatman_500k |
function getMD5ChallengeResponse username realm password method uri nonce
begin
set _tmp1 = hex digest call new string %s:%s:%s % tuple username realm password
set _tmp2 = hex digest call new string %s:%s % tuple method uri
return hex digest call new string %s:%s:%s % tuple _tmp1 nonce _tmp2
end function | def getMD5ChallengeResponse(username,
realm,
password,
method,
uri,
nonce
):
_tmp1 = md5.new('%s:%s:%s' %(username,realm,password)).hexdigest... | Python | nomic_cornstack_python_v1 |
function inet_pton af ip_string
begin
if af == AF_INET
begin
comment IPv4.
return call _inet_pton_af_inet ip_string
end
else
if af == AF_INET6
begin
set invalid_addr = call ValueError string illegal IP address string %r % ip_string
comment IPv6.
set values = list
if not call _is_str ip_string
begin
raise invalid_addr
... | def inet_pton(af, ip_string):
if af == AF_INET:
# IPv4.
return _inet_pton_af_inet(ip_string)
elif af == AF_INET6:
invalid_addr = ValueError('illegal IP address string %r' % ip_string)
# IPv6.
values = []
if not _is_str(ip_string):
raise ... | Python | nomic_cornstack_python_v1 |
import mla_MultiPipe.mla_file_utils.mla_Multi_import_utils as Miu
import re
call reload Miu
set application = call get_application
if application == string Maya
begin
import mla_MayaPipe.mla_Maya_general_utils.mla_general_utils as gu
end
else
if application == string Max
begin
comment TODO : create this one!!!!!!!!!!!!... | import mla_MultiPipe.mla_file_utils.mla_Multi_import_utils as Miu
import re
reload(Miu)
application = Miu.get_application()
if application == 'Maya':
import mla_MayaPipe.mla_Maya_general_utils.mla_general_utils as gu
elif application == 'Max':
# TODO : create this one!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
import ... | Python | zaydzuhri_stack_edu_python |
import os
from subprocess import call
from nltk.util import ngrams
from Analysis import Evaluation
from math import log
from numpy import linalg , array
class NaiveBayesText extends Evaluation
begin
function __init__ self smoothing bigrams trigrams discard_closed_class smoothing_constant=1 no_unigrams=false
begin
strin... | import os
from subprocess import call
from nltk.util import ngrams
from Analysis import Evaluation
from math import log
from numpy import linalg, array
class NaiveBayesText(Evaluation):
def __init__(self,smoothing,bigrams,trigrams,discard_closed_class,smoothing_constant=1,no_unigrams=False):
"""
... | Python | zaydzuhri_stack_edu_python |
from modules.utils import *
from matplotlib.ticker import LinearLocator , FormatStrFormatter
from matplotlib import cm
print string Plotting surfaces...
comment -----------------------------------------------------dd--
comment Surface random
comment -----------------------------------------------------dd--
set fs1 = fi... | from modules.utils import *
from matplotlib.ticker import LinearLocator, FormatStrFormatter
from matplotlib import cm
print("Plotting surfaces...")
# -----------------------------------------------------dd--
# Surface random
# -----------------------------------------------------dd--
fs1 = p.figure()
fs1_ax = fs1.a... | Python | zaydzuhri_stack_edu_python |
from bs4 import BeautifulSoup
from decimal import Decimal
import re
function convert amount cur_from cur_to date requests
begin
comment Использовать переданный requests
set response = get requests string https://www.cbr.ru/scripts/XML_daily.asp?date_req= { date }
set base = call BeautifulSoup content string xml
set cur... | from bs4 import BeautifulSoup
from decimal import Decimal
import re
def convert(amount, cur_from, cur_to, date, requests):
response = requests.get(f'https://www.cbr.ru/scripts/XML_daily.asp?date_req={date}') # Использовать переданный requests
base = BeautifulSoup(response.content, "xml")
curs2 = float(re.s... | Python | zaydzuhri_stack_edu_python |
import os
set class_name = input string What component would you like to add?
set source_dir = string ..\Source\Logic\Components\
set target_dir = input string Which directory should it live in?
set target_dir = source_dir + target_dir
set clean_target_dir = strip target_dir string
set clean_class = strip class_name st... | import os
class_name = input('What component would you like to add?\n')
source_dir = '..\\Source\\Logic\\Components\\'
target_dir = input('Which directory should it live in?\n')
target_dir = source_dir + target_dir
clean_target_dir = target_dir.strip('\r')
clean_class = class_name.strip('\r')
create_class = True
di... | Python | zaydzuhri_stack_edu_python |
import os
import json
from glob import glob
import numpy as np
import seaborn as sns
import scipy.io as sio
import tensorflow.compat.v1 as tf
import matplotlib.pyplot as plt
from tensorflow.python.platform import gfile
from IPython.display import Image
set filenames = sorted glob string C:\Users\ajink\Downloads\ML\Imag... | import os
import json
from glob import glob
import numpy as np
import seaborn as sns
import scipy.io as sio
import tensorflow.compat.v1 as tf
import matplotlib.pyplot as plt
from tensorflow.python.platform import gfile
from IPython.display import Image
filenames = sorted(glob('C:\\Users\\ajink\\Downloads\\ML\\Images\\... | Python | zaydzuhri_stack_edu_python |
function aggregated_node_edge_point self aggregated_node_edge_point
begin
set _aggregated_node_edge_point = aggregated_node_edge_point
end function | def aggregated_node_edge_point(self, aggregated_node_edge_point):
self._aggregated_node_edge_point = aggregated_node_edge_point | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment coding: utf-8
comment In[1]:
import requests
from bs4 import BeautifulSoup
import pandas as pd
comment In[2]:
comment Set first URL--COVID data for the US
set url = string https://www.worldometers.info/coronavirus/country/us/
set page = text
comment soup = bs(page.text, 'lxml')
set ... | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import requests
from bs4 import BeautifulSoup
import pandas as pd
# In[2]:
#Set first URL--COVID data for the US
url= "https://www.worldometers.info/coronavirus/country/us/"
page=requests.get(url).text
#soup = bs(page.text, 'lxml')
soup = BeautifulSoup(page,'html.pa... | Python | zaydzuhri_stack_edu_python |
function __iter__ self
begin
comment Trigger the consumer procs to start off.
comment We will iterate till there are no more messages available
set value = 0
set
while true
begin
set
try
begin
comment We will block for a small while so that the consumers get
comment a chance to run and put some messages in the queue
co... | def __iter__(self):
# Trigger the consumer procs to start off.
# We will iterate till there are no more messages available
self.size.value = 0
self.events.pause.set()
while True:
self.events.start.set()
try:
# We will block for a small whi... | Python | nomic_cornstack_python_v1 |
function validate_title self field
begin
set existing = set list comprehension call simplify_text title for b in all if b != edit_obj
if call simplify_text data in existing
begin
raise call ValidationError string You have an existing budget with the same name
end
end function | def validate_title(self, field):
existing = set([simplify_text(b.title) for b in
Budget.query.filter_by(workspace=g.workspace).all() if b != self.edit_obj])
if simplify_text(field.data) in existing:
raise wtforms.ValidationError("You have an existing budget with the same name") | Python | nomic_cornstack_python_v1 |
import time
import os
from slackclient import SlackClient
import bottle
from bottle import Bottle , run
string change token below to activate
class Connection
begin
set dict = dict
set sc = none
set summ = none
set names = dict
function read self token
begin
set sc = call SlackClient token
if call rtm_connect
begin
s... | import time
import os
from slackclient import SlackClient
import bottle
from bottle import Bottle, run
''' change token below to activate'''
class Connection:
dict = {}
sc = None
summ = None
names = {}
def read(self,token):
self.sc = SlackClient(token)
if self.sc... | Python | zaydzuhri_stack_edu_python |
for list in list1
begin
if list % 2 != 0
begin
append list3 list
end
end
for list in list2
begin
if list % 2 == 0
begin
append list3 list
end
end
print list3 | for list in list1:
if(list%2!=0):
list3.append(list)
for list in list2:
if(list%2==0):
list3.append(list)
print(list3) | Python | zaydzuhri_stack_edu_python |
import sys
function fact x
begin
if x == 0
begin
return 1
end
else
begin
return x * call fact x - 1
end
end function
set a = integer input string enter the nmbr : | import sys
def fact(x):
if x==0:
return 1
else:
return x * fact(x-1)
a=int(input('enter the nmbr : ')) | Python | zaydzuhri_stack_edu_python |
comment %% [markdown]
comment Python を使ったデータ分析
comment Python の基礎を学んだので、Python でデータ整理、分析をする際に役立つパッケージを紹介します。
comment %% [markdown]
comment Numpy
comment `numpy` は行列計算用のパッケージです。
comment 内部は C で実装されており、高速に計算をすることができます。
comment また、anaconda を使って python をインストールした場合には、 計算に Intel の Math Kernel Library が使われており、さらに高速に計算をすることができ... | #%% [markdown]
## Python を使ったデータ分析
# Python の基礎を学んだので、Python でデータ整理、分析をする際に役立つパッケージを紹介します。
#%% [markdown]
### Numpy
# `numpy` は行列計算用のパッケージです。
# 内部は C で実装されており、高速に計算をすることができます。
# また、anaconda を使って python をインストールした場合には、 計算に Intel の Math Kernel Library が使われており、さらに高速に計算をすることができます。
# `numpy` は `np` として 略して import するのが慣習です。
... | Python | zaydzuhri_stack_edu_python |
import os
from peewee import *
set db = call SqliteDatabase string supermercado.bd
class BaseModel extends Model
begin
class Meta
begin
set database = db
end class
end class
class Produto extends BaseModel
begin
set nome = call CharField
set preco = call FloatField
function __str__ self
begin
return string %s | %s % tu... | import os
from peewee import *
db = SqliteDatabase('supermercado.bd')
class BaseModel(Model):
class Meta:
database = db
class Produto(BaseModel):
nome = CharField()
preco = FloatField()
def __str__(self):
return '%s | %s' % (self.nome, self.preco)
class Item(BaseModel):
prduto =... | Python | zaydzuhri_stack_edu_python |
string 证明在偶数n以内,歌德巴赫猜想是成立的。歌德巴赫猜想是:任何一个充分大的偶数都可以表示为两个素数之和。 例如,4=2+2 6=3+3 8=3+5 50=3+47。 【输入形式】 输入偶数n 【输出形式】 对每一个偶数4, 6, 8, ..., n,依次输出一行。该行内容是<偶数>=<素数1>+<素数2>,要求素数1<=素数2. 【样例输入】 6 【样例输出】 4=2+2 6=3+3
function su_shu m
begin
comment 素数大于1
if m > 1
begin
for r in range 2 m
begin
if m % r == 0
begin
return false
end
end
f... | '''
证明在偶数n以内,歌德巴赫猜想是成立的。歌德巴赫猜想是:任何一个充分大的偶数都可以表示为两个素数之和。
例如,4=2+2 6=3+3 8=3+5 50=3+47。
【输入形式】
输入偶数n
【输出形式】
对每一个偶数4, 6, 8, ..., n,依次输出一行。该行内容是<偶数>=<素数1>+<素数2>,要求素数1<=素数2.
【样例输入】
6
【样例输出】
4=2+2
6=3+3
'''
def su_shu(m):
# 素数大于1
if m > 1:
for r in range(2, m):
if m % r == 0:
... | Python | zaydzuhri_stack_edu_python |
function next self t
begin
if next_ping_index == length pings
begin
raise StopIteration
end
set result = list
while next_ping_index < length pings and time < t
begin
append result pings at next_ping_index
set next_ping_index = next_ping_index + 1
end
return result
end function | def next(self, t):
if self.next_ping_index == len(self.pings):
raise StopIteration
result = []
while self.next_ping_index < len(self.pings) and self.pings[self.next_ping_index].time < t:
result.append(self.pings[self.next_ping_index])
self.next_ping_index += ... | Python | nomic_cornstack_python_v1 |
while n > 0
begin
set s = s + n % 10
set n = n // 10
end
print s | while n>0:
s+=(n%10)
n//=10
print(s)
| Python | zaydzuhri_stack_edu_python |
import asyncio
import time
async function task1
begin
print string Beginning task1
await sleep 2
print string Completed task
return string Finished task1
end function
async function task2
begin
print string Begining task2
await sleep 2
print string Completed task
return string Finished task2
end function
async function... | import asyncio
import time
async def task1():
print("Beginning task1")
await asyncio.sleep(2)
print("Completed task")
return "Finished task1"
async def task2():
print("Begining task2")
await asyncio.sleep(2)
print("Completed task")
return "Finished task2"
async def task3():
print("Begining tas... | Python | zaydzuhri_stack_edu_python |
comment ! /usr/bin/env python3
string Trial of publishers.. Ways to learn python and ros
import rospy
from geometry_msgs.msg import Twist , Vector3
class follow extends object
begin
function __init__ self
begin
set pub = call Publisher string /dd/cmd_vel Twist queue_size=10
set vel1 = call Twist linear=call Vector3 x=-... | #! /usr/bin/env python3
"""
Trial of publishers.. Ways to learn python and ros
"""
import rospy
from geometry_msgs.msg import Twist, Vector3
class follow(object):
def __init__(self):
self.pub = rospy.Publisher('/dd/cmd_vel', Twist, queue_size = 10)
self.vel1 = Twist(linear = Vector3(x=-1,y=0,z=0),... | Python | zaydzuhri_stack_edu_python |
function test_neg_put_without_record self
begin
set key = tuple string test string demo 1
with raises TypeError as typeError
begin
put key
end
assert string argument 'bins' (pos 2) in string value
end function | def test_neg_put_without_record(self):
key = ("test", "demo", 1)
with pytest.raises(TypeError) as typeError:
self.as_connection.put(key)
assert "argument 'bins' (pos 2)" in str(typeError.value) | Python | nomic_cornstack_python_v1 |
from tkinter import *
set root = call Tk
title root string My GUI with Harry
comment Important Label Options
comment text = adds the text
comment bd = background
comment fg = foreground
comment font = sets the font
comment padx = x_padding
comment pady = y_paddign
comment relief = borde_styling = SUNKEN, RAISED, GROOVE... | from tkinter import *
root = Tk()
root.title('My GUI with Harry')
#Important Label Options
# text = adds the text
# bd = background
# fg = foreground
# font = sets the font
# padx = x_padding
# pady = y_paddign
# relief = borde_styling = SUNKEN, RAISED, GROOVE, RIDGE
text_label = Label(text = 'Wikipedia began with its ... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/env python
from tools.logger import log
class Rect extends object
begin
string A minimal class for rectangles that allows overlap checking
function __init__ self x y w h typ name modifier=1
begin
string Modifier for RAMB18 being half-sized RAMB36 -- should be one for all except RAMB36
call __init__
se... | #!/usr/bin/env python
from tools.logger import log
class Rect(object):
"""A minimal class for rectangles that allows overlap checking"""
def __init__(self, x, y, w, h, typ, name, modifier=1):
""" Modifier for RAMB18 being half-sized RAMB36 -- should be one for all except RAMB36"""
super(Rect, ... | Python | zaydzuhri_stack_edu_python |
comment -*- coding:utf-8 -*-
import MySQLdb
import time
class Mysql extends object
begin
function __get_time self
begin
return string format time time string [%Y-%m-%d %H:%M:%S] call localtime time
end function
function __log self log_str *args **kw
begin
set current_time = call __get_time
end function
end class | # -*- coding:utf-8 -*-
import MySQLdb
import time
class Mysql(object):
def __get_time(self):
return self.time.strftime('[%Y-%m-%d %H:%M:%S]', time.localtime(time.time()))
def __log(self, log_str, *args, **kw):
current_time = self.__get_time() | Python | zaydzuhri_stack_edu_python |
function post_run_func_checked driver
begin
if post_run_func is not none
begin
call post_run_func driver
end
end function | def post_run_func_checked(driver: HammerDriver) -> None:
if post_run_func is not None:
post_run_func(driver) | Python | nomic_cornstack_python_v1 |
function tenant_id self
begin
return _tenant_id
end function | def tenant_id(self):
return self._tenant_id | Python | nomic_cornstack_python_v1 |
function auth self pair=true timeout=60
begin
comment get the S/N of client device
set auth_cmd = call Auth OP_CLIENT_SN
write channel call pack
while true
begin
set auth_reply = call unpack read channel
if auth_reply
begin
break
end
end
debug string Got client auth string. %s auth_reply
comment check if the auth key f... | def auth(self, pair=True, timeout=60):
# get the S/N of client device
auth_cmd = Auth(Auth.OP_CLIENT_SN)
self.channel.write(auth_cmd.pack())
while True:
auth_reply = Auth.unpack(self.channel.read())
if auth_reply: break
_log.debug("Got client auth string. ... | Python | nomic_cornstack_python_v1 |
function isprime n
begin
if n == 0 or n == 1
begin
return false
end
for i in range 2 n
begin
if n % i == 0
begin
return false
end
end
return true
end function | def isprime(n):
if n == 0 or n == 1: return False
for i in range(2,n):
if n%i == 0:
return False
return True | Python | zaydzuhri_stack_edu_python |
comment https://realpython.com/python-boto3-aws-s3/
comment https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html#configuration
comment https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-example-download-file.html#downloading-files
comment https://boto3.amazonaws.com/v1/documentati... | # https://realpython.com/python-boto3-aws-s3/
# https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html#configuration
# https://boto3.amazonaws.com/v1/documentation/api/latest/guide/s3-example-download-file.html#downloading-files
# https://boto3.amazonaws.com/v1/documentation/api/1.9.42/guide/s3-e... | Python | zaydzuhri_stack_edu_python |
import pandas as pd
import matplotlib.pyplot as plt
call use string ggplot
set fil = input string Enter your Excel filename:
set df = call read_excel fil
set tuple fig ax = call subplots
set var1 = input string Enter variable:
set my_scatter_plot = call boxplot df at var1
call set_title string Box plot of cars
show | import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
fil = input("Enter your Excel filename: ")
df = pd.read_excel(fil)
fig, ax = plt.subplots()
var1 = input("Enter variable:")
my_scatter_plot = ax.boxplot(
df[var1],
)
ax.set_title("Box plot of cars")
plt.show()
| Python | zaydzuhri_stack_edu_python |
function _get_ensemble_filename self the_variable mip realm
begin
comment use model parser to generate a list of available institutes and
comment models from data directory
set data_dir = data_dir
if data_dir at - 1 != sep
begin
set data_dir = data_dir + sep
end
set CMP = call CMIP5ModelParser data_dir
set model_list =... | def _get_ensemble_filename(self, the_variable, mip, realm):
# use model parser to generate a list of available institutes and
# models from data directory
data_dir = self.data_dir
if data_dir[-1] != os.sep:
data_dir += os.sep
CMP = preprocessor.CMIP5ModelParser(self... | Python | nomic_cornstack_python_v1 |
function plot_government government symbol gov_type external_axes=false
begin
set fig = call OpenBBFigure yaxis_title=string Amount ($1k) xaxis_title=string Date
call set_title string { capitalize gov_type } trading on { symbol }
call add_scatter name=string lower x=unique y=values / 1000
call add_scatter name=string u... | def plot_government(
government: pd.DataFrame,
symbol: str,
gov_type: str,
external_axes: bool = False,
) -> Optional[OpenBBFigure]:
fig = OpenBBFigure(yaxis_title="Amount ($1k)", xaxis_title="Date")
fig.set_title(f"{gov_type.capitalize()} trading on {symbol}")
fig.add_scatter(
nam... | Python | nomic_cornstack_python_v1 |
string Saves faces in tracklets into local directory.
import shutil
import os
import cv2
function save tracklets output_folder video_name
begin
comment delete output folder that currently exists
remove tree output_folder ignore_errors=true
make directory os output_folder
print string Saving faces...
for tracklet in tra... | """
Saves faces in tracklets into local directory.
"""
import shutil
import os
import cv2
def save(tracklets, output_folder, video_name):
# delete output folder that currently exists
shutil.rmtree(output_folder, ignore_errors=True)
os.mkdir(output_folder)
print("Saving faces...")
for tracklet in t... | Python | zaydzuhri_stack_edu_python |
comment Given a list of numbers and a target number,
comment find all possible unique subsets of the list of
comment numbers that sum up to the target number. The numbers will all be positive numbers.
comment Here's an example and some starter code.
function get_target nums target
begin
comment list of lists
set ret = ... | # Given a list of numbers and a target number,
# find all possible unique subsets of the list of
# numbers that sum up to the target number. The numbers will all be positive numbers.
#
# Here's an example and some starter code.
def get_target(nums, target):
ret = [] # list of lists
if target == 0:
retu... | Python | zaydzuhri_stack_edu_python |
import requests
import json
comment This function asks movies from the users as sample
function askMovies
begin
set more = string y
set movieList = list
while more == string y
begin
set movieName = input string Enter movie name :
append movieList movieName
set more = string n
set more = input string Want to conti.? ('... | import requests
import json
def askMovies(): #This function asks movies from the users as sample
more = 'y'
movieList = []
while(more=='y'):
movieName = input("Enter movie name : ")
movieList.append(movieName)
more = 'n'... | Python | zaydzuhri_stack_edu_python |
function test_list_recipes_site_cookbooks self
begin
set tuple resp error = execute self list fix string list_recipes
assert true string Modified by site-cookbooks in resp
end function | def test_list_recipes_site_cookbooks(self):
resp, error = self.execute([fix, 'list_recipes'])
self.assertTrue('Modified by site-cookbooks' in resp) | Python | nomic_cornstack_python_v1 |
function fetchAlbumInfo album_id
begin
set url = string https://api.spotify.com/v1/albums/ + album_id
set req = get requests url
set data = json req
set albuminfo = dict
set artistinfo = data at string artists
set firstartist = artistinfo at 0
set artist_id = firstartist at string id
set albuminfo at string artist_id ... | def fetchAlbumInfo(album_id):
url="https://api.spotify.com/v1/albums/"+album_id
req=requests.get(url)
data=req.json()
albuminfo={}
artistinfo=data['artists']
firstartist=artistinfo[0]
artist_id=firstartist['id']
albuminfo['artist_id']=artist_id
rawuri=data['uri']
albuminfo['alb... | Python | nomic_cornstack_python_v1 |
comment Project: Project Diamond
comment Purpose Details: To test the app3Email file
comment Course: IST 411
comment Author: Team 1
comment Date Developed: 11/10/2019
comment Last Date Changed:
comment Rev:
import unittest , urllib.request , json
from app3Email import EmailPayload
string Test EmailPayload class
class E... | # Project: Project Diamond
# Purpose Details: To test the app3Email file
# Course: IST 411
# Author: Team 1
# Date Developed: 11/10/2019
# Last Date Changed:
# Rev:
import unittest, urllib.request, json
from app3Email import EmailPayload
''' Test EmailPayload class '''
class EmailPayloadTest(unittest.TestCase):
... | Python | zaydzuhri_stack_edu_python |
import tweenerUI
import Gear
call reload tweenerUI
call reload Gear
from tweenerUI import tween
from Gear import Gear
from maya import cmds
class BaseWindow
begin
set windowName = string BaseWindow
function show self
begin
if call window windowName query=true exists=true
begin
call deleteUI windowName
end
call window w... | import tweenerUI
import Gear
reload(tweenerUI)
reload(Gear)
from tweenerUI import tween
from Gear import Gear
from maya import cmds
class BaseWindow:
windowName = "BaseWindow"
def show(self):
if cmds.window(self.windowName, query = True, exists = True):
cmds.deleteUI(self.windowName)
... | Python | zaydzuhri_stack_edu_python |
comment !/usr/bin/python3
from which_pyqt import PYQT_VER
if PYQT_VER == string PYQT5
begin
from PyQt5.QtCore import QLineF , QPointF
end
else
if PYQT_VER == string PYQT4
begin
from PyQt4.QtCore import QLineF , QPointF
end
else
begin
raise exception format string Unsupported Version of PyQt: {} PYQT_VER
end
import time... | #!/usr/bin/python3
from which_pyqt import PYQT_VER
if PYQT_VER == 'PYQT5':
from PyQt5.QtCore import QLineF, QPointF
elif PYQT_VER == 'PYQT4':
from PyQt4.QtCore import QLineF, QPointF
else:
raise Exception('Unsupported Version of PyQt: {}'.format(PYQT_VER))
import time
import numpy as np
from TSPClasses import *... | Python | zaydzuhri_stack_edu_python |
function OnPushPlotPowerScanBtn self
begin
print string Not yet implemented.
end function | def OnPushPlotPowerScanBtn(self):
print('Not yet implemented.') | Python | nomic_cornstack_python_v1 |
function head self head
begin
set _head = head
end function | def head(self, head):
self._head = head | Python | nomic_cornstack_python_v1 |
import numpy as np
from sklearn.decomposition import FastICA
class ICA
begin
function ica data_signals ref_signal verbose=false
begin
set data = data_signals
set reference = ref_signal
set result = list
for i in range length data
begin
set temp = call ica_trial data reference
append result temp
end
return result
end f... | import numpy as np
from sklearn.decomposition import FastICA
class ICA:
def ica(data_signals, ref_signal, verbose=False):
data = data_signals
reference = ref_signal
result = []
for i in range(len(data)):
temp = ICA.ica_trial(data,reference)
result.append(temp... | Python | zaydzuhri_stack_edu_python |
function is_final self
begin
if board at 0 == list 2 2 2 2
begin
return 2
end
else
if board at 3 == list 1 1 1 1
begin
return 1
end
else
if not call generate_all
begin
return 3 - next
end
else
begin
return 0
end
end function | def is_final(self):
if self.board[0] == [2, 2, 2, 2]:
return 2
elif self.board[3] == [1, 1, 1, 1]:
return 1
elif not self.generate_all():
return 3 - self.next
else:
return 0 | Python | nomic_cornstack_python_v1 |
function read_labeled_image_list image_list_file
begin
set f = open image_list_file string r
set filenames = list
set labels = list
for line in f
begin
set line = right strip line string
comment line[:-1].split(LABEL_SEP)
set tuple filename _ label = call partition LABEL_SEP
append filenames filename
append labels in... | def read_labeled_image_list(image_list_file):
f = open(image_list_file, 'r')
filenames = []
labels = []
for line in f:
line = line.rstrip('\n')
filename, _, label = line.partition(LABEL_SEP)#line[:-1].split(LABEL_SEP)
filenames.append(filename)
labels.append(int(label))
#print (filename+LABEL_SEP+":) "+l... | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
string @File :9.4.4my_cars.py @Copyright :luoming @Date : @Desc :
import car
set my_beetle = call Car string volswagen string beetle 2016
print call get_descriptive_name
set my_tesla = call ElectricCar string tesla string roadster 2016
print call get_descriptive_name | #!/usr/bin/env python
'''
@File :9.4.4my_cars.py
@Copyright :luoming
@Date :
@Desc :
'''
import car
my_beetle = car.Car('volswagen', 'beetle', 2016)
print(my_beetle.get_descriptive_name())
my_tesla = car.ElectricCar('tesla', 'roadster', 2016)
print(my_tesla.get_descriptive_name()) | Python | zaydzuhri_stack_edu_python |
function load self path
begin
with open path string rb as f
begin
set _nodes = load pickle f
end
end function | def load(self, path):
with open(path, 'rb') as f:
self._nodes = pickle.load(f) | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/env python
comment -*- coding=utf-8 -*-
comment author: mickey0524
comment single direction stack
comment 2019-04-26
from collections import deque
comment 数组中元素前一个比它小的元素
function single_direction_stack arr
begin
set stack = deque list
set res = list
for n in arr
begin
while stack and stack at - 1 >= ... | #!/usr/bin/env python
# -*- coding=utf-8 -*-
# author: mickey0524
# single direction stack
# 2019-04-26
from collections import deque
# 数组中元素前一个比它小的元素
def single_direction_stack(arr):
stack = deque([])
res = []
for n in arr:
while stack and stack[-1] >= n:
stack.pop()
res.a... | Python | zaydzuhri_stack_edu_python |
import requests , re , os , bs4 , json
function get_res url cookies=none
begin
set res = get requests url=url cookies=cookies
set encoding = string utf-8
call raise_for_status
if status_code == 200
begin
return res
end
else
begin
return none
end
end function
function get_page_number url cookies=none
begin
set res = cal... | import requests, re, os, bs4, json
def get_res(url, cookies=None):
res = requests.get(url=url, cookies=cookies)
res.encoding = 'utf-8'
res.raise_for_status()
if res.status_code == 200:
return res
else:
return None
def get_page_number(url, cookies=None):
res = get_res(url, coo... | Python | zaydzuhri_stack_edu_python |
function find_suppliers_without_agreements client framework_slug supplier_ids=none
begin
set records = call find_framework_suppliers_iter framework_slug agreement_returned=false
if supplier_ids
begin
set records = filter lambda r -> r at string supplierId in supplier_ids records
end
comment we're not interested in supp... | def find_suppliers_without_agreements(client, framework_slug, supplier_ids=None):
records = client.find_framework_suppliers_iter(framework_slug, agreement_returned=False)
if supplier_ids:
records = filter(lambda r: r["supplierId"] in supplier_ids, records)
# we're not interested in suppliers who are... | Python | nomic_cornstack_python_v1 |
function __init__ self num_nodes
begin
set _num_nodes = num_nodes
set _node_numbers = list comprehension node for node in call xrange num_nodes for _ in call xrange num_nodes
end function | def __init__(self, num_nodes):
self._num_nodes = num_nodes
self._node_numbers = [node for node in xrange(num_nodes) for _ in xrange(num_nodes)] | Python | nomic_cornstack_python_v1 |
import sys
from collections import defaultdict
function common seqs flank
begin
set occ = default dictionary int
for seq in seqs
begin
if length seq > length flank and flank in seq
begin
set index = length seq - length flank
while seq at slice index : index + length flank : != flank
begin
set index = index - 1
end
if ... | import sys
from collections import defaultdict
def common(seqs, flank):
occ = defaultdict(int)
for seq in seqs:
if len(seq) > len(flank) and flank in seq:
index = len(seq)-len(flank)
while seq[index:index+len(flank)] != flank:
index -= 1
if len(seq) > index+len(flank):
occ[ seq[index+len(... | Python | zaydzuhri_stack_edu_python |
import hashlib
import math
import uuid
from bitarray import bitarray
class BloomFilter extends object
begin
function __init__ self itemcount fpprob
begin
set fp_prob = fpprob
set size = call get_size itemcount fpprob
set bit_array3 = call bitarray size
call setall 0
set bit_array5 = call bitarray size
call setall 0
end... | import hashlib
import math
import uuid
from bitarray import bitarray
class BloomFilter(object):
def __init__(self, itemcount, fpprob):
self.fp_prob = fpprob
self.size = self.get_size(itemcount, fpprob)
self.bit_array3 = bitarray(self.size)
self.bit_array3.setall(0)
self.bit_... | Python | zaydzuhri_stack_edu_python |
from abc import ABC , abstractmethod
class Callback extends ABC
begin
string Abstract Base Class for all callbacks. A valid callback must specify the following methods:
function __init__ self response_payload=dict
begin
set reponse_payload = response_payload
end function
decorator property
decorator classmethod
decorat... | from abc import ABC, abstractmethod
class Callback(ABC):
""" Abstract Base Class for all callbacks. A valid callback must specify the following methods:"""
def __init__(self, response_payload={}):
self.reponse_payload = response_payload
@property
@classmethod
@abstractmethod
def stat... | Python | zaydzuhri_stack_edu_python |
import copy
function create_grid grid
begin
set height = 4
for i in range height
begin
append grid list 0 * 4
end
return grid
end function
function print_grid grid
begin
set width = 5
print string + + string - * 4 * width + string +
for i in range 4
begin
print string | end=string
for j in range 4
begin
if grid at i at... | import copy
def create_grid(grid):
height=4
for i in range(height):
grid.append([0]*4)
return grid
def print_grid (grid):
width=5
print("+"+"-"*(4*width)+"+")
for i in range(4):
print("|",end='')
for j in range(4):
if ... | Python | zaydzuhri_stack_edu_python |
function showcase_post_comment_details cls val
begin
return call cls string showcase_post_comment_details val
end function | def showcase_post_comment_details(cls, val):
return cls('showcase_post_comment_details', val) | Python | nomic_cornstack_python_v1 |
function write_dot cs path
begin
assert length path != 0 msg string Filename can't be empty
set output_file = open path string w
write output_file string digraph L{
write output_file string
write output_file string node[shape=circle,style=filled,label=""];
write output_file string
write output_file string edge[dir="non... | def write_dot(cs, path):
assert len(path)!=0, "Filename can't be empty"
output_file = open(path, "w")
output_file.write("digraph L{")
output_file.write("\n")
output_file.write("node[shape=circle,style=filled,label=\"\"];")
output_file.write("\n")
output_file.write("edge[dir=\"none\",minlen=2... | Python | nomic_cornstack_python_v1 |
function sum_digits num
begin
set total = 0
while num != 0
begin
set total = total + num % 10
set num = num // 10
end
return total
end function | def sum_digits(num):
total = 0
while num != 0:
total += num % 10
num //= 10
return total | Python | iamtarun_python_18k_alpaca |
function test_services_and_information
begin
set client = call TestClient app
set response = get client url=string http://localhost/v1/pois/osm:way:63178753?lang=fr
assert status_code == 200
set resp = json response
assert get get get resp string blocks at 2 string blocks at 0 string blocks == list dict string type str... | def test_services_and_information():
client = TestClient(app)
response = client.get(
url=f'http://localhost/v1/pois/osm:way:63178753?lang=fr',
)
assert response.status_code == 200
resp = response.json()
assert resp.get('blocks')[2].get('blocks')[0].get('blocks') == [
{
"type": "... | Python | nomic_cornstack_python_v1 |
function strip_pad plaintext
begin
return plaintext at slice : - ordinal plaintext at - 1 :
end function | def strip_pad(plaintext):
return plaintext[:-ord(plaintext[-1])] | Python | nomic_cornstack_python_v1 |
string This module contains tests for the main DO class
from unittest import TestCase
from doboto.exception import DOBOTOException , DOBOTONotFoundException , DOBOTOPollingException
class TestDOBOTOException extends TestCase
begin
string This class checks on the DOBOTOException Class
function test_can_instantiate self
... | """
This module contains tests for the main DO class
"""
from unittest import TestCase
from doboto.exception import DOBOTOException, DOBOTONotFoundException, DOBOTOPollingException
class TestDOBOTOException(TestCase):
"""
This class checks on the DOBOTOException Class
"""
def test_can_instantiate(se... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
from scipy import signal
comment def fitfunction(x,a,b,c,d,e,f,g,h,i):
comment return e*np.sin(d*x+f) + g*np.sin(h*x*x+i) + a*x*x + b*x + c
function fitfunction x a b c d
begin
return d * call sawtooth 0.2 * x - 7.5 + a * x * x + b ... | import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit
from scipy import signal
#def fitfunction(x,a,b,c,d,e,f,g,h,i):
# return e*np.sin(d*x+f) + g*np.sin(h*x*x+i) + a*x*x + b*x + c
def fitfunction(x,a,b,c,d):
return d*signal.sawtooth(0.2*(x-7.5)) + a*x*x + b*x + c
x = []
y = ... | Python | zaydzuhri_stack_edu_python |
import pygame
import random
import math
from enemyPlayer import Enemy
call init
call init
comment display size
set display_width = 1000
set display_height = 600
set FPS = 30
comment calls a surface (window) called gameDisplay where I will run the game
set gameDisplay = call set_mode tuple display_width display_height
c... | import pygame
import random
import math
from enemyPlayer import Enemy
pygame.mixer.init()
pygame.init()
#display size
display_width = 1000
display_height = 600
FPS = 30
#calls a surface (window) called gameDisplay where I will run the game
gameDisplay = pygame.display.set_mode((display_width, display... | Python | zaydzuhri_stack_edu_python |
function load_ipython_extension ip
begin
comment This is equivalent to `ip.register_magics(JuliaMagics)` (but it
comment let us access the instance of `JuliaMagics`):
set magics = call JuliaMagics shell=ip
call register_magics magics
set template = string Incompatible upstream libraries. Got ImportError: {}
if highligh... | def load_ipython_extension(ip):
# This is equivalent to `ip.register_magics(JuliaMagics)` (but it
# let us access the instance of `JuliaMagics`):
magics = JuliaMagics(shell=ip)
ip.register_magics(magics)
template = "Incompatible upstream libraries. Got ImportError: {}"
if magics.highlight:
... | Python | nomic_cornstack_python_v1 |
function device_time_check self
begin
if last_update_ts is none or time - last_update_ts > update_interval
begin
return true
end
return false
end function | def device_time_check(self) -> bool:
if (
self.last_update_ts is None
or (time.time() - self.last_update_ts) > self.update_interval
):
return True
return False | Python | nomic_cornstack_python_v1 |
function stop_reactor_on_state_machine_finish state_machine
begin
string Wait for a state machine to be finished and stops the reactor :param state_machine: the state machine to synchronize with
call wait_for_state_machine_finished state_machine
from twisted.internet import reactor
if running
begin
call run_hook string... | def stop_reactor_on_state_machine_finish(state_machine):
""" Wait for a state machine to be finished and stops the reactor
:param state_machine: the state machine to synchronize with
"""
wait_for_state_machine_finished(state_machine)
from twisted.internet import reactor
if reactor.running:
... | Python | jtatman_500k |
function addFile self srcFile_abs dstFile_rel
begin
update fileDict dict srcFile_abs dstFile_rel
end function | def addFile( self, srcFile_abs, dstFile_rel ):
self.fileDict.update( { srcFile_abs: dstFile_rel } ) | Python | nomic_cornstack_python_v1 |
string 切片模式:[start:end:step] start:切片开始位置,默认为0 end:切片截止位置,但不包括该位置,默认是列表长度 step:切片步长,默认是1个步长,当步长是负数时,表示反向切片,这时候start的数值应该大于end的数值 重点:切片操作返回的是一个新的list,不会改变原list
set a = list 1 2 3 4 5 6 7 8 9
print a at slice 1 : 9 : 2
string 带点技术的操作
comment 在列表头部插入元素
set a at slice : 0 : = list 1 2
comment 将3这个位置的元素改变成5
set a at slice... | """
切片模式:[start:end:step]
start:切片开始位置,默认为0
end:切片截止位置,但不包括该位置,默认是列表长度
step:切片步长,默认是1个步长,当步长是负数时,表示反向切片,这时候start的数值应该大于end的数值
重点:切片操作返回的是一个新的list,不会改变原list
"""
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a[1:9:2])
"""
带点技术的操作
"""
a[:0] = [1, 2] # 在列表头部插入元素
a[3:3] = [5] # 将3这个位置的元素改变成5
a[:3] = [1, 2, 3] # 将前三个元素更改成1,2,3... | Python | zaydzuhri_stack_edu_python |
import sys
import os
function ComputeMinFlipcount s
begin
set flipCount = 0
set lastSeen = string +
for c in s at slice - 1 : : - 1
begin
if c != lastSeen
begin
set flipCount = flipCount + 1
set lastSeen = c
end
end
return flipCount
end function
function main
begin
set T = integer call raw_input
for testNo in call xra... | import sys
import os
def ComputeMinFlipcount(s):
flipCount = 0
lastSeen = "+"
for c in s[-1::-1]:
if c != lastSeen:
flipCount += 1
lastSeen = c
return flipCount
def main():
T = int(raw_input())
for testNo in xrange(1,T+1):
s = raw_input() | Python | zaydzuhri_stack_edu_python |
import numpy as np
from sklearn.datasets import load_wine
from icecream import ic
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.utils import all_estimators
from sklearn.metrics import accuracy_score
import warnings
comment 경고무시
filter warnings string ignore
commen... | import numpy as np
from sklearn.datasets import load_wine
from icecream import ic
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from sklearn.utils import all_estimators
from sklearn.metrics import accuracy_score
import warnings
warnings.filterwarnings('ignore') # 경고무시
### 머신러... | Python | zaydzuhri_stack_edu_python |
comment MELEYCA CABRERA (UNEFA)
comment ver: https://repl.it/Dfq0/1
comment CLASE NODO
class Nodo
begin
function __init__ self valor
begin
set info = valor
set sig = none
end function
end class
comment CLASE LISTA
class Lista
begin
comment CONSTRUCTOR
function __init__ self
begin
set __primero = none
set __ultimo = non... | # MELEYCA CABRERA (UNEFA)
#ver: https://repl.it/Dfq0/1
# CLASE NODO
class Nodo:
def __init__ (self, valor):
self.info = valor
self.sig = None
# CLASE LISTA
class Lista:
# CONSTRUCTOR
def __init__ (self):
self.__primero = None
self.__ultimo = None
self.__actual = None
self.__n = 0
self.__pos = 0
... | Python | zaydzuhri_stack_edu_python |
function main_module self
begin
string Return the main module to which the receiver belongs.
if keyword == string submodule
begin
return call get_module i_including_modulename
end
return i_module
end function | def main_module(self):
"""Return the main module to which the receiver belongs."""
if self.i_module.keyword == "submodule":
return self.i_module.i_ctx.get_module(
self.i_module.i_including_modulename)
return self.i_module | Python | jtatman_500k |
function get_codegen_by_target name
begin
try
begin
return REGISTERED_CODEGEN at name
end
except KeyError
begin
raise call TVMCException string Composite target %s is not defined in TVMC. % name
end
end function | def get_codegen_by_target(name):
try:
return REGISTERED_CODEGEN[name]
except KeyError:
raise TVMCException("Composite target %s is not defined in TVMC." % name) | Python | nomic_cornstack_python_v1 |
import time
from core.redis import RedisStorage
class Bucket extends object
begin
string A bucket. A bucket "leaks" queries at a rate of ``rate`` per second, and has a maximum capacity of ``capacity``. When a new request arrives (call to ``consume()``), the bucket checks that it can add it without exceeding capacity; o... | import time
from core.redis import RedisStorage
class Bucket(object):
"""A bucket.
A bucket "leaks" queries at a rate of ``rate`` per second,
and has a maximum capacity of ``capacity``.
When a new request arrives (call to ``consume()``), the bucket checks that
it can add it without exceeding capa... | Python | zaydzuhri_stack_edu_python |
set numbers = list 1 2 3 4 5 6 7 8 9
set odd_numbers = list
set even_numbers = list
for num in numbers
begin
if num % 2 == 0
begin
append even_numbers num
end
else
begin
append odd_numbers num
end
end
sort odd_numbers
sort even_numbers
print string Odd Numbers: odd_numbers
print string Even Numbers: even_numbers | numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
odd_numbers = []
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
else:
odd_numbers.append(num)
odd_numbers.sort()
even_numbers.sort()
print("Odd Numbers:", odd_numbers)
print("Even Numbers:", even_numbers)
| Python | jtatman_500k |
function str_typed_attrs draw defaults=none
begin
set default = MISSING
if defaults is true or defaults is none and call draw call booleans
begin
set default = call draw call text
end
return tuple call _get_field _type=str default=default call text
end function | def str_typed_attrs(draw, defaults=None):
default = MISSING
if defaults is True or (defaults is None and draw(booleans())):
default = draw(text())
return _get_field(_type=str, default=default), text() | Python | nomic_cornstack_python_v1 |
import requests
set api_url = string http://numbersapi.com/{}/math
set params = dict string json string true
with open string dataset_24476_3.txt as file
begin
set numbers = list comprehension integer line for line in file
end
for number in numbers
begin
set response = get requests format api_url number params=params
i... | import requests
api_url = 'http://numbersapi.com/{}/math'
params = {
'json': 'true'
}
with open('dataset_24476_3.txt') as file:
numbers = [int(line) for line in file]
for number in numbers:
response = requests.get(api_url.format(number), params=params)
if response.json()['found']:
print('Int... | Python | zaydzuhri_stack_edu_python |
function test_writer_with_file
begin
set outputfile = string testfile.txt
call GCMT write=outputfile
assert exists path outputfile
remove os outputfile
end function | def test_writer_with_file():
outputfile = "testfile.txt"
GCMT(write=outputfile)
assert os.path.exists(outputfile)
os.remove(outputfile) | Python | nomic_cornstack_python_v1 |
function _unpack self b data_type
begin
if data_type == string LongType
begin
if _have_struct
begin
return call unpack b at 0
end
else
begin
return call unpack string >q b at 0
end
end
else
if data_type == string IntegerType
begin
if _have_struct
begin
return call unpack b at 0
end
else
begin
return call unpack string ... | def _unpack(self, b, data_type):
if data_type == 'LongType':
if _have_struct:
return _long_packer.unpack(b)[0]
else:
return struct.unpack('>q', b)[0]
elif data_type == 'IntegerType':
if _have_struct:
return _int_packer.... | Python | nomic_cornstack_python_v1 |
function first_A_task arr length
begin
comment degree of freedom
set df = length - 1
comment t-score, ppf - Percent point function
set t = call ppf 1 - alpha / 2 df
comment sample standard deviation
set s = standard deviation np arr ddof=1
set lower = mean np arr - t * s / square root length
set upper = mean np arr + t... | def first_A_task(arr, length):
df = length - 1 # degree of freedom
t = stats.t.ppf(1 - alpha / 2, df) # t-score, ppf - Percent point function
s = np.std(arr, ddof=1) # sample standard deviation
lower = np.mean(arr) - (t * s / np.sqrt(length))
upper = np.mean(arr) + (t * s / np.sqrt(length))
... | 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.