code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function is_empty self begin return length _data == 0 end function
def is_empty(self): return len(self._data) == 0
Python
nomic_cornstack_python_v1
function getTenantByUid self uid begin debug format string Call to getTenantByUid - uid: {} uid try begin set response = call sendHttpRequest CIC_TENANT_ENDPOINT + string ?uuid= + uid end except HTTPError as e begin debug call format_exc if code == 404 begin set body = read e debug format string Response code: {}, resp...
def getTenantByUid(self,uid): logger.debug("Call to getTenantByUid - uid: {}".format(uid)) try: response = self.httpHandler.sendHttpRequest(CIC_TENANT_ENDPOINT+"?uuid="+uid) except urllib2.HTTPError as e: logger.debug(traceback.f...
Python
nomic_cornstack_python_v1
function handlefailure self dummy=none begin log string OPENSIGNALNETWORKMODIFY-handlefailure string A failure occured comment KB/s ms set tempdict = dict string uploadSpeed 574.72 ; string averageRssiDb 22 ; string downloadSpeed 1213.44 ; string pingTime 98 return tempdict end function
def handlefailure(self, dummy=None): tracelayer.log("OPENSIGNALNETWORKMODIFY-handlefailure","A failure occured") tempdict = {'uploadSpeed':574.72,'averageRssiDb':22,'downloadSpeed':1213.44,'pingTime':98} #KB/s ms return tempdict
Python
nomic_cornstack_python_v1
import psycopg2 import sys import pprint import random import string comment conn_string = "host='localhost' dbname='hack' user='hack' password='hack'" set conn_string = string host='localhost' dbname='hack'
import psycopg2 import sys import pprint import random import string #conn_string = "host='localhost' dbname='hack' user='hack' password='hack'" conn_string = "host='localhost' dbname='hack'"
Python
zaydzuhri_stack_edu_python
function some seq func begin if not is instance seq tuple list tuple set begin raise call TypeError string param 'seq' must be a list, tuple, or set end if not callable func begin raise call TypeError string param 'func' must be a callable end for item in seq begin if call func item begin return true end end return fal...
def some(seq, func): if not isinstance(seq, (list, tuple, set)): raise TypeError("param 'seq' must be a list, tuple, or set") if not callable(func): raise TypeError("param 'func' must be a callable") for item in seq: if func(item): return True return False
Python
nomic_cornstack_python_v1
function flog lista begin set lista2 = list for i in lista begin append lista2 i % 2 end return lista2 end function function fun f l begin return f dist l end function set lista = list comprehension i for i in range 100
def flog(lista): lista2 = [] for i in lista: lista2.append(i%2) return lista2 def fun(f, l): return f(l) lista = [i for i in range(100)]
Python
zaydzuhri_stack_edu_python
comment 代码实现太多的数据切割技术 import os comment import pandas as pd import time import random comment 删除缺失值、去重############## string data = pd.read_csv("weibo-processed-B.csv",encoding="utf8") print(data.isnull().sum()) data = data.dropna() data.reset_index(drop=True,inplace=True) print(data.isnull().sum()) result = data.drop_d...
# 代码实现太多的数据切割技术 import os # import pandas as pd import time import random ##########删除缺失值、去重############## ''' data = pd.read_csv("weibo-processed-B.csv",encoding="utf8") print(data.isnull().sum()) data = data.dropna() data.reset_index(drop=True,inplace=True) print(data.isnull().sum()) result = data.drop_duplicates(['...
Python
zaydzuhri_stack_edu_python
import random import json import os comment this is an example of a function that will return a random item from a file comment https://stackoverflow.com/questions/3540288/how-do-i-read-a-random-line-from-one-file function random_line file_name file_path=none begin set current_dirname = directory name path __file__ if ...
import random import json import os # this is an example of a function that will return a random item from a file # https://stackoverflow.com/questions/3540288/how-do-i-read-a-random-line-from-one-file def random_line(file_name, file_path=None): current_dirname = os.path.dirname(__file__) if not file_path: ...
Python
zaydzuhri_stack_edu_python
async function _switch_dc self new_dc begin info string Reconnecting to new data center %s new_dc await call _replace_session_state dc_id=new_dc await call _disconnect self return await call connect end function
async def _switch_dc(self: 'TelegramClient', new_dc): self._log[__name__].info('Reconnecting to new data center %s', new_dc) await self._replace_session_state(dc_id=new_dc) await _disconnect(self) return await self.connect()
Python
nomic_cornstack_python_v1
import os import wget import shutil import vk_api import threading import configparser from zipfile import ZipFile from datetime import datetime from nested_lookup import nested_lookup from vk_api.longpoll import VkLongPoll , VkEventType class ConfigHandler begin function __init__ self path=string config.ini begin set ...
import os import wget import shutil import vk_api import threading import configparser from zipfile import ZipFile from datetime import datetime from nested_lookup import nested_lookup from vk_api.longpoll import VkLongPoll, VkEventType class ConfigHandler: def __init__(self, path='config.ini'): self.con...
Python
zaydzuhri_stack_edu_python
comment Made By Anirudh Rath | dh00mk3tu comment Visit anirudhrath.tech to know more comment Find if the number is Multiple of 5 set num = integer input string Enter a number: if num % 5 == 0 or num % 5 == 5 begin print num string Multiple of 5 end else begin print num string Not a Multiple of 5 end
# Made By Anirudh Rath | dh00mk3tu # Visit anirudhrath.tech to know more # Find if the number is Multiple of 5 num = int(input("Enter a number: ")) if ((num % 5) == 0 or (num % 5) == 5): print(num, "Multiple of 5") else: print(num, "Not a Multiple of 5")
Python
zaydzuhri_stack_edu_python
function __init__ self logger dbConnection dbSchema sourceEpsg descEpsg begin set __logger = logger set __strConnection = dbConnection set __dbSchema = dbSchema set __sourceEpsg = sourceEpsg set __descEpsg = descEpsg set conn = none set cur = none set __codeList = dict try begin set conn = call connect __strConnection...
def __init__(self, logger, dbConnection, dbSchema, sourceEpsg, descEpsg): self.__logger = logger self.__strConnection = dbConnection self.__dbSchema = dbSchema self.__sourceEpsg = sourceEpsg self.__descEpsg = descEpsg self.conn = None self.cur = None ...
Python
nomic_cornstack_python_v1
comment https://www.hackerrank.com/challenges/balanced-brackets/ set n = integer input function get_top begin if stack begin return stack at - 1 end return none end function for _ in range n begin set s = input set stack = list for b in s begin if b == string ( or b == string { or b == string [ begin append stack b en...
# https://www.hackerrank.com/challenges/balanced-brackets/ n = int(input()) def get_top(): if stack: return stack[-1] return None for _ in range(n): s = input() stack = [] for b in s: if b == '(' or b == '{' or b == '[': stack.append(b) else: top = get_top(...
Python
zaydzuhri_stack_edu_python
function test_multithread_false__S3_fileHandle__small_file self begin set file_handle = dict string id string 123 ; string concreteType S3_FILE_HANDLE ; string contentMd5 string someMD5 ; string contentSize SYNAPSE_DEFAULT_DOWNLOAD_PART_SIZE - 1 call _multithread_not_applicable file_handle end function
def test_multithread_false__S3_fileHandle__small_file(self): file_handle = { "id": "123", "concreteType": concrete_types.S3_FILE_HANDLE, "contentMd5": "someMD5", "contentSize": multithread_download.SYNAPSE_DEFAULT_DOWNLOAD_PART_SIZE - 1, } self._mu...
Python
nomic_cornstack_python_v1
function model_params_descriptions self begin return dict string n_layers tuple string Number of layers. The total number of layers is 2*(n_layers) + 1 this number (UP + downscaling) 3 ; string initial_feature_size tuple string Number of features in the first layer. 16 ; string filter_size tuple string Size of convolut...
def model_params_descriptions(self): return {'n_layers' : ('Number of layers. The total number of layers is 2*(n_layers) + 1 this number (UP + downscaling)',3), 'initial_feature_size' : ('Number of features in the first layer.',16), 'filter_size' : ('Size of convolutional filter'...
Python
nomic_cornstack_python_v1
import math set figure = string input set face = 0 if figure == string square begin set side_a = decimal input set face = side_a * side_a end else if figure == string rectangle begin set side_a = decimal input set side_b = decimal input set face = side_a * side_b end else if figure == string circle begin set radius = d...
import math figure = str(input()) face = 0 if figure == "square": side_a = float(input()) face = side_a * side_a elif figure == "rectangle": side_a = float(input()) side_b = float(input()) face = side_a * side_b elif figure == "circle": radius = float(input()) face = math.pi * (math.pow(radi...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np call set_option string display.max_rows 15 set amazon = read csv string C:/Users/HP/OneDrive/Desktop/AMZN.csv index_col=0 comment print(amazon.head(10)) comment Indexing and writing to file set amazon_subset = iloc at tuple slice : : slice 0 : 3 : comment amazon_subset.write_c...
import pandas as pd import numpy as np pd.set_option('display.max_rows',15) amazon = pd.read_csv('C:/Users/HP/OneDrive/Desktop/AMZN.csv',index_col=0) #print(amazon.head(10)) #Indexing and writing to file amazon_subset = amazon.iloc[:,0:3] #amazon_subset.write_csv('test_sub') amazon_subset = pd.DataFrame(amazon_subset) ...
Python
zaydzuhri_stack_edu_python
function render self begin return call QMessageBox icon title text standard_buttons end function
def render( self ): return QtGui.QMessageBox( self.icon, self.title, self.text, self.standard_buttons )
Python
nomic_cornstack_python_v1
from collections import Counter as co class Node begin function __init__ self data=0 begin set data = data set next = none end function end class class LinkedList begin function __init__ self begin set head = none set tail = none end function function insert_tail self value begin if tail == none begin set head = call N...
from collections import Counter as co class Node(): def __init__(self, data = 0): self.data = data self.next = None class LinkedList(): def __init__(self): self.head = None self.tail = None def insert_tail(self, value): if self.tail == None: self.head =...
Python
zaydzuhri_stack_edu_python
function _parse_patch lines begin set names = list set nametypes = list set counts = list set in_patch_chunk = false set in_git_header = false set binaryfile = false set currentfile = none set added = 0 set deleted = 0 for line in lines begin if starts with line _GIT_HEADER_START begin if currentfile is not none beg...
def _parse_patch(lines): names = [] nametypes = [] counts = [] in_patch_chunk = in_git_header = binaryfile = False currentfile = None added = deleted = 0 for line in lines: if line.startswith(_GIT_HEADER_START): if currentfile is not None: names.append(cur...
Python
nomic_cornstack_python_v1
import pymysql set city = input string City: set mydb = call connect string gpdw.inmz.net string megan string ******** string tmp set cursor = call cursor set count = 0 set count_dict = dict 0 string City id: ; 1 string Country id: ; 2 string City iso code: ; 3 string Country alpha2: ; 4 string Country alpha3: ; 5 stri...
import pymysql city = input("City: ") mydb = pymysql.connect('gpdw.inmz.net','megan','********','tmp') cursor = mydb.cursor() count = 0 count_dict = { 0: 'City id: ', 1: 'Country id: ', 2: 'City iso code: ', 3: 'Country alpha2: ', 4: 'Country alpha3: ', 5: 'Country name: ', 6: 'Country ...
Python
zaydzuhri_stack_edu_python
function video_codec self video_codec begin set _video_codec = video_codec end function
def video_codec(self, video_codec): self._video_codec = video_codec
Python
nomic_cornstack_python_v1
function getHash url begin comment return hashlib.sha256(url).hexdigest() comment NOTE: debugging return url end function
def getHash(url): #return hashlib.sha256(url).hexdigest() # NOTE: debugging return url
Python
nomic_cornstack_python_v1
string Workflow: search --> bookingSystem--> hotel Case: Search Select and Book Cancle Object: BookingSystem Hotel Room Single Double Example: Expedia = BookingSystem() #singleton Hilton = Hotel() Marriot = Hotel() Room_type_list = Expedia.search(date, size) Expedia.Book(room_type) Expedia.Canle(room_type) class Bookin...
""" Workflow: search --> bookingSystem--> hotel Case: Search Select and Book Cancle Object: BookingSystem Hotel Room Single Double Example: Expedia = BookingSystem() #singleton Hilton = Hotel() Marriot = Hotel() Room_type_list = Expedia.search(date, s...
Python
zaydzuhri_stack_edu_python
string Created on Mar 17, 2017 @author: Wonhee Cho email : danylight@gmail.com Web site: http://mediaq.usc.edu/mmsys17 Copyright 2017 Wonhee Cho Function: Generate Map import sys import json import numpy as np import csv from staticmap import StaticMap , CircleMarker from motionless import LatLonMarker , DecoratedMap f...
''' Created on Mar 17, 2017 @author: Wonhee Cho email : danylight@gmail.com Web site: http://mediaq.usc.edu/mmsys17 Copyright 2017 Wonhee Cho Function: Generate Map ''' import sys import json import numpy as np import csv from staticmap import StaticMap, CircleMarker from motionless import LatLonMarker, De...
Python
zaydzuhri_stack_edu_python
comment 【9.演算子】 set x = 10 set y = 2 comment 10+2=12 print x + y comment 10-2=8 print x - y comment 10×2=20 print x * y comment 10÷2=5 print x / y comment 10÷2のあまり(剰余)=0 print x % y comment ================================================================= comment 関係演算子 (正しいか正しくないかの結果が出る。) < > <= => set x = 10 set y = 2...
#【9.演算子】 x = 10 y = 2 print(x + y) # 10+2=12 print(x - y) # 10-2=8 print(x * y)# 10×2=20 print(x / y)# 10÷2=5 print(x % y)# 10÷2のあまり(剰余)=0 # ================================================================= # 関係演算子 (正しいか正しくないかの結果が出る。) < > <= => x = 10 y = 2 Z = 10 print(x > y) # True # 10は2より大きい(超える) print(x < y) # ...
Python
zaydzuhri_stack_edu_python
try begin set score = decimal score if 0 <= score <= 100 and score >= 90 begin print string A end else if 0 <= score <= 100 and score >= 80 begin print string B end else if 0 <= score <= 100 and score >= 70 begin print string C end else if 0 <= score <= 100 and score >= 60 begin print string D end else begin print stri...
try: score = float(score) if 0<=score<=100 and score >= 90: print('A') elif 0<=score<=100 and score >= 80: print('B') elif 0<=score<=100 and score >= 70: print('C') elif 0<=score<=100 and score >= 60: print('D') else: print('F') except: pr...
Python
zaydzuhri_stack_edu_python
function get_post_response_data self request token_obj begin set UserSerializer = call get_user_serializer_class set data = dict string expiry call format_expiry_datetime expiry ; string token token if UserSerializer is not none begin set data at string user = data end return data end function
def get_post_response_data(self, request, token_obj: "AuthToken"): UserSerializer = self.get_user_serializer_class() data = { "expiry": self.format_expiry_datetime(token_obj.expiry), "token": token_obj.token, } if UserSerializer is not None: data["user...
Python
nomic_cornstack_python_v1
comment Saves a type of html tag from entered url to desktop import requests from bs4 import BeautifulSoup from tkinter import * class HTML_Downloader extends Frame begin function __init__ self master=none begin set title_var = call IntVar set p_var = call IntVar set h1_var = call IntVar set url = call StringVar set va...
# Saves a type of html tag from entered url to desktop import requests from bs4 import BeautifulSoup from tkinter import * class HTML_Downloader(Frame): def __init__(self, master=None): title_var = IntVar() p_var = IntVar() h1_var = IntVar() url = StringVar() vars = [ title_var, p_var, h1_var, ur...
Python
zaydzuhri_stack_edu_python
comment probably slowest due to sort function - o((m+n) log(m+n)) time, o(m+n) space set nums3 = sorted nums1 + nums2 if length nums3 % 2 == 0 begin return nums3 at length nums3 // 2 + nums3 at length nums3 // 2 + 1 / 2 end else begin return nums3 at length nums3 // 2 end comment use two heaps (one min, one max) - o() ...
# probably slowest due to sort function - o((m+n) log(m+n)) time, o(m+n) space nums3 = sorted(nums1+nums2) if len(nums3) % 2 == 0: return (nums3[len(nums3)//2] + nums3[len(nums3)//2+1])/2 else: return nums3[len(nums3)//2] # use two heaps (one min, one max) - o() """ pseudocode - combine two lists as one list...
Python
zaydzuhri_stack_edu_python
function open_url self url begin comment use quote to deal with arabic/... url, safe ':/' is needed set url = quote url safe=string :/ set attempts = 0 set delay = decimal scrapy_interval + decimal call randrange 1 3 / 10 set longDelay = random integer 30 70 while attempts < 15 begin try begin comment timeout is necess...
def open_url(self, url): # use quote to deal with arabic/... url, safe ':/' is needed url = quote(url, safe = ':/') attempts = 0 delay = float(self.scrapy_interval) + float(random.randrange(1,3)/10) longDelay = random.randint(30,70) while attempts < 15: try: ...
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Tue May 26 09:31:20 2020 @author: hun import numpy as np import random comment e.g. hyposet = [['a',['b']],'c'] -> ['a','b','c']; flatset =[] function flatten_listINlist hyposet flatset begin for hype in hyposet begin if type hype is list beg...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue May 26 09:31:20 2020 @author: hun """ import numpy as np import random def flatten_listINlist(hyposet,flatset): #e.g. hyposet = [['a',['b']],'c'] -> ['a','b','c']; flatset =[] for hype in hyposet: if type(hype) is list: flatset ...
Python
zaydzuhri_stack_edu_python
set user_month = integer input string Введите целое число месяц (от 1 до 12): set months = dict 12 string зима ; 1 string зима ; 2 string зима ; 3 string весна ; 4 string весна ; 5 string весна ; 6 string лето ; 7 string лето ; 8 string лето ; 9 string осень ; 10 string осень ; 11 string осень print string { user_month...
user_month = int(input("Введите целое число месяц (от 1 до 12): ")) months = {12: "зима", 1: "зима", 2: "зима", 3: "весна", 4: "весна", 5: "весна", 6: "лето", 7: "лето", 8: "лето", 9: "осень", 10: "осень", 11: "осень"} print(f'{user_month} месяц - {months.get(user_month)}')
Python
zaydzuhri_stack_edu_python
comment -*- coding:Utf-8 -*- import time import numpy as np from exceptions import Full , Empty import code function timeit func loop begin set times = list set tt1 = call process_time for _ in range loop begin set t1 = performance counter call func append times performance counter - t1 end set tt2 = call process_time ...
# -*- coding:Utf-8 -*- import time import numpy as np from .exceptions import Full, Empty import code def timeit(func, loop): times = list() tt1 = time.process_time() for _ in range(loop): t1 = time.perf_counter() func() times.append(time.perf_counter() - t1) tt2 = time.proces...
Python
zaydzuhri_stack_edu_python
import threading , time , queue class ThreadPool begin function __init__ self maxsize begin set maxsize = maxsize set _q = queue maxsize for i in range maxsize begin put Thread end end function function get_thread self begin return get _q end function function add_thread self begin put Thread end function end class set...
import threading,time,queue class ThreadPool: def __init__(self,maxsize): self.maxsize=maxsize self._q=queue.Queue(maxsize) for i in range(maxsize): self._q.put(threading.Thread) def get_thread(self): return self._q.get() def add_thread(self): self._q.pu...
Python
zaydzuhri_stack_edu_python
function test_match_correct event dummy_algorithm dummy_state begin assert match event dummy_state end function
def test_match_correct(event, dummy_algorithm, dummy_state): assert dummy_algorithm.match(event, dummy_state)
Python
nomic_cornstack_python_v1
from datetime import datetime from common_types import InstrumentType , OptionKind , Instrument function validate_instrument instrument begin if not instrument_id or not tick_size begin raise exception string Invalid instrument definition: instrument id or tick_size is not defined. end if tick_size <= 0 begin raise exc...
from datetime import datetime from .common_types import InstrumentType, OptionKind, Instrument def validate_instrument(instrument: Instrument) -> None: if not instrument.instrument_id or not instrument.tick_size: raise Exception("Invalid instrument definition: instrument id or tick_size is not defined.") ...
Python
zaydzuhri_stack_edu_python
function _check_response self response_contents correct_jsons begin for tuple username content in items response_contents begin comment Used in debugger for comparing objects. comment self.maxDiff = None comment We should compare top_words for manually, comment because they are unsorted. set keys_to_compare = differenc...
def _check_response(self, response_contents, correct_jsons): for username, content in response_contents.items(): # Used in debugger for comparing objects. # self.maxDiff = None # We should compare top_words for manually, # because they are unsorted. ...
Python
nomic_cornstack_python_v1
function DisplaySliceVectors Centroids Vectors ax N=1 sections=1 begin comment Create boundaries in x for each slice. set SliceValues = linear space decimal min Centroids at tuple slice : : 0 decimal max Centroids at tuple slice : : 0 sections + 1 set idx1 = call asarray Centroids at tuple slice : : 0 >= Slice...
def DisplaySliceVectors(Centroids,Vectors,ax,N = 1,sections = 1): SliceValues = np.linspace(float(min(Centroids[:,0])),float(max(Centroids[:,0])),sections+1) # Create boundaries in x for each slice. idx1 = np.asarray((Centroids[:,0]>=SliceValues[N-1]))*np.asarray((Centroids[:,0]<=SliceValues[N])) idx...
Python
nomic_cornstack_python_v1
import paramiko import sys import os import time from password_generator import PasswordUtil comment sys.path.insert(0, '/Users/Sahoon/Project/python/password_generator') comment from PasswordUtil import PasswordUtil comment setting parameters like host IP, username, passwd and number of iterations to gather cmds set H...
import paramiko import sys import os import time from password_generator import PasswordUtil # sys.path.insert(0, '/Users/Sahoon/Project/python/password_generator') # from PasswordUtil import PasswordUtil #setting parameters like host IP, username, passwd and number of iterations to gather cmds HOST = "10.200.105.38"...
Python
zaydzuhri_stack_edu_python
function min_max_scale_date_hptc date_to_scale begin set one = call datetime 2021 4 1 - call datetime 2009 6 26 set current_scale = date_to_scale - call datetime 2009 6 26 return current_scale / one end function
def min_max_scale_date_hptc(date_to_scale): one = datetime.datetime(2021, 4, 1) - datetime.datetime(2009, 6, 26) current_scale = date_to_scale - datetime.datetime(2009, 6, 26) return current_scale / one
Python
nomic_cornstack_python_v1
comment Google2Piwik - exporting Google Analytics to Piwik comment @link http://clearcode.cc/ comment @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later import sql set TYPE_ACTION_URL = 1 set TYPE_ACTION_NAME = 4 class Action extends object begin function __init__ self path title internal_id begin set pa...
# # Google2Piwik - exporting Google Analytics to Piwik # # @link http://clearcode.cc/ # @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later # import sql TYPE_ACTION_URL = 1 TYPE_ACTION_NAME = 4 class Action(object): def __init__(self, path, title, internal_id): self.path = path ...
Python
zaydzuhri_stack_edu_python
import pygame import random set FUNDO = tuple 0 0 0 set tuple W H = tuple 640 480 set TAMANHO = tuple 640 480 set tuple w h = tuple 16 12 set BLOCO = W / w set BL = W / w set v = 1 / 3 class GameMessage extends Exception begin pass end class class GameOver extends GameMessage begin pass end class class GameNextStage ex...
import pygame import random FUNDO = 0, 0, 0 W, H = TAMANHO = 640, 480 w, h = 16, 12 BLOCO = BL = W / w v = 1 / 3 class GameMessage(Exception): pass class GameOver(GameMessage): pass class GameNextStage(GameMessage): pass monstros = [] class Mapa: def __init__(self, caminho, deslocamento=0, des_y=0...
Python
zaydzuhri_stack_edu_python
import math function heron a b c begin set s = a + b + c / 2 set area = square root s * s - a * s - b * s - c return area end function print string The area of the triangle is call heron 6 8 10
import math def heron(a, b, c): s = (a + b + c) / 2 area = math.sqrt(s * (s - a) * (s - b) * (s - c)) return area print('The area of the triangle is ', heron(6, 8, 10))
Python
iamtarun_python_18k_alpaca
comment I've set the password default to "admin" set password = string admin set attempt = input string Please enter the password to access: if attempt == password begin print string Access Granted print string Who do you wanna hack? end else begin print string Access Denied end
# I've set the password default to "admin" password = "admin" attempt = input("Please enter the password to access: ") if attempt == password: print("Access Granted") print("Who do you wanna hack?") else: print("Access Denied")
Python
zaydzuhri_stack_edu_python
function get_OccurringTrialTypes doc code=true begin set trial_id_list = call get_TrialIDs doc set output = call tolist return output end function
def get_OccurringTrialTypes(doc, code=True): trial_id_list = get_TrialIDs(doc) output = np.unique([get_TrialType(doc, trid, code=code) for trid in trial_id_list]).tolist() return output
Python
nomic_cornstack_python_v1
function test_rule_re_indenting self begin set formatter = call setup_formatter string { TAB * 1 } rule a: { TAB * 2 } wrapper: { TAB * 3 } "a" set expected = string rule a: { TAB * 1 } wrapper: { TAB * 2 } "a" assert call get_formatted == expected end function
def test_rule_re_indenting(self): formatter = setup_formatter( f"{TAB * 1}rule a:\n" f"{TAB * 2}wrapper:\n" f'{TAB * 3}"a"\n' ) expected = f"rule a:\n" f"{TAB * 1}wrapper:\n" f'{TAB * 2}"a"\n' assert formatter.get_formatted() == expected
Python
nomic_cornstack_python_v1
comment coding:utf-8 from multiprocessing import Pool , Queue , Process import multiprocessing as mp import time , random import codecs import jieba.analyse call set_stop_words string data.txt function extract_keyword input_string begin comment print("Do task by process {proc}".format(proc=os.getpid())) set tags = call...
# coding:utf-8 from multiprocessing import Pool, Queue, Process import multiprocessing as mp import time, random import codecs import jieba.analyse jieba.analyse.set_stop_words("data.txt") def extract_keyword(input_string): # print("Do task by process {proc}".format(proc=os.getpid())) tags = jieba.analyse.ex...
Python
zaydzuhri_stack_edu_python
async function start self begin set _acme_task = call run_task call _certificate_handler await wait _info_loaded end function
async def start(self) -> None: self._acme_task = self.cloud.run_task(self._certificate_handler()) await self._info_loaded.wait()
Python
nomic_cornstack_python_v1
from dataclasses import dataclass decorator dataclass class DateItem begin set dateStr : str set year : str set yearAD : str set month : str set day : str end class class DateProcess begin string Class for processing date string @parameter dateStr string function __init__ self dateStr begin set dateStr = dateStr set la...
from dataclasses import dataclass @dataclass class DateItem: dateStr:str year:str yearAD:str month:str day:str class DateProcess(): ''' Class for processing date string @parameter dateStr string ''' def __init__(self, dateStr): self.dateStr = dateStr self.latestdateStr = '' self.pr...
Python
zaydzuhri_stack_edu_python
function find_points_in_range self start=0 end=none begin set points = list if end is none begin set end = module - 1 end for x in call xrange start end + 1 begin set p = call check_x x if p == false begin continue end extend points p end return points end function
def find_points_in_range(self, start=0, end=None): points = [] if end is None: end = self.module - 1 for x in xrange(start, end + 1): p = self.check_x(x) if p == False: continue points.extend(p) return points
Python
nomic_cornstack_python_v1
string Problem Name: Find All Numbers Disappeared in an Array Platform: Leetcode Difficulty: Easy Problem Link: https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ string APPROACH: The problem states that a list containes value ranging from 1 to length but few are repeating twice, once or are not pr...
""" Problem Name: Find All Numbers Disappeared in an Array Platform: Leetcode Difficulty: Easy Problem Link: https://leetcode.com/problems/find-all-numbers-disappeared-in-an-array/ """ """ APPROACH: The problem states that a list containes value ranging from 1 to length but few are repeating twice, once or are not p...
Python
zaydzuhri_stack_edu_python
function sortList list begin sort list return list end function set sortedList = call sortList list 4 5 2 1 3 print sortedList
def sortList(list): list.sort() return list sortedList = sortList([4, 5, 2, 1, 3]) print(sortedList)
Python
flytech_python_25k
import view import model import random function run begin load model call welcome_menu call main_menu end function function main_menu begin while true begin set selection = random choice if selection == string 1 begin call create_account end else if selection == string 2 begin call login end else if selection == string...
import view import model import random def run(): model.load() view.welcome_menu() main_menu() def main_menu(): while True: selection = view.choice() if selection == "1": create_account() elif selection == "2": login() elif s...
Python
zaydzuhri_stack_edu_python
comment with open('module.py', 'r') as file: comment for line in file.readlines(): comment print(line) import os comment print(os.name) comment print(os.environ.get("PATH")) function findStr dirPath targetStr begin set L = list directory dirPath for file in L begin if targetStr in file begin print absolute path path fi...
# with open('module.py', 'r') as file: # for line in file.readlines(): # print(line) import os # print(os.name) # print(os.environ.get("PATH")) def findStr(dirPath, targetStr): L = os.listdir(dirPath) for file in L: if targetStr in file: print(os.path.abspath(file)) ...
Python
zaydzuhri_stack_edu_python
import urllib2 import json from bs4 import BeautifulSoup import pandas as pd set BASE_URL = string http://www.milb.com/gdcross/components/game/ comment the directory for AAA is /aaa/, AA is /aax comment then the year, in the form of year_2014/ comment then month in the form month_05/ (for May, for instance) comment the...
import urllib2 import json from bs4 import BeautifulSoup import pandas as pd BASE_URL = "http://www.milb.com/gdcross/components/game/" # the directory for AAA is /aaa/, AA is /aax # then the year, in the form of year_2014/ #then month in the form month_05/ (for May, for instance) #then day in the form day_06 #so to ge...
Python
zaydzuhri_stack_edu_python
function regression_plot begin set df = read csv string tempYearly.csv comment construct regression line set sns_plot = call regplot x=string Rainfall y=string Temperature data=df set image = call BytesIO save figure image format=string png comment reset position of image to 0 seek image 0 return image end function
def regression_plot(): df = pd.read_csv('tempYearly.csv') sns_plot = sns.regplot(x='Rainfall', y='Temperature', data=df) # construct regression line image = io.BytesIO() sns_plot.figure.savefig(image, format = 'png') image.seek(0) # reset position of image to 0 return image
Python
nomic_cornstack_python_v1
function add_undirected_edge self vertex_one vertex_two weight=none begin set _edge_dict at tuple vertex_one vertex_two = call Edge vertex_one vertex_two weight set _edge_dict at tuple vertex_two vertex_one = call Edge vertex_two vertex_one weight call add_edge vertex_one weight call add_edge vertex_two weight set from...
def add_undirected_edge(self, vertex_one, vertex_two, weight=None): self._edge_dict[vertex_one, vertex_two] = Edge(vertex_one, vertex_two, weight) self._edge_dict[vertex_two, vertex_one] = Edge(vertex_two, vertex_one, weight) self._vertex_dict[vertex_two].abstract_vertex.add_edge(vertex_one, wei...
Python
nomic_cornstack_python_v1
string Created on 09/08/2011 @author: nelson687 import facebook function get token begin set graph = call GraphAPI token set friendsJson = call get_connections string me string friends comment transform the json in a dictionary set friendsDict = dictionary for friend in friendsJson at string data begin set friendsDict ...
''' Created on 09/08/2011 @author: nelson687 ''' import facebook def get(token): graph = facebook.GraphAPI(token) friendsJson = graph.get_connections("me", "friends") #transform the json in a dictionary friendsDict = dict() for friend in friendsJson['data']: f...
Python
zaydzuhri_stack_edu_python
import os import getpass import glob import time function createIfNotExist folder begin if not exists path folder begin make directories folder end end function function move folderName files begin for file in files begin replace os file string { folderName } / { file } end end function function emptyfolder pathtofile ...
import os import getpass import glob import time def createIfNotExist(folder): if not os.path.exists(folder): os.makedirs(folder) def move(folderName,files): for file in files: os.replace(file,f"{folderName}/{file}") def emptyfolder(pathtofile): files=glob.glob(pathtofile) for file in...
Python
zaydzuhri_stack_edu_python
function iterate_document_sections document begin set paragraphs = list paragraphs at 0 for paragraph in paragraphs at slice 1 : : begin if call is_heading2 paragraph begin yield paragraphs set paragraphs = list paragraph continue end append paragraphs paragraph end yield paragraphs end function
def iterate_document_sections(document): paragraphs = [document.paragraphs[0]] for paragraph in document.paragraphs[1:]: if is_heading2(paragraph): yield paragraphs paragraphs = [paragraph] continue paragraphs.append(paragraph) yield paragraphs
Python
nomic_cornstack_python_v1
function roll self shift begin string shift vector set _saved = call LimitedSizeDict size_limit=2 ^ 5 set new_arr = zeros length self dtype=dtype if shift < 0 begin set shift = shift - length self * shift // length self end if shift == 0 begin return end set new_arr at slice 0 : shift : = self at slice length self - s...
def roll(self, shift): """shift vector """ self._saved = LimitedSizeDict(size_limit=2**5) new_arr = zeros(len(self), dtype=self.dtype) if shift < 0: shift = shift - len(self) * (shift // len(self)) if shift == 0: return n...
Python
jtatman_500k
function handle_repeat_request intent session begin if string attributes not in session or string speech_output not in session at string attributes begin return call get_welcome_response end else begin set attributes = session at string attributes set speech_output = attributes at string speech_output set reprompt_text...
def handle_repeat_request(intent, session): if 'attributes' not in session or 'speech_output' not in session['attributes']: return get_welcome_response() else: attributes = session['attributes'] speech_output = attributes['speech_output'] reprompt_text = attributes['reprompt_text...
Python
nomic_cornstack_python_v1
import json import os from flask import Flask from flask import jsonify from flask import render_template from flask import request from flask import redirect from flask import url_for from listman import ListMan set DATA_DIR = string data set app = call Flask __name__ set DEFAULT_LISTS = list string basic string high-...
import json import os from flask import Flask from flask import jsonify from flask import render_template from flask import request from flask import redirect from flask import url_for from listman import ListMan DATA_DIR = "data" app = Flask(__name__) DEFAULT_LISTS = ["basic", "high-freq", "advanced"] # =======...
Python
zaydzuhri_stack_edu_python
function project request project begin return time request project=project end function
def project(request, project): return time(request, project=project)
Python
nomic_cornstack_python_v1
string __author__:'vacada' __description__: 实现一个 @timer 装饰器,记录函数的运行时间,注意需要考虑函数可能会接收不定长参数。 __mtime__:2020/8/16 import time from functools import wraps function timer func begin decorator wraps func function inner *args **kwargs begin set start_time = time set ret = call func *args keyword kwargs set end_time = time prin...
""" __author__:'vacada' __description__: 实现一个 @timer 装饰器,记录函数的运行时间,注意需要考虑函数可能会接收不定长参数。 __mtime__:2020/8/16 """ import time from functools import wraps def timer(func): @wraps(func) def inner(*args, **kwargs): start_time = time.time() ret = func(*args, **kwargs) end_time = time.time() ...
Python
zaydzuhri_stack_edu_python
import numpy as np import torch comment If the predicted probability is higher than the following value, it is considered a vote set vote_prob_threshold = 0.25 comment If the ratio of positive voter is high thant the following value, positive result is accepted set vote_acc_threshold = 0.25 set original_shape = tuple 6...
import numpy as np import torch # If the predicted probability is higher than the following value, it is considered a vote vote_prob_threshold = 0.25 # If the ratio of positive voter is high thant the following value, positive result is accepted vote_acc_threshold = 0.25 original_shape = (608, 608) crop_shape = (400,...
Python
zaydzuhri_stack_edu_python
import unittest from numberAddCommas import addCommas class addCommasUnitTest extends TestCase begin function setUp self begin pass end function function tearDown self begin pass end function function test_Positive_Number self begin set ipunt = 12345678 set expected_result = string 12,345,678 set result = call addComma...
import unittest from numberAddCommas import addCommas class addCommasUnitTest(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_Positive_Number(self): ipunt = 12345678 expected_result = "12,345,678" result = addCommas(ipunt) self....
Python
zaydzuhri_stack_edu_python
import csv import pyConTextNLP.pyConText as pyConText from pyConTextNLP.itemData import contextItem import pyConTextNLP.itemData as itemData import networkx as nx function modifies g n modifiers begin string g: directed graph representing the ConText markup n: a node in g modifiers: a list of categories e.g. ["definite...
import csv import pyConTextNLP.pyConText as pyConText from pyConTextNLP.itemData import contextItem import pyConTextNLP.itemData as itemData import networkx as nx def modifies(g,n,modifiers): """g: directed graph representing the ConText markup n: a node in g modifiers: a list of categories e.g. ["definite_negated_...
Python
zaydzuhri_stack_edu_python
function jaccard graph node k begin set neighbors = set call neighbors node set scores = list for n in call nodes begin if node != n and not call has_edge node n begin set neighbors2 = set call neighbors n append scores tuple tuple node n 1.0 * length neighbors ? neighbors2 / length neighbors ? neighbors2 end end retu...
def jaccard(graph, node, k): neighbors = set(graph.neighbors(node)) scores = [] for n in graph.nodes(): if node!=n and not graph.has_edge(node,n): neighbors2 = set(graph.neighbors(n)) scores.append(((node,n), 1. * len(neighbors & neighbors2) / len(neighbors | neighbors2))) ...
Python
nomic_cornstack_python_v1
function _get_local_order_parameters structure_graph n begin comment TODO: move me to pymatgen once stable comment code from @nisse3000, moved here from graphs to avoid circular comment import, also makes sense to have this as a general NN method set cn = call get_coordination_of_site n if cn in list comprehension inte...
def _get_local_order_parameters(structure_graph, n): # TODO: move me to pymatgen once stable # code from @nisse3000, moved here from graphs to avoid circular # import, also makes sense to have this as a general NN method cn = structure_graph.get_coordination_of_site(n) if cn in [int(k_cn) for k_cn ...
Python
nomic_cornstack_python_v1
function test_create_too_long_comment self begin call expect_get_posts call AndReturn comment call ReplayAll set b = call new auth_entity=auth_entity set resp = call create_comment string http://blawg/path/to/post string Degenève string http://who string foo Degenève bar client=blogger_client call assert_equals dict st...
def test_create_too_long_comment(self): self.expect_get_posts() self.blogger_client.add_comment( '111', '222', '<a href="http://who">Degenève</a>: foo Degenève bar' ).AndReturn(self.comment) self.mox.ReplayAll() b = Blogger.new(auth_entity=self.auth_entity) resp = b.create_comment('http...
Python
nomic_cornstack_python_v1
function plotting x y path extra=true save=false show=false title=string begin call rc string text usetex=true call rc string font family=string serif set fig = figure figsize=tuple 5 3 set ax = call add_axes list 0.1 0.1 0.6 0.75 plot x y string ro lw=2 comment fit a line set lr = linear regression x y comment D, slop...
def plotting(x, y, path, extra=True, save=False, show=False, title=""): plt.rc('text', usetex=True) plt.rc('font', family='serif') fig = plt.figure(figsize=(5, 3)) ax = fig.add_axes([0.1, 0.1, 0.6, 0.75]) ax.plot( x, y, 'ro', lw=2) # fit a line lr = linregress(x, y) slope = lr.slope #...
Python
nomic_cornstack_python_v1
function jdcday jd begin set i = call trunc jd + 0.5 set f = jd + 0.5 - i set a = call trunc i - 1867216.25 / 36524.25 if i > 2299160 begin set b = i + 1 + a - call trunc a / 4 end else begin set b = i end set c = b + 1524 set d = call trunc c - 122.1 / 365.25 set e = call trunc 365.25 * d set g = call trunc c - e / 30...
def jdcday(jd): i = math.trunc(jd + 0.5) f = (jd + 0.5) - i a = math.trunc((i - 1867216.25) / 36524.25) if i > 2299160: b = i + 1 + a - math.trunc(a / 4) else: b = i c = b + 1524 d = math.trunc((c - 122.1) / 365.25) e = math.trunc(365.25 * d) g = math.trunc((c - e) / ...
Python
nomic_cornstack_python_v1
function dataframe_raw_trades begin set data = list list string 701 string 1 string 1000 string 700 string A1 list string 002 string 1 string 1000 string 1170 string B2 list string 103 string 2 string 500 string 200 string C3 set df_cols = list string CorrelationID string NumberOfTrades string Limit string Value string...
def dataframe_raw_trades(): data = [ ['701', '1', '1000', '700', 'A1'], ['002', '1', '1000', '1170', 'B2'], ['103', '2', '500', '200', 'C3'] ] df_cols = ['CorrelationID', 'NumberOfTrades', 'Limit', 'Value', 'TradeID'] df = pd.DataFrame(data, columns=df_cols) return df
Python
nomic_cornstack_python_v1
from sys import argv set tuple script input_encoding error = argv function main language_file encoding errors begin set line = read line language_file if line begin call print_line line encoding errors return call main language_file encoding errors end end function function print_line line encoding errors begin comment...
from sys import argv script, input_encoding, error = argv def main(language_file, encoding, errors): line = language_file.readline() if line: print_line(line, encoding, errors) return main(language_file, encoding, errors) def print_line(line, encoding, errors): # strip() removes \n from th...
Python
zaydzuhri_stack_edu_python
function initialize_summaries self begin comment Summaries: gradient values, loss and accuracy set grad_summaries = list for tuple g v in grads_and_vars begin if g is not none begin set var_name = replace name string : string _ set grad_hist_summary = call histogram format string {}/grad/hist var_name g set sparsity_s...
def initialize_summaries(self): # Summaries: gradient values, loss and accuracy grad_summaries = [] for g, v in self.grads_and_vars: if g is not None: var_name = v.name.replace(':','_') grad_hist_summary = tf.summary.histogram("{}/grad/hist".format(var...
Python
nomic_cornstack_python_v1
import pandas as pd set incentives_df = call read_excel string C:/Python27/My_Scripts/vamsi/interview/New folder/incentives.xlsx set incentive_upc_df = call read_excel string C:/Python27/My_Scripts/vamsi/interview/New folder/incentive_upc.xlsx set Transactions_url = string https://s3.amazonaws.com/inmar-interview-dataa...
import pandas as pd incentives_df = pd.read_excel('C:/Python27/My_Scripts/vamsi/interview/New folder/incentives.xlsx') incentive_upc_df = pd.read_excel('C:/Python27/My_Scripts/vamsi/interview/New folder/incentive_upc.xlsx') Transactions_url = "https://s3.amazonaws.com/inmar-interview-dataanalyst/Rawdata/Transactions...
Python
zaydzuhri_stack_edu_python
class LearningProblem extends object begin string Generic learning problem. function __init__ self begin pass end function function init self begin raise call NotImplementedError end function function next self iteration=none begin raise call NotImplementedError end function function update self update begin comment Re...
class LearningProblem(object): """Generic learning problem.""" def __init__(self): pass def init(self): raise NotImplementedError() def next(self, iteration=None): raise NotImplementedError() def update(self, update): # Returns a list of new le...
Python
zaydzuhri_stack_edu_python
function seek self begin raise call OSError end function
def seek(self): raise OSError()
Python
nomic_cornstack_python_v1
function sumDigits number begin if number < 0 begin set number = number * - 1 end set number_str = string number set total = 0 for i in number_str begin set total = total + integer i end return total end function print call sumDigits - 32
def sumDigits(number): if number < 0: number *= -1 number_str = str(number) total = 0 for i in number_str: total += int(i) return total print(sumDigits(-32))
Python
zaydzuhri_stack_edu_python
if a > b begin print string a bada hai end else begin print string b bada hai end
if a > b: print("a bada hai") else: print("b bada hai")
Python
zaydzuhri_stack_edu_python
comment ------------------------------currency------------------------------# comment ------------------------------Diana_Yu------------------------------# comment ------------------------------20171203------------------------------# string Module for currency exchange This module provides several string parsing functi...
#------------------------------currency------------------------------# #------------------------------Diana_Yu------------------------------# #------------------------------20171203------------------------------# """Module for currency exchange This module provides several string parsing functions to implement a simp...
Python
zaydzuhri_stack_edu_python
function register_server body namespace=none x_additional_headers=none **kwargs begin if namespace is none begin set tuple namespace error = call get_services_namespace if error begin return tuple none error end end set request = call create body=body namespace=namespace return call run_request request additional_heade...
def register_server( body: ModelsRegisterServerRequest, namespace: Optional[str] = None, x_additional_headers: Optional[Dict[str, str]] = None, **kwargs ): if namespace is None: namespace, error = get_services_namespace() if error: return None, error request = Registe...
Python
nomic_cornstack_python_v1
from context import * import pytest from triangle import Triangle class TestTriangle extends object begin function test_triangle_constructor_sets_length_of_3_sides self begin set sides = list 3 4 5 set triangle = call Triangle sides assert sides == sides end function end class
from .context import * import pytest from triangle import Triangle class TestTriangle(object): def test_triangle_constructor_sets_length_of_3_sides(self): sides = [3, 4, 5] triangle = Triangle(sides) assert triangle.sides == sides
Python
zaydzuhri_stack_edu_python
function simulation begin start traci call getCmdLine set step = 0 set vehID = 0 set openRoute = 1 set stopTime = 5 while step < 500 begin comment Endormir le programme pendant une seconde. sleep 0.1 comment Lancement de la simulation. call simulationStep set tuple cars_north cars_suth cars_est cars_west = call detectC...
def simulation(): traci.start(getCmdLine()) step = 0 vehID = 0 openRoute = 1 stopTime = 5 while step < 500: time.sleep(0.1) # Endormir le programme pendant une seconde. traci.simulationStep() # Lancement de la simulation. cars_north, cars_suth, cars_est, cars_west = det...
Python
nomic_cornstack_python_v1
function get_image name size=none begin assert name in IMAGE_COLLECTION msg string We don't have the image '%s' in the gallary % tuple name set tuple _ ext = call splitext IMAGE_COLLECTION at name set relative_path = join path string images name + ext set filename = call get_file relative_name=relative_path url=IMAGE_C...
def get_image(name, size = None): assert name in IMAGE_COLLECTION, "We don't have the image '%s' in the gallary" % (name, ) _, ext = os.path.splitext(IMAGE_COLLECTION[name]) relative_path = os.path.join('images', name)+ext filename = get_file( relative_name = relative_path, url = IMAGE_C...
Python
nomic_cornstack_python_v1
function _yield_native_fields self begin for tuple attr_name attr_value in items __dict__ begin if not is instance attr_value BaseField begin continue end if starts with attr_name string _ begin raise call InvalidStructError string Fields must not begin with an underscore. Found: { attr_name } = { type attr_value } end...
def _yield_native_fields(self) -> Generator[Tuple[str, BaseField], None, None]: for attr_name, attr_value in self.struct_class.__dict__.items(): if not isinstance(attr_value, BaseField): continue if attr_name.startswith("_"): raise InvalidStructError( ...
Python
nomic_cornstack_python_v1
comment py02_10_Debug.py set x = 100 comment 101 set x = x + 1 comment 102 set x = x + 1 comment x =102 print string x= x
# py02_10_Debug.py x = 100 x = x+1 # 101 x = x+1 # 102 print("x=", x) # x =102
Python
zaydzuhri_stack_edu_python
import numpy as np function verticalSeam cumulative begin comment find lowest cumulative value along bottom row set out = list comment last row append out argument minimum cumulative at - 1 for i in range length cumulative - 1 begin comment row we look at set y = - length out + 1 if out at - 1 == 0 begin set choices = ...
import numpy as np def verticalSeam(cumulative): # find lowest cumulative value along bottom row out = list() # last row out.append(np.argmin(cumulative[-1])) for i in range(len(cumulative) - 1): # row we look at y = -(len(out)+1) if out[-1] == 0: choices = [cu...
Python
zaydzuhri_stack_edu_python
class designStack_Min begin function __init__ self begin set stack = list set min_stack = list set size = 0 end function function push self x begin if not min_stack == 0 begin append min_stack x end else if x <= min_stack at - 1 begin append min_stack x end append stack x set size = size + 1 end function function pop...
class designStack_Min: def __init__(self): self.stack = [] self.min_stack = [] self.size = 0 def push(self,x:int)->None: if not self.min_stack==0: self.min_stack.append(x) else: if x<=self.min_stack[-1]: self.min_stack.append(x) ...
Python
zaydzuhri_stack_edu_python
comment Name: Ahsan Khan comment Date: 09/15/2020 comment Description: Showing arithmetic operators comment Arithmetic Operators Add (+), Subtract (-), Multiply (*), Divide (/) print 2 + 3 print 3 - 2 print 2 * 3 print 3 / 2 comment Integeral Division and Exponents, x^2 will be represented as (x ** 2). print 3 ^ 2 prin...
# Name: Ahsan Khan # Date: 09/15/2020 # Description: Showing arithmetic operators # Arithmetic Operators Add (+), Subtract (-), Multiply (*), Divide (/) print(2 + 3) print(3 - 2) print(2 * 3) print(3 / 2) # Integeral Division and Exponents, x^2 will be represented as (x ** 2). print(3 ** 2) print(3 ** 3)...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 string function that inserts a new document in collection (mongo) function insert_school mongo_collection **kwargs begin string return new id of the newly inserted document if mongo_collection begin return inserted_id end end function if __name__ == string __main__ begin call insert_school...
#!/usr/bin/env python3 """ function that inserts a new document in collection (mongo) """ def insert_school(mongo_collection, **kwargs): """ return new id of the newly inserted document """ if mongo_collection: return mongo_collection.insert_one(kwargs).inserted_id if __name__ == "__main__":...
Python
zaydzuhri_stack_edu_python
function large_sum begin set f = split read open string dig_p13.txt return string sum map int f at slice 0 : 10 : end function
def large_sum(): f = open('dig_p13.txt').read().split() return str(sum(map(int, f)))[0:10]
Python
zaydzuhri_stack_edu_python
function file_loader path begin try begin with open path as file begin return read file end end except FileNotFoundError begin print string File { path } does not exist. return none end end function print call file_loader string nonexistent print string - * 80 print call file_loader string 59_file_loader.py
def file_loader(path): try: with open(path) as file: return file.read() except FileNotFoundError: print(f'File {path} does not exist.') return None print(file_loader('nonexistent')) print('-' * 80) print(file_loader('59_file_loader.py'))
Python
zaydzuhri_stack_edu_python
for i in range 12 begin append d list for j in range 12 begin append d at i 0 end end for i in range 10 begin set a = split input for j in range 10 begin set d at i + 1 at j + 1 = integer a at j end end set x = 2 set y = 2 while true begin if d at x at y == 0 begin set d at x at y = 9 end else if d at x at y == 2 begin...
for i in range(12): d.append([]) for j in range(12): d[i].append(0) for i in range(10): a = input().split() for j in range(10): d[i+1][j+1] = int(a[j]) x = 2 y = 2 while True: if d[x][y] == 0: d[x][y] = 9 elif d[x][y] == 2: d[x][y] = 9 break if (d[x...
Python
zaydzuhri_stack_edu_python
from datetime import datetime as dt import toml import glob import logging from urllib.parse import urlencode import os import asyncio import aiohttp import discord from discord.ext import commands from cogs.utils.database import DatabaseConnection from cogs.utils.cached_message import CachedMessage function get_prefix...
from datetime import datetime as dt import toml import glob import logging from urllib.parse import urlencode import os import asyncio import aiohttp import discord from discord.ext import commands from cogs.utils.database import DatabaseConnection from cogs.utils.cached_message import CachedMessage def get_prefix(...
Python
zaydzuhri_stack_edu_python
function get_custom_num self begin set _sum = 0 for route in sequence begin set temp = array sequence set temp = temp at temp <= 1000 set _sum = _sum + length temp end return _sum end function
def get_custom_num(self): _sum = 0 for route in self.sequence: temp = np.array(route.sequence) temp = temp[temp <= 1000] _sum += len(temp) return _sum
Python
nomic_cornstack_python_v1
import abc from typing import List from datetime import date from movie.domain.model import Director , Genre , Actor , Movie , User set repo_instance = none class RepositoryException extends Exception begin function __init__ self message=none begin pass end function end class class AbstractRepository extends ABC begin ...
import abc from typing import List from datetime import date from movie.domain.model import Director, Genre, Actor, Movie, User repo_instance = None class RepositoryException(Exception): def __init__(self, message=None): pass class AbstractRepository(abc.ABC): @abc.abstractmethod def add_di...
Python
zaydzuhri_stack_edu_python
comment Python Making A Class Iterable.pdf class ClassIteration extends object begin function __init__ self stringinput begin print string Now in ClassIteration.__init__ self,stringinput. Class initiation create the instance. set stringinput = stringinput end function function __iter__ self begin print string Now in Cl...
#Python Making A Class Iterable.pdf class ClassIteration(object): def __init__(self, stringinput): print("Now in ClassIteration.__init__ self,stringinput. Class initiation create the instance.") self.stringinput = stringinput def __iter__(self): print("Now in ClassIteration.__iter__ sel...
Python
zaydzuhri_stack_edu_python