code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function update self current_day mortality_probability begin if state == infected begin if sick_days > 0 and current_day - day_of_infection >= sick_days begin comment Person has recovered and is henceforth immune set state = immune set day_of_immunity = current_day end else begin comment Person might die due to the mor...
def update(self, current_day, mortality_probability): if self.state == State.infected: if self.sick_days > 0 and current_day - self.day_of_infection >= self.sick_days: # Person has recovered and is henceforth immune self.state = State.immune self.day_...
Python
nomic_cornstack_python_v1
function _wait_for_device self dut begin while serial not in call list_adb_devices begin pass end call wait_for_device end function
def _wait_for_device(self, dut): while dut.serial not in android_device.list_adb_devices(): pass dut.adb.wait_for_device()
Python
nomic_cornstack_python_v1
from gmpy2 import isqrt function fermat n begin set a = call isqrt n set b2 = a * a - n set b = call isqrt n set count = 0 while b * b != b2 begin set a = a + 1 set b2 = a * a - n set b = call isqrt b2 set count = count + 1 end set p = a + b set q = a - b assert n == p * q return tuple p q end function
from gmpy2 import isqrt def fermat(n): a = isqrt(n) b2 = a * a - n b = isqrt(n) count = 0 while b * b != b2: a = a + 1 b2 = a * a - n b = isqrt(b2) count += 1 p = a + b q = a - b assert n == p * q return p, q
Python
zaydzuhri_stack_edu_python
function find_patterns pattern begin global k set fk = dict set temp_pattern = list comprehension i for j in patterns for i in j print temp_pattern for item in temp_pattern begin print item set support = count temp_pattern item if support >= min_support begin set fk at call frozenset item = support end end update main...
def find_patterns(pattern): global k fk = {} temp_pattern = [i for j in patterns for i in j] print(temp_pattern) for item in temp_pattern: print(item) support = temp_pattern.count(item) if support >= min_support: fk[frozenset(item)] = support main_dict.update(...
Python
zaydzuhri_stack_edu_python
function put self key value begin set hash_index = key % keyrange put key value end function
def put(self, key: int, value: int) -> None: hash_index = key % self.keyrange self.buckets[hash_index].put(key,value)
Python
nomic_cornstack_python_v1
function getBankFilepath mapName begin set banks = glob glob join path PATH_BANKS string *.%s % SC2_BANK_EXT set banks = list comprehension b for b in banks if search string ^%s % mapName base name path b flags=IGNORECASE if banks begin return banks at 0 end return join path PATH_BANKS string %s.%s % tuple mapName SC2_...
def getBankFilepath(mapName): banks = glob.glob(os.path.join(c.PATH_BANKS, "*.%s"%(c.SC2_BANK_EXT))) banks = [b for b in banks if re.search( "^%s"%mapName, os.path.basename(b), flags=re.IGNORECASE)] i...
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d from matplotlib import cm function gd begin string 一维y=x**2 初始x=10的梯度下降求最小值 :return: set x = 10 set result = list x set eta = 1.1 for i in range 10 begin set x = x - eta * x * 2 append result x end print result set fig = figure s...
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import axes3d from matplotlib import cm def gd(): ''' 一维y=x**2 初始x=10的梯度下降求最小值 :return: ''' x = 10 result = [x] eta = 1.1 for i in range(10): x -= eta * x * 2 result.append(x) print(result)...
Python
zaydzuhri_stack_edu_python
import random from typing import List function generate_matrix rows cols min_ max_ begin string Generuje maticu cisel zo zadaneho rozsahu Ako vstupy sluzia min/max hodnot a pocty riadkov a stlpcov :param rows: int pocet riadkov :param cols: int pocet stlpcov :param min_: int minimalna hodnota :param max_: int maximalna...
import random from typing import List def generate_matrix(rows: int, cols: int, min_: int, max_: int) -> List[list]: """ Generuje maticu cisel zo zadaneho rozsahu Ako vstupy sluzia min/max hodnot a pocty riadkov a stlpcov :param rows: int pocet riadkov :param cols: int pocet stlpcov :param min_...
Python
zaydzuhri_stack_edu_python
import sys set stdin = open string input.txt string r string function changetotwo ten begin for i in range 4 begin if ten ? 8 ? i begin print string 1 end=string end else begin print string 0 end=string end end end function for tc in range 1 integer input + 1 begin set tuple N S = split input set N = integer N print f...
import sys sys.stdin=open('input.txt','r') ''' ''' def changetotwo(ten): for i in range(4): if ten & (8>>i): print('1',end="") else: print('0',end= "") for tc in range(1,int(input())+1): N,S=input().split() N=int(N) print('#{}'.format(tc),end=" ") for i in r...
Python
zaydzuhri_stack_edu_python
comment arguments passing by user by input function greet name time begin print string good morning { name } , hope your greate at this { time } end function set xyz = input string enter your name set yzw = input string enter the time call greet xyz yzw
# arguments passing by user by input def greet(name,time): print(f'good morning{name}, hope your greate at this {time}') xyz = input('enter your name') yzw = input('enter the time') greet(xyz, yzw)
Python
zaydzuhri_stack_edu_python
from math import ceil , floor set lines = list comprehension integer right strip line string for line in open string ./_32387ba40b36359a38625cbb397eee65_QuickSort.txt set firstTen = lines function partitionFirstElement arr begin set r = length arr if r == 1 or r == 0 begin return 0 end set comparisons = length arr - 1 ...
from math import ceil, floor lines = [int(line.rstrip('\n')) for line in open('./_32387ba40b36359a38625cbb397eee65_QuickSort.txt')] firstTen = lines def partitionFirstElement (arr): r = len(arr) if(r == 1 or r == 0): return 0 comparisons = len(arr) - 1 p = arr[0] i = 1 for j in range(1, r): if arr[...
Python
zaydzuhri_stack_edu_python
import math set x = decimal input set y = ceil x print y
import math x=float(input()) y=math.ceil(x) print(y)
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Created on Thu Aug 09 16:00:44 2018 @author: Administrator from jqdatasdk import * import datetime comment auth('18610039264', 'zg19491001') from configDB import * call auth JOINQUANT_USER JOINQUANT_PW string 1、以下函数中 股票代码的格式为 '000001.XSHE','603980.XSHG',日期格式为 '2018-01-01' 2、开通权限后,您可...
# -*- coding: utf-8 -*- """ Created on Thu Aug 09 16:00:44 2018 @author: Administrator """ from jqdatasdk import * import datetime # auth('18610039264', 'zg19491001') from configDB import * auth(JOINQUANT_USER, JOINQUANT_PW) """ 1、以下函数中 股票代码的格式为 '000001.XSHE','603980.XSHG',日期格式为 '2018-01-01' 2、开通权限后,您可以在本地Python环境下安...
Python
zaydzuhri_stack_edu_python
function exec_display self stmt begin call stmt_print string call eval_node content end=if expression newline then string else string end function
def exec_display(self, stmt: DisplayStmt): self.stmt_print(str(self.evaluator.eval_node(stmt.content)), end="\n" if stmt.newline else "")
Python
nomic_cornstack_python_v1
function PresetCharactersExcelAddExSkillLevel builder ExSkillLevel begin return call AddExSkillLevel builder ExSkillLevel end function
def PresetCharactersExcelAddExSkillLevel(builder, ExSkillLevel): return AddExSkillLevel(builder, ExSkillLevel)
Python
nomic_cornstack_python_v1
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingClassifier import pickle set df = read csv string diabetes.csv set columns_to_consider = list string Pregnancies string Glucose string BloodPressure string Insulin string BMI string A...
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingClassifier import pickle df = pd.read_csv('diabetes.csv') columns_to_consider = ['Pregnancies', 'Glucose', 'BloodPressure','Insulin', 'BMI', 'Age'] x_train, x_test, y_tra...
Python
zaydzuhri_stack_edu_python
import pandas as pd set onefile = read csv string calander.csv print onefile comment print(pd.DataFrame.equals(onefile)) set df = call DataFrame onefile print df set g = groups print call get_group 25 set ipl_data = dict string Team list string Riders string Riders string Devils string Devils string Kings string kings ...
import pandas as pd onefile = pd.read_csv("calander.csv") print(onefile) #print(pd.DataFrame.equals(onefile)) df = pd.DataFrame(onefile) print(df) g = df.groupby('Maximum').groups print (g.get_group(25)) ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'kings', 'Kings', 'K...
Python
zaydzuhri_stack_edu_python
class Solution extends object begin function maxProfit self prices begin string :type prices: List[int] :rtype: int set buy = - 1 set profit = 0 set length = length prices for i in range length - 1 begin comment go down if prices at i + 1 <= prices at i begin if buy != - 1 begin comment sell set profit = profit + price...
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ buy = -1 profit = 0 length = len(prices) for i in range(length-1): # go down if prices[i+1] <= prices[i]: ...
Python
zaydzuhri_stack_edu_python
comment To find the largest number among three numbers set num1 = decimal input string Enter the first number: set num2 = decimal input string Enter the second number: set num3 = decimal input string Enter the third number: if num1 >= num2 and num1 >= num3 begin print format string {0} is the largest number num1 end el...
#To find the largest number among three numbers num1 = float(input("Enter the first number:")) num2 = float(input("Enter the second number:")) num3 = float(input("Enter the third number:")) if (num1 >= num2) and (num1 >= num3) : print("{0} is the largest number".format(num1)) elif (num2 >= num1) and(num2 >=...
Python
zaydzuhri_stack_edu_python
function list_pop_range bin_name index count ctx=none begin set op_dict = dict OP_KEY OP_LIST_POP_RANGE ; BIN_KEY bin_name ; INDEX_KEY index ; VALUE_KEY count if ctx begin set op_dict at CTX_KEY = ctx end return op_dict end function
def list_pop_range(bin_name, index, count, ctx=None): op_dict = { OP_KEY: aerospike.OP_LIST_POP_RANGE, BIN_KEY: bin_name, INDEX_KEY: index, VALUE_KEY: count } if ctx: op_dict[CTX_KEY] = ctx return op_dict
Python
nomic_cornstack_python_v1
import turtle from Square import square set screen = call Screen call bg string light green setup screen 600 500 call tracer 0 set x = 0 set y = 0 set color = string red while true begin set square = call Square x y color call draw clear square del square end call done
import turtle from Square import square screen = turtle.Screen() screen.bg("light green") screen.setup(600,500) screen.tracer(0) x = 0 y = 0 color = 'red' while True: square = Square(x, y, color) square.draw() square.clear() del square turtle.done()
Python
zaydzuhri_stack_edu_python
string Script to seed database. import os comment import json comment from random import choice, randint comment from datetime import datetime import crud from model import connect_to_db , db , User , Exercise , InjuryType , Routine import server from datetime import datetime comment always drop then create call system...
"""Script to seed database.""" import os # import json # from random import choice, randint # from datetime import datetime import crud from model import connect_to_db, db, User, Exercise, InjuryType, Routine import server from datetime import datetime # always drop then create os.system('dropdb ptremix') os.system(...
Python
zaydzuhri_stack_edu_python
function get_best_ai_agent begin set ai_agent = call DQNAgent train=false recurrent=true call load_model_from_path BEST_MODEL_PATH set eval = true return ai_agent end function
def get_best_ai_agent(): ai_agent = DQNAgent(train=False, recurrent=True) ai_agent.load_model_from_path(BEST_MODEL_PATH) ai_agent.eval = True return ai_agent
Python
nomic_cornstack_python_v1
function create_directory pathname begin make directories pathname call chmod pathname 448 end function
def create_directory(pathname): makedirs(pathname) os.chmod(pathname, 0o700)
Python
nomic_cornstack_python_v1
function connect user password host database begin set engine = call create_engine format string mysql://{user}:{password}@{host}/{database} user=user password=password host=host database=database call configure bind=engine info format string Successfully connected to {host}/{database} as {user} host=host database=data...
def connect(user, password, host, database): engine = create_engine('mysql://{user}:{password}@{host}/{database}' .format(user=user, password=password, host=host, database=database)) Session.configure(bind=engine) logger.info('Successfully connected to {host}/{database} as {user}'...
Python
nomic_cornstack_python_v1
function add_edge self v1 v2 begin comment add an edge value to the set in each vertex add vertices at v1 v2 end function
def add_edge(self, v1, v2): # add an edge value to the set in each vertex self.vertices[v1].add(v2)
Python
nomic_cornstack_python_v1
function __init__ self data_dir=string ./rsna-bone-age/ resize_to=tuple 256 256 augment=false preload=false preloaded_data=none begin set _resize_to = resize_to set _data_dir = data_dir set _augment = augment set _preload = preload set _df = read csv _data_dir + string /boneage-training-dataset.csv set _img_file_names ...
def __init__(self, data_dir='./rsna-bone-age/', resize_to=(256, 256), augment=False, preload=False, preloaded_data=None): self._resize_to = resize_to self._data_dir = data_dir self._augment = augment self._preload = preload self._df = pd.read_csv(self._data_dir...
Python
nomic_cornstack_python_v1
function addBouqetDesign self line begin set quantity = call _getTotalQuantityOfFlowers line set design = call BouqetDesign line at 0 line at 1 call _getFlowers line at slice 2 : - integer length string quantity : quantity append _designs design end function
def addBouqetDesign(self, line): quantity = self._getTotalQuantityOfFlowers(line) design = BouqetDesign( line[0], line[1], self._getFlowers(line[2:-int(len(str(quantity)))]), quantity ) self._designs.append(design)
Python
nomic_cornstack_python_v1
function handles_feed self *args **kwargs begin try begin call get_feed *args keyword kwargs end except UnhandledFeed begin return false end return true end function
def handles_feed(self, *args, **kwargs): try: self.get_feed(*args, **kwargs) except UnhandledFeed: return False return True
Python
nomic_cornstack_python_v1
function main begin set messageAlice = string Bonjour Bob Comment ca va? Ca va fait grave longtemps qu'on ne s'est pas vu. T'es chaud on se fait McDO :P Tu te souviens de la soirée, bahhh ... enfaite je suis tombé enceinte et t'es le père du gosse, il a 3 mois, il s'appelle Bernard, il a le meme nez que toi, miskine, e...
def main(): messageAlice = "Bonjour Bob Comment ca va? Ca va fait grave longtemps qu'on ne s'est pas vu. T'es chaud on se fait McDO :P Tu te souviens de la soirée, bahhh ... enfaite je suis tombé enceinte et t'es le père du gosse, il a 3 mois, il s'appelle Bernard, il a le meme nez que toi, miskine, et heureusement q...
Python
zaydzuhri_stack_edu_python
comment a=10 comment b=15 comment if b<a: comment print("B is greater then A") comment else: comment print set price = 15 set qty = 20 set amount = price * qty if amount < 100 begin print string 15% discount set discount = amount * 15 / 100 set amount = amount - discount print string amount payble amount end else begin...
#a=10 #b=15 #if b<a: #print("B is greater then A") #else: # print price=15 qty=20 amount=price*qty if amount<100: print("15% discount") discount=amount*15/100 amount=amount-discount print("amount payble",amount) else: print("5% discount ") discount=amount*5/100 amount=amount-discount...
Python
zaydzuhri_stack_edu_python
from os import system from datetime import datetime function clrscr begin set _ = call system string cls end function function isLeapYear year begin if year % 400 == 0 begin return true end if year % 100 == 0 begin return false end if year % 4 == 0 begin return true end return false end function function isRight pickup...
from os import system from datetime import datetime def clrscr(): _ = system('cls') def isLeapYear(year): if year%400==0: return True if year%100==0: return False if year%4==0: return True return False def isRight(pickup,drop,day,month,hour,minutes,m,year,later): if pi...
Python
zaydzuhri_stack_edu_python
function primes maxe begin string fonction qui cherche tous les nombres premiers entre # 2 et maxe# pre:Pour chaque nombre successif, on vérifie si on peut le diviser par un des nombres premiers déjà trouvés. Si non, on peut ajouter le nombre à la liste. post: retourner tous les nombres premiers entre 2 et maxe if maxe...
def primes(maxe): """fonction qui cherche tous les nombres premiers entre # 2 et maxe# pre:Pour chaque nombre successif, on vérifie si on peut le diviser par un des nombres premiers déjà trouvés. Si non, on peut ajouter le nombre à la liste. post: retourner tous les nombres premiers entre 2 et ...
Python
zaydzuhri_stack_edu_python
function _cover self begin raise call NotImplementedError end function
def _cover(self): raise NotImplementedError()
Python
nomic_cornstack_python_v1
function sum_of_array array begin set sum = 0 for i in range length array begin set sum = sum + array at i end return sum end function
def sum_of_array(array): sum = 0 for i in range(len(array)): sum += array[i] return sum
Python
jtatman_500k
function roofline_plot begin function attainable_performance operational_intensity begin return min PEAK_PERFORMANCE MEMORY_BANDWIDTH * operational_intensity end function set oi_values = call logspace - 4 12 1000 base=2 set perf_values = list comprehension call attainable_performance oi for oi in oi_values set tuple fi...
def roofline_plot(): def attainable_performance(operational_intensity): return min(PEAK_PERFORMANCE, MEMORY_BANDWIDTH * operational_intensity) oi_values = np.logspace(-4, 12, 1000, base=2) perf_values = [attainable_performance(oi) for oi in oi_values] fig, ax = viz_utils.setup_figure_1ax(x_lab...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Wed May 03 11:26:21 2017 @author: Kevin Anderson comment added per note import io import pandas as pd from bokeh.layouts import row from bokeh.models import ColumnDataSource , CustomJS from bokeh.models.widgets import Button from bokeh.io import curdoc import StringIO imp...
# -*- coding: utf-8 -*- """ Created on Wed May 03 11:26:21 2017 @author: Kevin Anderson """ import io # added per note import pandas as pd from bokeh.layouts import row from bokeh.models import ColumnDataSource, CustomJS from bokeh.models.widgets import Button from bokeh.io import curdoc import StringIO import base64...
Python
zaydzuhri_stack_edu_python
function num_integral_steps self begin return get pulumi self string num_integral_steps end function
def num_integral_steps(self) -> Optional[pulumi.Input[int]]: return pulumi.get(self, "num_integral_steps")
Python
nomic_cornstack_python_v1
import typing import yarl import aiohttp class Client begin set auth : Optional at dict set base_url : URL set _session = none function __init__ self base_url auth=none begin set auth = auth set base_url = call URL base_url end function function url_for self route begin if ends with path string / begin if starts with r...
import typing import yarl import aiohttp class Client: auth: typing.Optional[dict] base_url: yarl.URL _session = None def __init__(self, *, base_url: str, auth: typing.Optional[dict] = None): self.auth = auth self.base_url = yarl.URL(base_url) de...
Python
zaydzuhri_stack_edu_python
from collections import defaultdict set d = default dictionary lambda -> 0 d for i in a begin set d at i = get d i 0 + 1 end set p = 0 while p < 100010 begin set count = d at p - 1 + d at p + d at p + 1 set p = p + 1 if count > ans begin set ans = count end end print ans
from collections import defaultdict d = defaultdict(lambda: 0, d) for i in a: d[i]=d.get(i,0)+1 p=0 while(p<100010): count=d[p-1]+d[p]+d[p+1] p=p+1 if(count>ans): ans=count print(ans)
Python
zaydzuhri_stack_edu_python
function get_callbacks transfer_future callback_type begin string Retrieves callbacks from a subscriber :type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The transfer future the subscriber is associated to. :type callback_type: str :param callback_type: The type of callback to retrieve fr...
def get_callbacks(transfer_future, callback_type): """Retrieves callbacks from a subscriber :type transfer_future: s3transfer.futures.TransferFuture :param transfer_future: The transfer future the subscriber is associated to. :type callback_type: str :param callback_type: The type of callb...
Python
jtatman_500k
function _truncate_seq_pair tokens_a tokens_b mytokens_a mytokens_b labels_A labels_B max_length begin comment This is a simple heuristic which will always truncate the longer sequence comment one token at a time. This makes more sense than truncating an equal percent comment of tokens from each, since if one sequence ...
def _truncate_seq_pair(tokens_a, tokens_b, mytokens_a, mytokens_b, labels_A, labels_B, max_length): # This is a simple heuristic which will always truncate the longer sequence # one token at a time. This makes more sense than truncating an equal percent # of tokens from each, since if one sequence is very ...
Python
nomic_cornstack_python_v1
function __str__ self begin return string { _model_name } (pk= { _pk } ) end function
def __str__(self): return f"{self._model_name}(pk={self._pk})"
Python
nomic_cornstack_python_v1
function signup_view request begin if method == string POST begin set form = call CookerCreationForm POST if call is_valid begin set user = save set profile = call create user=user comment log the user in call login request user return call redirect string recipes:homepage end end else begin set form = call CookerCreat...
def signup_view(request): if request.method == 'POST': form = CookerCreationForm(request.POST) if form.is_valid(): user = form.save() user.profile = CookerProfile.objects.create(user=user) # log the user in login(request, user) return redir...
Python
nomic_cornstack_python_v1
function dataio_prepare hparams tokenizer begin comment 1. Define datasets set data_folder = hparams at string data_folder set train_data = call from_csv csv_path=hparams at string train_csv replacements=dict string data_root data_folder if hparams at string sorting == string ascending begin comment we sort training da...
def dataio_prepare(hparams, tokenizer): # 1. Define datasets data_folder = hparams["data_folder"] train_data = sb.dataio.dataset.DynamicItemDataset.from_csv( csv_path=hparams["train_csv"], replacements={"data_root": data_folder}, ) if hparams["sorting"] == "ascending": # we sort t...
Python
nomic_cornstack_python_v1
function Pwin state begin comment Assumes opponent also plays with optimal strategy. set tuple p me you pending = state if me + pending >= goal begin return 1 end else if you >= goal begin return 0 end else begin return max generator expression call Q_pig state action Pwin for action in call pig_actions state end end f...
def Pwin(state): # Assumes opponent also plays with optimal strategy. (p, me, you, pending) = state if me + pending >= goal: return 1 elif you >= goal: return 0 else: return max(Q_pig(state, action, Pwin) for action in pig_actions(state))
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 string Build and test a logistic regression model import os from pathlib import Path from sys import argv import mlflow as mlf import numpy as np import pandas as pd from sklearn import linear_model , metrics , model_selection if __name__ == string __main__ begin set dat_in_pth = call reso...
#!/usr/bin/env python3 """Build and test a logistic regression model""" import os from pathlib import Path from sys import argv import mlflow as mlf import numpy as np import pandas as pd from sklearn import linear_model, metrics, model_selection if __name__ == "__main__": dat_in_pth = Path("data/features.pkl")....
Python
zaydzuhri_stack_edu_python
from pyspark.sql import SparkSession from pyspark.sql.types import * from pyspark.sql.functions import * if __name__ == string __main__ begin set spark = call getOrCreate set temperatureSchema = call StructType list call StructField string stationID call StringType true call StructField string date call IntegerType tru...
from pyspark.sql import SparkSession from pyspark.sql.types import * from pyspark.sql.functions import * if __name__ == "__main__": spark = SparkSession.builder \ .master("local") \ .appName("sparkSQL") \ .getOrCreate() temperatureSchema = StructType( [ StructField(...
Python
zaydzuhri_stack_edu_python
comment Finds all triples of positive integers (i, j, k) such that comment i, j and k are two digit numbers, i < j < k, comment every digit occurs at most once in i, j and k, comment and the product of i, j and k is a 6-digit number comment consisting precisely of the digits that occur in i, j and k. comment If i, j an...
# Finds all triples of positive integers (i, j, k) such that # i, j and k are two digit numbers, i < j < k, # every digit occurs at most once in i, j and k, # and the product of i, j and k is a 6-digit number # consisting precisely of the digits that occur in i, j and k. # If i, j and k are numbers in the rang...
Python
zaydzuhri_stack_edu_python
for num in list begin if num < 5 begin append newList num end end print newList set secList = list set n = integer input string enter any number for num in list begin if num < n begin append secList num end end print secList
for num in list: if num<5: newList.append(num) print(newList) secList=[] n = int(input("enter any number")) for num in list: if num<n: secList.append(num) print(secList)
Python
zaydzuhri_stack_edu_python
for i in A begin for ii in i begin print string + string ii + string end=string end print string end print string ] print string 5. set cur = 0 for i in A begin set i at cur = i at cur + 2 set cur = cur + 1 end print string [ for i in A begin print string + string i end print string ]
for i in A: for ii in i: print("\t"+str(ii)+" ",end="") print("") print("]") print("5.") cur = 0 for i in A: i[cur] += 2 cur += 1 print("[") for i in A: print("\t"+str(i)) print("]")
Python
zaydzuhri_stack_edu_python
function test_multilingual_config begin set lang_configs = dict string en dict string processors string tokenize call run_multilingual_pipeline en_has_dependencies=false lang_configs=lang_configs end function
def test_multilingual_config(): lang_configs = { "en": {"processors": "tokenize"} } run_multilingual_pipeline(en_has_dependencies=False, lang_configs=lang_configs)
Python
nomic_cornstack_python_v1
comment Math Functions import math
# Math Functions import math
Python
zaydzuhri_stack_edu_python
string 베이즈 정리(Bayes' Theorem) P(A|B) = P(A,B) / P(B) = P(B,A) / P(B) = P(B|A)P(A) / P(B) = P(B|A)P(A) / [P(B,A) + P(B,~A)] 10,000명 중에 1명이 걸리는 질병(Disease): P(질병에 걸릴 확률) = P(D) = 1/10,000 = 0.0001 = 0.01% P(질병에 걸리지 않을 확률) = P(~D) = 9,999/10,000 = 99.99% 질병을 판단하는 검사(Test) 정확도 99%: P(질병에 걸린 사람을 정확하게 판별) = P(T|D) = 0.99 P(질...
""" 베이즈 정리(Bayes' Theorem) P(A|B) = P(A,B) / P(B) = P(B,A) / P(B) = P(B|A)P(A) / P(B) = P(B|A)P(A) / [P(B,A) + P(B,~A)] 10,000명 중에 1명이 걸리는 질병(Disease): P(질병에 걸릴 확률) = P(D) = 1/10,000 = 0.0001 = 0.01% P(질병에 걸리지 않을 확률) = P(~D) = 9,999/10,000 = 99.99% 질병을 판단하는 검사(Test) 정확도 99%: ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding:utf-8 -*- from app import app import time from datetime import datetime from random import randint function count_fib n begin if n in tuple 0 1 begin return n end return call count_fib n - 1 + call count_fib n - 2 end function decorator task function fib num begin set sta...
#!/usr/bin/env python # -*- coding:utf-8 -*- from .app import app import time from datetime import datetime from random import randint def count_fib(n): if n in (0, 1): return n return count_fib(n - 1) + count_fib(n - 2) @app.task def fib(num): start = datetime.now() time.sleep(randint(1, 5)...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Mon Jul 19 22:22:47 2021 @author: hienpham class Solution begin function canJump self nums begin set left = 0 set right = nums at 0 while right < length nums - 1 begin set possible_jumps = list comprehension i + nums at i for i in range left ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Jul 19 22:22:47 2021 @author: hienpham """ class Solution: def canJump(self, nums: List[int]) -> bool: left = 0 right = nums[0] while right < len(nums) - 1: possible_jumps = [i + nums[i] for i in range(le...
Python
zaydzuhri_stack_edu_python
function cancel_request_by_email email begin set req = call get_request_by_email email if not req begin return false end set is_complete = true return true end function
def cancel_request_by_email(email): req = get_request_by_email(email) if not req: return False req.is_complete = True return True
Python
nomic_cornstack_python_v1
function id self begin return get pulumi self string id end function
def id(self) -> str: return pulumi.get(self, "id")
Python
nomic_cornstack_python_v1
function process self content begin return tuple content string end function
def process(self, content): return content, ''
Python
nomic_cornstack_python_v1
function setPolicy self p begin set policy = p end function
def setPolicy(self, p): self.policy = p
Python
nomic_cornstack_python_v1
import sys set curr_word = none set curr_count = 0 set d = dict class Counter extends dict begin function __missing__ self key begin return 0 end function end class set c = counter for line in stdin begin set tuple count word = split line string set word = replace word string string set count = integer count if word ...
import sys curr_word = None curr_count = 0 d = {} class Counter(dict): def __missing__(self, key): return 0 c = Counter() for line in sys.stdin: count, word = line.split('\t') word = word.replace('\n', '') count = int(count) if word == curr_word: curr_count += count else: ...
Python
zaydzuhri_stack_edu_python
import numpy as np import OrbitUtils as orbut import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import scipy as sp import scipy.integrate as spi import datetime as dt import julianDay as jd import cartopy.crs as ccrs from cartopy.feature.nightshade import Nightshade from cartopy.mpl.ticker import ...
import numpy as np import OrbitUtils as orbut import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import scipy as sp import scipy.integrate as spi import datetime as dt import julianDay as jd import cartopy.crs as ccrs from cartopy.feature.nightshade import Nightshade from cartopy.mpl.ticker import ...
Python
zaydzuhri_stack_edu_python
import numpy as np from math import sqrt from collections import Counter function kNN_classify k X_train y_train x begin assert 1 <= k <= shape at 0 msg string k must be valid assert shape at 0 == shape at 0 msg string the size of X_train must equal to the size of y_train assert shape at 1 == shape at 0 msg string the ...
import numpy as np from math import sqrt from collections import Counter def kNN_classify(k, X_train, y_train, x): assert 1 <= k <= X_train.shape[0], "k must be valid" assert X_train.shape[0] == y_train.shape[0], "the size of X_train must equal to the size of y_train" assert X_train.shape[1] == x.shape[0...
Python
zaydzuhri_stack_edu_python
function get_code_lines self begin set currentText = call text set splitText = split currentText string set codeLines = list set codeFlag = false set count = - 1 for line in splitText begin set count = count + 1 if codeFlag == true begin append codeLines count end if search string ^<<|\@ string %s % line begin set cod...
def get_code_lines(self): currentText = self.parent.text() splitText = currentText.split("\n") codeLines = [] codeFlag = False count = -1 for line in splitText: count += 1 if codeFlag == True: codeLines.append(count) if...
Python
nomic_cornstack_python_v1
function _on_show_config_action self event begin log string Fetching { _config_path } if not call can_connect begin call fail string Container not ready end try begin set content = call pull _config_path comment juju requires keys to be lowercase alphanumeric (can't use self._config_path) call set_results dict string p...
def _on_show_config_action(self, event: ActionEvent): event.log(f"Fetching {self._config_path}") if not self.container.can_connect(): event.fail("Container not ready") try: content = self.container.pull(self._config_path) # juju requires keys to be lowercase ...
Python
nomic_cornstack_python_v1
import pandas as pd from VCU_LSTM_class import VCU_LSTM import os function create_model file epochs=5 begin set dataframe = read csv file set LSTM_model = call VCU_LSTM dataframe call create_autoencoder_model call model_compile epochs=epochs call model_predict_train call model_predict_test return LSTM_model end functio...
import pandas as pd from VCU_LSTM_class import VCU_LSTM import os def create_model(file, epochs=5): dataframe = pd.read_csv(file) LSTM_model = VCU_LSTM(dataframe) LSTM_model.create_autoencoder_model() LSTM_model.model_compile(epochs=epochs) LSTM_model.model_predict_train() LSTM_mo...
Python
zaydzuhri_stack_edu_python
function SetComment self comment begin set callResult = call _Call string SetComment comment end function
def SetComment(self, comment): callResult = self._Call("SetComment", comment)
Python
nomic_cornstack_python_v1
import math import matplotlib.pyplot as plt function proterm i value x begin set pro = 1 for j in range i begin set pro = pro * value - x at j end return pro end function comment Function for calculating comment divided difference table function dividedDiffTable x y n begin for i in range 1 n begin for j in range n - i...
import math import matplotlib.pyplot as plt def proterm(i, value, x): pro = 1 for j in range(i): pro = pro * (value - x[j]) return pro # Function for calculating # divided difference table def dividedDiffTable(x, y, n): for i in range(1, n): for j in range(n - i): y[j][...
Python
zaydzuhri_stack_edu_python
function move_folder self url path folder targ dst begin set targ = call adjust_path targ set dst = call adjust_path dst comment print('\n m365 spo folder move -o json -u {0} -s {1} -t {2}'.format(url, path + '/' + folder, '/' + targ + '/' + dst + '/')) comment return emulated_result_1 set result = run list string m365...
def move_folder(self, url, path, folder, targ, dst): targ = self.adjust_path(targ) dst = self.adjust_path(dst) # print('\n m365 spo folder move -o json -u {0} -s {1} -t {2}'.format(url, path + '/' + folder, '/' + targ + '/' + dst + '/')) # return emulated_result_1 result = (subp...
Python
nomic_cornstack_python_v1
function write self path=none begin if path is none begin set path = filepath end with open path string w as f begin write f format string {} comment write f format string {} scaling_factor for row in coordinate_matrix begin set row = format string {:.6f} {:.6f} {:.6f} row at 0 row at 1 row at 2 write f format string {...
def write(self, path: Optional[str] = None) -> None: if path is None: path = self.filepath with open(path, "w") as f: f.write("{}\n".format(self.comment)) f.write("\t{}\n".format(self.scaling_factor)) for row in self.simulation_cell.coordinate_matrix: ...
Python
nomic_cornstack_python_v1
function create_or_edit_issue request pk=none begin set issue = if expression pk then call get_object_or_404 Issue pk=pk else none if method == string POST begin set form = call IssueForm POST FILES instance=issue if call is_valid begin set issue = save set author = user save return call redirect single_issue pk end en...
def create_or_edit_issue(request, pk=None): issue = get_object_or_404(Issue, pk=pk) if pk else None if request.method == "POST": form = IssueForm(request.POST, request.FILES, instance=issue) if form.is_valid(): issue = form.save() issue.author = request.user i...
Python
nomic_cornstack_python_v1
comment BFS comment Time and space O(mn) class Solution begin function hasPath self maze start destination begin if not maze begin return false end set tuple m n = tuple length maze length maze at 0 function wall r c begin if r < 0 or c < 0 or r >= m or c >= n begin return true end else begin return maze at r at c end ...
# BFS # Time and space O(mn) class Solution: def hasPath(self, maze: List[List[int]], start: List[int], destination: List[int]) -> bool: if (not maze): return False m, n = len(maze), len(maze[0]) def wall(r, c): if (r < 0 or c < 0 or r >= m or c >= n): return True el...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin python comment coding=utf-8 string @Create_date: 2017-08-01 @Author: tangcheng @Email: tangcheng@cstech.ltd @description: 操作数据库 Copyright (c) 2017 HangZhou CSTech.Ltd. All rights reserved. import logging import psycopg2 import psycopg2.extras import config function sql_query sql binds=tuple begin stri...
#!/usr/bin python # coding=utf-8 """ @Create_date: 2017-08-01 @Author: tangcheng @Email: tangcheng@cstech.ltd @description: 操作数据库 Copyright (c) 2017 HangZhou CSTech.Ltd. All rights reserved. """ import logging import psycopg2 import psycopg2.extras import config def sql_query(sql, binds=()): """ 执行一条SQL语句 ...
Python
zaydzuhri_stack_edu_python
from DataStructures import FenwickTree from DataStructures import FenwickTreeMin from DataStructures import FenwickTree2D from DataStructures import FenwickTree2DMin import operator function fenwicktree_test begin set a = list 1 2 3 4 5 comment operation sum set bit = call from_list a add assert call get_range 0 4 == 1...
from DataStructures import FenwickTree from DataStructures import FenwickTreeMin from DataStructures import FenwickTree2D from DataStructures import FenwickTree2DMin import operator def fenwicktree_test(): a = [1, 2, 3, 4, 5] # operation sum bit = FenwickTree.from_list(a, operator.add) assert bit.get_r...
Python
zaydzuhri_stack_edu_python
function sleep seconds begin comment After load and initializing the PvAPI Python's built-in 'sleep' function comment stops working (returns too early). The is a replacement. from time import sleep , time set t = time set t0 = time while t < t0 + seconds begin sleep t0 + seconds - t set t = time end end function
def sleep(seconds): # After load and initializing the PvAPI Python's built-in 'sleep' function # stops working (returns too early). The is a replacement. from time import sleep,time t = t0 = time() while t < t0+seconds: sleep(t0+seconds - t); t = time()
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python2 comment -*- coding: utf-8 -*- string Created on Thu Jan 10 01:16:58 2019 @author: pi import RPi.GPIO as GPIO import time set blight = 25 set glight = 8 set rlight = 7 call setmode BCM setup GPIO rlight OUT setup GPIO glight OUT setup GPIO blight OUT while true begin call output rlight true...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Thu Jan 10 01:16:58 2019 @author: pi """ import RPi.GPIO as GPIO import time blight =25 glight =8 rlight =7 GPIO.setmode(GPIO.BCM) GPIO.setup(rlight,GPIO.OUT) GPIO.setup(glight,GPIO.OUT) GPIO.setup(blight,GPIO.OUT) while True: GPIO.output(rlight,T...
Python
zaydzuhri_stack_edu_python
string Testing Poisson problem implementations from Freund, Sternberg 'On weakly imposed boundary conditions for second order problem', 1995 Convergence study on unit circle. Mixed bcs are considered; u = u_exact on \Gamma_D grad(u).n = flux_exact on \Gamma_N from collections import namedtuple import matplotlib.pyplot ...
''' Testing Poisson problem implementations from Freund, Sternberg 'On weakly imposed boundary conditions for second order problem', 1995 Convergence study on unit circle. Mixed bcs are considered; u = u_exact on \Gamma_D grad(u).n = flux_exact on \Gamma_N ''' from collec...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 string The Lotka-Volterra model with prey density-dependance incorporated set __appname__ = string LV2.py set __author__ = string Jacob Griffiths (jacob.griffiths18@imperial.ac.uk) set __version__ = string 0.0.1 comment The Lokta-Volterra model ### import scipy.integrate as integrate impor...
#!/usr/bin/env python3 """ The Lotka-Volterra model with prey density-dependance incorporated """ __appname__ = 'LV2.py' __author__ = 'Jacob Griffiths (jacob.griffiths18@imperial.ac.uk)' __version__ = '0.0.1' ### The Lokta-Volterra model ### import scipy.integrate as integrate import scipy as sc import sys import ...
Python
zaydzuhri_stack_edu_python
function retry_on_deadlock targets *args attempts=2 commit=false **kwargs begin if not is instance targets list begin set targets = list targets end set current_attempt = 0 while true begin try begin set last_result = none for target in targets begin if is instance target Executable or is instance target str begin exec...
def retry_on_deadlock(targets, *args, attempts=2, commit=False, **kwargs): if not isinstance(targets, list): targets = [ targets ] current_attempt = 0 while True: try: last_result = None for target in targets: if isinstance(target, Executable) or isi...
Python
nomic_cornstack_python_v1
set name = string Candice set newname = lower name print name newname comment can directly type in a string constant without defining it as a variable string first print lower string Hi there! My name is Candice.
name = 'Candice' newname = name.lower() print(name, newname) print('Hi there! My name is Candice.'.lower()) #can directly type in a string constant without defining it as a variable string first
Python
zaydzuhri_stack_edu_python
function run self *args **options begin set args = list comment Set bind ip/port if specified. if addr begin if DEV_APPSERVER_VERSION == 1 begin extend args list string --address addr end else begin extend args list string --host addr end end if port begin if DEV_APPSERVER_VERSION == 1 begin extend args list string --...
def run(self, *args, **options): args = [] # Set bind ip/port if specified. if self.addr: if settings.DEV_APPSERVER_VERSION == 1: args.extend(['--address', self.addr]) else: args.extend(['--host', self.addr]) if self.port: ...
Python
nomic_cornstack_python_v1
function spider_idle self begin comment XXX: Handle a sentinel to close the spider. print string spider_idle call schedule_next_requests raise DontCloseSpider end function
def spider_idle(self): # XXX: Handle a sentinel to close the spider. print('spider_idle') self.schedule_next_requests() raise DontCloseSpider
Python
nomic_cornstack_python_v1
function is_sorted arr begin set sorted_arr = sorted arr if arr == sorted_arr begin return true end else begin sort arr return arr end end function
def is_sorted(arr): sorted_arr = sorted(arr) if arr == sorted_arr: return True else: arr.sort() return arr
Python
jtatman_500k
function generate_slug cls raw_string begin if not has attribute cls string slug begin return none end set slug = call slugify raw_string set obj = get attribute cls string slug set model = first call order_by call desc if model begin set idx_slug = split slug string - at - 1 if is digit idx_slug begin set idx_new = in...
def generate_slug(cls, raw_string): if not hasattr(cls, 'slug'): return None slug = slugify(raw_string) obj = getattr(cls, 'slug') model = cls.query.filter(obj.startswith(slug)).order_by(obj.desc()).first() if model: idx_slug = model.slug.split('-')[-1] if idx_slug.isdigit(): idx_new = int(idx_slug) + 1 ...
Python
nomic_cornstack_python_v1
function loadData self fileName crystalSym cOverA dataType=none begin if dataType is none begin set dataType = string OxfordBinary end set dataLoader = call EBSDDataLoader if dataType == string OxfordBinary begin set metadataDict = call loadOxfordCPR fileName set dataDict = call loadOxfordCRC fileName end else if dataT...
def loadData(self, fileName, crystalSym, cOverA, dataType=None): if dataType is None: dataType = "OxfordBinary" dataLoader = EBSDDataLoader() if dataType == "OxfordBinary": metadataDict = dataLoader.loadOxfordCPR(fileName) dataDict = dataLoader.loadOxfordCRC(...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment 发送附件 string 如果Email中要加上附件怎么办?带附件的邮件可以看做包含若干部分的邮件:文本和各个附件本身,所以,可以构造一个MIMEMultipart对象代表邮件本身,然后往里面加上一个MIMEText作为邮件正文,再继续往里面加上表示附件的MIMEBase对象即可: from email import encoders from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr , formatadd...
#-*- coding: utf-8 -*- #发送附件 ''' 如果Email中要加上附件怎么办?带附件的邮件可以看做包含若干部分的邮件:文本和各个附件本身,所以,可以构造一个MIMEMultipart对象代表邮件本身,然后往里面加上一个MIMEText作为邮件正文,再继续往里面加上表示附件的MIMEBase对象即可: ''' from email import encoders from email.header import Header from email.mime.text import MIMEText from email.utils import parseaddr, formataddr fro...
Python
zaydzuhri_stack_edu_python
function init_time_to_text begin with open base_directory + string textclock_timetext_DE-de.csv encoding=string utf-8 as f begin for line in f begin set line = replace line string string set tuple key val = split line string , set dict_time_to_text at key = val end end end function
def init_time_to_text(): with open(base_directory + "textclock_timetext_DE-de.csv", encoding="utf-8") as f: for line in f: line = line.replace("\n", "") (key,val) = line.split(",") dict_time_to_text[key] = val
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- comment python 3.5.2 with Anaconda3 4.2.0 import glob import numpy as np import cv2 comment 'pip install bhtsne' import bhtsne from Common.common import flatten , c_cycle function reshape_1dim img_paths size=tuple 128 128 begin comment map ( read image → resize image → transform 1dim from ...
# -*- coding: utf-8 -*- # python 3.5.2 with Anaconda3 4.2.0 import glob import numpy as np import cv2 import bhtsne # 'pip install bhtsne' from Common.common import flatten, c_cycle def reshape_1dim(img_paths, size=(128, 128)): # map ( read image → resize image → transform 1dim from images, [pathA, pathB, path...
Python
zaydzuhri_stack_edu_python
function posts_list request begin set posts = all return call SerializeOrRender string blog/posts_list.html dict string posts posts end function
def posts_list(request): posts = Post.objects.all() return SerializeOrRender('blog/posts_list.html', { 'posts': posts })
Python
nomic_cornstack_python_v1
comment from rangdomlist import randomlist comment #冒泡排序 comment def mp(nums): comment for i in range(len(nums)-1): comment print('第%s轮结果'%i,nums) comment for j in range(len(nums)-1-i): comment if nums[j] > nums[j+1]: comment nums[j],nums[j+1] = nums[j+1],nums[j] comment return nums comment #选择排序 comment def xp(nums): ...
# from rangdomlist import randomlist # # # # #冒泡排序 # def mp(nums): # for i in range(len(nums)-1): # print('第%s轮结果'%i,nums) # for j in range(len(nums)-1-i): # if nums[j] > nums[j+1]: # nums[j],nums[j+1] = nums[j+1],nums[j] # return nums # # # #选择排序 # def xp(nums): # ...
Python
zaydzuhri_stack_edu_python
class Solution begin function average self salary begin set minn = 10 ^ 7 set maxx = 10 set Total = 0 for s in salary begin if s > maxx begin set maxx = s end if s < minn begin set minn = s end set Total = Total + s end set Total = Total - minn - maxx return Total / length salary - 2 end function end class
class Solution: def average(self, salary: List[int]) -> float: minn = 10**7 maxx = 10 Total = 0 for s in salary: if s > maxx: maxx = s if s < minn: minn = s Total += s Total = Total-minn-maxx return T...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python # -*- coding: utf-8 -*- string File: ana.py Author: wyscjm Email: w079064@163.com Github: https://github.com/wyscjm Date: 2015-11-07 Ver: V0.1 Description: 1.分析文件链接 import os import re comment zhPattern = re.compile(u'[\u4e00-\u9fa5\+') function is_chinese uchar begin string 判断一个unicode是否是汉...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ File: ana.py Author: wyscjm Email: w079064@163.com Github: https://github.com/wyscjm Date: 2015-11-07 Ver: V0.1 Description: 1.分析文件链接 """ import os import re #zhPattern = re.compile(u'[\u4e00-\u9fa5\+') def is_chinese(uchar): """判断一个unicode是否是汉字""" ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment # Speed Dating comment ## Challenge description comment We will start a new data visualization and exploration project. Your goal will be to try to understand *love*! It's a very complicated subject so we've simplified it. Your goal is going to be to understand...
#!/usr/bin/env python # coding: utf-8 # # Speed Dating # # ## Challenge description # # We will start a new data visualization and exploration project. Your goal will be to try to understand *love*! It's a very complicated subject so we've simplified it. Your goal is going to be to understand what happens during a s...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment -*- coding: utf-8 -*- comment @Time : 2016/10/6 11:54 comment @Author : Hercwey comment @Site : comment @File : doc.py comment @Software: PyCharm string tutorial doc: https://github.com/faif/python-patterns/blob/master/README.md source codes: https://github.com/faif/python-patterns....
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2016/10/6 11:54 # @Author : Hercwey # @Site : # @File : doc.py # @Software: PyCharm """ tutorial doc: https://github.com/faif/python-patterns/blob/master/README.md source codes: https://github.com/faif/python-patterns.git Current Patterns: Creational ...
Python
zaydzuhri_stack_edu_python
from logging import debug from flask import Flask , render_template , request from flask_sqlalchemy import SQLAlchemy set app = call Flask __name__ set config at string SQLALCHEMY_DATABASE_URI = string mysql://root:password@localhost:3306/login set db = call SQLAlchemy app class Logs extends Model begin set sno = call ...
from logging import debug from flask import Flask,render_template,request from flask_sqlalchemy import SQLAlchemy app=Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI']='mysql://root:password@localhost:3306/login' db=SQLAlchemy(app) class Logs(db.Model): sno=db.Column(db.Integer,primary_key=True,autoincrement=...
Python
zaydzuhri_stack_edu_python
function output_header self begin write stderr string Generating output print string <!DOCTYPE html><html><head><base href="https://people.canonical.com/~ubuntu-security/cve/"><title>Security Issues</title> print string <link rel="StyleSheet" href="toplevel.css" type="text/css" /></head><body><table> print table_header...
def output_header(self): sys.stderr.write("Generating output\n") print("<!DOCTYPE html><html><head><base href=\"https://people.canonical.com/~ubuntu-security/cve/\"><title>Security Issues</title>"); print("<link rel=\"StyleSheet\" href=\"toplevel.css\" type=\"text/css\" /></head><body><table>")...
Python
nomic_cornstack_python_v1
function _kth_to_last_iterative self head k begin set node1 = head set node2 = none set flag = false set i = 0 while node1 is not none begin set i = i + 1 set node1 = next_node if flag begin set node2 = next_node end if i == k begin set flag = true set node2 = head end end return node2 end function
def _kth_to_last_iterative(self, head, k): # node1 = head node2 = None flag = False i = 0 while node1 is not None: i += 1 node1 = node1.next_node if flag: node2 = node2.next_node if i == k: fla...
Python
nomic_cornstack_python_v1
comment _*_coding=UTF-8_*_ comment copyright 2019 BILLAL FAUZAN comment Karya Anak Bangsa comment MD5 DENCRYPT Offline 90% string NOTE: Please Abang Eneng Jangan Ubah Source Code Ny Saya Susah Payah Membuat Program Ini Saya Sengaja Open Source Supaya Anak Indonesia Bisa Membuat Program Sendiri Jadi Jangan Di Recode Ban...
#_*_coding=UTF-8_*_ # copyright 2019 BILLAL FAUZAN # Karya Anak Bangsa # MD5 DENCRYPT Offline 90% """ NOTE: Please Abang Eneng Jangan Ubah Source Code Ny Saya Susah Payah Membuat Program Ini Saya Sengaja Open Source Supaya Anak Indonesia Bisa Membuat Program Sendiri Jadi Jangan Di Recode Bangsat!! """ __banner__...
Python
zaydzuhri_stack_edu_python
function _load_dependency cls tile dep family begin string Load a dependency from build/deps/<unique_id>. set depname = dep at string unique_id set depdir = join path folder string build string deps depname set deppath = join path depdir string module_settings.json if not exists path deppath begin raise call BuildError...
def _load_dependency(cls, tile, dep, family): """Load a dependency from build/deps/<unique_id>.""" depname = dep['unique_id'] depdir = os.path.join(tile.folder, 'build', 'deps', depname) deppath = os.path.join(depdir, 'module_settings.json') if not os.path.exists(deppath): ...
Python
jtatman_500k
class Solution begin function checkPerfectNumber self num begin string [summary] Parameters ---------- num : int [description] Returns ------- bool [description] if num <= 1 begin return false end set sum = 0 set i = 2 while i * i < num begin if num % i == 0 begin set sum = sum + i set sum = sum + num / i end set i = i...
class Solution: def checkPerfectNumber(self, num: int) -> bool: """[summary] Parameters ---------- num : int [description] Returns ------- bool [description] """ if (num <= 1): ...
Python
zaydzuhri_stack_edu_python