code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
try begin write f string hello world end finally begin close f end with open string test3.txt string w as f begin write f string helloworld end comment with statement context manager comment https://docs.python.org/3/reference/datamodel.html#object.__enter__ class MyFile begin function __init__ self name begin set name...
try: f.write('hello world') finally: f.close() with open('test3.txt', 'w') as f: f.write('helloworld') # with statement context manager # https://docs.python.org/3/reference/datamodel.html#object.__enter__ class MyFile: def __init__(self, name): self.name = name self.file = None ...
Python
zaydzuhri_stack_edu_python
comment Selection sort set lst = eval input string Enter list for i in range length lst begin set x = i for j in range i + 1 length lst begin if lst at x > lst at j begin set x = j end end comment Swap found minimum element with the first element set tuple lst at i lst at x = tuple lst at x lst at i end print lst
#Selection sort lst=eval(input('Enter list')) for i in range(len(lst)): x=i for j in range(i+1,len(lst)): if lst[x]>lst[j]: x=j lst[i],lst[x]=lst[x], lst[i] # Swap found minimum element with the first element print(lst)
Python
zaydzuhri_stack_edu_python
function message_retr self begin return _message_retr end function
def message_retr(self): return self._message_retr
Python
nomic_cornstack_python_v1
function classify_data data_points begin set classified_data = list for point in data_points begin if point % 2 == 0 begin append classified_data string green end else begin append classified_data string red end end return classified_data end function
def classify_data(data_points): classified_data = [] for point in data_points: if point % 2 == 0: classified_data.append('green') else: classified_data.append('red') return classified_data
Python
flytech_python_25k
function init pt content begin set p = call PTree set distribution = distribution set global_index = global_index set start_index = start_index set nb_segs = nb_segs set content = content return p end function
def init(pt, content): p = PTree() p.distribution = pt.distribution p.global_index = pt.global_index p.start_index = pt.start_index p.nb_segs = pt.nb_segs p.content = content return p
Python
nomic_cornstack_python_v1
function log_code_versions self code_versions begin for tuple key code_version in items code_versions begin if not is instance key string_types begin raise call TypeError format string key must be str, not {} type key end if not is instance code_version _Code begin raise call TypeError format string code version must b...
def log_code_versions(self, code_versions): for key, code_version in code_versions.items(): if not isinstance(key, six.string_types): raise TypeError("key must be str, not {}".format(type(key))) if not isinstance(code_version, code._Code): raise TypeError(...
Python
nomic_cornstack_python_v1
import numpy as np from transitionModelv2 import createTransitionModel class DrivingMDP begin function __init__ self begin set locations = list string Upper East Side string Upper West Side string East Harlem string Harlem string Washington Heights string Chelsea string Hell's Kitchen string Midtown string Midtown East...
import numpy as np from transitionModelv2 import createTransitionModel class DrivingMDP: def __init__(self): self.locations = ['Upper East Side', 'Upper West Side', 'East Harlem', 'Harlem', 'Washington Heights', 'Chelsea', "Hell's Kitchen", 'Midtown', 'Midtown East', 'Murray Hill and Gramercy', 'East Vill...
Python
zaydzuhri_stack_edu_python
import card import random comment This class represents a standard Deck of cards. We populate the deck using comment two for loops. class Deck begin function __init__ self begin comment Instance variable set cards = list comment Range over the cards for suit in SUITS begin for value in VALUES begin comment Create a ne...
import card import random # This class represents a standard Deck of cards. We populate the deck using # two for loops. class Deck: def __init__(self): # Instance variable self.cards = [] # Range over the cards for suit in card.SUITS: for value in card.VALUES: ...
Python
zaydzuhri_stack_edu_python
import flask import json from flask import request , render_template , redirect , url_for set app = call Flask __name__ set config at string DEBUG = true set SONGLIST = dict string Apple 1 ; string Cameron 2 ; string BestSong 3 decorator call route string / methods=list string GET function getAll begin return call rend...
import flask import json from flask import request, render_template, redirect, url_for app = flask.Flask(__name__) app.config['DEBUG'] = True SONGLIST = {'Apple': 1, 'Cameron': 2, 'BestSong': 3} @app.route('/', methods=['GET']) def getAll(): return render_template("vote.html", songList=SONGLIST) @a...
Python
zaydzuhri_stack_edu_python
set string = string ϲݿѧ print character 9733 * length string + 2 print character 9733 + string + character 9733 print character 9733 * length string + 2
string="ϲݿѧ" print(chr(0x2605)*(len(string)+2)) print(chr(0x2605)+string+chr(0x2605)) print(chr(0x2605)*(len(string)+2))
Python
zaydzuhri_stack_edu_python
function push_parser begin set usage = string usage: %prog [tx_options] push [options] set description = string This command pushes all local files that have been added to Transifex to the remote server. All new translations are merged with existing ones and if a language doesn't exists then it gets created. If you wan...
def push_parser(): usage = "usage: %prog [tx_options] push [options]" description = "This command pushes all local files that have been added to "\ "Transifex to the remote server. All new translations are merged "\ "with existing ones and if a language doesn't exists then it gets "\ "cr...
Python
nomic_cornstack_python_v1
string Crie um programa que leia nome, ano de nascimento e carteira de trabalho e cadastre-os (com idade) em um dicionário. Se por acaso a CTPS for diferente de zero, o dicionário receberá também o ano de contratação e o salário. Calcule e acrescente, além da idade, com quantos anos a pessoa vai se aposentar. Obs.: apo...
""" Crie um programa que leia nome, ano de nascimento e carteira de trabalho e cadastre-os (com idade) em um dicionário. Se por acaso a CTPS for diferente de zero, o dicionário receberá também o ano de contratação e o salário. Calcule e acrescente, além da idade, com quantos anos a pessoa vai se aposentar. Obs.: apos...
Python
zaydzuhri_stack_edu_python
function gender self begin return _gender end function
def gender(self): return self._gender
Python
nomic_cornstack_python_v1
function _list_params self the_list begin return list comprehension p for e in the_list for p in call _params e end function
def _list_params(self, the_list: List): return [p for e in the_list for p in self._params(e)]
Python
nomic_cornstack_python_v1
function question_2b_sanity_check decoder char_vocab begin print string - * 80 print string Running Sanity Check for Question 2b: CharDecoder.forward() print string - * 80 set sequence_length = 4 set inpt = zeros sequence_length BATCH_SIZE dtype=long set tuple logits tuple dec_hidden1 dec_hidden2 = call forward inpt se...
def question_2b_sanity_check(decoder, char_vocab): print("-" * 80) print("Running Sanity Check for Question 2b: CharDecoder.forward()") print("-" * 80) sequence_length = 4 inpt = torch.zeros(sequence_length, BATCH_SIZE, dtype=torch.long) logits, (dec_hidden1, dec_hidden2) = decoder.forward(inpt)...
Python
nomic_cornstack_python_v1
from tkinter import * import os import time set root = call Tk call resizable 0 0 title root string menu call geometry string 1024x600 function startprogram event begin call system string python3 detect_mask_video.py call destroy end function function exitprogram event begin call destroy end function comment Setting ba...
from tkinter import * import os import time root = Tk() root.resizable(0, 0) root.title("menu") root.geometry("1024x600") def startprogram(event): os.system('python3 detect_mask_video.py') root.destroy() def exitprogram(event): root.destroy() #Setting background image img = Phot...
Python
zaydzuhri_stack_edu_python
function from_dict cls dikt begin string Returns the dict as a model return call deserialize_model dikt cls end function
def from_dict(cls: typing.Type[T], dikt) -> T: """Returns the dict as a model""" return util.deserialize_model(dikt, cls)
Python
jtatman_500k
function get_ebbox obj begin set ebbox = zeros tuple 5 2 dtype=int64 comment apply hextensions if is instance obj Rect begin set ebbox at 0 = bbox at 0 - array list hextension 0 set ebbox at 1 = bbox at 1 + array list hextension 0 set ebbox at 2 = ebbox at 2 + array list hextension 0 set ebbox at 3 = ebbox at 3 + array...
def get_ebbox(obj): ebbox = np.zeros( (5,2), dtype=np.int64 ) if isinstance(obj, laygo2.object.physical.Rect): # apply hextensions ebbox[0] = obj.bbox[0] - np.array([obj.hextension, 0]) ebbox[1] = obj.bbox[1] + np.array([obj.hextension, 0]) ebbox[2] = ebbox[2] + np.a...
Python
nomic_cornstack_python_v1
import math for i in range 1 integer square root 1000000 + 1 begin set square = i * i print square end
import math for i in range(1, int(math.sqrt(1000000)) + 1): square = i * i print(square)
Python
jtatman_500k
function display_summary self print_loc begin print string Name: _name file=print_loc print string Generation: _generation file=print_loc print string Accuracy: _accuracy file=print_loc print string PP: _pp file=print_loc print string Power _power file=print_loc print string Type: _type file=print_loc print string Dama...
def display_summary(self, print_loc): print("Name: ", self._name, file=print_loc) print("Generation: ", self._generation, file=print_loc) print("Accuracy: ", self._accuracy, file=print_loc) print("PP: ", self._pp, file=print_loc) print("Power", self._power, file=print_loc) ...
Python
nomic_cornstack_python_v1
function _build_representation_layer self input_src_word input_src_word_mask input_src_char input_src_char_mask input_trg_word input_trg_word_mask input_trg_char input_trg_char_mask begin set src_word_vocab_size = data_src_word_vocab_size set src_word_embed_dim = model_representation_src_word_embed_dim set src_word_dro...
def _build_representation_layer(self, input_src_word, input_src_word_mask, input_src_char, input_src_char_mask, input_trg_word, ...
Python
nomic_cornstack_python_v1
function capitalize_string string begin comment Remove leading and trailing whitespace set string = strip string set result = list set capitalize_next = true for char in string begin if is alpha char begin if capitalize_next begin append result upper char set capitalize_next = false end else begin append result lower ...
def capitalize_string(string): string = string.strip() # Remove leading and trailing whitespace result = [] capitalize_next = True for char in string: if char.isalpha(): if capitalize_next: result.append(char.upper()) capitalize_next = False ...
Python
jtatman_500k
function set_center_freq self *args begin return call usrp_sink_sptr_set_center_freq self *args end function
def set_center_freq(self, *args): return _uhd_swig.usrp_sink_sptr_set_center_freq(self, *args)
Python
nomic_cornstack_python_v1
function SetAddonsConfig 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 SetAddonsConfig(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
function catalog_product_attribute_media_gallery_management_v1_remove_delete_with_http_info self sku entry_id **kwargs begin set all_params = list string sku string entry_id append all_params string callback append all_params string _return_http_data_only append all_params string _preload_content append all_params stri...
def catalog_product_attribute_media_gallery_management_v1_remove_delete_with_http_info(self, sku, entry_id, **kwargs): all_params = ['sku', 'entry_id'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.appe...
Python
nomic_cornstack_python_v1
function check_keys_match_zsk_policy request policy logger begin if not keys_match_zsk_policy begin warning string KSR-BUNDLE-KEYS: Disabled by policy (keys_match_zsk_policy) return end set seen : Dict at tuple str Key = dict for bundle in bundles begin for key in keys begin if key_identifier in seen begin comment ver...
def check_keys_match_zsk_policy( request: Request, policy: RequestPolicy, logger: Logger ) -> None: if not policy.keys_match_zsk_policy: logger.warning("KSR-BUNDLE-KEYS: Disabled by policy (keys_match_zsk_policy)") return seen: Dict[str, Key] = {} for bundle in request.bundles: ...
Python
nomic_cornstack_python_v1
string zliczanie wystapien elementu w tablicy/stringu, usuwanie danego elementu set liczba_binarna = string 1111010101011100001 print count liczba_binarna string 1 count liczba_binarna string 0 length liczba_binarna set liczba_binarna = replace liczba_binarna string 1 string print liczba_binarna length liczba_binarna
''' zliczanie wystapien elementu w tablicy/stringu, usuwanie danego elementu ''' liczba_binarna = "1111010101011100001" print(liczba_binarna.count('1'), liczba_binarna.count('0'), len(liczba_binarna)) liczba_binarna = liczba_binarna.replace("1", '') print(liczba_binarna, len(liczba_binarna))
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Thu Feb 21 14:22:02 2019 @author: jmilli import numpy as np import vip_hci as vip set ds9 = call Ds9Window comment pixel scale in arcsec/px set pixel_scale = 0.01225 comment distance to the star in pc set dstar = 80 comment 1pc means 1arcsec ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 21 14:22:02 2019 @author: jmilli """ import numpy as np import vip_hci as vip ds9=vip.Ds9Window() pixel_scale=0.01225 # pixel scale in arcsec/px dstar= 80 # distance to the star in pc # 1pc means 1arcsec represents 1au nx = 200 ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Sat Oct 16 17:45:16 2021 @author: abuumar class Auto begin function __init__ self make model year mileage=0 begin set make = make set model = model set year = year set mileage = 0 end function function get_info self begin return string The re...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Oct 16 17:45:16 2021 @author: abuumar """ class Auto(): def __init__(self,make,model,year,mileage=0): self.make = make self.model = model self.year = year self.mileage = 0 def get_info(self): ret...
Python
zaydzuhri_stack_edu_python
function setup_class cls begin set T = 1.0 * eV set particle = string H+ comment get thermal velocity and thermal velocity squared set vTh = call thermal_speed T particle=particle method=string most_probable set vx = 100000.0 * m / s set vy = 100000.0 * m / s set vz = 100000.0 * m / s set vx_drift = 0 * m / s set vy_dr...
def setup_class(cls): cls.T = 1.0 * u.eV cls.particle = "H+" # get thermal velocity and thermal velocity squared cls.vTh = thermal_speed(cls.T, particle=cls.particle, method="most_probable") cls.vx = 1e5 * u.m / u.s cls.vy = 1e5 * u.m / u.s cls.vz = 1e5 * u.m / u....
Python
nomic_cornstack_python_v1
function execute_command cmd begin string given a command return output_status, and out_data set execute_state = false set stdoutdata = none set stderrdata = none end function
def execute_command(cmd): """ given a command return output_status, and out_data """ execute_state=False stdoutdata=None stderrdata=None
Python
zaydzuhri_stack_edu_python
function references self assessment_id begin set url = string { root_url } /lit/api/assessment/ { assessment_id } /reference-export/ set response_json = json get session url return call DataFrame response_json end function
def references(self, assessment_id: int) -> pd.DataFrame: url = f"{self.session.root_url}/lit/api/assessment/{assessment_id}/reference-export/" response_json = self.session.get(url).json() return pd.DataFrame(response_json)
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Sun Aug 9 23:47:05 2020 @author: dineshy86 import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np set train = read csv string train.csv set test = read csv string test.csv set sample = read csv string sample.csv set corr = call corr c...
# -*- coding: utf-8 -*- """ Created on Sun Aug 9 23:47:05 2020 @author: dineshy86 """ import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np train = pd.read_csv('train.csv') test= pd.read_csv('test.csv') sample= pd.read_csv('sample.csv') corr = train.corr()...
Python
zaydzuhri_stack_edu_python
function lookup_table *a **d begin set d = dictionary *a keyword d update d call dictreverse d return call to_storage d end function
def lookup_table(*a, **d): d = dict(*a, **d) d.update(dictreverse(d)) return to_storage(d)
Python
nomic_cornstack_python_v1
import re with open string input/day21.txt as file begin set food_strings = call splitlines end set foods = list for food_string in food_strings begin set tuple ingredients_string allergens_string = call groups set ingredients_set = set split ingredients_string string set allergens = split allergens_string string , ap...
import re with open('input/day21.txt') as file: food_strings = file.read().splitlines() foods = [] for food_string in food_strings: ingredients_string, allergens_string = re.search(r'(.+) \(contains (.+)\)', food_string).groups() ingredients_set = set(ingredients_string.split(' ')) allergens = allergen...
Python
zaydzuhri_stack_edu_python
from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.common.exceptions import TimeoutException from selenium.webdriver.support import expected_conditions as EC from base import BasePage class DashboardPage extends BasePage begin set TABLE_HEADERS = tuple CS...
from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait from selenium.common.exceptions import TimeoutException from selenium.webdriver.support import expected_conditions as EC from .base import BasePage class DashboardPage(BasePage): TABLE_HEADERS = (By.CSS_SELECTOR, '#...
Python
zaydzuhri_stack_edu_python
import pygame import math set BLACK = tuple 0 0 0 set WHITE = tuple 255 255 255 set GREY = tuple 112 128 144 set RED = tuple 255 218 185 set BLUE = tuple 135 206 250 comment Screen dimensions set SCREEN_WIDTH = 800 set SCREEN_HEIGHT = 600 class Platform extends Sprite begin string Platform the user can jump on function...
import pygame import math BLACK = (0, 0, 0) WHITE = (255, 255, 255) GREY = (112, 128, 144) RED = (255, 218, 185) BLUE = (135, 206, 250) # Screen dimensions SCREEN_WIDTH = 800 SCREEN_HEIGHT = 600 class Platform(pygame.sprite.Sprite): """ Platform the user can jump on """ def __init__(self): """ Assum...
Python
zaydzuhri_stack_edu_python
function test_delete_user tenant_user begin call delete_user tenant_user call refresh_from_db assert is_active is false end function
def test_delete_user(tenant_user): TenantUser.objects.delete_user(tenant_user) tenant_user.refresh_from_db() assert tenant_user.is_active is False
Python
nomic_cornstack_python_v1
import os , time , random import pandas as pd import numpy as np from tqdm import tqdm class BenchMark begin set file = none set dataframe = none function __init__ self name begin set name = name call check_file set start_time = time print string ==== START BENCHMARK ==== end function function check_file self begin if ...
import os, time, random import pandas as pd import numpy as np from tqdm import tqdm class BenchMark: file = None dataframe = None def __init__(self, name): self.name = name self.check_file() self.start_time = time.time() print("==== START BENCHMARK ====") def check_fi...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding:utf-8 -*- set __author__ = string Andy string Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last...
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'Andy' """ Given an array of non-negative integers, you are initially positioned at the first index of the array. Each element in the array represents your maximum jump length at that position. Determine if you are able to reach the last index. For example: A =...
Python
zaydzuhri_stack_edu_python
function unauthorized begin call flash string You must be logged in to view that page return call redirect call url_for string catalog_bp.index end function
def unauthorized(): flash('You must be logged in to view that page') return redirect(url_for('catalog_bp.index'))
Python
nomic_cornstack_python_v1
function get_coordinates node_class begin string Generate coordinates for a node in a given class. set quadrant_size = 2 * pi / 8.0 set quadrant = call get_quadrant_from_class node_class set begin_angle = quadrant_size * quadrant set r = 200 + 800 * random set alpha = begin_angle + random * quadrant_size set x = r * co...
def get_coordinates(node_class): """Generate coordinates for a node in a given class.""" quadrant_size = (2 * math.pi / 8.0) quadrant = get_quadrant_from_class(node_class) begin_angle = quadrant_size * quadrant r = 200 + 800*random.random() alpha = begin_angle + random.random() * quadrant_size ...
Python
jtatman_500k
function test_splitter_pass_cv_object load_pos_and_neg_data begin from sktime.forecasting.model_selection._split import ExpandingWindowSplitter from pycaret.time_series import setup set fold = 3 comment regular horizon of 12 months set fh = array range 1 13 comment extended horizon of 24 months set fh_extended = array ...
def test_splitter_pass_cv_object(load_pos_and_neg_data): from sktime.forecasting.model_selection._split import ExpandingWindowSplitter from pycaret.time_series import setup fold = 3 fh = np.arange(1, 13) # regular horizon of 12 months fh_extended = np.arange(1, 25) # extended horizon of 24 mont...
Python
nomic_cornstack_python_v1
comment import webdriver from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time comment create webdriver object set dri...
# import webdriver from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC import time # create webdriver object driver = webdriver...
Python
zaydzuhri_stack_edu_python
from selenium import webdriver from bs4 import BeautifulSoup from math import ceil import os function crawler begin set i = 1 call implicitly_wait 10 call click if length split text string == 2 begin set max_page_num = ceil decimal split text string at 0 / 10 end else begin set max_page_num = ceil decimal replace split...
from selenium import webdriver from bs4 import BeautifulSoup from math import ceil import os def crawler(): i = 1 driver.implicitly_wait(10) driver.find_element_by_xpath('//*[@id="app"]/div/div[2]/div/div[2]/div').click() if len(driver.find_element_by_xpath('//*[@id="app"]/div/div/div[2]/d...
Python
zaydzuhri_stack_edu_python
import random , datetime from enum import Enum from elo_settings import * from sim_settings import * comment LOGGING set time = string now set filename = string logs/ + replace time string : string . + string .log set logFile = open filename string w set log = string LOG + string time + string set log = log + format s...
import random, datetime from enum import Enum from elo_settings import * from sim_settings import * # LOGGING time = str(datetime.datetime.now()) filename = "logs/" + time.replace(":", ".") + ".log" logFile = open(filename, "w") log = "LOG " + str(time) + "\n" log += "Simulation Settings: \n" \ "Number of Playe...
Python
zaydzuhri_stack_edu_python
import cv2 import numpy as np set img = call imread string data/images/mountain.jpeg image show string ori img set sharpen = array list list 0 - 1 0 list - 1 5 - 1 list 0 - 1 0 dtype=string int set result = call filter2D img - 1 sharpen image show string sharp result call waitKey call destroyAllWindows
import cv2 import numpy as np img = cv2.imread('data/images/mountain.jpeg') cv2.imshow("ori", img) sharpen = np.array( [ [0, -1, 0], [-1, 5, -1], [0, -1, 0] ] , dtype='int' ) result = cv2.filter2D(img, -1, sharpen) cv2.imshow("sharp", result) cv2.waitKey() cv2.de...
Python
zaydzuhri_stack_edu_python
import numpy as np comment 배열의 인덱싱 set a = array list 0 1 2 3 4 print a at 2 print a at - 1 comment 다차원 배열의 인덱싱은 comma로 구분 set a = array list list 0 1 2 list 3 4 5 print a comment 1번째 행의 1번째 열 print a at tuple 1 1 comment 0번째 행의 1번째 열 print a at tuple 0 1 comment 마지막 행의 마지막 열 print a at tuple - 1 - 1 print string -----...
import numpy as np # 배열의 인덱싱 a=np.array([0,1,2,3,4]) print(a[2]) print(a[-1]) # 다차원 배열의 인덱싱은 comma로 구분 a=np.array([[0,1,2],[3,4,5]]) print(a) print(a[1,1]) #1번째 행의 1번째 열 print(a[0,1]) #0번째 행의 1번째 열 print(a[-1,-1]) #마지막 행의 마지막 열 print("----------------------------------------") # 배열 슬라이싱 b=np.arr...
Python
zaydzuhri_stack_edu_python
comment 참과 거짓 boolean comment if comment True, False comment and, or, not set a = true set b = false comment false 출력 print a and b comment true 출력 print a or b comment 동일한 의미가 아니라 변수에 값을 대입한다는 말이다. set c = true print a == true comment 둘 다 동일하게 True print a is true comment if문 실습 set d = 7 if d > 5 begin print string d...
# 참과 거짓 boolean # if # True, False # and, or, not a = True b = False print(a and b) # false 출력 print(a or b) # true 출력 c = True #동일한 의미가 아니라 변수에 값을 대입한다는 말이다. print(a == True) print(a is True) #둘 다 동일하게 True #if문 실습 d = 7 if d > 5: print("d는 5보다 크다") else: print("d는 5보다 작거나 같다") q = 135 if q > 150 : ...
Python
zaydzuhri_stack_edu_python
string QUESTION #20 - VALID PARENTHESES Difficulty: Easy comment test case 1 - "((})" returns False comment test case 2 - "(){}[" returns False (odd length, edge case) comment test case 3 - "{}[]()" returns True comment test case 4 - "({[]})" returns True comment test case 5 - "((" returns False (didn't come up with th...
""" QUESTION #20 - VALID PARENTHESES Difficulty: Easy """ # test case 1 - "((})" returns False # test case 2 - "(){}[" returns False (odd length, edge case) # test case 3 - "{}[]()" returns True # test case 4 - "({[]})" returns True # test case 5 - "((" returns False (didn't come up with this one myself) def isValid(...
Python
zaydzuhri_stack_edu_python
from Console.LoopOutPut import printDesign from Objects import Data comment class Sell: function runSellLoop history begin set history = history print string ...Running...SellLoop set myInput = none set exitWord = string exit while myInput != exitWord begin set myInput = call printDesign string sell call sellCommands m...
from Console.LoopOutPut import printDesign from Objects import Data # class Sell: def runSellLoop(history): history = history print('...Running...SellLoop') myInput = None exitWord = "exit" while myInput != exitWord: myInput = printDesign('sell') sellCommands(myInput) print('...
Python
zaydzuhri_stack_edu_python
function search_pfas self decays spacings begin function pfas_factory x y begin set elo = call EloModel return call PFAExtSpacing elo decay_rate=x spacing_rate=y end function return search factory=pfas_factory xvalues=decays yvalues=spacings xlabel=string decay rates ylabel=string spacing rates end function
def search_pfas(self, decays, spacings): def pfas_factory(x, y): elo = EloModel() return PFAExtSpacing(elo, decay_rate=x, spacing_rate=y) return self.search( factory=pfas_factory, xvalues=decays, yvalues=spacings, xlabel='decay rat...
Python
nomic_cornstack_python_v1
comment Ek program likhiye jisse ki agar di hui key pehle se dictionary me comment exist karti ho toh “exists “ print kare aur agar nahi karti ho toh comment “not exists” print kare. Example :- set dict = dict string name string Raju ; string mark 56 set key_name = input string enter the key name :- if key_name in dict...
# Ek program likhiye jisse ki agar di hui key pehle se dictionary me # exist karti ho toh “exists “ print kare aur agar nahi karti ho toh # “not exists” print kare. Example :- dict={"name":"Raju","mark":56} key_name=input("enter the key name :-") if key_name in dict: print("exist") else: print("not exist")
Python
zaydzuhri_stack_edu_python
function tanpi self begin return call _unop string tanpi end function
def tanpi(self): return self._unop("tanpi")
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- import csv import fileinput import sys import numpy from pynm.feature.metric.itml import learn_metric , convert_data class ItmlCommand begin set name = string itml set help = string Information Theoretic Metric Learning decorator classmethod function build_arg_parser cls parser begin call a...
# -*- coding:utf-8 -*- import csv import fileinput import sys import numpy from pynm.feature.metric.itml import learn_metric, convert_data class ItmlCommand: name = 'itml' help = 'Information Theoretic Metric Learning' @classmethod def build_arg_parser(cls, parser): parser.add_argument('-i...
Python
jtatman_500k
function multi_show_uploaded request key begin set image = call get_object_or_404 MultiuploaderImage key_data=key set url = MEDIA_URL + name return call render_to_response string multiuploader/one_image.html dict string multi_single_url url end function
def multi_show_uploaded(request, key): image = get_object_or_404(MultiuploaderImage, key_data=key) url = settings.MEDIA_URL+image.image.name return render_to_response('multiuploader/one_image.html', {"multi_single_url":url,})
Python
nomic_cornstack_python_v1
function getdict self crop=true begin string Get final dictionary. If ``crop`` is ``True``, apply :func:`.cnvrep.bcrop` to returned array. set D = Y if crop begin set D = call bcrop D dsz dimN end return D end function
def getdict(self, crop=True): """Get final dictionary. If ``crop`` is ``True``, apply :func:`.cnvrep.bcrop` to returned array. """ D = self.Y if crop: D = cr.bcrop(D, self.cri.dsz, self.cri.dimN) return D
Python
jtatman_500k
function __init__ self begin comment add ram member = 256 bytes set ram = list 0 * 256 comment add registers = 8 set registers = list 0 * 8 comment add program counter = PC value: 0 set pc = 0 comment make a binary operations table set binary_ops = dict 130 LDI ; 71 PRN ; 1 HLT ; 162 MUL ; 69 PUSH ; 70 POP ; 80 CALL ; ...
def __init__(self): #add ram member = 256 bytes self.ram = [0] * 256 #add registers = 8 self.registers = [0] * 8 #add program counter = PC value: 0 self.pc = 0 #make a binary operations table self.binary_ops = { 0b10000010: self.LDI, ...
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt from scipy.fftpack import fft , fftfreq , fftshift import math import numpy as np from scipy.io import wavfile class My_Signal begin function __init__ self t=none amplitude=none frequency=none begin set amplitude = amplitude set frequency = frequency if not amplitude == none or frequency...
import matplotlib.pyplot as plt from scipy.fftpack import fft, fftfreq, fftshift import math import numpy as np from scipy.io import wavfile class My_Signal: def __init__(self, t=None, amplitude=None, frequency=None): self.amplitude = amplitude self.frequency = frequency if not (amplitude =...
Python
zaydzuhri_stack_edu_python
function testSampleNode self begin set op = call sample_node 10 1 with call Session as sess begin set nodes = run op assert equal 10 length nodes list comprehension assert true n in list 1 3 5 for n in nodes end end function
def testSampleNode(self): op = ops.sample_node(10, 1) with tf.Session() as sess: nodes = sess.run(op) self.assertEqual(10, len(nodes)) [self.assertTrue(n in [1, 3, 5]) for n in nodes]
Python
nomic_cornstack_python_v1
function done_parsing self begin comment STUDENT return call input_buffer_len == 1 and call stack_len == 1 end function comment END STUDENT
def done_parsing(self): # STUDENT return (self.input_buffer_len() == 1 ) and (self.stack_len()==1) # END STUDENT
Python
nomic_cornstack_python_v1
comment Utility functions import matplotlib.pyplot as plt import re import numpy as np import pandas as pd from functools import partial from sklearn.decomposition import PCA from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline from sklearn.preprocessing import Imputer from sk...
# Utility functions import matplotlib.pyplot as plt import re import numpy as np import pandas as pd from functools import partial from sklearn.decomposition import PCA from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline from sklearn.preprocessing import Imputer from sklearn...
Python
zaydzuhri_stack_edu_python
function source self begin return _src end function
def source(self): return self._src
Python
nomic_cornstack_python_v1
function ISetPatternFeatureArray self FeatCount=defaultNamedNotOptArg ArrayDataIn=defaultNamedNotOptArg begin return call InvokeTypes 16 LCID 1 tuple 24 0 tuple tuple 3 1 tuple 16393 1 FeatCount ArrayDataIn end function
def ISetPatternFeatureArray(self, FeatCount=defaultNamedNotOptArg, ArrayDataIn=defaultNamedNotOptArg): return self._oleobj_.InvokeTypes(16, LCID, 1, (24, 0), ((3, 1), (16393, 1)),FeatCount , ArrayDataIn)
Python
nomic_cornstack_python_v1
import random function typoglycemia strin begin set ll = length strin set strout = string if ll > 4 begin set strout = strout + strin at 0 set rand = random sample range 1 ll - 1 ll - 2 for i in rand begin set strout = strout + strin at i end set strout = strout + strin at ll - 1 end else begin set strout = strout + s...
import random def typoglycemia(strin): ll = len(strin) strout = "" if ll > 4: strout += strin[0] rand = random.sample(range(1,ll-1),ll-2) for i in rand: strout += strin[i] strout += strin[ll-1] else: strout += strin return strout str = "I couldn'...
Python
zaydzuhri_stack_edu_python
import cv2 import numpy as np from matplotlib import pyplot as plt comment loading image set img0 = call imread string image.jpg comment converting to gray scale set gray = call cvtColor img0 COLOR_BGR2GRAY comment remove noise set img = call GaussianBlur gray tuple 3 3 0 comment convolute with proper kernels set lapla...
import cv2 import numpy as np from matplotlib import pyplot as plt # loading image img0 = cv2.imread('image.jpg',) # converting to gray scale gray = cv2.cvtColor(img0, cv2.COLOR_BGR2GRAY) # remove noise img = cv2.GaussianBlur(gray,(3,3),0) # convolute with proper kernels laplacian = cv2.Laplacian(img,...
Python
zaydzuhri_stack_edu_python
function selectionCorners self begin if none != bottomLeftPoint and none != topRightPoint begin return tuple bottomLeftPoint topRightPoint end return none end function
def selectionCorners(self): if(None != self.editor.selectionTool.bottomLeftPoint and None != self.editor.selectionTool.topRightPoint): return (self.editor.selectionTool.bottomLeftPoint, self.editor.selectionTool.topRightPoint) return None
Python
nomic_cornstack_python_v1
function create_accumulator self begin return dict end function
def create_accumulator(self) -> WrapperAccumulator: return {}
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python set n = integer call raw_input set l = list set cnt = list 0 * n for i in range n begin set tuple a b c = map int split call raw_input set tuple a b = tuple a - 1 b - 1 append l list a b c end set other = l at 0 at 1 for i in range 1 n begin for j in range i n begin if l at j at 0 == other...
#!/usr/bin/env python n = int(raw_input()) l = [] cnt = [0]*n for i in range(n): a, b, c = map(int, raw_input().split()) a, b = a-1, b-1 l.append([a, b, c]) other = l[0][1] for i in range(1, n): for j in range(i, n): if l[j][0] == other or l[j][1] == other: if l[j][0] == other: ot...
Python
zaydzuhri_stack_edu_python
import ast import io from nose.tools import istest , assert_equal from farthing.locations import Location from farthing.ast_util import find_return_annotation_location from farthing import parser decorator istest class ReturnAnnotationLocationTests extends object begin decorator istest function returns_location_of_retu...
import ast import io from nose.tools import istest, assert_equal from farthing.locations import Location from farthing.ast_util import find_return_annotation_location from farthing import parser @istest class ReturnAnnotationLocationTests(object): @istest def returns_location_of_return_annotation_hole(self)...
Python
zaydzuhri_stack_edu_python
comment Escreva um programa que leia 10 números e imprima “Positivo” ou “Negativo” de acordo com o valor do número digitado set n = 1 while n <= 10 begin set number = decimal input string Informe um número: set n = n + 1 if number >= 0 begin print format string O número {} é POSITIVO number end else begin print format ...
# Escreva um programa que leia 10 números e imprima “Positivo” ou “Negativo” de acordo com o valor do número digitado n = 1 while n <= 10: number = float(input("Informe um número:")) n += 1 if(number >= 0): print("O número {} é POSITIVO".format(number)) else: print("O número {} é NEGAT...
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function __init__ self begin set memo = list end function function climbStairs self n begin string :type n: int :rtype: int set memo = list - 1 * n + 1 return call calcWays n end function function calcWays self n begin if n == 0 or n == 1 begin return 1 end if memo at n == - 1 begin...
class Solution(object): def __init__(self): self.memo = [] def climbStairs(self, n): """ :type n: int :rtype: int """ self.memo = [-1] * (n+1) return self.calcWays(n) def calcWays(self,n): if n == 0 or n == 1: return 1 if s...
Python
zaydzuhri_stack_edu_python
function get_sensors_temperature_with_http_info self access_token sensor_param **kwargs begin set all_params = list string access_token string sensor_param append all_params string callback append all_params string _return_http_data_only append all_params string _preload_content append all_params string _request_timeou...
def get_sensors_temperature_with_http_info(self, access_token, sensor_param, **kwargs): all_params = ['access_token', 'sensor_param'] all_params.append('callback') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeo...
Python
nomic_cornstack_python_v1
function WriteVToKeithley self voltage begin try begin sleep 0.2 write call instrument string GPIB::22 string SOUR:VOLT + string voltage sleep 0.2 return call ask string READ? end except any begin call errorMessage string An error talking to the keithley has occurred end end function
def WriteVToKeithley(self,voltage): try: wx.Sleep(.2) visa.instrument("GPIB::22").write("SOUR:VOLT "+str(voltage)) wx.Sleep(.2) return visa.instrument("GPIB::22").ask("READ?") except: self.errorMessage('An error talking to the keithley has occu...
Python
nomic_cornstack_python_v1
import random import lib.exact_cover from lib.n_queens import flatten class InvalidBoard extends Exception begin pass end class function empty_board begin set board = list for i in range 1 10 begin set row = list for j in range 1 10 begin append row none end append board row end return board end function function sub...
import random import lib.exact_cover from lib.n_queens import flatten class InvalidBoard(Exception): pass def empty_board(): board = [] for i in range(1, 10): row = [] for j in range(1, 10): row.append(None) board.append(row) return board def subgrid(x, y, board): x_min, y_min = [3 * (i /...
Python
zaydzuhri_stack_edu_python
function test_retrieve_column_as_list begin comment Setup a test instrument table for tests. Drop and recreate the table at comment the start of each test set table_name = string test_instruments set table_def = dict string ric string text ; string cusip string text ; string isin string text set database = call create_...
def test_retrieve_column_as_list(): # Setup a test instrument table for tests. Drop and recreate the table at # the start of each test table_name = "test_instruments" table_def = {"ric": "text", "cusip": "text", "isin": "text"} database = helper.create_db() h...
Python
nomic_cornstack_python_v1
function clean_old_password self begin set old_password = cleaned_data at string old_password print old_password print user if not call check_password old_password begin raise call ValidationError call _ string Your old password was entered incorrectly. Please enter it again. end return old_password end function
def clean_old_password(self): old_password = self.cleaned_data["old_password"] print(old_password) print(self.user) if not self.user.check_password(old_password): raise forms.ValidationError( _("Your old password was entered incorrectly. Please enter it again...
Python
nomic_cornstack_python_v1
function _convert_opts opts begin return join string opts end function
def _convert_opts(opts): return ' '.join(opts)
Python
nomic_cornstack_python_v1
comment !/usr/bin/python -u import datetime import modbus_tcp_sim import os import sys from twisted.internet import reactor from fronius_sim import FroniusSim set app_dir = directory name path directory name path absolute path path __file__ set bottle_dir = call normpath join path app_dir string .. string .. string sof...
#!/usr/bin/python -u import datetime import modbus_tcp_sim import os import sys from twisted.internet import reactor from fronius_sim import FroniusSim app_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) bottle_dir = os.path.normpath(os.path.join(app_dir, '..', '..', 'software', 'ext', 'bottle')) sy...
Python
jtatman_500k
function print_code clazz methods begin comment translate camel-case method names to Python style set methods = list comprehension lower sub string ([a-z])([A-Z]) string \1_\2 s for s in methods write stderr string methods + string print at tuple string \begin{oframed} string \begin{leftbar} at html end function
def print_code(clazz, methods): # translate camel-case method names to Python style methods = [re.sub(r'([a-z])([A-Z])', r'\1_\2', s).lower() for s in methods] sys.stderr.write(str(methods) + '\n') print [r'\begin{oframed}', r'\begin{leftbar}'][html]
Python
nomic_cornstack_python_v1
class StatItem begin function __init__ self url begin set url = url set bill_count = 0 end function function inc_bill_count self begin set bill_count = bill_count + 1 end function function __str__ self begin return string url: { url } , bill_count: { bill_count } end function function __eq__ self another begin comment ...
class StatItem: def __init__(self, url: str): self.url = url self.bill_count = 0 def inc_bill_count(self): self.bill_count += 1 def __str__(self): return f"url: {self.url}, bill_count: {self.bill_count}" def __eq__(self, another): # Need to test return ...
Python
zaydzuhri_stack_edu_python
comment Basic of Python comment Title : Inheritance comment Date : 2020-06-24 comment Creator : tunealog class Person begin function __init__ self name age begin set name = name set age = age end function function say_hello self to_name begin print string Hello + to_name + string I'm + name + string + age + string yea...
# Basic of Python # Title : Inheritance # Date : 2020-06-24 # Creator : tunealog class Person: def __init__(self, name, age): self.name = name self.age = age def say_hello(self, to_name): print("Hello " + to_name + " I'm " + self.name + " " + self.age + " years old") ...
Python
zaydzuhri_stack_edu_python
function format_discounted_price original_price discount_percentage begin try begin comment Validate inputs if not is instance original_price tuple int float or not is instance discount_percentage tuple int float begin raise call ValueError string Invalid inputs: original_price and discount_percentage must be numeric. ...
def format_discounted_price(original_price, discount_percentage): try: # Validate inputs if not isinstance(original_price, (int, float)) or not isinstance(discount_percentage, (int, float)): raise ValueError("Invalid inputs: original_price and discount_percentage must be numeric.") ...
Python
jtatman_500k
import random function generate_palette num_colors bright=true begin if num_colors < 2 or num_colors > 10 begin raise call ValueError string Number of colors should be between 2 and 10 end comment Define the hue ranges for different parts of the spectrum set hue_ranges = list tuple 0 30 tuple 30 90 tuple 90 150 tuple 1...
import random def generate_palette(num_colors, bright=True): if num_colors < 2 or num_colors > 10: raise ValueError("Number of colors should be between 2 and 10") # Define the hue ranges for different parts of the spectrum hue_ranges = [ (0, 30), # Red (30, 90), # Yellow ...
Python
greatdarklord_python_dataset
function __get__ self obj nodes=true edges=true begin if nodes begin call _add_nodes graph=obj end if edges begin call _add_edges graph=obj end call fit_bounds bounds=bounding_box return m end function
def __get__(self, obj, nodes=True, edges=True): if nodes: self._add_nodes(graph=obj) if edges: self._add_edges(graph=obj) self.m.fit_bounds(bounds=obj.bounding_box) return self.m
Python
nomic_cornstack_python_v1
function __insert_row cursor orderlog_row begin set filename = jpeg_image set statinfo = call stat filename set the_length = st_size set fd = open filename string rb set blob_tuple = tuple fd the_length set sql = string insert into orderlog values (?, ?, ?, ?, ?, ?, ?, ?, ?) set is_delivered = 0 if is_delivered begin s...
def __insert_row(cursor: Cursor, orderlog_row: OrderLogRow) -> int: filename = orderlog_row.jpeg_image statinfo = os.stat(filename) the_length = statinfo.st_size fd = open(filename, "rb") blob_tuple = (fd, the_length) sql = "insert into orderlog values (?, ?, ?, ?, ?, ?...
Python
nomic_cornstack_python_v1
import mysql.connector as mydb from datetime import datetime as dt import schedule import time from time import sleep import pandas as pd import setting import math import lineNotify function main begin comment 取得間隔(秒) set interval = 60 * 5 set API_KEY = API_KEY set API_SECRET = API_SECRET set RDShost = RDShost set RDS...
import mysql.connector as mydb from datetime import datetime as dt import schedule import time from time import sleep import pandas as pd import setting import math import lineNotify def main(): # 取得間隔(秒) interval = 60*5 API_KEY = setting.API_KEY API_SECRET = setting.API_SECRET RDShost = setting.RDShost R...
Python
zaydzuhri_stack_edu_python
function setContext self context begin set __context = context return self end function
def setContext(self, context): self.__context = context return self
Python
nomic_cornstack_python_v1
function shape_element element begin if tag == string node begin comment Creates dictionary from list of desired keys set csv_format = call fromkeys schema_keys at string nodes comment In this case, the type is 'node' set csv_format at string type = tag for k in csv_format begin comment 'type' is not an XML attribute o...
def shape_element(element): if element.tag == 'node': csv_format = dict.fromkeys(sql_schema.schema_keys['nodes']) # Creates dictionary from list of desired keys csv_format['type'] = element.tag # In this case, the type is 'node' for k in csv_format: # 'type' is not an XML attri...
Python
nomic_cornstack_python_v1
import random class Solution begin function __init__ self rects begin set valid_rects = list set count = 0 for rect in rects begin set tuple x1 y1 = tuple rect at 0 rect at 1 set tuple x2 y2 = list rect at 2 rect at 3 append valid_rects list count + y2 - y1 + 1 * x2 - x1 + 1 list x1 y1 x2 y2 set count = valid_rects at...
import random class Solution: def __init__(self, rects): self.valid_rects = [] self.count = 0 for rect in rects: x1,y1 = rect[0], rect[1] x2,y2 = [rect[2], rect[3]] self.valid_rects.append([self.count + (y2-y1+1) * (x2-x1+1), [x1,y1,x2,y2]]) se...
Python
zaydzuhri_stack_edu_python
function close_connection self connection_id begin pop connections connection_id end function
def close_connection(self, connection_id): self.connections.pop(connection_id)
Python
nomic_cornstack_python_v1
async function rng ctx num1 num2 begin set num1 = integer num1 set num2 = integer num2 set mn = min num1 num2 set mx = max num1 num2 set output = string Number generated is: ` { random integer mn mx } ` await call send output end function
async def rng(ctx, num1, num2): num1 = int(num1) num2 = int(num2) mn = min(num1, num2) mx = max(num1, num2) output = f'Number generated is: `{random.randint(mn,mx)}`' await ctx.send(output)
Python
nomic_cornstack_python_v1
import numpy as np import pandas as pd import xgboost as xgb import gc import operator import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split function ceate_feature_map features begin set outfile = open string ../../output/xgb/xgb.fmap string w set i = 0 for feat in features begin write ou...
import numpy as np import pandas as pd import xgboost as xgb import gc import operator import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split def ceate_feature_map(features): outfile = open('../../output/xgb/xgb.fmap', 'w') i = 0 for feat in features: outfile.write('{...
Python
zaydzuhri_stack_edu_python
function build_input_dataset self inputs begin set n_examples = length inputs set example_length = length inputs at 0 at 0 at 0 * length inputs at 1 at 0 at 0 set dataset = zeros tuple n_examples example_length dtype=int for i in range n_examples begin set dataset at tuple i slice : : = reshape call asarray call mat...
def build_input_dataset(self, inputs): n_examples = len(inputs) example_length = len(inputs[0][0][0]) * len(inputs[1][0][0]) dataset = np.zeros((n_examples, example_length), dtype=int) for i in range(n_examples): dataset[i,:] = np.asarray(np.matrix(inputs[i][0])).reshape(-1)...
Python
nomic_cornstack_python_v1
from selenium import webdriver set TEST_DATA = dict string single_input string My best message here!! ; string two_input_first 333 ; string two_input_second 444 set output_second = TEST_DATA at string two_input_first + TEST_DATA at string two_input_second function main begin set browser = call Chrome get browser string...
from selenium import webdriver TEST_DATA = { 'single_input': 'My best message here!!', 'two_input_first': 333, 'two_input_second': 444 } output_second = TEST_DATA['two_input_first'] + TEST_DATA['two_input_second'] def main(): browser = webdriver.Chrome() browser.get("https://www.seleniumeasy.com...
Python
zaydzuhri_stack_edu_python
set x = open string xyz.txt string r print read x 5
x=open("xyz.txt","r") print(x.read(5))
Python
zaydzuhri_stack_edu_python
function downloader url path begin set start = time set size = 0 set response = get requests url stream=true set chunk_size = 1024 set content_size = integer headers at string content-length if status_code == 200 begin print string [File size]: %0.2f MB % content_size / chunk_size / 1024 with open path string wb as fil...
def downloader(url, path): start = time.time() size = 0 response = requests.get(url, stream=True) chunk_size = 1024 content_size = int(response.headers['content-length']) if response.status_code == 200: print('[File size]: %0.2f MB' % (content_size / chunk_size / 1024)) with open...
Python
nomic_cornstack_python_v1
import unittest import exerfunc01 class MyTestCase extends TestCase begin function test_passamparametro self begin call soma 2 1 5 assert true true end function function test_testaA self begin with assert raises Exception begin call soma 1 1 5 end end function function test_testaretorno1 self begin set retorno = call s...
import unittest import exerfunc01 class MyTestCase(unittest.TestCase): def test_passamparametro(self): exerfunc01.soma(2,1,5) self.assertTrue(True) def test_testaA(self): with self.assertRaises(Exception): exerfunc01.soma(1,1,5) def test_testaretorno1(self): reto...
Python
zaydzuhri_stack_edu_python
function J self opt ic U start end begin set n = length U set timestep = end - start / decimal n set s = 0 set s = s + 0.5 * call assemble U at 0 ^ 2 * dx for i in range n - 2 begin set s = s + call assemble U at i + 1 ^ 2 * dx end set s = s + 0.5 * call assemble U at - 1 ^ 2 * dx return timestep * s end function
def J(self,opt,ic,U,start,end): n = len(U) timestep = (end-start)/float(n) s = 0 s += 0.5*assemble(U[0]**2*dx) for i in range(n-2): s += assemble(U[i+1]**2*dx) s += 0.5*assemble(U[-1]**2*dx) return timestep*s
Python
nomic_cornstack_python_v1
function job_timeout_ms self begin return get pulumi self string job_timeout_ms end function
def job_timeout_ms(self) -> pulumi.Output[Optional[str]]: return pulumi.get(self, "job_timeout_ms")
Python
nomic_cornstack_python_v1