code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import cv2 , io , json , requests , numpy as np comment API - Preencha sua api key e a linguagem desejada. set url_api = string https://api.ocr.space/parse/image set apiKey = string set language = string comment OCR comment Substitua "eng.jpg" pela imagem que será utilizada. set img = call imread string img/eng.jpg s...
import cv2, io, json, requests, numpy as np # API - Preencha sua api key e a linguagem desejada. url_api = "https://api.ocr.space/parse/image" apiKey = "" language = "" #OCR #Substitua "eng.jpg" pela imagem que será utilizada. img = cv2.imread('img/eng.jpg') _, compressedimage = cv2.imencode('.jpg', img, [1, 90]) f...
Python
zaydzuhri_stack_edu_python
comment Travis the ridiculous security system set knownUsers = list string Alice string Bob string Charlie string David string Ed string Frank string Gary string Henry while true begin print string Hi! My name is Travis set name = capitalize strip input string What is your name?: if name in knownUsers begin print forma...
#Travis the ridiculous security system knownUsers = ["Alice", "Bob", "Charlie", "David", "Ed", "Frank", "Gary", "Henry"] while True: print("Hi! My name is Travis") name = input("What is your name?: ").strip().capitalize() if name in knownUsers: print("Hello {}! Welcome!".format(name)) ...
Python
zaydzuhri_stack_edu_python
import abc import os import logging from datetime import datetime from system import system_channels from conversation_listeners.AbstractConversationListener import AbstractConversationListener set logger = call getLogger __name__ class _BaseMturkListener extends AbstractConversationListener begin string Base listener ...
import abc import os import logging from datetime import datetime from system import system_channels from conversation_listeners.AbstractConversationListener import AbstractConversationListener logger = logging.getLogger(__name__) class _BaseMturkListener(AbstractConversationListener): """ Base listener ...
Python
zaydzuhri_stack_edu_python
comment This file is meant for knowing what in Sage should be added to the database. function individual_graphs begin string Return a list of Sage commands building each 'individual graph' import inspect set l = list import sage.graphs.graph_generators set G = GraphGenerators set methods = list comprehension x for x i...
# This file is meant for knowing what in Sage should be added to the database. def individual_graphs(): r""" Return a list of Sage commands building each 'individual graph' """ import inspect l = [] import sage.graphs.graph_generators G = sage.graphs.graph_generators.GraphGenerators met...
Python
zaydzuhri_stack_edu_python
from IronWASP import * import re comment Extend the Module base class class HearbleedScanner extends Module begin comment Implement the StartModule method of Module class. This is the method called by IronWASP when user tries to launch the moduule from the UI. function StartModule self begin comment IronConsole is a CL...
from IronWASP import * import re #Extend the Module base class class HearbleedScanner(Module): #Implement the StartModule method of Module class. This is the method called by IronWASP when user tries to launch the moduule from the UI. def StartModule(self): #IronConsole is a CLI window where output can be pr...
Python
zaydzuhri_stack_edu_python
function get_symbols self begin return _symbol_list end function
def get_symbols(self): return self._symbol_list
Python
nomic_cornstack_python_v1
function ackley x begin set bias = 0.2 set ave_seq = sum list comprehension i - bias * i - bias for i in x / length x set ave_cos = sum list comprehension cos 2.0 * pi * i - bias for i in x / length x set value = - 20 * exp - 0.2 * square root ave_seq - exp ave_cos + 20.0 + e return value end function
def ackley(x): bias = 0.2 ave_seq = sum([(i - bias) * (i - bias) for i in x]) / len(x) ave_cos = sum([np.cos(2.0 * np.pi * (i - bias)) for i in x]) / len(x) value = -20 * np.exp(-0.2 * np.sqrt(ave_seq)) - np.exp(ave_cos) + 20.0 + np.e return value
Python
nomic_cornstack_python_v1
function inform_listeners self begin set d = call get_all_sorted for listener in listeners begin call stream_updated d end end function
def inform_listeners(self): d = self.get_all_sorted() for listener in self.listeners: listener.stream_updated(d)
Python
nomic_cornstack_python_v1
function update_discard_filter_text self min max begin set vol_min = min set vol_max = max try begin call setText call format_digits vol_max call setText call format_digits vol_min end except any begin pass end end function
def update_discard_filter_text(self, min, max): self.vol_min = min self.vol_max = max try: self.l_high_discard_filter_value.setText(self.format_digits(self.vol_max)) self.l_low_discard_filter_value.setText(self.format_digits(self.vol_min)) except: pass
Python
nomic_cornstack_python_v1
comment DeckSOLUTION.py comment Author: RoxAnn H. Stalvey comment Modified by Pharr from CardSOLUTION import Card from random import randrange class Deck begin function __init__ self begin set deck = list set suits = list string Clubs string Spades string Hearts string Diamonds for suit in suits begin for i in range 1...
# DeckSOLUTION.py # Author: RoxAnn H. Stalvey # Modified by Pharr from CardSOLUTION import Card from random import randrange class Deck: def __init__(self): self.deck = [] suits = ["Clubs", "Spades", "Hearts", "Diamonds"] for suit in suits: for i in range (1, 14): ...
Python
zaydzuhri_stack_edu_python
from numpy import * set N = integer input set A = list map int split input print 2 * N - 1 if absolute max A < absolute min A begin set x = argument minimum A for n in range N begin print x + 1 n + 1 end for n in range N - 1 begin print N - n N - n - 1 end end else begin set x = argument maximum A for n in range N begi...
from numpy import * N = int(input()) A = list(map(int,input().split())) print(2*N-1) if abs(max(A))<abs(min(A)): x = argmin(A) for n in range(N): print(x+1,n+1) for n in range(N-1): print(N-n,N-n-1) else: x = argmax(A) for n in range(N): print(x+1,n+1) for n in range(N-1): print(n+1,n+2)
Python
zaydzuhri_stack_edu_python
comment generator comment 如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢? comment 这样就不必创建完整的list,从而节省大量的空间。 comment 在Python中,这种一边循环一边计算的机制,称为生成器 comment 要创建一个generator,有很多种方法。 comment 第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator set L = list comprehension x * x for x in range 10 print L comment [0, 1, 4, 9, 16, 25, 36, 49,...
# generator # 如果列表元素可以按照某种算法推算出来,那我们是否可以在循环的过程中不断推算出后续的元素呢? # 这样就不必创建完整的list,从而节省大量的空间。 # 在Python中,这种一边循环一边计算的机制,称为生成器 # 要创建一个generator,有很多种方法。 ########################################################################### # 第一种方法很简单,只要把一个列表生成式的[]改成(),就创建了一个generator L = [x * x for x in range(10)] print(L) # [0, 1, 4, ...
Python
zaydzuhri_stack_edu_python
function _sum_of_terminal_adjacent_edges self begin set terminal_terminal_capacity_sum = 0.0 set terminal_vertex_capacity_sum = 0.0 for terminal in terminals begin set neighbors = graph at terminal for neighbor in neighbors begin if neighbor in terminals begin set terminal_terminal_capacity_sum = terminal_terminal_capa...
def _sum_of_terminal_adjacent_edges(self): terminal_terminal_capacity_sum = 0.0 terminal_vertex_capacity_sum = 0.0 for terminal in self.terminals: neighbors = self.graph[terminal] for neighbor in neighbors: if neighbor in self.terminals: ...
Python
nomic_cornstack_python_v1
function spawnPlayer player begin set room = random sample roomsList 1 at 0 comment Uncomment below to force spawn in a certain room set room = string 544 set room = room set players at name = player set status = PLAYING call sendToRoomNotPlayer player format string {0}{1} appears in a flash!{2} BLUE player WHITE call ...
def spawnPlayer( player ): room = random.sample(world.maps.World.roomsList, 1)[0] # Uncomment below to force spawn in a certain room room = "544" player.room = room world.maps.World.mapGrid[room].players[player.name] = player player.status = PLAYING sendToRoomNotPlay...
Python
nomic_cornstack_python_v1
function premik ukaz x y smer begin set smeri = string NESW set premiki = list tuple 0 - 1 tuple 1 0 tuple 0 1 tuple - 1 0 set ismer = index smeri smer if ukaz == string R begin set smer = smeri at ismer + 1 % 4 end else if ukaz == string L begin set smer = smeri at ismer - 1 % 4 end else begin set tuple dx dy = premik...
def premik(ukaz, x, y, smer): smeri = "NESW" premiki = [(0, -1), (1, 0), (0, 1), (-1, 0)] ismer = smeri.index(smer) if ukaz == "R": smer = smeri[(ismer + 1) % 4] elif ukaz == "L": smer = smeri[(ismer - 1) % 4] else: dx, dy = premiki[ismer] x += dx * ukaz...
Python
zaydzuhri_stack_edu_python
function findVal a b begin if b > 1 and a % b == 0 begin raise exception string Sorry. It's impossible to find a solution end return if expression b == 0 then a else a / b + call findVal b a % b end function function answer M F begin comment your code here try begin return call findVal call long M call long F - 2 end e...
def findVal(a, b): if (b > 1 and a % b == 0): raise Exception("Sorry. It's impossible to find a solution") return a if b == 0 else (a/b + findVal(b, a % b)) def answer(M, F): # your code here try: return findVal(long(M), long(F)) - 2 except: return "impossible"
Python
zaydzuhri_stack_edu_python
function nodeId self begin return power 2 _depth + _ordinal - 1 end function
def nodeId(self): return (pow(2,self._depth) + self._ordinal) - 1
Python
nomic_cornstack_python_v1
comment a1pr1.py - Assignment 1, Problem 1 comment Indexing and slicing puzzles comment This is an individual-only problem that you must complete on your own. comment List puzzles set pi = list 3 1 4 1 5 9 set e = list 2 7 1 comment Example puzzle (puzzle 0): comment Creating the list [2, 5, 9] from pi and e set answer...
# # a1pr1.py - Assignment 1, Problem 1 # # Indexing and slicing puzzles # # This is an individual-only problem that you must complete on your own. # # # List puzzles # pi = [3, 1, 4, 1, 5, 9] e = [2, 7, 1] # Example puzzle (puzzle 0): # Creating the list [2, 5, 9] from pi and e answer0 = [e[0]] + pi[-2:] # Solve...
Python
zaydzuhri_stack_edu_python
if choice == 1 begin exec read open string gamble7.py end if choice == 2 begin exec read open string blackjack.py end if choice == 3 begin exec read open string casinoroyale.py end else begin print string Please enter a valid option end
if (choice == 1): exec(open('gamble7.py').read()) if (choice == 2): exec(open('blackjack.py').read()) if (choice == 3): exec(open('casinoroyale.py').read()) else: print('Please enter a valid option')
Python
zaydzuhri_stack_edu_python
import pathlib import re import time from parser_module import Parse from ranker import Ranker import utils from word2vec import Word2vec class Searcher begin function __init__ self inverted_index stemming word2vec begin string :param inverted_index: dictionary of inverted index set parser = parse stemming set ranker =...
import pathlib import re import time from parser_module import Parse from ranker import Ranker import utils from word2vec import Word2vec class Searcher: def __init__(self, inverted_index, stemming, word2vec): """ :param inverted_index: dictionary of inverted index """ self.parse...
Python
zaydzuhri_stack_edu_python
function write_results_side_effect request begin class SideEffect begin set case = param function __call__ self *args **kwargs begin if case == string success begin return tuple dict string foo string bar set end else if case == string sigterm begin raise TermException end else begin raise RuntimeError end end function...
def write_results_side_effect(request): class SideEffect: case = request.param def __call__(self, *args, **kwargs): if self.case == "success": return ({"foo": "bar"}, set()) elif self.case == "sigterm": raise TermException else: ...
Python
nomic_cornstack_python_v1
function get_debug_firmware_id_string self begin comment Read the address via get_var_strict; this will fetch the value comment from chipdata as well, but we can ignore it. set chip_str = call get_var_strict string $_build_identifier_string set rawstr = call get_dm_const address size set decoded_str = string for chars...
def get_debug_firmware_id_string(self): # Read the address via get_var_strict; this will fetch the value # from chipdata as well, but we can ignore it. chip_str = self.chipdata.get_var_strict('$_build_identifier_string') rawstr = self.debuginfo.get_dm_const(chip_str.address, chip_str.siz...
Python
nomic_cornstack_python_v1
function main begin set parser = call ArgumentParser description=string Convert DJI P3 packets sniffed from a serial link into pcap format call add_argument string port1 help=string The serial port to read from call add_argument string port2 help=string The serial port to read from call add_argument string -b string --...
def main(): parser = argparse.ArgumentParser(description='Convert DJI P3 packets sniffed from a serial link into pcap format') parser.add_argument('port1', help='The serial port to read from') parser.add_argument('port2', help='The serial port to read from')...
Python
nomic_cornstack_python_v1
function soft_assert_bulk_verify_filter_ui_elements modal soft_assert begin set filter_section_element = call expand call expect exists string 'Reset to Default' button should be displayed in filter section. call expect call get_state_filter_options == list string Select All string In Review string Filter should contai...
def soft_assert_bulk_verify_filter_ui_elements(modal, soft_assert): filter_section_element = modal.filter_section.expand() soft_assert.expect( filter_section_element.reset_to_default_button.exists, "'Reset to Default' button should be displayed in filter section.") soft_assert.expect( filter_sec...
Python
nomic_cornstack_python_v1
class Solution begin function jump self nums begin set maxdest = decimal string -inf set pos = 0 set jump = 0 for i in range length nums - 1 begin comment calculate the max dest from the index set maxdest = max maxdest i + nums at i comment will get with min jump to reach destination if pos == i begin set pos = maxdest...
class Solution: def jump(self, nums: List[int]) -> int: maxdest = float("-inf") pos = 0 jump = 0 for i in range(len(nums) - 1): # calculate the max dest from the index maxdest = max(maxdest, i + nums[i]) # will get with min jump to re...
Python
zaydzuhri_stack_edu_python
from pyodbc_data import * import plotly.graph_objects as go from plotly import offline function small_basket begin set total_smallbasket = 0 set total_smallbasket1 = 0 set total_smallbasket2 = 0 for row in cursor begin if row at 5 begin set total_smallbasket = total_smallbasket + row at 5 end end for row in cursor1 beg...
from pyodbc_data import * import plotly.graph_objects as go from plotly import offline def small_basket(): total_smallbasket = 0 total_smallbasket1 = 0 total_smallbasket2 = 0 for row in cursor: if row[5]: total_smallbasket += (row[5]) for row in cursor1: ...
Python
zaydzuhri_stack_edu_python
function test_read_existing tmppath begin set fd = call get_tsta_file tmppath set tuple full_path fc = tuple fd at string full_path fd at string contents set xfile = call XRootDPyFile call mkurl full_path set res = read xfile assert res == encode fc comment After having read the entire file, the file pointer is at the ...
def test_read_existing(tmppath): fd = get_tsta_file(tmppath) full_path, fc = fd["full_path"], fd["contents"] xfile = XRootDPyFile(mkurl(full_path)) res = xfile.read() assert res == fc.encode() # After having read the entire file, the file pointer is at the # end of the file and consecutive ...
Python
nomic_cornstack_python_v1
function ciag x begin set s = 0 set s1 = 1 for i in range 1 x begin set s1 = s1 + s set s = s1 - s end return s1 end function function rek x begin if x < 3 begin return 1 end else begin return call rek x - 1 + call rek x - 2 end end function
def ciag(x): s = 0 s1 = 1 for i in range(1,x): s1 = s1 + s s = s1 - s return s1 def rek(x): if x < 3: return 1 else: return rek(x-1)+rek(x-2)
Python
zaydzuhri_stack_edu_python
function test_get_lm3_dist self dist begin call importorskip string lmoments3 set dc = call get_dist dist set lm3dc = call get_lm3_dist dist set par = params at dist set expected = call pdf inputs_pdf set values = call pdf inputs_pdf call assert_array_almost_equal values expected end function
def test_get_lm3_dist(self, dist): pytest.importorskip("lmoments3") dc = stats.get_dist(dist) lm3dc = stats.get_lm3_dist(dist) par = self.params[dist] expected = dc(**par).pdf(self.inputs_pdf) values = lm3dc(**par).pdf(self.inputs_pdf) np.testing.assert_array_almo...
Python
nomic_cornstack_python_v1
function guess num begin set a = input string Guess a Number if a == num begin print string SUCCESS end else begin call guess num end end function call guess 10
def guess(num): a = input("Guess a Number ") if a == num: print("SUCCESS") else: guess(num) guess(10)
Python
zaydzuhri_stack_edu_python
function spectrum spectrum_file bins values frequency=true limits=none wave_units=none value_units=none wave_name=none value_name=none error=none subtract_continuum_with_mask=none rebin_to=none begin comment Import a spectrum with bins set spectrum = read Table spectrum_file format=string ascii assert type wave_units i...
def spectrum(spectrum_file, bins, values, frequency=True, limits=None, wave_units=None, value_units=None, wave_name=None, value_name=None, error=None, subtract_continuum_with_mask=None, rebin_to=None): # Import a spectrum with bins spectrum = ap.table.Table.r...
Python
nomic_cornstack_python_v1
function place self begin assert not placed set placed = true save set counters = call process_analytics comment Poke a secret attribute on self for testing purposes set _placed_counters = counters end function
def place(self): assert not self.placed self.placed = True self.save() counters = self.process_analytics() # Poke a secret attribute on self for testing purposes self._placed_counters = counters
Python
nomic_cornstack_python_v1
function test_cons_restart self begin set body = dict string force false comment the function to be tested: set resp = post hmc string /api/console/operations/restart body true true assert enabled assert resp is none end function
def test_cons_restart(self): body = { 'force': False, } # the function to be tested: resp = self.urihandler.post( self.hmc, '/api/console/operations/restart', body, True, True) assert self.hmc.enabled assert resp is None
Python
nomic_cornstack_python_v1
import os comment 500개의 지원서가 있는곳으로 이동 change directory string C:\Users\student\Startcamp\TIL\02_Day comment 특정경로에 있는 모든 파일을 가져옴 set filenames = list directory string . for filename in filenames begin comment 확장자가 .txt인 파일만 이름을 바꾼다. comment 확장자만 따로 분리 set extension = call splitext filename at - 1 if extension == string ...
import os os.chdir(r'C:\Users\student\Startcamp\TIL\02_Day') #500개의 지원서가 있는곳으로 이동 filenames = os.listdir('.') #특정경로에 있는 모든 파일을 가져옴 for filename in filenames : #확장자가 .txt인 파일만 이름을 바꾼다. extension = os.path.splitext(filename)[-1] #확장자만 따로 분리 if extension == '.txt': os.rename(filename, file...
Python
zaydzuhri_stack_edu_python
string # Creating a list colors = ["blue", "turquoise", "pink", "orange", "black", "red", "lemon", "green", "brown"] # Use sqaure brackets !!!! print(colors) print(colors[0]) print(colors[1]) # Length of the list print("There are %d things in the ;ost." % len(colors)) # Changing Elements in a list colors[1] = "purple" ...
""" # Creating a list colors = ["blue", "turquoise", "pink", "orange", "black", "red", "lemon", "green", "brown"] # Use sqaure brackets !!!! print(colors) print(colors[0]) print(colors[1]) # Length of the list print("There are %d things in the ;ost." % len(colors)) # Changing Elements in a list colors[1] = "purple" ...
Python
zaydzuhri_stack_edu_python
function write writer value begin call writeString value end function
def write(writer: BitStreamWriter, value: str) -> None: writer.writeString(value)
Python
nomic_cornstack_python_v1
function log_first_n lvl msg n=1 name=none key=string caller begin if is instance key str begin set key = tuple key end assert length key > 0 set tuple caller_module caller_key = call _find_caller set hash_key = tuple if string caller in key begin set hash_key = hash_key + caller_key end if string message in key begin...
def log_first_n(lvl, msg, n=1, *, name=None, key="caller"): if isinstance(key, str): key = (key,) assert len(key) > 0 caller_module, caller_key = _find_caller() hash_key = () if "caller" in key: hash_key = hash_key + caller_key if "message" in key: hash_key = hash_key + ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment coding: utf-8 import numpy as np import statistics as stats import ipdb import pdb import traceback function similarity vecA vecB begin string https://en.wikipedia.org/wiki/Cosine_similarity from math import sqrt return dot vecA vecB / square root dot vecA vecA * dot vecB vecB end ...
#!/usr/bin/env python3 # coding: utf-8 import numpy as np import statistics as stats import ipdb import pdb import traceback def similarity(vecA:np.ndarray, vecB:np.ndarray)->np.float: """ https://en.wikipedia.org/wiki/Cosine_similarity """ from math import sqrt return np.dot(vecA, vecB)/sqrt(np.do...
Python
zaydzuhri_stack_edu_python
string Created on 2009-10-26 @author: Administrator import socket import time set clients = dict if __name__ == string __main__ begin set server = call socket AF_INET SOCK_STREAM set address = tuple string localhost 88 call bind address call listen 5 set flag = true while flag begin set client = call accept set client...
''' Created on 2009-10-26 @author: Administrator ''' import socket import time clients = {} if __name__ == '__main__': server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) address = 'localhost', 88 server.bind(address) server.listen(5) flag = True while flag: client = server.acc...
Python
zaydzuhri_stack_edu_python
function label2img predict begin set lbl = reshape argument maximum predict axis=- 1 SIZE set new_image = zeros tuple shape at 0 shape at 1 3 uint8 for color in color_dict begin set a = as type lbl == color uint8 set new_image at tuple slice : : slice : : 0 = new_image at tuple slice : : slice : : 0 + a * c...
def label2img(predict): lbl = np.argmax(predict,axis=-1).reshape(SIZE) new_image = np.zeros((lbl.shape[0],lbl.shape[1],3),np.uint8) for color in color_dict: a = (lbl == color).astype(np.uint8) new_image[:,:,0] += a*color_dict[color][0] new_image[:,:,1] += a*color_dict[color][1] ...
Python
nomic_cornstack_python_v1
comment coding: utf-8 comment ## 线性相关矩阵秩计算样例 comment In[2]: import numpy as np comment 定义2阶线性相关矩阵 set M1 = array list list 1 2 list 2 4 comment 定义2阶非线性相关矩阵 set M2 = array list list 3 5 list 4 1 comment 计算2*2线性相关矩阵的秩 set M1_rank = call matrix_rank M1 tol=none print string The rank of matrix M1 is M1_rank comment 计算2*2非线...
# coding: utf-8 # ## 线性相关矩阵秩计算样例 # In[2]: import numpy as np # 定义2阶线性相关矩阵 M1 = np.array([[1,2], [2,4]]) # 定义2阶非线性相关矩阵 M2 = np.array([[3,5], [4,1]]) # 计算2*2线性相关矩阵的秩 M1_rank = np.linalg.matrix_rank(M1, tol=None) print('The rank of matrix M1 is', M1_rank) # 计算2*2非线性相关矩阵的秩 M2_rank = np.linalg.matrix_rank(M2, tol=None...
Python
zaydzuhri_stack_edu_python
function to_hdf5 self path begin if not HDF5_INSTALLED begin raise call ImportError h5py_msg end set d = call _to_dict output=string hdf5 call save_dict d path string data end function
def to_hdf5(self, path): if not HDF5_INSTALLED: raise ImportError(h5py_msg) d = self._to_dict(output='hdf5') hdftools.save_dict(d, path, 'data')
Python
nomic_cornstack_python_v1
string Given a digit string excluded 01, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Cellphone Although the above answer is in lexicographical order, your answer could be in any order you want. Example Given ...
''' Given a digit string excluded 01, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Cellphone Although the above answer is in lexicographical order, your answer could be in any order you want. Example Given...
Python
zaydzuhri_stack_edu_python
function N_out K P S N_in begin return integer N_in + 2 * P - K / S + 1 end function
def N_out(K,P,S,N_in): return (int((N_in+2*P-K)/S)+1)
Python
nomic_cornstack_python_v1
function load_data self path=none begin if path is none begin assert _file_name is not none msg string Invaild file path ! end else begin set _file_name = path end return call __load_data end function
def load_data(self, path=None): if path is None: assert self._file_name is not None, "Invaild file path !" else: self._file_name = path return self.__load_data()
Python
nomic_cornstack_python_v1
function serialize self buff begin try begin set _x = self write buff call pack seq secs nsecs set _x = frame_id set length = length _x if python3 or type _x == unicode begin set _x = encode _x string utf-8 set length = length _x end if python3 begin write buff call pack string <I%sB % length length *_x end else begin ...
def serialize(self, buff): try: _x = self buff.write(_struct_3I.pack(_x.header.seq, _x.header.stamp.secs, _x.header.stamp.nsecs)) _x = self.header.frame_id length = len(_x) if python3 or type(_x) == unicode: _x = _x.encode('utf-8') length = len(_x) if python3: ...
Python
nomic_cornstack_python_v1
for ind in range n begin add wokabl lower input end set n = integer input set outset = set for ind in range n begin set words = list comprehension string word for word in split input for word in words begin if lower word not in wokabl begin if lower word not in outset begin print word end add outset lower word end end ...
for ind in range(n): wokabl.add(input().lower()) n = int(input()) outset = set() for ind in range(n): words = [str(word) for word in input().split()] for word in words: if word.lower() not in wokabl: if word.lower() not in outset: print(word) outset.add(w...
Python
zaydzuhri_stack_edu_python
function mirror_percentage self begin return get pulumi self string mirror_percentage end function
def mirror_percentage(self) -> Optional['outputs.VirtualServiceSpecHttpMirrorPercentage']: return pulumi.get(self, "mirror_percentage")
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 string ex7.py Author: Omar Amr Matr.Nr.: K11776960 Exercise 7 from ex6 import play comment This function takes the number of rounds to be player as input from the user. Then it calls the the plat function comment from ex6. Each round is accumulated to a string and eventually this string is...
#!/usr/bin/env python3 """ex7.py Author: Omar Amr Matr.Nr.: K11776960 Exercise 7 """ from ex6 import play # This function takes the number of rounds to be player as input from the user. Then it calls the the plat function # from ex6. Each round is accumulated to a string and eventually this string is written to "Res...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- import random function main begin set year = 2013 set month = 11 set day = 23 set hour = 22 for minute in range 60 begin for second in range 60 begin set d = tuple year month day hour minute second seed d set r = random integer 0 9 print d r end end end functi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import random def main(): year = 2013 month = 11 day = 23 hour = 22 for minute in range(60): for second in range(60): d = (year, month, day, hour, minute, second) random.seed(d) r = random.randint(0,9) ...
Python
zaydzuhri_stack_edu_python
function fix_environment_deviations self prefix spec deviations=none begin comment pragma: no cover pass end function
def fix_environment_deviations(self, prefix, spec, deviations=None): pass # pragma: no cover
Python
nomic_cornstack_python_v1
comment Želimo definirati pivotiranje na mestu za tabelo a. comment Ker bi želeli pivotirati zgolj dele tabele a, se hkrati omejimo na comment del tabele, ki se nahaja med indeksoma start in end. comment Na primer, za start = 0 in end = 8 tabelo comment [10, 4, 5, 15, 11, 2, 17, 0, 18] comment preuredimo v comment [0, ...
########################################################################## # Želimo definirati pivotiranje na mestu za tabelo a. # Ker bi želeli pivotirati zgolj dele tabele a, se hkrati omejimo na # del tabele, ki se nahaja med indeksoma start in end. # Na primer, za start = 0 in end = 8 tabelo # # [10, 4, 5, 15, 11, ...
Python
zaydzuhri_stack_edu_python
function handle_gui_example_five_intent self message begin set gui at string sampleText = string Loading.. call show_page string proportionalDelegateExample.qml end function
def handle_gui_example_five_intent(self, message): self.gui['sampleText'] = "Loading.." self.gui.show_page("proportionalDelegateExample.qml")
Python
nomic_cornstack_python_v1
function test_badconstructor self begin class Foo extends object begin function __init__ self one two begin pass end function end class call mapper Foo users set sess = call create_session assert raises TypeError Foo string one _sa_session=sess assert length list sess == 0 assert raises TypeError Foo string one end fun...
def test_badconstructor(self): class Foo(object): def __init__(self, one, two): pass mapper(Foo, users) sess = create_session() self.assertRaises(TypeError, Foo, 'one', _sa_session=sess) assert len(list(sess)) == 0 self.assertRaises(TypeError, ...
Python
nomic_cornstack_python_v1
function leftFixedPointMPO O Al tol begin set D = shape at 0 set d = shape at 1 comment construct handle for the action of the relevant operator and cast to linear operator set transferLeftHandleMPO = lambda v -> reshape call ncon tuple reshape v tuple D d D Al call conj Al O tuple list 5 3 1 list 1 2 - 3 list 5 4 - 1 ...
def leftFixedPointMPO(O, Al, tol): D = Al.shape[0] d = Al.shape[1] # construct handle for the action of the relevant operator and cast to linear operator transferLeftHandleMPO = lambda v: (ncon((v.reshape((D,d,D)), Al, np.conj(Al), O),([5, 3, 1], [1, 2, -3], [5, 4, -1], [3, 2, -2, 4]))).reshape(-1)...
Python
nomic_cornstack_python_v1
function create_X df begin set N = call nunique set M = call nunique set user_mapper = dictionary zip unique df at string userId list range N set movie_mapper = dictionary zip unique df at string movieId list range M set user_inv_mapper = dictionary zip list range N unique df at string userId set movie_inv_mapper = dic...
def create_X(df): N = df['userId'].nunique() M = df['movieId'].nunique() user_mapper = dict(zip(np.unique(df["userId"]), list(range(N)))) movie_mapper = dict(zip(np.unique(df["movieId"]), list(range(M)))) user_inv_mapper = dict(zip(list(range(N)), np.unique(df["userId"]))) movie_inv_mapper...
Python
nomic_cornstack_python_v1
string 適性レビュー表から取得 from bs4 import BeautifulSoup function get_course_suitability soup begin comment -----*----- コース適正を取得 -----*----- ## set selector = string #db_main_box > div.db_main_deta > div > div.db_prof_area_01 > div.db_prof_box > dl > dd > table > tr:nth-child(1) > td > img comment "苦手"の割合 return call get_ratio...
""" 適性レビュー表から取得 """ from bs4 import BeautifulSoup def get_course_suitability(soup): ## -----*----- コース適正を取得 -----*----- ## selector = '#db_main_box > div.db_main_deta > div > div.db_prof_area_01 > div.db_prof_box > dl > dd > table > tr:nth-child(1) > td > img' return get_ratio(soup, selector) # "苦手"の割合 ...
Python
zaydzuhri_stack_edu_python
function value self begin return get pulumi self string value end function
def value(self) -> str: return pulumi.get(self, "value")
Python
nomic_cornstack_python_v1
function __init__ self shell directory=none stale_check=_GH_STALE_CHECK **kwargs begin call __init__ directory if get kwargs string scripts_directory begin set _scripts_dir = kwargs at string scripts_directory set _force_created_scripts_dir = false end else begin set _scripts_dir = join path _container_dir string _scri...
def __init__(self, shell, directory=None, stale_check=_GH_STALE_CHECK, **kwargs): super(ContainerDir, self).__init__(directory) if kwargs.get("scripts_directory"): self._scripts_dir = kwargs["scripts_directory"] ...
Python
nomic_cornstack_python_v1
function constant_time_compare val1 val2 begin set len_eq = length val1 == length val2 if len_eq begin set result = 0 set left = val1 end else begin set result = 1 set left = val2 end comment even with compare_digest it's not clear whether it properly comment compares strings of differing lengths using constant-time co...
def constant_time_compare(val1, val2): len_eq = len(val1) == len(val2) if len_eq: result = 0 left = val1 else: result = 1 left = val2 # even with compare_digest it's not clear whether it properly # compares strings of differing lengths using constant-time ...
Python
nomic_cornstack_python_v1
import glob import sys import os import argparse import codecs import logging call basicConfig format=string %(asctime)-15s [%(name)s] %(levelname)s: %(message)s level=ERROR set logger = call getLogger __name__ set parser = call ArgumentParser description=string Convert plain files to two-column format. formatter_class...
import glob import sys import os import argparse import codecs import logging logging.basicConfig(format='%(asctime)-15s [%(name)s] %(levelname)s: %(message)s', level=logging.ERROR) logger = logging.getLogger(__name__) parser = argparse.ArgumentParser(description='Convert plain files to two-column format.', ...
Python
zaydzuhri_stack_edu_python
while t begin set tuple n c k = list comprehension integer x for x in split input set a = list comprehension integer x for x in split input set pre_a_sum = list append pre_a_sum a at 0 for i in range 1 n begin append pre_a_sum pre_a_sum at i - 1 + a at i end set f = 0 for i in range n begin set tuple s e ans = tuple i...
while t: n, c, k = [int(x) for x in input().split()] a = [int(x) for x in input().split()] pre_a_sum = [] pre_a_sum.append(a[0]) for i in range(1, n): pre_a_sum.append(pre_a_sum[i-1] + a[i]) f = 0 for i in range(n): s, e, ans = i, n-1, i-1 sc = 0 if i != 0:...
Python
zaydzuhri_stack_edu_python
import pygame import os from grand_staff import * import random class CPainter begin string Class to paint the GUI set STAFF_LINE_INTERVAL = 50 set STAFF_LINE_LENGTH = STAFF_LINE_INTERVAL * 15 set STAFF_LINE_WIDTH = 3 set STAFF_X = STAFF_LINE_INTERVAL * 3 set STAFF_Y = STAFF_LINE_INTERVAL / 2 set LEDGER_LINE_LENGTH = S...
import pygame; import os; from grand_staff import *; import random; class CPainter(): """ Class to paint the GUI """ STAFF_LINE_INTERVAL = 50; STAFF_LINE_LENGTH = STAFF_LINE_INTERVAL * 15; STAFF_LINE_WIDTH = 3; STAFF_X = STAFF_LINE_INTERVAL*3; STAFF_Y = STAFF_LINE_INTERVAL/2; LED...
Python
zaydzuhri_stack_edu_python
class Vertex begin function __init__ self key value begin set id = key set value = value set connectedTo = dict set color = string white end function function addNeigh self nbr weight=0 begin set connectedTo at nbr = weight end function function getColor self begin return color end function function setColor self colo...
class Vertex: def __init__(self,key,value): self.id = key self.value = value self.connectedTo = {} self.color = 'white' def addNeigh(self,nbr,weight=0): self.connectedTo[nbr]=weight def getColor(self): return self.color def setColor(self,color): s...
Python
zaydzuhri_stack_edu_python
function post_lookup_new begin return call do_lookup body_to_adapter end function
def post_lookup_new(): return do_lookup(body_to_adapter)
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import ast function main begin set paths = call literal_eval input string Enter paths: set out_path = set set in_path = set for tuple city_a city_b in paths begin add out_path city_a add in_path city_b end for city in in_path begin if city not in out_path begin print city return end end en...
#!/usr/bin/env python3 import ast def main() -> None: paths = ast.literal_eval(input("Enter paths: ")) out_path = set() in_path = set() for city_a, city_b in paths: out_path.add(city_a) in_path.add(city_b) for city in in_path: if city not in out_path: print(c...
Python
zaydzuhri_stack_edu_python
function get_wind_speed self begin if has_anemometer begin set ws = query self GET_WINDSPEED set ws = ws * 0.84 comment The manual says to add 3 km/h to the reading but that seems off. comment ws += 3 * u.km / u.hour return ws end else begin return none end end function
def get_wind_speed(self) -> float | None: if self.has_anemometer: ws = self.query(WeatherCommand.GET_WINDSPEED) ws *= 0.84 # The manual says to add 3 km/h to the reading but that seems off. # ws += 3 * u.km / u.hour return ws else: ...
Python
nomic_cornstack_python_v1
function resolve_json_id self json_id allow_no_match=false begin string Given an id found in scraped JSON, return a DB id for the object. params: json_id: id from json allow_no_match: just return None if id can't be resolved returns: database id raises: ValueError if id couldn't be resolved if not json_id begin return ...
def resolve_json_id(self, json_id, allow_no_match=False): """ Given an id found in scraped JSON, return a DB id for the object. params: json_id: id from json allow_no_match: just return None if id can't be resolved returns: ...
Python
jtatman_500k
comment encoding: utf-8 string Name: tools/files.py Desc: File Handling Note: import os import zipfile import shutil comment 判斷檔案/資料夾是否存在 function exist_or_not file_dir begin if not is directory path file_dir begin return false end return true end function comment 新增資料夾 function create_dir dir_path begin make directory...
# encoding: utf-8 """ Name: tools/files.py Desc: File Handling Note: """ import os import zipfile import shutil # 判斷檔案/資料夾是否存在 def exist_or_not(file_dir): if not os.path.isdir(file_dir): return False return True # 新增資料夾 def create_dir(dir_path): os.mkdir(dir_path) # 移除資料夾 def remove_dir(dir_path...
Python
zaydzuhri_stack_edu_python
comment def create_class(name): comment if name=='user': comment class User: comment def __str__(self): comment return "user" comment return User comment #type动态创建类 comment # User =type("User",(),{}) comment class BaseClass(): comment def answer(self): comment return 'i am user' comment def say(self): comment return 'i...
# def create_class(name): # if name=='user': # class User: # def __str__(self): # return "user" # return User # #type动态创建类 # # User =type("User",(),{}) # # class BaseClass(): # def answer(self): # return 'i am user' # # def say(self): # return 'i am method...
Python
zaydzuhri_stack_edu_python
function peaks_from_info bam_fileobj wiggle pos_counts lengths interval gene_length max_gap=25 fdr_alpha=0.05 binom_alpha=0.001 method=string random user_threshold=none minreads=20 poisson_cutoff=0.05 plotit=false width_cutoff=10 windowsize=1000 SloP=false correct_p=false max_width=none min_width=none algorithm=string ...
def peaks_from_info(bam_fileobj, wiggle, pos_counts, lengths, interval, gene_length, max_gap=25, fdr_alpha=0.05, binom_alpha=0.001, method="random" ,user_threshold=None, minreads=20, poisson_cutoff=0.05, plotit=False, width_cutoff=10, windowsize=1000, SloP=F...
Python
nomic_cornstack_python_v1
import numpy as np import math import random class EGreedy_TS begin function __init__ self alpha begin set alpha = alpha set articles_clicks = dictionary set articles_impressions = dictionary set articles_mean = dictionary set articles_var = dictionary end function function add_new_article self article_id begin if arti...
import numpy as np import math import random class EGreedy_TS: def __init__(self, alpha): self.alpha = alpha self.articles_clicks = dict() self.articles_impressions = dict() self.articles_mean = dict() self.articles_var = dict() def add_new_article(self, article_id): if article_id not in self.article...
Python
zaydzuhri_stack_edu_python
try begin set f = open path end except FileNotFoundError begin print string I can't find your file. Check the path.. end try else begin set lines = read lines f set lines_number = length lines print string Number of line: lines_number close f end
try: f = open(path) except FileNotFoundError: print("I can't find your file. Check the path..") else: lines = f.readlines() lines_number =len(lines) print("Number of line: ", lines_number) f.close()
Python
zaydzuhri_stack_edu_python
comment Redes 2 comment Practica 3 comment videoUDP.py comment Carlos Hojas García-Plaza y Sergio Cordero Rojas comment Se encuentran todas las funciones que se encarga del envio y recpecion UDP import queue import socket import cv2 from PIL import Image , ImageTk import numpy as np import time class videoUDP begin com...
##### # Redes 2 # Practica 3 # videoUDP.py # # Carlos Hojas García-Plaza y Sergio Cordero Rojas # # Se encuentran todas las funciones que se encarga del envio y recpecion UDP # ##### import queue import socket import cv2 from PIL import Image, ImageTk import numpy as np import time class videoUDP: # puertos puerto...
Python
zaydzuhri_stack_edu_python
function create_full_set cls categories profile=none begin set element_lists = list for tuple category_name element_names in items categories begin set category = call create name=category_name append element_lists list comprehension call create category=category name=element_name for element_name in element_names end...
def create_full_set(cls, categories, profile=None): element_lists = [] for category_name, element_names in categories.items(): category = CategoryFactory.create(name=category_name) element_lists.append( [ ElementFactory.create(category=...
Python
nomic_cornstack_python_v1
function get_root_hosts self begin set rules = call _get_rules return call _xmltree_to_list rules string root string name end function
def get_root_hosts(self): rules = self._get_rules() return self.filer._xmltree_to_list(rules, 'root', 'name')
Python
nomic_cornstack_python_v1
function has_param_with_name self param_name begin return param_name in params end function
def has_param_with_name(self, param_name): return param_name in self.params
Python
nomic_cornstack_python_v1
comment def greet_name(names): comment for name in names: comment message = f"Hi, {name.title()}!" comment print (message) comment username = ['Vikram', 'crystal', 'abhishek'] comment greet_name(username) set unprinted_designs = list string phone case string robot pendant string dodecahedron set completed_models = list...
# def greet_name(names): # for name in names: # message = f"Hi, {name.title()}!" # print (message) # username = ['Vikram', 'crystal', 'abhishek'] # greet_name(username) # unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron'] completed_models = [] while unprinted_designs: current_design = unprinted...
Python
zaydzuhri_stack_edu_python
import re set phoneNumRegex = compile string (\(\d{3}\))-(\d{3}-\d{4}) set mo = search string this string has my num (503)-312-7679 print string phone number is { call group } print string mo.group(1) : { call group 1 } print string mo.group(2) : { call group 2 } print string mo.group(0) : { call group 0 } print string...
import re phoneNumRegex = re.compile(r'(\(\d{3}\))-(\d{3}-\d{4})') mo = phoneNumRegex.search('this string has my num (503)-312-7679') print(f'phone number is {mo.group()}') print(f'mo.group(1) : {mo.group(1)}') print(f'mo.group(2) : {mo.group(2)}') print(f'mo.group(0) : {mo.group(0)}') print(f'mo.groups() : {mo....
Python
zaydzuhri_stack_edu_python
from collections import Counter import statistics function calculate_mean_median_mode numbers begin set mean = sum numbers / length numbers set sorted_numbers = sorted numbers if length sorted_numbers % 2 == 0 begin set median = sorted_numbers at length sorted_numbers // 2 - 1 + sorted_numbers at length sorted_numbers ...
from collections import Counter import statistics def calculate_mean_median_mode(numbers): mean = sum(numbers) / len(numbers) sorted_numbers = sorted(numbers) if len(sorted_numbers) % 2 == 0: median = (sorted_numbers[len(sorted_numbers)//2 - 1] + sorted_numbers[len(sorted_numbers)//2]) / 2 ...
Python
greatdarklord_python_dataset
comment Question: Big Bang Secrets comment Programmer: Het Patel comment Teacher: Mr. Veera comment Course: ICS4U0 comment Date Written: 10/1/20 comment Purpose: To output a decoded version of the text inputted by the user depending on the amount to shift the characters by. comment Asks the user to input the k value wh...
#Question: Big Bang Secrets #Programmer: Het Patel #Teacher: Mr. Veera #Course: ICS4U0 #Date Written: 10/1/20 #Purpose: To output a decoded version of the text inputted by the user depending on the amount to shift the characters by. k_value=int(input('Value of K: ')) #Asks the user to input the k value which is...
Python
zaydzuhri_stack_edu_python
function BindingStatus_fromString *args begin return call BindingStatus_fromString *args end function
def BindingStatus_fromString(*args): return _libsbml.BindingStatus_fromString(*args)
Python
nomic_cornstack_python_v1
from rpsClasses import Player , Roll , Rock , Paper , Scissors import random function print_header begin print string ------------------------- print string ---ROCK PAPER SCISSORS--- print string ------------------------- print end function function get_players_name begin return input string Enter username: end functio...
from rpsClasses import Player, Roll, Rock, Paper, Scissors import random def print_header(): print('-------------------------') print('---ROCK PAPER SCISSORS---') print('-------------------------') print() def get_players_name(): return input("Enter username: ") def build_the_three_rolls(): rolls = [ Rock('...
Python
zaydzuhri_stack_edu_python
function projector_sync_send_data projector_id collection_elements begin comment Load the projector object. If broadcast is on, use the broadcast projector comment instead. if config at string projector_broadcast > 0 begin set projector_id = config at string projector_broadcast end set projector = get objects pk=projec...
def projector_sync_send_data(projector_id: int, collection_elements: List[CollectionElement]) -> List[Any]: # Load the projector object. If broadcast is on, use the broadcast projector # instead. if config['projector_broadcast'] > 0: projector_id = config['projector_broadcast'] projector = Proj...
Python
nomic_cornstack_python_v1
comment -*- coding:utf-8 -*- class Node extends object begin function __init__ self col_name split_node gini_result ID begin set col_name = col_name set split_node = split_node set gini_result = gini_result set leftNode = none set rightNode = none set id = ID end function end class class Leaf extends object begin funct...
# -*- coding:utf-8 -*- class Node(object): def __init__(self,col_name,split_node,gini_result,ID): self.col_name = col_name self.split_node = split_node self.gini_result = gini_result self.leftNode = None self.rightNode = None self.id = ID class Leaf(object): ...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python string Pass in activity primitive representation. E.g. python -m part2.tfidf file4 import sys import config from sklearn.feature_extraction.text import TfidfTransformer import numpy as np import pandas as pd
#! /usr/bin/env python ''' Pass in activity primitive representation. E.g. python -m part2.tfidf file4 ''' import sys import config from sklearn.feature_extraction.text import TfidfTransformer import numpy as np import pandas as pd
Python
zaydzuhri_stack_edu_python
function kills self kills begin set _kills = kills end function
def kills(self, kills): self._kills = kills
Python
nomic_cornstack_python_v1
function name self name begin pass end function
def name(self, name): pass
Python
nomic_cornstack_python_v1
function test_update_supply_user self begin set is_checked = is_checked assert false is_checked set url = reverse string inventories:supplies-details-update args=list id id set request = patch url dict string is_checked true call force_authenticate request user=test_user set response = call call as_view request invento...
def test_update_supply_user(self): is_checked = InventorySupply.objects.get(pk=self.test_inventory_supply.id).is_checked self.assertFalse(is_checked) url = reverse("inventories:supplies-details-update", args=[self.test_report.id, self.test_supply.id]) request = self.factory.patch(url, {'...
Python
nomic_cornstack_python_v1
function get_win_target best_of begin return best_of // 2 + 1 end function
def get_win_target(best_of): return (best_of // 2) + 1
Python
nomic_cornstack_python_v1
function getnumbaranz self begin set nz_ = call c_int64 set res = call MSK_XX_getnumbaranz __nativep call byref nz_ if res != 0 begin set tuple _ msg = call __getlasterror res raise error call rescode res msg end set nz_ = value set _nz_return_value = nz_ return _nz_return_value end function
def getnumbaranz(self): nz_ = ctypes.c_int64() res = __library__.MSK_XX_getnumbaranz(self.__nativep,ctypes.byref(nz_)) if res != 0: _,msg = self.__getlasterror(res) raise Error(rescode(res),msg) nz_ = nz_.value _nz_return_value = nz_ return (_nz_return_value)
Python
nomic_cornstack_python_v1
function kaiser_beta a begin if a > 50 begin set beta = 0.1102 * a - 8.7 end else if a > 21 begin set beta = 0.5842 * a - 21 ^ 0.4 + 0.07886 * a - 21 end else begin set beta = 0.0 end return beta end function
def kaiser_beta(a): if a > 50: beta = 0.1102 * (a - 8.7) elif a > 21: beta = 0.5842 * (a - 21) ** 0.4 + 0.07886 * (a - 21) else: beta = 0.0 return beta
Python
nomic_cornstack_python_v1
import re class BagProcessor extends object begin function __init__ self input_file=string input.txt begin set input_file = input_file set num = 0 end function function execute self begin set all_bags = call read_rules return call get_num_bags all_bags string shiny gold - 1 end function function read_rules self begin s...
import re class BagProcessor(object): def __init__(self, input_file='input.txt'): self.input_file = input_file self.num = 0 def execute(self): all_bags = self.read_rules() return self.get_num_bags(all_bags, 'shiny gold') - 1 def read_rules(self): parent_exp = re.c...
Python
zaydzuhri_stack_edu_python
function test_list_date_time_min_length_2_nistxml_sv_iv_list_date_time_min_length_3_3 mode save_output output_format begin call assert_bindings schema=string nistData/list/dateTime/Schema+Instance/NISTSchema-SV-IV-list-dateTime-minLength-3.xsd instance=string nistData/list/dateTime/Schema+Instance/NISTXML-SV-IV-list-da...
def test_list_date_time_min_length_2_nistxml_sv_iv_list_date_time_min_length_3_3(mode, save_output, output_format): assert_bindings( schema="nistData/list/dateTime/Schema+Instance/NISTSchema-SV-IV-list-dateTime-minLength-3.xsd", instance="nistData/list/dateTime/Schema+Instance/NISTXML-SV-IV-list-dat...
Python
nomic_cornstack_python_v1
function test_list_date_time_pattern_2_nistxml_sv_iv_list_date_time_pattern_3_4 mode save_output output_format begin call assert_bindings schema=string nistData/list/dateTime/Schema+Instance/NISTSchema-SV-IV-list-dateTime-pattern-3.xsd instance=string nistData/list/dateTime/Schema+Instance/NISTXML-SV-IV-list-dateTime-p...
def test_list_date_time_pattern_2_nistxml_sv_iv_list_date_time_pattern_3_4(mode, save_output, output_format): assert_bindings( schema="nistData/list/dateTime/Schema+Instance/NISTSchema-SV-IV-list-dateTime-pattern-3.xsd", instance="nistData/list/dateTime/Schema+Instance/NISTXML-SV-IV-list-dateTime-pa...
Python
nomic_cornstack_python_v1
function update_permissions_for_existing_gdrive_user request begin set logger = call get_logger info string [resource_management/gdrive_views.py update_permissions_for_existing_gdrive_user()] request.POST= { POST } call validate_request_to_update_gdrive_permissions request set gdrive = call GoogleDrive GOOGLE_WORKSPACE...
def update_permissions_for_existing_gdrive_user(request): logger = Loggers.get_logger() logger.info( "[resource_management/gdrive_views.py update_permissions_for_existing_gdrive_user()] " f"request.POST={request.POST}" ) validate_request_to_update_gdrive_permissions(request) gdrive =...
Python
nomic_cornstack_python_v1
import random import math import colorsys from _base_classes import Animation class Feynman extends Animation begin set RESET_RGB = none set NB_CYCLES_PER_ANIMATION = 1 set VARIETY = 3 function __init__ self rainbow begin call __init__ rainbow if random < 0.5 begin set run_step = run_interval end else begin set run_per...
import random import math import colorsys from _base_classes import Animation class Feynman(Animation): RESET_RGB = None NB_CYCLES_PER_ANIMATION = 1 VARIETY = 3 def __init__(self, rainbow): super(self.__class__, self).__init__(rainbow) if random.random() < 0.5: self.ru...
Python
zaydzuhri_stack_edu_python
function reason_to_be_disabled cls begin comment Assume by default the given decoder is always enabled. return none end function
def reason_to_be_disabled(cls): # Assume by default the given decoder is always enabled. return None
Python
nomic_cornstack_python_v1
function find_sum numbers begin set total = 0 for num in numbers begin if not is instance num tuple int float begin raise call ValueError string Invalid input: non-numeric value found. end if num > 0 begin set total = total + num end end return total end function
def find_sum(numbers): total = 0 for num in numbers: if not isinstance(num, (int, float)): raise ValueError("Invalid input: non-numeric value found.") if num > 0: total += num return total
Python
jtatman_500k
comment -*- coding: utf-8 -*- import requests import pprint from passpacker import passwords as public_passwords class ChatworkApi begin function __init__ self passwords=none begin set passwords = passwords or public_passwords set api_key = passwords at string chatwork_api_key set chat_id = passwords at string chatwork...
# -*- coding: utf-8 -*- import requests import pprint from passpacker import passwords as public_passwords class ChatworkApi(): def __init__(self, passwords=None): passwords = passwords or public_passwords self.api_key = passwords['chatwork_api_key'] self.chat_id = passwords['chatwork_chat...
Python
zaydzuhri_stack_edu_python