code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
import numpy as np import sys comment state, margin, swingable EC votes(ME-SW = maine state wide(CD assumed 1 R 1 D), NE-2 = Nebraska 2nd) set states = dict string MI tuple - 0.3 16 ; string WI tuple - 0.7 10 ; string NH tuple 0.3 4 ; string PA tuple - 0.7 20 ; string FL tuple - 1.2 29 ; string MN tuple 1.5 10 ; string...
import numpy as np import sys #state, margin, swingable EC votes(ME-SW = maine state wide(CD assumed 1 R 1 D), NE-2 = Nebraska 2nd) states = { "MI": (-0.3,16),"WI": (-.7,10), "NH": (0.3,4), "PA": (-0.7,20),"FL":(-1.2,29),"MN":(1.5,10), "NV": (2.4,6),"ME-SW":(2.9,2), "NE-2":(-2.3,1), "NC":(-3.7,15), "AZ":(-3.6,11)} sta...
Python
zaydzuhri_stack_edu_python
function export_docs fp app_name begin from otree.models import Session from otree.models import Participant from otree.views.admin import get_all_fields comment generate doct_dict set models_module = call get_models_module app_name set model_names = list string Participant string Player string Group string Subsession ...
def export_docs(fp, app_name): from otree.models import Session from otree.models import Participant from otree.views.admin import get_all_fields # generate doct_dict models_module = get_models_module(app_name) model_names = ["Participant", "Player", "Group", "Subsession", "Session"] line_...
Python
nomic_cornstack_python_v1
string RUN ON Windows with 100% on Scale and Layout settings Welcome to my coursework The beginning of the program is towards the bottom where the main menu is created. from booksearch import * from bookcheckout import * from bookreturn import * from booklist import * from tkinter import * import tkinter from matplotli...
'''RUN ON Windows with 100% on Scale and Layout settings Welcome to my coursework The beginning of the program is towards the bottom where the main menu is created.''' from booksearch import * from bookcheckout import * from bookreturn import * from booklist import * from tkinter import * import tkinter fro...
Python
zaydzuhri_stack_edu_python
import re function main begin set f = open string input.in string r set fout = open string output.out string w set lines = read lines f set L = integer split lines at 0 string at 0 set D = integer split lines at 0 string at 1 set N = integer split lines at 0 string at 2 set dic = list for word in lines at slice 1 : D ...
import re def main(): f = open('input.in','r') fout = open('output.out','w') lines = f.readlines() L=int(lines[0].split(' ')[0]) D=int(lines[0].split(' ')[1]) N=int(lines[0].split(' ')[2]) dic = [] for word in lines[1:D+1]: dic.append(word.strip('\n')) case = 1
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python3 comment -*- coding: utf-8 -*- string Created on Thu Oct 5 11:31:50 2017 1007 maximization the likelihood function, not search for the root of the gradient @author: zhang string newEvent: the list of event that to be calculated, eventAccInfo = [num of birth event, length of path], the accum...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Oct 5 11:31:50 2017 1007 maximization the likelihood function, not search for the root of the gradient @author: zhang """ ''' newEvent: the list of event that to be calculated, eventAccInfo = [num of birth event, length of path], the accumulated...
Python
zaydzuhri_stack_edu_python
function sum_natural_numbers n begin return n * n + 1 / 2 end function
def sum_natural_numbers(n): return (n * (n + 1)) / 2
Python
jtatman_500k
import sys import datetime import sqlite3 from sqlite3 import Error from collections import namedtuple set datos = tuple string fecha string Descripcion string Cantidad string Precio string total set switch = true set diccionario_ventas = dict set lista_ventas = list set Detalle = named tuple string venta tuple strin...
import sys import datetime import sqlite3 from sqlite3 import Error from collections import namedtuple datos =("fecha","Descripcion", "Cantidad", "Precio", "total") switch = True diccionario_ventas={} lista_ventas=[] Detalle = namedtuple("venta", ("fecha","Descripcion", "Cantidad", "Precio", "total")) total2= 0 i=0 ...
Python
zaydzuhri_stack_edu_python
function test_get_request_invoke_render_with_form_object self begin set mock_render = start patch string identity.views.DeleteProjectView.get_context_data set fake_resource = call FakeResource set return_value = fake_resource set _ = view self request set computed_form = get call_args at 1 string form assert equal fake...
def test_get_request_invoke_render_with_form_object(self): mock_render = patch( 'identity.views.DeleteProjectView.get_context_data').start() fake_resource = FakeResource() self.form.return_value = fake_resource _ = self.view(self.request) computed_form = mock_rende...
Python
nomic_cornstack_python_v1
function _parse_comments reader begin set regex = string \s*(#|\/{2}).*$ set regex_inline = string (:?(?:\s)*([A-Za-z\d\.{}]*)|((?<=\").*\"),?)(?:\s)*(((#|(\/{2})).*)|)$ set pipe = list for line in reader begin if search regex line begin if search string ^ + regex line IGNORECASE begin continue end else if search rege...
def _parse_comments(reader): regex = r'\s*(#|\/{2}).*$' regex_inline = r'(:?(?:\s)*([A-Za-z\d\.{}]*)|((?<=\").*\"),?)(?:\s)*(((#|(\/{2})).*)|)$' pipe = [] for line in reader: if re.search(regex, line): if re.search(r'^' + regex, line, re.IGNORECASE): continue...
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string Created on Fri Apr 17 12:48:13 2020 @author: zenit Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are ...
# -*- coding: utf-8 -*- """ Created on Fri Apr 17 12:48:13 2020 @author: zenit Given a 2d grid map of '1's (land) and '0's (water), count the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid...
Python
zaydzuhri_stack_edu_python
function _generateFileFromProb filename numRecords categoryList initProb firstOrderProb secondOrderProb seqLen numNoise=0 resetsEvery=none begin string Generate a set of records reflecting a set of probabilities. Parameters: ---------------------------------------------------------------- filename: name of .csv file to...
def _generateFileFromProb(filename, numRecords, categoryList, initProb, firstOrderProb, secondOrderProb, seqLen, numNoise=0, resetsEvery=None): """ Generate a set of records reflecting a set of probabilities. Parameters: ---------------------------------------------------------------- filename: ...
Python
jtatman_500k
function unsubscribe self begin return call _execute_command string unsubscribe end function
def unsubscribe(self) -> Result[None]: return self._execute_command('unsubscribe')
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python comment _*_ coding:utf-8 _*_ import functools import socket import threading from queue import Queue from scaninfo import ScanInfo set print = partial print end=string function _tcpConnect IP=none PORT=none begin string tcpConnect 用于扫描开放端口,采用的方法是通过向目标IP和PORT发送TCP CONNECT链接,链接成功则返回1,不成功则继续进行...
#!/usr/bin/env python # _*_ coding:utf-8 _*_ import functools import socket import threading from queue import Queue from scaninfo import ScanInfo print = functools.partial(print, end='') def _tcpConnect(IP=None, PORT=None): ''' tcpConnect 用于扫描开放端口,采用的方法是通过向目标IP和PORT发送TCP CONNECT链接,链接...
Python
zaydzuhri_stack_edu_python
function is_valid_provider provider begin comment Check in the case enable Login using Facebook if call is_facebook_provider provider and FACEBOOK_LOGIN_ENABLED begin return true end comment Check in the case enable Login using Google if call is_google_provider provider and GOOGLE_LOGIN_ENABLED begin return true end re...
def is_valid_provider(provider): # Check in the case enable Login using Facebook if is_facebook_provider(provider) and drfr_settings.FACEBOOK_LOGIN_ENABLED: return True # Check in the case enable Login using Google if is_google_provider(provider) and drfr_settings.GOOGLE_LOGIN_ENABLED: ...
Python
nomic_cornstack_python_v1
import random from Card import Card set suits = tuple string Hearts string Diamonds string Spades string Clubs set ranks = tuple string Two string Three string Four string Five string Six string Seven string Eight string Nine string Ten string Jack string Queen string King string Ace set values = dict string Two 2 ; st...
import random from Card import Card suits= ("Hearts", "Diamonds", "Spades", "Clubs") ranks = ("Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace") values = {"Two": 2, "Three": 3, "Four":4, "Five":5, "Six":6, "Seven":7, "Eight":8, "Nine":9, "Ten":10, "Jack":11, "Queen":...
Python
zaydzuhri_stack_edu_python
import torchvision import numpy as np from PIL import Image import mmcv function xyxy2xywh bbox_xyxy begin string Transform the bbox format from x1y1x2y2 to xywh. Args: bbox_xyxy (np.ndarray): Bounding boxes (with scores), shaped (n, 4) or (n, 5). (left, top, right, bottom, [score]) Returns: np.ndarray: Bounding boxes ...
import torchvision import numpy as np from PIL import Image import mmcv def xyxy2xywh(bbox_xyxy): """Transform the bbox format from x1y1x2y2 to xywh. Args: bbox_xyxy (np.ndarray): Bounding boxes (with scores), shaped (n, 4) or (n, 5). (left, top, right, bottom, [score]) Returns: ...
Python
zaydzuhri_stack_edu_python
function getSnapshots self begin set cmd = list string serviced string snapshot string list set results = call command cmd if results begin if results at 0 begin set snapshots = split results at 0 end else if string no snapshots found in results at 1 begin set snapshots = list end else begin print results at 1 set sna...
def getSnapshots(self): cmd = ["serviced", "snapshot", "list"] results = self.command(cmd) if results: if results[0]: snapshots = results[0].split() else: if "no snapshots found" in results[1]: snapshots = [] ...
Python
nomic_cornstack_python_v1
function test_tpredic_with_pandas_dates begin try begin import pandas as pd set dt = time delta hours=1 set dr = call date_range string 2001-01-01 string 2001-01-02 freq=dt debug dr set dl = call asarray list dr set const_names = call asarray list encode string M2 set const_freqs = call asarray list m2_freq / pi * 2 se...
def test_tpredic_with_pandas_dates(): try: import pandas as pd dt = timedelta(hours=1) dr = pd.date_range("2001-01-01", "2001-01-02", freq=dt) logger.debug(dr) dl = np.asarray(list(dr)) const_names = np.asarray(["M2 ".encode(),]) const_freqs = np.asarray([bm...
Python
nomic_cornstack_python_v1
function startJob self begin info string STARTING job with args %r % args set pid = call fork if pid == 0 begin comment Redirect the stdout output to dev null in the child. set logPath = args at string resourcePrefix + args at string path + args at string filename + string _log.txt set logFile = open logPath string wb ...
def startJob(self): logging.info("STARTING job with args %r" % self.args) self.pid = os.fork() if self.pid == 0: # Redirect the stdout output to dev null in the child. logPath = self.args['resourcePrefix'] + self.args['path'] + self.args['filename'] + '_log.txt' ...
Python
nomic_cornstack_python_v1
import numpy as np comment Define the function function f x begin return 3 * x ^ 2 + 2 * x - 10 end function function grad_f x begin return 6 * x + 2 end function comment Gradient Descent set x_old = 0 comment Arbitrary initial value set x_new = 4 comment Stop criteria set epsilon = 0.01 set precision = 1e-05 comment M...
import numpy as np # Define the function def f(x): return (3 * (x**2)) + (2 * x) - 10 def grad_f(x): return (6 * x) + 2 # Gradient Descent x_old = 0 x_new = 4 # Arbitrary initial value epsilon = 0.01 # Stop criteria precision = 0.00001 max_iters = 1000 # Maximum number of iterations iters = 0 while abs(x_n...
Python
jtatman_500k
comment 19. Uma escola com cursos em regime semestral, realiza duas avaliações durante o semestre e calcula a média do aluno, comment da seguinte maneira: comment MEDIA = (P1 + 2.P2) / 3 comment Fazer um programa para entrar via teclado com os valores das notas (P1 e P2) e calcular a média. comment Exibir a situação fi...
#19. Uma escola com cursos em regime semestral, realiza duas avaliações durante o semestre e calcula a média do aluno, # da seguinte maneira: #MEDIA = (P1 + 2.P2) / 3 #Fazer um programa para entrar via teclado com os valores das notas (P1 e P2) e calcular a média. # Exibir a situação final do aluno (“Aprovado ou Reprov...
Python
zaydzuhri_stack_edu_python
function run *args begin run join string args shell=true check=true end function
def run(*args): subprocess.run(' '.join(args), shell=True, check=True)
Python
nomic_cornstack_python_v1
class Parrot begin comment class attribute set species = string bird comment instance attribute function __init__ self name age begin set name = name set age = age end function end class comment instantiate the Parrot class set blu = call Parrot string Blu 10 set woo = call Parrot string Woo 15 comment access the class...
class Parrot: # class attribute species = "bird" # instance attribute def __init__(self, name, age): self.name = name self.age = age # instantiate the Parrot class blu = Parrot("Blu", 10) woo = Parrot("Woo", 15) # access the class attributes print("Blu is a {}".format(...
Python
zaydzuhri_stack_edu_python
function my_color_function field begin if field > 100000000 begin return string #ff0000 end else begin return string #008000 end end function
def my_color_function(field): if field > 100000000: return "#ff0000" else: return "#008000"
Python
nomic_cornstack_python_v1
function training2 self epochs=300 num_batches=320 learn_rate=0.1 load_data=true pickle_rbm=true begin if trained2 begin print string This RBM already completed Training 2. end else if not trained1 begin print string Please complete Training 1 with this RBM before starting Training 2. end else if not added_classif begi...
def training2(self, epochs=300, num_batches=320, learn_rate=0.1, load_data=True, pickle_rbm=True): if self.trained2: print("This RBM already completed Training 2.") elif not self.trained1: print("Please complete Training 1 with this RBM before starting Training 2.") elif...
Python
nomic_cornstack_python_v1
function docLines self begin set tuple summary description = call _getDocParts if description begin return summary + list string + description end return summary end function
def docLines(self): summary, description = self._getDocParts() if description: return summary + [""] + description return summary
Python
nomic_cornstack_python_v1
function get_gcs_store self begin from cedar.stores.gcs import GCSStore set cfg = get self string gcs dict set store = call from_credentials keyword kwds return store end function
def get_gcs_store(self): from cedar.stores.gcs import GCSStore cfg = self.get('gcs', {}) store = GCS.from_credentials(**kwds) return store
Python
nomic_cornstack_python_v1
import random set oper_num = random integer 1 10 if oper_num == 1 or oper_num == 6 begin print 300 + 50 end else if oper_num == 2 or oper_num == 7 begin print 300 - 50 end else if oper_num == 3 or oper_num == 8 begin print 300 * 50 end else if oper_num == 4 or oper_num == 9 begin print 300 / 50 end else begin print 300...
import random oper_num=random.randint(1,10) if oper_num==1 or oper_num==6: print(300+50) elif oper_num==2 or oper_num==7: print(300-50) elif oper_num==3 or oper_num==8: print(300*50) elif oper_num==4 or oper_num==9: print(300/50) else: print(300%50) print("결과값 :",oper_num)
Python
zaydzuhri_stack_edu_python
function run_once self begin string Execute the worker once. This method will return after a file change is detected. call _capture_signals call _start_monitor try begin call _run_worker end except KeyboardInterrupt begin return end finally begin call _stop_monitor call _restore_signals end end function
def run_once(self): """ Execute the worker once. This method will return after a file change is detected. """ self._capture_signals() self._start_monitor() try: self._run_worker() except KeyboardInterrupt: return finally: ...
Python
jtatman_500k
function hidden_size self begin return call get_hidden_size end function
def hidden_size(self): return self._internal.get_hidden_size()
Python
nomic_cornstack_python_v1
comment Given a string, create a PALINDRONE for that word set str = string Are we not drawn onward, we few, drawn onward to new era? function reverse str begin comment Given a string, reverse it return join string reversed str end function print string The following is a palindrone : str print string After reversing i...
# Given a string, create a PALINDRONE for that word str = 'Are we not drawn onward, we few, drawn onward to new era?' def reverse(str): # Given a string, reverse it return "".join(reversed(str)) print("The following is a palindrone : ", str) print("After reversing it, it it still a palindron : ",reverse(str....
Python
zaydzuhri_stack_edu_python
comment years = int(user_age) set months = user_age * 12 set seconds = months * 30 * 24 * 60 * 60 print string Your age, { user_age } , is equal to { months } months. print string Your age, { user_age } , is equal to { seconds } seconds.
# years = int(user_age) months = user_age * 12 seconds = months * 30 * 24 * 60 * 60 print(f"Your age, {user_age}, is equal to {months} months.") print(f"Your age, {user_age}, is equal to {seconds} seconds.")
Python
zaydzuhri_stack_edu_python
comment Task 2 comment 2. Написать программу, со следующим интерфейсом: пользователю предоставляется на comment выбор 12 вариантов перевода(описанных в первой задаче). Пользователь вводит цифру comment от одного до двенадцати. После программа запрашивает ввести численное значение. comment Затем программа выдает конверт...
# Task 2 # 2. Написать программу, со следующим интерфейсом: пользователю предоставляется на # выбор 12 вариантов перевода(описанных в первой задаче). Пользователь вводит цифру # от одного до двенадцати. После программа запрашивает ввести численное значение. # Затем программа выдает конвертированный результат. Использов...
Python
zaydzuhri_stack_edu_python
function get_ages_local begin set result = dict 0 list 0 7 / 365.25 ; 0.01 list 7 / 365.25 28 / 365.25 ; 0.1 list 28 / 365.25 1 ; 1 list 1 5 for i in range 5 91 5 begin set result at i = list i i + 5 end set result at 95 = list 95 100 return result end function
def get_ages_local(): result = {0:[0,7/365.25], .01:[7/365.25,28/365.25], .1:[28/365.25,1], 1:[1,5]} for i in range(5,91,5): result[i] = [i,i+5] result[95] = [95,100] return result
Python
nomic_cornstack_python_v1
function host self value begin set _properties at string host = value end function
def host(self, value: str): self._properties["host"] = value
Python
nomic_cornstack_python_v1
function make_oscfun freq_osc freq tstop dt begin set t = array range 0 tstop dt set r = zeros size np t set amp = tstop * freq / 1000 / - 1 / 2 * pi * freq_osc / 1000 * sin 2 * pi * freq_osc / 1000 * tstop + tstop comment E_t[n_spikes] = integral_t(r(t)*1) --> solve for the amplitude (n_spikes is given by the period t...
def make_oscfun(freq_osc, freq, tstop, dt): t = np.arange(0, tstop, dt) r = np.zeros(np.size(t)) amp = (tstop*freq/1000) / (-1/(2*np.pi*freq_osc/1000) * np.sin(2*np.pi*freq_osc/1000*tstop) + tstop) # E_t[n_spikes] = integral_t(r(t)*1) --> solve for the amplitude (n_spikes is given by the period t...
Python
nomic_cornstack_python_v1
import cv2 import numpy function main begin set videoSrc = string ../video/ExampleVideo.mp4 set video = call VideoCapture videoSrc call namedWindow string Virtual Wall Example while call isOpened begin set tuple isFrame frame = read video if isFrame begin image show string Virtual Wall Example frame comment wait 40 ms ...
import cv2 import numpy def main(): videoSrc = '../video/ExampleVideo.mp4' video = cv2.VideoCapture(videoSrc) cv2.namedWindow('Virtual Wall Example') while(video.isOpened()): isFrame,frame = video.read() if(isFrame): cv2.imshow('Virtual Wall Example', frame) cv2.waitKey(40) # wait 40 ms to give the...
Python
zaydzuhri_stack_edu_python
comment /usr/bin/python3.7 print string Hello, this is a simple example of concatenation with the use of the plus sign, + string which allows this below line to be MERGED with the above, + string concatenation = a group of things linked together or occurring together in a way that produces a particular result.
#/usr/bin/python3.7 print("Hello, this is a simple example of concatenation with the use of the plus sign, " + "which allows this below line to be MERGED with the above, " + "concatenation = a group of things linked together or occurring together in a way that produces a particular result.")
Python
zaydzuhri_stack_edu_python
from pyjarowinkler.distance import get_jaro_distance import editdistance import fuzzy from tqdm import tqdm function pheonetic_distance name1 name2 begin string this returns edit distance for phonetic similarity for two words set soundness1 = call nysiis name1 set soundness2 = call nysiis name2 set nysiis_score = eval ...
from pyjarowinkler.distance import get_jaro_distance import editdistance import fuzzy from tqdm import tqdm def pheonetic_distance(name1, name2): ''' this returns edit distance for phonetic similarity for two words''' soundness1 = fuzzy.nysiis(name1) soundness2 = fuzzy.nysiis(name2) nysiis_score = ed...
Python
zaydzuhri_stack_edu_python
import sys from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * import re function hex_to_rgb value begin set value = left strip value string # set lv = length value return list generator expression integer value at slice i : i + lv // 3 : 16 for i in range 0 lv lv // 3 end function class...
import sys from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * import re def hex_to_rgb(value): value = value.lstrip('#') lv = len(value) return list(int(value[i:i + lv // 3], 16) for i in range(0, lv, lv // 3)) class Example(QWidget): def __init__(self...
Python
zaydzuhri_stack_edu_python
function rotate_dice L0 begin set L = L0 at slice : : for k in p_dice begin yield L set L at slice : : = generator expression L at e for e in D at k end end function while 1 begin set N = integer input if N == 0 begin break end set res = list for i in range N begin set cube = split input for dice in call rotate_...
def rotate_dice(L0): L = L0[:] for k in p_dice: yield L L[:] = (L[e] for e in D[k]) while 1: N = int(input()) if N == 0: break res = [] for i in range(N): cube = input().split() for dice in rotate_dice(cube): if dice in res: br...
Python
jtatman_500k
function calculate_tfidf documents year month begin set now = time set tfidfPath = format string intermed/tfidf/tfidf-{}-{}.json year month if not is file path tfidfPath begin set tf_df = default dictionary Counter for item in items documents begin set document = item at 1 for word in set document begin update tf_df at...
def calculate_tfidf(documents, year, month): now = time.time() tfidfPath = "intermed/tfidf/tfidf-{}-{}.json".format(year, month) if not os.path.isfile(tfidfPath): tf_df = defaultdict(Counter) for item in documents.items(): document = item[1] for word in set(document...
Python
nomic_cornstack_python_v1
function get_info self begin string get merged info about phantom conf set result = copy copy streams at 0 set stat_log = stat_log set steps = list set ammo_file = string set rps_schedule = none set ammo_count = 0 set duration = 0 set instances = 0 set loadscheme = list set loop_count = 0 for stream in streams begin...
def get_info(self): """ get merged info about phantom conf """ result = copy.copy(self.streams[0]) result.stat_log = self.stat_log result.steps = [] result.ammo_file = '' result.rps_schedule = None result.ammo_count = 0 result.duration = 0 result....
Python
jtatman_500k
comment !/usr/bin/env python comment coding: utf-8 comment # Web Scraping: comment 1. Import the libraries and classes: comment - urllib request. comment - BeautifulSoup. comment 2. Steps: comment a. html upload. comment b. html parser. comment c. Extraction of data from web page. comment d. Transformation into require...
#!/usr/bin/env python # coding: utf-8 # # Web Scraping: # 1. Import the libraries and classes: # - urllib request. # - BeautifulSoup. # 2. Steps: # # # a. html upload. # b. html parser. # c. Extraction of data from web page. # d. Transformation into required file: csv. # Imp...
Python
zaydzuhri_stack_edu_python
function block self *blocks **kwargs begin string Build a basic code block. Positional arguments should be instances of CodeBlock or strings. All code blocks passed as positional arguments are added at indentation level 0. None blocks are skipped. assert string name not in kwargs set default kwargs string code self set...
def block(self, *blocks, **kwargs) -> "CodeBlock": """ Build a basic code block. Positional arguments should be instances of CodeBlock or strings. All code blocks passed as positional arguments are added at indentation level 0. None blocks are skipped. """ assert ...
Python
jtatman_500k
function test_create_firewall_group_compact self begin set firewall_group = deep copy _mock_firewall_group_attrs del firewall_group at string ports del firewall_group at string egress_firewall_policy del firewall_group at string ingress_firewall_policy set created_firewall = deep copy firewall_group update created_fire...
def test_create_firewall_group_compact(self): firewall_group = deepcopy(self._mock_firewall_group_attrs) del firewall_group['ports'] del firewall_group['egress_firewall_policy'] del firewall_group['ingress_firewall_policy'] created_firewall = deepcopy(firewall_group) crea...
Python
nomic_cornstack_python_v1
comment Escreva um programa que pergunte a quantidade de quilômetros percorridos por um carro alugado pelo usuário, assim comment como a quantidade de dias pelos quais o carro foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$60 comment por dia e R$0,15 por km rodado. set km_rodado = decimal input strin...
# Escreva um programa que pergunte a quantidade de quilômetros percorridos por um carro alugado pelo usuário, assim # como a quantidade de dias pelos quais o carro foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$60 # por dia e R$0,15 por km rodado. km_rodado = float(input("Informe a quilometragem: ")...
Python
zaydzuhri_stack_edu_python
from flask import Flask , request , render_template from flask_debugtoolbar import DebugToolbarExtension from stories import Story set app = call Flask __name__ set config at string SECRET_KEY = string yeet set debug = call DebugToolbarExtension app set prompts = dict 0 list string place string noun string verb string ...
from flask import Flask, request, render_template from flask_debugtoolbar import DebugToolbarExtension from stories import Story app = Flask(__name__) app.config['SECRET_KEY'] = 'yeet' debug = DebugToolbarExtension(app) prompts = {0: ['place', 'noun', 'verb', 'adjective', 'plural_noun'], 1: ['person', 'noun_1', 'noun...
Python
zaydzuhri_stack_edu_python
function change_schedulecourse_color request begin set id = get GET string id set color = get GET string color set schedule_title = session at string active_schedule set current_user = get objects user_email=email comment TODO: this will break if the section/schedule are not found set schedule = get objects title=sched...
def change_schedulecourse_color(request): id = request.GET.get('id') color = request.GET.get('color') schedule_title = request.session['active_schedule'] current_user = Student.objects.get(user_email=request.user.email) # TODO: this will break if the section/schedule are not found...
Python
nomic_cornstack_python_v1
from urllib.parse import urlparse comment domain ismini okuma (example.com) function get_domain_name url begin try begin set results = split call get_sub_domain_name url string . return results at - 2 + string . + results at - 1 end except any begin return string end end function comment sub domain okuma (name.example...
from urllib.parse import urlparse # domain ismini okuma (example.com) def get_domain_name(url): try: results = get_sub_domain_name(url).split('.') return results[-2] + '.' + results[-1] except: return '' # sub domain okuma (name.example.com) def get_sub_domain_name(url): try: ...
Python
zaydzuhri_stack_edu_python
function handleCommand self cmd args begin set function = get attribute self string cmd_ + cmd none if function is none or cmd not in commands begin return end set types = commands at cmd if length types != length args begin set converted = false end else begin comment Unless the below loop has a conversion problem. se...
def handleCommand(self, cmd, args): function = getattr(self, 'cmd_' + cmd, None) if function is None or cmd not in self.commands: return types = self.commands[cmd] if len(types) != len(args): converted = False else: converted = Tr...
Python
nomic_cornstack_python_v1
function get_projects_async future_session connection offset=0 limit=- 1 error_msg=none begin set url = base_url + string /api/monitors/projects set headers = dict string X-MSTR-ProjectID none set params = dict string offset offset ; string limit limit set future = get future_session url=url headers=headers params=para...
def get_projects_async(future_session: "FuturesSession", connection: "Connection", offset: int = 0, limit: int = -1, error_msg: str = None): url = connection.base_url + '/api/monitors/projects' headers = {'X-MSTR-ProjectID': None} params = {'offset': offset, 'limit': limit} future...
Python
nomic_cornstack_python_v1
from django.contrib.auth.models import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager extends BaseUserManager begin function create_user self username role password **extra_fields begin string Create and save a User with the username,role and password :param email: :para...
from django.contrib.auth.models import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): def create_user(self, username, role, password, **extra_fields): """ Create and save a User with the username,role and password :param em...
Python
zaydzuhri_stack_edu_python
string Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too. You need to find the shortest such subarray and output its length. Example 1: Input: [2, 6, 4, 8, 10, 9, 15] Output: 5 Explanation:...
''' Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too. You need to find the shortest such subarray and output its length. Example 1: Input: [2, 6, 4, 8, 10, 9, 15] Output: 5 Explanation: ...
Python
zaydzuhri_stack_edu_python
function sphere_volume r begin return 4 * 3.14159 / 3 * r ^ 3 end function
def sphere_volume(r): return (4 * 3.14159 / 3)*r**3
Python
nomic_cornstack_python_v1
class Solution begin function findDuplicate self nums begin set store = dict for num in nums begin if num not in store begin set store at num = 1 end else begin return num end end end function end class comment Floyd's Tortoise and Hare (Cycle Detection) comment class Solution: comment def findDuplicate(self, nums): c...
class Solution: def findDuplicate(self, nums: List[int]) -> int: store = {}; for num in nums: if num not in store: store[num] = 1; else: return num; #Floyd's Tortoise and Hare (Cycle Detection) #class Solution: # def findDuplicate(self, num...
Python
zaydzuhri_stack_edu_python
function to_gff self file_name subset=none **kwargs begin call write_gff file_name call regions subset lazy=true keyword kwargs end function
def to_gff(self, file_name, subset=None, **kwargs): write_gff(file_name, self.regions(subset, lazy=True), **kwargs)
Python
nomic_cornstack_python_v1
function minimal_paths self begin try begin if __correct begin comment the set of the nodes to which the minimal path has not been found comment at the beginning all the nodes are unmarked set unmarked_nodes = set call get_vertices comment the dictionary that contains pairs like (n : c) where n is the id of the node an...
def minimal_paths(self): try: if self.__correct: # the set of the nodes to which the minimal path has not been found # at the beginning all the nodes are unmarked unmarked_nodes = set(self.__graph.get_vertices()) # the dictionary that ...
Python
nomic_cornstack_python_v1
with open string data/lotus_sutra.txt string r as f begin set lines = list comprehension strip line for line in f set cleaned = list comment removes newlines and 'year unknown text' for line in lines begin if line != string and line != string year unknown begin comment removes integers try begin integer line pass end...
with open ("data/lotus_sutra.txt", "r") as f: lines = [line.strip() for line in f] cleaned = [] #removes newlines and 'year unknown text' for line in lines: if line != '' and line != 'year unknown': #removes integers try: (int(line)) pass except: cleaned.append(line) # print (len(lines))...
Python
zaydzuhri_stack_edu_python
function start_video video_path target_faces target_dress_path begin set tuple model classes colors output_layers = call load_yolo set dress_checker = call get_siamese_dress call load_weights string model_dresses.h5 set target_dress = call imread target_dress_path set target_dress = call resize target_dress tuple 32 32...
def start_video(video_path, target_faces, target_dress_path): model, classes, colors, output_layers = load_yolo() dress_checker = get_siamese_dress() dress_checker.load_weights('model_dresses.h5') target_dress = cv2.imread(target_dress_path) target_dress = cv2.resize(target_dress, (32, 32), interpol...
Python
nomic_cornstack_python_v1
function ftoi f d=2 begin return integer f * power 10 d end function function itof i d=2 begin return i * power 10 - d end function function iper a b begin if b == 0 begin return 0 end return round a * 10000 / b end function function ishare a b begin return integer a * b / 10000 end function function ishare_c a b begin...
def ftoi(f: float, d: int = 2) -> int: return int(f*pow(10, d)) def itof(i: int, d: int = 2) -> float: return i*pow(10, -d) def iper(a: int, b: int) -> int: if b == 0: return 0 return round(a * 10000 / b) def ishare(a: int, b: int) -> int: return int((a * b) / 10000) def ishare_c(a: ...
Python
zaydzuhri_stack_edu_python
import math import numpy class Number begin comment these are the input values function numberstodirection self direct elf value_of_a value_of_b value_of_c angle begin comment instead of using switch case,if case is used in python set angle_1 = integer angle if direct == 3 begin comment these are angles for rotation al...
import math import numpy class Number: def numberstodirection(self,direct,elf,value_of_a,value_of_b,value_of_c,angle):#these are the input values # instead of using switch case,if case is used in python self.angle_1 = int(angle) if direct == 3: # these ar...
Python
zaydzuhri_stack_edu_python
function _cmp_ self other begin return call cmp call matrix call matrix end function
def _cmp_(self, other): return cmp(self.matrix(), other.matrix())
Python
nomic_cornstack_python_v1
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits import mplot3d comment 一组数据的可视化 function plot1 x y begin comment 显示真实值散点图 plot x y string o color=string blue label=string y_true comment 标签设置 x label string X y label string y comment 图例显示最佳位置 legend loc=string best comment 显示图形 show end function fun...
import numpy as np import matplotlib.pyplot as plt from mpl_toolkits import mplot3d def plot1(x,y):#一组数据的可视化 plt.plot(x,y,'o',color='blue',label='y_true')#显示真实值散点图 plt.xlabel("X")#标签设置 plt.ylabel("y") plt.legend(loc='best')#图例显示最佳位置 plt.show()#显示图形 def plot2(x,y,x_test,y_pre): plt.plot(x, y, 'o...
Python
zaydzuhri_stack_edu_python
import math comment create NaN value set x = decimal string nan if call isnan x begin print string x is NaN end else begin print string x is not NaN end comment Output: x is NaN
import math x = float('nan') # create NaN value if math.isnan(x): print('x is NaN') else: print('x is not NaN') # Output: x is NaN
Python
flytech_python_25k
comment !/usr/bin/python function name_to_ticker series refs names targets begin string return subset dataframe premised on the 'names' column, which must contain values using the provided 'series'.. @series, list of company names to be converted @refs, dataframe containing references for conversion @names, column with...
#!/usr/bin/python def name_to_ticker(series, refs, names, targets): ''' return subset dataframe premised on the 'names' column, which must contain values using the provided 'series'.. @series, list of company names to be converted @refs, dataframe containing references for conversion @na...
Python
zaydzuhri_stack_edu_python
function test_check_in_trie self begin set words = list string CAT string DOG string CAR string CARP string TAR string GOD string RAT string GO for word in words begin set result = call in_trie expected_trie word assert equal word result end end function
def test_check_in_trie(self): words = ['CAT', 'DOG', 'CAR', 'CARP', 'TAR', 'GOD', 'RAT', 'GO'] for word in words: result = self.puzzle_solution.in_trie(self.expected_trie, word) ...
Python
nomic_cornstack_python_v1
function __init__ __self__ resource_name args opts=none begin Ellipsis end function
def __init__(__self__, resource_name: str, args: QueueArgs, opts: Optional[pulumi.ResourceOptions] = None): ...
Python
nomic_cornstack_python_v1
import folium import pandas as pd set df = read csv string /Users/star/Desktop/GitHub_Code_To_Show_off/volcanoes/Volcanoes-USA.txt set test1 = map location=list 40.446 - 101.689 zoom_start=4 tiles=string Stamen Terrain function mrk_color elev begin if elev in range 0 1000 begin set color = string green end else if elev...
import folium import pandas as pd df = pd.read_csv("/Users/star/Desktop/GitHub_Code_To_Show_off/volcanoes/Volcanoes-USA.txt") test1 = folium.Map(location=[40.446,-101.689],zoom_start=4,tiles ='Stamen Terrain') def mrk_color(elev): if elev in range (0,1000): color= "green" elif elev in range (1000,3000): color=...
Python
zaydzuhri_stack_edu_python
function editParticipantBtn_clicked self begin set participantId = call getSelectedId model=participantModel view=participantTableView if participantId begin set dialog = call EditParticipantDialog participantId=participantId comment For Modal dialog call exec_ end end function
def editParticipantBtn_clicked(self): participantId = self.getSelectedId(model=dbInteractionInstance.participantModel, view=self.ui.participantTableView) if participantId: dialog = EditParticipantDialog(participantId=participantId) # For Modal dialog dialog.exec_()
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- string @author: Brownbull - Gabriel Carcamo - carcamo.gabriel@gmail.com MLR from env.Include.ml.imports import * from env.Include.ml.processing import * from env.Include.ml.visual import * from env.Include.ml.optimize import * function MLR_input folderPath modelName X Y config begin set fu...
# -*- coding: utf-8 -*- """ @author: Brownbull - Gabriel Carcamo - carcamo.gabriel@gmail.com MLR """ from env.Include.ml.imports import * from env.Include.ml.processing import * from env.Include.ml.visual import * from env.Include.ml.optimize import * def MLR_input(folderPath, modelName, X, Y, config): ...
Python
zaydzuhri_stack_edu_python
function get_repo_info user_id begin with call scoped_session as session begin return call order_by call asc end end function
def get_repo_info(user_id): with scoped_session() as session: return session.query(UserRequests).filter_by(user_id=user_id).\ order_by(UserRequests.id.asc())
Python
nomic_cornstack_python_v1
function num_hyperparameters self begin return num_hyperparameters end function
def num_hyperparameters(self): return self._covariance.num_hyperparameters
Python
nomic_cornstack_python_v1
comment 외장함수 comment sys 모듈은 파이썬 인터프리터가 제공하는 변수와 함수를 직접 제어할 수 있게 해주는 모듈이다. import sys print argv exit comment pickle은 객체의 형태를 그대로 유지하면서 파일에 저장하고 불러올 수 있게 하는 모듈이다. import pickle set f = open string test.txt string wb set data = dict 1 string python ; 2 string you need dump data f close f import pickle set f = open strin...
##외장함수 #sys 모듈은 파이썬 인터프리터가 제공하는 변수와 함수를 직접 제어할 수 있게 해주는 모듈이다. import sys print(sys.argv) sys.exit #pickle은 객체의 형태를 그대로 유지하면서 파일에 저장하고 불러올 수 있게 하는 모듈이다. import pickle f = open("test.txt", "wb") data = {1: 'python', 2: 'you need'} pickle.dump(data, f) f.close() import pickle f = open("test.txt", "rb") data = pickle.lo...
Python
zaydzuhri_stack_edu_python
import csv set mergedtsvfile = open string title.merged.tsv string w set mergedoutput = writer mergedtsvfile delimiter=string function yield_tsv file begin set field = split next file string set field = list comprehension strip f for f in field yield field end function function mergeByID file ID begin set temparray = l...
import csv mergedtsvfile = open("title.merged.tsv","w") mergedoutput = csv.writer(mergedtsvfile,delimiter = '\t') def yield_tsv(file): field = next(file).split("\t") field = [f.strip() for f in field] yield field def mergeByID(file,ID): temparray = [] mergefilearray=[] pointer = '' mergev...
Python
zaydzuhri_stack_edu_python
function hlil_instructions self begin for block in hlil_basic_blocks begin yield from block end end function
def hlil_instructions(self) -> 'highlevelil.HLILInstructionsType': for block in self.hlil_basic_blocks: yield from block
Python
nomic_cornstack_python_v1
for i in range n begin if n + 1 // 2 >= i + 1 begin set ans at x at i at 0 = x at n + 1 // 2 at 1 end else begin set ans at x at i at 0 = x at n + 1 // 2 - 1 at 1 end end print join string map str ans
for i in range(n): if (n+1)//2 >= i+1: ans[x[i][0]] = x[(n+1)//2][1] else: ans[x[i][0]] = x[(n+1)//2-1][1] print("\n".join(map(str, ans)))
Python
zaydzuhri_stack_edu_python
import itertools import math import operator import primes function digits n begin return list comprehension integer i for i in string n end function function sumOfDigits n begin return sum call digits n end function function divisors n begin string Finds divisors by trying all possibilities set sqrt = square root n yi...
import itertools import math import operator import primes def digits(n): return [int(i) for i in str(n)] def sumOfDigits(n): return sum(digits(n)) def divisors(n): """Finds divisors by trying all possibilities""" sqrt = math.sqrt(n) yield 1 for i in range(2, int(sqrt)+1): q, r = ...
Python
zaydzuhri_stack_edu_python
function create_location_efs Subdirectory=none EfsFilesystemArn=none Ec2Config=none Tags=none begin pass end function
def create_location_efs(Subdirectory=None, EfsFilesystemArn=None, Ec2Config=None, Tags=None): pass
Python
nomic_cornstack_python_v1
for i in range 0 n begin set num = input set num = num at slice : : - 1 print num end
for i in range(0,n): num = input() num = num[::-1] print(num)
Python
zaydzuhri_stack_edu_python
from app.model.modelImport import * class Opcion extends Model begin set __tablename__ = string opcion set cod = call Column string cod_opcion Integer primary_key=true index=true set nombre = call Column string nombre_opcion call String 80 nullable=false unique=true index=true set isActiv = call Column string is_activ ...
from app.model.modelImport import * class Opcion(db.Model): __tablename__ = 'opcion' cod = db.Column('cod_opcion',Integer, primary_key = True, index=True) nombre = db.Column('nombre_opcion',String(80), nullable=False,unique=True,index = True) isActiv = db.Column('is_activ',Boolean,nullable=True) ...
Python
zaydzuhri_stack_edu_python
function video_stack video begin set video = array video set tuple *batch_shape n_frames H W D = shape set perm = tuple range length batch_shape + tuple array list 1 2 0 3 + length batch_shape return reshape transpose np video perm *batch_shape H W n_frames * D end function
def video_stack(video): video = np.array(video) *batch_shape, n_frames, H, W, D = video.shape perm = tuple(range(len(batch_shape))) + tuple(np.array([1, 2, 0, 3]) + len(batch_shape)) return np.transpose(video, perm).reshape(*batch_shape, H, W, n_frames*D)
Python
nomic_cornstack_python_v1
function check_parenthesis string begin set pars = 0 for s in string begin comment print pars if s in tuple string ( string [ string { begin set pars = pars + 1 end else if s in tuple string ) string ] string } begin set pars = pars - 1 end end end function
def check_parenthesis(string): pars = 0 for s in string: #print pars if s in ('(','[','{'): pars+=1 elif s in (')',']','}'): pars-=1
Python
zaydzuhri_stack_edu_python
function from_service_account_file cls filename *args **kwargs begin set credentials = call from_service_account_file filename set kwargs at string credentials = credentials return call cls *args keyword kwargs end function
def from_service_account_file(cls, filename: str, *args, **kwargs): credentials = service_account.Credentials.from_service_account_file(filename) kwargs["credentials"] = credentials return cls(*args, **kwargs)
Python
nomic_cornstack_python_v1
function cluster_sentences target_words sentences target_positions language=string ru begin set instances = sorted zip target_words range length target_positions key=lambda it -> it at 0 set idx2label = dictionary for tuple target_word grouped_instances in group by instances lambda it -> it at 0 begin set grouped_inst_...
def cluster_sentences( target_words: List[str], sentences: List[str], target_positions: List[str], language: str = "ru", ) -> List[str]: instances = sorted( zip(target_words, range(len(target_positions))), key=lambda it: it[0], ) idx2label = dict() for target_word, grouped_inst...
Python
nomic_cornstack_python_v1
for t in range T begin set n = integer input set xs = list comprehension integer x for x in split input comment for i in range(len(xs)-2): comment if xs[i]+xs[i+1] >= xs[i+2]: comment print(i+1, i+2, i+3) comment break comment else: comment print(-1) comment lol I thought the prompt was the inverse if xs at 0 + xs at 1...
for t in range(T): n = int(input()) xs = [int(x) for x in input().split()] # for i in range(len(xs)-2): # if xs[i]+xs[i+1] >= xs[i+2]: # print(i+1, i+2, i+3) # break # else: # print(-1) # lol I thought the prompt was the inverse if xs[0] + xs[1] <= xs[len(...
Python
zaydzuhri_stack_edu_python
function _take_define_sample info head begin set info = call compss_wait_on info set n_list = info at string size set total = sum n_list if total < head begin set head = total end set cum_sum = cumulative sum np n_list set idx = next generator expression x for tuple x val in enumerate cum_sum if val >= head set list_id...
def _take_define_sample(info, head): info = compss_wait_on(info) n_list = info['size'] total = sum(n_list) if total < head: head = total cum_sum = np.cumsum(n_list) idx = next(x for x, val in enumerate(cum_sum) if val >= head) list_ids = n_list[0: idx+1] list_ids[-1] -= (cum_s...
Python
nomic_cornstack_python_v1
function generate_round_scoring_tiles seed=0 begin if seed is not 0 begin seed seed end set all_tiles_list = list 1 2 3 4 5 5 6 6 7 7 set randomized_tiles = list for _ in range 6 begin set chosen_tile_index = random integer 0 length all_tiles_list - 1 append randomized_tiles all_tiles_list at chosen_tile_index pop all_...
def generate_round_scoring_tiles(seed=0): if seed is not 0: random.seed(seed) all_tiles_list = [1, 2, 3, 4, 5, 5, 6, 6, 7, 7] randomized_tiles = list() for _ in range(6): chosen_tile_index = random.randint(0, len(all_tiles_list) - 1) randomized_tiles.append(all_tiles_list[chose...
Python
nomic_cornstack_python_v1
function cholesky_band l mininf=0.0 begin comment KBW: added isfinite check so that it doesn't need to be done in comment the for loop. This should be okay because sqrt and division of comment positive numbers by other positive numbers should never lead to comment non-finite numbers. However, need to watch out for nume...
def cholesky_band(l, mininf=0.0): # KBW: added isfinite check so that it doesn't need to be done in # the for loop. This should be okay because sqrt and division of # positive numbers by other positive numbers should never lead to # non-finite numbers. However, need to watch out for numerical # iss...
Python
nomic_cornstack_python_v1
import unittest class TestFizzBuzz extends TestCase begin function test_3_donne_fizz self begin assert equal string Fizz call fizz_buzz 3 end function function test_5_donne_buzz self begin assert equal string Buzz call fizz_buzz 5 end function function test_15_donne_buzz self begin assert equal string FizzBuzz call fiz...
import unittest class TestFizzBuzz(unittest.TestCase): def test_3_donne_fizz(self): self.assertEqual("Fizz", fizz_buzz(3)) def test_5_donne_buzz(self): self.assertEqual("Buzz", fizz_buzz(5)) def test_15_donne_buzz(self): self.assertEqual("FizzBuzz", fizz_buzz(15)) def fizz_buzz(chiffre): if chiffre % 15 == ...
Python
zaydzuhri_stack_edu_python
string Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. For example, given preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] Return the following binary tree: 3 / 9 20 / 15 7 class Node begin function __init__ self v begin set left ...
""" Given preorder and inorder traversal of a tree, construct the binary tree. Note: You may assume that duplicates do not exist in the tree. For example, given preorder = [3,9,20,15,7] inorder = [9,3,15,20,7] Return the following binary tree: 3 / \ 9 20 / \ 15 7 """ class Node: def __ini...
Python
zaydzuhri_stack_edu_python
function sortKey self mode matrix begin comment distance calculation... set distance = call distances LOCAL_ORIGIN modelView=matrix projection=call getProjection viewport=call getViewport at 0 if appearance begin set key = call sortKey mode matrix end else begin set key = tuple false list none end if key at 0 begin se...
def sortKey( self, mode, matrix ): # distance calculation... distance = polygonsort.distances( LOCAL_ORIGIN, modelView = matrix, projection = mode.getProjection(), viewport = mode.getViewport(), )[0] if self.appearance: key = se...
Python
nomic_cornstack_python_v1
function update_scan2D_type self param begin try begin show show set scan_subtype = call value show scan_subtype == string Adaptive if scan_subtype == string Adaptive begin if call value == string resolution begin set title = string Minimal feature (%): if opts at string title != title begin call setValue 1 call setVal...
def update_scan2D_type(self, param): try: self.settings.child('scan2D_settings', 'step_2d_axis1').show() self.settings.child('scan2D_settings', 'step_2d_axis2').show() scan_subtype = self.settings.child('scan2D_settings', 'scan2D_type').value() self.settings.child...
Python
nomic_cornstack_python_v1
class File begin function __init__ self file_name inode begin set name = file_name set inode = inode end function end class class INode begin function __init__ self name begin set name = name set pointer = list end function function add_pointer self pointer begin append pointer pointer end function end class class Dat...
class File(): def __init__(self, file_name, inode): self.name = file_name self.inode = inode class INode(): def __init__(self, name): self.name = name self.pointer = [] def add_pointer(self, pointer): self.pointer.append(pointer) class Data(): def __init__...
Python
zaydzuhri_stack_edu_python
comment TEST HERO from import Hero from import Skill from import events from import clientcommands from cooldown import Cooldown from random import randint class Undead extends Hero begin set name = string Undead Scourge end class decorator skill class Unholy extends Skill begin set name = string Unholy Aura set ma...
## TEST HERO from . import Hero from . import Skill from . import events from . import clientcommands from ..cooldown import Cooldown from random import randint class Undead(Hero): name = 'Undead Scourge' @Undead.skill class Unholy(Skill): name = 'Unholy Aura' max_level = 8 @events('player_spawn') ...
Python
zaydzuhri_stack_edu_python
import abc import six decorator call add_metaclass ABCMeta comment pylint: disable=too-few-public-methods class HealthPlugin extends object begin string Base class for Health plugins To add a new Health plugins you should use HealthPlugin as your base class and override the get_status() method. Then add to your setup.p...
import abc import six @six.add_metaclass(abc.ABCMeta) # pylint: disable=too-few-public-methods class HealthPlugin(object): """Base class for Health plugins To add a new Health plugins you should use HealthPlugin as your base class and override the get_status() method. Then add to your setup.py a new ...
Python
zaydzuhri_stack_edu_python
from flask_unchained.bundles.sqlalchemy import SessionManager , SQLAlchemyUnchained function setup db begin set session_manager = call SessionManager db class Foo extends Model begin class Meta begin set lazy_mapped = false end class set name = call Column String end class call create_all return tuple Foo session_manag...
from flask_unchained.bundles.sqlalchemy import SessionManager, SQLAlchemyUnchained def setup(db: SQLAlchemyUnchained): session_manager = SessionManager(db) class Foo(db.Model): class Meta: lazy_mapped = False name = db.Column(db.String) db.create_all() return Foo, sessio...
Python
jtatman_500k
string Created on 15 September 2017 @author: Yahya Almardeny This class for measuring the Relative Humidity level in air class Humidity begin function __init__ self mcp channel sys_volt begin comment ADC object set mcp = mcp comment channel on ADC to read from (RH Sensor is connected to) set channel = channel comment V...
''' Created on 15 September 2017 @author: Yahya Almardeny This class for measuring the Relative Humidity level in air ''' class Humidity(): def __init__(self, mcp, channel, sys_volt): self.mcp = mcp # ADC object self.channel = channel # channel on ADC to read from (RH Sensor is connected t...
Python
zaydzuhri_stack_edu_python
comment coding:utf8 class ASN1 begin function __init__ self begin pass end function decorator staticmethod function decode b6 begin set newB6 = dictionary set newB6 at string enc = b6 set newB6 at string pos = 0 set b5 = b6 set b8 = get newB6 string enc at get newB6 string pos set newB6 at string pos = newB6 at string ...
# coding:utf8 class ASN1: def __init__(self): pass @staticmethod def decode(b6): newB6 = dict() newB6["enc"] = b6 newB6["pos"] = 0 b5 = b6 b8 = newB6.get("enc")[newB6.get("pos")] newB6["pos"] += 1 b3 = newB6.get("enc")[newB6.get("pos")] ...
Python
zaydzuhri_stack_edu_python
string Module with leap year functions function leap_year year begin string Determine if year is a leap year return year % 4 == 0 and year % 100 != 0 or year % 400 == 0 end function
"""Module with leap year functions""" def leap_year(year): """Determine if year is a leap year""" return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
Python
zaydzuhri_stack_edu_python