code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
comment Logout method function get self begin set response = call get_custom_response success=true message=string You are Logged out successfully status_code=200 return response end function
def get(self): # Logout method response = get_custom_response(success=True, message='You are Logged out successfully' , status_code=200 ) return response
Python
nomic_cornstack_python_v1
function eval_func self fx begin set pnoise_class = call Pnoise fx call func_ldbc fx label=label return pnoise_class end function
def eval_func(self, fx): pnoise_class = Pnoise(fx, self.func_ldbc(fx), label=self.label) return pnoise_class
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt from import DogWavelet as dwvt from import PoissonWavelet as pwvt import sys function construct_Gmat frame dlon dlat pars secderivs=false begin string Constructs the design matrix G for given q-grids and observation locations. Inputs: frame N x 3 array with columns l...
import numpy as np import matplotlib.pyplot as plt from . import DogWavelet as dwvt from . import PoissonWavelet as pwvt import sys def construct_Gmat(frame, dlon, dlat, pars, secderivs=False): """ Constructs the design matrix G for given q-grids and observation locations. Inputs: frame ...
Python
zaydzuhri_stack_edu_python
string 程序:冰雹猜想 作者:苏秦@小海豚科学馆公众号 来源:图书《Python趣味编程:从入门到人工智能》 set n = integer input string 请输入一个正整数: set state = true while state begin if n % 2 == 0 begin set n = n // 2 end else begin set n = 3 * n + 1 end print n if n == 1 begin comment 让循环结束 set state = false end end
''' 程序:冰雹猜想 作者:苏秦@小海豚科学馆公众号 来源:图书《Python趣味编程:从入门到人工智能》 ''' n = int(input('请输入一个正整数:')) state = True while state: if n % 2 == 0: n = n // 2 else: n = 3 * n + 1 print(n) if n == 1: state = False #让循环结束
Python
zaydzuhri_stack_edu_python
while a >= b begin set s = s + a // b set a = a // b + a % b end print s + c
while a >= b: s += a // b a = (a // b) + (a % b) print(s + c)
Python
jtatman_500k
function hey _string begin if not strip _string begin return string Fine. Be that way! end if is upper _string begin return string Whoa, chill out! end if ends with _string string ? begin return string Sure. end return string Whatever. end function
def hey(_string): if not _string.strip(): return 'Fine. Be that way!' if _string.isupper(): return 'Whoa, chill out!' if _string.endswith('?'): return 'Sure.' return 'Whatever.'
Python
zaydzuhri_stack_edu_python
function drawmaze self begin set win = call GraphWin string Perfect Maze 600 600 call setBackground string White comment Used to generalize the size difference for the input of larger numbers. The background resolution/ grid size, N set scale = 600 / N set x1 = scale set y1 = 0 set x2 = scale set y2 = scale comment VER...
def drawmaze(self): win=GraphWin("Perfect Maze",600,600) win.setBackground("White") scale=600/self.N #Used to generalize the size difference for the input of larger numbers. The background resolution/ grid size, N x1=scale y1=0 x2=scale y2=scale ##VER...
Python
nomic_cornstack_python_v1
function EjecutaRequest self funcion parametros payload begin call _log string EjecutaRequest: Llamado 4 try begin set endpoint = parametros at 0 end except any begin set endpoint = string end try begin set header = parametros at 1 end except any begin set header = dict end call _validsec if is instance authheader di...
def EjecutaRequest(self,funcion, parametros,payload): self._log ("EjecutaRequest: Llamado ",4) try : endpoint=parametros[0] except: endpoint="" try : header=parametros[1] except: header={} self._validsec() ...
Python
nomic_cornstack_python_v1
comment pip install requests comment pip install bs4 import datetime import requests import bs4 set 현재 = string now print 현재 set 날 = 현재 at slice : 4 : + 현재 at slice 5 : 7 : + 현재 at slice 8 : 10 : print 날 set html = get requests string http://school.cbe.go.kr/deogbeol-e/M01030802/list?ymd= + 날 set 수프 = call Beautifu...
### pip install requests ### pip install bs4 import datetime import requests import bs4 현재 = str(datetime.datetime.now()) print(현재) 날 = 현재[:4] + 현재[5:7] + 현재[8:10] print(날) html = requests.get("http://school.cbe.go.kr/deogbeol-e/M01030802/list?ymd=" + 날) 수프 = bs4.BeautifulSoup(html.text, "html.p...
Python
zaydzuhri_stack_edu_python
function proxyGETNode self **kwargs begin set allParams = list string name set params = locals for tuple key val in call iteritems begin if key not in allParams begin raise call TypeError string Got an unexpected keyword argument '%s' to method proxyGETNode % key end set params at key = val end del params at string kwa...
def proxyGETNode(self, **kwargs): allParams = ['name'] params = locals() for (key, val) in params['kwargs'].iteritems(): if key not in allParams: raise TypeError("Got an unexpected keyword argument '%s'" " to method proxyGETNode" % key...
Python
nomic_cornstack_python_v1
function example_dilute_to_required_molar_concentration begin set powder_mass = parse string 5mg set target_dilution = parse string 20mM set powder_molecular_weight = parse string 544.43g/mol set powder_mols = powder_mass / powder_molecular_weight set diluting_agent_volume = powder_mols / target_dilution print string T...
def example_dilute_to_required_molar_concentration() -> None: powder_mass = parse("5mg") target_dilution = parse("20mM") powder_molecular_weight = parse("544.43g/mol") powder_mols = powder_mass / powder_molecular_weight diluting_agent_volume = powder_mols / target_dilution print( f"The r...
Python
nomic_cornstack_python_v1
function applystreamclone repo remotereqs fp begin set lock = lock try begin call consumestreamclone repo fp comment new requirements = old non-format requirements + comment new format-related remote requirements comment requirements from the streamed-in repository set requirements = list remotereqs ? set requirements ...
def applystreamclone(repo, remotereqs, fp): lock = repo.lock() try: consumestreamclone(repo, fp) # new requirements = old non-format requirements + # new format-related remote requirements # requirements from the streamed-in repository repo.requirement...
Python
nomic_cornstack_python_v1
function change llist rlist begin set r = lenth - 1 set tflag = 1 global flag global cha while r >= 0 and tflag begin for l in range lenth begin if rlist at r - llist at l * 2 <= cha and rlist at r > llist at l begin set tuple rlist at r llist at l = tuple llist at l rlist at r sort rlist sort llist set cha = sum rlist...
def change(llist, rlist): r = lenth - 1 tflag = 1 global flag global cha while r >= 0 and tflag: for l in range(lenth): if ((rlist[r] - llist[l]) * 2 <= cha and rlist[r] > llist[l]): rlist[r], llist[l] = llist[l], rlist[r] rlist.sort() ...
Python
zaydzuhri_stack_edu_python
function fromParams self params begin set args = dictionary map lambda kv -> tuple string kv at 0 kv at 1 items params return call self keyword args end function
def fromParams(self, params): args = dict(map(lambda kv: (str(kv[0]),kv[1]), params.items())) return self(**args)
Python
nomic_cornstack_python_v1
function runner_scenario_x_times repetitions scenario_names feature_files out begin if scenario_names is not none begin set to_test = scenario_names end else if feature_files is not none begin set to_test = feature_files end else begin set to_test = string testsuite end set msg = string Running + string repetitions + s...
def runner_scenario_x_times(repetitions, scenario_names, feature_files, out): if scenario_names is not None: to_test = scenario_names elif feature_files is not None: to_test = feature_files else: to_test = "testsuite" msg = ("\nRunning " + str(repetitions) + " times test(s):\n " ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 import re import collections set Token = named tuple string Token list string type_ string value function tokenize expr tokens_spec begin string Token Generator set token_regex = compile join string | generator expression string (?P<%s>%s) % pair for pair in tokens_spec for item in call fi...
#!/usr/bin/env python3 import re import collections Token = collections.namedtuple('Token', ['type_', 'value']) def tokenize(expr, tokens_spec): '''Token Generator''' token_regex = re.compile('|'.join('(?P<%s>%s)' % pair for pair in tokens_spec)) for item in re.finditer(token_regex, expr): if ite...
Python
zaydzuhri_stack_edu_python
async function on_message self message begin if bot begin comment Ignore all bots. return end await call process_commands message end function
async def on_message(self, message): if message.author.bot: return # Ignore all bots. await self.process_commands(message)
Python
nomic_cornstack_python_v1
function clean_ufo path begin string Make sure old UFO data is removed, as it may contain deleted glyphs. if ends with path string .ufo and exists path path begin remove tree path end end function
def clean_ufo(path): """Make sure old UFO data is removed, as it may contain deleted glyphs.""" if path.endswith(".ufo") and os.path.exists(path): shutil.rmtree(path)
Python
jtatman_500k
function knapsack items weight_limit begin comment Initialize an empty list to hold the items to include in the knapsack set knapsack_items = list end function comment Iterate over each item in the list
def knapsack(items, weight_limit): # Initialize an empty list to hold the items to include in the knapsack knapsack_items = [] # Iterate over each item in the list
Python
iamtarun_python_18k_alpaca
function controlPoints self begin return call Point3D end function
def controlPoints(self): return Point3D()
Python
nomic_cornstack_python_v1
import pytest from circles import Point from circles import Circle from circles import Rectangle from circles import point_in_circle from circles import rect_in_circle from circles import rect_circle_overlap class TestCircles begin set circle_test_data = list tuple call Point 0 0 call Circle call Point 0 0 10 true tupl...
import pytest from circles import Point from circles import Circle from circles import Rectangle from circles import point_in_circle from circles import rect_in_circle from circles import rect_circle_overlap class TestCircles(): circle_test_data = [ (Point(0, 0), Circle(Point(0, 0), 10), True), (P...
Python
zaydzuhri_stack_edu_python
async function send_previous_messages self messages new_page_number begin print string PrivateChatConsumer string send_previous_messages await call send_json dict string messages_payload string previous_messages ; string messages messages ; string new_page_number new_page_number end function
async def send_previous_messages(self, messages, new_page_number): print("PrivateChatConsumer", "send_previous_messages") await self.send_json({ "messages_payload": "previous_messages", "messages": messages, "new_page_number": new_page_number })
Python
nomic_cornstack_python_v1
comment ----------------------------------- comment 简述:一个整数,它加上100和加上268后都是一个完全平方数 comment 提问:请问该数是多少? comment Python解题思路分析:在10000以内判断,将该数加上100后再开方,加上268后再开方, comment 如果开方后的结果满足如下条件,即是结果,Python完全平方数. comment ----------------------------------- import math comment 错误解法:math.sqrt()函数的返回值始终是float型,则不能用ininstance判断 string ...
#----------------------------------- #简述:一个整数,它加上100和加上268后都是一个完全平方数 #提问:请问该数是多少? #Python解题思路分析:在10000以内判断,将该数加上100后再开方,加上268后再开方, # 如果开方后的结果满足如下条件,即是结果,Python完全平方数. #----------------------------------- import math #错误解法:math.sqrt()函数的返回值始终是float型,则不能用ininstance判断 ''' for i in range(10000): print(i) if isinstan...
Python
zaydzuhri_stack_edu_python
function stop_following follow_id begin if not user begin call flash string Access unauthorized. string danger return call redirect string / end set followed_user = call get_or_404 follow_id remove following followed_user commit session return call redirect string /users/ { id } /following end function
def stop_following(follow_id): if not g.user: flash("Access unauthorized.", "danger") return redirect("/") followed_user = User.query.get_or_404(follow_id) g.user.following.remove(followed_user) db.session.commit() return redirect(f"/users/{g.user.id}/following")
Python
nomic_cornstack_python_v1
from player import RLAgent , Human from game import Game import random import numpy as np from time import time import json import sys import os set game_board_width = 2 set game_board_height = 2 set gamma = 0.9 set learning_rate = 0.0001 set batch_size = 150 set copy_weights_switch = 1000 set replay_memory_size = 1000...
from player import RLAgent, Human from game import Game import random import numpy as np from time import time import json import sys import os game_board_width = 2 game_board_height = 2 gamma = 0.9 learning_rate = 0.0001 batch_size = 150 copy_weights_switch = 1000 replay_memory_size = 10000 def save_data(data, file_...
Python
zaydzuhri_stack_edu_python
import cv2 import os from scipy import ndimage from scipy.spatial import distance from sklearn.cluster import KMeans comment takes all images and convert them to grayscale. comment return a dictionary that holds all images category by category. function load_images_from_folder folder begin set images = dict for filena...
import cv2 import os from scipy import ndimage from scipy.spatial import distance from sklearn.cluster import KMeans # takes all images and convert them to grayscale. # return a dictionary that holds all images category by category. def load_images_from_folder(folder): images = {} for filename in os.listdir(fo...
Python
zaydzuhri_stack_edu_python
from typing import List comment data structure import pandas as pd import numpy as np comment OpenCV import cv2 comment OS import glob import random import math from sys import float_info import os comment In-house library from src.models.person import Person from src.models.detail_predict import DetailPredict from src...
from typing import List #data structure import pandas as pd import numpy as np #OpenCV import cv2 #OS import glob import random import math from sys import float_info import os #In-house library from src.models.person import Person from src.models.detail_predict import DetailPredict from src.models.eigen_faces impor...
Python
zaydzuhri_stack_edu_python
function update begin print string %s Checking for updates... % INFO set process = popen string git pull %s HEAD % GIT_REPOSITORY shell=true stdout=PIPE stderr=PIPE set tuple stdout stderr = communicate process set success = not returncode if success begin set updated = string Already not in stdout set process = popen ...
def update(): print("%s Checking for updates..." % INFO) process = Popen("git pull %s HEAD" % GIT_REPOSITORY, shell=True, stdout=PIPE, stderr=PIPE) stdout, stderr = process.communicate() success = not process.returncode if success: updated = "Already" not in stdout ...
Python
nomic_cornstack_python_v1
string Common code for tests which convert a JSON test set into a numeric score from __future__ import absolute_import , division , print_function , with_statement , unicode_literals set __author__ = string Stephan Sokolow (deitarion/SSokolow) set __license__ = string MIT import json , sys if major > 2 begin comment py...
"""Common code for tests which convert a JSON test set into a numeric score""" from __future__ import (absolute_import, division, print_function, with_statement, unicode_literals) __author__ = "Stephan Sokolow (deitarion/SSokolow)" __license__ = "MIT" import json, sys if sys.version_info.majo...
Python
zaydzuhri_stack_edu_python
function current_spi_to_number self begin string Convert subpage & subitem to a integer * if page == 1, then return 0, since the item count is the true # of items * if page == 2, then return, page-1 * items_per_page, since we are returning the # of items on a full page. Args: * None Returns: * Integer - Which represent...
def current_spi_to_number(self): """ Convert subpage & subitem to a integer * if page == 1, then return 0, since the item count is the true # of items * if page == 2, then return, page-1 * items_per_page, since we are returning the # of items on a full page. Args: * None Ret...
Python
jtatman_500k
function test_invitations_status_expiry session begin set sent_date = now - time delta minutes=integer AFFILIATION_TOKEN_EXPIRY_PERIOD_MINS set invitation = call factory_affiliation_invitation_model session=session status=string PENDING sent_date=sent_date add session invitation commit session set result : str = status...
def test_invitations_status_expiry(session): sent_date = datetime.now() - timedelta(minutes=int(get_named_config().AFFILIATION_TOKEN_EXPIRY_PERIOD_MINS)) invitation = factory_affiliation_invitation_model(session=session, status='PENDING', sent_date=sent_date) session.add(invitation) session.commit() ...
Python
nomic_cornstack_python_v1
function partition_by_rating begin set review_data = call get_review_data set partition = list list list list list list for data in review_data begin append partition at data at string stars - 1 data end return partition end function
def partition_by_rating(): review_data = get_review_data() partition = [[],[],[],[],[]] for data in review_data: partition[data["stars"] - 1].append(data) return partition
Python
nomic_cornstack_python_v1
function process_new_user begin set username = form at string username set date_of_birth = form at string date_of_birth set full_name = form at string full_name set new_profile = call Profile username=username api_token=string bananas date_of_birth=date_of_birth full_name=full_name add session new_profile commit sessio...
def process_new_user(): username = request.form["username"] date_of_birth = request.form["date_of_birth"] full_name = request.form["full_name"] new_profile = Profile( username=username, api_token="bananas", date_of_birth=date_of_birth, full_name=full_name ) db....
Python
nomic_cornstack_python_v1
string Third Project: Optimization of uCIR code. Subject: MC921 - Construction of Compilers Authors: Victor Ferreira Ferrari - RA 187890 Vinicius Couto Espindola - RA 188115 University of Campinas - UNICAMP - 2020 Last Modified: 09/07/2020. from os.path import exists import re class uCIROptimizer extends object begin f...
''' Third Project: Optimization of uCIR code. Subject: MC921 - Construction of Compilers Authors: Victor Ferreira Ferrari - RA 187890 Vinicius Couto Espindola - RA 188115 University of Campinas - UNICAMP - 2020 Last Modified: 09/07/2020. ''' from os.path import exists import re class uCIROptimizer(obj...
Python
zaydzuhri_stack_edu_python
while c < n begin print z set z = x + y set y = x set x = z set c = c + 1 end
while c < n: print (z) z=x+y y=x x=z c=c+1
Python
zaydzuhri_stack_edu_python
function _lost self roll point begin pass end function
def _lost(self, roll, point): pass
Python
nomic_cornstack_python_v1
import random from linear_algebra import distance from stats import mean import matplotlib.pyplot as plt function random_point dim begin return list comprehension random for _ in range dim end function function random_distances dim num_pairs begin return list comprehension distance call random_point dim call random_poi...
import random from linear_algebra import distance from stats import mean import matplotlib.pyplot as plt def random_point(dim): return [random.random() for _ in range(dim)] def random_distances(dim, num_pairs): return [distance(random_point(dim), random_point(dim)) for _ in range(num_pairs)] d...
Python
zaydzuhri_stack_edu_python
function sanitize buf backspaces=list string  string   escape_regex=compile string \x1b(\[|\]|\(|\))[;?0-9]*[0-9A-Za-z](.*\x07)? begin comment Filter out control characters comment First, handle the backspaces. for backspace in backspaces begin try begin while true begin set ind = index buf backspace set buf = jo...
def sanitize(buf, backspaces=['\x08\x1b[K', '\x08 \x08'], escape_regex=re.compile(r'\x1b(\[|\]|\(|\))[;?0-9]*[0-9A-Za-z](.*\x07)?')): # Filter out control characters # First, handle the backspaces. for backspace in backspaces: try: while True: i...
Python
nomic_cornstack_python_v1
function test_Resector1 self begin call delayDisplay string Starting the test comment first, get some data import SampleData call downloadFromURL nodeNames=string FA fileNames=string FA.nrrd uris=string http://slicer.kitware.com/midas3/download?items=5767 checksums=string SHA256:12d17fba4f2e1f1a843f0757366f28c3f3e1a8bb...
def test_Resector1(self): self.delayDisplay("Starting the test") # # first, get some data # import SampleData SampleData.downloadFromURL( nodeNames='FA', fileNames='FA.nrrd', uris='http://slicer.kitware.com/midas3/download?items=5767', checksums='SHA256:12d17fba4f2e1f1a8...
Python
nomic_cornstack_python_v1
comment Задание 2. В приложении парсинга википедии получить первую ссылку на comment другую страницу и вывести все значимые слова из неё. Результат записать comment в файл в форматированном виде comment Задание 3.*Научить приложение определять количество ссылок в статье. comment Спарсить каждую ссылку и результаты запи...
# Задание 2. В приложении парсинга википедии получить первую ссылку на # другую страницу и вывести все значимые слова из неё. Результат записать # в файл в форматированном виде # Задание 3.*Научить приложение определять количество ссылок в статье. # Спарсить каждую ссылку и результаты записать в отдельные файлы. impo...
Python
zaydzuhri_stack_edu_python
import logging from flask_restful import Resource , reqparse from marshmallow_sqlalchemy import ModelSchema from dropshipping import db from dropshipping.models.categoria import Categoria class CategoriaSchema extends ModelSchema begin class Meta begin set model = Categoria end class end class class ListaCategoriaAPI e...
import logging from flask_restful import Resource, reqparse from marshmallow_sqlalchemy import ModelSchema from dropshipping import db from dropshipping.models.categoria import Categoria class CategoriaSchema(ModelSchema): class Meta: model = Categoria class ListaCategoriaAPI(Resource): def __init...
Python
zaydzuhri_stack_edu_python
function _convert_mode self mode begin if mode in map_atstr_id begin set at = call get_agent_type mode return tuple call get_name mode end if mode in map_name_atstr begin return tuple mode map_name_atstr at mode end comment for distance-based shortest path calculation only comment it shall not be used with any accessib...
def _convert_mode(self, mode): if mode in self.map_atstr_id: at = self.get_agent_type(mode) return at.get_name(), mode if mode in self.map_name_atstr: return mode, self.map_name_atstr[mode] # for distance-based shortest path calculation only # it sha...
Python
nomic_cornstack_python_v1
string Title housemate Author ITSC (Taewon Kang) Date 2018.08.30 class house_sasa begin set sub_title = string SASA comment 객체를 제작할 때 실행됨 function __init__ self name begin set target_name = sub_title + name end function function go_place self place begin print string %s, %s 로 이동중! % tuple target_name place end function...
""" Title housemate Author ITSC (Taewon Kang) Date 2018.08.30 """ class house_sasa: sub_title = "SASA " def __init__(self, name): # 객체를 제작할 때 실행됨 self.target_name = self.sub_title + name def go_place(self, place): print("%s, %s 로 이동중!" % (self.target_name, place)) cl...
Python
zaydzuhri_stack_edu_python
from web3 import Web3 from web3.personal import Personal comment Create a Web3 instance to use set w3 = call Web3 call EthereumTesterProvider comment Create a Personal instance to use set personal = call Personal w3 comment Generate a new wallet address set address = call newAccount string my_wallet_password comment Ou...
from web3 import Web3 from web3.personal import Personal # Create a Web3 instance to use w3 = Web3(Web3.EthereumTesterProvider()) # Create a Personal instance to use personal = Personal(w3) # Generate a new wallet address address = personal.newAccount('my_wallet_password') print(address) # Output: 0x...
Python
jtatman_500k
function magic arr i=0 begin if arr at i == i begin return i end if i == length arr - 1 or arr at i > length arr - 1 begin return none end return call magic arr max arr at i i + 1 end function
def magic(arr, i=0): if arr[i] == i: return i if i == len(arr) - 1 or arr[i] > len(arr) - 1: return None return magic(arr, max(arr[i], i + 1))
Python
zaydzuhri_stack_edu_python
import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 function process_image image begin set image = array image comment ref_point = [(0, 300), (1072, 720)] comment plt.imshow(image, cmap="hot") comment plt.show() comment image = image[ref_point[0][1]:ref_point[1][1], ref_point[...
import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np import cv2 def process_image(image): image = np.array(image) #ref_point = [(0, 300), (1072, 720)] #plt.imshow(image, cmap="hot") #plt.show() #image = image[ref_point[0][1]:ref_point[1][1], ref_point[0][0]:ref_po...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python from z3 import * function IntArr prefix sz N begin string Create a vector with N Bit-Vectors of size sz return list comprehension call BitVec string %s__%s % tuple prefix i sz for i in range N end function function get_var_name **kwargs begin return keys kwargs at 0 end function function getEle...
#!/usr/bin/python from z3 import * def IntArr(prefix, sz, N): """Create a vector with N Bit-Vectors of size sz""" return [ BitVec('%s__%s' % (prefix, i), sz) for i in range(N) ] def get_var_name(**kwargs): return kwargs.keys()[0] def getElement(arr , idx, name1, name2, name3): #if type(idx) is int: # ...
Python
zaydzuhri_stack_edu_python
import requests import pytest import json import random import string function _url path begin return string https://automationintesting.online/ + path + string / end function function _error_message resp begin return format string response is {0} text end function function generate_random_numeric_string length begin r...
import requests import pytest import json import random import string def _url(path): return 'https://automationintesting.online/' + path + '/' def _error_message(resp): return "\nresponse is {0}\n".format(resp.text) def generate_random_numeric_string(length): return ''.join(random.choices(string.digits,...
Python
zaydzuhri_stack_edu_python
if result % 2 == 0 begin print result string its even end else begin print result string its odd end
if result%2==0: print(result,"its even") else: print(result,"its odd")
Python
zaydzuhri_stack_edu_python
while 1 begin if length messi_n >= n begin break end set messi_n2 = messi_n1 set messi_n1 = messi_n set messi_n = messi_n1 + messi_n2 end if messi_n at n - 1 == string begin print string Messi Messi Gimossi end else begin print messi_n at n - 1 end
while 1: if len(messi_n) >= n: break messi_n2 = messi_n1 messi_n1 = messi_n messi_n = messi_n1 + messi_n2 if messi_n[n-1] == " ": print("Messi Messi Gimossi") else: print(messi_n[n-1])
Python
zaydzuhri_stack_edu_python
for i in range 1 n + 1 begin if i % x == 0 and i % y == 0 begin print string FizzBuzz end else if i % x == 0 begin print string Fizz end else if i % y == 0 begin print string Buzz end else begin print i end end
for i in range(1, n + 1): if i % x == 0 and i % y == 0: print("FizzBuzz") elif i % x == 0: print("Fizz") elif i % y == 0: print("Buzz") else: print(i)
Python
zaydzuhri_stack_edu_python
function _do_node_query self addresses from_block_number to_block_number begin set parameter_addresses = if expression length addresses > 300 then none else addresses set transfer_events = call get_total_transfer_history parameter_addresses from_block=from_block_number to_block=to_block_number if parameter_addresses be...
def _do_node_query(self, addresses: List[ChecksumAddress], from_block_number: int, to_block_number: int) -> List[LogReceipt]: parameter_addresses = None if len(addresses) > 300 else addresses transfer_events = self.ethereum_client.erc20.get_total_transfer_history(parameter_address...
Python
nomic_cornstack_python_v1
comment coding: utf-8 comment In[1]: import pandas as pd comment In[2]: set df = call read_excel string Data.xlsx comment In[3]: import warnings filter warnings string ignore comment ### Vectorising Questions comment In[4]: comment allows for format() import string import pandas set mydoclist = list Questions from coll...
# coding: utf-8 # In[1]: import pandas as pd # In[2]: df = pd.read_excel('Data.xlsx') # In[3]: import warnings warnings.filterwarnings('ignore') # ### Vectorising Questions # In[4]: import string #allows for format() import pandas mydoclist = list(df.Questions) from collections import Counter for doc in ...
Python
zaydzuhri_stack_edu_python
function create_offset_transform node begin set offset_transform = call createNode string transform call match_nodes node offset_transform set offset_transform = rename offset_transform format string {node}_zero node=node return offset_transform end function
def create_offset_transform(node): offset_transform = cmds.createNode('transform') match_nodes(node, offset_transform) offset_transform = cmds.rename(offset_transform, '{node}_zero'.format(node=node)) return offset_transform
Python
nomic_cornstack_python_v1
import datetime function is_prime n begin if n < 2 begin return false end for i in range 2 integer n ^ 0.5 + 1 begin if n % i == 0 begin return false end end return true end function function execute_if_prime func begin function wrapper *args **kwargs begin set today = day if call is_prime today begin return call func ...
import datetime def is_prime(n): if n < 2: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True def execute_if_prime(func): def wrapper(*args, **kwargs): today = datetime.date.today().day if is_prime(today): re...
Python
jtatman_500k
function test_mask_type_masked_float self begin set data = list 1.0 2.0 3.0 none unknown 4.0 set tuple mask typ = call _get_mask_and_type data assert equal mask list 0 0 0 1 2 0 assert equal typ float end function
def test_mask_type_masked_float(self): data = [1.0, 2.0, 3.0, None, ihm.unknown, 4.0] mask, typ = ihm.format_bcif._get_mask_and_type(data) self.assertEqual(mask, [0, 0, 0, 1, 2, 0]) self.assertEqual(typ, float)
Python
nomic_cornstack_python_v1
function ordering self type begin string Get the attribute ordering defined in the specified XSD type information. @param type: An XSD type object. @type type: SchemaObject @return: An ordered list of attribute names. @rtype: list set result = list for tuple child ancestry in call resolve begin set name = name if name...
def ordering(self, type): """ Get the attribute ordering defined in the specified XSD type information. @param type: An XSD type object. @type type: SchemaObject @return: An ordered list of attribute names. @rtype: list """ result = [] for ...
Python
jtatman_500k
function _eval_composite self vars expr dest=none begin set parts = split strip expr string if length parts == 1 begin try begin comment Try parsing as an atom; may fail which is okay, there's more cases we comment can try below. return call _eval_atom vars parts at 0 end except NotAnAtom begin pass end end set tuple i...
def _eval_composite(self, vars, expr, dest=None): parts = expr.strip().split(" ") if len(parts) == 1: try: # Try parsing as an atom; may fail which is okay, there's more cases we # can try below. return self._eval_atom(vars, parts[0]) except NotAnAtom: pass (instr...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python string Bloom filters in Python, using SHA-1 and Python longs. My first attempt stored the whole filter in a single arbitrary-size integer, but for some reason that was 100x slower than storing it in a bunch of 256-bit integers. import sha function nbits_required n begin string Bits required to ...
#!/usr/bin/python """Bloom filters in Python, using SHA-1 and Python longs. My first attempt stored the whole filter in a single arbitrary-size integer, but for some reason that was 100x slower than storing it in a bunch of 256-bit integers. """ import sha def nbits_required(n): """Bits required to represent any...
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/env python3 import math comment Basic four function calculator. Not much just yet, might add more functionality. set choice = 0 function addition numOne numTwo begin set result = decimal numOne + decimal numTwo return result end function function subtraction numOne numTwo begin set result = decimal n...
#! /usr/bin/env python3 import math #Basic four function calculator. Not much just yet, might add more functionality. choice = 0 def addition(numOne, numTwo): result = float(numOne) + float(numTwo) return result def subtraction(numOne, numTwo): result = float(numOne) - float(numTwo) return result...
Python
zaydzuhri_stack_edu_python
function unit begin return call Vec2d 0 1 end function
def unit(): return Vec2d(0, 1)
Python
nomic_cornstack_python_v1
function prime n begin set s = list set l = range 2 n while l begin set x = l at 0 append s x set l = list comprehension i for i in l if not i % x == 0 end return s end function
def prime(n): s = [] l = range(2, n) while l: x = l[0] s.append(x) l = [i for i in l if not i % x == 0] return s
Python
zaydzuhri_stack_edu_python
function forward self feats batch_img_metas begin set mlvl_batch_img_metas = list comprehension batch_img_metas for i in range length feats return call multi_apply forward_single feats mlvl_batch_img_metas end function
def forward(self, feats: List[Tensor], batch_img_metas: List[dict]): mlvl_batch_img_metas = [batch_img_metas for i in range(len(feats))] return multi_apply(self.forward_single, feats, mlvl_batch_img_metas)
Python
nomic_cornstack_python_v1
function get_form self begin set form = call get_form pop fields string label if get kwargs string sprint_number begin set board = get objects desk__owner__user=user sequence=kwargs at string board_sequence set initial = dict string sprint get objects number=kwargs at string sprint_number board=board set widget = call ...
def get_form(self): form = super(StickerCreate, self).get_form() form.fields.pop('label') if self.kwargs.get('sprint_number'): board = Board.objects.get( desk__owner__user=self.user, sequence=self.kwargs['board_sequence'] ) fo...
Python
nomic_cornstack_python_v1
function set_message_direct self message begin set topic = mqtt_publish_topics at string cv1 at string receiver_command_node_topic at 0 % _node_number set cmd = call set_user_message bc_id message call publish topic cmd return cmd end function
def set_message_direct(self, message): topic = mqtt_publish_topics["cv1"]["receiver_command_node_topic"][0]%self._node_number cmd = self._cv.set_user_message(self._cv.bc_id, message) self._mqttc.publish(topic, cmd) return cmd
Python
nomic_cornstack_python_v1
comment Usage: python3 signed_network_extraction.py <board_name> <year1,year2,...> import os import sys import json import pickle import logging from time import time from pttnet import preprocess comment 'Gossiping' set BOARD = argv at 1 comment ['2015'] set YEARS = list comprehension y for y in split argv at 2 string...
# Usage: python3 signed_network_extraction.py <board_name> <year1,year2,...> import os import sys import json import pickle import logging from time import time from pttnet import preprocess BOARD = sys.argv[1] # 'Gossiping' YEARS = [y for y in sys.argv[2].split(',')] # ['2015'] BASE_DIR = 'data/corpus/' OUTPUT_E...
Python
zaydzuhri_stack_edu_python
function test_drydock_health_skip_update_site begin set expected_log = string Drydock did not pass health check. Continuing as "continue-on-fail" option is enabled. set req = call Response set status_code = none set action_info = dict string dag_id string update_site ; string parameters dict string continue-on-fail str...
def test_drydock_health_skip_update_site(): expected_log = ('Drydock did not pass health check. Continuing ' 'as "continue-on-fail" option is enabled.') req = Response() req.status_code = None action_info = { "dag_id": "update_site", "parameters": {"continue-on-fai...
Python
nomic_cornstack_python_v1
function feedparser_to_dict self nested_dict begin if type nested_dict == bytes begin return string nested_dict end if type nested_dict == list begin return list comprehension call feedparser_to_dict thing for thing in nested_dict end if not type nested_dict == FeedParserDict begin return nested_dict end return diction...
def feedparser_to_dict(self, nested_dict): if type(nested_dict) == bytes: return str(nested_dict) if type(nested_dict) == list: return [self.feedparser_to_dict(thing) for thing in nested_dict] if not type(nested_dict) == feedparser.FeedParserDict: return neste...
Python
nomic_cornstack_python_v1
function create_sub_directories main_directory_path sub_directory_names_list begin try begin for sub_name in sub_directory_names_list begin make directories string { main_directory_path } / { sub_name } exist_ok=true make directories string { main_directory_path } / { sub_name } exist_ok=true end end except Exception a...
def create_sub_directories(main_directory_path: str, sub_directory_names_list: list): try: for sub_name in sub_directory_names_list: os.makedirs(f"{main_directory_path}/{sub_name}", exist_ok=True) os.makedirs(f"{main_directory_path}/{sub_name}", exist_ok=True) except Exception as...
Python
nomic_cornstack_python_v1
comment !/usr/bin/python comment encoding='utf-8' string Created on: September 11, 2016 Created by: Webs class Game extends object begin function __init__ self wrong_guesses_remaining=5 guess_list=list begin set wrong_guesses_remaining = wrong_guesses_remaining set guess_list = guess_list end function end class
#!/usr/bin/python #encoding='utf-8' ''' Created on: September 11, 2016 Created by: Webs ''' class Game(object): def __init__(self, wrong_guesses_remaining=5, guess_list=[]): self.wrong_guesses_remaining = wrong_guesses_remaining self.guess_list = guess_list
Python
zaydzuhri_stack_edu_python
function SetPropertyValidator *args **kwargs begin return call PropertyGridInterface_SetPropertyValidator *args keyword kwargs end function
def SetPropertyValidator(*args, **kwargs): return _propgrid.PropertyGridInterface_SetPropertyValidator(*args, **kwargs)
Python
nomic_cornstack_python_v1
function are_all_chars_unique string begin set str_list = list string sort str_list for index in range length str_list - 1 begin if str_list at index == str_list at index + 1 begin return false end end return true end function
def are_all_chars_unique(string: str): str_list = list(string) str_list.sort() for index in range(len(str_list) - 1): if str_list[index] == str_list[index + 1]: return False return True
Python
zaydzuhri_stack_edu_python
function combineAttributesWithNodes node attribute begin set node = call makeList node set attribute = call makeList attribute set attributes = list if node at 0 begin for n in node begin for attr in attribute begin if type attr is str begin append attributes attr end else begin append attributes call __getattr__ attr...
def combineAttributesWithNodes(node, attribute): node = utils.misc.makeList(node) attribute = utils.misc.makeList(attribute) attributes = [] if node[0]: for n in node: for attr in attribute: if type(attr) is str: attributes.append(att...
Python
nomic_cornstack_python_v1
function test_create_volume_missing_iops_io1 begin set kwargs = dict string zone string us-west-2 ; string type string io1 set ret = call create_volume kwargs=kwargs call=string function assert ret is false end function
def test_create_volume_missing_iops_io1(): kwargs = {"zone": "us-west-2", "type": "io1"} ret = ec2.create_volume(kwargs=kwargs, call="function") assert ret is False
Python
nomic_cornstack_python_v1
function show_menu begin string 显示菜单 print string * * 50 print string 欢迎使用【卡片管理系统】V1.0 print string print string 1. 新增卡片 print string 2. 显示卡片 print string 3. 搜索卡片 print string print string 0. 退出系统 print string * * 50 end function function new_card begin string 新增名片 print string 新增名片 set name = input string 请输入姓名: set p...
def show_menu(): """显示菜单""" print("*" * 50) print("欢迎使用【卡片管理系统】V1.0") print("") print("1. 新增卡片") print("2. 显示卡片") print("3. 搜索卡片") print("") print("0. 退出系统") print("*" * 50) def new_card(): """新增名片""" print("新增名片") name = input("请输入姓名:") phone = input("请输入手机号:")...
Python
zaydzuhri_stack_edu_python
comment coding:utf-8 import xml.sax import sys import time import chardet insert path 0 string scripts from langconv import * import jieba import jieba.posseg as pseg call reload sys call setdefaultencoding string utf-8 class GenWord2VecMaterial extends ContentHandler begin function __init__ self of begin set CurrentDa...
# coding:utf-8 import xml.sax import sys import time import chardet sys.path.insert(0, 'scripts') from langconv import * import jieba import jieba.posseg as pseg reload(sys) sys.setdefaultencoding('utf-8') class GenWord2VecMaterial(xml.sax.ContentHandler): def __init__(self, of): self.CurrentData = "" ...
Python
zaydzuhri_stack_edu_python
function test_readhist_endpoint_get self begin comment the mock is for solr call with call object client string get as get_mock begin set return_value = call Mock set mock_response = call Mock set status_code = 200 set return_value = dict string responseHeader dict string status 0 ; string QTime 60 ; string params dict...
def test_readhist_endpoint_get(self): # the mock is for solr call with mock.patch.object(self.current_app.client, 'get') as get_mock: get_mock.return_value = mock_response = mock.Mock() mock_response.status_code = 200 mock_response.json.return_value = {u'responseHeade...
Python
nomic_cornstack_python_v1
import os import sys import urllib.request import json set client_id = string ss2uZ9mximctqJH9D5sp set client_secret = string 85JTDZCnVa comment with open('source.txt','r',encoding='utf8') as f: comment srcText = f.read() function choise begin while true begin set text = input string 번역하실 언어를 선택해주세요: if text == string ...
import os import sys import urllib.request import json client_id = "ss2uZ9mximctqJH9D5sp" client_secret = "85JTDZCnVa" #with open('source.txt','r',encoding='utf8') as f: # srcText = f.read() def choise(): while(True): text = input("번역하실 언어를 선택해주세요:") if(text == "한국어"): srcText = inp...
Python
zaydzuhri_stack_edu_python
import csv set food = list dict reader open string Food_Inspections.csv comment replace empty cells with null value function fill_cells data begin set result = call amend_duplicate_license_number data for x in result begin for value in keys x begin if x at value == string begin set x at value = string null end comment...
import csv food = list(csv.DictReader(open('Food_Inspections.csv'))) def fill_cells(data): # replace empty cells with null value result = amend_duplicate_license_number(data) for x in result: for value in x.keys(): if x[value] == '': x[value] = 'null' if len(x...
Python
zaydzuhri_stack_edu_python
function say_my_name first_name last_name=string begin if type first_name is not str begin raise call TypeError string first_name must be a string end if type last_name is not str begin raise call TypeError string last_name must be a string end print string My name is first_name last_name end function
def say_my_name(first_name, last_name=""): if type(first_name) is not str: raise TypeError("first_name must be a string") if type(last_name) is not str: raise TypeError("last_name must be a string") print("My name is", first_name, last_name)
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Thu Apr 30 21:07:11 2015 @author: Craig comment read subway/bus info from below, or drop in FF/IE comment http://web.mta.info/status/serviceStatus.txt import urllib from lxml import etree class Subway begin string class to hold data about a NYC subway line function __init...
# -*- coding: utf-8 -*- """ Created on Thu Apr 30 21:07:11 2015 @author: Craig """ # read subway/bus info from below, or drop in FF/IE #http://web.mta.info/status/serviceStatus.txt import urllib from lxml import etree class Subway(): '''class to hold data about a NYC subway line''' def __init__(self, name, ...
Python
zaydzuhri_stack_edu_python
function text_box_1_show self **event_args begin call focus end function
def text_box_1_show(self, **event_args): self.text_box_1.focus()
Python
nomic_cornstack_python_v1
comment 1 Define suitable variables set a = 999999 print type a set b = 5.55555555555 print type b set c = string x print type c set d = string Kokkola print type d set e = 2.33 print type e set f = 10 print type f set g = 300 print type g set h = 9000000000 print type h set i = 3000000000 print type i print comment 2 ...
# 1 Define suitable variables a = 999999 print (type (a)) b = 5.55555555555 print (type (b)) c = 'x' print (type (c)) d = "Kokkola" print (type (d)) e = 2.33 print (type (e)) f = 10 print (type (f)) g = 300 print (type (g)) h = 9000000000 print (type (h)) i = 3000000000 print (type (i)) print () # 2 Calculat...
Python
zaydzuhri_stack_edu_python
string Functions for files on the system import os import shutil import json from pathlib import Path from typing import List import click from app import steam_site , helpers set MODS_DETAILS_FILENAME = string mods_details.json set MODLINES_FILENAME = string modlines.json function get_current_mod_details mods_path beg...
"""Functions for files on the system""" import os import shutil import json from pathlib import Path from typing import List import click from app import steam_site, helpers MODS_DETAILS_FILENAME = "mods_details.json" MODLINES_FILENAME = "modlines.json" def get_current_mod_details(mods_path: Path) -> dict: """G...
Python
zaydzuhri_stack_edu_python
string Defines a tracker class for tracking the input temperatures class TempTracker begin string Temperature Tracker class set minimumTemperature = 0 set maximumTemperature = 110 function __init__ self begin comment A list to store the input temperature values set _tempTrackerList = list end function function isValid...
""" Defines a tracker class for tracking the input temperatures """ class TempTracker(): """ Temperature Tracker class """ minimumTemperature = 0 maximumTemperature = 110 def __init__(self): #A list to store the input temperature values self._tempTrackerList = [] def isValid(self,temperature): """...
Python
zaydzuhri_stack_edu_python
function search A x begin for i in range length A begin if A at i == x begin return i end print A at i end return - 1 end function set A = list 2 8 555 7 1 100 3 6 4 8 5 2 9 10 set x = 555 print search A x
def search(A,x): for i in range(len(A)): if A[i] == x: return i print(A[i]) return -1 A = [2,8,555,7,1,100,3,6,4,8,5,2,9,10] x = 555 print(search(A,x))
Python
zaydzuhri_stack_edu_python
for i in range n begin set SUM = SUM + a at i - i - 1 append B a at i - i - 1 end set Bs = sorted B if n % 2 == 1 begin set b = Bs at n // 2 end else begin set b = Bs at n // 2 - 1 + Bs at n // 2 // 2 end set ans = 0 for i in B begin set ans = ans + absolute i - b end print ans
for i in range(n): SUM += a[i]-i-1 B.append(a[i]-i-1) Bs = sorted(B) if n%2 == 1: b = Bs[n//2] else: b = (Bs[n//2-1]+Bs[n//2])//2 ans = 0 for i in B: ans += abs(i-b) print(ans)
Python
zaydzuhri_stack_edu_python
comment ! /usr/bin/python3 comment This program creates a dictionary of 2010 Census Tract data. import openpyxl import os import pprint change directory string /home/jddelia/python/automate/chap12/ set census_book = call load_workbook string censuspopdata.xlsx set census_sheet = call get_sheet_by_name string Population...
#! /usr/bin/python3 # This program creates a dictionary of 2010 Census Tract data. import openpyxl import os import pprint os.chdir('/home/jddelia/python/automate/chap12/') census_book = openpyxl.load_workbook('censuspopdata.xlsx') census_sheet = census_book.get_sheet_by_name('Population by Census Tract') census_da...
Python
zaydzuhri_stack_edu_python
function xgb_evaluate_fine max_depth gamma colsample_bytree subsample min_child_weight reg_lambda reg_alpha eta boost_rounds scale_pos_weight nfold=10 begin set xgb_params = dict string eval_metric string auc ; string max_depth round max_depth ; string subsample subsample ; string eta eta ; string gamma gamma ; string ...
def xgb_evaluate_fine( max_depth, gamma, colsample_bytree, subsample, min_child_weight, reg_lambda, reg_alpha, eta, boost_rounds, scale_pos_weight, nfold=10, ): xgb_params = { "eval_metric": "auc", "max_depth": round(max_depth), "subsample": subsa...
Python
nomic_cornstack_python_v1
function set_variable self name value begin if _scalamagic and not starts with name string _i begin call bind name value end else begin debug string Not setting variable %s name end end function
def set_variable(self, name, value): if self._scalamagic and (not name.startswith("_i")): self.scala_interpreter.bind(name, value) else: self.log.debug('Not setting variable %s', name)
Python
nomic_cornstack_python_v1
from typing import List import unittest from model import tasks class TestRepository extends TestCase begin function test_list self begin set rep = call Repository set l = list assert equal length l 2 assert equal id 1 assert equal text string task1 assert equal done false assert equal id 2 set done = true set l = list...
from typing import List import unittest from model import tasks class TestRepository(unittest.TestCase): def test_list(self): rep = tasks.Repository() l = rep.list() self.assertEqual(len(l), 2) self.assertEqual(l[0].id, 1) self.assertEqual(l[0].text, "task1") self....
Python
jtatman_500k
function make_csv_coder schema mode=TRAIN begin set column_names = CSV_ORDERED_COLUMNS if mode == INFER begin remove column_names LABEL_COLUMN end return call CsvCoder column_names schema delimiter=string , end function
def make_csv_coder(schema, mode=tf.contrib.learn.ModeKeys.TRAIN): column_names = CSV_ORDERED_COLUMNS if mode == tf.contrib.learn.ModeKeys.INFER: column_names.remove(LABEL_COLUMN) return coders.CsvCoder(column_names, schema, delimiter=',')
Python
nomic_cornstack_python_v1
function sign permutation begin set cycles = call to_cycle_notation permutation comment The sign of the permutation is equal to -1 to the power of the number of even cycles set num_even_cycles = 0 for perm_cycle in cycles begin if length perm_cycle % 2 == 0 begin set num_even_cycles = num_even_cycles + 1 end end return...
def sign(permutation): cycles = to_cycle_notation(permutation) # The sign of the permutation is equal to -1 to the power of the number of even cycles num_even_cycles = 0 for perm_cycle in cycles: if len(perm_cycle) % 2 == 0: num_even_cycles += 1 return (-1)**num_even_cycles
Python
nomic_cornstack_python_v1
comment cannot find CLR method function __getitem__ self *args begin pass end function
def __getitem__(self, *args): #cannot find CLR method pass
Python
nomic_cornstack_python_v1
function _postprocess self doc parsed_doc begin return parsed_doc end function
def _postprocess(self, doc, parsed_doc): return parsed_doc
Python
nomic_cornstack_python_v1
import hashlib import hmac import time import requests import config set NAME = string Bittrex set BASE_URL = string https://bittrex.com/api/v1.1/ set URL = BASE_URL + string account/getbalances?apikey={api_key}&nonce={nonce} function get_balances begin set nonce = string integer time * 1000 set url = format URL api_ke...
import hashlib import hmac import time import requests import config NAME = 'Bittrex' BASE_URL = 'https://bittrex.com/api/v1.1/' URL = BASE_URL + 'account/getbalances?apikey={api_key}&nonce={nonce}' def get_balances(): nonce = str(int(time.time() * 1000)) url = URL.format(api_key=config.TREX_KEY, nonce=nonce) ...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Converts most ascii chars into the upside-down equivalent in unicode. Mostly a toy to figure out how to write add-ons for Sublime Text. import sublime , sublime_plugin set _UD_CHAR_CODES = dict string string ; string _ string ‾ ; string ? string ¿ ; string ! string ¡ ; string " st...
# -*- coding: utf-8 -*- """ Converts most ascii chars into the upside-down equivalent in unicode. Mostly a toy to figure out how to write add-ons for Sublime Text. """ import sublime, sublime_plugin _UD_CHAR_CODES = { ' ': ' ', # single space '_': u'\u203E', '?': u'\u00BF', '!': u'\u00A1', '"'...
Python
zaydzuhri_stack_edu_python
import sys for line in stdin begin set x = split strip line set m = x at 0 set n = x at 1 if m == string 0 and n == string 0 begin break end if length n < 2 begin set p = integer n end else begin set p = integer n at slice - 2 : : end set q = integer m at - 1 if q == 0 begin set res = 0 end else if q == 1 begin set re...
import sys for line in sys.stdin: x = line.strip().split() m = x[0] n = x[1] if m == '0' and n == '0': break if len(n) < 2: p = int(n) else: p = int(n[-2:]) q = int(m[-1]) if q == 0: res = 0 elif q == 1: res = 1 elif q == 2: t = p % 4 u = [2, 4, 8, 6] res = u[t - 1] elif q == 3: t = ...
Python
zaydzuhri_stack_edu_python
function add_reactive_forwarders cl functions begin function add_one cl name func begin function wrapped self *args begin decorator reactive comment fixme: we should rather forward to the _target, not to __eval__ function reactive_f self_unwrapped *args begin return call func self_unwrapped *args end function set prefi...
def add_reactive_forwarders(cl: Any, functions: Iterable[Tuple[str, Callable]]): def add_one(cl: Any, name, func): def wrapped(self, *args): @reactive # fixme: we should rather forward to the _target, not to __eval__ def reactive_f(self_unwrapped, *args): return fun...
Python
nomic_cornstack_python_v1
function __getSimple self begin set resp2 = dict for item in tesult begin if item == RESPONSE begin for item1 in call response begin set resp2 at item1 = call response at item1 end end else begin set resp2 at item = tesult at item end end return resp2 string Solo por compatibilidad quitar cunado marcio implemente el s...
def __getSimple(self): resp2={} for item in self.tesult: if item==self.RESPONSE: for item1 in self.response(): resp2[item1]=self.response()[item1] else: resp2[item]=self.tesult[item] return resp2 ...
Python
nomic_cornstack_python_v1