code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
class Bookshelf begin class Book begin function __init__ self name file begin set name = name set _file = file end function function readBook self begin set text = open _file string r print read text close text end function end class set library = dict string Pride and Predjudice string pandp.txt ; string Grapes of Wra...
class Bookshelf(): class Book(): def __init__(self, name, file): self.name = name self._file = file def readBook(self): text = open(self._file, 'r') print(text.read()) text.close() library = {"Pride and Predjudice": "pandp.txt", "Grap...
Python
zaydzuhri_stack_edu_python
function display_topics model dictionary num_topics output_path begin comment topics = model.show_topics(num_topics=num_topics) set output_file = open output_path string w comment for i in range(0, num_topics): comment word_probability_tuples = model.get_topic_terms(i, topn=20) comment _words = [dictionary[word_id] for...
def display_topics(model, dictionary, num_topics, output_path): # topics = model.show_topics(num_topics=num_topics) output_file = open(output_path, 'w') # for i in range(0, num_topics): # word_probability_tuples = model.get_topic_terms(i, topn=20) # _words = [dictionary[word_id] for wor...
Python
nomic_cornstack_python_v1
comment IMPORTANDO Modulo de Classes Abstratas from abc import ABC , abstractmethod comment Classe Abstrata de pagamentos, que irá ser a base para os tipos de pagamento class pagamento extends ABC begin function __init__ self tipoPagamento begin set __tipoPagamento = tipoPagamento end function comment GETTERS function ...
from abc import ABC, abstractmethod #IMPORTANDO Modulo de Classes Abstratas #Classe Abstrata de pagamentos, que irá ser a base para os tipos de pagamento class pagamento(ABC): def __init__(self, tipoPagamento): self.__tipoPagamento = tipoPagamento #GETTERS def getTipoPagamento(self): retu...
Python
zaydzuhri_stack_edu_python
function parseParameter v t begin if t == string begin return v end else if t == integer begin return call fromstring v dtype=int count=1 sep=string at 0 end else if t == real begin return call fromstring v dtype=double count=1 sep=string at 0 end else if t == integerList begin return call fromstring v dtype=int sep=st...
def parseParameter(v,t): if t==ParameterType.string: return v elif t==ParameterType.integer: return np.fromstring(v,dtype=np.int,count=1,sep=" ")[0] elif t==ParameterType.real: return np.fromstring(v,dtype=np.double,count=1,sep=" ")[0] elif t==ParameterType.integerList: return np.fromstring(v,dtype=np.int,s...
Python
nomic_cornstack_python_v1
class Employee begin function __init__ self name salary department begin set name = name set salary = salary set department = department end function function validate_name self begin if length name > 50 begin raise call ValueError string Name cannot exceed 50 characters. end end function function validate_salary self ...
class Employee: def __init__(self, name, salary, department): self.name = name self.salary = salary self.department = department def validate_name(self): if len(self.name) > 50: raise ValueError("Name cannot exceed 50 characters.") def validate_salary(self):...
Python
jtatman_500k
function _rms data begin if length shape > 1 begin comment np.sqrt(np.mean(data ** 2, axis=1)) return standard deviation np data axis=1 end comment np.sqrt(np.mean(data ** 2)) return standard deviation np data end function
def _rms(data): if len(data.shape) > 1: return np.std(data, axis=1) #np.sqrt(np.mean(data ** 2, axis=1)) return np.std(data) #np.sqrt(np.mean(data ** 2))
Python
nomic_cornstack_python_v1
import os class Stack begin function __init__ self begin set arr = list set Top = - 1 end function function push self a begin set Top = Top + 1 append arr a print format string Element {} push successful a end function function pop self begin try begin set Top = Top - 1 return pop arr Top + 1 end except any begin set ...
import os class Stack: def __init__(self): self.arr = [] self.Top = -1 def push(self, a): self.Top += 1 self.arr.append(a) print("Element {} push successful".format(a)) def pop(self): try: self.Top -= 1 return self.arr.pop(self.Top+...
Python
zaydzuhri_stack_edu_python
function random_sample_from_prod_discrete_domain list_of_list_of_vals num_samples begin return call random_sample_from_discrete_domain list_of_list_of_vals num_samples end function
def random_sample_from_prod_discrete_domain(list_of_list_of_vals, num_samples): return random_sample_from_discrete_domain(list_of_list_of_vals, num_samples)
Python
nomic_cornstack_python_v1
function test_first_degenerate self begin assert equal call first_degenerate none assert equal call first_degenerate none assert equal call first_degenerate none assert equal call first_degenerate 0 assert equal call first_degenerate 7 assert equal call first_degenerate 11 end function
def test_first_degenerate(self): self.assertEqual(self.RNA("").first_degenerate(), None) self.assertEqual(self.RNA("a").first_degenerate(), None) self.assertEqual(self.RNA("UCGACA--CU-gacucaguacgua").first_degenerate(), None) self.assertEqual(self.RNA("nCAGU").first_degenerate(), 0) ...
Python
nomic_cornstack_python_v1
import os , sys , time , subprocess comment Open a file set path = string E:/Capstone Project/New for Journal/2_MPEF with JPEG/ set srcpath = path + string /1_Compressed Image Frames/lou_dyn/ set dstpath = path + string 2_Compressed MPEG/lou_dyn/ set dirs = list directory srcpath set start_time = time comment This woul...
import os, sys, time, subprocess # Open a file path = "E:/Capstone Project/New for Journal/2_MPEF with JPEG/" srcpath = path + "/1_Compressed Image Frames/lou_dyn/" dstpath = path + "2_Compressed MPEG/lou_dyn/" dirs = os.listdir( srcpath ) start_time = time.time() # This would print all the files and directories for...
Python
zaydzuhri_stack_edu_python
function light_head_preprocess_image image labels bboxes out_shape data_format is_training=false **kwargs begin if is_training begin return call light_head_preprocess_for_train image labels bboxes out_shape=out_shape data_format=data_format end else begin return call light_head_preprocess_for_eval image labels bboxes o...
def light_head_preprocess_image(image, labels, bboxes, out_shape, data_format, is_training=False, **kwargs): if is_training: return light_head_preprocess_for_train(image, labels, bbo...
Python
nomic_cornstack_python_v1
function update_project id begin if method == string POST begin set result = call update_project_to_db id form at string title form at string link form at string description call flash result return call redirect call url_for string portfolio end else begin set project = call get_project id return call render_template ...
def update_project(id): if request.method == "POST": result = update_project_to_db( id, request.form["title"], request.form["link"], request.form["description"] ) flash(result) return redirect(url_for("portfolio")) else: pro...
Python
nomic_cornstack_python_v1
import os function all_path dirname begin comment 所有的文件 set result = list for tuple maindir subdir file_name_list in walk dirname begin comment 当前主目录 print string 1: maindir comment 当前主目录下的所有目录 print string 2: subdir comment 当前主目录下的所有文件 print string 3: file_name_list for filename in file_name_list begin comment 合并成一个完...
import os def all_path(dirname): result = []#所有的文件 for maindir, subdir, file_name_list in os.walk(dirname): print("1:",maindir) #当前主目录 print("2:",subdir) #当前主目录下的所有目录 print("3:",file_name_list) #当前主目录下的所有文件 for filename in file_name_list: apath = os.p...
Python
zaydzuhri_stack_edu_python
function org_apache_felix_proxy_load_balancer_connection_enable self org_apache_felix_proxy_load_balancer_connection_enable begin set _org_apache_felix_proxy_load_balancer_connection_enable = org_apache_felix_proxy_load_balancer_connection_enable end function
def org_apache_felix_proxy_load_balancer_connection_enable(self, org_apache_felix_proxy_load_balancer_connection_enable: ConfigNodePropertyBoolean): self._org_apache_felix_proxy_load_balancer_connection_enable = org_apache_felix_proxy_load_balancer_connection_enable
Python
nomic_cornstack_python_v1
from flask import Flask from flask_sqlalchemy import SQLAlchemy import os from flask_migrate import Migrate set db = call SQLAlchemy comment database_name = "movies" comment database_path = "postgresql://{}:{}@{}/{}".format('postgres','123','localhost:5432',database_name) set database_path = environ at string DATABASE_...
from flask import Flask from flask_sqlalchemy import SQLAlchemy import os from flask_migrate import Migrate db = SQLAlchemy() #database_name = "movies" #database_path = "postgresql://{}:{}@{}/{}".format('postgres','123','localhost:5432',database_name) database_path = os.environ['DATABASE_URL'] if database_path.startsw...
Python
zaydzuhri_stack_edu_python
comment 常用的正则表达式 import re comment 匹配IP地址格式,但不保证IP地址合法 set string = string haha192.168.1.1heh set r = compile string (\d{1,3}\.){3}\d{1,3} set temp = search string print call group comment 匹配IP地址格式,保证IP地址合法 set string = string haha192.122.1.1heh comment r = re.compile(r'((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[...
# 常用的正则表达式 import re # 匹配IP地址格式,但不保证IP地址合法 string = 'haha192.168.1.1heh' r = re.compile(r'(\d{1,3}\.){3}\d{1,3}') temp = r.search(string) print(temp.group()) # 匹配IP地址格式,保证IP地址合法 string = 'haha192.122.1.1heh' # r = re.compile(r'((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)') r = re.compile(r'((2[...
Python
zaydzuhri_stack_edu_python
import sys append path string ./utils/ import pandas as pd from utils.utils_pp import ds_from_json_from_zip , get_label_dict from sklearn.preprocessing import MultiLabelBinarizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.multiclass import OneVsRestClassifier from sklearn import svm from s...
import sys sys.path.append('./utils/') import pandas as pd from utils.utils_pp import ds_from_json_from_zip, get_label_dict from sklearn.preprocessing import MultiLabelBinarizer from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.multiclass import OneVsRestClassifier from sklearn import svm from s...
Python
zaydzuhri_stack_edu_python
function ortho_B_W number inputs begin set B = randn number set B = B / norm B set X = random tuple number inputs set tuple U _ Vt = call svd X full_matrices=false set Vt = T return tuple B Vt end function
def ortho_B_W(number, inputs): B = np.random.randn(number) B /= np.linalg.norm(B) X = np.random.random((number, inputs)) U, _, Vt = np.linalg.svd(X, full_matrices=False) Vt = Vt.T return B, Vt
Python
nomic_cornstack_python_v1
function trip_duration_stats df begin print string Calculating Trip Duration... set start_time = time comment display total travel time set total_travel_time = integer sum set total_travel_minutes = integer total_travel_time / 60 set total_travel_hours = integer total_travel_time / 3600 set total_travel_days = integer ...
def trip_duration_stats(df): print('\nCalculating Trip Duration...\n') start_time = time.time() # display total travel time total_travel_time = int(df['Trip Duration'].sum()) total_travel_minutes = int(total_travel_time/60) total_travel_hours = int(total_travel_time/3600) total_travel_days...
Python
nomic_cornstack_python_v1
import math from library.bodies import DynamicBodyConstants comment pixels per metre set M2PX = 16 set car_constants = call DynamicBodyConstants length=M2PX * 4.5 width=M2PX * 1.75 wheelbase=M2PX * 3 track=M2PX * 1.75 min_velocity=0 max_velocity=M2PX * 9 min_throttle=M2PX * - 9 max_throttle=M2PX * 9 min_steering_angle=...
import math from library.bodies import DynamicBodyConstants M2PX = 16 # pixels per metre car_constants = DynamicBodyConstants( length=M2PX * 4.5, # [4.5 m] width=M2PX * 1.75, # [1.75 m] wheelbase=M2PX * 3, # [3 m] track=M2PX * 1.75, # [1.75 m] min_velocity=0, # [0 m/s] max_velocity=M2PX...
Python
zaydzuhri_stack_edu_python
comment Write a program which accept string from user and copy capital comment characters of that string into another string. comment Input : “Marvellous Multi OS” comment Output : “MMOS” function StrCpyCap strs begin set arr = list set list1 = list strs set length = length list1 set i = 0 while i < length begin if li...
# Write a program which accept string from user and copy capital # characters of that string into another string. # Input : “Marvellous Multi OS” # Output : “MMOS” def StrCpyCap(strs): arr=[] list1=list(strs) length=len(list1) i=0 while i<length: if list1[i]>='A' and list1[i...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding:utf-8 -*- comment Author: kent comment 改程序需要在终端环境下运行,pycharm下不能得到正确结果 import getpass set _username = string zhaojian set _password = string abc123 set username = input string username: comment password = getpass.getpass("password:") set passoword = input string passorod: ...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author: kent #改程序需要在终端环境下运行,pycharm下不能得到正确结果 import getpass _username = 'zhaojian' _password = 'abc123' username = input("username:") #password = getpass.getpass("password:") passoword = input("passorod:") if _username == username and _password == passoword: print("...
Python
zaydzuhri_stack_edu_python
function second_moments ix iy ksize=7 sigma=10 begin if ksize == 1 begin return tuple ix ^ 2 iy ^ 2 ix * iy end set gk = call get_gaussian_kernel ksize sigma comment print(gk) set tuple m n = shape set sx2 = call my_filter2D reshape np ix ^ 2 tuple m n 1 gk set sxsy = call my_filter2D reshape np ix * iy tuple m n 1 gk ...
def second_moments(ix, iy, ksize = 7, sigma = 10): if ksize == 1: return ix**2, iy**2, ix*iy gk = get_gaussian_kernel(ksize, sigma) # print(gk) m, n = ix.shape sx2 = my_filter2D(np.reshape(ix**2, (m, n, 1)), gk) sxsy = my_filter2D(np.reshape(ix*iy, (m, n, 1)), gk) sy2 = m...
Python
nomic_cornstack_python_v1
function split_args kwargs begin set init_args = dict set method_args = dict for tuple key arg in items kwargs begin if starts with key INIT_KEY begin set init_args at split key string . at - 1 = arg end else if starts with key METHOD_KEY begin set method_args at split key string . at - 1 = arg end end return tuple i...
def split_args(kwargs: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]: init_args = {} method_args = {} for key, arg in kwargs.items(): if key.startswith(INIT_KEY): init_args[key.split('.')[-1]] = arg elif key.startswith(METHOD_KEY): method_args[key.split('.')[-1]] = arg return in...
Python
nomic_cornstack_python_v1
function get_assignment_map_from_checkpoint tvars init_checkpoint begin set assignment_map = dict set initialized_variable_names = dict set name_to_variable = ordered dictionary for var in tvars begin set name = name set m = match string ^(.*):\d+$ name if m is not none begin set name = call group 1 end set name_to_v...
def get_assignment_map_from_checkpoint(tvars, init_checkpoint): assignment_map = {} initialized_variable_names = {} name_to_variable = collections.OrderedDict() for var in tvars: name = var.name m = re.match('^(.*):\\d+$', name) if m is not None: name = m.group(1) ...
Python
nomic_cornstack_python_v1
function mlx_crc data begin set crc = 0 for i in data begin set crc = crc + i if crc > 255 begin set crc = crc - 255 end end return 255 - crc end function
def mlx_crc(data, ): crc = 0 for i in data: crc += i if crc > 255: crc -= 255 return 255-crc
Python
nomic_cornstack_python_v1
function move my_history their_history my_score their_score begin if length my_history == 0 begin return string c end else if length their_history - 1 == string b begin return string b end else begin return string c end end function move string b string c 0 0
def move(my_history, their_history, my_score, their_score): if len(my_history) == 0: return'c' elif (len(their_history)-1) == 'b': return'b' else: return 'c' move("b","c",0,0)
Python
zaydzuhri_stack_edu_python
function stop self key begin set data = _watch at key if data at 0 < 0 begin set data at 0 = time - data at 1 end end function
def stop(self,key): data = self._watch[key] if data[0]<0 : data[0] = time.time() - data[1]
Python
nomic_cornstack_python_v1
comment Vamos aprimorar o código: cadastro de jogador de futebol.py que foi desenvolvido no CodeLab da aula14. Faça com que o seu código funcione para vários jogadores, incluindo um sistema de visualização de detalhes de aproveitamento de cada jogador. comment Modo 1 class Jogador begin function __init__ self nome part...
# Vamos aprimorar o código: cadastro de jogador de futebol.py que foi desenvolvido no CodeLab da aula14. Faça com que o seu código funcione para vários jogadores, incluindo um sistema de visualização de detalhes de aproveitamento de cada jogador. # Modo 1 class Jogador: def __init__(self, nome, partidas, golsTota...
Python
zaydzuhri_stack_edu_python
import random class CardGame begin set deck = none set scores = none function __init__ self begin set deck = call generateDeck set scores = dict string player1 0 ; string player2 0 end function function generateDeck self begin set suits = list string Clubs string Diamonds string Hearts string Spades set ranks = list st...
import random class CardGame: deck = None scores = None def __init__(self): self.deck = self.generateDeck() self.scores = {'player1': 0, 'player2': 0} def generateDeck(self): suits = ['Clubs', 'Diamonds', 'Hearts', 'Spades'] ranks = ['2','3','4','5','6','7','8','...
Python
iamtarun_python_18k_alpaca
function _checkoutemptytree self begin set oid = write call TreeBuilder call checkout_tree _repository at oid end function
def _checkoutemptytree(self) -> None: oid = self._repository.TreeBuilder().write() self._repository.checkout_tree(self._repository[oid])
Python
nomic_cornstack_python_v1
function handle_yes_request intent session begin set result = call handle_continue_end_ambiguity_request intent session try begin set continue_prompt_asked = session at string attributes at string continuePromptAsked if call strtobool continue_prompt_asked == 1 begin set result = call handle_restart_session intent sess...
def handle_yes_request(intent, session): result = handle_continue_end_ambiguity_request(intent, session) try: continue_prompt_asked = session['attributes']['continuePromptAsked'] if strtobool(continue_prompt_asked) == 1: result = handle_restart_session(intent, session) except Key...
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt function load Dir id begin with open Dir + string output + id as f begin set content = read lines f end set content = list comprehension strip x for x in content set x = list set y = list set y0 = list set i = 0 while i < length content begin append x integer conten...
import numpy as np import matplotlib.pyplot as plt def load(Dir, id): with open(Dir + 'output' + id) as f: content = f.readlines() content = [x.strip() for x in content] x = [] y = [] y0 = [] i = 0 while i < len(content): x.append(int(content[i])) s1 = 0 s2 = 0 for j in range(5): i += 1 t1 = ...
Python
zaydzuhri_stack_edu_python
comment Python3 implementation of the approach comment Fuction to return the count comment of the required numbers function countNum N arr begin comment To store the count of comment required numbers set count = 0 for i in range N begin comment Initialize sum to 0 set Sum = 0 for j in range N begin comment If current e...
# Python3 implementation of the approach # Fuction to return the count # of the required numbers def countNum(N, arr): # To store the count of # required numbers count = 0 for i in range(N): # Initialize sum to 0 Sum = 0 for j in range(N): ...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt function vectorize_sequences sequences dimension=10000 begin comment 크기가 (len(sequences), dimension))이고 모든 원소가 0인 행렬을 만듭니다 set results = zeros tuple length sequences dimension for tuple i sequence in enumerate sequences begin comment results[i]에...
import tensorflow as tf import numpy as np import matplotlib.pyplot as plt def vectorize_sequences(sequences, dimension=10000): # 크기가 (len(sequences), dimension))이고 모든 원소가 0인 행렬을 만듭니다 results = np.zeros((len(sequences), dimension)) for i, sequence in enumerate(sequences): results[i, sequence] = 1. ...
Python
zaydzuhri_stack_edu_python
from netaddr import IPNetwork import requests import configparser import boto3 import sys function getopts begin from sys import argv comment Empty dictionary to store key-value pairs. set opts = dict comment While there are arguments left to parse... while argv begin comment Found a "-name value" pair. if argv at 0 a...
from netaddr import IPNetwork import requests import configparser import boto3 import sys def getopts(): from sys import argv opts = {} # Empty dictionary to store key-value pairs. while argv: # While there are arguments left to parse... if argv[0][0] == '-': # Found a "-name value" pair. ...
Python
zaydzuhri_stack_edu_python
function inverse_value controllerName attributeName begin set currentValue = get attribute controllerName + string . + attributeName set inverseValue = decimal currentValue - currentValue * 2 set attribute controllerName + string . + attributeName inverseValue end function
def inverse_value(controllerName, attributeName): currentValue = cmds.getAttr(controllerName + "." + attributeName) inverseValue = float((currentValue - (currentValue * 2))) cmds.setAttr((controllerName + "." + attributeName), inverseValue)
Python
nomic_cornstack_python_v1
function load_xml self abstract_element begin call set_attributes abstract_element self set value_of = text save end function
def load_xml(self, abstract_element): set_attributes(abstract_element,self) self.value_of = abstract_element.text self.save()
Python
nomic_cornstack_python_v1
comment String formatting with templates comment Compared to other string formatting methods, these have increases security functions from string import Template comment The $ are important set templ = call Template string You are watching ${title} by ${author} set string = call substitute title=string Advanced Python ...
# String formatting with templates # Compared to other string formatting methods, these have increases security functions from string import Template # The $ are important templ = Template('You are watching ${title} by ${author}') string = templ.substitute(title='Advanced Python', author='Andrew Dunkle') print(string...
Python
zaydzuhri_stack_edu_python
import argparse from landmark_detection.landmark_detector import LandmarkDetector import cv2 if __name__ == string __main__ begin set parser = call ArgumentParser description=string Evaluate a single image by the trained model formatter_class=ArgumentDefaultsHelpFormatter call add_argument string --image type=str help=...
import argparse from landmark_detection.landmark_detector import LandmarkDetector import cv2 if __name__ == "__main__": parser = argparse.ArgumentParser(description='Evaluate a single image by the trained model', formatter_class=argparse.ArgumentDefaultsHelpFormatter) pars...
Python
zaydzuhri_stack_edu_python
function cmd_sync self low timeout=none full_return=false begin set reformatted_low = call _reformat_low low return call cmd_sync self reformatted_low timeout full_return end function
def cmd_sync(self, low, timeout=None, full_return=False): reformatted_low = self._reformat_low(low) return mixins.SyncClientMixin.cmd_sync( self, reformatted_low, timeout, full_return )
Python
nomic_cornstack_python_v1
comment Problem 14 comment 1 1 comment 2 1 2 comment 3 10 5 16 8 4 2 1 8 comment 4 2 1 3 comment 5 16 8 4 2 1 6 comment 6 3 10 5 16 8 4 2 1 9 comment 7 22 11 34 17 54 27 82 41 124 62 31 92 46 23 import sys call setrecursionlimit 100000 comment retuns the number of terms of the Collatz sequence that starts with the inte...
# Problem 14 # 1 1 # 2 1 2 # 3 10 5 16 8 4 2 1 8 # 4 2 1 3 # 5 16 8 4 2 1 6 # 6 3 10 5 16 8 4 2 1 9 # 7 22 11 34 17 54 27 82 41 124 62 31 92 46 23 import sys sys.setrecursionlimit(100000) # retuns the number of terms of the Collatz sequence that starts with the integer "num" def collatz (num): ...
Python
zaydzuhri_stack_edu_python
function _check_cls self begin if _cls is none begin raise call ValueError string _cls has not been set end end function
def _check_cls(self): if self._cls is None: raise ValueError("_cls has not been set")
Python
nomic_cornstack_python_v1
function __call__ self input begin if state is not none begin set state = alpha * input + 1 - alpha * state end else begin set state = input end return state end function
def __call__(self, input: Union[np.ndarray, float]): if self.state is not None: self.state = self.alpha * input + (1 - self.alpha) * self.state else: self.state = input return self.state
Python
nomic_cornstack_python_v1
comment ================================= comment Sound Sensor Raspi comment ================================= comment VCC ==> 2 comment GND ==> 9 comment OUT ==> 37 import RPi.GPIO as GPIO from time import sleep import requests comment GPIO SETUP set channel = 37 call setmode BOARD setup GPIO channel IN pull_up_down=P...
# ================================= # Sound Sensor Raspi # ================================= # VCC ==> 2 # GND ==> 9 # OUT ==> 37 import RPi.GPIO as GPIO from time import sleep import requests #GPIO SETUP channel = 37 GPIO.setmode(GPIO.BOARD) GPIO.setup(chan...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment --------------------------------------------------------- comment FILE DESCRIPTION: comment --------------------------------------------------------- comment Download and save results from completed HIT assignments comment --------------------------------------------------------- c...
#!/usr/bin/env python3 #--------------------------------------------------------- # FILE DESCRIPTION: #--------------------------------------------------------- # Download and save results from completed HIT assignments #--------------------------------------------------------- # IMPORTS #----------------------------...
Python
zaydzuhri_stack_edu_python
function drct u v begin comment TODO return 0 if value begin set val = 1 end return call direction val string DEG end function
def drct(u, v): return 0 #TODO if (v.value): val = 1 return dt.direction(val, 'DEG')
Python
nomic_cornstack_python_v1
import streamlit as st comment NLP Pkgs from textblob import TextBlob import pandas as pd from PIL import Image comment Emoji comment import emoji comment Audio comment from gtts import gTTS from bokeh.models.widgets import Div decorator cache comment Web Scraping Pkg comment from bs4 import BeautifulSoup comment from ...
import streamlit as st # NLP Pkgs from textblob import TextBlob import pandas as pd from PIL import Image # Emoji #import emoji # Audio #from gtts import gTTS from bokeh.models.widgets import Div # Web Scraping Pkg #from bs4 import BeautifulSoup #from urllib.request import urlopen # Fetch Text From Url @st.cache ...
Python
zaydzuhri_stack_edu_python
function AddSymbolicLink self path linked_path begin if call FileEntryExistsByPath path begin raise call ValueError string Path: { path } already set. end call _AddParentDirectories path call AddFileEntry path file_entry_type=FILE_ENTRY_TYPE_LINK link_data=linked_path end function
def AddSymbolicLink(self, path, linked_path): if self.file_system.FileEntryExistsByPath(path): raise ValueError(f'Path: {path:s} already set.') self._AddParentDirectories(path) self.file_system.AddFileEntry( path, file_entry_type=definitions.FILE_ENTRY_TYPE_LINK, link_data=linked_path...
Python
nomic_cornstack_python_v1
comment 대표값으로 접근 function findset n begin while p at n != n begin set n = p at n end return n end function function mst begin global V set c = 0 set s = 0 set i = 0 comment 노드의 수보다 1개 적은 간선 필요 while c < V begin set p1 = call findset edge at i at 0 set p2 = call findset edge at i at 1 if p1 != p2 begin set s = s + edge ...
def findset(n): # 대표값으로 접근 while p[n] != n: n = p[n] return n def mst(): global V c=0 s=0 i=0 while c<V: # 노드의 수보다 1개 적은 간선 필요 p1 = findset(edge[i][0]) p2 = findset(edge[i][1]) if p1 != p2: s+= edge[i][2] c+=1 p[p2] = p1 #...
Python
zaydzuhri_stack_edu_python
function Fibonacci n begin set f = list comprehension 0 for i in range n + 1 set f at 0 = 0 set f at 1 = 1 if n <= 1 begin return f at n end else begin for i in range 2 n begin set f at i = f at i + f at i - 2 + f at i - 1 end end return f at n end function
def Fibonacci(n): f = [0 for i in range(n+1)] f[0] = 0 f[1] = 1 if n <= 1: return f[n] else: for i in range(2, n): f[i] += (f[i - 2] + f[i - 1]) return f[n]
Python
zaydzuhri_stack_edu_python
function find_feature_and_threshold_to_split_by self patients begin set num_of_features = length symptoms comment For each feature find the value to split by that provides the best IG comment Save the best feature and the threshold set best_ig = 0 set best_feature = none set best_threshold = none set final_smaller = li...
def find_feature_and_threshold_to_split_by(self, patients): num_of_features = len(patients[0].symptoms) # For each feature find the value to split by that provides the best IG # Save the best feature and the threshold best_ig = 0 best_feature = None best_threshold = Non...
Python
nomic_cornstack_python_v1
function fwintegritycheckautomatictesting self begin call printer string ********************************************************************************* call printer string ******************FIRMWARE INTEGRITY CHECK AUTOMATIC TESTING********************* call printer string *******************************************...
def fwintegritycheckautomatictesting(self): self.rdmc.ui.printer( "\n*************************************************" "********************************\n" ) self.rdmc.ui.printer( "******************FIRMWARE INTEGRITY CHECK AUTOMATIC " "TESTING***...
Python
nomic_cornstack_python_v1
comment Doubly linked List.... class node begin function __init__ self data begin set data = data set left = none set right = none end function end class class DoublylinkedList begin function __init__ self begin set head = none set temp = none end function function insertAtFirst self value begin set newNode = call node...
#Doubly linked List.... class node: def __init__(self, data): self.data = data self.left=None self.right=None class DoublylinkedList: def __init__(self): self.head=None self.temp=None def insertAtFirst(self,value): newNode=node(value) if(self.head==None): self.head=newNode self.temp=self.head e...
Python
zaydzuhri_stack_edu_python
function make_weights_for_balanced_classes images nclasses begin print string balanced classes set set count = list 0 * nclasses for item in images begin set count at item at 1 = count at item at 1 + 1 end set weight_per_class = list 0.0 * nclasses set N = decimal sum count for i in range nclasses begin comment print(i...
def make_weights_for_balanced_classes(images, nclasses): print("balanced classes set") count = [0] * nclasses for item in images: count[item[1]] += 1 weight_per_class = [0.] * nclasses ...
Python
nomic_cornstack_python_v1
from PyQt5.QtCore import QThread , pyqtSignal from PyQt5.QtNetwork import QUdpSocket , QHostAddress class MessageWorker extends QThread begin set conn_est = call pyqtSignal set msg_sent = call pyqtSignal function __init__ self begin call __init__ self set server_addr = call QHostAddress string 75.65.192.207 set server_...
from PyQt5.QtCore import QThread, pyqtSignal from PyQt5.QtNetwork import QUdpSocket, QHostAddress class MessageWorker(QThread): conn_est = pyqtSignal() msg_sent = pyqtSignal() def __init__(self): QThread.__init__(self) self.server_addr = QHostAddress('75.65.192.207') self.server_...
Python
zaydzuhri_stack_edu_python
function dna_starts_with string prefix begin return string at slice 0 : length prefix : == prefix end function comment neater to push this into a less repetitious form... comment expect true assert call dna_starts_with string ATC string A comment expect false assert not call dna_starts_with string TTC string A comment...
def dna_starts_with(string, prefix): return string[0:len(prefix)] == prefix #neater to push this into a less repetitious form... assert dna_starts_with("ATC", "A") #expect true assert not dna_starts_with("TTC", "A") #expect false assert not dna_starts_with("ATC", "TC") #expect false assert not dna_starts_with(...
Python
zaydzuhri_stack_edu_python
function get_config begin global _BASE_CONFIG return deep copy _BASE_CONFIG end function
def get_config(): global _BASE_CONFIG return copy.deepcopy(_BASE_CONFIG)
Python
nomic_cornstack_python_v1
function get_principal_byemail self email begin set providers = call get_cfg_storage AUTH_PROVIDER_ID for tuple pname provider in items providers begin set principal = call get_principal_byemail email if principal is not none begin return principal end end end function
def get_principal_byemail(self, email): providers = config.get_cfg_storage(AUTH_PROVIDER_ID) for pname, provider in providers.items(): principal = provider.get_principal_byemail(email) if principal is not None: return principal
Python
nomic_cornstack_python_v1
function GetCommandTabBoxCount self begin return call InvokeTypes 1 LCID 1 tuple 3 0 tuple end function
def GetCommandTabBoxCount(self): return self._oleobj_.InvokeTypes(1, LCID, 1, (3, 0), (),)
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string class Rectangulo begin function __init__ self base altura begin comment La verificación de las restricciones no se están haciendo comment Se denomina variable de instancia set __base = decimal base set __altura = decimal altura end function function __str__ self begin return string...
# -*- coding: utf-8 -*- ''' ''' class Rectangulo(): # def __init__(self, base, altura): # # La verificación de las restricciones no se están haciendo # self.__base = float(base) # Se denomina variable de instancia self.__altur...
Python
zaydzuhri_stack_edu_python
import os import pandas as pd import matplotlib.pyplot as plt from datetime import datetime import psycopg2 import numpy as np from sklearn.preprocessing import MinMaxScaler from imblearn.over_sampling import SMOTE from os.path import dirname , abspath set d = directory name directory name absolute path __file__ functi...
import os import pandas as pd import matplotlib.pyplot as plt from datetime import datetime import psycopg2 import numpy as np from sklearn.preprocessing import MinMaxScaler from imblearn.over_sampling import SMOTE from os.path import dirname, abspath d = dirname(dirname(abspath(__file__))) def _user_table(file_path:...
Python
zaydzuhri_stack_edu_python
import numpy as np class ScipyConstraints extends object begin function __init__ self begin set constraints = list end function function add_l2_regularization self params lam begin function lagrangian pv pi begin set pb = array list comprehension pv at pi at p for p in params return lam - 0.5 * dot pb pb end function ...
import numpy as np class ScipyConstraints(object): def __init__(self): self.constraints = [] def add_l2_regularization(self, params, lam): def lagrangian(pv, pi): pb = np.array([pv[pi[p]] for p in params]) return lam - .5 * np.dot(pb, pb) def jacobian(pv, pi...
Python
zaydzuhri_stack_edu_python
function LinkedListSum list_one list_two begin if length != length or length == 0 begin return end set list_sum = call LinkedList set node_one = head set node_two = head while node_one is not none begin call add_in_tail call Node value + value set node_one = next set node_two = next end return list_sum end function
def LinkedListSum(list_one, list_two): if (list_one.len() != list_two.len()) or (list_one.len() == 0): return list_sum = LinkedList() node_one = list_one.head node_two = list_two.head while node_one is not None: list_sum.add_in_tail(Node(node_one.value + node_two.value)) ...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np from sklearn.feature_extraction.text import CountVectorizer set df = read csv string Movie-Review-Sentiment-Analysis\movie_data.csv head df comment converting raw data to tf-idf format comment convert to sparse feature vector comment using bag-of-words model from NLP set count = c...
import pandas as pd import numpy as np from sklearn.feature_extraction.text import CountVectorizer df = pd.read_csv('Movie-Review-Sentiment-Analysis\movie_data.csv') df.head() #converting raw data to tf-idf format #convert to sparse feature vector #using bag-of-words model from NLP count = CountVectorizer() data_do...
Python
zaydzuhri_stack_edu_python
comment multiple inheritance init call analysis class A begin function __init__ self begin print string init of A end function function feature1 self begin print string Feature 1-A end function function featurea self begin print string Feature A end function end class class B begin function __init__ self begin print st...
# multiple inheritance init call analysis class A: def __init__(self): print("init of A") def feature1(self): print("Feature 1-A") def featurea(self): print("Feature A") class B: def __init__(self): print("init of B") def feature1(self): print("Fea...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python2 import os import shutil import scipy.io import numpy as np import ElasticRod import tensorflow as tf import math function rotation_matrix axis theta begin string Return the rotation matrix associated with counterclockwise rotation about the given axis by theta radians. set axis = call asar...
#!/usr/bin/env python2 import os import shutil import scipy.io import numpy as np import ElasticRod import tensorflow as tf import math def rotation_matrix(axis, theta): """ Return the rotation matrix associated with counterclockwise rotation about the given axis by theta radians. """ axis = np.as...
Python
zaydzuhri_stack_edu_python
function sparse_linear self max_ctax begin set path = list set nums = length years for num in range nums begin set first_part_path = linear space 0 max_ctax num=num set second_part_path = array list max_ctax * nums - num append path concatenate list first_part_path second_part_path end set columns = list comprehension...
def sparse_linear(self, max_ctax): path = [] nums = len(self.years) for num in range(nums): first_part_path = np.linspace(0, max_ctax, num=num) second_part_path = np.array([max_ctax] * (nums - num)) path.append(np.concatenate(...
Python
nomic_cornstack_python_v1
function _pad_diff arr w h arr_shape begin set w_diff = arr_shape - w set h_diff = arr_shape - h if length shape > 2 begin set padded_arr = call pad arr tuple tuple 0 w_diff tuple 0 h_diff tuple 0 0 string constant constant_values=nan end else begin set padded_arr = call pad arr tuple tuple 0 w_diff tuple 0 h_diff stri...
def _pad_diff(arr, w, h, arr_shape): w_diff = arr_shape - w h_diff = arr_shape - h if len(arr.shape) > 2: padded_arr = np.pad(arr, ((0, w_diff), (0, h_diff), (0, 0)), "constant", constant_values=np.nan) else: padded_arr = np.pad(arr, ((0, w_diff), (0, h_diff)), "constant", constant_valu...
Python
nomic_cornstack_python_v1
function _parse_answer answer begin set name = answer at slice 0 : 2 : set answer_type = answer at slice 2 : 4 : set answer_class = answer at slice 4 : 6 : set ttl = answer at slice 6 : 10 : set data_length = answer at slice 10 : 12 : set address = answer at slice 12 : : return tuple name answer_type answer_clas...
def _parse_answer(answer): name = answer[0:2] answer_type = answer[2:4] answer_class = answer[4:6] ttl = answer[6:10] data_length = answer[10:12] address = answer[12:] return ( name, answer_type, answer_class, ttl, data_length, address )
Python
nomic_cornstack_python_v1
function show_all_thumbnails label=string j022708p4901_00273 filters=list string visb string visr string y string j string h scale_ab=21 close=true thumb_height=2.0 rgb_params=RGB_PARAMS begin import glob comment from PIL import Image import numpy as np import matplotlib.pyplot as plt import astropy.io.fits as pyfits f...
def show_all_thumbnails(label='j022708p4901_00273', filters=['visb', 'visr', 'y', 'j', 'h'], scale_ab=21, close=True, thumb_height=2., rgb_params=RGB_PARAMS): import glob #from PIL import Image import numpy as np import matplotlib.pyplot as plt import astropy.io.fits as pyfits from as...
Python
nomic_cornstack_python_v1
function item4 self begin return if expression item4 then call get_item item4 else none end function
def item4(self): return cassiopeia.riotapi.get_item(self.data.item4) if self.data.item4 else None
Python
nomic_cornstack_python_v1
function calculate_link app need_info begin try begin if need_info at string is_external begin set link = need_info at string external_url end else begin set link = string ../ + call get_target_uri need_info at string docname + string # + need_info at string target_node at string refid if need_info at string is_part be...
def calculate_link(app, need_info): try: if need_info["is_external"]: link = need_info["external_url"] else: link = "../" + app.builder.get_target_uri(need_info["docname"]) + "#" + need_info["target_node"]["refid"] if need_info["is_part"]: link = f...
Python
nomic_cornstack_python_v1
function step_changes self begin return copy call _get_deltas end function
def step_changes(self) -> pd.Series: return self._get_deltas().copy()
Python
nomic_cornstack_python_v1
function animate_2d t im1 im2 u_hat u begin call set_array detach t dist call set_array detach t dist end function
def animate_2d(t, im1, im2, u_hat, u): im1.set_array(u_hat[t,:,:].squeeze().t().detach()) im2.set_array(u[t,:,:].squeeze().t().detach())
Python
nomic_cornstack_python_v1
function iter_all_multipass_groups self begin return call from_iterable generator expression call get_identity_groups identifier for x in identities if provider != string indico and provider in identity_providers end function
def iter_all_multipass_groups(self): return itertools.chain.from_iterable(multipass.identity_providers[x.provider].get_identity_groups(x.identifier) for x in self.identities if x.provider != 'indico' and x.provider in mult...
Python
nomic_cornstack_python_v1
function status logger begin string Creates a one-line summary on the actions that were logged by the given Logger. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string summarizing the status. set aborted = call get_aborted_actions set succeeded = cal...
def status(logger): """ Creates a one-line summary on the actions that were logged by the given Logger. :type logger: Logger :param logger: The logger that recorded what happened in the queue. :rtype: string :return: A string summarizing the status. """ aborted = logger.get_aborte...
Python
jtatman_500k
comment while응용 import random comment 난수 발생 1~100 string com=random.randrange(1,101) #1~100사이의 난수 발생 count=0 while True: #무한루프 #사용자의 입력값을 받는다 user=int(input("1~100까지 사이의 숫자를 입력:")) count+=1 #비교후에 힌트 제공 if com>user: print(f"{user}보다 큰 수를 입력히세요") elif com<user: print(f"{user}보다 작은 수를 입력하세요") else: print(f"정답입니다!!,입력횟수={c...
# while응용 import random #난수 발생 1~100 ''' com=random.randrange(1,101) #1~100사이의 난수 발생 count=0 while True: #무한루프 #사용자의 입력값을 받는다 user=int(input("1~100까지 사이의 숫자를 입력:")) count+=1 #비교후에 힌트 제공 if com>user: print(f"{user}보다 큰 수를 입력히세요") elif com<user: print(f"{user}보...
Python
zaydzuhri_stack_edu_python
function getAy self begin return components at 1 end function
def getAy(self): return self.motion.acceleration.components[1]
Python
nomic_cornstack_python_v1
import sys from datetime import datetime from xml import sax comment import pymongo import psycopg2 class Handler extends ContentHandler begin function __init__ self callback begin set level = - 1 set collection = none set document = none set item_name = none set data = list set callback = callback end function functi...
import sys from datetime import datetime from xml import sax #import pymongo import psycopg2 class Handler(sax.handler.ContentHandler): def __init__(self, callback): self.level = -1 self.collection = None self.document = None self.item_name = None self.data = [] self...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Sat Jul 14 10:21:17 2018 @author: Paul Festor import numpy as np from random import shuffle import matplotlib.pyplot as plt class Perceptron begin function __init__ self sizes seeEpochsProgression=false cost=string mean_squared savePlots=fals...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jul 14 10:21:17 2018 @author: Paul Festor """ import numpy as np from random import shuffle import matplotlib.pyplot as plt class Perceptron: def __init__(self, sizes, seeEpochsProgression = False, cost = "mean_squared", sav...
Python
zaydzuhri_stack_edu_python
function menu_dispatch prompt menu begin while true begin try begin set response = upper input prompt if call == string quit begin break end end except KeyError begin print string { response } is not an option end end end function
def menu_dispatch(prompt, menu): while True: try: response = input(prompt).upper() if menu[response]() == "quit": break except KeyError: print(f"{response} is not an option")
Python
nomic_cornstack_python_v1
function bubble_sort arr begin set n = length arr comment Traverse through all array elements for i in range n begin comment Last i elements are already in place for j in range 0 n - i - 1 begin comment Traverse the array from 0 to n-i-1. Swap if the element found is greater than the next element if arr at j > arr at j...
def bubble_sort(arr): n = len(arr) # Traverse through all array elements for i in range(n): # Last i elements are already in place for j in range(0, n-i-1): # Traverse the array from 0 to n-i-1. Swap if the element found is greater than the next element if arr[j] > ar...
Python
jtatman_500k
import openpyxl set wb = call load_workbook string example.xlsx print type wb print sheetnames set sheet = wb at string Sheet3 print sheet print title set sheet = active print sheet print sheet at string A1 print value set c = sheet at string B1 print value print string Row + string row + string , Column + string colum...
import openpyxl wb=openpyxl.load_workbook('example.xlsx') print(type(wb)) print(wb.sheetnames) sheet=wb['Sheet3'] print(sheet) print(sheet.title) sheet=wb.active print(sheet) print(sheet['A1']) print(sheet['A1'].value) c=sheet['B1'] print(c.value) print('Row '+str(c.row)+', Column '+str(c.column)+' is '+c.value) prin...
Python
zaydzuhri_stack_edu_python
function record self data begin with open _file string wb as fp begin info string Writing %s to file %s data _file dump data fp end end function
def record(self, data): with open(self._file, 'wb') as fp: LOGGER.info("Writing %s to file %s", data, self._file) pickle.dump(data, fp)
Python
nomic_cornstack_python_v1
function getContextBytes self begin Ellipsis end function
def getContextBytes(self) -> List[int]: ...
Python
nomic_cornstack_python_v1
from abc import ABC , abstractmethod from pedeval.experiment_design import ExperimentDesign import warnings import numpy as np from scipy.stats import percentileofscore class BootstrapMeanEvaluation extends ABC begin function __init__ self n_init_samples=100 n_bootstrap_mean_samples=100 **kwargs begin set initial_sampl...
from abc import ABC, abstractmethod from pedeval.experiment_design import ExperimentDesign import warnings import numpy as np from scipy.stats import percentileofscore class BootstrapMeanEvaluation(ABC): def __init__(self, n_init_samples: int = 100, n_bootstrap_mean_samples: int = 100, **kwargs): self.ini...
Python
zaydzuhri_stack_edu_python
from PIL import Image from auth_server import * from error import * from other import * import pytest from storage import data from json import dumps import requests import urllib from flask import Flask , request from storage import data string Given a URL of an image on the internet, crops the image within bounds (x_...
from PIL import Image from auth_server import * from error import * from other import * import pytest from storage import data from json import dumps import requests import urllib from flask import Flask, request from storage import data ''' Given a URL of an image on the internet, crops the image within bounds (x_star...
Python
zaydzuhri_stack_edu_python
function is_active self begin return not pending end function
def is_active(self): return not self.pending
Python
nomic_cornstack_python_v1
function ifinbroadcastpkts self oidonly=false begin comment Initialize key variables set data_dict = default dictionary dict comment Process OID set oid = string .1.3.6.1.2.1.31.1.1.1.3 comment Return OID value. Used for unittests if oidonly is true begin return oid end comment Process results set results = walk oid no...
def ifinbroadcastpkts(self, oidonly=False): # Initialize key variables data_dict = defaultdict(dict) # Process OID oid = '.1.3.6.1.2.1.31.1.1.1.3' # Return OID value. Used for unittests if oidonly is True: return oid # Process results result...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment @Author : Rock Wayne comment @Created : 2020-07-22 21:53:49 comment @Last Modified : 2020-07-22 21:53:49 comment @Mail : lostlorder@gmail.com comment @Version : 1.0.0 string # 给定一个会议时间安排的数组,每个会议时间都会包括开始和结束的时间 [[s1,e1],[s2,e2],...] (si < ei),为避免会议冲突,同时要考...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Author : Rock Wayne # @Created : 2020-07-22 21:53:49 # @Last Modified : 2020-07-22 21:53:49 # @Mail : lostlorder@gmail.com # @Version : 1.0.0 """ # 给定一个会议时间安排的数组,每个会议时间都会包括开始和结束的时间 [[s1,e1],[s2,e2],...] (si < ei),为避免会议冲突,同时要考虑 # 充分利用会议室资源,请你...
Python
zaydzuhri_stack_edu_python
import os import shutil import yaml import scripts.sort as sort comment Relative paths to Desktop set Desktop = join path environ at string HOMEPATH string Desktop set desktop_files = list directory Desktop comment Relative paths to Downloads dir set Downloads = join path environ at string HOMEPATH string Downloads set...
import os import shutil import yaml import scripts.sort as sort # Relative paths to Desktop Desktop = os.path.join(os.environ["HOMEPATH"], 'Desktop') desktop_files = os.listdir(Desktop) # Relative paths to Downloads dir Downloads = os.path.join(os.environ["HOMEPATH"], 'Downloads') Downloads_files = os.list...
Python
zaydzuhri_stack_edu_python
while salir != string y begin set contador = contador + 1 set nota = integer input string Ingrese la nota de su clase %d: % contador append notas_clases nota set salir = input string ¿Desea salir? y/n: end set total_notas = 0 for nota in notas_clases begin set total_notas = total_notas + nota end set promedio = total_n...
while salir != 'y': contador += 1 nota = int (input("Ingrese la nota de su clase %d: " % contador)) notas_clases.append(nota) salir = input("¿Desea salir? y/n: ") total_notas = 0 for nota in notas_clases: total_notas += nota promedio = (total_notas / contador) print("Su promedio es: %d" % promedio ) if promed...
Python
zaydzuhri_stack_edu_python
function getTypeCode self begin return call SpeciesFeature_getTypeCode self end function
def getTypeCode(self): return _libsbml.SpeciesFeature_getTypeCode(self)
Python
nomic_cornstack_python_v1
function forward self x y begin for module in call children begin set tuple x y = call module x y end return tuple x y end function
def forward(self, x, y): for module in self.children(): x, y = module(x, y) return x, y
Python
nomic_cornstack_python_v1
comment SETELAH DIUBAH SESUAI INTRUKSI set laptop = 2 print string Jumlah Laptop: laptop
#SETELAH DIUBAH SESUAI INTRUKSI laptop = 2 print("Jumlah Laptop: ",(laptop))
Python
zaydzuhri_stack_edu_python
function capitalize sentence begin set new_word_list = list for word in split sentence begin append new_word_list capitalize word end set new_sentence = join string new_word_list return new_sentence end function
def capitalize(sentence): new_word_list = [ ] for word in sentence.split(): new_word_list.append(word.capitalize()) new_sentence = ' '.join(new_word_list) return new_sentence
Python
nomic_cornstack_python_v1
function post self request *args **kwargs begin set employee_mapping_payload = data call assert_valid employee_mapping_payload is not none string Request body is empty set mapping_utils = call MappingUtils kwargs at string workspace_id set employee_mapping_object = call create_or_update_employee_mapping employee_mappin...
def post(self, request, *args, **kwargs): employee_mapping_payload = request.data assert_valid(employee_mapping_payload is not None, 'Request body is empty') mapping_utils = MappingUtils(kwargs['workspace_id']) employee_mapping_object = mapping_utils.create_or_update_employee_mapping(e...
Python
nomic_cornstack_python_v1
function get_loss self get_rating neighbors_num=0 begin set id_pairs = zip customer_vendor_ratings at string customer_id customer_vendor_ratings at string vendor_id set y_pred = array list comprehension call get_rating customer vendor neighbors_num for tuple customer vendor in id_pairs set y_true = array customer_vendo...
def get_loss(self, get_rating, neighbors_num=0): id_pairs = zip(self.customer_vendor_ratings['customer_id'], self.customer_vendor_ratings['vendor_id']) y_pred = np.array([get_rating(customer, vendor, neighbors_num) for (customer, vendor) in id_pairs]) y_true = np.array...
Python
nomic_cornstack_python_v1
comment Function checker => checks is last element breaks the pattern or not comment Parameters: comment per => partial solution function checker per begin set i = length per - 1 for j in range i begin if i - j == absolute per at i - per at j begin return false end end return true end function comment Function solver =...
# Function checker => checks is last element breaks the pattern or not # Parameters: # per => partial solution def checker(per): i=len(per)-1 for j in range(i): if( i-j == abs(per[i]-per[j])): return False return True # Function solver => Generates the solution list. # Parameters: # pe...
Python
zaydzuhri_stack_edu_python