code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function last_word_dict self rhyme_dict begin set scheme = dict 1 string A ; 2 string B ; 3 string A ; 4 string B ; 5 string C ; 6 string D ; 7 string C ; 8 string D ; 9 string E ; 10 string F ; 11 string E ; 12 string F ; 13 string G ; 14 string G set last_word_dict = dict string for i in range(1,15): temp = [] if i ...
def last_word_dict(self, rhyme_dict): scheme = {1: 'A', 2: 'B', 3: 'A', 4: 'B', 5: 'C', 6: 'D', 7: 'C', 8: 'D', 9: 'E', 10: 'F', 11: 'E', 12: 'F', 13: 'G', 14: 'G'} last_word_dict={} """for i in range(1,15): temp = [] if i in [1,2,5,6,9,10,13]: #lines with a new rhyme ...
Python
nomic_cornstack_python_v1
import math import itertools function find_factors n begin set factors = set add factors 1 for i in call xrange 2 integer square root n + 1 begin if n % i == 0 begin add factors i add factors n / i end end return factors end function set abundant = set set perfect = set set deficient = set for i in call xrange 1 30000 ...
import math import itertools def find_factors(n): factors = set() factors.add(1) for i in xrange(2,int(math.sqrt(n))+1): if n % i == 0: factors.add(i) factors.add(n/i) return factors abundant = set() perfect = set() deficient = set() for i in xrange(1,30000): sum_for_i = sum(find_factors(...
Python
zaydzuhri_stack_edu_python
function street_name self begin return _street_name end function
def street_name(self): return self._street_name
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string ------------------------------------------------- File Name: 一些力扣没有的面试题 Description : Author : amilyxy date: 2020/10/1 ------------------------------------------------- string 1.平方后不重复元素 desc:给定一个有序数组,返回平方之后不重复的元素 nums = [-5,-3,-1,-1,0,1,1,1,2] comment 双指针方法一:遍历取绝对值最大,记录上一个数 functio...
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: 一些力扣没有的面试题 Description : Author : amilyxy date: 2020/10/1 ------------------------------------------------- """ ''' 1.平方后不重复元素 desc:给定一个有序数组,返回平方之后不重复的元素 nums = [-5,-3,-1,-1,0,1,1,1,2] ''' # 双指针方...
Python
zaydzuhri_stack_edu_python
set car = 100 set space_in_a_car = 4.0 set drivers = 30 set passengers = 100 set car_not_driven = car - drivers set average = passengers / drivers print string There are car_not_driven string cars not driven print string We have drivers string drivers print string average passenger: average
car=100 space_in_a_car=4.0 drivers=30 passengers=100 car_not_driven = car - drivers average=passengers/drivers print("There are", car_not_driven, "cars not driven") print("We have", drivers ,"drivers") print("average passenger: ", average)
Python
zaydzuhri_stack_edu_python
function filter_content self begin set pred = call predict_token_label set ret = list compress filter lambda token -> not starts with token string < and ends with token string > tokens pred return ret end function
def filter_content(self): pred = self.predict_token_label() ret = list(itertools.compress( filter(lambda token:not(token.startswith('<') and token.endswith('>')),self.tokens), pred)) return ret
Python
nomic_cornstack_python_v1
import enum from abc import ABC from app.model.exception.exceptions import InvalidTypeException class TransitionType extends Enum begin set Start = tuple 0 set LoginSuccess = tuple 1 set LoginFailure = tuple 2 set CaptchaSuccess = tuple 3 set CaptchaFailure = tuple 4 set SlotOpen = tuple 5 set SlotClose = 6 end class c...
import enum from abc import ABC from app.model.exception.exceptions import InvalidTypeException class TransitionType(enum.Enum): Start = 0, LoginSuccess = 1, LoginFailure = 2, CaptchaSuccess = 3, CaptchaFailure = 4, SlotOpen = 5, SlotClose = 6 class AnotherTransitionType(enum.Enum): ...
Python
zaydzuhri_stack_edu_python
function enable_syslog_logging logger syslog_host syslog_port begin comment Standard Library from logging.handlers import SysLogHandler add logger call SysLogHandler address=tuple string syslog_host syslog_port format=_FMT_BASIC enqueue=true debug string Logging to syslog target {}:{} enabled string syslog_host string ...
def enable_syslog_logging(logger, syslog_host, syslog_port): # Standard Library from logging.handlers import SysLogHandler logger.add( SysLogHandler(address=(str(syslog_host), syslog_port)), format=_FMT_BASIC, enqueue=True, ) logger.debug( "Logging to syslog target ...
Python
nomic_cornstack_python_v1
import json from tkinter import * from functools import partial comment requires tk set UPDATE_MS = integer 1000 / 6 set buttonLabels = list string BUTTON1 string BUTTON2 string BUTTON3 string BUTTON4 string BUTTON5 string BUTTON6 string RIGHT string UP string DOWN string LEFT set buttonPlaces = list tuple 376 248 tupl...
import json from tkinter import * from functools import partial #requires tk UPDATE_MS = int(1000/6) buttonLabels = ["BUTTON1", "BUTTON2", "BUTTON3", "BUTTON4", "BUTTON5", "BUTTON6", "RIGHT", "UP", "DOWN", "LEFT"] buttonPlaces = [(376,248), (430,208), (499,210), (564,218), (180,259), (618,355), (418,115), (3...
Python
zaydzuhri_stack_edu_python
from typing import Dict , Any class FilaPrioritaria begin set codigo = 0 set fila = list set clientes_atendidos = list set senha_atual = none function gera_senha_atual self begin set senha_atual = string NM { codigo } end function function reseta_fila self begin if codigo >= 100 begin set codigo = 0 end else begin se...
from typing import Dict, Any class FilaPrioritaria: codigo = 0 fila = [] clientes_atendidos = [] senha_atual = None def gera_senha_atual(self) -> None: self.senha_atual = f'NM{self.codigo}' def reseta_fila(self) -> None: if self.codigo >= 100: self.codigo = 0 ...
Python
zaydzuhri_stack_edu_python
from collections import deque set dirs = list tuple 0 - 1 tuple 0 1 tuple - 1 0 tuple 1 0 function BFS begin set count = 0 set que = deque list tuple 0 0 while que begin set tuple i j = call popleft for d in range 4 begin if 0 <= i + dirs at d at 0 < N and 0 <= j + dirs at d at 1 < M begin if not visit at i + dirs at d...
from collections import deque dirs = [(0, -1), (0, 1), (-1, 0), (1, 0)] def BFS(): count = 0 que = deque([(0, 0)]) while que: i, j = que.popleft() for d in range(4): if 0 <= i + dirs[d][0] < N and 0 <= j + dirs[d][1] < M: if not visit[i + dirs[d][0]][j + dirs[d]...
Python
zaydzuhri_stack_edu_python
function dfs_iterative graph root begin set stack = list root set V = set while stack begin set current = pop stack if current not in V begin add V current comment ------ in case of adj_matrix (Comment the below section) ------ for tuple i neighbour in enumerate graph at current begin if neighbour == 1 and i not in V b...
def dfs_iterative(graph, root): stack = [root] V = set() while stack: current = stack.pop() if current not in V: V.add(current) # ------ in case of adj_matrix (Comment the below section) ------ for i,neighbour in enumerate(graph[current]): ...
Python
zaydzuhri_stack_edu_python
function calc_duration_rms self duration osc_freq osc_damping m0 m1 m2 begin del tuple osc_freq osc_damping m0 m1 m2 return duration end function
def calc_duration_rms(self, duration, osc_freq, osc_damping, m0, m1, m2): del (osc_freq, osc_damping, m0, m1, m2) return duration
Python
nomic_cornstack_python_v1
function test_update_log caplog mock_empty_os_environ mock_settings_file begin set tuple settings_file_path expected = mock_settings_file set climate = call Climate prefix=string TEST_STUFF settings_files=tuple settings_file_path assert update_log == string msg string before updating, the update log should be empty up...
def test_update_log(caplog, mock_empty_os_environ, mock_settings_file): settings_file_path, expected = mock_settings_file climate = core.Climate(prefix="TEST_STUFF", settings_files=(settings_file_path,)) assert climate.update_log == "", "before updating, the update log should be empty" climate.update({"...
Python
nomic_cornstack_python_v1
function version_check self begin comment anchor_matcher --> matcher if has attribute self string anchor_matcher begin set matcher = anchor_matcher end if has attribute self string head_in_features begin set in_features = head_in_features end if has attribute self string test_topk_candidates begin set topk_candidates =...
def version_check(self): # anchor_matcher --> matcher if hasattr(self, "anchor_matcher"): self.matcher = self.anchor_matcher if hasattr(self, "head_in_features"): self.in_features = self.head_in_features if hasattr(self, "test_topk_candidates"): self.topk_candidates = self.test_t...
Python
nomic_cornstack_python_v1
string Utility file to seed postman_routes database data in seed_data/ from sqlalchemy import func from model import User , Collection , Route , BboxGeometry , EdgesGeometry , NodesGeometry , RouteGeometry import datetime from model import connect_to_db , db from server import app import json from werkzeug.security imp...
"""Utility file to seed postman_routes database data in seed_data/""" from sqlalchemy import func from model import ( User, Collection, Route, BboxGeometry, EdgesGeometry, NodesGeometry, RouteGeometry, ) import datetime from model import connect_to_db, db from server import app import json ...
Python
zaydzuhri_stack_edu_python
from random import randint print string - * 23 print format string {:-^23} string Exercício 074 print string - * 23 set values = tuple random integer 0 10 random integer 0 10 random integer 0 10 random integer 0 10 random integer 0 10 print string Os valores sorteados foram: end=string for value in values begin print v...
from random import randint print('-' * 23) print('{:-^23}'.format(' Exercício 074 ')) print('-' * 23) values = (randint(0, 10), randint(0, 10), randint(0, 10), randint(0, 10), randint(0, 10)) print(f'Os valores sorteados foram: ', end='') for value in values: print(value, end=' ') print(f'\nO maior valor sortea...
Python
zaydzuhri_stack_edu_python
function difference self begin return string baseline end function
def difference(self): return "baseline"
Python
nomic_cornstack_python_v1
function reset self pingroup=none begin try begin GPIO end except NameError begin comment print("GPIO is not defined, the pins were not reset!") pass end try else begin comment If None, reset all pins if pingroup is none begin call reset stepper call reset led call reset solenoid end else if pingroup == led begin comme...
def reset(self,pingroup=None): try: GPIO except NameError: #print("GPIO is not defined, the pins were not reset!") pass else: if pingroup is None: # If None, reset all pins self.reset(PINGROUP.stepper) self.reset(PINGROUP.led) self.reset(PINGROUP.solenoid) elif pingroup == PINGROUP.led...
Python
nomic_cornstack_python_v1
function choose_mll_class model_class state_dict=none refit=true begin comment NOTE: We currently do not support `ModelListGP`. This code block will only comment be relevant once we support `ModelListGP`. if state_dict is none or refit and is subclass model_class ModelListGP begin return SumMarginalLogLikelihood end re...
def choose_mll_class( model_class: Type[Model], state_dict: Optional[Dict[str, Tensor]] = None, refit: bool = True, ) -> Type[MarginalLogLikelihood]: # NOTE: We currently do not support `ModelListGP`. This code block will only # be relevant once we support `ModelListGP`. if (state_dict is None o...
Python
nomic_cornstack_python_v1
function test_not_ready_if_insufficient_output_space self begin set package = input_ovf set default_confirm_response = false comment Make working directory requirements negligible but output huge with call object command string working_dir_disk_space_required return_value=0 ; call object vm string predicted_output_size...
def test_not_ready_if_insufficient_output_space(self): self.command.package = self.input_ovf self.command.ui.default_confirm_response = False # Make working directory requirements negligible but output huge with mock.patch.object(self.command, "working_dir...
Python
nomic_cornstack_python_v1
function init_model session model begin comment If there is a checkpoint, load it if not exists gfile train_dir begin make directory gfile train_dir end set ckpt = call get_checkpoint_state train_dir if ckpt and call checkpoint_exists model_checkpoint_path begin print string Reading model parameters from %s % model_che...
def init_model(session, model): # If there is a checkpoint, load it if not tf.gfile.Exists(FLAGS.train_dir): tf.gfile.MkDir(FLAGS.train_dir) ckpt = tf.train.get_checkpoint_state(FLAGS.train_dir) if ckpt and tf.train.checkpoint_exists(ckpt.model_checkpoint_path): print("Reading model para...
Python
nomic_cornstack_python_v1
function get_countries begin comment get connection with db set tuple cnx cur = call connect_to_db execute cur string SELECT DISTINCT country FROM locations order by country set lst = call fetchall close cur close cnx return lst end function
def get_countries(): cnx,cur = connect_to_db() #get connection with db cur.execute("SELECT DISTINCT country FROM locations order by country") lst = cur.fetchall() cur.close() cnx.close() return lst
Python
nomic_cornstack_python_v1
comment coding="utf-8" set lst = list 1 1 0 2 2 2 4 3 3 4 2 0 0 set resultList = list set middleList = list string set j = string for i in lst begin if i == middleList at - 1 begin append middleList i end else begin set middleList = list append middleList i append resultList middleList end end print resultList
#coding="utf-8" lst=[1,1,0,2,2,2,4,3,3,4,2,0,0] resultList=[] middleList=[''] j='' for i in lst: if i==middleList[-1]: middleList.append(i) else: middleList=[] middleList.append(i) resultList.append(middleList) print(resultList)
Python
zaydzuhri_stack_edu_python
from tkinter import * from tkinter import messagebox import sqlite3 import time import turtle import random class User begin function __init__ self username password score begin set username = username set password = password set score = score end function function update_score self high_score begin set score = high_sc...
from tkinter import * from tkinter import messagebox import sqlite3 import time import turtle import random class User: def __init__(self,username,password,score): self.username=username self.password=password self.score=score def update_score(self,high_score): self.s...
Python
zaydzuhri_stack_edu_python
function modify self begin if on_client_side begin return end comment get executable set dbg = prof_orig at string debug at 0 if dbg == string begin set dbg = string nodebug end if get prof_orig string D typ=string exec begin set d_exe = get prof_orig string D typ=string exec at 0 end else begin set d_exe = dict strin...
def modify(self): if self.on_client_side: return # get executable dbg = self.prof_orig['debug'][0] if dbg == '': dbg = 'nodebug' if self.prof_orig.Get('D', typ='exec'): d_exe = self.prof_orig.Get('D', typ='exec')[0] else: d_...
Python
nomic_cornstack_python_v1
from typing import List class Solution begin function coinChange self coins amount begin set dp = list comprehension list comprehension decimal string inf for i in range amount + 1 for i in range length coins + 1 comment when making 0 amount, min coins required are 0 set tuple m n = tuple length dp length dp at 0 for i...
from typing import List class Solution: def coinChange(self, coins: List[int], amount: int) -> int: dp = [[float("inf") for i in range(amount+1)] for i in range(len(coins)+1)] # when making 0 amount, min coins required are 0 m, n = len(dp), len(dp[0]) for i in range(m): ...
Python
zaydzuhri_stack_edu_python
function func self begin if args begin set obj = search strip args end else begin set obj = obj end if not obj begin return end comment we want an attribute read_text to be defined. set tastetext = tasteable_text if tastetext begin set string = string You taste |C%s|n: %s % tuple key tastetext end else begin set string...
def func(self): if self.args: obj = self.caller.search(self.args.strip()) else: obj = self.obj if not obj: return # we want an attribute read_text to be defined. tastetext = obj.db.tasteable_text if tastetext: string = "You...
Python
nomic_cornstack_python_v1
function us14_multiple_births repo begin set error = list for fam in values families begin set children = fam at string CHIL at string detail if children != string NA and length children > 5 begin set date = dict for child in list children begin set child_birth = individuals at child at string BIRT at string detail i...
def us14_multiple_births(repo): error = [] for fam in repo.families.values(): children = fam['CHIL']['detail'] if children != 'NA' and len(children) > 5: date = {} for child in list(children): child_birth = repo.individuals[child]['BIRT']['detail'] ...
Python
nomic_cornstack_python_v1
function setLength self new_length begin set length = new_length end function
def setLength(self, new_length): self.length = new_length
Python
nomic_cornstack_python_v1
import os , hashlib , sys import requests set headers = dict string User-Agent string SubDB/1.0 (get_my_subtitle/1.0; http://github.com/mohi7solanki/get-my-subtitle) function get_hash name begin set readsize = 64 * 1024 with open name string rb as f begin set size = get size path name set data = read f readsize seek f ...
import os, hashlib, sys import requests headers = {'User-Agent': 'SubDB/1.0 (get_my_subtitle/1.0; http://github.com/mohi7solanki/get-my-subtitle)'} def get_hash(name): readsize = 64 * 1024 with open(name, 'rb') as f: size = os.path.getsize(name) data = f.read(readsize) ...
Python
zaydzuhri_stack_edu_python
class Stack begin function __init__ self begin set stack = list end function function push self data begin append stack data end function function pop self begin if length stack == 0 begin return - 1 end return pop stack end function function peek self begin if length stack == 0 begin return - 1 end return stack at - ...
class Stack: def __init__(self): self.stack = [] def push(self, data): self.stack.append(data) def pop(self): if len(self.stack) == 0: return -1 return self.stack.pop() def peek(self): if len(self.stack) == 0: return -1 ...
Python
iamtarun_python_18k_alpaca
comment -*- coding: utf-8 -*- string Created on Tue Jan 14 12:57:20 2020 @author: Kyle Cheng import pandas as pd import time import os import numpy as np comment 计算指定日期指定合约的最后一小时平均持仓量 function last_hour_open_interest date contract begin set data = read csv filepath + date + string \ + contract comment 为了减少运算量,不先对数据的时间进...
# -*- coding: utf-8 -*- """ Created on Tue Jan 14 12:57:20 2020 @author: Kyle Cheng """ import pandas as pd import time import os import numpy as np #计算指定日期指定合约的最后一小时平均持仓量 def last_hour_open_interest(date, contract): data = pd.read_csv(filepath + date + '\\' + contract) #为了减少运算量,不先对数据的时...
Python
zaydzuhri_stack_edu_python
import matplotlib.image as mpimg import sys set result = list if length argv == 1 begin set matrix = list list 1 2 3 4 list 5 6 7 8 list 9 10 11 12 end else begin try begin set matrix = call imread argv at 1 end except FileNotFoundError begin print string File does not exist. Try again exit 0 end end comment Get the d...
import matplotlib.image as mpimg import sys result = [] if len(sys.argv) == 1: matrix = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]] else: try: matrix = mpimg.imread(sys.argv[1]) except FileNotFoundError: print('File does not exist. Try again') sys.exit(...
Python
zaydzuhri_stack_edu_python
comment Baum-Sweet Sequence function bs_sequence range_nr begin comment 1 for bin(0) set result = list 1 set split_numbers = list generator expression list filter lambda x -> x != string split binary number at slice 2 : : string 1 for number in range 1 range_nr + 1 for item in split_numbers begin set item = list com...
# Baum-Sweet Sequence def bs_sequence(range_nr): result = [1] # 1 for bin(0) split_numbers = list( list(filter(lambda x: x != '', bin(number)[2:].split("1"))) for number in range(1, range_nr + 1)) for item in split_numbers: item = [False for element in item if divmod(len(element), 2)[1] !=...
Python
zaydzuhri_stack_edu_python
function w2f w begin return call as_float_array call w2q w end function
def w2f(w): return quat.as_float_array(w2q(w))
Python
nomic_cornstack_python_v1
function save_data filename data begin with open filename string wb as out_file begin dump data out_file end end function
def save_data(filename, data): with open(filename, "wb") as out_file: pickle.dump(data, out_file)
Python
nomic_cornstack_python_v1
function _combine_forces self F_k F_c F_f begin set Frub = F_k at DoF + F_c at DoF + F_f at DoF set FFrub = F_k + F_c + F_f return tuple Frub FFrub end function
def _combine_forces(self, F_k, F_c, F_f): Frub = F_k[self.DoF] + F_c[self.DoF] + F_f[self.DoF] FFrub = F_k + F_c + F_f return Frub, FFrub
Python
nomic_cornstack_python_v1
from unittest import TestCase from model import connect_to_db , db , User , Language , Contact , Message , MessageLang , MessageContact from server import app from flask import Flask from flask_sqlalchemy import SQLAlchemy import server import subprocess import MessageController , UserController , sentiment_analysis , ...
from unittest import TestCase from model import connect_to_db, db, User, Language, Contact, Message, MessageLang, MessageContact from server import app from flask import Flask from flask_sqlalchemy import SQLAlchemy import server import subprocess import MessageController, UserController, sentiment_analysis, yandex, se...
Python
zaydzuhri_stack_edu_python
function publish TopicArn=none TargetArn=none PhoneNumber=none Message=none Subject=none MessageStructure=none MessageAttributes=none begin pass end function
def publish(TopicArn=None, TargetArn=None, PhoneNumber=None, Message=None, Subject=None, MessageStructure=None, MessageAttributes=None): pass
Python
nomic_cornstack_python_v1
string k-means clustering import numpy as np import matplotlib.pyplot as plt import math function loadDataSet filename begin set file = open filename set dataList = list for line in read lines file begin set lineList = split strip line string set fltline = map float lineList append dataList fltline end set dataMat = c...
''' k-means clustering ''' import numpy as np import matplotlib.pyplot as plt import math def loadDataSet(filename): file = open(filename) dataList = [] for line in file.readlines(): lineList = line.strip().split('\t') fltline = map(float, lineList) dataList.append(fltline) dat...
Python
zaydzuhri_stack_edu_python
comment Code for tutorial found at comment https://www.wzdftpd.net/blog/python-scripts-in-gdb.html class PrintGList extends Command begin string Glib Glist: wsd_print_glist list objecttpe Iterate through the list if nodes in a Glist and display a human-readable form of the objects. function __init__ self begin call __i...
#Code for tutorial found at #https://www.wzdftpd.net/blog/python-scripts-in-gdb.html class PrintGList( gdb.Command ): """ Glib Glist: wsd_print_glist list objecttpe Iterate through the list if nodes in a Glist and display a human-readable form of the objects. """ def __init__( sel...
Python
zaydzuhri_stack_edu_python
function make_values sv lines begin comment browse program lines for tuple num lig in enumerate lines begin comment process conditions and values comment conditions (unprocessed) if starts with lig When begin comment no surrounding spaces or brackets set clau = call no_brackets strip lig at slice length When : : Spac...
def make_values(sv, lines): for num, lig in enumerate(lines): # browse program lines # process conditions and values if lig.startswith(When): # conditions (unprocessed) clau=no_brackets(li...
Python
nomic_cornstack_python_v1
function MergeAHEBuffyDetection est_joints8 est_det est_bbox gt_annot ep_arr fr_arr begin import iconvnet_datacvt as icvt import Stickmen if shape at - 1 != shape at - 1 or shape at - 1 != shape at - 1 or shape at - 1 != shape at - 1 or shape at - 1 != shape at - 1 begin raise call BuffyError string ep_arr, fr_arr, est...
def MergeAHEBuffyDetection(est_joints8, est_det, est_bbox, gt_annot, ep_arr, fr_arr): import iconvnet_datacvt as icvt import Stickmen if ep_arr.shape[-1] != fr_arr.shape[-1] or \ fr_arr.shape[-1] != est_bbox.shape[-1] or \ fr_arr.shape[-1] != est_det.shape[-1] or \ fr_arr.shape[-1] != est_...
Python
nomic_cornstack_python_v1
function re_estimate_transition self x fb_array begin with call name_scope string Init_3D_tensor begin comment M: v tensor (pg 70): num_states x num_states x num_observations comment u (pg 70) is the fb_array I think set M = call Variable zeros tuple N - 1 S S float32 set total_log_prob = call reduce_logsumexp forward_...
def re_estimate_transition(self, x, fb_array): with tf.name_scope('Init_3D_tensor'): # M: v tensor (pg 70): num_states x num_states x num_observations # u (pg 70) is the fb_array I think self.M = tf.Variable( tf.zeros( (self.N - 1, self.S,...
Python
nomic_cornstack_python_v1
comment The module which calculates different things related to lists function sum lis begin set sum = 0 for item in lis begin set sum = sum + item end return sum end function
#The module which calculates different things related to lists def sum(lis): sum = 0 for item in lis: sum += item return sum
Python
zaydzuhri_stack_edu_python
set n1 = integer input string Enter a number: set sum = 0 while n1 > 0 begin set sum = sum + n1 set n1 = n1 - 1 end print string The sum of first n natural numbers is sum
n1=int(input("Enter a number: ")) sum = 0 while(n1 > 0): sum=sum+n1 n1=n1-1 print("The sum of first n natural numbers is",sum)
Python
zaydzuhri_stack_edu_python
for i in range 100 begin append My_list i end if 10 in My_list begin print string yes end else begin print string no end
for i in range(100): My_list.append(i) if 10 in My_list: print("yes") else: print("no")
Python
zaydzuhri_stack_edu_python
function lex_string self input_string begin comment Isolate & extract: set intermediate_seq = list dict string string input_string while length intermediate_seq != 0 begin set intermediate_seq = call isolate_priority_lexemes intermediate_seq continue end comment Scan & slice: set lexemes = list for element in master_s...
def lex_string(self, input_string): # Isolate & extract: intermediate_seq = [{'string': input_string}] while len(intermediate_seq) != 0: intermediate_seq = self.isolate_priority_lexemes(intermediate_seq) continue # Scan & slice: lexemes = [] ...
Python
nomic_cornstack_python_v1
function _translate__l3vpn_ntw_vpn_services_vpn_service_vpn_nodes_vpn_node_vpn_network_accesses_vpn_network_access_connection_bearer_pseudowire input_yang_obj translated_yang_obj=none begin if call _changed begin set vcid = vcid end if call _changed begin set far_end = far_end end return translated_yang_obj end functio...
def _translate__l3vpn_ntw_vpn_services_vpn_service_vpn_nodes_vpn_node_vpn_network_accesses_vpn_network_access_connection_bearer_pseudowire( input_yang_obj, translated_yang_obj=None): if input_yang_obj.vcid._changed(): input_yang_obj.vcid = input_yang_obj.vcid if input_yang_obj.far_end._changed...
Python
nomic_cornstack_python_v1
function test_before_clean__validation_results self begin set importer = call SimpleValidationsImporter files at string csv_sheet call assertEquals ordered dictionary _validation_results end function
def test_before_clean__validation_results(self): importer = SimpleValidationsImporter(self.files['csv_sheet']) self.assertEquals(OrderedDict(), importer._validation_results)
Python
nomic_cornstack_python_v1
function restrict s ks strict=0 begin if is instance s dict begin set r = call type s for k in ks begin try begin set r at k = s at k end except KeyError begin if strict begin raise end end end return r end if is instance s tuple list tuple basestring begin set r = list for k in ks begin try begin append r s at k end e...
def restrict(s, ks, strict=0): if isinstance(s, dict): r = type(s)() for k in ks: try: r[k] = s[k] except KeyError: if strict: raise return r if isinstance(s, (list, tuple, basestring)): r = list() for k in ks: try: r.append(s[k]) except IndexError...
Python
nomic_cornstack_python_v1
function test_shoppingcart_detail self begin comment first we create a customer set id = call _create_model string customer customer_data list string name string email string phone if id begin comment then we create a product set id_prod = call _create_model string product product_data list string name string descripti...
def test_shoppingcart_detail(self): # first we create a customer id = self._create_model("customer", self.customer_data, ["name", "email", "phone"]) if id: # then we create a product id_prod = self._create_model("product", self.product_data, ["name", "description", "image...
Python
nomic_cornstack_python_v1
function _bbcomponentwalk self begin for tuple path subdirs files in walk call oedir begin try begin del subdirs at index subdirs string .svn end except ValueError begin pass end for file in files begin set tuple pf ext = call splitext file if ext == string .bb begin yield call partition string _ at 0 end end end end f...
def _bbcomponentwalk(self): for path, subdirs, files in os.walk(self.oedir()): try: del subdirs[subdirs.index('.svn')] except ValueError: pass for file in files: pf, ext = os.path.splitext(file) ...
Python
nomic_cornstack_python_v1
function is_set_max_noutput_items self begin return call atsc_equalizer_sptr_is_set_max_noutput_items self end function
def is_set_max_noutput_items(self): return _atsc_swig.atsc_equalizer_sptr_is_set_max_noutput_items(self)
Python
nomic_cornstack_python_v1
import bz2 import gzip comment compression pretty straightforward with bz2 and gzip modules comment gzip compression with open string somefile.gz string rt as f begin set text = read f end comment bz2 compression with open string somefile.bz2 string rt as f begin set text = read f end comment gzip compression with open...
import bz2 import gzip # compression pretty straightforward with bz2 and gzip modules # gzip compression with gzip.open('somefile.gz', 'rt') as f: text = f.read() # bz2 compression with bz2.open('somefile.bz2', 'rt') as f: text = f.read() # gzip compression with gzip.open('somefile.gz', 'wt') as f: f.wri...
Python
zaydzuhri_stack_edu_python
function reproject_raster res src_epsg dst_epsg begin set src_name = string res_ { res } _epsg_ { src_epsg } set src_path = join path src_name string { src_name } .tif with open src_path as src begin set dst_crs = string epsg: { dst_epsg } set tuple transform width height = call calculate_default_transform crs dst_crs ...
def reproject_raster(res: int, src_epsg: int, dst_epsg: int) -> None: src_name = f"res_{res}_epsg_{src_epsg}" src_path = os.path.join(src_name, f"{src_name}.tif") with rio.open(src_path) as src: dst_crs = f"epsg:{dst_epsg}" transform, width, height = calculate_default_transform( ...
Python
nomic_cornstack_python_v1
function __init__ self event_type=none pool_id=none id_lt=none id_lte=none id_gt=none id_gte=none created_lt=none created_lte=none created_gt=none created_gte=none begin Ellipsis end function
def __init__( self, event_type: typing.Optional[toloka.client.webhook_subscription.WebhookSubscription.EventType] = None, pool_id: typing.Optional[str] = None, id_lt: typing.Optional[str] = None, id_lte: typing.Optional[str] = None, id_gt: typing.Optional[str] = None, ...
Python
nomic_cornstack_python_v1
async function github self ctx begin await call send string https://github.com/nick411077/nickcan_bot end function
async def github(self, ctx): await ctx.send('https://github.com/nick411077/nickcan_bot')
Python
nomic_cornstack_python_v1
string Tipos de dados str - Strings - textos 'texto' "Texto" int - inteiro - qualquer numero negativo ou potivo ou zero 10 20 -30 0 flout - real/ponto flutuante - 10.50 1.5 15.2 2.1 bool - boolean - True/False comment retorna o type print string texto type string texto comment retorna o type print 10 type 10 comment re...
""" Tipos de dados str - Strings - textos 'texto' "Texto" int - inteiro - qualquer numero negativo ou potivo ou zero 10 20 -30 0 flout - real/ponto flutuante - 10.50 1.5 15.2 2.1 bool - boolean - True/False """ print('texto',type('texto')) # retorna o type print(10,type(10)) # retorna o type pr...
Python
zaydzuhri_stack_edu_python
function fileMetamodel cls filename begin try begin set extension = call splitext filename at 1 return call theMetamodel ext=extension end comment raise except:TODO:4 except UnexpectedValue begin return none end end function
def fileMetamodel(cls, filename: str) -> Any: try: extension = os.path.splitext(filename)[1] return cls.theMetamodel(ext=extension) except UnexpectedValue: # raise except:TODO:4 return None
Python
nomic_cornstack_python_v1
function jmodesdct jcnt nmodes=20 begin set l = size np jcnt set jk = call dct jcnt type=2 norm=string ortho for i in call xrange length jk begin if i == 0 begin set jk at i = jk at i * square root 1.0 / 4.0 * l end else begin set jk at i = jk at i * square root 1.0 / 2.0 * l end end return jk end function
def jmodesdct(jcnt, nmodes=20): l = np.size(jcnt) jk = dct(jcnt, type=2, norm='ortho') for i in xrange(len(jk)): if i == 0: jk[i] *= np.sqrt(1.0 / (4.0 * l)) else: jk[i] *= np.sqrt(1.0 / (2.0 * l)) return jk
Python
nomic_cornstack_python_v1
import collections string Counter是对字典类型的补充,用于追踪值的出现次数,具备字典的所有功能 + 自己的功能 set a = string abababsbsbhh comment 直接列出每个元素出现了几次,传入列表和元组也一样 set c = counter a print c comment 输出:Counter({'b': 5, 'a': 3, 'h': 2, 's': 2}) comment most_common 列出Counter内的前几个 print call most_common print call most_common 1 print call most_common 3 ...
import collections ''' Counter是对字典类型的补充,用于追踪值的出现次数,具备字典的所有功能 + 自己的功能 ''' a='abababsbsbhh' c=collections.Counter(a) #直接列出每个元素出现了几次,传入列表和元组也一样 print(c) #输出:Counter({'b': 5, 'a': 3, 'h': 2, 's': 2}) #most_common 列出Counter内的前几个 print(c.most_common()) print(c.most_common(1)) print(c.most_common(3)) '''...
Python
zaydzuhri_stack_edu_python
function evaluate all begin string Evaluete expressions with prefix operands :param l: A given list whit to operands for each operator :return: Result number of eval function is_operator op begin string Determinate if is a string is operator or not :param op: A string operand/operator :return: True if operator, False o...
def evaluate(all): """ Evaluete expressions with prefix operands :param l: A given list whit to operands for each operator :return: Result number of eval """ def is_operator(op): """ Determinate if is a string is operator or not :param op: A string operand/operator ...
Python
zaydzuhri_stack_edu_python
string 20. Valid Parentheses https://leetcode.com/problems/valid-parentheses/ class Solution begin function isValid self s begin string :type s: str :rtype: bool comment Remove whitespace set s = replace s string string set parentheses_pairs = list string () string [] string {} set is_valid = true set l_previous = len...
""" 20. Valid Parentheses https://leetcode.com/problems/valid-parentheses/ """ class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ s = s.replace(' ', '') # Remove whitespace parentheses_pairs = ['()', '[]', '{}'] is_valid = True ...
Python
zaydzuhri_stack_edu_python
function parse_history_snapshot self begin if not history_snapshot begin return dict end if 1 != length history_snapshot begin raise call ValueError string Expected history snapshot with one entry only end set first_item = history_snapshot at 0 return dict string baseline_accuracy call extract_accuracy get first_item ...
def parse_history_snapshot(self) -> dict: if not self.history_snapshot: return {} if 1 != len(self.history_snapshot): raise ValueError("Expected history snapshot with one entry only") first_item = self.history_snapshot[0] return { "baseline_accuracy"...
Python
nomic_cornstack_python_v1
function __add_credit_menu self begin debug string Displaying __add_credit_menu comment Create a payment methods keyboard set keyboard = list comment Add the supported payment methods to the keyboard comment Cash append keyboard list call KeyboardButton get loc string menu_cash comment Telegram Payments if ccard at str...
def __add_credit_menu(self): log.debug("Displaying __add_credit_menu") # Create a payment methods keyboard keyboard = list() # Add the supported payment methods to the keyboard # Cash keyboard.append([telegram.KeyboardButton(self.loc.get("menu_cash"))]) # Telegram...
Python
nomic_cornstack_python_v1
function time self begin return get pulumi self string time end function
def time(self) -> Optional[str]: return pulumi.get(self, "time")
Python
nomic_cornstack_python_v1
function get_instance_state instance_id region=DEFAULT_REGION begin set instance = call get_instance_from_id instance_id region return instance at string State at string Name end function
def get_instance_state(instance_id, region=DEFAULT_REGION): instance = get_instance_from_id(instance_id, region) return instance["State"]["Name"]
Python
nomic_cornstack_python_v1
function dgTimerReset self begin pass end function
def dgTimerReset(self): pass
Python
nomic_cornstack_python_v1
function get_enum_key key choices begin string Get an enum by prefix or equality if key in choices begin return key end set keys = list comprehension k for k in choices if starts with k key if length keys == 1 begin return keys at 0 end end function
def get_enum_key(key, choices): """ Get an enum by prefix or equality """ if key in choices: return key keys = [k for k in choices if k.startswith(key)] if len(keys) == 1: return keys[0]
Python
jtatman_500k
comment 此处实现了一个拖拽操作,动作链还包括键盘按键 from selenium import webdriver from selenium.webdriver import ActionChains set browser = call Chrome set url = string http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable get browser url call frame string iframeResult comment 找到要拖拽的节点 set source = call find_element_by_css_sel...
# 此处实现了一个拖拽操作,动作链还包括键盘按键 from selenium import webdriver from selenium.webdriver import ActionChains browser = webdriver.Chrome() url = 'http://www.runoob.com/try/try.php?filename=jqueryui-api-droppable' browser.get(url) browser.switch_to.frame('iframeResult') source = browser.find_element_by_css_selector('#dra...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu Jul 9 15:09:27 2020 @author: Nikita import numpy as np import random function randMatrix m n begin set a = reshape array range m * n m n for i in range m begin for j in range n begin set a at i at j = random integer 0 1 end end return a end function function transA a ...
# -*- coding: utf-8 -*- """ Created on Thu Jul 9 15:09:27 2020 @author: Nikita """ import numpy as np import random def randMatrix(m,n): a = np.arange(m*n).reshape(m,n) for i in range(m): for j in range(n): a[i][j] = random.randint(0,1) return a def transA(a,m,n): trA = np.aran...
Python
zaydzuhri_stack_edu_python
function test_basic_operations_with_assignee self begin comment Admin adds reader as an assignee call set_user users at string admin set response = call _post_relationship users at string reader id assert equal status_code 201 comment Reader is now allowed to update the object call set_user users at string reader set r...
def test_basic_operations_with_assignee(self): # Admin adds reader as an assignee self.api.set_user(self.users["admin"]) response = self._post_relationship(self.users["reader"], self.obj.id) self.assertEqual(response.status_code, 201) # Reader is now allowed to update the object self.api.set_u...
Python
nomic_cornstack_python_v1
function soak_time_increment self begin set str_soak_time = call cget string text set soak_time = integer str_soak_time set soak_time = soak_time + 1 call configure text=string soak_time call reset_timer end function
def soak_time_increment(self): str_soak_time = self.soak_time_disp.cget('text') soak_time = int(str_soak_time) soak_time += 1 self.soak_time_disp.configure(text=str(soak_time)) self.reset_timer()
Python
nomic_cornstack_python_v1
function tearDown self begin pass end function
def tearDown(self): pass
Python
nomic_cornstack_python_v1
function make_cone self coords vertex direction name=string None begin set cent = mean np coords axis=0 comment axis = np.mean(coords - vertex, axis=0) * self.scale_height set height = norm cent - vertex * scale_height set cos = dot coords - vertex direction / norm coords axis=1 * norm direction set angle = median call...
def make_cone(self, coords, vertex, direction, name='None'): cent = np.mean(coords, axis=0) #axis = np.mean(coords - vertex, axis=0) * self.scale_height height = np.linalg.norm(cent - vertex) * self.scale_height cos = np.dot(coords - vertex, direction) / (np.linalg.norm(coords, axis=1) ...
Python
nomic_cornstack_python_v1
from flask_wtf import FlaskForm from wtforms import StringField , SelectField , IntegerField from wtforms.validators import InputRequired , DataRequired , Email class InfoForm extends FlaskForm begin set item = call StringField string Item you want to buy validators=list call InputRequired set cost = call IntegerField ...
from flask_wtf import FlaskForm from wtforms import StringField, SelectField, IntegerField from wtforms.validators import InputRequired, DataRequired, Email class InfoForm(FlaskForm): item = StringField('Item you want to buy', validators=[InputRequired()]) cost = IntegerField('Cost', validators=[ ...
Python
zaydzuhri_stack_edu_python
function state self begin set now = now if start < now begin if end > now begin if enrollment_end > now begin return string is_open end return string is_ongoing end return string is_archived end else if enrollment_start > now begin return string is_coming end else if enrollment_end > now begin return string is_open end...
def state(self): now = timezone.now() if self.start < now: if self.end > now: if self.enrollment_end > now: return "is_open" return "is_ongoing" return "is_archived" elif self.enrollment_start > now: return "...
Python
nomic_cornstack_python_v1
function set_option self name value begin set _options at name = value end function
def set_option(self, name, value): self._options[name] = value
Python
nomic_cornstack_python_v1
import paho.mqtt.client as paho import logging import datetime import MySQLdb call basicConfig filename=string example.log filemode=string w level=INFO
import paho.mqtt.client as paho import logging import datetime import MySQLdb logging.basicConfig(filename='example.log', filemode='w', level=logging.INFO)
Python
zaydzuhri_stack_edu_python
from mcpi.minecraft import Minecraft import cv2 import numpy as np set face_cascade = call CascadeClassifier string C:\Users\86183\AppData\Roaming\Python\Python38\site-packages\cv2\data\haarcascade_frontalface_default.xml set cap = call VideoCapture 0 set mc = call create set position = call getPos call postToChat stri...
from mcpi.minecraft import Minecraft import cv2 import numpy as np face_cascade = cv2.CascadeClassifier("C:\\Users\\86183\\AppData\\Roaming\\Python\\Python38\\site-packages\\cv2\\data\\haarcascade_frontalface_default.xml") cap = cv2.VideoCapture(0) mc = Minecraft.create() position = mc.player.getPos() mc.pos...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import Tkinter as tk comment DrawBox.py import DrawBox as drbx set window = call Tk title window string 行李放置 comment 視窗大小 call geometry string 200x60 comment 執行DrawBox.py 中的 run_plot function run_pack begin call run_plot end function comment def run_optpack(): #執行DrawBox.py 中的 run_plot com...
# -*- coding: utf-8 -*- import Tkinter as tk import DrawBox as drbx #DrawBox.py window=tk.Tk() window.title('行李放置') window.geometry('200x60') #視窗大小 # def run_pack(): #執行DrawBox.py 中的 run_plot drbx.run_plot() # def run_optpack(): #執行DrawBox.py 中的 run_plot # drbx.run_optplot() b = tk.Button(window, te...
Python
zaydzuhri_stack_edu_python
function forward self input begin return call updateOutput input end function
def forward(self, input): return self.updateOutput(input)
Python
nomic_cornstack_python_v1
import numpy as np class Output begin function __init__ self name pointed_variable simulation begin set name = name set pointed_variable = pointed_variable set values = zeros 0 set simulation = simulation end function function get_values self begin return values end function function print self begin set value = eval s...
import numpy as np class Output: def __init__(self, name, pointed_variable, simulation): self.name = name self.pointed_variable = pointed_variable self.values = np.zeros(0) self.simulation = simulation def get_values(self): return self.values def print(self): ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Sat Apr 28 20:07:01 2018 @author: David import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit set Datei1 = call genfromtxt string CO.txt dtype=float comments=string # set Datei2 = call genfromtxt string CO30.txt dtype=float comments=strin...
# -*- coding: utf-8 -*- """ Created on Sat Apr 28 20:07:01 2018 @author: David """ import numpy as np import matplotlib.pyplot as plt from scipy.optimize import curve_fit Datei1 = np.genfromtxt("CO.txt",dtype=float, comments='#') Datei2 = np.genfromtxt("CO30.txt",dtype=float,comments='#') Datei3 = np.genfromtxt("HC...
Python
zaydzuhri_stack_edu_python
comment Input firstname set name = input string Enter your username: if length name < 4 begin print string Username is invalid: Too short - must have between 4 and 8 alphanumeric characters end else if length name > 8 begin print string Username is invalid: Too long - must have between 4 and 8 alphanumeric characters e...
# Input firstname name = input("Enter your username: ") if len(name) < 4: print("Username is invalid:\n Too short - must have between 4 and 8 alphanumeric characters") elif len(name) > 8: print("Username is invalid:\n Too long - must have between 4 and 8 alphanumeric characters") elif not name[0].islower(): ...
Python
zaydzuhri_stack_edu_python
function get_sparsity self excludes=list begin return list comprehension call get_sparsity excludes for layer in layers end function
def get_sparsity(self, excludes=[]): return [layer.get_sparsity(excludes) for layer in self.layers]
Python
nomic_cornstack_python_v1
function standard_cauchy random_state size=none chunk_size=none gpu=none dtype=none begin if dtype is none begin set dtype = dtype end set size = call _handle_size size set seed = call gen_random_seeds 1 call to_numpy at 0 set op = call TensorStandardCauchy size=size seed=seed gpu=gpu dtype=dtype return call op chunk_s...
def standard_cauchy(random_state, size=None, chunk_size=None, gpu=None, dtype=None): if dtype is None: dtype = np.random.RandomState().standard_cauchy(size=(0,)).dtype size = random_state._handle_size(size) seed = gen_random_seeds(1, random_state.to_numpy())[0] op = TensorStandardCauchy(size=siz...
Python
nomic_cornstack_python_v1
function select_all_tasks self conn cmd begin set cur = call cursor execute cur cmd comment cur.execute("PRAGMA table_info(deploys)") set rows = call fetchall return rows end function
def select_all_tasks(self, conn, cmd): cur = conn.cursor() cur.execute(cmd) # cur.execute("PRAGMA table_info(deploys)") rows = cur.fetchall() return rows
Python
nomic_cornstack_python_v1
import json with open string example.json string w as f begin dump dict string key string value f end comment Code executed.
import json with open('example.json', 'w') as f: json.dump({'key': 'value'}, f) # Code executed.
Python
flytech_python_25k
function set_status_installed begin set fd = open INSTALLER_PATH + string /.installed string w close fd end function
def set_status_installed(): fd = open(settings.INSTALLER_PATH+"/.installed", "w") fd.close()
Python
nomic_cornstack_python_v1
function standardize_input_data data names shapes=none check_batch_axis=true exception_prefix=string begin try begin set data_len = length data end except TypeError begin comment For instance if data is `None` or a symbolic Tensor. set data_len = none end if not names begin if data_len and not is instance data dict beg...
def standardize_input_data(data, names, shapes=None, check_batch_axis=True, exception_prefix=''): try: data_len = len(data) except TypeError: # For instance if data is `None` or a symbolic Tensor. ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment python 3 comment Matthew J Neave 6.5.2014 comment extract sequences using a list of IDs comment input fasta first, then seq IDs, then a name for the output comment modification: only unique genes are written comment this will only write the first transcript isoform, from Trinity out...
#!/usr/bin/env python # python 3 # Matthew J Neave 6.5.2014 # extract sequences using a list of IDs # input fasta first, then seq IDs, then a name for the output # modification: only unique genes are written # this will only write the first transcript isoform, from Trinity output import sys from Bio import SeqIO fas...
Python
zaydzuhri_stack_edu_python
function html_form begin global usr call html_start if notice_string or error_string or okay_string begin print string <table align=center id=msgs><tr><td> if error_string begin print string <span id=warn>%s</span> % replace error_string string string <br> end if notice_string begin print string <span id=notice>%s</sp...
def html_form(): global usr html_start() if notice_string or error_string or okay_string: print("<table align=center id=msgs><tr><td>") if error_string: print("<span id=warn>%s</span>" % error_string.replace( '\n', '<br>\n')) if notice_string: ...
Python
nomic_cornstack_python_v1
comment This script can generate example data for "city" and "InterviewSlot" models. from models import * class GenerateData begin decorator staticmethod function add_schools schools begin comment from models import School for school in schools begin call create name=school at string name location=school at string loca...
# This script can generate example data for "city" and "InterviewSlot" models. from models import * class GenerateData: @staticmethod def add_schools(schools): # from models import School for school in schools: School.create(name=school['name'], location=school['location']) @...
Python
zaydzuhri_stack_edu_python
function TuptoDict tupe d begin for tuple a b in tupe begin append set default d a list b end return d end function set tup_input = list tuple string John tuple string Physics 80 tuple string Daniel tuple string Science 90 tuple string John tuple string Science 95 tuple string Mark tuple string Maths 100 tuple string D...
def TuptoDict(tupe, d): for a, b in tupe: d.setdefault(a, []).append(b) return d tup_input = [( "John", ("Physics", 80)), ("Daniel", ("Science", 90)), ("John", ("Science", 95)), ("Mark",("Maths", 100)), ("Daniel", ("History", 75)), ("Mark", ("Social", 95))] dict1 = {} dict2 = {} dict2 = TuptoDict(tup_input, ...
Python
zaydzuhri_stack_edu_python
import numpy as np from numpy import fft function biginteger_mul a b begin set a = array list comprehension integer i for i in a set b = array list comprehension integer i for i in b comment 首先对齐 set sz = length a + length b set a = call pad a tuple sz - length a 0 at slice : : - 1 set b = call pad b tuple sz - lengt...
import numpy as np from numpy import fft def biginteger_mul(a: str, b: str) -> str: a = np.array([int(i) for i in a]) b = np.array([int(i) for i in b]) # 首先对齐 sz = len(a) + len(b) a = np.pad(a, (sz - len(a), 0))[::-1] b = np.pad(b, (sz - len(b), 0))[::-1] aa = fft.fft(a) bb = fft.fft(b...
Python
zaydzuhri_stack_edu_python
function add_numbers begin set summation = 0 while true begin try begin set number = input string Please enter an integer to add (or type 'stop' to exit): if lower number == string stop begin break end else begin set number = integer number set summation = summation + number end end except ValueError begin print string...
def add_numbers(): summation = 0 while True: try: number = input("Please enter an integer to add (or type 'stop' to exit): ") if number.lower() == "stop": break else: number = int(number) summation += number exce...
Python
flytech_python_25k
function data_factory_id self begin return get pulumi self string data_factory_id end function
def data_factory_id(self) -> pulumi.Input[str]: return pulumi.get(self, "data_factory_id")
Python
nomic_cornstack_python_v1