code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function get_source_url self obj begin if not location begin return none end comment Compute the path relative to the project root. set rel_path = call relpath absolute path path filename _project_root if not call issub rel_path begin debug string Ignored API object %s, path points outside of project root. name return ...
def get_source_url(self, obj: docspec.ApiObject) -> Optional[str]: if not obj.location: return None # Compute the path relative to the project root. rel_path = os.path.relpath(os.path.abspath(obj.location.filename), self._project_root) if not nr.fs.issub(rel_path): logger.debug('Ignored AP...
Python
nomic_cornstack_python_v1
while input != string done begin set userInput = string input string if userInput == string done begin print string The geometric mean is: round sum ^ 1 / lengthOfSequence 4 end else begin set userInput = integer userInput set sum = sum + userInput set lengthOfSequence = lengthOfSequence + 1 end end
while input != "done": userInput = str(input("")) if userInput=="done": print("The geometric mean is:", round(sum ** (1 / lengthOfSequence), (4))) else: userInput = int(userInput) sum += userInput lengthOfSequence += 1
Python
zaydzuhri_stack_edu_python
string Model and functions for Landlord Ratings project. from flask_sqlalchemy import SQLAlchemy set db = call SQLAlchemy class User extends Model begin set __tablename__ = string Users set user_id = call Column Integer primary_key=true autoincrement=true set fname = call Column call String 30 set lname = call Column c...
"""Model and functions for Landlord Ratings project.""" from flask_sqlalchemy import SQLAlchemy db = SQLAlchemy() class User(db.Model): __tablename__ = "Users" user_id = db.Column(db.Integer, primary_key=True, autoincrement=True) fname = db.Column(db.String(30)) lname = db.Column(db.String(30)) ...
Python
zaydzuhri_stack_edu_python
import os import csv set csvpath = string ./election_data.csv set mydict = dict set totvotes = 0 with open csvpath string r as polldata begin set csvreader = reader polldata next csvreader for row in csvreader begin set totvotes = totvotes + 1 if row at 2 in keys mydict begin set mydict at row at 2 = mydict at row at ...
import os import csv csvpath = './election_data.csv' mydict = {} totvotes = 0 with open(csvpath,'r') as polldata: csvreader = csv.reader(polldata) next(csvreader) for row in csvreader: totvotes = totvotes + 1 if row[2] in mydict.keys(): mydict[row[2]] = mydict[row[2]] + 1 ...
Python
zaydzuhri_stack_edu_python
function eye_change begin set expressions = list string wink string shut string sad string mad string default while true begin for i in expressions begin call set_expression i sleep 20 end end end function
def eye_change(): expressions = ['wink', 'shut', 'sad', 'mad', 'default'] while True: for i in expressions: EYES.set_expression(i) sleep(20)
Python
nomic_cornstack_python_v1
function get_direction self atom_ids=none begin if atom_ids is none begin set atom_ids = range length _atoms end else if is instance atom_ids int begin set atom_ids = tuple atom_ids end else if not is instance atom_ids tuple list tuple begin set atom_ids = list atom_ids end if length atom_ids == 0 begin raise call Valu...
def get_direction( self, atom_ids: typing.Optional[OneOrMany[int]] = None, ) -> np.ndarray: if atom_ids is None: atom_ids = range(len(self._atoms)) elif isinstance(atom_ids, int): atom_ids = (atom_ids,) elif not isinstance(atom_ids, (list, tuple)): ...
Python
nomic_cornstack_python_v1
function bounding_sequence n begin comment Step 1: Initialize comment a_0 set a = 1 / 2 comment Step 2: Compute the sequence a_k for k in range 1 n + 1 begin comment a_k = a_{k-1} + (1/n) * a_{k-1}^2 set a = a + 1 / n * a ^ 2 end comment Step 3: Calculate bounds set lower_bound = 1 - 1 / n set upper_bound = 1 comment S...
def bounding_sequence(n): # Step 1: Initialize a = 1/2 # a_0 # Step 2: Compute the sequence a_k for k in range(1, n + 1): a = a + (1/n) * a**2 # a_k = a_{k-1} + (1/n) * a_{k-1}^2 # Step 3: Calculate bounds lower_bound = 1 - 1/n upper_bound = 1 # Step 4: Return results re...
Python
dbands_pythonMath
string Chapter 2 Python Advanced(2) - Property(2) - Getter / Setter Keyword - @Property 프로퍼티 사용 장점 1. 파이써닉한 코드 2. 변수 제약 설정 3. Getter, Setter 효과 동등(코드 일관성 지킬 수 있다) - 캡슐화 - 유효성 검사 기능 추가 용이 - 대체 표현(속성 노출, 내부의 표현 은닉 가능) - 속성의 수명 및 메모리 관리 용이 -> 사용하지 않을 땐 클래스와 함께 소멸(클래스 내부에서 변수 선언, 사용하기에) - getter, setter 작동에 대해 설계된 여러 라이브러리...
""" Chapter 2 Python Advanced(2) - Property(2) - Getter / Setter Keyword - @Property 프로퍼티 사용 장점 1. 파이써닉한 코드 2. 변수 제약 설정 3. Getter, Setter 효과 동등(코드 일관성 지킬 수 있다) - 캡슐화 - 유효성 검사 기능 추가 용이 - 대체 표현(속성 노출, 내부의 표현 은닉 가능) - 속성의 수명 및 메모리 관리 용이 -> 사용하지 않을 땐 클래스와 함께 소멸(클래스 내부에서 변수 선언, 사용하기에) - getter, setter 작동에 대해 설계된 여러 라이브...
Python
zaydzuhri_stack_edu_python
function get_literature_recids_for_orcid orcid begin set orcid_object = string [{"schema": "ORCID", "value": " { orcid } "}] comment this first query is written in a way that can use the index on (json -> ids) try begin set author_rec_uuid = id end except NoResultFound begin warning string No profile is associated with...
def get_literature_recids_for_orcid(orcid): orcid_object = f'[{{"schema": "ORCID", "value": "{orcid}"}}]' # this first query is written in a way that can use the index on (json -> ids) try: author_rec_uuid = ( db.session.query(RecordMetadata.id) .filter( type...
Python
nomic_cornstack_python_v1
comment ! /usr/bin/env python3 comment Multiple_Halt_Find.py string Find how many halt (or undefined cells) all TMs in a file have. Prints out all TMs with more than one halt state and lists the number of TMs that have each number of halts. import math import sys from IO import IO function get_ttable string begin set s...
#! /usr/bin/env python3 # # Multiple_Halt_Find.py # """ Find how many halt (or undefined cells) all TMs in a file have. Prints out all TMs with more than one halt state and lists the number of TMs that have each number of halts. """ import math import sys from IO import IO def get_ttable(string): start = string....
Python
zaydzuhri_stack_edu_python
string This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. from todo.models import Event , User from django.core.exceptions import ValidationError from todo.forms import EventForm import unittest cl...
""" This file demonstrates writing tests using the unittest module. These will pass when you run "manage.py test". Replace this with more appropriate tests for your application. """ from todo.models import Event, User from django.core.exceptions import ValidationError from todo.forms import EventForm import unittest ...
Python
zaydzuhri_stack_edu_python
comment cook your dish here set T = integer input for _ in range T begin set tuple A B = map int split input set round_ = 1 while 1 > 0 begin if round_ % 2 != 0 begin if A >= round_ begin set A = A - round_ end else begin print string Bob break end end else if B >= round_ begin set B = B - round_ end else begin print s...
# cook your dish here T = int(input()) for _ in range(T): A, B = map(int, input().split()) round_ = 1 while 1 > 0: if round_ % 2 != 0: if A >= round_: A -= round_ else: print('Bob') break else: if B >= round...
Python
zaydzuhri_stack_edu_python
string print("你好") a = int (input("输入第一个数字:")) b = int (input ("输入第二个数字:")) c = a + b print ("a与b的和为:", c) print("布尔值的产生:", a > b) x = ["哈哈",45,"想念","知乎","什么",2,4] print(x[2]) x.append(345) print(x) x.insert(3,"魅力") print(x) qu = x.pop(5) print (qu) print (x.reverse()) xx = {"name":"李梅","age":23,"high":"167cm",3:"可惜"} ...
''' print("你好") a = int (input("输入第一个数字:")) b = int (input ("输入第二个数字:")) c = a + b print ("a与b的和为:", c) print("布尔值的产生:", a > b) x = ["哈哈",45,"想念","知乎","什么",2,4] print(x[2]) x.append(345) print(x) x.insert(3,"魅力") print(x) qu = x.pop(5) print (qu) print (x.reverse()) xx = {"name":"李梅","age":23,"high":"167cm",3:"可惜"} ...
Python
zaydzuhri_stack_edu_python
import numpy as np import scipy.spatial as spatial class AbstractTotalModel begin string This class is the base model for all the different interaction models implemented. All the common functions such as self.get_position or self.total_movement are written in this class. This class is defined as abstract because it ca...
import numpy as np import scipy.spatial as spatial class AbstractTotalModel: """ This class is the base model for all the different interaction models implemented. All the common functions such as self.get_position or self.total_movement are written in this class. This class is defined as abstract because...
Python
zaydzuhri_stack_edu_python
function instance_create instance nfs_preserve=false begin info string Instance | Provision | Instance ID - %s instance at string _id debug string Instance | Provision | Instance ID - %s | Instance - %s instance at string _id instance comment Setup path variables set instance_code_path_sid = format string {0}/{1}/{1} I...
def instance_create(instance, nfs_preserve=False): log.info('Instance | Provision | Instance ID - %s', instance['_id']) log.debug('Instance | Provision | Instance ID - %s | Instance - %s', instance['_id'], instance) # Setup path variables instance_code_path_sid = '{0}/{1}/{1}'.format(INSTANCE_ROOT, inst...
Python
nomic_cornstack_python_v1
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd set df = read csv string iris.csv print string **** Headers before dropping columns **** print head df 5 describe df info print string **** Headers after dropping columns **** drop df list string Sepal_Length inplace=true axis=1 print head df 5 s...
import seaborn as sns import matplotlib.pyplot as plt import pandas as pd df = pd.read_csv('iris.csv') print("**** Headers before dropping columns ****") print(df.head(5)) df.describe() df.info() print("**** Headers after dropping columns ****") df.drop(['Sepal_Length'], inplace=True, axis=1) print(df.head(5)) ''...
Python
zaydzuhri_stack_edu_python
function connect_database self *args **kwargs begin return call connect_database *args keyword kwargs end function
def connect_database(self, *args, **kwargs): return self._get_storage().connect_database(*args, **kwargs)
Python
nomic_cornstack_python_v1
import subprocess run list string sudo string shutdown string now
import subprocess subprocess.run(["sudo", "shutdown", "now"])
Python
flytech_python_25k
function get_output_folder self begin return join path root_output_folder base_fish_folder end function
def get_output_folder(self): return os.path.join(self.root_output_folder, self.base_fish_folder)
Python
nomic_cornstack_python_v1
import math set num = decimal input string Enter a number: comment checking if the number is negative if num < 0 begin print string The square root of the given number cannot be computed end else begin print string The square root of the given number is: square root num end
import math num = float(input("Enter a number: ")) # checking if the number is negative if num < 0: print("The square root of the given number cannot be computed") else: print("The square root of the given number is:",math.sqrt(num))
Python
jtatman_500k
function solution_problem_33 nums target begin comment nums.sort() print call best_solution nums target end function function best_solution nums target begin set tuple l r = tuple 0 length nums - 1 while l < r begin set m = l + r - l // 2 print m if nums at m >= nums at l and target < nums at l or target > nums at m or...
def solution_problem_33(nums, target): #nums.sort() print(best_solution(nums, target)) def best_solution(nums, target): l, r = 0, len(nums)-1 while l < r: m = l + (r-l)//2 print(m) if (nums[m] >= nums[l] and (target < nums[l] or target > nums[m])) or (nums[m] < nums[l] and targe...
Python
zaydzuhri_stack_edu_python
function add_quizmaster user_id begin with INSERTION_LOCK begin set curr = get query SESSION QuizMaster user_id if not curr begin set curr = call QuizMaster user_id add SESSION curr commit SESSION return string Successfully added { user_id } to database. end return string { user_id } Already in database. end end functi...
def add_quizmaster(user_id: int) -> str: with INSERTION_LOCK: curr = SESSION.query(QuizMaster).get(user_id) if not curr: curr = QuizMaster(user_id) SESSION.add(curr) SESSION.commit() return f"Successfully added {user_id} to database." return f...
Python
nomic_cornstack_python_v1
function export_escn out_file config begin import io_scene_godot call export out_file config end function
def export_escn(out_file, config): import io_scene_godot io_scene_godot.export(out_file, config)
Python
nomic_cornstack_python_v1
function eval self t endBehavior=string halt begin set tuple i u = call getSegment t endBehavior if i < 0 begin return milestones at 0 end else if i >= length milestones begin return milestones at - 1 end comment linear interpolate between milestones[i] and milestones[i+1] return call interpolate milestones at i milest...
def eval(self,t,endBehavior='halt'): i,u = self.getSegment(t,endBehavior) if i<0: return self.milestones[0] elif i>=len(self.milestones): return self.milestones[-1] #linear interpolate between milestones[i] and milestones[i+1] return self.interpolate(self.milestones[i],self.milestones[i+1],u)
Python
nomic_cornstack_python_v1
function create_nexus_file taxa_list out_filename method begin for i in range length taxa_list begin if length taxa_list at i != length taxa_list at i - 1 begin raise call ValueError string the sequences do not have equal length! end end set template = format string #NEXUS Begin data; dimensions ntax={num_taxa} nchar={...
def create_nexus_file(taxa_list,out_filename,method): for i in range(len(taxa_list)): if len(taxa_list[i]) != len(taxa_list[i-1]): raise ValueError("the sequences do not have equal length!") template ="""#NEXUS Begin data; dimensions ntax={num_taxa} nchar={seq_len}; format datatype=...
Python
nomic_cornstack_python_v1
function is_int obj begin return is instance obj tuple Integral integer end function
def is_int(obj): return isinstance(obj, (numbers.Integral, np.integer))
Python
nomic_cornstack_python_v1
import SocketServer import subprocess import random import string import os function random_string begin return join string random sample hexdigits 8 end function function shell_exec cmd begin return check output cmd shell=true end function class Server extends ForkingMixIn TCPServer begin set allow_reuse_address = tr...
import SocketServer import subprocess import random import string import os def random_string(): return ''.join(random.sample(string.hexdigits, 8)) def shell_exec(cmd): return subprocess.check_output(cmd, shell=True) class Server(SocketServer.ForkingMixIn, SocketServer.TCPServer): allow_reuse_a...
Python
zaydzuhri_stack_edu_python
comment write Fibonacci series up to n function fib n begin set tuple a b = tuple 1 1 while a < n begin print a end=string set tuple a b = tuple b a + b end print end function
def fib(n): # write Fibonacci series up to n a, b = 1, 1 while a < n: print(a, end=' ') a, b = b, a + b print()
Python
nomic_cornstack_python_v1
function test_lagged_checkpoint_completion chkFreqPatched looper txnPoolNodeSet sdk_wallet_client sdk_pool_handle begin set slow_node = txnPoolNodeSet at - 1 comment All the nodes in the pool normally orders all the 3PC-batches in a comment checkpoint except the last 3PC-batch. The last 3PC-batch in the comment checkpo...
def test_lagged_checkpoint_completion(chkFreqPatched, looper, txnPoolNodeSet, sdk_wallet_client, sdk_pool_handle): slow_node = txnPoolNodeSet[-1] # All the nodes in the pool normally orders all the 3PC-batches in a # checkpoint except the last 3PC-batch. The last 3PC-b...
Python
nomic_cornstack_python_v1
set r = decimal input set pi = 3.1416 set res = r ^ 2 * pi print format string {:.2f} res
r = float(input()) pi = 3.1416 res = (r**2)*pi print("{:.2f}".format(res))
Python
zaydzuhri_stack_edu_python
function notify_all self sender notice_type param begin set observers = filter call Q project=self ? call Q project__descendants=self if call is_authenticated begin set observers = call exclude user=sender end for observer in call distinct begin notify observer label=notice_type project=self param=param sender=sender e...
def notify_all(self, sender, notice_type, param): observers = Observer.objects.filter(models.Q(project=self)|models.Q(project__descendants=self)) if sender.is_authenticated(): observers = observers.exclude(user=sender) for observer in observers.distinct(): observer.notify...
Python
nomic_cornstack_python_v1
comment 导入模块 import functools comment 将字符串转换成10进制数据 comment print(int("10")) comment 有多个 二进制字符串转换成十进制 comment base的默认值是 10 print integer string 1010 base=2 print integer string 101010 base=2 comment 想 int("10100") 直接转 comment 重新定义函数 function intB num begin return integer num base=2 end function print call intB string 1...
# 导入模块 import functools # 将字符串转换成10进制数据 # print(int("10")) # 有多个 二进制字符串转换成十进制 # base的默认值是 10 print(int("1010",base=2)) print(int("101010",base=2)) # 想 int("10100") 直接转 # 重新定义函数 def intB(num): return int(num,base=2) print(intB("1010")) # 偏函数 # 参数1: 需要转变的函数名,参数2:需要设置的默认参数 int2 = functools.partial(int,base=2) ...
Python
zaydzuhri_stack_edu_python
function svg_pdf self svg_list begin print string Converting, please wait... for svg in svg_list begin set pdf_abspath = split svg string \ at - 1 set pdf_name = split pdf_abspath string . at 0 print format string Converting file: {} pdf_abspath set drawing = call svg2rlg _in + pdf_abspath call drawToFile drawing _out ...
def svg_pdf(self, svg_list): print('\nConverting, please wait...\n') for svg in svg_list: pdf_abspath = svg.split('\\')[-1] pdf_name = pdf_abspath.split('.')[0] print('Converting file: {}'.format(pdf_abspath)) drawing = svg2rlg(self._in + pdf_abspath) ...
Python
nomic_cornstack_python_v1
from __future__ import unicode_literals import pygame , sys from pygame.locals import QUIT import time import threading from config_util import Config from weather import Weather import os class Clock begin function __init__ self screen begin set _screen = screen set _black = copy _screen set running = false call load_...
from __future__ import unicode_literals import pygame,sys from pygame.locals import QUIT import time import threading from config_util import Config from weather import Weather import os class Clock: def __init__(self,screen): self._screen = screen self._black=self._screen.copy() self.runn...
Python
zaydzuhri_stack_edu_python
from nodes import Coach , Student string The implementation of limited_infection. Essentially, we pass in a root coach and a limit. If there are more nodes than the limit, then we can't infect this node as some nodes would end up not infected. In this case, we return False to signify that this node is unable to infect....
from nodes import Coach, Student """ The implementation of limited_infection. Essentially, we pass in a root coach and a limit. If there are more nodes than the limit, then we can't infect this node as some nodes would end up not infected. In this case, we return False to signify that this node is unable to infect. I...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Wed Feb 8 21:15:49 2012 @author: anatoliy import time import numpy as np import cv import cv2 import cvutils from cvutils import array2point_list from crowdmisc import Properties set SmallTextFont = none set LargeTextFont = none function drawText image text color rowNumbe...
# -*- coding: utf-8 -*- """ Created on Wed Feb 8 21:15:49 2012 @author: anatoliy """ import time import numpy as np import cv import cv2 import cvutils from cvutils import array2point_list from crowdmisc import Properties SmallTextFont = None LargeTextFont = None def drawText(image, text, color, rowNumber = 0): ...
Python
zaydzuhri_stack_edu_python
function path_globs_for_spec self spec glob_match_error_behavior begin return call _generate_path_globs tuple spec *self.ignores glob_match_error_behavior end function
def path_globs_for_spec( self, spec: Union[FilesystemLiteralSpec, FilesystemGlobSpec], glob_match_error_behavior: GlobMatchErrorBehavior, ) -> PathGlobs: return self._generate_path_globs((spec, *self.ignores), glob_match_error_behavior)
Python
nomic_cornstack_python_v1
class Pulse begin function __init__ self amplitude=none peak_time=none arrival_time=none rise_time=none charge=none begin set amplitude = amplitude set peak_time = peak_time set arrival_time = arrival_time set rise_time = rise_time set charge = charge end function function set_amplitude self a begin set amplitude = a e...
class Pulse: def __init__(self, amplitude=None, peak_time=None, arrival_time=None, rise_time=None, charge=None): self.amplitude = amplitude self.peak_time = peak_time self.arrival_time = arrival_time self.rise_time = rise_time self.charge = charge def set_amplitude(self, a): self.amplitude = a def se...
Python
zaydzuhri_stack_edu_python
function log_archive_method_finished result begin comment Prettify CMD string and make it safe to copy-paste by quoting arguments set quoted_cmd = join string generator expression if expression string in arg then format string "{}" arg else arg for arg in cmd if status == string failed begin if __name__ == string Tim...
def log_archive_method_finished(result: "ArchiveResult"): # Prettify CMD string and make it safe to copy-paste by quoting arguments quoted_cmd = ' '.join( '"{}"'.format(arg) if ' ' in arg else arg for arg in result.cmd ) if result.status == 'failed': if result.output.__class__._...
Python
nomic_cornstack_python_v1
import random function get_digits_sum num begin return sum generator expression integer digit for digit in string num end function function generate_array begin set array = list 1 3 5 7 9 shuffle random array comment Remove duplicate elements set array = list set array comment Sort array based on the sum of each elemen...
import random def get_digits_sum(num): return sum(int(digit) for digit in str(num)) def generate_array(): array = [1, 3, 5, 7, 9] random.shuffle(array) # Remove duplicate elements array = list(set(array)) # Sort array based on the sum of each element's individual digits array.sor...
Python
jtatman_500k
import sys import re set inputFile = open string 494.in string r set outputFile = open string 494.out string w set lines = join string read lines stdin set text = read lines inputFile set numWords = list for line in text begin comment re.sub(r'[ ]+',' ', line) set line = sub string [^a-zA-Z] string line set line = s...
import sys import re inputFile = open("494.in","r") outputFile = open("494.out","w") lines = "".join(sys.stdin.readlines()) text = inputFile.readlines() numWords = [] for line in text: # re.sub(r'[ ]+',' ', line) line = re.sub(r'[^a-zA-Z]', ' ', line) line = re.sub(r'\s+',' ', line) if (re.match(r'\...
Python
zaydzuhri_stack_edu_python
function pc_output_buffers_full_var self *args begin return call atsc_pad_sptr_pc_output_buffers_full_var self *args end function
def pc_output_buffers_full_var(self, *args): return _atsc_swig.atsc_pad_sptr_pc_output_buffers_full_var(self, *args)
Python
nomic_cornstack_python_v1
function dimension self begin return max _l1 + 1 call ZZ 0 end function
def dimension(self): return max(self._l1+1, ZZ(0))
Python
nomic_cornstack_python_v1
function insert_from_list tablename ins_fields ins_values begin set sql_query = string %s %s; % tuple call __insert_clause tablename ins_fields call __values_clause_2 ins_values return sql_query end function
def insert_from_list(tablename, ins_fields, ins_values): sql_query = "%s %s;" % (__insert_clause(tablename, ins_fields), __values_clause_2(ins_values)) return sql_query
Python
nomic_cornstack_python_v1
comment -*-coding: utf-8 -*- import os , sys import time import curses function desact_inter princip_window begin clear princip_window call addstr 4 20 string Desactivation de l'interface Ethernet : call color_pair 1 call addstr 6 0 string ============================================================================ cal...
# -*-coding: utf-8 -*- import os, sys import time import curses def desact_inter(princip_window): princip_window.clear() princip_window.addstr(4,20,"Desactivation de l'interface Ethernet : ",curses.color_pair(1)) princip_window.addstr(6,0,"==================================================================...
Python
zaydzuhri_stack_edu_python
function test_conservation show=false CFL=0.5 Nlist=10 ^ array range 2 5 1 **kwargs begin print print string Testing Conservation print kwargs set diff_mass_list = list set diff_final_list = list comment exclude these parameters from file names set exclude_params = list string A0 string beta string irregular string i...
def test_conservation(show=False,CFL=0.5,Nlist=10**np.arange(2,5,1),**kwargs): print() print('Testing Conservation') print(kwargs) diff_mass_list = [] diff_final_list = [] # exclude these parameters from file names exclude_params = ['A0','beta','irregular','ivp_method','source','type'...
Python
nomic_cornstack_python_v1
function traverse self traverser **kwargs begin set rrt = call traverse traverser keyword kwargs return call unary_operation self rrt keyword kwargs end function
def traverse(self, traverser, **kwargs): rrt = self.right.traverse(traverser, **kwargs) return traverser.unary_operation(self, rrt, **kwargs)
Python
nomic_cornstack_python_v1
function import_sampled_points self annotation_set import_data begin from projects.models import PointAnnotation set images = all set points_to_bulk_save = list comment iterate through the images and create points for image in images begin for annotation in import_data at string id at image_name begin set point_annota...
def import_sampled_points(self, annotation_set, import_data): from projects.models import PointAnnotation images = annotation_set.images.all() points_to_bulk_save = [] # iterate through the images and create points for image in images: for annotation in import_data...
Python
nomic_cornstack_python_v1
function addOne self i j=none begin set __counter = __counter + 1 if j == none begin set j = i end comment Atualizar as visitações de cada estado if j not in __visiting begin set __visiting at j = 1 end else if j in __visiting begin set __visiting at j = __visiting at j + 1 end if i not in __dtmc begin set __dtmc at i ...
def addOne(self, i, j=None): self.__counter += 1 if j == None: j = i # Atualizar as visitações de cada estado if j not in self.__visiting: self.__visiting[j] = 1 elif j in self.__visiting: self.__visiti...
Python
nomic_cornstack_python_v1
function getTransactionsFromSender self sender begin set transactions = list for transaction in transactionList begin if transaction at string sender == sender begin append transactions transaction end end return transactions end function
def getTransactionsFromSender(self, sender): transactions = [] for transaction in self.transactionList: if(transaction["sender"] == sender): transactions.append(transaction) return transactions
Python
nomic_cornstack_python_v1
function insert_date self datetime year month day date_str begin set params = tuple datetime year month day date_str execute cursor string INSERT INTO date VALUES (NULL, ?, ?, ?, ?, ?) params set date_id = lastrowid commit connection return date_id end function
def insert_date(self, datetime, year, month, day, date_str): params = (datetime, year, month, day, date_str) self.cursor.execute("INSERT INTO date VALUES (NULL, ?, ?, ?, ?, ?)", params) date_id = self.cursor.lastrowid self.connection.commit() return date_id
Python
nomic_cornstack_python_v1
function maximum_pdu_size self value begin comment pylint: disable=attribute-defined-outside-init comment Bounds and type checking of the received maximum length of the comment variable field of P-DATA-TF PDUs (in bytes) comment * Must be numerical, greater than or equal to 0 (0 indicates comment no maximum length (PS3...
def maximum_pdu_size(self, value): # pylint: disable=attribute-defined-outside-init # Bounds and type checking of the received maximum length of the # variable field of P-DATA-TF PDUs (in bytes) # * Must be numerical, greater than or equal to 0 (0 indicates # no maximum...
Python
nomic_cornstack_python_v1
function create_cluster_subnet_group ClusterSubnetGroupName=none Description=none SubnetIds=none Tags=none begin pass end function
def create_cluster_subnet_group(ClusterSubnetGroupName=None, Description=None, SubnetIds=None, Tags=None): pass
Python
nomic_cornstack_python_v1
function removeDuplicates arr begin set newArr = list for i in arr begin if i not in newArr begin append newArr i end end return newArr end function set arr = list 1 3 5 4 6 3 5 4 set result = call removeDuplicates arr print result
def removeDuplicates(arr): newArr = [] for i in arr: if i not in newArr: newArr.append(i) return newArr arr = [1, 3, 5, 4, 6, 3, 5, 4] result = removeDuplicates(arr) print(result)
Python
iamtarun_python_18k_alpaca
function __init__ self x k begin call __init__ x k end function
def __init__(self, x: dict, k: int): super().__init__(x, k)
Python
nomic_cornstack_python_v1
function sub_mean_ch X begin set temp_images = list set X = as type X float32 for i in X begin set i at tuple slice : : slice : : 0 = i at tuple slice : : slice : : 0 - 103.939 set i at tuple slice : : slice : : 1 = i at tuple slice : : slice : : 1 - 116.779 set i at tuple slice : : slice :...
def sub_mean_ch(X): temp_images=[] X=X.astype(np.float32) for i in X: i[:,:,0] -= 103.939 i[:,:,1] -= 116.779 i[:,:,2] -= 123.68 i = i.transpose((2,0,1)) temp_images.append(i) return np.array(temp_images).astype(np.float32)
Python
nomic_cornstack_python_v1
function _check_is_share_busy self share begin if is_busy begin set msg = call _ string Share %(share_id)s is busy as part of an active task: %(task)s. % dict string share_id share at string id ; string task share at string task_state raise call ShareBusyException reason=msg end end function
def _check_is_share_busy(self, share): if share.is_busy: msg = _("Share %(share_id)s is busy as part of an active " "task: %(task)s.") % { 'share_id': share['id'], 'task': share['task_state'] } raise exception.ShareBusyExcep...
Python
nomic_cornstack_python_v1
function find_first_and_last lst_or_tpl begin set res = list comprehension lst_or_tpl at i for i in tuple 0 - 1 return tuple res end function function find_first_and_last_v2 lst_or_tpl begin return tuple lst_or_tpl at 0 lst_or_tpl at - 1 end function print call find_first_and_last list 0 1 2 3 4 5 print call find_first...
def find_first_and_last(lst_or_tpl): res = [lst_or_tpl[i] for i in (0, -1)] return tuple(res) def find_first_and_last_v2(lst_or_tpl): return (lst_or_tpl[0],lst_or_tpl[-1]) print(find_first_and_last([0, 1, 2, 3, 4, 5])) print(find_first_and_last((0, 1, 2, 3, 4, 5, 6, 7))) print(find_first_and_last(range(0,...
Python
zaydzuhri_stack_edu_python
async function tome self ctx name=none begin set num_visible = await call num_visible ctx if not num_visible begin return await call send string You have no tomes. You can make one at <https://avrae.io/dashboard/homebrew/spells>! end if name is none begin set tome = await call from_ctx ctx end else begin try begin set ...
async def tome(self, ctx, *, name=None): num_visible = await Tome.num_visible(ctx) if not num_visible: return await ctx.send( "You have no tomes. You can make one at <https://avrae.io/dashboard/homebrew/spells>!") if name is None: tome = await Tome.from_...
Python
nomic_cornstack_python_v1
function evaluate_classifier input_ labels per_example_weights=none topk=1 name=PROVIDED phase=train begin string Calculates the total ratio of correct predictions across all examples seen. In test and infer mode, this creates variables in the graph collection pt.GraphKeys.TEST_VARIABLES and does not add them to tf.Gra...
def evaluate_classifier(input_, labels, per_example_weights=None, topk=1, name=PROVIDED, phase=Phase.train): """Calculates the total ratio of correct predictions across all examples seen. In test and infer mode, this creates variables in the graph collection pt.GraphKeys.TEST_VARIABLES an...
Python
jtatman_500k
function dev_view begin call _custom_for_suffix string dev end function
def dev_view(): _custom_for_suffix('dev')
Python
nomic_cornstack_python_v1
function test1_to_json_string self begin set _Base__nb_objects = 0 set rect = call Rectangle 5 4 3 6 set new_dict = call to_dictionary set jstrg = call to_json_string list new_dict assert equal new_dict dict string y 6 ; string height 4 ; string width 5 ; string x 3 ; string id 1 assert equal type new_dict dict assert ...
def test1_to_json_string(self): Base._Base__nb_objects = 0 rect = Rectangle(5, 4, 3, 6) new_dict = rect.to_dictionary() jstrg = Base.to_json_string([new_dict]) self.assertEqual(new_dict, {'y': 6, 'height': 4, 'width': 5, 'x': 3, 'id': 1}) ...
Python
nomic_cornstack_python_v1
class ParkingSystem begin function __init__ self big medium small begin set A = list big medium small end function function addCar self carType begin set A at carType - 1 = A at carType - 1 - 1 return A at carType - 1 >= 0 end function end class
class ParkingSystem: def __init__(self, big, medium, small): self.A = [big, medium, small] def addCar(self, carType): self.A[carType - 1] -= 1 return self.A[carType - 1] >= 0
Python
zaydzuhri_stack_edu_python
function extract_fields media_items existing_log=false begin set data = list for img_res in media_items begin comment no login is required to view, gonna use it to get the actual size of the image if existing_log begin set img_url = img_res at string baseUrl set tuple img_size_human size_bytes = call get_img_size img_...
def extract_fields(media_items, existing_log=False): data = [] for img_res in media_items: # no login is required to view, gonna use it to get the actual size of the image if existing_log: img_url = img_res['baseUrl'] img_size_human, size_bytes = get_img_size(img_url)...
Python
nomic_cornstack_python_v1
import numpy as np import sys function atom_type x begin if x == string C begin return string C end if x == string A begin return string C end if x == string N begin return string N end if x == string O begin return string O end if x == string P begin return string P end if x == string S begin return string S end if x ...
import numpy as np import sys def atom_type(x): if x == "C" : return " C " if x == "A" : return " C " if x == "N" : return " N " if x == "O" : return " O " if x == "P" : return " P " if x == "S" : return " S " if x == "H" : return " H " if x == "F" : return " F " if x == "I"...
Python
zaydzuhri_stack_edu_python
try begin new_list at 5 end except IndexError begin print string The value is not in range end if 1 in new_list begin print true end for n in new_list begin if n == 1 begin print true break end end comment returns length of the list length new_list comment adds 4 to the list append new_list 4 comment adds a list of 5,6...
try: new_list[5] except IndexError: print("The value is not in range") if 1 in new_list: print(True) for n in new_list: if n == 1: print(True) break len(new_list) # returns length of the list new_list.append(4) # adds 4 to the list new_list.extend([5,6]) # adds a list of 5,6 to the lis...
Python
zaydzuhri_stack_edu_python
comment School desks comment A school decided to replace the desks in three classrooms. comment Each desk sits two students. Given the number of students in each class, comment print the smallest possible number of desks that can be purchased. comment Print number of desks needed if A class has 21 students, B class has...
# School desks # A school decided to replace the desks in three classrooms. # Each desk sits two students. Given the number of students in each class, # print the smallest possible number of desks that can be purchased. # Print number of desks needed if A class has 21 students, B class has 22 students, C class has 19 ...
Python
zaydzuhri_stack_edu_python
from libraryapp.DAO.CategoriesTree import CategoriesTree from models import Book , Category class CategoryDAO begin function get_category self begin set main_categories = call get_main_categories set categories = list for main_category in main_categories begin set subcategories = call get_subcategories main_category s...
from libraryapp.DAO.CategoriesTree import CategoriesTree from ..models import Book, Category class CategoryDAO: def get_category(self): main_categories = self.get_main_categories() categories = [] for main_category in main_categories: subcategories = self.get_subcategories(main...
Python
zaydzuhri_stack_edu_python
import unittest from solution.inversion_counter import InversionCounter class InversionCounterTestCase extends TestCase begin function test_sort_and_count_empty_input self begin assert equal call sort_and_count list 0 end function function test_sort_and_count_one_element self begin assert equal call sort_and_count list...
import unittest from solution.inversion_counter import InversionCounter class InversionCounterTestCase(unittest.TestCase): def test_sort_and_count_empty_input(self): self.assertEqual(InversionCounter.sort_and_count([]), 0) def test_sort_and_count_one_element(self): self.assertEqual(InversionC...
Python
zaydzuhri_stack_edu_python
from collections import deque import graph as g set graph = call Graph set graph = call populate_graph graph example_graph2 function bf_traversal tree begin string Breadth-first tree traaversal with loops set queue = deque set queue = queue + list root set traversed = list set contents = list while queue begin set cu...
from collections import deque import graph as g graph = g.Graph() graph = g.populate_graph(graph, g.example_graph2) def bf_traversal(tree): '''Breadth-first tree traaversal with loops''' queue = deque() queue += [tree.root] traversed = [] contents = [] while queue: curre...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment encoding=utf8 comment Function: Perform all the procudures in order. comment Procedure: 1.Extract main text from mails and create word tokens; comment 2.Get the stem of words and remove stop words; comment 3.Word Feature Selection by gini index and frequency comment 4.Compute TF-IDF...
#!/usr/bin/env python #encoding=utf8 ## Function: Perform all the procudures in order. ## Procedure: 1.Extract main text from mails and create word tokens; ## 2.Get the stem of words and remove stop words; ## 3.Word Feature Selection by gini index and frequency ## 4.Compute TF-IDF and ...
Python
zaydzuhri_stack_edu_python
function evnod a begin if a % 2 == 0 begin print format string {0} is Even a end else begin print format string {0} is Odd a end end function call evnod 3 call evnod 6
def evnod(a): if (a% 2) == 0: print("{0} is Even".format(a)) else: print("{0} is Odd".format(a)) evnod(3) evnod(6)
Python
zaydzuhri_stack_edu_python
function unzip_or_move_file self file_name to_dir do_unzip=true begin if call file_extension file_name == string zip and do_unzip is true begin comment Unzip if logger begin info string going to unzip + file_name + string to + to_dir end set myzip = zip file file_name string r extract all myzip to_dir end else if call ...
def unzip_or_move_file(self, file_name, to_dir, do_unzip=True): if self.file_extension(file_name) == 'zip' and do_unzip is True: # Unzip if self.logger: self.logger.info("going to unzip " + file_name + " to " + to_dir) myzip = zipfile.ZipFile(file_name, 'r') ...
Python
nomic_cornstack_python_v1
function list_staged cache_path compare path_length begin set db = call get_cache cache_path set records = call list_staged_records if not records begin call secho string No Staged Notebooks fg=string blue end call echo call tabulate_stage_records records path_length=path_length cache=db end function
def list_staged(cache_path, compare, path_length): db = get_cache(cache_path) records = db.list_staged_records() if not records: click.secho("No Staged Notebooks", fg="blue") click.echo(tabulate_stage_records(records, path_length=path_length, cache=db))
Python
nomic_cornstack_python_v1
function extract_labels filename num_images begin print string Extracting filename with open filename as bytestream begin set buf = read bytestream 1 * num_images set labels = as type call frombuffer buf dtype=uint8 int64 end return labels end function
def extract_labels(filename, num_images): print('Extracting', filename) with open(filename) as bytestream: buf = bytestream.read(1 * num_images) labels = numpy.frombuffer(buf, dtype=numpy.uint8).astype(numpy.int64) return labels
Python
nomic_cornstack_python_v1
function clone_user src_val dest_val base_user new_user_list options begin set dump_sql = get options string dump false set overwrite = get options string overwrite false set verbosity = get options string verbosity false set quiet = get options string quiet false set global_privs = get options string global_privs fals...
def clone_user(src_val, dest_val, base_user, new_user_list, options): dump_sql = options.get("dump", False) overwrite = options.get("overwrite", False) verbosity = options.get("verbosity", False) quiet = options.get("quiet", False) global_privs = options.get("global_privs", False) # Don't requi...
Python
nomic_cornstack_python_v1
import sys import pytest insert path 0 string . from day import Day from day18 import * decorator fixture scope=string function function example begin set day = call Day 18 set data = string 2,2,2 1,2,2 3,2,2 2,1,2 2,3,2 2,2,1 2,2,3 2,2,4 2,2,6 1,2,5 3,2,5 2,1,5 2,3,5 load day data return day end function decorator fix...
import sys import pytest sys.path.insert(0, ".") from day import Day from day18 import * @pytest.fixture(scope="function") def example(): day = Day(18) data = """2,2,2 1,2,2 3,2,2 2,1,2 2,3,2 2,2,1 2,2,3 2,2,4 2,2,6 1,2,5 3,2,5 2,1,5 2,3,5""" day.load(data) return day @pytest.fixture(scope="function...
Python
zaydzuhri_stack_edu_python
function resource_id self begin return get pulumi self string resource_id end function
def resource_id(self) -> Optional[pulumi.Input[str]]: return pulumi.get(self, "resource_id")
Python
nomic_cornstack_python_v1
comment 기존 코딩테스트와 같이 표준 라이브러리(standard library)의 사용은 가능합니다. 단, 그 중 CLI를 구현하기 위한 목적으로 만들어진 표준 라이브러리의 사용은 금지합니다. ex) 사용금지: python의 argparse https://docs.python.org/ko/3/library/argparse.html comment flag값에 대한 처리해주는 함수 function flag_solution flag_rule argument begin if flag_rule == string STRING begin for arg in argument ...
# 기존 코딩테스트와 같이 표준 라이브러리(standard library)의 사용은 가능합니다. 단, 그 중 CLI를 구현하기 위한 목적으로 만들어진 표준 라이브러리의 사용은 금지합니다. ex) 사용금지: python의 argparse https://docs.python.org/ko/3/library/argparse.html def flag_solution(flag_rule, argument): # flag값에 대한 처리해주는 함수 if flag_rule == 'STRING': for arg in argument: if 6...
Python
zaydzuhri_stack_edu_python
set number = integer input string Введите число set numberProg = number + 2 print numberProg
number = int(input("Введите число ")) numberProg = number + 2 print(numberProg)
Python
zaydzuhri_stack_edu_python
function test_analysis_runtime_opts self begin set opts = dict string opt1 false ; string opt2 false set run_opts = dict string opt1 true ; string opt2 true ; string opt3 true set analysis = call FakeAnalysis call set_options keyword opts run call ExperimentData keyword run_opts comment add also the default 'figure_nam...
def test_analysis_runtime_opts(self): opts = {"opt1": False, "opt2": False} run_opts = {"opt1": True, "opt2": True, "opt3": True} analysis = FakeAnalysis() analysis.set_options(**opts) analysis.run(ExperimentData(), **run_opts) # add also the default 'figure_names' option...
Python
nomic_cornstack_python_v1
function _distance_last_evaluations self begin if shape at 0 < 2 begin comment less than 2 evaluations return inf end return square root sum X at tuple - 1 slice : : - X at tuple - 2 slice : : ^ 2 end function
def _distance_last_evaluations(self): if self.X.shape[0] < 2: # less than 2 evaluations return np.inf return np.sqrt(np.sum((self.X[-1, :] - self.X[-2, :]) ** 2))
Python
nomic_cornstack_python_v1
import numpy as np from sknn.mlp import Regressor , Layer import sklearn.preprocessing as pre from sklearn.datasets import samples_generator comment get working directory import os print get current directory + string set workingDir = get current directory comment add a path to the code (for the dependencies of import)...
import numpy as np from sknn.mlp import Regressor, Layer import sklearn.preprocessing as pre from sklearn.datasets import samples_generator #get working directory import os print(os.getcwd() + "\n") workingDir = os.getcwd() #add a path to the code (for the dependencies of import) codeDir = workingDir + '/code' import...
Python
zaydzuhri_stack_edu_python
import math set N = integer input set count = 0 for i in range 1 N + 1 begin set d = 2 set k = i while d * d <= k begin while k % d * d == 0 begin set k = k / d * d end set d = d + 1 end set d = 1 while k * d * d <= N begin set count = count + 1 set d = d + 1 end end print count
import math N = int(input()) count = 0 for i in range(1, N+1): d = 2 k = i while d*d <= k: while k%(d*d) == 0: k /= d*d d += 1 d = 1 while k*d*d <= N: count += 1 d += 1 print(count)
Python
zaydzuhri_stack_edu_python
function patch self pattern handler begin return call route PATCH pattern handler end function
def patch(self, pattern, handler): return self.route(PATCH, pattern, handler)
Python
nomic_cornstack_python_v1
function to_str self begin return call pformat call to_dict end function
def to_str(self): return pprint.pformat(self.to_dict())
Python
nomic_cornstack_python_v1
import sys set original = argv at 1 set trans = argv at 2 set f = open original set cab = read f close f set change = replace cab string string * 8 print change set f = open trans string w write f change close f
import sys original = sys.argv[1] trans = sys.argv[2] f = open(original) cab = f.read() f.close() change = cab.replace("\t", " "*8) print(change) f = open(trans, 'w') f.write(change) f.close()
Python
zaydzuhri_stack_edu_python
function time_covariance self var_str0 var_str1 date0=none date1=none begin set var0 = dataset at var_str0 set var1 = dataset at var_str1 set var0 = rename string var1 set var1 = rename string var2 set var0 = call data_array_time_slice var0 date0 date1 set var1 = call data_array_time_slice var1 date0 date1 set pdvar = ...
def time_covariance(self, var_str0, var_str1, date0=None, date1=None): var0 = self.dataset[var_str0] var1 = self.dataset[var_str1] var0 = var0.rename("var1") var1 = var1.rename("var2") var0 = general_utils.data_array_time_slice(var0, date0, date1) var1 = general_utils.dat...
Python
nomic_cornstack_python_v1
function dataset_uuid self begin return get pulumi self string dataset_uuid end function
def dataset_uuid(self) -> Optional[str]: return pulumi.get(self, "dataset_uuid")
Python
nomic_cornstack_python_v1
from tkinter import * set root = call Tk title root string This is just a title set frame = call LabelFrame root text=string Frame name padx=5 pady=5 call pack padx=10 pady=10 set button = call Button frame text=string Click here padx=10 pady=10 grid row=0 column=0 call mainloop
from tkinter import * root = Tk() root.title("This is just a title") frame = LabelFrame(root,text="Frame name",padx=5,pady=5) frame.pack(padx=10,pady=10) button = Button(frame, text="Click here", padx=10,pady=10) button.grid(row=0,column=0) root.mainloop()
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- from subprocess import Popen , PIPE , STDOUT try begin comment py3k from subprocess import DEVNULL end except ImportError begin import os set DEVNULL = open devnull string wb end set text = string René Descartes set p = popen list string espeak string -b strin...
#!/usr/bin/env python # -*- coding: utf-8 -*- from subprocess import Popen, PIPE, STDOUT try: from subprocess import DEVNULL # py3k except ImportError: import os DEVNULL = open(os.devnull, 'wb') text = u"René Descartes" p = Popen(['espeak', '-b', '1'], stdin=PIPE, stdout=DEVNULL, stderr=STDOUT) p.communi...
Python
jtatman_500k
class Checkout begin function __init__ self begin set item = list set price = list end function function add_item self item price begin if type price != int begin raise call ValueError string Invalid Price end append item item append price price end function function cal_total self begin set total = 0 for i in price ...
class Checkout: def __init__(self): self.item = [] self.price = [] def add_item(self, item, price): if type(price) != int: raise ValueError('Invalid Price') self.item.append(item) self.price.append(price) def cal_total(self): total = 0 for...
Python
zaydzuhri_stack_edu_python
class Portfolio extends object begin string Managing portfolio data function __init__ self data=none begin set _data = data end function decorator property function data self begin return _data end function function get_page_content self portfolio_item page begin return data at integer portfolio_item - 1 at integer pag...
class Portfolio(object): """Managing portfolio data""" def __init__(self, data=None): self._data = data @property def data(self): return self._data def get_page_content(self, portfolio_item, page): return self.data[int(portfolio_item)-1][int(page)-1] def is_last_page...
Python
zaydzuhri_stack_edu_python
function httpquery url=string data=none headers=dict timeout=60 begin try begin set req = call Request url data=data headers=headers set r = url open req timeout=timeout end except HTTPError as e begin set r = e end except Exception as e begin return dict string status - 1 ; string error string e end set headers = di...
def httpquery(url = "", data = None, headers = {}, timeout = 60): try: req = Request(url, data = data, headers = headers) r = urlopen(req, timeout = timeout) except HTTPError as e: r = e except Exception as e: return { "status": -1...
Python
nomic_cornstack_python_v1
function test_load_labware decoy mock_engine_client subject begin call then_return list call EngineLabwareLoadParams string hello string world 654 call then_return tuple string some_namespace 9001 call then_return string some_labware call then_return call LoadLabwareResult labwareId=string abc123 definition=call constr...
def test_load_labware( decoy: Decoy, mock_engine_client: EngineClient, subject: ProtocolCore, ) -> None: decoy.when( mock_engine_client.state.labware.find_custom_labware_load_params() ).then_return([EngineLabwareLoadParams("hello", "world", 654)]) decoy.when( load_labware_params...
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt comment import necessary Python packages import os set data = call genfromtxt string 2in_xor.txt delimiter=string set shape = call shape data set height = shape at 1 set width = shape at 0 set inputs = zeros tuple width 2 set outputs_training = zeros tuple width 1 for ...
import numpy as np import matplotlib.pyplot as plt # import necessary Python packages import os data=np.genfromtxt("2in_xor.txt",delimiter="") shape = np.shape(data) height = shape[1] width = shape[0] inputs = np.zeros((width,2)) outputs_training = np.zeros((width,1)) for i in range(width): ...
Python
zaydzuhri_stack_edu_python
function accept_scan begin try begin set r = call get_json set results = call run_scan cidr=r at string cidr arguments=r at string arguments end except KeyError as e begin return call internal_error string KeyError: { e } end except Exception as e begin return call internal_error string Unknown Exception: { e } end ret...
def accept_scan(): try: r = request.get_json() results = run_scan(cidr=r['cidr'], arguments=r['arguments']) except KeyError as e: return internal_error(f"KeyError: {e}") except Exception as e: return internal_error(f"Unknown Exception: {e}") return results
Python
nomic_cornstack_python_v1
string 异常的传递 function func_a begin print string Func a run ... call func_b end function function func_b begin print string Func b run ... try begin call func_c end except Exception begin print string 你的除数为0了 end end function function func_c begin print string Func c run ... comment try: comment print(1 / 0) comment exc...
''' 异常的传递 ''' def func_a(): print('Func a run ...') func_b() def func_b(): print("Func b run ...") try: func_c() except Exception: print('你的除数为0了') def func_c(): print('Func c run ...') # try: # print(1 / 0) # except Exception: # ...
Python
zaydzuhri_stack_edu_python
function __init__ self begin set type = string BoundaryCondition set location = array list decimal string inf * - 1 decimal string inf end function
def __init__(self): self.type = "BoundaryCondition" self.location = np.array([float('inf')*-1, float('inf')])
Python
nomic_cornstack_python_v1
function open self url *args **kwargs begin if __verbose == 1 begin write stdout string . flush stdout end else if __verbose >= 2 begin print url end set resp = get self url *args keyword kwargs if has attribute resp string soup begin set __current_page = soup end set __current_url = url set __current_form = none retur...
def open(self, url, *args, **kwargs): if self.__verbose == 1: sys.stdout.write('.') sys.stdout.flush() elif self.__verbose >= 2: print(url) resp = self.get(url, *args, **kwargs) if hasattr(resp, 'soup'): self.__current_page = resp.soup ...
Python
nomic_cornstack_python_v1