code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function test_filter_by_product self begin set one = call create name=string Foo 1 call create name=string Foo 2 set res = get self params=dict string filter-product string id call assertInList res string Foo 1 call assertNotInList res string Foo 2 end function
def test_filter_by_product(self): one = self.factory.create(name="Foo 1") self.factory.create(name="Foo 2") res = self.get( params={"filter-product": str(one.product.id)}) self.assertInList(res, "Foo 1") self.assertNotInList(res, "Foo 2")
Python
nomic_cornstack_python_v1
string Name: Heecheon Park Date: September 6th 2019 Minnesota State University Moorhead Running 1000x1000 matrix multiplication with list and mpi with 5 processors. Execution Method: mpiexec -np 5 python3 mpi_list_matmult.py from mpi4py import MPI from numba import njit , jit import numpy as np import sys import time s...
""" Name: Heecheon Park Date: September 6th 2019 Minnesota State University Moorhead Running 1000x1000 matrix multiplication with list and mpi with 5 processors. Execution Method: mpiexec -np 5 python3 mpi_list_matmult.py """ from mpi4py import MPI from numba import njit, jit import numpy as np import sys import ti...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment encoding: utf-8 import json import numpy import networkx import matplotlib.pylab as plt comment TODO Student: Read the Graph from 'valar-morghulis.gml.gz' using networkx comment and convert it to an undirected graph. comment TODO Student: Use the method for community detection descr...
#!/usr/bin/env python # encoding: utf-8 import json import numpy import networkx import matplotlib.pylab as plt # TODO Student: Read the Graph from 'valar-morghulis.gml.gz' using networkx # and convert it to an undirected graph. # TODO Student: Use the method for community detection described in the # ...
Python
zaydzuhri_stack_edu_python
function create_compute_worker_config self worker_config=none lightly_config=none selection_config=none begin if is instance selection_config dict begin set selection = call selection_config_from_dict cfg=selection_config end else begin set selection = selection_config end if worker_config is not none begin set worker_...
def create_compute_worker_config( self, worker_config: Optional[Dict[str, Any]] = None, lightly_config: Optional[Dict[str, Any]] = None, selection_config: Optional[Union[Dict[str, Any], SelectionConfig]] = None, ) -> str: if isinstance(selection_config, dict): sel...
Python
nomic_cornstack_python_v1
from sqlalchemy import create_engine from db.config import DATABASE_URI from db.members import Member from sqlalchemy.orm import sessionmaker from contextlib import contextmanager set engine = call create_engine DATABASE_URI set Session = call sessionmaker bind=engine decorator contextmanager function session_scope beg...
from sqlalchemy import create_engine from db.config import DATABASE_URI from db.members import Member from sqlalchemy.orm import sessionmaker from contextlib import contextmanager engine = create_engine(DATABASE_URI) Session = sessionmaker(bind=engine) @contextmanager def session_scope(): session = Session() ...
Python
zaydzuhri_stack_edu_python
function getFactors num begin set number = range 1 num + 1 set sum = 0 for i in number begin if num % i == 0 begin print i set sum = sum + i end end end function
def getFactors(num): number = range(1, num+1); sum =0; for i in number: if(num % i == 0): print(i); sum = sum + i;
Python
zaydzuhri_stack_edu_python
function f a d k n begin if k > n begin return a end return f dist a + d d k + 1 n end function set parts = split input set a = integer parts at 0 set b = integer parts at 1 if b < 0 begin print f dist a - 1 1 absolute b end else begin print f dist a 1 1 absolute b end
def f(a, d, k, n): if k > n: return a return f(a + d, d, k + 1, n) parts = input().split() a = int(parts[0]) b = int(parts[1]) if b < 0: print(f(a, -1, 1, abs(b))) else: print(f(a, 1, 1, abs(b)))
Python
zaydzuhri_stack_edu_python
function Get_Isolation_Areas_With_Items self begin try begin set _isolation_areas = dictionary for _iso in find all string ./Isolation_Areas/Isolation_Area begin set _isolation_items = dictionary set _isolation_items at string ID = integer attrib at string ID set _isolation_items at string Track_ID = text set _isolatio...
def Get_Isolation_Areas_With_Items(self): try: _isolation_areas = dict() for _iso in self.root_node.findall('./Isolation_Areas/Isolation_Area'): _isolation_items = dict() _isolation_items['ID'] = int(_iso.attrib['ID']) ...
Python
nomic_cornstack_python_v1
import matplotlib.pyplot as plt import math set fig = figure string Function Growth, n = 20 figsize=tuple 7 7 set ax = call add_subplot 111 set n = 1002 set lin = list comprehension x for x in range 1 n set quad = list comprehension x * x for x in range 1 n set log = list comprehension log x for x in range 1 n set nlog...
import matplotlib.pyplot as plt import math fig = plt.figure("Function Growth, n = 20", figsize=(7, 7)) ax = fig.add_subplot(111) n = 1002 lin = [x for x in range(1,n)] quad = [x*x for x in range(1,n)] log = [math.log(x) for x in range(1,n)] nlog = [n*math.log(x) for x in range(1,n)] cubic = [x*x*x for x in range(1,n...
Python
zaydzuhri_stack_edu_python
from entities.level import Level from entities.vehicle import Vehicle class ParkingSystem extends object begin function __init__ self slots_per_row rows_per_level levels begin set level_count = levels set rows_per_level = rows_per_level set slots_per_row = slots_per_row set levels = list set vehicle_slot_registry = di...
from entities.level import Level from entities.vehicle import Vehicle class ParkingSystem(object): def __init__(self, slots_per_row, rows_per_level, levels): self.level_count = levels self.rows_per_level = rows_per_level self.slots_per_row = slots_per_row self.levels = [] ...
Python
zaydzuhri_stack_edu_python
function handle_create self **kwargs begin raise call NotImplementedError end function
def handle_create(self, **kwargs): raise NotImplementedError()
Python
nomic_cornstack_python_v1
import gensim import logging import argparse set parser = call ArgumentParser description=string Script for finding similar items call add_argument string -w string --words type=str help=string Query terms set args = call parse_args set model = load Word2Vec string /Users/Rishita/ITIS/semester_02/myModelBonus set wordl...
import gensim import logging import argparse parser = argparse.ArgumentParser(description='Script for finding similar items') parser.add_argument('-w', '--words', type=str, help='Query terms') args = parser.parse_args() model = gensim.models.Word2Vec.load('/Users/Rishita/ITIS/semester_02/myModelBonus') wordlist = args...
Python
zaydzuhri_stack_edu_python
function load_data image_key=string x label_key=string y begin set dirname = string ciFAIR-10 set archive_name = string ciFAIR-10.zip set origin = string https://github.com/cvjena/cifair/releases/download/v1.0/ciFAIR-10.zip set md5_hash = string ca08fd390f0839693d3fc45c4e49585f set path = call get_file archive_name ori...
def load_data(image_key: str = "x", label_key: str = "y") -> Tuple[NumpyDataset, NumpyDataset]: dirname = 'ciFAIR-10' archive_name = 'ciFAIR-10.zip' origin = 'https://github.com/cvjena/cifair/releases/download/v1.0/ciFAIR-10.zip' md5_hash = 'ca08fd390f0839693d3fc45c4e49585f' path = get_file(archive...
Python
nomic_cornstack_python_v1
with open string p022_names.txt string r as f begin set names = replace read line f string " string end set names = split names string , function name_to_value name begin set value = 0 for i in range length name begin set value = value + ordinal name at i - 64 end return value end function sort names set total = 0 for ...
with open('p022_names.txt', 'r') as f: names = f.readline().replace("\"", "") names = names.split(',') def name_to_value(name): value = 0 for i in range(len(name)): value += ord(name[i]) - 64 return value names.sort() total = 0 for i in range(len(names)): total += name_to_value(names[i]...
Python
zaydzuhri_stack_edu_python
function run self begin call collect_data end function
def run(self): self.collect_data()
Python
nomic_cornstack_python_v1
function playerStandings begin set tuple db cur = call connect comment results from VIEW set query = string SELECT id, player, wins, played from results order by wins desc; execute cur query set players = call fetchall close cur return players end function
def playerStandings(): db, cur = connect() # results from VIEW query = "SELECT id, player, wins, played from results order by wins desc;" cur.execute(query) players = cur.fetchall() cur.close() return players
Python
nomic_cornstack_python_v1
function phase_delay self az elv begin set az = pi * az / 180.0 set elv = pi * elv / 180.0 set phase_shift = 2 * pi * x_loc * sin elv * cos az + y_loc * sin elv * sin az set time_deley = - phase_shift / 2.0 * pi * lamb / 1500.0 comment print "time delay = ", time_deley set complex_phase_shift = exp 1j * phase_shift set...
def phase_delay(self, az, elv): az = pi * az / 180.0 elv = pi * elv / 180.0 phase_shift = 2 * pi * (self.x_loc * np.sin(elv) * np.cos(az) + self.y_loc * np.sin(elv) * np.sin(az)) time_deley = -(phase_shift / (2.0 * pi)) * (self.lamb / 1500.0) # print "time delay = ", time_deley ...
Python
nomic_cornstack_python_v1
class Solution begin function countVowelSubstrings self word begin set vowels = set literal string a string e string i string o string u set tuple ans last_consonant = tuple 0 - 1 set last_seen_vowels = dictionary comprehension v : - 2 for v in vowels for tuple i x in enumerate word begin if x not in vowels begin set l...
class Solution: def countVowelSubstrings(self, word: str) -> int: vowels = {'a', 'e', 'i', 'o', 'u'} ans, last_consonant = 0, -1 last_seen_vowels = {v: -2 for v in vowels} for i, x in enumerate(word): if x not in vowels: last_consonant = i els...
Python
zaydzuhri_stack_edu_python
function model_to_rest_resource self model verbose=false begin return call to_dict verbose end function
def model_to_rest_resource(self, model, verbose=False): return Resource(model, PREFERENCE_FIELDS).to_dict(verbose)
Python
nomic_cornstack_python_v1
import pandas as pd set df = read csv string C:\Users\Deependu Mandal\Desktop\knn.csv set df = drop df list 13 set df = drop df labels=string Index axis=1 set df at string Age = fill missing df at string Age mean df at string Age set df at string Salary = fill missing df at string Salary mean df at string Salary head d...
import pandas as pd df = pd.read_csv(r'C:\Users\Deependu Mandal\Desktop\knn.csv') df = df.drop([13]) df = df.drop(labels='Index',axis=1) df['Age'] = df['Age'].fillna(df['Age'].mean()) df['Salary'] = df['Salary'].fillna(df['Salary'].mean()) df.head(15) X = df.drop(labels='Purchase_Item',axis=1) print(X) Y = df[['...
Python
zaydzuhri_stack_edu_python
import os from pygame import mixer import tkinter as tk from tkinter import * from tkinter.filedialog import askdirectory from mutagen.id3 import ID3 , ID3NoHeaderError from tkinter import messagebox set listOfSongs = list set realNames = list set index = 0 function createWidgets begin set trackLabel = call Label roo...
import os from pygame import mixer import tkinter as tk from tkinter import * from tkinter.filedialog import askdirectory from mutagen.id3 import ID3, ID3NoHeaderError from tkinter import messagebox listOfSongs =[] realNames =[] index = 0 def createWidgets(): trackLabel = Label(root, text="Select Your Track: ")...
Python
zaydzuhri_stack_edu_python
function populate_plot self plot data begin comment Determine which type of line gets which color set color_map = dict string REF Category20c_20 at 16 ; string REF1 Category20c_20 at 16 ; string REF2 Category20c_20 at 16 ; string REF3 Category20c_20 at 16 ; string REF4 Category20c_20 at 16 ; string SCRIBE_LINE Category...
def populate_plot(self, plot, data): # Determine which type of line gets which color color_map = { 'REF': Category20c_20[16], 'REF1': Category20c_20[16], 'REF2': Category20c_20[16], 'REF3': Category20c_20[16], 'REF4': Categ...
Python
nomic_cornstack_python_v1
import pandas as pd import random set diccionario_notas = dict string Crecencio list 87 100 none ; string Domitilia list 80 none 57 ; string Rutilio list 80 78 57 ; string Ludoviko list 100 100 100 set notas_diccionario = call DataFrame diccionario_notas print notas_diccionario print string set index = list string Prog...
import pandas as pd import random diccionario_notas= {"Crecencio":[87,100,None], \ "Domitilia":[80,None,57], \ "Rutilio":[80,78,57],\ "Ludoviko":[100,100,100]} notas_diccionario= pd.DataFrame(diccionario_notas) print(notas_diccionario) print(...
Python
zaydzuhri_stack_edu_python
function register_callback self begin raise exception string not implemented end function
def register_callback(self): raise Exception('not implemented')
Python
nomic_cornstack_python_v1
class BankAccount begin function __init__ self interest=0 balance=0 begin set interest = interest set balance = balance end function end class
class BankAccount: def __init__(self, interest = 0, balance = 0): self.interest = interest self.balance = balance
Python
zaydzuhri_stack_edu_python
set A = integer input string Enter A : if A < 10 and A != 10 begin print A string < 10 string : Yes end
A=int(input("Enter A : ")) if(A<10 and A!=10): print(A,"< 10",": Yes")
Python
zaydzuhri_stack_edu_python
comment 1 comment / \ comment 2 3 comment return [[1], [3, 2]] comment Ex: Given the following tree… comment 8 comment / \ comment 2 29 comment / \ comment 3 9 comment return [[8], [29, 2], [3, 9]] comment keep track of levels, if even level push right child first, if odd, push left first
# 1 # / \ # 2 3 # return [[1], [3, 2]] # Ex: Given the following tree… # 8 # / \ # 2 29 # / \ # 3 9 # return [[8], [29, 2], [3, 9]] # keep track of levels, if even level push right child first, if odd, push left first
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import urllib import time from datetime import datetime function urlopen url begin try begin return url open url=url end except any begin return none end end function function server_test url begin print call isoformat if url open url begin print string The server is runing ! end else begi...
# -*- coding: utf-8 -*- import urllib import time from datetime import datetime def urlopen(url): try: return urllib.urlopen(url=url) except: return None def server_test(url): print(datetime.now().isoformat()) if urlopen(url): print("The server is runing !") else: ...
Python
zaydzuhri_stack_edu_python
while true begin set task = input if task == string Enough begin print string Average score: { grade_sum / grade_counter } print string Number of problems: { grade_counter } print string Last problem: { last_task } break end set last_task = task set grade = integer input set grade_counter = grade_counter + 1 set grade_...
while True: task = input() if task == 'Enough': print(f'Average score: {grade_sum / grade_counter:.2f}') print(f'Number of problems: {grade_counter}') print(f'Last problem: {last_task}') break last_task = task grade = int(input()) grade_counter += 1 ...
Python
zaydzuhri_stack_edu_python
import unittest from mycroft import helpers class MockSocket begin string Mocks a Python socket function __init__ self begin set bytes = b'' end function function send self bytes_ begin set bytes = bytes + bytes_ end function end class class TestParseMessage extends TestCase begin function test_msg_with_body self begin...
import unittest from mycroft import helpers class MockSocket(): """ Mocks a Python socket """ def __init__(self): self.bytes = b'' def send(self, bytes_): self.bytes += bytes_ class TestParseMessage(unittest.TestCase): def test_msg_with_body(self): helper = helpers...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Updated Jan 21, 2018 The primary goal of this file is to demonstrate a simple unittest implementation @author: jrr @author: rk import unittest from Triangle import classifyTriangle comment This code implements the unit test functionality comment https://docs.python.org/3/library/uni...
# -*- coding: utf-8 -*- """ Updated Jan 21, 2018 The primary goal of this file is to demonstrate a simple unittest implementation @author: jrr @author: rk """ import unittest from Triangle import classifyTriangle # This code implements the unit test functionality # https://docs.python.org/3/library/unittest.html ha...
Python
zaydzuhri_stack_edu_python
function reverse_array arr begin set start = 0 set end = length arr - 1 while start < end begin set tuple arr at start arr at end = tuple arr at end arr at start set start = start + 1 set end = end - 1 end return arr end function
def reverse_array(arr): start = 0 end = len(arr) - 1 while start < end: arr[start], arr[end] = arr[end], arr[start] start += 1 end -= 1 return arr
Python
greatdarklord_python_dataset
function get self title begin set post = call get_a_post title if not post begin call abort 404 end else begin return post end end function
def get(self, title): post = get_a_post(title) if not post: api.abort(404) else: return post
Python
nomic_cornstack_python_v1
function line_is_valid line begin if string - in map lambda item -> strip item split strip line string ; begin return false end else begin return true end end function
def line_is_valid(line): if '-' in map(lambda item: item.strip(), line.strip().split(";")): return False else: return True
Python
nomic_cornstack_python_v1
import tweepy import csv comment import datetime comment import sys comment coloque aqui as suas credenciais do seu app twitter set consumer_key = string set consumer_secret = string set access_token = string set access_token_secret = string set auth = call OAuthHandler consumer_key consumer_secret call set_access_...
import tweepy import csv # import datetime # import sys # coloque aqui as suas credenciais do seu app twitter consumer_key = '' consumer_secret = '' access_token = '' access_token_secret = '' auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy...
Python
zaydzuhri_stack_edu_python
function __init__ self dim rn gammak=1.0 sine=false begin set dim = dim set rn = rn set gammak = gammak set sine = sine call generateCoefficients end function
def __init__(self, dim, rn, gammak=1.0, sine=False): self.dim = dim self.rn = rn self.gammak = gammak self.sine = sine self.generateCoefficients()
Python
nomic_cornstack_python_v1
function append self element begin append path element end function
def append(self, element): self.path.append(element)
Python
nomic_cornstack_python_v1
function __init__ self *args begin call TUndirNet_swiginit self call new_TUndirNet *args end function
def __init__(self, *args): _snap.TUndirNet_swiginit(self, _snap.new_TUndirNet(*args))
Python
nomic_cornstack_python_v1
function pipeline_families request begin set t = call get_template string pipeline/pipeline_families.html set c = dict string is_user_admin call admin_check user return call HttpResponse call render c request end function
def pipeline_families(request): t = loader.get_template('pipeline/pipeline_families.html') c = { "is_user_admin": admin_check(request.user) } return HttpResponse(t.render(c, request))
Python
nomic_cornstack_python_v1
import requests , openpyxl , csv from bs4 import BeautifulSoup from random import randint set num = 0 set list = list string 豆瓣排名 string 电影名字 string 豆瓣评分 string 推荐语 string 详情链接 string wb=openpyxl.Workbook() sheet=wb.active sheet.title='movies' sheet['A1']='豆瓣排名' sheet['B1']='电影名字' sheet['C1']='豆瓣评分' sheet['D1']='推荐语' s...
import requests,openpyxl,csv from bs4 import BeautifulSoup from random import randint num=0 list=['豆瓣排名','电影名字','豆瓣评分','推荐语','详情链接'] ''' wb=openpyxl.Workbook() sheet=wb.active sheet.title='movies' sheet['A1']='豆瓣排名' sheet['B1']='电影名字' sheet['C1']='豆瓣评分' sheet['D1']='推荐语' sheet['F1']='详情链接' ''' csv_file=open('豆瓣电影top25...
Python
zaydzuhri_stack_edu_python
function write_pyfile file begin set data = call load_file file set pyfilename = string pydata_ + split file string . at 0 + string .py set pyfile = open pyfilename string w write pyfile string from numpy import * write pyfile string xl = + string data close pyfile end function
def write_pyfile(file): data = load_file(file) pyfilename = "pydata_" + file.split(".")[0] + ".py" pyfile = open(pyfilename, 'w') pyfile.write("from numpy import *\n") pyfile.write("xl = " + str(data)) pyfile.close()
Python
nomic_cornstack_python_v1
function node request node_id begin set node = call get_object_or_404 HierarchyNode pk=node_id return call render_to_response string node.html dict string node node context_instance=call RequestContext request end function
def node(request, node_id): node = get_object_or_404(HierarchyNode, pk=node_id) return render_to_response("node.html", {"node": node}, context_instance=RequestContext(request))
Python
nomic_cornstack_python_v1
string You are given a dictionary of _names_ and the amount of _points_ they have. Return a dictionary with the same names, but instead of points, return what prize they get. `"Gold"`, `"Silver"`, or `"Bronze"` to the 1st, 2nd and 3rd place respectively. For all the other names, return `"Participation"` for the prize. ...
""" You are given a dictionary of _names_ and the amount of _points_ they have. Return a dictionary with the same names, but instead of points, return what prize they get. `"Gold"`, `"Silver"`, or `"Bronze"` to the 1st, 2nd and 3rd place respectively. For all the other names, return `"Participation"` for the prize....
Python
zaydzuhri_stack_edu_python
import random import string import time import os function generate l begin set code = string 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ set ge = string for i in range 0 l begin set num = random integer 0 length code set ge = ge + code at num end print ge comment python自带sample功能,从多个字符中生成指定数量的随机字符 ...
import random import string import time import os def generate(l): code = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ge = '' for i in range(0, l): num = random.randint(0, len(code)) ge += code[num] print(ge) # python自带sample功能,从多个字符中生成指定数量的随机字符 print(''.jo...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- import unittest from browser import Browser from pages.open_page import OpenPage from pages.page_with_multiple_images import PageWithMultipleImages class EnteringPageWithMultipleImages extends TestCase begin function setUp self begin set browser = call Browser set driver = start browser se...
# -*- coding: utf-8 -*- import unittest from browser import Browser from pages.open_page import OpenPage from pages.page_with_multiple_images import PageWithMultipleImages class EnteringPageWithMultipleImages(unittest.TestCase): def setUp(self): self.browser = Browser() self.driver = self.browse...
Python
zaydzuhri_stack_edu_python
function word new begin set upper = 0 set lower = 0 print string length of string is : length new for i in range 0 length new begin if is upper new at i begin set upper = upper + 1 end else begin set lower = lower + 1 end end print string upper case letter are: upper print string lower case letter are: lower end functi...
def word(new): upper=0 lower=0 print("length of string is :",len(new)) for i in range(0,len(new)): if new[i].isupper(): upper=upper+1 else: lower=lower+1 print("upper case letter are:",upper) print("lower case letter are:",lower) new="aniMAL" w...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Mon Sep 12 21:05:41 2016 @author: kevin function main begin set num = string with open string Files/1000digits.txt string r as f begin for line in f begin set num = num + line at slice : - 1 : end end set maxProd = 0 for i in range length num - 13 begin set prod = 1 fo...
# -*- coding: utf-8 -*- """ Created on Mon Sep 12 21:05:41 2016 @author: kevin """ def main(): num = "" with open("Files/1000digits.txt", "r") as f: for line in f: num += line[:-1] maxProd = 0 for i in range(len(num)-13): prod = 1 for j in range(13): ...
Python
zaydzuhri_stack_edu_python
function Restart self **kwargs begin comment signal any alive workers to stop set while length workers > 0 begin set worker = pop workers comment wait for worker to complete if call isAlive begin join worker end end clear restartEvent set status = string NotConfigured set statusMessage = string Service not configured s...
def Restart(self, **kwargs): # signal any alive workers to stop self.restartEvent.set() while len(self.workers) > 0: worker = self.workers.pop() # wait for worker to complete if worker.isAlive(): worker.join() self.restartEvent.clear...
Python
nomic_cornstack_python_v1
set a = 3 set a = a + 10 print a set b = 100 set b = b - 7 print b set c = 44 set c = c * 2 print c set d = 125 set d = d / 5 print integer d set e = 8 set e = e ^ 3 print e set f1 = 123 set f2 = 345 if f1 > f2 begin print true end else begin print false end set g1 = 350 set g2 = 200 if g2 > g1 begin print true end els...
a = 3 a += 10 print(a) b = 100 b -= 7 print(b) c = 44 c *= 2 print(c) d = 125 d /= 5 print(int(d)) e = 8 e **= 3 print(e) f1 = 123 f2 = 345 if(f1 > f2): print(True) else: print(False) g1 = 350 g2 = 200 if(g2 > g1): print(True) else: print(False) h = 1357988018575474 m = h % 11 if(m == 0): print(T...
Python
zaydzuhri_stack_edu_python
while true begin print string Who are you? set name = call raw_input if name != string Hamza begin continue end print string Hello, Hamza. What is the password? (It is a Town.) set password = call raw_input if password == string Mungadi begin break end end print string Access granted.
while True: print('Who are you?') name = raw_input() if name != 'Hamza': continue print('Hello, Hamza. What is the password? (It is a Town.)') password = raw_input() if password == 'Mungadi': break print('Access granted.')
Python
zaydzuhri_stack_edu_python
import xml.etree.ElementTree as ET import json
import xml.etree.ElementTree as ET import json
Python
zaydzuhri_stack_edu_python
with open string input.txt string r as f begin set lines = split read f string end function _partition line left=0 right=127 d_l=string F d_r=string B begin set tuple l r = tuple left right for direction in line begin set m = l + r - l // 2 if direction == d_l begin set r = m end else if direction == d_r begin set l = ...
with open('input.txt', 'r') as f: lines = f.read().split('\n') def _partition(line, left=0, right=127, d_l='F', d_r='B'): l, r = left, right for direction in line: m = l + (r - l) // 2 if direction == d_l: r = m elif direction == d_r: l = m + 1 return l ...
Python
zaydzuhri_stack_edu_python
import pdb from itertools import combinations from functools import reduce import operator function find_subset input_list size begin return list call combinations input_list size end function function prod iterable begin return reduce mul iterable 1 end function function find_the_three_numbers_sum2020 input_content be...
import pdb from itertools import combinations from functools import reduce import operator def find_subset(input_list, size): return list(combinations(input_list, size)) def prod(iterable): return reduce(operator.mul, iterable, 1) def find_the_three_numbers_sum2020(input_content): size = 3 input_c...
Python
zaydzuhri_stack_edu_python
from docx import Document from docx.shared import Inches set document = call Document call add_heading string Document Title 0 set p = call add_paragraph string A plain paragraph having some set bold = true call add_run string and some set italic = true call add_heading string Heading, level 1 level=1 call add_paragrap...
from docx import Document from docx.shared import Inches document = Document() document.add_heading('Document Title', 0) p = document.add_paragraph('A plain paragraph having some ') p.add_run('bold').bold = True p.add_run(' and some ') p.add_run('italic.').italic = True document.add_heading('Heading, le...
Python
zaydzuhri_stack_edu_python
set resultado = input print resultado set num1 = integer input set num2 = integer input print num1 + num2
resultado=input() print (resultado) num1=int(input()) num2=int(input()) print(num1+num2)
Python
zaydzuhri_stack_edu_python
function post self begin set filename = string time set filepath = join path join path config at string UPLOAD_FOLDER filename with open filepath string bw as uploadfile begin set chunk_size = 1024 while true begin set chunk = read stream chunk_size if length chunk == 0 begin break end write uploadfile chunk end end in...
def post(self): filename = str(time.time()) filepath = os.path.join( os.path.join(current_app.config['UPLOAD_FOLDER'], filename)) with open(filepath, 'bw') as uploadfile: chunk_size = 1024 while True: chunk = request.stream.read(chunk_size) ...
Python
nomic_cornstack_python_v1
for line in f begin set x = split line append l x end close f comment print(l) sort l reverse=true for i in l begin print i at 0 end
for line in f: x = line.split() l.append(x) f.close() #print(l) l.sort(reverse=True) for i in l: print(i[0])
Python
zaydzuhri_stack_edu_python
function __init__ s i j begin comment Posição do centro set tuple cx cy = call convert i j comment Cor (pode ser passada para o construtor no futuro) set cor = tuple 200 200 200 comment Vértices do hexágono set pontos = tuple tuple cx cy - L tuple cx + l cy - L / 2 tuple cx + l cy + L / 2 tuple cx cy + L tuple cx - l c...
def __init__(s,i,j): # Posição do centro s.cx, s.cy = convert(i,j) # Cor (pode ser passada para o construtor no futuro) s.cor = (200,200,200) # Vértices do hexágono s.pontos = ( (s.cx, s.cy-L), (s.cx+l, s.cy-L/2), (s.cx+l, s.cy+L/2),...
Python
nomic_cornstack_python_v1
function __sub__ self other begin return call frozenset end function
def __sub__(self, other): return frozenset()
Python
nomic_cornstack_python_v1
function client_secret_certificate_thumbprint self begin return get pulumi self string client_secret_certificate_thumbprint end function
def client_secret_certificate_thumbprint(self) -> Optional[str]: return pulumi.get(self, "client_secret_certificate_thumbprint")
Python
nomic_cornstack_python_v1
function load_state_dict self state begin pass end function
def load_state_dict(self, state): pass
Python
nomic_cornstack_python_v1
function VCTP_add_3DPlotDatatypeTD_for_DTHP RSRC fo po fpClassEx VCTP begin if fpClassEx in tuple string xControl:3D_Bar_Plot_Merge_VI.vi begin set dcoUDCRefClass = string 3D Bar end else if fpClassEx in tuple string xControl:3D_Comet_Plot_Merge_VI.vi begin set dcoUDCRefClass = string 3D Comet end else if fpClassEx in ...
def VCTP_add_3DPlotDatatypeTD_for_DTHP(RSRC, fo, po, fpClassEx, VCTP): if fpClassEx in ("xControl:3D_Bar_Plot_Merge_VI.vi",): dcoUDCRefClass = "3D Bar" elif fpClassEx in ("xControl:3D_Comet_Plot_Merge_VI.vi",): dcoUDCRefClass = "3D Comet" elif fpClassEx in ("xControl:3D_Contour_Plot_Merge_...
Python
nomic_cornstack_python_v1
function test_detail_view_with_a_future_question self begin set future_question = call create_question question_text=string Future question. days=5 set response = get client reverse string polls:detail args=tuple id assert equal status_code 404 end function
def test_detail_view_with_a_future_question(self): future_question = create_question(question_text ='Future question.', days = 5) response = self.client.get(reverse('polls:detail', args=(future_question.id,))) self.assertEqual(response.status_code, 404)
Python
nomic_cornstack_python_v1
function evaluationFunction self currentGameState action begin comment Useful information you can extract from a GameState (pacman.py) set successorGameState = call generatePacmanSuccessor action set newPos = call getPacmanPosition set newFood = call asList set newGhostStates = call getGhostStates set newScaredTimes = ...
def evaluationFunction(self, currentGameState, action): # Useful information you can extract from a GameState (pacman.py) successorGameState = currentGameState.generatePacmanSuccessor(action) newPos = successorGameState.getPacmanPosition() newFood = successorGameState.getFood().asList() ...
Python
nomic_cornstack_python_v1
function test_125019_identity_temp_with_user_photo self begin info string .... Start test_125019_identity_temp_with_user_photo .... try begin with step allure string teststep1: identity user. begin with step allure string teststep: user feature. begin set headers = dict string authorization token call update_header hea...
def test_125019_identity_temp_with_user_photo(self): self.logger.info(".... Start test_125019_identity_temp_with_user_photo ....") try: with allure.step("teststep1: identity user."): with allure.step("teststep: user feature."): headers = {"authorization": ...
Python
nomic_cornstack_python_v1
comment Shift Cipher Decrypt Program - CSCI 4905 - Kevin Bednar comment Begin by importing important details from constants from constants import cShiftText , lShift , numShift , primaryLetter comment Letters to attempt shift by, in order of highest chance to lowest chance set attemptShift = primaryLetter comment Initi...
#Shift Cipher Decrypt Program - CSCI 4905 - Kevin Bednar #Begin by importing important details from constants from constants import cShiftText,lShift,numShift,primaryLetter #Letters to attempt shift by, in order of highest chance to lowest chance attemptShift = primaryLetter key = 0 #Initialize key (attempt) plaintex...
Python
zaydzuhri_stack_edu_python
function find_best_it n_rows n_orders rhythm it_range begin comment milliseconds in total for all orders set max_t = rhythm * 1000.0 - 450.0 set total_exec_times = zeros like it_range comment print("####") for tuple i it in enumerate it_range begin set n_accs = call n_acc max_t n_rows n_orders it set time = call exec_t...
def find_best_it(n_rows, n_orders, rhythm, it_range): max_t = rhythm * 1000. - 450. #milliseconds in total for all orders total_exec_times = np.zeros_like(it_range) # print("####") for i, it in enumerate(it_range): n_accs = n_acc(max_t, n_rows, n_orders, it) time = exec_tim...
Python
nomic_cornstack_python_v1
function test_unarchive_run self begin pass end function
def test_unarchive_run(self): pass
Python
nomic_cornstack_python_v1
import pygame import heapq from PIL import Image from keras.models import load_model import numpy as np from pandas import datetime set model = call load_model string mnist.h5 function predict_digit img begin set img = call resize tuple 28 28 set img = call convert string L set img = array img set img = reshape img 1 2...
import pygame import heapq from PIL import Image from keras.models import load_model import numpy as np from pandas import datetime model = load_model('mnist.h5') def predict_digit(img): img = img.resize((28, 28)) img = img.convert('L') img = np.array(img) img = img.reshape(1, 28, 28, 1) img = i...
Python
zaydzuhri_stack_edu_python
if Celcius > 100 begin print TemperaturaF string grados Fahrenheit son Celcius string grados celcius, el agua si hierve a esta temperatura end else begin print TemperaturaF string grados Fahrenheit son Celcius string grados celcius, el agua no hierve a esta temperatura end
if Celcius>100: print(TemperaturaF ,"grados Fahrenheit son", Celcius, " grados celcius, el agua si hierve a esta temperatura") else: print(TemperaturaF ,"grados Fahrenheit son", Celcius, " grados celcius, el agua no hierve a esta temperatura")
Python
zaydzuhri_stack_edu_python
function makeAssignment subject title type date description begin comment ["Subject", "Title", "Type", "Date", "Description"] set dic = dict set dic at string Subject = subject set dic at string Title = title set dic at string Type = type set dic at string Date = date set dic at string Description = description return...
def makeAssignment(subject, title, type, date, description): # ["Subject", "Title", "Type", "Date", "Description"] dic = {} dic["Subject"] = subject dic["Title"] = title dic["Type"] = type dic["Date"] = date dic["Description"] = description return dic
Python
zaydzuhri_stack_edu_python
function get_position_pid self begin set reception_packet = call _send_receive_packet list get_pos_pid 4 * 3 set param_p = call _bytes_to_int32 reception_packet at slice 1 : 4 : set param_i = call _bytes_to_int32 reception_packet at slice 5 : 9 : set param_d = call _bytes_to_int32 reception_packet at slice 9 : 13 : ret...
def get_position_pid(self): reception_packet = super()._send_receive_packet([IDDebug.get_pos_pid], 4*3) param_p = super()._bytes_to_int32(reception_packet[1:4]) param_i = super()._bytes_to_int32(reception_packet[5:9]) param_d = supe...
Python
nomic_cornstack_python_v1
function check_item item tab search_item begin set item_name = item at string name set item_typeline = item at string typeLine set league = item at string league set note = get item string note set x_coord = string item at string x set y_coord = string item at string y if search_item at string league != league begin re...
def check_item(item, tab, search_item): item_name = item['name'] item_typeline = item['typeLine'] league = item['league'] note = item.get('note') x_coord = str(item['x']) y_coord = str(item['y']) if search_item['league'] != league: return False if search_item['name'] in item_n...
Python
nomic_cornstack_python_v1
function wait_for_pods_to_be_deleted client namespace pod_selector timeout=time delta minutes=5 polling_interval=time delta seconds=30 begin set end_time = now + timeout while true begin set pods = call list_pods client namespace pod_selector info string %s pods matched %s pods length items pod_selector if not items be...
def wait_for_pods_to_be_deleted(client, namespace, pod_selector, timeout=datetime.timedelta(minutes=5), polling_interval=datetime.timedelta( seconds=30)): e...
Python
nomic_cornstack_python_v1
function PrependTransform self t begin return call itkMultiTransformD33_PrependTransform self t end function
def PrependTransform(self, t: 'itkTransformD33') -> "void": return _itkMultiTransformPython.itkMultiTransformD33_PrependTransform(self, t)
Python
nomic_cornstack_python_v1
function init_client_ui_data self begin set sheetname : str = string translation if ui_wb begin tuple call commit_from_sheet ws=call sheet_by_name sheetname model=DATASET_WB_SHEET_MODEL_MAP at sheetname end end function comment Sheet comment db.Model
def init_client_ui_data(self): sheetname: str = 'translation' if self.ui_wb: commit_from_sheet( ws=self.ui_wb.sheet_by_name(sheetname), # Sheet model=DATASET_WB_SHEET_MODEL_MAP[sheetname]), # db.Model
Python
nomic_cornstack_python_v1
comment Verifica la data comment Scrivi un programma che definisca un oggetto per la rappresentazione di una data, l'oggetto sarà composto da giorno, mese e anno (input a piacere). comment Adesso, scrivi una funzione che prenda in input la data e verifichi se è valida o meno, in questo modo: comment Input: comment day:...
# # Verifica la data # Scrivi un programma che definisca un oggetto per la rappresentazione di una data, l'oggetto sarà composto da giorno, mese e anno (input a piacere). # Adesso, scrivi una funzione che prenda in input la data e verifichi se è valida o meno, in questo modo: # Input: # day: 18 # month:...
Python
zaydzuhri_stack_edu_python
comment A website requires the users to input username and password to register. Write a program to check the validity of password input by users. comment Following are the criteria for checking the password: comment 1. At least 1 letter between [a-z] comment 2. At least 1 number between [0-9] comment 3. At least 1 let...
#A website requires the users to input username and password to register. Write a program to check the validity of password input by users. #Following are the criteria for checking the password: #1. At least 1 letter between [a-z] #2. At least 1 number between [0-9] #3. At least 1 letter between [A-Z] #4. At least 1 ch...
Python
zaydzuhri_stack_edu_python
comment Part One #### print sum generator expression 1 for d in split read open string i string if count d string : - count d string ci == 7 comment Part Two ##### print format string There are {} valid passports length list comprehension 1 for d in split read open string input.txt string if all list comprehension find...
##### Part One #### print(sum(1 for d in open("i").read().split("\n\n") if d.count(":")-d.count("ci")==7)) ##### Part Two ##### print("There are {} valid passports".format(len([1 for d in open("input.txt").read().split("\n\n") if all([__import__("re").findall(p, d) for p in [r"\bpid:\d{9}\b", r"\beyr:20(2\d|30)\b", ...
Python
zaydzuhri_stack_edu_python
import os import urllib from google.cloud import vision from google.cloud.vision import types from firebase import Firebase import requests import json comment Google Vision API creds set environ at string GOOGLE_APPLICATION_CREDENTIALS = string creds.json comment Firebase configuration set config = dict string apiKey ...
import os import urllib from google.cloud import vision from google.cloud.vision import types from firebase import Firebase import requests import json # Google Vision API creds os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r'creds.json' # Firebase configuration config = { "apiKey": "AIzaSyDQ1lcaiMTXR3Dmey...
Python
zaydzuhri_stack_edu_python
comment https://leetcode.com/problems/perfect-squares/ comment Time: O(n) comment Space: O(n) class Solution begin function numSquares self n begin if n <= 3 begin return n end comment this has all the square numbers that are smaller than n (so only these numbers can add up to make n) set lst = list set i = 1 while i ...
# https://leetcode.com/problems/perfect-squares/ # Time: O(n) # Space: O(n) class Solution: def numSquares(self, n: int) -> int: if n <= 3: return n lst = [] # this has all the square numbers that are smaller than n (so only these numbers can add up to make n) i = 1 whi...
Python
zaydzuhri_stack_edu_python
for i in range n begin for j in range T at i * b begin append M V at i end end set R = list 0 + T at slice : : for i in range n begin set R at i + 1 = R at i + 1 + R at i end for i in range n begin set le = R at i * b set ri = R at i + 1 * b set j = 0 if i - 1 >= 0 and V at i - 1 > V at i begin while le >= 0 begin s...
for i in range(n) : for j in range(T[i] * b) : M.append(V[i]) R = [0] + T[:] for i in range(n) : R[i+1] += R[i] for i in range(n) : le = R[i] * b ri = R[i+1] * b j = 0 if i-1 >= 0 and V[i-1] > V[i] : while le >= 0 : M[le] = min(M[le], V[i] ...
Python
zaydzuhri_stack_edu_python
from model import Model class Post extends Model begin function __init__ self title=none body=none begin if not title or not body begin raise call ValueError string Post must have both title and body. end set title = title set body = body end function function toData self begin return dict string title title ; string b...
from model import Model class Post(Model): def __init__(self, title=None, body=None): if not title or not body: raise ValueError("Post must have both title and body.") self.title = title self.body = body def toData(self): return { "title": self.title, "body": self....
Python
zaydzuhri_stack_edu_python
try begin try begin 1 // 0 end except any begin print string a assert 1 == 0 print string b end finally begin print string finally end end except AssertionError begin print string except end comment out: a comment out: finally comment out: except
try: try: 1 // 0 except: print('a') assert 1 == 0 print('b') finally: print('finally') except AssertionError: print('except') #out: a #out: finally #out: except
Python
zaydzuhri_stack_edu_python
comment Import Libraries import numpy as np import pandas as pd import sklearn import scipy comment Import Data set new_data = read csv string new_data.csv print string Preprocessing is Started!! Please Wait.... comment Data Preprocessing ##### comment Missing Values ##### set libor_rate = fill missing libor_rate mean ...
## Import Libraries import numpy as np import pandas as pd import sklearn import scipy ## Import Data new_data=pd.read_csv("new_data.csv") print("Preprocessing is Started!! Please Wait.... \n") ##### Data Preprocessing ##### ##### Missing Values ##### new_data.libor_rate=new_data.libor_rate.fillna(new_data.lib...
Python
zaydzuhri_stack_edu_python
string https://www.hackerrank.com/challenges/s10-binomial-distribution-1/tutorial string Variavel Randomica https://en.wikipedia.org/wiki/Four-sided_die https://en.wikipedia.org/wiki/Random_variable https://pt.wikipedia.org/wiki/Vari%C3%A1vel_aleat%C3%B3ria string probability mass function https://pt.wikipedia.org/wiki...
''' https://www.hackerrank.com/challenges/s10-binomial-distribution-1/tutorial ''' ''' Variavel Randomica https://en.wikipedia.org/wiki/Four-sided_die https://en.wikipedia.org/wiki/Random_variable https://pt.wikipedia.org/wiki/Vari%C3%A1vel_aleat%C3%B3ria ''' ''' probability mass function https://pt.wikipedia.org/wi...
Python
zaydzuhri_stack_edu_python
with open string text1.txt string r encoding=string utf8 as file begin set reader1 = read file end with open string text2.txt string r encoding=string utf8 as file begin set reader2 = read file end set s1 = set split reader1 set s2 = set split reader2 set s3 = intersection s1 s2 set s4 = s1 - s3 set s5 = s2 - s3 print ...
with open('text1.txt','r',encoding = "utf8") as file: reader1 = file.read() with open('text2.txt','r',encoding = "utf8") as file: reader2 = file.read() s1 = set(reader1.split()) s2 = set(reader2.split()) s3 = s1.intersection(s2) s4 = s1 - s3 s5 = s2 - s3 print(s3) print(s1.union(s2)) print(s4) print(s5) pri...
Python
zaydzuhri_stack_edu_python
function _compute_acq_withGradients self X begin set X = call atleast_2d X set acqX = zeros tuple shape at 0 1 set dacq_dX = zeros shape set Z_samples = call normal size=5 for h in range n_gp_hyps_samples begin call set_hyperparameters h set inv_sqrt_varX = call posterior_variance X ^ - 0.5 set inv_varX_noiseless = cal...
def _compute_acq_withGradients(self, X): X = np.atleast_2d(X) acqX = np.zeros((X.shape[0], 1)) dacq_dX = np.zeros(X.shape) Z_samples = np.random.normal(size=5) for h in range(self.n_gp_hyps_samples): self.model.set_hyperparameters(h) inv_sqrt_varX ...
Python
nomic_cornstack_python_v1
if a == b begin for i in range 1 a + 1 begin print i - i end=string end end else if a > b begin for i in range 1 a + 1 begin print i end=string end set s = a * a + 1 // 2 set size = b set ans = list for i in range s 0 - 1 begin if i > s begin continue end if size * size - 1 // 2 <= s - i begin append ans - i set s = s...
if a == b: for i in range(1, a+1): print(i, -i, end=' ') elif a > b: for i in range(1, a+1): print(i, end=' ') s = a*(a+1) // 2 size = b ans = [] for i in range(s, 0, -1): if i > s: continue if size*(size-1) // 2 <= (s-i): ans.append(-i) ...
Python
zaydzuhri_stack_edu_python
comment Program to find the sum of all elements in an array function sum_arr arr begin comment faster sum using numpy return sum arr end function
# Program to find the sum of all elements in an array def sum_arr(arr): # faster sum using numpy return np.sum(arr)
Python
flytech_python_25k
for i in range T begin set times = dict string B 0 ; string G 0 ; string R 0 set n = integer input for j in range n begin set a = split input string set times at a at 0 = times at a at 0 + dic at a at 0 + a at 1 end if times at string B == times at string G and times at string B == times at string R begin print string ...
for i in range(T): times = {'B':0 , 'G':0 , 'R':0} n = int(input()) for j in range(n): a = input().split(' ') times[a[0]]+=dic[a[0]+a[1]] if (times['B'] == times['G'] and times['B'] == times['R'] ): print('trempate') elif((times['B'] == times['G'] and times['B'] > times['R'] )or (times['B'] == times['R'...
Python
zaydzuhri_stack_edu_python
import numpy as np import math set SHOULD_PRINT = false function getRotationMatrix alpha beta gama begin set cosAlpha = cos alpha set sinAlpha = sin alpha set cosBeta = cos beta set sinBeta = sin beta set cosGama = cos gama set sinGama = sin gama set r1 = cosAlpha * cosBeta set r2 = cosAlpha * sinBeta * sinGama - sinAl...
import numpy as np import math SHOULD_PRINT = False def getRotationMatrix(alpha, beta, gama): cosAlpha = math.cos(alpha) sinAlpha = math.sin(alpha) cosBeta = math.cos(beta) sinBeta = math.sin(beta) cosGama = math.cos(gama) sinGama = math.sin(gama) r1 = cosAlpha * cosBeta r2 = (cosAlpha * sinBeta * sinGama) ...
Python
zaydzuhri_stack_edu_python
from itertools import izip set __author__ = string seven function mkdir path begin import os set path = strip path set path = right strip path string \ set isExists = exists path path end function
from itertools import izip __author__ = 'seven' def mkdir(path): import os path = path.strip() path = path.rstrip("\\") isExists = os.path.exists(path)
Python
zaydzuhri_stack_edu_python
import getopt import os import sys import cli_helpers import methods set HELP_STRING = string Required flags: At least one of the following must be used: -c 'company title' -p 'position title' Optional flags: -v or --verbose Prints the cover letter to the terminal. By default this is enabled, and is disabled if -n or -...
import getopt import os import sys import cli_helpers import methods HELP_STRING = """ Required flags: At least one of the following must be used: -c 'company title' -p 'position title' Optional flags: -v or --verbose Prints the cover letter to the terminal. By default this is enabled, and is disabled if -n or...
Python
zaydzuhri_stack_edu_python
for i in liste begin print integer i + 1 end for i in range 0 length liste begin set liste at i = liste at i + 1 end print liste import random set s = random integer 2 5 print s set listee = list for i in range 10 begin append listee random integer 0 10 end print listee set test_sayısı = 100000 function createArray s ...
for i in liste: print(int(i)+1) for i in range(0,len(liste)): liste[i]=liste[i]+1 print(liste) import random s=random.randint(2,5) print(s) listee=[] for i in range(10): listee.append(random.randint(0,10)) print(listee) test_sayısı=100000 def createArray(s): myList=[] for i in range(s): ...
Python
zaydzuhri_stack_edu_python
if n == 2 begin print - 1 end else if n == 3 begin list comprehension print x for x in s3 end else begin set tuple d m = divide mod n 4 set d = d - 1 set m = m + 4 for i in range d begin list comprehension print string . * 4 * i + x + string . * 4 * d - i - 1 + m for x in s at 0 end list comprehension print string . * ...
if n == 2: print(-1) elif n == 3: [print(x) for x in s3] else: d, m = divmod(n, 4) d -= 1 m += 4 for i in range(d): [print("." * 4 * i + x + "." * (4 * (d - i - 1) + m)) for x in s[0]] [print("." * 4 * d + x) for x in s[m - 4]]
Python
jtatman_500k
from math import gcd set tuple N X = map int split input set A = list map lambda x -> absolute integer x - X split input set g = A at 0 for i in range 1 N begin set g = call gcd g A at i end print g
from math import gcd N, X = map(int, input().split()) A = list(map(lambda x: abs(int(x) - X), input().split())) g = A[0] for i in range(1, N): g = gcd(g, A[i]) print(g)
Python
zaydzuhri_stack_edu_python
function parse cls option_description begin set tuple short lng argcount value env = tuple none none 0 false none set tuple options _ description = call partition string set options = replace replace options string , string string = string for sec in split options begin if starts with sec string -- begin set lng = sec ...
def parse(cls, option_description): short, lng, argcount, value, env = None, None, 0, False, None options, _, description = option_description.strip().partition(' ') options = options.replace(',', ' ').replace('=', ' ') for sec in options.split(): if sec.startswith('--'): ...
Python
nomic_cornstack_python_v1
comment Andrew Parker comment 9/27/17 comment fives.py - Prints out multiples of 5 up a certain number set num = integer input string Enter a Number: for i in range 5 num 5 begin print i end
#Andrew Parker #9/27/17 #fives.py - Prints out multiples of 5 up a certain number num = int(input('Enter a Number: ')) for i in range(5,num,5): print(i)
Python
zaydzuhri_stack_edu_python
function fetch_wikipedia_pages_info page_ids database begin set pages_info = dict set current_page_ids_index = 0 while current_page_ids_index < length page_ids begin comment Query at most 50 pages per request (given WikiMedia API limits) set end_page_ids_index = min current_page_ids_index + 50 length page_ids set quer...
def fetch_wikipedia_pages_info(page_ids, database): pages_info = {} current_page_ids_index = 0 while current_page_ids_index < len(page_ids): # Query at most 50 pages per request (given WikiMedia API limits) end_page_ids_index = min(current_page_ids_index + 50, len(page_ids)) query_params = { ...
Python
nomic_cornstack_python_v1