code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import RPi.GPIO as GPIO import asyncio class Traffic begin function __init__ self arah dio pinTraffic begin set __arah = arah set __dio = dio set __pinTraffic = pinTraffic end function function getDio self begin return __dio end function function getGreenTime self begin return __greentime end function function getRedTi...
import RPi.GPIO as GPIO import asyncio class Traffic: def __init__(self,arah, dio,pinTraffic): self.__arah = arah self.__dio = dio self.__pinTraffic = pinTraffic def getDio(self): return self.__dio def getGreenTime(self): return self.__greentime de...
Python
zaydzuhri_stack_edu_python
function __repr__ self begin return call to_str end function
def __repr__(self): return self.to_str()
Python
nomic_cornstack_python_v1
string Program to predict the quality of a text using supervised learning import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.svm import SVC comment Load the training dataset set train_data = read csv string data comment Preprocess the data by creating features using CountVector...
""" Program to predict the quality of a text using supervised learning """ import pandas as pd from sklearn.feature_extraction.text import CountVectorizer from sklearn.svm import SVC #Load the training dataset train_data = pd.read_csv("data") #Preprocess the data by creating features using CountVectorizer vectorizer...
Python
jtatman_500k
import numpy as np function test_check_type_invalid begin from sudoku.loader import check_type assert call check_type none is false end function function test_check_type_valid begin from sudoku.loader import check_type assert call check_type call ndarray shape=tuple 9 9 is true end function function test_check_shape_va...
import numpy as np def test_check_type_invalid(): from sudoku.loader import check_type assert check_type(None) is False def test_check_type_valid(): from sudoku.loader import check_type assert check_type(np.ndarray(shape=(9, 9))) is True def test_check_shape_valid(): from sudoku.loader impor...
Python
zaydzuhri_stack_edu_python
function UpdateablePersonFactory FullPersonFactory begin function create_updateable_person address_book **kw begin set default kw string keywords list KEYWORD set default kw string last_name string Tester return call FullPersonFactory address_book keyword kw end function return create_updateable_person end function
def UpdateablePersonFactory(FullPersonFactory): def create_updateable_person(address_book, **kw): kw.setdefault('keywords', [KEYWORD]) kw.setdefault('last_name', u'Tester') return FullPersonFactory(address_book, **kw) return create_updateable_person
Python
nomic_cornstack_python_v1
function test_repositories_repo_name_labels_get self begin pass end function
def test_repositories_repo_name_labels_get(self): pass
Python
nomic_cornstack_python_v1
function sprot_search_ful text make_wild=none swissprot=1 trembl=none cgi=string http://www.expasy.ch/cgi-bin/sprot-search-ful begin set variables = dict string SEARCH text if make_wild begin set variables at string makeWild = string on end if swissprot begin set variables at string S = string on end if trembl begin se...
def sprot_search_ful(text, make_wild=None, swissprot=1, trembl=None, cgi='http://www.expasy.ch/cgi-bin/sprot-search-ful'): variables = {'SEARCH' : text} if make_wild: variables['makeWild'] = 'on' if swissprot: variables['S'] = 'on' if trembl: variables['T'] =...
Python
nomic_cornstack_python_v1
comment !usr/bin/env python comment -*- coding:utf-8 -*- comment author: sfhong2020 time:2020/3/30 19:20 function existWordWay board word begin set tuple m n = tuple length board length board at 0 if m == 0 begin return false end set marked = list comprehension list comprehension false for _ in range n for _ in range m...
#!usr/bin/env python # -*- coding:utf-8 -*- # author: sfhong2020 time:2020/3/30 19:20 def existWordWay(board, word): m, n = len(board), len(board[0]) if m == 0: return False marked = [[False for _ in range(n)] for _ in range(m)] directions = [(0, 1), (0, -1), (1, 0), (-1, 0)] def search_word(boar...
Python
zaydzuhri_stack_edu_python
function draw self begin call start_render call draw_lrwh_rectangle_textured 0 0 SCREEN_WIDTH SCREEN_HEIGHT background set background = toxicity_assets at toxicity at string overworld call draw_background background comment Draw rule set tuple name description = split upper rule string - set name = call draw_text name ...
def draw(self) -> None: arcade.start_render() arcade.draw_lrwh_rectangle_textured( 0, 0, constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT, self.background ) background = self.toxicity_assets[self.toxicity]["overworld"] self.draw_background(background) # Draw ...
Python
nomic_cornstack_python_v1
function consistencyCheckP5a self state begin call logCheckDescription string P5a indentation=3 set passed = true end function
def consistencyCheckP5a(self, state): logCheckDescription("P5a", indentation=3) passed = True
Python
nomic_cornstack_python_v1
function snmpqosqos_real_bytes self begin try begin return _snmpqosqos_real_bytes end except Exception as e begin raise e end end function
def snmpqosqos_real_bytes(self) : try : return self._snmpqosqos_real_bytes except Exception as e: raise e
Python
nomic_cornstack_python_v1
from glob import glob from numpy.core.fromnumeric import shape import torch from torch.utils.data.dataloader import DataLoader from torch.utils.data.dataset import Dataset from torchvision.io import read_image import numpy as np class MammoDataset extends Dataset begin function __init__ self image_dir label_dir image_s...
from glob import glob from numpy.core.fromnumeric import shape import torch from torch.utils.data.dataloader import DataLoader from torch.utils.data.dataset import Dataset from torchvision.io import read_image import numpy as np class MammoDataset(Dataset): def __init__(self, image_dir, label_dir, image_suffix='jp...
Python
zaydzuhri_stack_edu_python
string ATC SpOT Weather Status Listens to Davis VP2 weather data, logs Dome Health & Safety decisions from openpyxl import load_workbook import os from spot import Dome import logging import datetime from io import BufferedWriter , FileIO import time from spot.Dome import Dome from astral import Astral set path = strin...
''' ATC SpOT Weather Status Listens to Davis VP2 weather data, logs Dome Health & Safety decisions ''' from openpyxl import load_workbook import os from spot import Dome import logging import datetime from io import BufferedWriter, FileIO import time from spot.Dome import Dome from astral import Astral path = 'SpOT/dat...
Python
zaydzuhri_stack_edu_python
import numpy as np class LogisticRegression begin function __init__ self X y tolerance=1e-05 begin string Initializes Class for Logistic Regression Parameters ---------- X : ndarray(n-rows,m-features) Numerical training data. y: ndarray(n-rows,) Interger training labels. tolerance : float (default 1e-5) Stopping thresh...
import numpy as np class LogisticRegression: def __init__(self,X,y,tolerance=1e-5): """Initializes Class for Logistic Regression Parameters ---------- X : ndarray(n-rows,m-features) Numerical training data. y: ndarray(n-rows,) Interger training labels. tolerance : float (default 1e-5) St...
Python
zaydzuhri_stack_edu_python
for i in range 0 n - k begin set s = s + string l at i + string end print strip s
for i in range(0,n-k): s=s+str(l[i])+" " print(s.strip())
Python
zaydzuhri_stack_edu_python
import numpy as np import matplotlib.pyplot as plt import os function read_data path begin set data_str = list with open path string r as fr begin set lines = read lines fr for line in lines begin append data_str split line end end return as type array data_str float64 end function function plot_res C_set k begin comm...
import numpy as np import matplotlib.pyplot as plt import os def read_data(path): data_str = [] with open(path, 'r') as fr: lines = fr.readlines() for line in lines: data_str.append(line.split()) return np.array(data_str).astype(np.float64) def plot_res(C_set, k): # print...
Python
zaydzuhri_stack_edu_python
while duvidas begin set tem_duvidas = input string duvida?: if tem_duvidas != string não begin print string Pratique mais end else begin set duvidas = false end end print string Até a próxima
while duvidas: tem_duvidas = input ('duvida?: ') if tem_duvidas !='não': print ('Pratique mais') else: duvidas= False print ('Até a próxima')
Python
zaydzuhri_stack_edu_python
for line in f begin set linestr = string set data = split line string , for i in range length feats begin if feats at i at slice : 3 : == string CCC or is upper feats at i begin if data at 2 + i != string and data at 2 + i != string 0 begin set linestr = linestr + string + string i + 2 + string : + data at 2 + i e...
for line in f: linestr = "" data = line.split(",") for i in range(len(feats)): if feats[i][:3] == "CCC" or feats[i].isupper(): if data[2 + i] != "" and data[2 + i] != "0": linestr += " " + str(i +2) + ":" + data[2+i] if feats[i] == "secondoutlier": ...
Python
zaydzuhri_stack_edu_python
function display_name self begin return get pulumi self string display_name end function
def display_name(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "display_name")
Python
nomic_cornstack_python_v1
function rename self ops begin comment Super hacky import. Its only used for typechecking comment pylint: disable=import-outside-toplevel for operation in reversed ops begin if is instance operation Function begin set func_name = function_name return end end end function
def rename(self, ops: List[Operation]): # Super hacky import. Its only used for typechecking # pylint: disable=import-outside-toplevel for operation in reversed(ops): if isinstance(operation, Function): self.func_name = operation.function_name return
Python
nomic_cornstack_python_v1
function result self begin try begin set result_path = call inquire string RSTFILE end except RuntimeError begin set result_path = string end if not result_path begin set result_path = join path path string %s.rst % _jobname end else if not directory name path result_path begin set result_path = join path path string ...
def result(self): try: result_path = self.inquire('RSTFILE') except RuntimeError: result_path = '' if not result_path: result_path = os.path.join(self.path, '%s.rst' % self._jobname) elif not os.path.dirname(result_path): result_path = os....
Python
nomic_cornstack_python_v1
string A basic Stack implementation in Python using array, with the following functionalities implemented: -Push operation -Pop operation -Display stack class Stack begin function __init__ self begin set stack = list end function function insertElement self data begin append stack data end function function deleteEleme...
''' A basic Stack implementation in Python using array, with the following functionalities implemented: -Push operation -Pop operation -Display stack ''' class Stack: def __init__(self): self.stack = list() def insertElement(self, data): self.stack.append(data) def de...
Python
zaydzuhri_stack_edu_python
function plot2DRepresentation self begin set fig = figure figsize=tuple 8 6 set tuple actual_points expected_points = call getActualAndExpectedPoints for tuple i tuple key point in enumerate actual_points begin scatter plt x y call text x y string key end if __is_one_2_many_match begin set tuple reference_label point2 ...
def plot2DRepresentation(self): fig = plt.figure(figsize=(8, 6)) actual_points, expected_points = self.getActualAndExpectedPoints() for i, (key, point) in enumerate(actual_points): plt.scatter(point.x, point.y) plt.text(point.x, point.y, str(key)) if self.__is_one...
Python
nomic_cornstack_python_v1
comment Print Fibbonaci numbers up to n function fib n begin set tuple a b = tuple 0 1 while a < n begin print a set tuple a b = tuple b a + b end return none end function comment For every number between 0 and n: if number can be divided by 3-print 'Fizz', by 5-print 'Buzz', by both - print 'FizzBuzz' function fizzBuz...
# Print Fibbonaci numbers up to n def fib(n): a, b = 0, 1 while a < n: print(a) a, b = b, a+b return None # For every number between 0 and n: if number can be divided by 3-print 'Fizz', by 5-print 'Buzz', by both - print 'FizzBuzz' def fizzBuzz(n): for num in range(n+1): if num % 3 == 0: if nu...
Python
zaydzuhri_stack_edu_python
comment Review II set Celular = integer input string Ingrese su número de celular: set Email = input string Escriba su email más usado: set EmailFormato = lower Email print string Ubicación: LIMA - CALLAO- PROVINCIA set Ubicación = upper input string Escriba la ubicación escogida if Ubicación in tuple string LIMA strin...
#Review II Celular=int(input("Ingrese su número de celular:")) Email=input("Escriba su email más usado: ") EmailFormato=Email.lower() print("Ubicación: LIMA - CALLAO- PROVINCIA") Ubicación=input("Escriba la ubicación escogida").upper() if Ubicación in ("LIMA","CALLAO","PROVINCIA"): print("Escogió: "+ Ubicación) pr...
Python
zaydzuhri_stack_edu_python
for i in range 10 begin for j in range 11 20 begin print i * j end end
for i in range(10): for j in range(11,20): print(i*j)
Python
zaydzuhri_stack_edu_python
from tkinter import Tk , Button , Frame class b begin set i = integer set j = integer function press self i j begin print i j end function function __init__ self f i j begin set i = i set j = j grid row=i column=j end function end class set root = call Tk title root string Button Array call geometry string 720x360 set ...
from tkinter import Tk,Button,Frame class b: i=int() j=int() def press(self,i,j): print(i,j) def __init__(self,f,i,j): self.i=i self.j=j Button(f,text=chr(i+65)+str(j),height=2,width=6,command=lambda: self.press(self.i,self.j)).grid(row=i,column=j) root = Tk() root.titl...
Python
zaydzuhri_stack_edu_python
comment rint(questions.split('?')) comment print("Where now? Who now? When now?".split('? '))
#rint(questions.split('?')) #print("Where now? Who now? When now?".split('? '))
Python
zaydzuhri_stack_edu_python
import sys import time if __name__ == string __main__ begin set stdout = string hello world print string hello world sleep 600 print string bey exit 0 end
import sys import time if __name__ == '__main__': sys.stdout = 'hello world' print('hello world') time.sleep(600) print('bey') sys.exit(0)
Python
zaydzuhri_stack_edu_python
function __init__ self json_data begin set json_data = json_data end function
def __init__(self, json_data): self.json_data = json_data
Python
nomic_cornstack_python_v1
comment def gen_str(): comment return 'abcdefghijklmnopqrstuvwyz' comment print(gen_str()) comment import random comment import os comment with open('user.txt','a+') as f: comment for i in range (200): comment s = gen_str()[:6] comment password = '0000' comment result = s+'_'+str(i)+'|'+password+'\n' comment f.write(re...
#def gen_str(): # return 'abcdefghijklmnopqrstuvwyz' #print(gen_str()) #import random #import os #with open('user.txt','a+') as f: # for i in range (200): # s = gen_str()[:6] # password = '0000' # result = s+'_'+str(i)+'|'+password+'\n' # f.write(result) import random import time str_l...
Python
zaydzuhri_stack_edu_python
function click_ele self xpath begin set wait = call WebDriverWait driver DEFAULT_WAIT set ele = call until call element_to_be_clickable tuple XPATH xpath call click end function
def click_ele(self, xpath): wait = WebDriverWait(self.driver, DEFAULT_WAIT) ele = wait.until(EC.element_to_be_clickable((By.XPATH, xpath))) ele.click()
Python
nomic_cornstack_python_v1
from cryptography.fernet import Fernet comment Generate key set key = call generate_key comment Initialize Fernet object set cipher = call Fernet key comment Encrypt and decrypt a message set text = string hello world set encrypted = call encrypt encode text set decrypted = decode call decrypt encrypted print string En...
from cryptography.fernet import Fernet # Generate key key = Fernet.generate_key() # Initialize Fernet object cipher = Fernet(key) # Encrypt and decrypt a message text = 'hello world' encrypted = cipher.encrypt(text.encode()) decrypted = cipher.decrypt(encrypted).decode() print(f'Encrypted: {encrypted}, Decrypted: {...
Python
flytech_python_25k
from selenium import webdriver import time set driver = call Chrome get driver string http://www.imooc.com/article/ai sleep 2 set js = string document.documentElement.scrollTop=100000; set t = true while t begin set element_list = call find_elements_by_class_name string article-lwrap for element in element_list begin s...
from selenium import webdriver import time driver = webdriver.Chrome() driver.get('http://www.imooc.com/article/ai') time.sleep(2) js = 'document.documentElement.scrollTop=100000;' t = True while t: element_list = driver.find_elements_by_class_name('article-lwrap') for element in element_list: text = el...
Python
zaydzuhri_stack_edu_python
function _integrate_fast grid values begin set integral = 0 for i in range length grid - 1 begin set w = grid at i + 1 - grid at i set h = values at i + values at i + 1 set integral = integral + w * h / 2 end comment type: ignore return integral end function
def _integrate_fast(grid: ndarray, values: ndarray) -> f64: integral = 0 for i in range(len(grid) - 1): w = grid[i + 1] - grid[i] h = values[i] + values[i + 1] integral += w * h / 2 return integral # type: ignore
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np import matplotlib.pyplot as plt import math import econtools.metrics as mt import seaborn as sns import os import sys append path directory name path absolute path path directory name path __file__ import data_management.figures_management import data_management.tables_management ...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import math import econtools.metrics as mt import seaborn as sns import os import sys sys.path.append(os.path.dirname(os.path.abspath(os.path.dirname(__file__)))) import data_management.figures_management import data_management.tables_management imp...
Python
zaydzuhri_stack_edu_python
comment 一个.py文件就称之为一个模块(Module) comment 为了避免模块名冲突,Python又引入了按目录来组织模块的方法,称为包(Package) comment 引入了包以后,只要顶层的包名不与别人冲突,那所有模块都不会与别人冲突。现在,abc.py模块的名字就变成了mycompany.abc,类似的,xyz.py的模块名变成了mycompany.xyz。 comment 每一个包目录下面都会有一个__init__.py的文件,这个文件是必须存在的,否则,Python就把这个目录当成普通目录,而不是一个包。__init__.py可以是空文件,也可以有Python代码,因为__init__.py本身就是一个模块...
#一个.py文件就称之为一个模块(Module) #为了避免模块名冲突,Python又引入了按目录来组织模块的方法,称为包(Package) #引入了包以后,只要顶层的包名不与别人冲突,那所有模块都不会与别人冲突。现在,abc.py模块的名字就变成了mycompany.abc,类似的,xyz.py的模块名变成了mycompany.xyz。 #每一个包目录下面都会有一个__init__.py的文件,这个文件是必须存在的,否则,Python就把这个目录当成普通目录,而不是一个包。__init__.py可以是空文件,也可以有Python代码,因为__init__.py本身就是一个模块,而它的模块名就是mycompany #一个包也可以看为...
Python
zaydzuhri_stack_edu_python
import argparse import json function average xs begin return decimal sum xs / length xs end function function main stats_file begin string When you evaluate a policy on a gym environment (see run_ai.py and run_self.py), gym produces a directory with a bunch of statistics files summarizing the performance of the policy....
import argparse import json def average(xs): return float(sum(xs)) / len(xs) def main(stats_file): """ When you evaluate a policy on a gym environment (see run_ai.py and run_self.py), gym produces a directory with a bunch of statistics files summarizing the performance of the policy. The stats fil...
Python
zaydzuhri_stack_edu_python
function SetResultVar self var begin set callResult = call _Call string SetResultVar var end function
def SetResultVar(self, var): callResult = self._Call("SetResultVar", var)
Python
nomic_cornstack_python_v1
function set_range_value self data begin string Validates date range by parsing into 2 datetime objects and validating them both. set dtfrom = pop data string value_from set dtto = pop data string value_to if dtfrom is dtto is none begin set errors at string value = list string Date range requires values raise call Val...
def set_range_value(self, data): """ Validates date range by parsing into 2 datetime objects and validating them both. """ dtfrom = data.pop('value_from') dtto = data.pop('value_to') if dtfrom is dtto is None: self.errors['value'] = ['Date range requir...
Python
jtatman_500k
function initialize self begin pass end function
def initialize(self): pass
Python
nomic_cornstack_python_v1
string Customer Relationship Management (CRM) module Data table structure: * id (string): Unique and random generated identifier at least 2 special characters (except: ';'), 2 number, 2 lower and 2 upper case letters) * name (string) * email (string) * subscribed (int): Is she/he subscribed to the newsletter? 1/0 = yes...
""" Customer Relationship Management (CRM) module Data table structure: * id (string): Unique and random generated identifier at least 2 special characters (except: ';'), 2 number, 2 lower and 2 upper case letters) * name (string) * email (string) * subscribed (int): Is she/he subscribed to the...
Python
zaydzuhri_stack_edu_python
function _process_sentence self sentence begin comment regex for floats and integers starting with optional $ or € set regex = compile string ^[$€]?(?=.)([+-]?([0-9]*)(\.([0-9]+))?)$ comment split into words if language == string russian and lemma begin set tokenized = call lemmatize sentence end else begin set tokeniz...
def _process_sentence(self, sentence): #regex for floats and integers starting with optional $ or € regex = re.compile(r'^[$€]?(?=.)([+-]?([0-9]*)(\.([0-9]+))?)$') #split into words if self.language == 'russian' and self.lemma: tokenized = self.m.lemmatize(sentence) ...
Python
nomic_cornstack_python_v1
import os set parentdir = directory name path directory name path absolute path path __file__ insert path 0 parentdir from libs.TimeMachine.TimeValuePattern.patterns.TimeValuePattern_ParticlePos import * class TimeValue extends object begin function __init__ self value frame pattern=none begin set value = value set fra...
import os parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) os.sys.path.insert(0,parentdir) from libs.TimeMachine.TimeValuePattern.patterns.TimeValuePattern_ParticlePos import* class TimeValue(object): def __init__(self, value, frame, pattern=None): self.value = value self.f...
Python
zaydzuhri_stack_edu_python
function FastqGGIterator handle begin set handle_readline = readline while true begin set line = call handle_readline if line == string begin return end if line at 0 == string @ begin break end end while true begin set title_lines = list set seq_strings = list set quality_strings = list set count = 0 while count < ...
def FastqGGIterator(handle): handle_readline = handle.readline while True: line = handle_readline() if line == "" : return if line[0] == "@": break while True: title_lines = [] seq_strings = [] quality_strings = [] count = 0 while c...
Python
nomic_cornstack_python_v1
function write_frame self data header=none **kwargs begin if not is instance data VDIFFrame begin set data = call fromdata data header keyword kwargs end return call tofile self end function
def write_frame(self, data, header=None, **kwargs): if not isinstance(data, VDIFFrame): data = VDIFFrame.fromdata(data, header, **kwargs) return data.tofile(self)
Python
nomic_cornstack_python_v1
function __sub__ self other begin return call from_xyz call X - call X call Y - call Y call Z - call Z end function
def __sub__(self, other): return Vector.from_xyz(self.X() - other.X(), self.Y() - other.Y(), self.Z() - other.Z())
Python
nomic_cornstack_python_v1
string You are given n vertices and m edges of a graph.your task is to find all the vertices that have remaining all other vertices as neighbours in the graph. If no such vertices are present in the graph print -1 Note :given graph is undirected graph Input: First line contains number of vertices n Second line contains...
""" You are given n vertices and m edges of a graph.your task is to find all the vertices that have remaining all other vertices as neighbours in the graph. If no such vertices are present in the graph print -1 Note :given graph is undirected graph Input: First line contains number of vertices n Second line contain...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python import sys import re import os import shutil import commands from jnpr.junos import Device from pprint import pprint as pp string Display SRX AppTrack Table function print_app_table dev begin string Print the application tracking table. set applications = list set bytes = list set sessions = ...
#!/usr/bin/python import sys import re import os import shutil import commands from jnpr.junos import Device from pprint import pprint as pp """Display SRX AppTrack Table """ def print_app_table(dev): """ Print the application tracking table. """ applications = [] bytes = [] sessions = [] encryp...
Python
zaydzuhri_stack_edu_python
function train self train_gen valid_gen=none optimizer=sgd lr=0.001 momentum=0.9 decay=4e-05 nesterov=true classifier_dropout=0.7 steps_per_epoch=100 validation_steps=100 epochs=1 out_prefix=string out_period=1 fix_extractor=false begin set trainable = true set trainable = not fix_extractor set rate = classifier_dropo...
def train(self, train_gen, valid_gen=None, optimizer=SGD(lr=0.001, momentum=0.9, decay=0.00004, nesterov=True), classifier_dropout=0.7, steps_per_epoch=100, validation_steps=100, epochs=1, out_prefix='', out_period=1, fix_extractor=False): self.classifier().trainable = True self.e...
Python
nomic_cornstack_python_v1
function check_args self args kwargs begin set compargs = _current_args set spillover = none set required = list end function
def check_args(self, args, kwargs): compargs=self._current_args spillover=None required=[]
Python
nomic_cornstack_python_v1
class Funcionario begin set _salario = 0 function __init__ self salario begin set _salario = salario end function function bonifica self valor begin set _salario = _salario + valor end function function get_salario self begin return _salario end function end class
class Funcionario: _salario = 0 def __init__(self,salario): self._salario = salario def bonifica(self, valor): self._salario += valor def get_salario(self): return self._salario
Python
zaydzuhri_stack_edu_python
function checkMagazine magazine note begin set dict = dict for word in magazine begin if word in dict begin set dict at word = dict at word + 1 end else begin set dict at word = 1 end end for word in note begin if word not in dict begin print string No return end else begin set occurences = dict at word if occurences ...
def checkMagazine(magazine, note): dict = {} for word in magazine: if word in dict: dict[word] += 1 else: dict[word] = 1 for word in note: if word not in dict: print("No") return else: occurences = dict[word] ...
Python
zaydzuhri_stack_edu_python
import socket set server_host = call gethostname set server_port = 15000 set sock = call socket AF_INET SOCK_DGRAM set mensaje = encode string Hola, simplemente te estoy enviando un mensaje. string ascii call sendto mensaje tuple server_host server_port set tuple data tuple host_origen puerto_origen = call recvfrom 409...
import socket server_host = socket.gethostname() server_port = 15000 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) mensaje = "Hola, simplemente te estoy enviando un mensaje.".encode('ascii') sock.sendto(mensaje, (server_host, server_port)) data, (host_origen, puerto_origen) = sock.recvfrom(4096) print(data...
Python
zaydzuhri_stack_edu_python
from tkinter import * import time import math import types set PI = pi function biaomianji r1 r2 h begin if r1 > r2 begin set tuple r1 r2 = tuple r2 r1 end else if r1 == r2 begin if r1 != 0 begin set yuanzhu = true end else begin return input string 数据有误,请重新输入 end end set l1 = r1 ^ 2 + r1 * h / r2 - r1 ^ 2 ^ 0.5 set l2...
from tkinter import * import time import math import types PI=math.pi def biaomianji(r1, r2, h): if r1 > r2: r1, r2=r2, r1 elif r1 == r2: if r1 != 0: yuanzhu=True else: return input('数据有误,请重新输入') l1=(r1**2+(r1*h/(r2-r1))**2)**0.5 l2=l1*r2/r1 result=f...
Python
zaydzuhri_stack_edu_python
import json from collections import defaultdict from conditiontoken import ConditionToken from policy import Policy string PolicyParser Parse policies in a file to policy objects. Also extract a few information for latter uses. class PolicyParser begin string Parse policy file into Policy objects. Input: policyfile: A ...
import json from collections import defaultdict from .conditiontoken import ConditionToken from .policy import Policy """PolicyParser Parse policies in a file to policy objects. Also extract a few information for latter uses. """ class PolicyParser: """Parse policy file into Policy objects. Input:...
Python
zaydzuhri_stack_edu_python
import functions as func import os function encrypt input_file key=string begin set output_file = input_file + string .cry set input_file = open input_file string rb set output_file = open output_file string wb for line in input_file begin write output_file call encrypt_line line key end close input_file close output_f...
import functions as func import os def encrypt(input_file, key=''): output_file = input_file + '.cry' input_file = open(input_file, 'rb') output_file = open(output_file, 'wb') for line in input_file: output_file.write(func.encrypt_line(line, key)) input_file.close() output_file.close() ...
Python
zaydzuhri_stack_edu_python
comment import module lớp trừu tượng from abc import ABC , abstractmethod comment tạo ra một lớp mẹ đa giác nói chung class Polygon extends ABC begin comment abstract method function noofsides self begin comment placeholder pass end function end class comment lớp con tam giác class Triangle extends Polygon begin commen...
# import module lớp trừu tượng from abc import ABC, abstractmethod # tạo ra một lớp mẹ đa giác nói chung class Polygon(ABC): # abstract method def noofsides(self): #placeholder pass # lớp con tam giác class Triangle(Polygon): # viết thuộc tính riêng kế thừa từ hàm noofsides ...
Python
zaydzuhri_stack_edu_python
from django.test import TestCase from models import Player comment Test Case for object creation class PlayerTestCase extends TestCase begin function setUp self begin call create name=string test age=100 photo=string test nationality=string test overall=100 club=string test value=string test position=string test value_...
from django.test import TestCase from .models import Player class PlayerTestCase(TestCase): #Test Case for object creation def setUp(self): Player.objects.create( name="test", age=100, photo="test", nationality="test", overall=100, club="test", ...
Python
zaydzuhri_stack_edu_python
function add_to_scene_at self timestamp begin if not call is_interpolatable string in_scene begin call set_keyframe string in_scene timestamp true call set_interpolator string in_scene step_interpolator end else begin call set_keyframe string in_scene timestamp true end end function
def add_to_scene_at(self, timestamp): if not self.is_interpolatable('in_scene'): self.set_keyframe('in_scene', timestamp, True) self.set_interpolator('in_scene', step_interpolator) else: self.set_keyframe('in_scene', timestamp, True)
Python
nomic_cornstack_python_v1
function _convert_flags self fromlist tolist flaglist context numlines begin comment all anchor names will be generated using the unique "to" prefix comment process change flags, generating middle column of next anchors/links set next_id = list string * length flaglist set next_href = list string * length flaglist se...
def _convert_flags( self, fromlist, tolist, flaglist, context, numlines ): # all anchor names will be generated using the unique "to" prefix # process change flags, generating middle column of next anchors/links next_id = [''] * len( flaglist ) next_href = [''] * len( flaglist ) num_chg, in_change = 0, Fals...
Python
nomic_cornstack_python_v1
comment reliably restored by inspect function module_repr module begin pass end function
def module_repr(module): # reliably restored by inspect pass
Python
nomic_cornstack_python_v1
function check_walls self area_id levelscript position rules begin set call_signature = call hash tuple position + call hash call repr rules + call hash area_id if call_signature in object_wall_traces begin return object_wall_traces at call_signature end set mesh = area_geometries at area_id set position at 1 = positio...
def check_walls(self, area_id: int, levelscript: LevelScriptParser, position: list, rules: list): call_signature = hash(tuple(position)) + \ hash(repr(rules)) + hash(area_id) if call_signature in self.object_wall_traces: return self.object_wall_traces[call_signature] me...
Python
nomic_cornstack_python_v1
from main import * from items import * from skills import * from mobs import * import random set lowkey_lvl = 0 comment Basic commands function commands comm begin global lowkey_lvl if in_battle == 0 begin if comm == string inventory or comm == string inv begin call check_inv end else if comm == string skill or comm ==...
from main import * from items import * from skills import * from mobs import * import random lowkey_lvl = 0 # Basic commands def commands(comm): global lowkey_lvl if in_battle == 0: if comm == "inventory" or comm == "inv": check_inv() elif comm == "skill" or comm == "skills": ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python string Create the diagram of the database layout Using the tables module, prints to stdout a GraphViz dot file showing the table relationships. import collections import dbprocessing.tables import sqlalchemy.schema import sqlalchemy.types set tablestart = string "{tablename}" [ shape=none l...
#!/usr/bin/env python """Create the diagram of the database layout Using the tables module, prints to stdout a GraphViz dot file showing the table relationships.""" import collections import dbprocessing.tables import sqlalchemy.schema import sqlalchemy.types tablestart = ''' "{tablename}" [ shape=none la...
Python
zaydzuhri_stack_edu_python
for i in range 0 12 begin append matriz list for j in range 0 12 begin append matriz at i decimal input end end set soma = 0 for k in matriz at linha begin set soma = soma + k end if op == string S begin print soma end else if op == string M begin print soma / 12 end
for i in range(0,12): matriz.append([]) for j in range(0,12): matriz[i].append(float(input())) soma=0 for k in matriz[linha]: soma+=k if(op=="S"): print(soma) elif(op=="M"): print(soma/12)
Python
zaydzuhri_stack_edu_python
function _launch_kit self begin comment Set up the renderer async function __setup begin await call new_stage comment Acquire settings for simulator set _carb_settings = call acquire_settings_interface set _omni_settings = call get_settings_interface comment Set the common settings for the simulator call _setup_setting...
def _launch_kit(self): # Set up the renderer async def __setup(): await omni.kit.asyncapi.new_stage() # Acquire settings for simulator self._carb_settings = carb.settings.acquire_settings_interface() self._omni_settings = omni.kit.settings.get_settings_i...
Python
nomic_cornstack_python_v1
function run_cp2k_phonopy cp2k_code structure_pk begin for mode in list string serial string parallel begin print string >>> Compute forces + 3 displacements for water - MODE: { mode } set builder = call get_builder set structure = call load_node structure_pk set mode = string mode comment Compute only few displacement...
def run_cp2k_phonopy(cp2k_code, structure_pk): for mode in ['serial', 'parallel']: print(f'>>> Compute forces + 3 displacements for water - MODE: {mode}') builder = Cp2kPhonopyWorkChain.get_builder() builder.structure = load_node(structure_pk) builder.mode = Str(mode) builder...
Python
nomic_cornstack_python_v1
comment coding:utf-8 import requests import json set host = string http://192.168.1.12 function login user psw begin comment 拼接请求地址 set url = host + string /park-user-service/park/admin_user/login comment 设置请求头header信息 set h = dict string User-Agent string Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/201001...
#coding:utf-8 import requests import json host = "http://192.168.1.12" def login(user,psw): # 拼接请求地址 url = host + "/park-user-service/park/admin_user/login" # 设置请求头header信息 h = { "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0", "Accept":"*/...
Python
zaydzuhri_stack_edu_python
function send_email msg_body run_path experiment_name run_number begin set server = call SMTP string smtp.gmail.com 587 call starttls call login string kafkabot9000@gmail.com string thisisnotimportant set msg = call MIMEMultipart set files = list string { run_path } /cumulative_reward_ { experiment_name } _R { run_numb...
def send_email(msg_body: str, run_path: str, experiment_name: str, run_number: int) -> None: server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login("kafkabot9000@gmail.com", "thisisnotimportant") msg = MIMEMultipart() files = [f"{run_path}/cumulative_reward_{experiment_name}_R...
Python
nomic_cornstack_python_v1
function test_is_authentication_disabled_negative_test begin set environ at string DISABLE_AUTHENTICATION = string assert not call is_authentication_disabled set environ at string DISABLE_AUTHENTICATION = string 0 assert not call is_authentication_disabled set environ at string DISABLE_AUTHENTICATION = string false as...
def test_is_authentication_disabled_negative_test(): os.environ['DISABLE_AUTHENTICATION'] = '' assert not is_authentication_disabled() os.environ['DISABLE_AUTHENTICATION'] = '0' assert not is_authentication_disabled() os.environ['DISABLE_AUTHENTICATION'] = 'false' assert not is_authentication_...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import pandas as pd function read_series begin set values = list set indexes = list while true begin set data = input string Dej dane: if length data == 0 begin break end else begin set splitted = split data if length splitted < 2 begin raise Exception end else begin append indexes split...
#!/usr/bin/env python3 import pandas as pd def read_series(): values = [] indexes = [] while True: data = input("Dej dane: ") if len(data) == 0: break else: splitted = data.split() if len(splitted) < 2: raise Exception ...
Python
zaydzuhri_stack_edu_python
string PRE-PROCESSORS ============================================================================= Preprocessors work on source text before we start doing anything too complicated. from __future__ import absolute_import from __future__ import unicode_literals from import util from import odict import re function bui...
""" PRE-PROCESSORS ============================================================================= Preprocessors work on source text before we start doing anything too complicated. """ from __future__ import absolute_import from __future__ import unicode_literals from . import util from . import odict import re def b...
Python
zaydzuhri_stack_edu_python
function __init__ self fn begin set fn = fn end function
def __init__(self, fn: callable): self.fn = fn
Python
nomic_cornstack_python_v1
function service_account self begin return get pulumi self string service_account end function
def service_account(self) -> str: return pulumi.get(self, "service_account")
Python
nomic_cornstack_python_v1
function get_name self begin if champion_name is none begin set query = first filter by query champion_id=champion_id if query is none begin call push string Did not find a champion name at all. Requesting name. try begin set champion_name = call get_champion champion_id at string name commit session end comment DEPRIC...
def get_name(self): if self.champion_name is None: query = ( ChampionData.query .filter_by(champion_id=self.champion_id) .first() ) if query is None: LOGGING.push( "Did not find a champion n...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python3 comment -*- coding: UTF-8 -*- string category_controler: category_controler contains the CategoryController class. Classes: CategoryController: The CategoryController object processes the category controller. Methods: get_categories(): Gets all the categories from the database. set_categories(...
#!/usr/bin/python3 # -*- coding: UTF-8 -*- """ category_controler: category_controler contains the CategoryController class. Classes: CategoryController: The CategoryController object processes the category controller. Methods: get_categories(): Gets all the categories from the database. set_categori...
Python
zaydzuhri_stack_edu_python
function test_main_link_dir self begin comment Use current working directory explicitly to load links set args = list string --layout layout_single_signed_path string --layout-keys alice_path string --link-dir string . call assert_cli_sys_exit args 0 comment Fail with an explicit link directory, where no links are foun...
def test_main_link_dir(self): # Use current working directory explicitly to load links args = [ "--layout", self.layout_single_signed_path, "--layout-keys", self.alice_path, "--link-dir", ".", ] self.assert_cli_sys_...
Python
nomic_cornstack_python_v1
from collections import defaultdict class UnionFind begin function __init__ self n begin set par = list - 1 * n + 1 set size = list 1 * n + 1 end function function root self x begin if par at x == - 1 begin return x end else begin set par at x = call root par at x return par at x end end function function issame self x...
from collections import defaultdict class UnionFind: def __init__(self, n) -> None: self.par = [-1]*(n + 1) self.size = [1]*(n + 1) def root(self, x): if self.par[x] == -1: return x else: self.par[x] = self.root(self.par[x]) return self.par[...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You must do this in-place without altering the nodes' values. For example, Given {1,2,3,4}, reorder it to {1,4,2,3}. comment Definition for singly-linked list. class L...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Given a singly linked list L: L0→L1→…→Ln-1→Ln, reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→… You must do this in-place without altering the nodes' values. For example, Given {1,2,3,4}, reorder it to {1,4,2,3}. """ # Definition for singly-linked list. class ListNode(objec...
Python
zaydzuhri_stack_edu_python
function populator size begin set populations = list for i in range size begin set p = call Program call randomize append populations p end return populations end function
def populator(size): populations = [] for i in range(size): p = Program() p.randomize() populations.append(p) return populations
Python
nomic_cornstack_python_v1
function _make_fit_and_prediction_plot x y xx yy column start_date total_days model_type country begin plot x y string ko label=column plot xx yy label=string Fitted Function set column_title = title replace column string _ string title plt country + string + model_type + string Model for + column_title legend loc=str...
def _make_fit_and_prediction_plot(x, y, xx, yy, column, start_date, total_days, model_type, country): plt.plot(x, y, 'ko', label=column) plt.plot(xx, yy, label='Fitted Function') column_title = (column.replace('_', ' ')).title() plt.title(country + ' ' + model_type + ' Model for ' + column_title) pl...
Python
nomic_cornstack_python_v1
function get_cached_structure_search request search_request_id begin debug string tuple string check cached request search_request_id set request = get objects pk=integer search_request_id if request begin set kwargs = dict string smiles smiles ; string molfile molfile ; string type type if date_time_fullfilled begin i...
def get_cached_structure_search(request, search_request_id): logger.debug(str(('check cached request',search_request_id))) request = PubchemRequest.objects.get(pk=int(search_request_id)); if request: kwargs = { 'smiles':request.smiles, 'molfile':request.molfile, ...
Python
nomic_cornstack_python_v1
function suma_w_portfelu nominaly portfel begin set kwota_w_portfelu = 0 for tuple nominal ilosc in enumerate portfel begin set kwota_w_portfelu = kwota_w_portfelu + nominaly at nominal * ilosc end return kwota_w_portfelu end function function rozmien nominaly portfel kwota begin set kwota_poczatkowa = kwota set wybran...
def suma_w_portfelu(nominaly, portfel): kwota_w_portfelu = 0 for nominal, ilosc in enumerate(portfel): kwota_w_portfelu += nominaly[nominal]*ilosc return kwota_w_portfelu def rozmien(nominaly, portfel, kwota): kwota_poczatkowa = kwota wybrane_nominaly = {} kwota_w_portfelu = suma_w_por...
Python
zaydzuhri_stack_edu_python
function create_set_of_dominating_solutions solutions begin set set_of_dominated = list for index in range length solutions begin append set_of_dominated call find_dominated_solutions solutions index end return set_of_dominated end function
def create_set_of_dominating_solutions(solutions): set_of_dominated = [] for index in range(len(solutions)): set_of_dominated.append(find_dominated_solutions(solutions, index)) return set_of_dominated
Python
nomic_cornstack_python_v1
function select_day self day begin string 选取日期(一般用于分钟线) Arguments: day {[type]} -- [description] Raises: ValueError -- [description] Returns: [type] -- [description] function _select_day day begin return loc at tuple day call slice none end function try begin return call new call _select_day day type if_fq end except a...
def select_day(self, day): """选取日期(一般用于分钟线) Arguments: day {[type]} -- [description] Raises: ValueError -- [description] Returns: [type] -- [description] """ def _select_day(day): return self.data.loc[day, slice(None)] ...
Python
jtatman_500k
import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from keras import backend as K from sklearn.metrics import roc_curve , auc from uad.decision.reconstruction import decision_function function is_binary labels begin set l = list for elt in labels begin if not elt in l begin append l elt end end...
import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from keras import backend as K from sklearn.metrics import roc_curve, auc from uad.decision.reconstruction import decision_function def is_binary(labels): l = [] for elt in labels: if not elt in l: l.append(elt) ...
Python
zaydzuhri_stack_edu_python
function addIndent self begin call addIndent end function
def addIndent(self): self._prompter_formatter.addIndent()
Python
nomic_cornstack_python_v1
function send_to_route self route payment_hash begin set request = call SendToRouteRequest route=route payment_hash=payment_hash try begin set payment = call SendToRouteV2 request timeout=GRPC_TIMEOUT_SEC end except RpcError as e begin if call code == DEADLINE_EXCEEDED begin raise PaymentTimeOut end raise end if call H...
def send_to_route(self, route: lnd.Route, payment_hash: bytes): request = lndrouter.SendToRouteRequest( route=route, payment_hash=payment_hash, ) try: payment = self._routerrpc.SendToRouteV2( request, timeout=GRPC_TIMEOUT_SEC, ) ...
Python
nomic_cornstack_python_v1
function ADT_QCD_LEPTON begin comment As input for the quark-mass ratios, we use the quark masses at MZ and the lepton masses set ip = call Num_input set mu = mu_at_MZ set md = md_at_MZ set ms = ms_at_MZ set me = me set mmu = mmu set mtau = mtau comment Create the ADT: set gamma_hat_P63eu_Q81u = horizontal stack tuple ...
def ADT_QCD_LEPTON(): # As input for the quark-mass ratios, we use the quark masses at MZ and the lepton masses ip = Num_input() mu = ip.mu_at_MZ md = ip.md_at_MZ ms = ip.ms_at_MZ me = ip.me mmu = ip.mmu mtau = ip.mtau # Create the ADT: gamma_hat_P63eu_Q81u = np.hstack((-16 *...
Python
nomic_cornstack_python_v1
from app.entity.clienteEntity import ClienteEntity from sqlalchemy import or_ from base import session_factory from app.model.clienteModel import ClienteModel function getById id begin set session = call session_factory set response = get query session ClienteEntity id close session return response end function functio...
from app.entity.clienteEntity import ClienteEntity from sqlalchemy import or_ from .base import session_factory from app.model.clienteModel import ClienteModel def getById(id: int): session = session_factory() response = session.query(ClienteEntity).get(id) session.close() return response def getAl...
Python
zaydzuhri_stack_edu_python
class Cat extends object begin string 猫科动物 set tag = string 我是家猫 function __init__ self name age sex=none begin set name = name comment 双下划綫开头的表示私有的属性,实例化不能访问或设置其值 set __age = age set sex = sex end function function set_age self age begin string 改变猫的年龄 :param age: :return: set __age = age return __age end function func...
class Cat(object): """ 猫科动物 """ tag = '我是家猫' def __init__(self,name,age,sex=None): self.name = name #双下划綫开头的表示私有的属性,实例化不能访问或设置其值 self.__age = age self.sex = sex def set_age(self,age): """ 改变猫的年龄 :param age: :return: """ ...
Python
zaydzuhri_stack_edu_python
import unittest from mock import patch , MagicMock from src.common_upgrades.sql_utilities import SqlConnection , run_sql import mysql.connector class TestSQLUtils extends TestCase begin function setUp self begin set _connection = none end function decorator patch string src.common_upgrades.sql_utilities.getpass decorat...
import unittest from mock import patch, MagicMock from src.common_upgrades.sql_utilities import SqlConnection, run_sql import mysql.connector class TestSQLUtils(unittest.TestCase): def setUp(self): SqlConnection._connection = None @patch('src.common_upgrades.sql_utilities.getpass') @patch('src.co...
Python
zaydzuhri_stack_edu_python
function reached_goals self begin return call execute_script string return yaCounter20644114.goals; end function
def reached_goals(self): return self.browser.execute_script('return yaCounter20644114.goals;')
Python
nomic_cornstack_python_v1
function _buildLSTM self X embedding dropout_prob=0.0 begin set start_time = time call _p string In <_buildLSTM> set suffix = string if params at string var_model == string lstmr begin set suffix = string r return call _LSTMlayer embedding suffix dropout_prob end else if params at string var_model == string lstm begin...
def _buildLSTM(self, X, embedding, dropout_prob = 0.): start_time = time.time() self._p('In <_buildLSTM>') suffix = '' if self.params['var_model']=='lstmr': suffix='r' return self._LSTMlayer(embedding, suffix, dropout_prob) elif self.params['var_model']=='...
Python
nomic_cornstack_python_v1
function wordcount begin try begin comment initialize empty hash set wordcount = dict comment open file to read with open string File_to_be_read_relatedto_Assignment_3.1.txt as file begin comment iterate through through each split word in the file for word in split read file begin comment count each word in file if wo...
def wordcount(): try: wordcount = {} # initialize empty hash with open("File_to_be_read_relatedto_Assignment_3.1.txt") as file: # open file to read for word in file.read().split(): # iterate through through each split word in the file if word not in wordcount: ...
Python
zaydzuhri_stack_edu_python
for i in bruh begin set new = list for e in i begin append new e * num end append matrix new end set final = list set counter = 0 for i in matrix begin for m in range num begin append final matrix at counter end set counter = counter + 1 end for i in final begin print join string i end
for i in bruh: new = [] for e in i: new.append(e * num) matrix.append(new) final = [] counter = 0 for i in matrix: for m in range(num): final.append(matrix[counter]) counter += 1 for i in final: print(''.join(i))
Python
zaydzuhri_stack_edu_python
from typing import List , Dict function find_longest_common_prefix arr_of_dictionaries begin if not arr_of_dictionaries begin return string end set keys = keys arr_of_dictionaries at 0 for dictionary in arr_of_dictionaries at slice 1 : : begin set keys = keys ? keys dictionary end set common_prefix = string for cha...
from typing import List, Dict def find_longest_common_prefix(arr_of_dictionaries: List[Dict[str, str]]) -> str: if not arr_of_dictionaries: return "" keys = arr_of_dictionaries[0].keys() for dictionary in arr_of_dictionaries[1:]: keys = keys & dictionary.keys() common_prefix = "" ...
Python
jtatman_500k
function _create_user self email password **extra_fields begin if not email begin raise call ValueError string The given email must be set or Users must have an email address. end set email = call normalize_email email set user = model email=email keyword extra_fields call set_password password save using=_db return us...
def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The given email must be set or Users must have an email address.') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) u...
Python
nomic_cornstack_python_v1
function extract_feature labels t_unit=0.01 begin set max_sec = max generator expression end_time for label in labels set frm_num = ceil max_sec / t_unit set onset = zeros tuple frm_num 88 set dura = zeros tuple frm_num 88 set inter_onset_interval = zeros frm_num comment Extract piano roll feature (onset, duration) set...
def extract_feature(labels, t_unit=0.01): max_sec = max(label.end_time for label in labels) frm_num = math.ceil(max_sec / t_unit) onset = np.zeros((frm_num, 88)) dura = np.zeros((frm_num, 88)) inter_onset_interval = np.zeros(frm_num) # Extract piano roll feature (onset, duration) onset_idx_...
Python
nomic_cornstack_python_v1