code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function project_fingerprint begin try begin comment skipcq:BAN-B607,BAN-B603 set remote = check output list string git string remote string get-url string origin stderr=DEVNULL return hex digest sha256 remote end except tuple CalledProcessError OSError begin return none end end function
def project_fingerprint() -> Optional[Text]: try: remote = check_output( # skipcq:BAN-B607,BAN-B603 ["git", "remote", "get-url", "origin"], stderr=DEVNULL ) return hashlib.sha256(remote).hexdigest() except (CalledProcessError, OSError): return None
Python
nomic_cornstack_python_v1
comment coding: utf-8 from yowsup.layers.interface import YowInterfaceLayer , ProtocolEntityCallback from yowsup.layers.protocol_messages.protocolentities import TextMessageProtocolEntity import random class ReplyEchoLayer extends YowInterfaceLayer begin decorator call ProtocolEntityCallback string message function onM...
# coding: utf-8 from yowsup.layers.interface import YowInterfaceLayer, ProtocolEntityCallback from yowsup.layers.protocol_messages.protocolentities import TextMessageProtocolEntity import random class ReplyEchoLayer(YowInterfaceLayer): @ProtocolEntityCallback("message") def onMessage(self, messageProtocolEnt...
Python
zaydzuhri_stack_edu_python
comment 1. Basic format for list comprehension comment new_list = [NEW_ITEM for ITEM in LIST], where we replace the KEY_WORDS comment numbers = [1, 2, 3] comment new_numbers = [n+1 for n in numbers] ..... [2, 3, 4] comment 2. Conditional List comprehension comment new_list = [NEW_ITEM for ITEM in LIST if TEST] comment ...
# 1. Basic format for list comprehension # new_list = [NEW_ITEM for ITEM in LIST], where we replace the KEY_WORDS # numbers = [1, 2, 3] # new_numbers = [n+1 for n in numbers] ..... [2, 3, 4] # 2. Conditional List comprehension # new_list = [NEW_ITEM for ITEM in LIST if TEST] # names = ['darren', 'jim', 'eleanor'] # ne...
Python
zaydzuhri_stack_edu_python
import math set x1 = eval input set y1 = eval input set x2 = eval input set y2 = eval input set Distance = x1 - x2 ^ 2 + y1 - y2 ^ 2 print string ( x1 string , y1 string ) print string ( x2 string , y2 string ) print string Distance = %.4f % square root Distance
import math x1=eval(input()) y1=eval(input()) x2=eval(input()) y2=eval(input()) Distance=(x1-x2)**2+(y1-y2)**2 print("(" , x1 , ",", y1 , ")") print("(" , x2 , ",", y2 , ")") print("Distance = %.4f"%(math.sqrt(Distance)))
Python
zaydzuhri_stack_edu_python
string Created on 14 feb. 2019 @author: Edy function stergFisier numeFisier begin set f = open numeFisier string w close f end function function citesteNumar begin while true begin set numar = input string >> try begin set numar = integer numar return numar end except ValueError as ve begin print string Nu i binie end ...
''' Created on 14 feb. 2019 @author: Edy ''' def stergFisier(numeFisier): f = open(numeFisier,"w") f.close() def citesteNumar(): while True: numar = input(">>") try: numar = int(numar) return numar except ValueError as ve: print("Nu ...
Python
zaydzuhri_stack_edu_python
comment type: (int, FrameType) -> None function handle_shutdown_signal self signal_number _stack_frame begin if not acquire _shutdown_lock false begin comment Ctrl+C can result in 2 or even more signals coming in within nanoseconds of each other. We lock to comment prevent handling them all. The duplicates can always b...
def handle_shutdown_signal(self, signal_number, _stack_frame): # type: (int, FrameType) -> None if not self._shutdown_lock.acquire(False): # Ctrl+C can result in 2 or even more signals coming in within nanoseconds of each other. We lock to # prevent handling them all. The duplicates can...
Python
nomic_cornstack_python_v1
function termination_grace_period_seconds self begin return get pulumi self string termination_grace_period_seconds end function
def termination_grace_period_seconds(self) -> Optional[float]: return pulumi.get(self, "termination_grace_period_seconds")
Python
nomic_cornstack_python_v1
comment Add two number program set n1 = integer input string Enter first number : set n2 = integer input string Enter second number : print format string sum of {} and {} is {} n1 n2 n1 + n2
#Add two number program n1=int(input("Enter first number : ")) n2=int(input("Enter second number : ")) print(" sum of {} and {} is {} ".format(n1,n2,n1+n2))
Python
zaydzuhri_stack_edu_python
function eol self begin if enable_scrolling begin if not max_length begin comment infinite scrolling return false end return length content >= max_length end if length content >= max_length begin return true end if content >= _visible_width begin return true end return false end function
def eol(self): if self.enable_scrolling: if not self.max_length: return False # infinite scrolling return len(self.content) >= self.max_length if len(self.content) >= self.max_length: return True if self.content >= self._visible_width: ...
Python
nomic_cornstack_python_v1
string Обчислення конкретної функції, в залежності від введеного значення х x>3 or x<0 F(x)=4 0≤x≤3 F(x)=x^2 import Checker as ch call greet 1 string Обчислення конкретної функції, в залежності від введеного значення х x>3 or x<0 F(x)=4 0≤x≤3 F(x)=x^2 set x = input string x= set x = call floatCheck x if 0 <= x <= 3 beg...
""" Обчислення конкретної функції, в залежності від введеного значення х x>3 or x<0 F(x)=4 0≤x≤3 F(x)=x^2 """ import Checker as ch ch.greet(1,"""Обчислення конкретної функції, в залежності від введеного значення х x>3 or x<0 F(x)=4 0≤x≤3 F(x)=x^2 """) x = input('x=') x = ch.floatCheck(x) if 0 <= x <= 3: print('F...
Python
zaydzuhri_stack_edu_python
function init_model_parallel self_name backend=PROCESS_GROUP self_rank=- 1 init_method=none num_send_recv_threads=4 begin call _init_rpc backend self_name self_rank init_method num_send_recv_threads from api import _agent call _init id end function
def init_model_parallel(self_name, backend=RpcBackend.PROCESS_GROUP, self_rank=-1, init_method=None, num_send_recv_threads=4): _init_rpc(backend, self_name, self_rank, init_method, num_send_recv_threa...
Python
nomic_cornstack_python_v1
import sqlite3 comment ABRIR CONEXION CON BASE DE DATOS set database = call connect string linioexp_parcial_lab3.db set lista = list comment OBTENER OBJETO CURSOR set cursor = call cursor set query = string SELECT * FROM colaborador execute cursor query set lista = call fetchall print lista
import sqlite3 database = sqlite3.connect("linioexp_parcial_lab3.db") # ABRIR CONEXION CON BASE DE DATOS lista=[] cursor = database.cursor() # OBTENER OBJETO CURSOR query = '''SELECT * FROM colaborador ''' cursor.execute(query) lista=cursor.fetchall() print(lista)
Python
zaydzuhri_stack_edu_python
function SetTexture self Config_name=defaultNamedNotOptArg TextureIn=defaultNamedNotOptArg begin return call InvokeTypes 98 LCID 1 tuple 11 0 tuple tuple 8 1 tuple 9 1 Config_name TextureIn end function
def SetTexture(self, Config_name=defaultNamedNotOptArg, TextureIn=defaultNamedNotOptArg): return self._oleobj_.InvokeTypes(98, LCID, 1, (11, 0), ((8, 1), (9, 1)),Config_name , TextureIn)
Python
nomic_cornstack_python_v1
import numpy as np from scipy.misc import lena import OpenGL.GL as gl class Canvas begin set done_init_texture = false function initTexture self begin string init the texture - this has to happen after an OpenGL context has been created comment make the OpenGL context associated with this canvas the current one comment...
import numpy as np from scipy.misc import lena import OpenGL.GL as gl class Canvas(): done_init_texture = False def initTexture(self): """ init the texture - this has to happen after an OpenGL context has been created """ # make the OpenGL context associated with this ...
Python
zaydzuhri_stack_edu_python
function parse_data self text maxwidth maxheight template_dir context urlize_all_links begin comment create a dictionary of user urls -> rendered responses set replacements = dict set user_urls = set find all URL_RE text for user_url in user_urls begin try begin set resource = call embed user_url maxwidth=maxwidth max...
def parse_data(self, text, maxwidth, maxheight, template_dir, context, urlize_all_links): # create a dictionary of user urls -> rendered responses replacements = {} user_urls = set(re.findall(URL_RE, text)) for user_url in user_urls: try: ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python import httplib import hashlib import json string json data { "ver": "TVOS.04.15.010.03.17", "url": "http://172.21.29.243/aosp_mangosteen-ota-TVOS.04.15.010.03.17.zip", "size": "395984367", "md5": "28b4d7f751a1b0a9f3a7e7cf78734c19" } function main begin set conn = call HTTPConnection string 172....
#!/usr/bin/python import httplib import hashlib import json ''' json data { "ver": "TVOS.04.15.010.03.17", "url": "http://172.21.29.243/aosp_mangosteen-ota-TVOS.04.15.010.03.17.zip", "size": "395984367", "md5": "28b4d7f751a1b0a9f3a7e7cf78734c19" } ''' def main(): conn = httplib.HTTPConnection("172.2...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- class Solution begin string @param k: An integer @param n: An integer @return: An integer denote the count of digit k in 1..n function digitCounts self k n begin comment write your code here set strk = string k set count = 0 for i in range 0 n + 1 begin set stri = string i for j in stri be...
# -*- coding: utf-8 -*- class Solution: """ @param k: An integer @param n: An integer @return: An integer denote the count of digit k in 1..n """ def digitCounts(self, k, n): # write your code here strk=str(k) count=0 for i in range(0,n+1): stri=str(i...
Python
zaydzuhri_stack_edu_python
function is_dir path begin return is directory path path end function
def is_dir(path): return os.path.isdir(path)
Python
nomic_cornstack_python_v1
function test_details_description self begin set description = string _foodesc_ <script> save set res = get self headers=dict string X-Requested-With string XMLHttpRequest call mustcontain string <em>foodesc</em> &lt;script&gt; end function
def test_details_description(self): self.tag.description = "_foodesc_ <script>" self.tag.save() res = self.get(headers={"X-Requested-With": "XMLHttpRequest"}) res.mustcontain("<em>foodesc</em> &lt;script&gt;")
Python
nomic_cornstack_python_v1
comment ! /usr/bin/python comment this script detects comment o tabs comment o CRs comment the script accepts a list of files (or file wildcards) comment as sysargs... import sys , os.path , string set tabsize = 8
#! /usr/bin/python # # this script detects # # o tabs # o CRs # # the script accepts a list of files (or file wildcards) # as sysargs... # import sys, os.path, string tabsize = 8
Python
zaydzuhri_stack_edu_python
import argparse import numpy as np import cv2 import matplotlib.pyplot as plt import glob set parser = call ArgumentParser call add_argument string --dataset_dir type=str default=string ../rgbd_dataset/RGBD/ call add_argument string --dataset_name type=str default=string Nami7 call add_argument string --start type=int ...
import argparse import numpy as np import cv2 import matplotlib.pyplot as plt import glob parser = argparse.ArgumentParser() parser.add_argument('--dataset_dir', type=str, default='../rgbd_dataset/RGBD/') parser.add_argument('--dataset_name', type=str, default='Nami7') parser.add_argument('--start', type=in...
Python
zaydzuhri_stack_edu_python
function get_phone_stream self begin set phones = list with open phnfile string r as filehandle begin for line in filehandle begin set phone = split strip line string at 2 append phones PHONE_IDX_DICT at phone end end return array phones end function
def get_phone_stream(self): phones = [] with open(self.phnfile, 'r') as filehandle: for line in filehandle: phone = line.strip().split(" ")[2] phones.append(PHONE_IDX_DICT[phone]) return np.array(phones)
Python
nomic_cornstack_python_v1
function save self outfile sep=none fmt=string %.5f begin comment save the activations if sep in list none string begin comment numpy binary format set npz = dict string activations self ; string fps fps call savez outfile keyword npz end else begin if ndim > 2 begin raise call ValueError string Only 1D and 2D activat...
def save(self, outfile, sep=None, fmt='%.5f'): # save the activations if sep in [None, '']: # numpy binary format npz = {'activations': self, 'fps': self.fps} np.savez(outfile, **npz) else: if self.ndim > 2: rais...
Python
nomic_cornstack_python_v1
function get_camera_list self begin set sql = format string set role {}; write_role + string SELECT site_name FROM raw.cameras return sql end function
def get_camera_list(self): sql = 'set role {}; '.format(self.write_role) \ + f"SELECT site_name FROM raw.cameras" return sql
Python
nomic_cornstack_python_v1
function execute_query self query test_logical=false skip_json=false begin set plan = call get_plan query logical=test_logical if not test_logical and not skip_json begin comment Test that JSON compilation runs without error set json_string = dumps call compile_to_json string some query string some logical plan plan st...
def execute_query(self, query, test_logical=False, skip_json=False): plan = self.get_plan(query, logical=test_logical) if not test_logical and not skip_json: # Test that JSON compilation runs without error json_string = json.dumps(compile_to_json("some query", ...
Python
nomic_cornstack_python_v1
function __call__ self index=none begin if index is not none begin set index = index end else begin set index = index + 1 if index == length functions begin set index = 0 end end set f = functions at index print format string Calling {} f f dist end function
def __call__(self, index=None): if index is not None: self.index = index else: self.index += 1 if self.index == len(self.functions): self.index = 0 f = self.functions[self.index] print('Calling {}'.format(f)) f()
Python
nomic_cornstack_python_v1
function build_table self view_entries limit format_method build_urls=true begin if build_urls begin call build_table_urls view_entries end set index = 0 for view_entry in view_entries begin set index = index + 1 set index = index call echo call format_method view_entry if index >= limit begin break end end if build_ur...
def build_table(self, view_entries, limit, format_method, build_urls=True): if build_urls: self.build_table_urls(view_entries) index = 0 for view_entry in view_entries: index += 1 view_entry.index = index click.echo(format_method(view_entry)) ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python from glob import glob import sys , os import bencode import hashlib , base64 function torrent2magnet f begin if length f == 0 begin return false end set f = f at 0 set torrent = read open f string r try begin set metadata = call bdecode torrent end except BTFailure begin return false end se...
#!/usr/bin/env python from glob import glob import sys, os import bencode import hashlib, base64 def torrent2magnet(f): if len(f) == 0: return False f = f[0] torrent = open(f, 'r').read() try: metadata = bencode.bdecode(torrent) except bencode.BTL.BTFailure: return False ...
Python
zaydzuhri_stack_edu_python
function formated_name name begin return strip title name end function function formated_hello name begin return strip title name end function
def formated_name(name): return name.title().strip() def formated_hello(name): return name.title().strip()
Python
zaydzuhri_stack_edu_python
function classify_question_senate question bill_title votetype amendment amendment2 amendment3 test=0 begin set dict = dict set amendment = lower amendment end function
def classify_question_senate(question,bill_title,votetype,amendment,amendment2,amendment3,test=0): dict={} amendment=amendment.lower()
Python
nomic_cornstack_python_v1
from knock20 import wiki_UK import re for line in split call wiki_UK string begin set obj = find all string (==+)(.*?)==+ line if obj begin for i in obj begin print length i at 0 - 1 i at 1 end end end comment i[0]は=の数。今回は==でレベル1のため、len()でとった長さから1を引く必要がある comment for line in wiki_UK().split('\n'): comment if "===" in l...
from knock20 import wiki_UK import re for line in wiki_UK().split('\n'): obj = re.findall(r'(==+)(.*?)==+', line) if obj: for i in obj: print(len(i[0])-1, i[1]) #i[0]は=の数。今回は==でレベル1のため、len()でとった長さから1を引く必要がある # for line in wiki_UK().split('\n'): # if "===" in line: # print(li...
Python
zaydzuhri_stack_edu_python
function source_interface self source_interface begin set _source_interface = source_interface end function
def source_interface(self, source_interface): self._source_interface = source_interface
Python
nomic_cornstack_python_v1
comment Test the function set dict1 = dict string A 1 ; string B 2 set dict2 = dict string C 3 ; string D 4 ; string A 6 ; string E 8 set merged_dict = call merge_and_sort dict1 dict2
# Test the function dict1 = {'A': 1, 'B': 2} dict2 = {'C': 3, 'D': 4, 'A': 6, 'E': 8} merged_dict = merge_and_sort(dict1, dict2)
Python
greatdarklord_python_dataset
comment Below are a set of scores that students have received in the past semester. Write code to determine how many are 90 comment or above and assign that result to the value a_scores. set scores = string 67 80 90 78 93 20 79 89 96 97 92 88 79 68 58 90 98 100 79 74 83 88 80 86 85 70 90 100 set scores = split scores s...
# Below are a set of scores that students have received in the past semester. Write code to determine how many are 90 # or above and assign that result to the value a_scores. scores = "67 80 90 78 93 20 79 89 96 97 92 88 79 68 58 90 98 100 79 74 83 88 80 86 85 70 90 100" scores = scores.split() a_scores = 0 for score i...
Python
zaydzuhri_stack_edu_python
function test01a self begin set b = array range N rootdir=rootdir call resize 3 set a = array range 3 comment print "b->", `b` call assert_array_equal a b at slice : : string Arrays are not equal end function
def test01a(self): b = bcolz.arange(self.N, rootdir=self.rootdir) b.resize(3) a = np.arange(3) # print "b->", `b` assert_array_equal(a, b[:], "Arrays are not equal")
Python
nomic_cornstack_python_v1
comment listeners comment nc -l -p 5232 -vvv import os import platform import base64 from Session import * from MenuBase import * class Shell begin function __init__ self name desc codeLines begin set _name = name set _desc = desc set _lines = codeLines set _base64 = base64 encode bytes codeLines string utf-8 set _encr...
# listeners # nc -l -p 5232 -vvv import os import platform import base64 from Session import * from MenuBase import * class Shell: def __init__(self, name, desc, codeLines): self._name = name self._desc = desc self._lines = codeLines self._base64 = base64.b64encode(bytes(codeLines...
Python
zaydzuhri_stack_edu_python
import socket from multiprocessing import Process import re class HTTPServer extends object begin function __init__ self application begin set server_socket = call socket AF_INET SOCK_STREAM set app = application end function function bind self port begin call bind tuple string port end function function start self be...
import socket from multiprocessing import Process import re class HTTPServer(object): def __init__(self, application): self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.app = application def bind(self, port): self.server_socket.bind(('', port)) def start(se...
Python
zaydzuhri_stack_edu_python
set num = 3.14159 set rounded_num = round num 2 set rounded_num_str = string rounded_num print rounded_num_str
num = 3.14159 rounded_num = round(num, 2) rounded_num_str = str(rounded_num) print(rounded_num_str)
Python
greatdarklord_python_dataset
from PNL import BayesNet import unittest function basic_network only_structure=false begin string Returns a basic valid network to test the APIs set structure = dict string node1 dict string state1 0.3 ; string state2 0.7 ; string node2 dict string state1 0.7 ; string state2 0.3 if only_structure begin return structure...
from PNL import BayesNet import unittest def basic_network(only_structure=False): """ Returns a basic valid network to test the APIs """ structure = { "node1" : { "state1" : 0.3, "state2" : 0.7, }, "node2" : { "state1" : 0.7, ...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np from sklearn.ensemble import GradientBoostingClassifier from sklearn.model_selection import GridSearchCV , cross_val_score set data_loc = string data/uci_data/poker_hand/poker-hand-training-true.data.txt set col_names = list string S1 string C1 string S2 string C2 string S3 string...
import pandas as pd import numpy as np from sklearn.ensemble import GradientBoostingClassifier from sklearn.model_selection import GridSearchCV, cross_val_score data_loc = 'data/uci_data/poker_hand/poker-hand-training-true.data.txt' col_names = ['S1', 'C1', 'S2', 'C2', 'S3', 'C3', 'S4', 'C4', 'S5', 'C5', 'hand'] df =...
Python
zaydzuhri_stack_edu_python
comment x坐标变换 comment input x,y out put new x,y import numpy as np import cv2 as cv from math import cos , sin , radians , tan , atan , degrees , atan2 , asin , sqrt comment class p1top2(): set door_height = 2.032 set garage_height = 2.1336 comment [-2.798125, 0.11343750000000086, 12.1] comment [-9.713291932979814, 0.1...
#x坐标变换 # input x,y out put new x,y import numpy as np import cv2 as cv from math import cos,sin,radians,tan,atan,degrees,atan2, asin,sqrt # class p1top2(): door_height = 2.032 garage_height = 2.1336 # [-2.798125, 0.11343750000000086, 12.1] # [-9.713291932979814, 0.11343750000000086, 15.129510512251684]...
Python
zaydzuhri_stack_edu_python
function longest_word_length string begin set words = split string string set max_length = 0 for word in words begin if length word > max_length begin set max_length = length word end end return max_length end function
def longest_word_length(string): words = string.split(' ') max_length = 0 for word in words: if len(word) > max_length: max_length = len(word) return max_length
Python
flytech_python_25k
function p_mean_variance self mels y t clip_denoised begin set batch_size = shape at 0 set noise_level = to repeat batch_size 1 mels set eps_recon = nn mels y noise_level set y_recon = call predict_start_from_noise y t eps_recon if clip_denoised begin call clamp_ - 1.0 1.0 end set tuple model_mean posterior_log_varianc...
def p_mean_variance(self, mels, y, t, clip_denoised: bool): batch_size = mels.shape[0] noise_level = torch.FloatTensor( [self.sqrt_alphas_cumprod_prev[t+1]]).repeat(batch_size, 1).to(mels) eps_recon = self.nn(mels, y, noise_level) y_recon = self.predict_start_from_noise(y, t,...
Python
nomic_cornstack_python_v1
function test_spring_underneath_keepalive self begin call set_block tuple 0 0 0 slot call set_block tuple 0 1 0 slot add tracked tuple 0 0 0 add tracked tuple 0 1 0 comment Tight-loop run the hook to equilibrium. while tracked begin process end comment Remove the upper spring. call destroy tuple 0 1 0 add tracked tuple...
def test_spring_underneath_keepalive(self): self.w.set_block((0, 0, 0), blocks["spring"].slot) self.w.set_block((0, 1, 0), blocks["spring"].slot) self.hook.tracked.add((0, 0, 0)) self.hook.tracked.add((0, 1, 0)) # Tight-loop run the hook to equilibrium. while self.hook....
Python
nomic_cornstack_python_v1
function unwrap self target_type begin set node = self while is instance node AlgoWrapper begin if is instance node target_type begin return node end set node = algorithm end if is instance node target_type begin return node end raise call RuntimeError string Unable to find a wrapper or algorithm of type { target_type ...
def unwrap(self, target_type: type[WrappedT]) -> WrappedT: node = self while isinstance(node, AlgoWrapper): if isinstance(node, target_type): return node node = node.algorithm if isinstance(node, target_type): return node raise RuntimeE...
Python
nomic_cornstack_python_v1
comment mapping of province to abbreviation set provinces = dict string Ontario string ON ; string British Columbia string BC ; string Quebec string QC comment mapping of province to capitalize set cities = dict string ON string Toronto ; string QC string Montreal ; string NS string Halifax comment add more cities set ...
# mapping of province to abbreviation provinces = { "Ontario": "ON", "British Columbia": "BC", "Quebec":"QC" } # mapping of province to capitalize cities = { "ON": "Toronto", "QC": "Montreal", "NS": "Halifax" } # add more cities cities["BC"] = "Vancouver" # print out some cities
Python
zaydzuhri_stack_edu_python
import pandas as pd set movies = read csv string http://bit.ly/imdbratings print string Head: print head movies print print string Columns: print columns print print string Shape: print shape print comment Output: comment Head: comment star_rating title content_rating genre duration \ comment 0 9.3 The Shawshank Redemp...
import pandas as pd movies = pd.read_csv('http://bit.ly/imdbratings') print('Head:') print(movies.head()) print() print('Columns: ') print(movies.columns) print() print('Shape: ') print (movies.shape) print() # Output: # Head: # star_rating title content_rating genre duration \ # 0 ...
Python
zaydzuhri_stack_edu_python
comment 构造器方法 comment Critter Caretaker comment 一只需要细心呵护的虚拟动物 class Critter extends object begin string A virtual pet function _init_ self name hunger=0 boredom=0 begin set name = name set hunger = hunger set bordom = boredom end function comment _pass_time()方法 function _pass_time self begin set hunger = hunger + 1 set...
#构造器方法 #Critter Caretaker #一只需要细心呵护的虚拟动物 class Critter(object): """A virtual pet""" def _init_(self, name, hunger = 0, boredom =0): self.name = name self.hunger = hunger self.bordom = boredom #_pass_time()方法 def _pass_time(self): self.hunger += 1 self.boredom +...
Python
zaydzuhri_stack_edu_python
function move_to self row col begin set position = call Position row col end function
def move_to(self, row, col): self.position = Position(row, col)
Python
nomic_cornstack_python_v1
function nth iterable n default=none begin return next iterator slice iterable n none default end function
def nth(iterable, n, default=None): return next(islice(iterable, n, None), default)
Python
nomic_cornstack_python_v1
for i in range 1 9 begin for j in range i begin print i end=string set i = i + 0 end print end
for i in range(1,9): for j in range (i): print(i,end=" ") i=i+0 print()
Python
zaydzuhri_stack_edu_python
function mass self begin if _propagator is not none begin return call getMass end else begin set err_msg = string Mass of + namespace + string not initialized. Build propagator method has to be called first! raise call AttributeError err_msg end end function
def mass(self): if self._propagator is not None: return self._propagator._propagator_num.getInitialState().getMass() else: err_msg = "Mass of " + self.namespace + " not initialized. Build propagator method has to be called first!" raise AttributeError(err_msg)
Python
nomic_cornstack_python_v1
comment Deisgn an API to get latest message id such that no previous messages are missing. It should have following methods: comment # this method should adds a message with id number as received message comment def ack(number) comment # this method should return the id of last message whose previous counts are not mis...
# Deisgn an API to get latest message id such that no previous messages are missing. It should have following methods: # # this method should adds a message with id number as received message # def ack(number) # # this method should return the id of last message whose previous counts are not missing # def latest() #...
Python
zaydzuhri_stack_edu_python
string https://docs.python.org/3/library/ import math from math import sqrt comment import externalmodules.cars as cars #this is not the better way to do it comment from externalmodules import cars from externalmodules.cars import info , carlocation class ModulesDemo begin function builtin_modules self begin comment th...
""" https://docs.python.org/3/library/ """ import math from math import sqrt #import externalmodules.cars as cars #this is not the better way to do it #from externalmodules import cars from externalmodules.cars import info, carlocation class ModulesDemo(): def builtin_modules(self): print(int(math.sqrt(100))) #thi...
Python
zaydzuhri_stack_edu_python
function locate_file file_in_root_path begin set cur_file_path = directory name path directory name path absolute path path __file__ set tuple proj_root_path _ = split path cur_file_path set target_file_path = join path proj_root_path file_in_root_path return target_file_path end function
def locate_file(file_in_root_path): cur_file_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) proj_root_path, _ = os.path.split(cur_file_path) target_file_path = os.path.join(proj_root_path, file_in_root_path) return target_file_path
Python
nomic_cornstack_python_v1
function py_cpu_nms dets thresh begin comment 所有图片的坐标信息,字典形式储存?? set x1 = dets at tuple slice : : 0 set y1 = dets at tuple slice : : 1 set x2 = dets at tuple slice : : 2 set y2 = dets at tuple slice : : 3 set scores = dets at tuple slice : : 4 comment 计算出所有图片的面积 set areas = x2 - x1 + 1 * y2 - y1 + 1 comm...
def py_cpu_nms(dets, thresh): # 所有图片的坐标信息,字典形式储存?? x1 = dets[:, 0] y1 = dets[:, 1] x2 = dets[:, 2] y2 = dets[:, 3] scores = dets[:, 4] areas = (x2 - x1 + 1) * (y2 - y1 + 1) # 计算出所有图片的面积 order = scores.argsort()[::-1] # 图片评分按升序排序 keep = [] # 用来存放最后保留的图片的相应评分 while order.size ...
Python
nomic_cornstack_python_v1
function pull_messages client subscription begin set name = call get_full_subscription_name PROJECT_ID subscription set body = dict string returnImmediately false ; string maxMessages BATCH_SIZE return execute call pull subscription=name body=body num_retries=NUM_RETRIES end function
def pull_messages(client, subscription): name = get_full_subscription_name(PROJECT_ID,subscription) body = {'returnImmediately': False, 'maxMessages': BATCH_SIZE } return client.projects().subscriptions().pull( subscription=name, body=body).execute(num_retries=NUM_RETRIES)
Python
nomic_cornstack_python_v1
function get_json_data file_path begin with open file_path string r as file begin return load json file end end function
def get_json_data(file_path: str) -> list: with open(file_path, 'r') as file: return json.load(file)
Python
nomic_cornstack_python_v1
import torch import numpy as np from scipy.spatial.distance import pdist , squareform string This file contains general purpose functions used across different experiments function sigmoid x begin return 1 / 1 + exp - x end function function pairwise_distances N x y begin string Returns distance matrix that contains th...
import torch import numpy as np from scipy.spatial.distance import pdist, squareform """ This file contains general purpose functions used across different experiments """ def sigmoid(x): return 1 / (1 + np.exp(-x)) def pairwise_distances(N, x, y): """ Returns distance matrix that contains the dist...
Python
zaydzuhri_stack_edu_python
import os import sys import re from matplotlib import pyplot from pylab import genfromtxt from matplotlib.backends.backend_pdf import PdfPages function getDigits begin set ids = list set files = list comprehension f for f in list directory string . if string .dat in f for file in files begin append ids integer find al...
import os import sys import re from matplotlib import pyplot from pylab import genfromtxt from matplotlib.backends.backend_pdf import PdfPages def getDigits (): ids = [] files = [f for f in os.listdir('.') if ".dat" in f] for file in files: ids.append(int(re.findall('\d+',file)[0])) ids.sort() return ids def...
Python
zaydzuhri_stack_edu_python
import threading from queue import Queue import time import random import input_module import alertt import storage import json comment generate data in random time function generate_data q q_alert q_data begin print string ======****** Welcome to Use Patient Monitor ******====== print string ==========================...
import threading from queue import Queue import time import random import input_module import alertt import storage import json # generate data in random time def generate_data(q, q_alert, q_data): print("======****** Welcome to Use Patient Monitor ******======") print("==============================================...
Python
zaydzuhri_stack_edu_python
from WTDrivers import WTDrivers from selenium import webdriver import time set driver = call Chrome call maximize_window get driver string https://www.youtube.com/ comment filepath:where all the images will be stored set obj = call WTDrivers driver filetype=string .png filepath=string ./tmp/images/ set sub_image = stri...
from WTDrivers import WTDrivers from selenium import webdriver import time driver = webdriver.Chrome() driver.maximize_window() driver.get('https://www.youtube.com/') obj = WTDrivers(driver,filetype=".png",filepath="./tmp/images/") #filepath:where all the images will be stored sub_image = "test_scripts/images/ico...
Python
zaydzuhri_stack_edu_python
import datetime , calendar set today = today print string ============================== Welcome to Zenith Bank =============================== set Pin_code = input string Please Enter your Pin Code: if Pin_code == string 123 begin print string Welcome name end else begin print string Pin codes dont match end comment =...
import datetime,calendar today = datetime.date.today() print('==============================\n Welcome to Zenith Bank \n===============================') Pin_code=input('Please Enter your Pin Code: ') if Pin_code=='123': print('Welcome',Customer.name) else: print('Pin codes dont match') # ========== ...
Python
zaydzuhri_stack_edu_python
for item in data begin set tuple country town cost = split strip item string " string > set town = capitalize town set cost = integer cost if country not in travel begin set temp_dict = dict town cost set travel at country = temp_dict end else if town in travel at country begin if cost < travel at country at town begin...
for item in data: country, town, cost = item.strip('"').split(' > ') town = town.capitalize() cost = int(cost) if country not in travel: temp_dict = {town: cost} travel[country] = temp_dict else: if town in travel[country]: if cost < travel[country][town]: travel[country][town] = cost elif town not ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import sys from Game import game import os.path import xml.etree.ElementTree as ET import urllib.parse import requests import json comment Constants comment --------- set GAMES_JSON = string games.json set outputobject = dict set outputobject at string games = list set already_collected_g...
#!/usr/bin/env python import sys from Game import game import os.path import xml.etree.ElementTree as ET import urllib.parse import requests import json # Constants # --------- GAMES_JSON = "games.json" outputobject = {} outputobject["games"] = [] already_collected_games = [] if os.path.isfile(GAMES_JSON): with ...
Python
zaydzuhri_stack_edu_python
function find_IP_from_additional_data self additional_data begin set IPs = list comment 1 : A Record set IPs = list comprehension address for rrset in additional_data if rdtype == 1 return IPs end function
def find_IP_from_additional_data(self, additional_data : list): IPs = list() IPs = [rrset[0].address for rrset in additional_data if rrset.rdtype == 1] # 1 : A Record return IPs
Python
nomic_cornstack_python_v1
function getTelemetrySubscriptions self request context begin call set_code UNIMPLEMENTED call set_details string Method not implemented! raise call NotImplementedError string Method not implemented! end function
def getTelemetrySubscriptions(self, request, context): context.set_code(grpc.StatusCode.UNIMPLEMENTED) context.set_details('Method not implemented!') raise NotImplementedError('Method not implemented!')
Python
nomic_cornstack_python_v1
import os import shutil import face_recognition import cv2 class Faces_Recognition begin function __init__ self photo_of_child_dir photo_social_dir begin set error_mean = 0.5 comment можно было бы использовать CUDA, но нужен графический процессор от nvidia (модель cnn, быстрее и лучше) set model = string hog set photo_...
import os import shutil import face_recognition import cv2 class Faces_Recognition(): def __init__(self, photo_of_child_dir, photo_social_dir): self.error_mean = 0.5 self.model = 'hog' # можно было бы использовать CUDA, но нужен графический процессор от nvidia (модель cnn, быстрее и лучше) ...
Python
zaydzuhri_stack_edu_python
import numpy as np import pandas as pd import matplotlib.pyplot as plt function dframe days begin set d = call DataFrame index=days columns=list string A string B string C string D string E string ps string sA string sB string sC string sD string sE data=1 set name = string days set loc at tuple slice 3 : : string A ...
import numpy as np import pandas as pd import matplotlib.pyplot as plt def dframe(days): d = pd.DataFrame(index=days, columns=[ "A", "B", "C", "D", "E", "ps", "sA", "sB", "sC", "sD", "sE"], data=1) d.index.name = "days" d.loc[3:, "A"] = 0 d.loc[6:, "B"] = 0 d.loc[5:, "C"] = 0 d.loc[4:,...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python import os , re , urllib from urllib2 import Request , urlopen , URLError , HTTPError function main begin set base_url = string http://www.google.com/events/io/2011/static/css/ set source = string style.css set file = open source comment download images referenced in stylesheet for line in f...
#!/usr/bin/env python import os, re, urllib from urllib2 import Request, urlopen, URLError, HTTPError def main(): base_url = "http://www.google.com/events/io/2011/static/css/" source = "style.css" file = open(source) # download images referenced in stylesheet for line in file: urls = re.findall("url\((.*)\)",...
Python
zaydzuhri_stack_edu_python
import numpy set N = integer input set A = list set B = list for i in range N begin append A array split input int end for j in range N begin append B array split input int end print dot A B
import numpy N = int(input()) A = [] B = [] for i in range(N): A.append(numpy.array(input().split(), int)) for j in range(N): B.append(numpy.array(input().split(), int)) print(numpy.dot(A,B))
Python
zaydzuhri_stack_edu_python
function summary_frame self xname=none alpha=0.05 begin if effect is not none begin comment we have everything for a params table set use_t = distribution == string t comment Not used in params_frame set yname = string constraints if xname is none begin set xname = list comprehension string c%d % ii for ii in range len...
def summary_frame(self, xname=None, alpha=0.05): if self.effect is not None: # we have everything for a params table use_t = (self.distribution == 't') yname='constraints' # Not used in params_frame if xname is None: xname = ['c%d'%ii for ii in ra...
Python
nomic_cornstack_python_v1
function __init__ self access_key_id bucket cacert endpoint no_ssl_verify region secret_access_key staging_directory begin set log = call get_logger set access_key_id = access_key_id set bucket = bucket set cacert = cacert set endpoint = endpoint set no_ssl_verify = no_ssl_verify set region = region set secret_access_k...
def __init__(self, access_key_id, bucket, cacert, endpoint, no_ssl_verify, region, secret_access_key, staging_directory): self.log = logger.Logger.get_logger() self.access_key_id = access_key_id self.bucket = bucket self.cacert = cacert self.endpoint = endpoint self.no_ss...
Python
nomic_cornstack_python_v1
string rolling_dice.py ~~~~~~~~~~~~~~~ This module solves the rolling dice in-class problem. Run with "python rolling_dice.py" function average i outcomes begin set rsp = 0 for j in range 1 7 begin set rsp = rsp + get outcomes tuple i j 0 end return rsp / 6 end function function simulate n_rounds begin set outcomes = d...
""" rolling_dice.py ~~~~~~~~~~~~~~~ This module solves the rolling dice in-class problem. Run with "python rolling_dice.py" """ def average(i, outcomes): rsp = 0 for j in range(1, 7): rsp += outcomes.get((i, j), 0) return rsp / 6 def simulate(n_rounds): outcomes = {} fo...
Python
zaydzuhri_stack_edu_python
comment Definition for a binary tree node. comment class TreeNode: comment def __init__(self, x): comment self.val = x comment self.left = None comment self.right = None comment 递归做法,28ms class Solution begin function inorderTraversal self root begin set res = list if not root begin return res end function helper root...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None #递归做法,28ms class Solution: def inorderTraversal(self, root: TreeNode) -> List[int]: res = [] if not root: retur...
Python
zaydzuhri_stack_edu_python
function diskdata begin string Get total disk size in GB. set p = popen string /bin/df -l -P set ddata = dict set tsize = 0 for line in read lines p begin set d = split line if string /dev/sd in d at 0 or string /dev/hd in d at 0 or string /dev/mapper in d at 0 begin set tsize = tsize + integer d at 1 end end set ddat...
def diskdata(): """Get total disk size in GB.""" p = os.popen("/bin/df -l -P") ddata = {} tsize = 0 for line in p.readlines(): d = line.split() if ("/dev/sd" in d[0] or "/dev/hd" in d[0] or "/dev/mapper" in d[0]): tsize = tsize + int(d[1]) ddata["Disk_GB"] = int(tsize...
Python
jtatman_500k
comment Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем. comment Об окончании ввода данных свидетельствует пустая строка. set file_obj = open string 5-1.txt string a encoding=string utf-8 while true begin set user_enter = input string Введите текст (для выхода остав...
# Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем. # Об окончании ввода данных свидетельствует пустая строка. file_obj = open('5-1.txt', 'a', encoding='utf-8') while True: user_enter = input('Введите текст (для выхода оставьте строку пустую и нажмите "Ente...
Python
zaydzuhri_stack_edu_python
function writefile self path content=none frompath=none begin set full = join path base_path path if not exists path directory name path full begin make directories directory name path full end set f = open full string wb if content is not none begin write f content end if frompath is not none begin if template_path be...
def writefile(self, path, content=None, frompath=None): full = os.path.join(self.base_path, path) if not os.path.exists(os.path.dirname(full)): os.makedirs(os.path.dirname(full)) f = open(full, 'wb') if content is not None: f.write(content) ...
Python
nomic_cornstack_python_v1
function start_period self start_period begin set _start_period = start_period end function
def start_period(self, start_period): self._start_period = start_period
Python
nomic_cornstack_python_v1
from flask import Flask , request , jsonify from flask_pymongo import PyMongo from werkzeug.security import generate_password_hash , check_password_hash import uuid import jwt import datetime from functools import wraps set app = call Flask __name__ set config at string SECRET_KEY = string securekey set config at strin...
from flask import Flask, request, jsonify from flask_pymongo import PyMongo from werkzeug.security import generate_password_hash, check_password_hash import uuid import jwt import datetime from functools import wraps app = Flask(__name__) app.config['SECRET_KEY']='securekey' app.config['MONGO_DBNAME'] = 's_database' a...
Python
zaydzuhri_stack_edu_python
function write_pdb fileobj images begin if is instance fileobj str begin set fileobj = call paropen fileobj string w end if not is instance images tuple list tuple begin set images = list images end set format = string ATOM %5d %-4s %8.3f%8.3f%8.3f 0.00 0.00 comment RasMol complains if the atom index exceeds 100000. Th...
def write_pdb(fileobj, images): if isinstance(fileobj, str): fileobj = paropen(fileobj, 'w') if not isinstance(images, (list, tuple)): images = [images] format = 'ATOM %5d %-4s %8.3f%8.3f%8.3f 0.00 0.00\n' # RasMol complains if the atom index exceeds 100000. There migh...
Python
nomic_cornstack_python_v1
if n * a > b begin print b end else if n * a < b begin print n * a end else begin print b end
if n*a >b: print(b) elif n*a <b: print(n*a) else: print(b)
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment In[6]: import json , sys , os from os.path import expanduser as eu from hac import GreedyAgglomerativeClusterer import networkx as nx from collections import defaultdict from itertools import combinations comment # Clustering! comment In this notebook, we perfo...
#!/usr/bin/env python # coding: utf-8 # In[6]: import json,sys,os from os.path import expanduser as eu from hac import GreedyAgglomerativeClusterer import networkx as nx from collections import defaultdict from itertools import combinations # # Clustering! # In this notebook, we perform the actual clustering. Give...
Python
zaydzuhri_stack_edu_python
from sklearn.base import BaseEstimator , OutlierMixin from scipy.stats import norm from scipy.special import logsumexp from tqdm import tqdm class BayesOCPD extends BaseEstimator OutlierMixin begin string Bayesian online change point detection, see Adams & MacKay 2007. function __init__ self model hazard mini_run_lengt...
from sklearn.base import BaseEstimator, OutlierMixin from scipy.stats import norm from scipy.special import logsumexp from tqdm import tqdm class BayesOCPD(BaseEstimator, OutlierMixin): """ Bayesian online change point detection, see Adams & MacKay 2007. """ def __init__(self, model, hazard, mini_run_l...
Python
zaydzuhri_stack_edu_python
import pandas as pd comment Creating two separate DataFrames set df1 = call DataFrame dict string A list 1 2 3 set df2 = call DataFrame dict string B list 4 5 6 comment Concatenating DataFrames along columns set merged_df = concat list df1 df2 axis=1 comment Let me examine if the code works comment 1. Concatenated two ...
import pandas as pd # Creating two separate DataFrames df1 = pd.DataFrame({'A': [1, 2, 3]}) df2 = pd.DataFrame({'B': [4, 5, 6]}) # Concatenating DataFrames along columns merged_df = pd.concat([df1, df2], axis=1) # Let me examine if the code works # 1. Concatenated two DataFrames along columns # Executing code... # C...
Python
flytech_python_25k
import os import json import pickle import numpy as np import scipy.sparse from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import LogisticRegression from my_preprocess import preprocessing function get_features sen1 sen2 begin set num_samples = length sen1 set corpus_sen1 = list co...
import os import json import pickle import numpy as np import scipy.sparse from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.linear_model import LogisticRegression from my_preprocess import preprocessing def get_features(sen1, sen2): num_samples = len(sen1) corpus_sen1 = [' '.join(item)...
Python
zaydzuhri_stack_edu_python
string Player functions, includes player progression comment Specialties # set FIGHTER = dictionary list tuple string name string Fighter tuple string exp_mult 1.0 tuple string description string The Fighter excels are armed combat and wears enemies down through a combination of ranged and melee moves set SWORDMASTER =...
"""Player functions, includes player progression""" ############### # Specialties # ############### FIGHTER = dict([ ("name", "Fighter"), ("exp_mult", 1.0), ("description", "The Fighter excels are armed combat and wears enemies down through a combination of ranged and melee moves") ]) SWORDMASTER = dict([ ("na...
Python
zaydzuhri_stack_edu_python
string 作者:王小糖 功能:模拟掷骰子,记录每次点数的次数 版本:2.0 日期:15/1/2019 2.0新增功能:掷两个骰子,记录结果 import random function roll_dice begin string 模拟掷骰子 :return: set roll = random integer 1 6 return roll end function function main begin string 主函数 :return: set total_times = 100000 comment 初始化列表[0,0,0,0,0,0] set ID_list = list range 2 13 set result...
""" 作者:王小糖 功能:模拟掷骰子,记录每次点数的次数 版本:2.0 日期:15/1/2019 2.0新增功能:掷两个骰子,记录结果 """ import random def roll_dice(): """ 模拟掷骰子 :return: """ roll=random.randint(1,6) return roll def main(): """ 主函数 :return: """ total_times=100000 # 初始化列表[0,0,0,0,0,0] ID_list=list(range(2,13)) result_list=[0]*11 result_dict=...
Python
zaydzuhri_stack_edu_python
function get_lbaas_agent_hosting_pool self pool **_params begin return get self pool_path + LOADBALANCER_AGENT % pool params=_params end function
def get_lbaas_agent_hosting_pool(self, pool, **_params): return self.get((self.pool_path + self.LOADBALANCER_AGENT) % pool, params=_params)
Python
nomic_cornstack_python_v1
comment This script is a library of variables and objects. All of the sprites' data and the sprite obj itself is contained here. from tkinter import * import random , sol_class set master = call Tk set my_can = call MainWindow master set Celestial_body = Celestial_body set Asteroid = Asteroid comment Solar distance val...
#This script is a library of variables and objects. All of the sprites' data and the sprite obj itself is contained here. from tkinter import * import random, sol_class master = Tk() my_can = sol_class.MainWindow(master) Celestial_body = sol_class.Celestial_body Asteroid = sol_class.Asteroid #Solar distance values f...
Python
zaydzuhri_stack_edu_python
comment arr = [3, 1, 2, 4, 3], n = 5 function solution arr begin set n = length arr comment slice 후, sum()에서 시간복잡도 N*N set minDif = absolute sum arr at slice 1 : : - sum arr at slice : 1 : for p in range 1 n begin if sum arr at slice p : : == sum arr at slice : p : begin set minDif = 0 break end set dif = absolute ...
# arr = [3, 1, 2, 4, 3], n = 5 def solution(arr): n = len(arr) minDif = abs(sum(arr[1:]) - sum(arr[:1])) # slice 후, sum()에서 시간복잡도 N*N for p in range(1, n): if sum(arr[p:]) == sum(arr[:p]): minDif = 0 break dif = abs(sum(arr[p:]) - sum(arr[:p])) if dif < min...
Python
zaydzuhri_stack_edu_python
function get_chembl_version url begin set p = url parse url set host = hostname set path_str = path set path_obj = call Path path_str set path_dir = parent set filename = name set ftp = call FTP host=host call login call cwd path_str set files = call nlst comment for each file, see if regex matches. if matches, return ...
def get_chembl_version(url) -> str: p = urlparse(url) host = p.hostname path_str = p.path path_obj = pathlib.Path(path_str) path_dir = path_obj.parent filename = path_obj.name ftp = ftplib.FTP(host=host) ftp.login() ftp.cwd(path_str) files = ftp.nlst() for f in files: # ...
Python
nomic_cornstack_python_v1
function draw_rectangle self roi color thickness=2 begin set top_left = call _format_point call Point roi at 0 roi at 1 set bottom_right = call _format_point call Point roi at 2 roi at 3 call rectangle img tuple tuple call bgra thickness=thickness end function
def draw_rectangle(self, roi, color, thickness=2): top_left = self._format_point(Point(roi[0], roi[1])) bottom_right = self._format_point(Point(roi[2], roi[3])) opencv.rectangle(self.img, top_left.tuple(), bottom_right.tuple(), color.bgra(), thickness=thickness)
Python
nomic_cornstack_python_v1
import sys set mapping_dict = dict string OTH 0 ; string REJ 1 ; string RSTO 2 ; string RSTOS0 3 ; string RSTR 4 ; string S0 5 ; string S1 6 ; string S2 7 ; string S3 8 ; string SF 9 ; string SH 10 ; string 1 1 ; string 0 0 ; string normal 1 ; string ? - 1 function replaceValue strl begin try begin return mapping_dict ...
import sys mapping_dict = { 'OTH': 0, 'REJ': 1, 'RSTO': 2, 'RSTOS0': 3, 'RSTR': 4, 'S0': 5, 'S1': 6, 'S2': 7, 'S3': 8, 'SF': 9, 'SH': 10, '1':1, '0':0, 'normal':1, '?':-1 } def replaceValue(strl): try: return mapping_dict[strl] except: ...
Python
zaydzuhri_stack_edu_python
import unittest from lexer import lexer from checkWithOriginal import lex class TestLexer extends TestCase begin function test_comment self begin assert equal call lexer string (☯‿├┬┴┬┴ Zignoruj mnie proszę list end function function test_empty self begin assert equal call lexer string list end function function test_s...
import unittest from lexer import lexer from checkWithOriginal import lex class TestLexer(unittest.TestCase): def test_comment(self): self.assertEqual(lexer("(☯‿├┬┴┬┴ Zignoruj mnie proszę"), []) def test_empty(self): self.assertEqual(lexer(""), []) def test_spaces(self): self.as...
Python
zaydzuhri_stack_edu_python
function rt n begin return n * n end function function lt n begin return call rt n - n - 1 end function function lb n begin return call rt n - 2 * n - 1 end function function rb n begin return call rt n - 3 * n - 1 end function function diagonal n begin set s = 1 for i in range 3 n + 2 2 begin set s = s + call rt i + c...
def rt(n): return n*n def lt(n): return rt(n) - (n-1) def lb(n): return rt(n) - 2*(n-1) def rb(n): return rt(n) - 3*(n-1) def diagonal(n): s = 1 for i in range(3, n+2, 2): s += (rt(i) + lt(i) +lb(i) + rb(i)) return s
Python
zaydzuhri_stack_edu_python
from newton_raphson import * function f x begin return x ^ 4 - 38.5 * x ^ 3 + 458 * x ^ 2 - 1701.5 * x + 741 end function function df x begin return 4 * x ^ 3 - 115.5 * x ^ 2 + 916 * x - 1701.5 end function set tuple x _ = call newton_raphson f df 12.0 print string x = x
from newton_raphson import * def f(x): return x**4 - 38.5*x**3 + 458*x**2 - 1701.5*x + 741 def df(x): return 4*x**3 - 115.5*x**2 + 916*x - 1701.5 x, _ = newton_raphson(f, df, 12.0) print("x = ", x)
Python
zaydzuhri_stack_edu_python
comment Quicksort is a divide and conquer algorithm. comment A large array is divided into smaller sub-arrays that are then recursively sorted. comment 1. Pick an element from the array that becomes the pivot. comment 2. Partition the array so that all elements with values less than the pivot come before the pivot, com...
# Quicksort is a divide and conquer algorithm. # A large array is divided into smaller sub-arrays that are then recursively sorted. # 1. Pick an element from the array that becomes the pivot. # 2. Partition the array so that all elements with values less than the pivot come before the pivot, # while all elements wit...
Python
zaydzuhri_stack_edu_python
function _clone self *args **kwargs begin string Overrides the QuerySet._clone method by adding the cloning of the VersionedQuerySet's query_time parameter :param kwargs: Same as the original QuerySet._clone params :return: Just as QuerySet._clone, this method returns a clone of the original object set clone = call _cl...
def _clone(self, *args, **kwargs): """ Overrides the QuerySet._clone method by adding the cloning of the VersionedQuerySet's query_time parameter :param kwargs: Same as the original QuerySet._clone params :return: Just as QuerySet._clone, this method returns a clone of the ...
Python
jtatman_500k
comment check if crop cat works import torch import torch.nn as nn import torch.nn.functional as F class UNet extends Module begin function __init__ self n_classes begin call __init__ comment Hint: Do not use ReLU in last convolutional set of up-path (128-64-64) for stability reasons! set downc1 = call downStep 1 64 se...
#check if crop cat works import torch import torch.nn as nn import torch.nn.functional as F class UNet(nn.Module): def __init__(self, n_classes): super(UNet, self).__init__() # Hint: Do not use ReLU in last convolutional set of up-path (128-64-64) for stability reasons! self.downc1 = downS...
Python
zaydzuhri_stack_edu_python