code stringlengths 10 2.58M | original_code stringlengths 3 3.18M | original_language stringclasses 1
value | source stringclasses 7
values |
|---|---|---|---|
function __call__ self src dest log_file_id log_database
begin
comment : Absolute path to source file
comment :
comment : :type: str
set _src = src
comment : Database which handles the mapping of id to log messages
comment :
comment : :type: .log_sqllite_database.LogSqlLiteDatabase
set _log_database = log_database
comm... | def __call__(self, src, dest, log_file_id, log_database):
#: Absolute path to source file
#:
#: :type: str
self._src = src
#: Database which handles the mapping of id to log messages
#:
#: :type: .log_sqllite_database.LogSqlLiteDatabase
self._log_database ... | Python | nomic_cornstack_python_v1 |
function me self channel action
begin
append _me tuple channel action
end function | def me(self, channel, action):
self._me.append((channel, action)) | Python | nomic_cornstack_python_v1 |
function __str__ self
begin
set tmp = list
for layer in reversed range size at Y
begin
comment Print each layer
append tmp format string Layer {}: layer
comment Level border
append tmp string . * size at X + 2
for row in range size at Z
begin
comment Print each row
set rowtxt = string .
for cell in range size at X
beg... | def __str__(self):
tmp = []
for layer in reversed(range(self.size[Y])):
# Print each layer
tmp.append("Layer {}:".format(layer))
tmp.append("."*(self.size[X] + 2)) # Level border
for row in range(self.size[Z]):
# Print each row
... | Python | nomic_cornstack_python_v1 |
comment encoding:utf8
import sys
call reload sys
call setdefaultencoding string utf8
import MySQLdb
import db , conf
function open_sql_text
begin
set db = call connect keyword sql_info_text
set cur = call cursor
return tuple db cur
end function
function get_text
begin
set tuple conn cur = call open_sql_text
set query =... | #encoding:utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import MySQLdb
import db,conf
def open_sql_text():
db = MySQLdb.connect(**conf.sql_info_text)
cur = db.cursor()
return db,cur
def get_text():
conn,cur = open_sql_text()
query = 'SELECT * FROM text'
try:
cur.execute(quer... | Python | zaydzuhri_stack_edu_python |
import math
function is_prime n
begin
if n < 2
begin
return false
end
for i in range 2 integer square root n + 1
begin
if n % i == 0
begin
return false
end
end
return true
end function
function categorize_numbers numbers
begin
set primes = list
set non_primes = list
for num in numbers
begin
if call is_prime num
begin... | import math
def is_prime(n):
if n < 2:
return False
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
def categorize_numbers(numbers):
primes = []
non_primes = []
for num in numbers:
if is_prime(num):
primes.append... | Python | greatdarklord_python_dataset |
function test_okgrade_magic
begin
with open join path here string notebooks/injected-magic.ipynb as f
begin
set nb = load json f
end
set return_env = call execute_notebook nb initial_env=dict string __GOFER_GRADER__ true
assert return_env at string gofer_grader_present == true
end function | def test_okgrade_magic():
with open(os.path.join(here, 'notebooks/injected-magic.ipynb')) as f:
nb = json.load(f)
return_env = execute_notebook(nb, initial_env={'__GOFER_GRADER__': True})
assert return_env['gofer_grader_present'] == True | Python | nomic_cornstack_python_v1 |
function setRequestId self reqid
begin
set request_id = reqid
end function | def setRequestId(self, reqid) :
self.request_id = reqid | Python | nomic_cornstack_python_v1 |
import csv
import pandas as pd
import numpy as np
import requests
import json
import sys
import re
function readReviwerscsv CSVFile
begin
set df = read csv CSVFile
set Affiliation = apply Affiliation lambda x -> split x at slice 1 : - 1 : string ,
set Affiliation = list comprehension tuple lst for lst in Affiliation
c... | import csv
import pandas as pd
import numpy as np
import requests
import json
import sys
import re
def readReviwerscsv(CSVFile):
df=pd.read_csv(CSVFile)
df.Affiliation=df.Affiliation.apply(lambda x: x[1:-1].split(','))
df.Affiliation = [tuple(lst) for lst in df.Affiliation]
#df=df.assign(Affiliation=df.Affiliation... | Python | zaydzuhri_stack_edu_python |
function foo n
begin
set n = n + 100 * 500
return n
end function
function foo2 lista
begin
append lista 11
append lista 12
append lista 13
append lista 14
append lista 15
end function
print variable_dos
call foo2 variable_dos
print variable_dos
comment resultado = foo(variable_uno)
comment print(variable_uno,resultado) | def foo(n):
n += 100*500
return n
def foo2(lista):
lista.append(11)
lista.append(12)
lista.append(13)
lista.append(14)
lista.append(15)
print(variable_dos)
foo2(variable_dos)
print(variable_dos)
#resultado = foo(variable_uno)
#print(variable_uno,resultado) | Python | zaydzuhri_stack_edu_python |
from api import *
import numpy as np
from igraph import Graph , plot
import numpy as np
import igraph
function get_network users_ids as_edgelist=true
begin
set vertices = list string It's me
set edges = list
set ids = list
set relat = dict
for user_id in users_ids at string response at string items
begin
set name = ... | from api import *
import numpy as np
from igraph import Graph, plot
import numpy as np
import igraph
def get_network(users_ids, as_edgelist=True):
vertices = ["It's me"]
edges = []
ids = []
relat = {}
for user_id in users_ids['response']['items']:
name = user_id['first_name'] + user_id['l... | Python | zaydzuhri_stack_edu_python |
function is_out_bounds x y x_ax_min x_ax_max y_ax_min y_ax_max
begin
comment Our plotting area is hard coded to span the (-1, 1)^2 range
if x < x_ax_min or x > x_ax_max or y < y_ax_min or y > y_ax_max
begin
return 1
end
else
begin
return 0
end
end function | def is_out_bounds(x, y, x_ax_min, x_ax_max, y_ax_min, y_ax_max):
# Our plotting area is hard coded to span the (-1, 1)^2 range
if x < x_ax_min or x > x_ax_max or y < y_ax_min or y > y_ax_max:
return 1
else:
return 0 | Python | nomic_cornstack_python_v1 |
function visit_statements self nodes
begin
string Generate the adjoint of a series of statements.
set tuple primals adjoints = tuple list deque
for node in nodes
begin
set tuple primal adjoint = call visit node
if not is instance primal list
begin
set primal = list primal
end
if not is instance adjoint list
begin
set ... | def visit_statements(self, nodes):
"""Generate the adjoint of a series of statements."""
primals, adjoints = [], collections.deque()
for node in nodes:
primal, adjoint = self.visit(node)
if not isinstance(primal, list):
primal = [primal]
if not isinstance(adjoint, list):
ad... | Python | jtatman_500k |
import png
import numpy as np
import numpngw
from PIL import Image
import random
import cv2
import os
function to_png path
begin
set image_type = split path string .
if image_type at - 1 != string png
begin
try
begin
set im = open path
set new = string
for i in image_type
begin
if i == image_type at - 1
begin
continue... | import png
import numpy as np
import numpngw
from PIL import Image
import random
import cv2
import os
def to_png(path):
image_type = path.split('.')
if image_type[-1] != 'png':
try:
im = Image.open(path)
new = ''
for i in image_type:
if i == image_type[-1]:
continue
... | Python | zaydzuhri_stack_edu_python |
comment Set {} Unique
set set1 = set literal 1 2 3 4 4
comment {1, 2, 3, 4}
print set1
comment <class 'set'>
print type set1
comment ADD
add set1 5
comment {1, 2, 3, 4, 5}
print set1
comment UPDATE
update set1 list 6 7
comment {1, 2, 3, 4, 5, 6, 7}
print set1
comment DELETE
remove set1 7
comment {1, 2, 3, 4, 5, 6}
prin... | # Set {} Unique
set1 = {1,2,3,4,4}
print(set1) # {1, 2, 3, 4}
print(type(set1)) # <class 'set'>
# ADD
set1.add(5)
print(set1) # {1, 2, 3, 4, 5}
# UPDATE
set1.update([6,7])
print(set1) # {1, 2, 3, 4, 5, 6, 7}
# DELETE
set1.remove(7)
print(set1) # {1, 2, 3, 4, 5, 6}
set1.remove(12) # Exception - Ke... | Python | zaydzuhri_stack_edu_python |
comment author: Ljsh
comment parms : array 传入的数组
comment date : 2019/4/14
comment PyVersion 3.6
function MaxSubArray array
begin
set maxSum = 0
set thisSum = 0
for i in range length array
begin
set thisSum = call func thisSum + array at i
set maxSum = max thisSum maxSum
end
return maxSum
end function | # author: Ljsh
# parms : array 传入的数组
# date : 2019/4/14
# PyVersion 3.6
def MaxSubArray(array):
maxSum = 0
thisSum = 0
for i in range(len(array)):
thisSum = func(thisSum+array[i])
maxSum = max(thisSum,maxSum)
return maxSum
| Python | zaydzuhri_stack_edu_python |
function update_defaults_from_instrument self pInstrument ignore_changes=false
begin
if instr_name != call getName
begin
log format string *** WARNING: Setting reduction properties of the instrument {0} from the instrument {1}. *** This only works if both instruments have the same reduction properties! instr_name call ... | def update_defaults_from_instrument(self,pInstrument,ignore_changes=False):
if self.instr_name != pInstrument.getName():
self.log("*** WARNING: Setting reduction properties of the instrument {0} from the instrument {1}.\n"
"*** This only works if both instruments have the same ... | Python | nomic_cornstack_python_v1 |
function flat_lists_with_possibility lists
begin
set lists = deep copy lists
set lists = sorted lists key=len reverse=true
set list_possibility = list
set max_index = 0
set total_elements = 0
set possibilities = list
for items in lists
begin
append list_possibility 0.0
set length = length items
if length > 0
begin
se... | def flat_lists_with_possibility(lists):
lists = deepcopy(lists)
lists = sorted(lists, key=len, reverse=True)
list_possibility = []
max_index = 0
total_elements = 0
possibilities = []
for items in lists:
list_possibility.append(0.0)
length = len(items)
if length > 0:
... | Python | nomic_cornstack_python_v1 |
function _lexicon_lookup self word
begin
return word in lexicon
end function | def _lexicon_lookup(self, word):
return word in self.lexicon | Python | nomic_cornstack_python_v1 |
for i in range 1 10
begin
set route = route + height * 2
set height = height / 2
end | for i in range(1,10):
route += height*2
height /= 2
| Python | zaydzuhri_stack_edu_python |
class Myclass
begin
set i = 12345
end class
print i
class Complex
begin
function __init__ self realpart imagepart
begin
set r = realpart
set i = imagepart
end function
function __del__ self
begin
print string delete all
end function
end class
set x = call Complex 3.0 - 4.5
print r i
set x = none
class Dog
begin
functio... | class Myclass:
i = 12345
print(Myclass.i)
class Complex:
def __init__(self,realpart,imagepart):
self.r = realpart
self.i = imagepart
def __del__(self):
print('delete all')
x = Complex(3.0,-4.5)
print(x.r, x.i)
x = None
class Dog:
def __init__(self,name):
self.__name ... | Python | zaydzuhri_stack_edu_python |
import matplotlib.pyplot as plt
import sys
if __name__ == string __main__
begin
set name = argv at 1
set target = name + string .png
print string Visualize %s to %s % tuple name target
set data = list comprehension decimal l for l in open name string r if not starts with l string #
set xs = list comprehension i for i i... | import matplotlib.pyplot as plt
import sys
if __name__=='__main__':
name = sys.argv[1]
target = name + ".png"
print ("Visualize %s to %s" % (name, target))
data = [ float(l) for l in open(name, "r") if not l.startswith("#")]
xs = [ i for i in range(0, len(data))]
plt.plot(xs, data)
plt.savefig(target)
| Python | zaydzuhri_stack_edu_python |
function functionA x
begin
set answer = 0
for i in range x
begin
set answer = answer + x - i
end
return answer
end function | def functionA(x):
answer = 0
for i in range(x):
answer += x-i
return answer
| Python | flytech_python_25k |
function controller_permissions self controller_permissions
begin
set _controller_permissions = controller_permissions
end function | def controller_permissions(self, controller_permissions):
self._controller_permissions = controller_permissions | Python | nomic_cornstack_python_v1 |
function interpolate_pore_data self Tvals=none
begin
if size sp Tvals == 1
begin
set Pvals = Tvals
end
else
if size sp Tvals != call num_throats
begin
raise exception string The list of throat information received was the wrong length
end
else
begin
set Pvals = zeros call num_pores
comment Only interpolate conditions f... | def interpolate_pore_data(self,Tvals=None):
if sp.size(Tvals)==1:
Pvals = Tvals
elif sp.size(Tvals) != self.num_throats():
raise Exception('The list of throat information received was the wrong length')
else:
Pvals = sp.zeros((self.num_pores()))
#O... | Python | nomic_cornstack_python_v1 |
function test_preprocess_hic cool
begin
set clr = call Cooler cool
call preprocess_hic clr
call preprocess_hic clr region=REGION
call preprocess_hic clr min_contacts=44035
call preprocess_hic clr min_contacts=376 region=REGION
end function | def test_preprocess_hic(cool):
clr = cooler.Cooler(cool)
pah.preprocess_hic(clr)
pah.preprocess_hic(clr, region=REGION)
pah.preprocess_hic(clr, min_contacts=44035)
pah.preprocess_hic(clr, min_contacts=376, region=REGION) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
string Spyder Editor creator - Benjamin Strope last Edited: March 12 2021 12:10 Modules of linear datatypes
class Stack
begin
string linear structure, shortest var in is first one out
function __init__ self
begin
set items = list
end function
function empty self
begin
return items == list... | # -*- coding: utf-8 -*-
"""
Spyder Editor
creator - Benjamin Strope
last Edited: March 12 2021 12:10
Modules of linear datatypes
"""
class Stack:
'''linear structure, shortest var in is first one out'''
def __init__(self):
self.items = []
def empty(self):
return self.items == ... | Python | zaydzuhri_stack_edu_python |
function computeDensityBiparti self layerlabels1 layerlabels2
begin
set durationLinks = 0
set durationNodes = 0
for j in call giveListOfLinks
begin
set durationLinks = durationLinks + call duration
end
for i in call giveLayers
begin
for j in call giveLayers
begin
if call giveLayerLabel in layerlabels1 and call giveLaye... | def computeDensityBiparti(self,layerlabels1,layerlabels2):
durationLinks=0
durationNodes=0
for j in self.em.giveListOfLinks():
durationLinks=durationLinks+j.giveIntervals2().duration()
for i in self.layers.giveLayers():
for j in self.layers.giveLayers():
... | Python | nomic_cornstack_python_v1 |
function train_one_epoch net train_iter loss updater
begin
comment Set the model to training mode
train net
comment Sum of training loss, sum of training accuracy, no. of examples
set metric = call Accumulator 3
for tuple X y in train_iter
begin
comment Move data to device - GPU or CPU as set
set tuple X y = tuple to X... | def train_one_epoch (net, train_iter, loss, updater):
# Set the model to training mode
net.train()
# Sum of training loss, sum of training accuracy, no. of examples
metric = Accumulator(3)
for X, y in train_iter:
X, y = X.to(device), y.to(device) # Move data to device - GPU or CPU as set... | Python | nomic_cornstack_python_v1 |
function relaxng view_type
begin
if view_type not in _relaxng_cache
begin
with call file_open join path string base string rng string %s_view.rng % view_type as frng
begin
try
begin
set relaxng_doc = parse etree frng
set _relaxng_cache at view_type = call RelaxNG relaxng_doc
end
except Exception
begin
exception string ... | def relaxng(view_type):
if view_type not in _relaxng_cache:
with tools.file_open(os.path.join('base', 'rng', '%s_view.rng' % view_type)) as frng:
try:
relaxng_doc = etree.parse(frng)
_relaxng_cache[view_type] = etree.RelaxNG(relaxng_doc)
except Excepti... | Python | nomic_cornstack_python_v1 |
from node import node
from sklearn import preprocessing
import numpy as np
import copy
class datapoint
begin
function __init__ self state policy value=none
begin
comment unmodified state
set S = deep copy state
comment numpy array
set P = policy
comment scalar
set V = value
end function
function display self
begin
prin... | from node import node
from sklearn import preprocessing
import numpy as np
import copy
class datapoint():
def __init__(self, state, policy, value = None):
self.S = copy.deepcopy(state) #unmodified state
self.P = policy #numpy array
self.V = value ... | Python | zaydzuhri_stack_edu_python |
import math
function numcyc num numofdig numoftimes
begin
set rdig = num % power 10 numoftimes
set num = integer num / power 10 numoftimes
return integer rdig * power 10 numofdig - numoftimes + 1 + num
end function
string A=10 B=40 Barr=[4,0] count=0 for num in range (A,B): print "START FOR NUM " + num mainnum=num dig=... | import math
def numcyc(num,numofdig,numoftimes):
rdig=num%(math.pow(10,numoftimes))
num=int(num/(math.pow(10,numoftimes)))
return int(rdig*math.pow(10,numofdig-numoftimes+1) +num)
"""A=10
B=40
Barr=[4,0]
count=0
for num in range (A,B):
print "START FOR NUM " + num
mainnum=num
... | Python | zaydzuhri_stack_edu_python |
from django import template
comment 기존 템플릿 라이브러리에
set register = call Library
decorator filter
function hashtag_link word
begin
comment word는 article 객체가 들어갈건데
comment article의 content 들만 모두 가져와서 그 중 해시태그에만 링크를 붙인다.
comment 공백포함 내용 저장
set content = content + string
comment word가 가지는 hashtag전부 가져옴
set hashtags = all
co... | from django import template
register = template.Library() # 기존 템플릿 라이브러리에
@register.filter
def hashtag_link(word):
# word는 article 객체가 들어갈건데
# article의 content 들만 모두 가져와서 그 중 해시태그에만 링크를 붙인다.
content = word.content + ' ' # 공백포함 내용 저장
hashtags = word.hashtags.all() # word가 가지는 hashtag전부 가져옴
# 기존 ... | Python | zaydzuhri_stack_edu_python |
comment Section05-3
comment 파이썬 흐름제어(제어문)
comment 제어문 관련 퀴즈(정답은 영상)
comment 1 ~ 5 문제 if 구문 사용
comment 1. 아래 딕셔너리에서 '가을'에 해당하는 과일을 출력하세요.
set q1 = dict string 봄 string 딸기 ; string 여름 string 토마토 ; string 가을 string 사과
for k in keys q1
begin
if k == string 가을
begin
comment 딕셔너리에서 벨류값 출력하는 방법
print q1 at k
end
end
for tuple... | # Section05-3
# 파이썬 흐름제어(제어문)
# 제어문 관련 퀴즈(정답은 영상)
# 1 ~ 5 문제 if 구문 사용
# 1. 아래 딕셔너리에서 '가을'에 해당하는 과일을 출력하세요.
q1 = {"봄": "딸기", "여름": "토마토", "가을": "사과"}
for k in q1.keys():
if k == "가을":
print(q1[k]) # 딕셔너리에서 벨류값 출력하는 방법
for k, v in q1.items():
if k == "가을":
print(v)
# 2. 아래 딕... | Python | zaydzuhri_stack_edu_python |
function number_groups group1 group2 group3
begin
set output = list
for i in group1
begin
if i in group2 or i in group3
begin
append output i
end
end
for i in group2
begin
if i in group3
begin
append output i
end
end
return sorted list set output
end function | def number_groups(group1, group2, group3):
output = []
for i in group1:
if i in group2 or i in group3:
output.append(i)
for i in group2:
if i in group3:
output.append(i)
return sorted(list(set(output)))
| Python | zaydzuhri_stack_edu_python |
function project_net_on_place place
begin
set place_net = call PetriNet
set place_net_im = call Marking
set place_net_fm = call Marking
set input_trans = list comprehension source for arc in in_arcs
set output_trans = list comprehension target for arc in out_arcs
if length input_trans == 0 or length output_trans == 0
b... | def project_net_on_place(place):
place_net = PetriNet()
place_net_im = Marking()
place_net_fm = Marking()
input_trans = [arc.source for arc in place.in_arcs]
output_trans = [arc.target for arc in place.out_arcs]
if len(input_trans) == 0 or len(output_trans) == 0:
raise Excepti... | Python | nomic_cornstack_python_v1 |
class Tree
begin
function __init__ self value left=none right=none parent=none
begin
set value = value
set left = left
set right = right
set parent = parent
end function
function __str__ self
begin
return string value
end function
end class | class Tree:
def __init__(self, value, left = None, right = None, parent = None):
self.value = value
self.left = left
self.right = right
self.parent = parent
def __str__(self):
return str(self.value)
| Python | zaydzuhri_stack_edu_python |
function switch_tab self event direction
begin
comment Get the index of the tab that the user wants to go to
set current = index notebook select notebook
set destination = if expression direction == string next then current + 1 else current - 1
try
begin
comment Attempt to select the notebook tab
select notebook destin... | def switch_tab(self, event, direction):
# Get the index of the tab that the user wants to go to
current = self.notebook.index(self.notebook.select())
destination = (current + 1) if direction == 'next' else (current - 1)
try:
# Attempt to select the notebook tab
s... | Python | nomic_cornstack_python_v1 |
function edit_car
begin
set carid = form at string carid
set make = form at string make
set bodytype = form at string bodytype
set color = form at string color
set seats = form at string seats
set location = form at string location
set costperhour = form at string costperhour
comment create a new Car object.
set car = ... | def edit_car():
carid = request.form["carid"]
make = request.form["make"]
bodytype = request.form["bodytype"]
color = request.form["color"]
seats = request.form["seats"]
location = request.form["location"]
costperhour = request.form["costperhour"]
# create a new Car object.
car = C... | Python | nomic_cornstack_python_v1 |
function largest_n_items input_list n
begin
return list
end function | def largest_n_items(input_list, n):
return [] | Python | nomic_cornstack_python_v1 |
function setup_db_for_hist_prices_storage self stock_sym_list start=today - call relativedelta years=20 end=today
begin
for sub_list in call break_list_to_sub_list stock_sym_list
begin
comment print ('processing sub list', sub_list)
comment need to check duplicates in the database
for susublist in sub_list
begin
commen... | def setup_db_for_hist_prices_storage(self, stock_sym_list, start= datetime.date.today()-relativedelta(years=20), end = datetime.date.today()):
for sub_list in self.break_list_to_sub_list(stock_sym_list):
# print ('processing sub list', sub_list)
# need to check duplicates in the database ... | Python | nomic_cornstack_python_v1 |
function ignore_save_variables cls
begin
return list
end function | def ignore_save_variables(cls):
return [] | Python | nomic_cornstack_python_v1 |
import numpy as np
from scipy.misc import comb
function bezier points ns=20
begin
set points = array points
set n = length points
set step = 1.0 / ns
set rtn_points = list
for t in array range 0 1 + step step
begin
set c = array list 0 0 float
for tuple i p in enumerate points
begin
set c = c + call comb n - 1 i * t ^... | import numpy as np
from scipy.misc import comb
def bezier(points,ns=20):
points = np.array(points)
n = len(points)
step = 1.0/ns
rtn_points = []
for t in np.arange(0,1+step,step):
c = np.array([0,0],np.float)
for i,p in enumerate(points):
c += comb(n-1,i) * t**i * (1-t)... | Python | zaydzuhri_stack_edu_python |
function add self turn status
begin
if turn == string F or turn == string L or turn == string R
begin
append turns turn
append values status
end
end function | def add(self, turn, status):
if turn == 'F' or turn == 'L' or turn == 'R':
self.turns.append(turn)
self.values.append(status) | Python | nomic_cornstack_python_v1 |
function my_custom_logger logger_name level=INFO
begin
set logger = call getLogger logger_name
call setLevel level
set format_string = string %(asctime)s, %(levelname)s, %(filename)s, %(message)s
set log_format = call Formatter format_string
comment Creating and adding the console handler
set console_handler = call Str... | def my_custom_logger(logger_name, level=logging.INFO):
logger = logging.getLogger(logger_name)
logger.setLevel(level)
format_string = ('%(asctime)s, %(levelname)s, %(filename)s, %(message)s')
log_format = logging.Formatter(format_string)
# Creating and adding the console handler
console_handler ... | Python | nomic_cornstack_python_v1 |
function parameters_ui layout params
begin
comment r = layout.row()
comment r.prop(params, "control_num")
set pb = pose
set r = call row
set col = call column align=true
set row = call row align=true
call prop params string tweak_axis expand=true
comment for i,axis in enumerate( [ 'x', 'y', 'z' ] ):
comment row.prop(pa... | def parameters_ui(layout, params):
# r = layout.row()
# r.prop(params, "control_num")
pb = bpy.context.object.pose
r = layout.row()
col = r.column(align=True)
row = col.row(align=True)
row.prop(params, "tweak_axis", expand=True)
# for i,axis in enumerate( [ 'x', 'y', 'z' ] ):
# ... | Python | nomic_cornstack_python_v1 |
comment 012345678901234567890
set sub = string rue
set i = 0
while i < length s - length sub
begin
set a = 0
set c = 0
while a < length sub
begin
if s at i + a == sub at a
begin
set c = c + 1
end
set a = a + 1
end
end | # 012345678901234567890
sub = "rue"
i=0
while i<len(s)-len(sub):
a=0
c=0
while a<len(sub):
if s[i+a] == sub[a]:
c+=1
a+=1 | Python | zaydzuhri_stack_edu_python |
function test_block_bad_consensus self
begin
pass
end function | def test_block_bad_consensus(self):
pass | Python | nomic_cornstack_python_v1 |
comment !/usr/bin/python3
from tkinter import *
from tkinter import messagebox
class TechnologyAssetsView
begin
function __init__ self title bg_color lbl_text lbl_text_color
begin
set root = call Tk
title root title
call configure bg=bg_color
call resizable width=false height=false
set technology_assets_entry_lblframe ... | #!/usr/bin/python3
from tkinter import *
from tkinter import messagebox
class TechnologyAssetsView:
def __init__(self, title, bg_color, lbl_text, lbl_text_color):
root = Tk()
root.title(title)
root.configure(bg=bg_color)
root.resizable(width=False, height=False)
technolog... | Python | zaydzuhri_stack_edu_python |
function rocm_smi
begin
try
begin
set output = check output list string rocm-smi string -i string --json
set gpu_count = length call literal_eval decode output
end
except Exception
begin
return none
end
return gpu_count
end function | def rocm_smi():
try:
output = subprocess.check_output(["rocm-smi", "-i", "--json"])
gpu_count = len(ast.literal_eval(output.decode()))
except Exception:
return None
return gpu_count | Python | nomic_cornstack_python_v1 |
function _update_motion_data self msg
begin
if _auv_motion != motion
begin
set _target_euler at string alpha = _actual_euler at string alpha
set _target_euler at string beta = _actual_euler at string beta
set _target_euler at string gamma = _actual_euler at string gamma
set _auv_motion = motion
end
set _thrusters_actua... | def _update_motion_data(self, msg):
if self._auv_motion != msg.motion:
self._target_euler["alpha"] = self._actual_euler["alpha"]
self._target_euler["beta"] = self._actual_euler["beta"]
self._target_euler["gamma"] = self._actual_euler["gamma"]
self._auv_motion = ms... | Python | nomic_cornstack_python_v1 |
function answers self
begin
return _dns_answers
end function | def answers(self):
return self._dns_answers | Python | nomic_cornstack_python_v1 |
function setShelsCount self shellsCount
begin
for tuple shellIndex newCount in enumerate shellsCount
begin
if shellIndex in shelsData
begin
set maxCount = length shelsData at shellIndex - 1
set currentCount = get __shelsCount shellIndex 0
set __shelsCount at shellIndex = newCount
if newCount > currentCount
begin
for sh... | def setShelsCount(self, shellsCount):
for shellIndex, newCount in enumerate(shellsCount):
if shellIndex in self.__context.shelsData:
maxCount = len(self.__context.shelsData[shellIndex]) - 1
currentCount = self.__shelsCount.get(shellIndex, 0)
self.__she... | Python | nomic_cornstack_python_v1 |
from PySide2.QtWidgets import *
from PySide2.QtCore import *
import itchat
import sys
import datetime
import time
import threading
class MyTimer extends QTimer
begin
function __init__ self label
begin
call __init__ self
set label = label
end function
end class
class MyUi extends QWidget
begin
function __init__ self
beg... | from PySide2.QtWidgets import *
from PySide2.QtCore import *
import itchat
import sys
import datetime
import time
import threading
class MyTimer(QTimer):
def __init__(self, label):
QTimer.__init__(self)
self.label = label
class MyUi(QWidget):
def __init__(self):
QWidget.__init__(self)... | Python | zaydzuhri_stack_edu_python |
comment Define your item pipelines here
comment Don't forget to add your pipeline to the ITEM_PIPELINES setting
comment See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
comment useful for handling different item types with a single interface
from itemadapter import ItemAdapter
class Homework2Pipeline
be... | # Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
from itemadapter import ItemAdapter
class Homework2Pipeline:
def process_ite... | Python | zaydzuhri_stack_edu_python |
import json
from datetime import datetime
from django.test import TestCase
from library.models import Author
from library.models import Book
class TestBook extends TestCase
begin
function test_get_something_that_does_not_exist self
begin
set response = get client string /exists
assert equal 404 status_code
end function... | import json
from datetime import datetime
from django.test import TestCase
from library.models import Author
from library.models import Book
class TestBook(TestCase):
def test_get_something_that_does_not_exist(self):
response = self.client.get("/exists")
self.assertEqual(404, response.status_code... | Python | zaydzuhri_stack_edu_python |
string -Medium- *DP* *Kadane's Algorithm* Given an integer array arr and an integer k, modify the array by repeating it k times. For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2]. Return the maximum sub-array sum in the modified array. Note that the length of the sub-array can be... | '''
-Medium-
*DP*
*Kadane's Algorithm*
Given an integer array arr and an integer k, modify the array by repeating it k times.
For example, if arr = [1, 2] and k = 3 then the modified array will be [1, 2, 1, 2, 1, 2].
Return the maximum sub-array sum in the modified array. Note that the length of
the sub-array can b... | Python | zaydzuhri_stack_edu_python |
function _set_p2p_secondary_path self v load=false
begin
if has attribute v string _utype
begin
set v = call _utype v
end
try
begin
set t = call YANGDynClass v base=call YANGListType string name yc_p2p_secondary_path_openconfig_mpls_te__mpls_lsps_constrained_path_tunnels_tunnel_p2p_tunnel_attributes_p2p_secondary_paths... | def _set_p2p_secondary_path(self, v, load=False):
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=YANGListType("name",yc_p2p_secondary_path_openconfig_mpls_te__mpls_lsps_constrained_path_tunnels_tunnel_p2p_tunnel_attributes_p2p_secondary_paths_p2p_secondary_path, yang_name="p2p... | Python | nomic_cornstack_python_v1 |
function test_activate_notification self
begin
set url = reverse string set_notifications
call force_authenticate user=user
post url format=string json
set response = post url format=string json
assert equal status_code HTTP_200_OK
assert equal data at string message string You have sucessfully turned notifications on
... | def test_activate_notification(self):
url = reverse('set_notifications')
self.client.force_authenticate(user=self.user)
self.client.post(url, format="json")
response = self.client.post(url, format="json")
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.ass... | Python | nomic_cornstack_python_v1 |
import math
print call factorial integer input string Enter an Integer :
set n = integer input string Enter another Integer :
set result = 1
for i in range 1 n + 1 1
begin
set result = result * i
end
print string Factorial of + string n + string is + string result | import math
print(math.factorial(int(input("Enter an Integer : "))))
n = int(input("Enter another Integer : "))
result = 1
for i in range(1,n+1,1):
result *= i
print("Factorial of "+str(n)+" is "+str(result)) | Python | zaydzuhri_stack_edu_python |
function get_customer code
begin
string Fetch a customer with the code. Returns None if the customer is not found.
set Party = model string party.party
set results = find Party list tuple string code string = code
if results
begin
return results at 0 at string id
end
end function | def get_customer(code):
"""
Fetch a customer with the code.
Returns None if the customer is not found.
"""
Party = client.model('party.party')
results = Party.find([('code', '=', code)])
if results:
return results[0]['id'] | Python | jtatman_500k |
import json
import unittest
from poly_nlp.tasks.pre_trained.sentence_transformer import SentenceTransformerEncoderTask , SentenceTransformerTrainerTask
from poly_nlp.tasks.pre_trained.sentence_transformer.custom import SoftTailIRTrainer
from sentence_transformers.evaluation import InformationRetrievalEvaluator
class Se... | import json
import unittest
from poly_nlp.tasks.pre_trained.sentence_transformer import (
SentenceTransformerEncoderTask,
SentenceTransformerTrainerTask,
)
from poly_nlp.tasks.pre_trained.sentence_transformer.custom import SoftTailIRTrainer
from sentence_transformers.evaluation import InformationRetrievalEvalu... | Python | zaydzuhri_stack_edu_python |
function convertToTitle columnNumber
begin
set look = dict 1 string A ; 2 string B ; 3 string C ; 4 string D ; 5 string E ; 6 string F ; 7 string G ; 8 string H ; 9 string I ; 10 string J ; 11 string K ; 12 string L ; 13 string M ; 14 string N ; 15 string O ; 16 string P ; 17 string Q ; 18 string R ; 19 string S ; 20 s... | def convertToTitle(columnNumber: int) :
look = { 1 : "A", 2 :"B", 3 : "C", 4 : "D", 5 : "E", 6 : "F",
7 : "G", 8 : "H", 9 : "I", 10 :"J", 11 : "K", 12 : "L",
13 : "M", 14 : "N", 15 : "O", 16 : "P", 17 : "Q", 18 : "R",
19 : "S", 20 : "T", 21 : "U", 22 : "V", 23 : ... | Python | zaydzuhri_stack_edu_python |
function dfs graph start end visited res
begin
if start in visited
begin
return res
end
for idx in range length graph at start
begin
set to = graph at start at idx at 0
if to == end
begin
return 1
end
call dfs graph to end visited ? set literal start res
end
return 0
end function
function learn_js
begin
set vertices = ... | def dfs(graph, start, end, visited, res):
if start in visited:
return res
for idx in range(len(graph[start])):
to = graph[start][idx][0]
if to == end:
return 1
dfs(graph, to, end, (visited | {start}), res)
return 0
def learn_js():
vertices = int(input())
... | Python | zaydzuhri_stack_edu_python |
from datetime import date , datetime
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from users.models import Event , User_Profile
from invites import event_invite
import pictures
function _validate_request request
begin
string Check ... | from datetime import date, datetime
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from users.models import Event, User_Profile
from invites import event_invite
import pictures
def _validate_request(request):
'''
Check that... | Python | zaydzuhri_stack_edu_python |
import cv2
import json
function Myfind line st ed
begin
set pos0 = find line string ' st ed
set pos1 = find line string jpg st ed
comment pic_name
set picn = line at slice pos0 + 1 : pos1 + 3 :
set pos0 = find line string [ st ed
set pos1 = find line string ] st ed
comment 存放同一张图的所有数据
set my_data = list
comment 存放对于同... | import cv2
import json
def Myfind(line, st, ed):
pos0 = line.find('\'', st, ed)
pos1 = line.find('jpg', st, ed)
picn = line[pos0+1:pos1+3] # pic_name
pos0 = line.find('[', st, ed)
pos1 = line.find(']', st, ed)
my_data = [] # 存放同一张图的所有数据
user_id = [] # 存放对于同一张图,来标过的id
dat = [] ... | Python | zaydzuhri_stack_edu_python |
print 3 + 2
print 3 - 2
print 3 * 2
print 3 / 2
print 3 // 2
print 3 % 2
set num_1 = 3
set num_2 = 4
print num_1 == num_2
print num_1 != num_2
print num_1 < num_2
print num_1 >= num_2
set num1 = string 100
set num2 = string 200
print num1 + num2
set num1 = integer num1
set num2 = integer num2
print num1 + num2
set num3... | print (3 + 2)
print ( 3 -2)
print ( 3 * 2)
print (3 / 2)
print (3 // 2)
print ( 3 % 2)
num_1 = 3
num_2 = 4
print (num_1 == num_2)
print (num_1 != num_2)
print (num_1 < num_2)
print (num_1 >= num_2)
num1 = '100'
num2 = '200'
print (num1 + num2)
num1 = int(num1)
num2 = int (num2)
print (num1 + num2)
num3 = 'satyam'
nu... | Python | zaydzuhri_stack_edu_python |
from sage.all_cmdline import *
set N = integer call raw_input string
set solver = call MixedIntegerLinearProgram maximization=false solver=string GLPK
set variable = call new_variable integer=true nonnegative=true
set Rw = list 0 * N
set Ru = list 0 * N
set wSon = list
set uSon = list
for n in range 0 N
begin
append ... | from sage.all_cmdline import *
N = int(raw_input(''))
solver = MixedIntegerLinearProgram(maximization=False, solver="GLPK")
variable = solver.new_variable(integer = True, nonnegative = True)
Rw = [0] * N
Ru = [0] * N
wSon = []
uSon = []
for n in range(0, N):
wSon.append([])
uSon.append([])
for n in range(0... | Python | zaydzuhri_stack_edu_python |
function scrubLibPaths self
begin
call LogInfo string Scrubbing the LD and DYLD LIBRARY paths
call scrubLibPath string LD_LIBRARY_PATH
call scrubLibPath string DYLD_LIBRARY_PATH
call scrubLibPath string DYLD_FALLBACK_LIBRARY_PATH
call scrubLibPath string DYLD_FRAMEWORK_PATH
call scrubLibPath string DYLD_FALLBACK_FRAMEW... | def scrubLibPaths( self ):
self.LogInfo("Scrubbing the LD and DYLD LIBRARY paths")
self.scrubLibPath("LD_LIBRARY_PATH")
self.scrubLibPath("DYLD_LIBRARY_PATH")
self.scrubLibPath("DYLD_FALLBACK_LIBRARY_PATH")
self.scrubLibPath("DYLD_FRAMEWORK_PATH")
self.s... | Python | nomic_cornstack_python_v1 |
function take_step self i1 i2 alpha_array X y C b K
begin
if i1 == i2
begin
return false
end
set eps = 1e-05
set tuple alpha1 alpha2 = alpha_array at list i1 i2
set tuple y1 y2 = y at list i1 i2
set tuple X1 X2 = X at list i1 i2
set E1 = call get_output X1 alpha_array X y b - y1
set E2 = call get_output X2 alpha_array ... | def take_step(self, i1, i2, alpha_array, X, y, C, b, K):
if i1 == i2:
return False
eps = 1e-05
alpha1, alpha2 = alpha_array[[i1, i2]]
y1, y2 = y[[i1, i2]]
X1, X2 = X[[i1, i2]]
E1 = self.get_output(X1, alpha_array, X, y, b) - y1
E2 = self.get_output(X2... | Python | nomic_cornstack_python_v1 |
for i in range cases
begin
set ans = string
set t1 = input
set t2 = input
for j in range length t1
begin
if t1 at j == t2 at j
begin
set ans = ans + string .
end
else
begin
set ans = ans + string *
end
end
print t1
print t2
print ans
print
end | for i in range(cases):
ans = ""
t1 = input()
t2 = input()
for j in range(len(t1)):
if(t1[j]==t2[j]):
ans+="."
else:
ans+="*"
print(t1)
print(t2)
print(ans)
print()
| Python | zaydzuhri_stack_edu_python |
comment 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
comment 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
comment 输出:[1,2,3,6,9,8,7,4,5]
from typing import List
class Solution
begin
function spiralOrder self matrix
begin
if not matrix
begin
return list
end
comment m行,n列
set tuple m n = tuple length matrix length matrix at 0
set res = lis... | # 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
#
# 输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
# 输出:[1,2,3,6,9,8,7,4,5]
from typing import List
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if not matrix:
return []
#m行,n列
m, n = len(matrix), len(matrix[0])
... | Python | zaydzuhri_stack_edu_python |
comment Using embendding in Deep learning and Conv1D
from keras.layers import Flatten , Dense
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
set samples = list string The cat sat on the mat. string The dog ate my homework.
set token_index = dict
for sample in samples
begin
for word in split s... | # Using embendding in Deep learning and Conv1D
from keras.layers import Flatten, Dense
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
samples = ['The cat sat on the mat.', 'The dog ate my homework.']
token_index = {}
for sample in samples:
for word in sample.split():
if word not ... | Python | zaydzuhri_stack_edu_python |
function start_time self
begin
return get pulumi self string start_time
end function | def start_time(self) -> str:
return pulumi.get(self, "start_time") | Python | nomic_cornstack_python_v1 |
string Set 4: Recover the key from CBC with IV=Key Setting the IV the same as the key can lead to vulnerabilities. In this case, when the plaintext is given back, and the ciphertext can be manipulated. Suppose three blocks are encrypted. The ciphertext can be changed as follows: C0, C1, C2 = C0, 0, C0 Then when the pla... | """
Set 4: Recover the key from CBC with IV=Key
Setting the IV the same as the key can lead to vulnerabilities. In this case,
when the plaintext is given back, and the ciphertext can be manipulated.
Suppose three blocks are encrypted. The ciphertext can be changed as follows:
C0, C1, C2 = C0, 0, C0
Then when the plai... | Python | zaydzuhri_stack_edu_python |
function bubble_sort_descending arr
begin
set n = length arr
for i in range n - 1
begin
for j in range 0 n - i - 1
begin
if arr at j < arr at j + 1
begin
set tuple arr at j arr at j + 1 = tuple arr at j + 1 arr at j
end
end
end
return arr
end function
comment Example usage
set arr = list 2 5 8 9 1
set sorted_arr = call... | def bubble_sort_descending(arr):
n = len(arr)
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] < arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
# Example usage
arr = [2, 5, 8, 9, 1]
sorted_arr = bubble_sort_descending(arr)
print(sorted_arr)
| Python | greatdarklord_python_dataset |
comment 'Bergman minimal Model'
import numpy as np
import pandas as pd
set parameters = read csv string parameters.csv
set events = list string Stroke string InsulinResistance string Retinopathy string RetinalDetachment string Diet
class Pancreas
begin
function __init__ self BetaCellCount
begin
set BetaCellCount = Beta... | ##'Bergman minimal Model'
import numpy as np
import pandas as pd
parameters=pd.read_csv('parameters.csv')
events=['Stroke','InsulinResistance','Retinopathy','RetinalDetachment','Diet']
class Pancreas():
def __init__(self,BetaCellCount):
self.BetaCellCount=BetaCellCount | Python | zaydzuhri_stack_edu_python |
from model.Sql import SqlOp
function getNicknameByUsername username
begin
comment s.select('USER','username like "Showi"')
set s = call SqlOp
set allData = select s string USER format string USERNAME is "{}" username
print string #USER_DBOP.getNicknameByUsername allData
comment nickname = allData[0][1]#!!!!!!!!!!!!!!!!... | from model.Sql import SqlOp
def getNicknameByUsername(username):
s = SqlOp()#s.select('USER','username like "Showi"')
allData = s.select('USER','USERNAME is "{}"'.format(username))
print('#USER_DBOP.getNicknameByUsername',allData)
# nickname = allData[0][1]#!!!!!!!!!!!!!!!!!!!????
nickname = 'und... | Python | zaydzuhri_stack_edu_python |
function is_nan space f
begin
return call wrap call isnan f
end function | def is_nan(space, f):
return space.wrap(math.isnan(f)) | Python | nomic_cornstack_python_v1 |
comment -*- coding: utf-8 -*-
comment @Time : 2020/7/9 20:58
comment @Author : python_HongHu
comment @Email : 464646939@qq.com
comment @File : work_data_china.py
comment @Software: PyCharm
import json
import jsonpath
import pandas as pd
import pymysql as pymysql
import requests
from pyecharts import options as opts
fro... | # -*- coding: utf-8 -*-
# @Time : 2020/7/9 20:58
# @Author : python_HongHu
# @Email : 464646939@qq.com
# @File : work_data_china.py
# @Software: PyCharm
import json
import jsonpath
import pandas as pd
import pymysql as pymysql
import requests
from pyecharts import options as opts
from pyecharts.charts import ... | Python | zaydzuhri_stack_edu_python |
for i in range 1 11
begin
print i
end | for i in range(1, 11):
print(i) | Python | jtatman_500k |
function registration_name self
begin
return _registration_name
end function | def registration_name(self):
return self._registration_name | Python | nomic_cornstack_python_v1 |
function import_modules modules_path skip_list=none
begin
comment skip list not defined: create an empty one
if skip_list is none
begin
set skip_list = list
end
comment make sure __init__ is not loaded
append skip_list string __init__
comment lists python files in the current directory
set dir_entries = glob glob join... | def import_modules(modules_path, skip_list=None):
# skip list not defined: create an empty one
if skip_list is None:
skip_list = []
# make sure __init__ is not loaded
skip_list.append('__init__')
# lists python files in the current directory
dir_entries = glob.glob(os.path.join(modules_... | Python | nomic_cornstack_python_v1 |
from collections import defaultdict , Counter
from print_board import print_board
set LOCATIONS = list list - 1 - 1 list 0 - 1 list 1 - 1 list - 1 0 list 1 0 list - 1 1 list 0 1 list 1 1
function around x y board
begin
set surrounds = list
for tuple x_off y_off in LOCATIONS
begin
set check = tuple x + x_off y + y_off
... | from collections import defaultdict, Counter
from print_board import print_board
LOCATIONS = [
[-1, -1],
[0, -1],
[1, -1],
[-1, 0],
[1, 0],
[-1, 1],
[0, 1],
[1, 1]
]
def around(x, y, board):
surrounds = []
for (x_off, y_off) in LOCATIONS:
check = (x + x_off, y + y_off)
i... | Python | zaydzuhri_stack_edu_python |
comment Heather Stafford
comment 5/14/18
comment homework6.py - how to struggle
string file = open('engmix.txt') word = input('Enter a word: ') result = 'is not' for line in file: if word == line.strip(): result = 'is' print('The word', result, 'in the dictionary') file = open('engmix.txt') L = [] for line in file: L.a... | #Heather Stafford
#5/14/18
#homework6.py - how to struggle
"""
file = open('engmix.txt')
word = input('Enter a word: ')
result = 'is not'
for line in file:
if word == line.strip():
result = 'is'
print('The word', result, 'in the dictionary')
file = open('engmix.txt')
L = []
for line in file... | Python | zaydzuhri_stack_edu_python |
from telegram import Update
from telegram.ext import CommandHandler , CallbackContext
from functionalities.functionalities import BotFunctionality
from subscription_watcher import SubscriptionWatcher , Subscription
class SubscriptionFunctionality extends BotFunctionality
begin
function __init__ self watcher
begin
call ... | from telegram import Update
from telegram.ext import CommandHandler, CallbackContext
from functionalities.functionalities import BotFunctionality
from subscription_watcher import SubscriptionWatcher, Subscription
class SubscriptionFunctionality(BotFunctionality):
def __init__(self, watcher: SubscriptionWatcher)... | Python | zaydzuhri_stack_edu_python |
from datetime import datetime
import cv2
import numpy as np
from sklearn.cluster import KMeans , MiniBatchKMeans
class FeatureGetter extends object
begin
function __init__ self
begin
set sift_det = call SIFT_create
end function
function get_img self img_path
begin
set img = call imread img_path
return img
end function
... | from datetime import datetime
import cv2
import numpy as np
from sklearn.cluster import KMeans,MiniBatchKMeans
class FeatureGetter(object):
def __init__(self):
self.sift_det = cv2.xfeatures2d.SIFT_create()
def get_img(self, img_path):
img = cv2.imread(img_path)
return img
def get_fe... | Python | zaydzuhri_stack_edu_python |
import jieba.analyse
class Pickup
begin
function pickup self content
begin
set trank = call TextRank
set span = 5
set words = call textrank content topK=2 allowPOS=list string ns string n string vn string v string nr string x
return words
end function
function separate self content
begin
set result = list
for s in cal... | import jieba.analyse
class Pickup:
def pickup(self, content):
trank = jieba.analyse.TextRank()
trank.span = 5
words = trank.textrank(content, topK=2,
allowPOS=['ns', 'n', 'vn', 'v', 'nr', 'x'])
return words
def separate(self, content):
re... | Python | zaydzuhri_stack_edu_python |
string @Author: Uthsavi KP @Date: 2021-01-05 08:25:53 @Last Modified by: Uthsavi KP @Last Modified time: 2021-01-05 08:25:53 @Title : To Convert List To Tuple
class ListToTuple
begin
function __init__ self
begin
set list_items = list 1 9 2 8 3
end function
function list_to_tuple_conversion self
begin
string converting ... | '''
@Author: Uthsavi KP
@Date: 2021-01-05 08:25:53
@Last Modified by: Uthsavi KP
@Last Modified time: 2021-01-05 08:25:53
@Title : To Convert List To Tuple
'''
class ListToTuple:
def __init__(self):
self.list_items = [1,9,2,8,3]
def list_to_tuple_conversion(self):
"""
converting li... | Python | zaydzuhri_stack_edu_python |
from comp61542.statistics import average , utils
import itertools
import numpy as np
from xml.sax import handler , make_parser , SAXException
from comp61542 import app
set PublicationType = list string Conference Paper string Journal string Book string Book Chapter
class Publication
begin
set CONFERENCE_PAPER = 0
set J... | from comp61542.statistics import average, utils
import itertools
import numpy as np
from xml.sax import handler, make_parser, SAXException
from comp61542 import app
PublicationType = [
"Conference Paper", "Journal", "Book", "Book Chapter"]
class Publication:
CONFERENCE_PAPER = 0
JOURNAL = 1
BOOK = 2
... | Python | zaydzuhri_stack_edu_python |
function migrate cr version
begin
pass
end function | def migrate(cr, version):
pass | Python | nomic_cornstack_python_v1 |
from graphics import *
class Wheel
begin
function __init__ self center wheel_radius tire_radius
begin
set tire_circle = call Circle center tire_radius
set wheel_circle = call Circle center wheel_radius
end function
function draw self win
begin
set win = win
call draw win
call draw win
end function
function undraw self
... | from graphics import *
class Wheel():
def __init__(self, center, wheel_radius, tire_radius):
self.tire_circle = Circle(center, tire_radius)
self.wheel_circle = Circle(center, wheel_radius)
def draw(self, win):
self.win = win
self.tire_circle.draw(win)
self.wheel_circle... | Python | zaydzuhri_stack_edu_python |
comment error = "엄마핀구아들이 "파이썬이 좋아"라고 했데"
set long_string = string 첫째줄은 좋은데 둘째줄도 괜찮을까?
print long_string
set quote1 = string 가끔은 '와 + string "를 모두 쓰기도 해
set quote2 = string 가끔은 '와 "를 모두 쓰기도 해
print quote1
print quote2 | # error = "엄마핀구아들이 "파이썬이 좋아"라고 했데"
long_string = '''첫째줄은 좋은데
둘째줄도 괜찮을까?'''
print(long_string)
quote1 = "가끔은 '와" + '"를 모두 쓰기도 해'
quote2 = """가끔은 '와 "를 모두 쓰기도 해"""
print(quote1)
print(quote2)
| Python | zaydzuhri_stack_edu_python |
from sequences import building_set_cumulative_sequences , builiding_sequences
from sequences import display_cumulative_sequences , display_sequences
from matplotlib import pyplot as plt
from numpy import mean , std , amax , amin
from returns import read_data , building_returns
comment Method that returns mean, standard... | from sequences import building_set_cumulative_sequences, builiding_sequences
from sequences import display_cumulative_sequences, display_sequences
from matplotlib import pyplot as plt
from numpy import mean, std, amax, amin
from returns import read_data, building_returns
# Method that returns mean, standard devi... | Python | zaydzuhri_stack_edu_python |
function favorite_dessert users_dessert
begin
return string How did you know I liked { users_dessert } ?
end function | def favorite_dessert(users_dessert):
return f"How did you know I liked {users_dessert}?" | Python | nomic_cornstack_python_v1 |
class ListNode
begin
function __init__ self val=0 next=none
begin
set val = val
set next = next
end function
end class
function addTwoNumbers l1 l2
begin
set dummy = call ListNode
set curr = dummy
set carry = 0
while l1 or l2 or carry != 0
begin
set num1 = if expression l1 then val else 0
set num2 = if expression l2 th... | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def addTwoNumbers(l1, l2):
dummy = ListNode()
curr = dummy
carry = 0
while l1 or l2 or carry != 0:
num1 = l1.val if l1 else 0
num2 = l2.val if l2 else 0
total = num1 + num... | Python | jtatman_500k |
import cv2
from polygon_drawer import PolygonDrawer
from tracker import Tracker
from distance_calculator import DistanceCalculator
from unit_converter import UnitConverter
from rect_matcher import RectMatcher
from tracker_drawer import TrackerDrawer
from csv_writer import CsvWriter
from center_finder import CenterFinde... | import cv2
from polygon_drawer import PolygonDrawer
from tracker import Tracker
from distance_calculator import DistanceCalculator
from unit_converter import UnitConverter
from rect_matcher import RectMatcher
from tracker_drawer import TrackerDrawer
from csv_writer import CsvWriter
from center_finder import CenterFinde... | Python | zaydzuhri_stack_edu_python |
import numpy as np
import sklearn
import librosa
import glob
function detect_leading_silence sound silence_threshold=0.001 chunk_size=10
begin
comment this function first normalizes audio data
comment calculates the amplitude of each frame
comment silence_threshold is used to flip the silence part
comment the number of... | import numpy as np
import sklearn
import librosa
import glob
def detect_leading_silence(sound, silence_threshold=.001, chunk_size=10):
# this function first normalizes audio data
#calculates the amplitude of each frame
#silence_threshold is used to flip the silence part
#the number of silence frame is ... | Python | zaydzuhri_stack_edu_python |
comment -*- coding: utf-8 -*-
import requests , csv , sys
from bs4 import BeautifulSoup
from PIL import Image
from io import BytesIO
set keyword = string 弱受
close open format string {}.csv keyword string w encoding=string utf-8-sig
set file = open format string {}.csv keyword string a encoding=string utf-8-sig
set writ... | # -*- coding: utf-8 -*-
import requests, csv, sys
from bs4 import BeautifulSoup
from PIL import Image
from io import BytesIO
keyword = "弱受"
open("{}.csv".format(keyword), "w", encoding='utf-8-sig').close()
file = open("{}.csv".format(keyword), "a", encoding='utf-8-sig')
writer = csv.writer(file)
def get_url(page):
... | Python | zaydzuhri_stack_edu_python |
import time
from apscheduler.schedulers.blocking import BlockingScheduler
function job
begin
print string format time time string %Y-%m-%d %H:%M:%S call localtime time
end function
if __name__ == string __main__
begin
comment BlockingScheduler:在进程中运行单个任务,调度器是唯一运行的东西
set scheduler = call BlockingScheduler
comment 采用阻塞的方... | import time
from apscheduler.schedulers.blocking import BlockingScheduler
def job():
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))
if __name__ == '__main__':
# BlockingScheduler:在进程中运行单个任务,调度器是唯一运行的东西
scheduler = BlockingScheduler()
# 采用阻塞的方式
# 采用date的方式,在特定时间只执行... | Python | zaydzuhri_stack_edu_python |
function __init__ __self__ duration
begin
set __self__ string duration duration
end function | def __init__(__self__, *,
duration: pulumi.Input[str]):
pulumi.set(__self__, "duration", duration) | 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.