code
stringlengths
10
2.58M
original_code
stringlengths
3
3.18M
original_language
stringclasses
1 value
source
stringclasses
7 values
function test_datetime_naive self begin assert equal dumps list call datetime 2000 1 1 2 3 4 123 b'["2000-01-01T02:03:04.123"]' end function
def test_datetime_naive(self): self.assertEqual( orjson.dumps([datetime.datetime(2000, 1, 1, 2, 3, 4, 123)]), b'["2000-01-01T02:03:04.123"]', )
Python
nomic_cornstack_python_v1
function pay drink begin set qtr_pay = integer input string How many quarters? set dime_pay = integer input string How many dimes? set nickel_pay = integer input string How many nickels? set penny_pay = integer input string How many pennies? set payment_given = qtr_pay * qtr + dime_pay * dime + nickel_pay * nickel + pe...
def pay(drink): qtr_pay = int(input("How many quarters? ")) dime_pay = int(input("How many dimes? ")) nickel_pay = int(input(" How many nickels? ")) penny_pay = int(input("How many pennies? ")) payment_given = (qtr_pay * qtr) + (dime_pay * dime) + (nickel_pay * nickel) + (penny_pay * penny) prin...
Python
nomic_cornstack_python_v1
import torch import torch.nn as nn comment L2 Loss comment L2Loss(outputs, targets) comment outputs -> shape BATCH_SIZE x NUM_CLASSES comment targets -> shape BATCH_SIZE x NUM_CLASSES class L2Loss begin comment Constructor function __init__ self reduction=none alpha=1.0 begin set default_reduction = string mean if redu...
import torch import torch.nn as nn # # L2 Loss # L2Loss(outputs, targets) # outputs -> shape BATCH_SIZE x NUM_CLASSES # targets -> shape BATCH_SIZE x NUM_CLASSES # class L2Loss(): # Constructor def __init__(self, reduction=None, alpha=1.0): default_reduction = 'mean' if red...
Python
zaydzuhri_stack_edu_python
function eam_embed self begin return call _parse_params_section string EAM-Embed _parse_embed_line end function
def eam_embed(self): return self._parse_params_section("EAM-Embed", self._parse_embed_line)
Python
nomic_cornstack_python_v1
function __gt__ self other begin if _strength > strength begin return true end return false end function
def __gt__(self, other): if self._strength > other.strength: return True return False
Python
nomic_cornstack_python_v1
function logp self value begin set p_trans = p_trans set p_t0 = p_t0 comment We need a the probability of the next state given the current state P(x_t | x_t-1) comment Index into trans matrix to generate categorical probabilities for the next point which is based on the comment previous point (except the last) set p_t ...
def logp(self, value): p_trans = self.p_trans p_t0 = self.p_t0 # We need a the probability of the next state given the current state P(x_t | x_t-1) # Index into trans matrix to generate categorical probabilities for the next point which is based on the # previous point (except t...
Python
nomic_cornstack_python_v1
import datetime while true begin set time = string format time call utcnow string %H:%M:%S.%f end
import datetime while True: time = datetime.datetime.utcnow().strftime('%H:%M:%S.%f')
Python
zaydzuhri_stack_edu_python
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By import time import Tkinter as tk set top = call Tk set F = call Frame top ca...
from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By import time import Tkinter as tk top=tk.Tk() F=tk.Frame(top) F.pack(fi...
Python
zaydzuhri_stack_edu_python
function execute_string self sql_text remove_comments=false return_cursors=true begin set ret = list if PY2 begin set stream = call StringIO if expression is instance sql_text str then decode sql_text string utf-8 else sql_text end else begin set stream = call StringIO sql_text end for tuple sql is_put_or_get in call ...
def execute_string(self, sql_text, remove_comments=False, return_cursors=True): ret = [] if PY2: stream = StringIO(sql_text.decode('utf-8') if isinstance( sql_text, str) else sql_text) else: stream = StringIO(s...
Python
nomic_cornstack_python_v1
comment Crear variables y asignarles un valor set texto = string Máster en Python set texto2 = string con Víctor Robles set numero = 45 set decimal = 6.7 comment Mostrar el valor de las variables print texto print texto2 print numero print decimal print string ----------------------- comment Sustituir el valor de algun...
# Crear variables y asignarles un valor texto = "Máster en Python" texto2 = "con Víctor Robles" numero = 45 decimal = 6.7 # Mostrar el valor de las variables print(texto) print(texto2) print(numero) print(decimal) print("-----------------------") # Sustituir el valor de algunas variables / reasignando valores num...
Python
zaydzuhri_stack_edu_python
function has_been_modified self begin return _has_been_modified end function
def has_been_modified(self): return self._has_been_modified
Python
nomic_cornstack_python_v1
function _validate_config cls config begin return config end function
def _validate_config(cls, config): return config
Python
nomic_cornstack_python_v1
function _push_with_children_to_stack self formula **kwargs begin comment Deal with quantifiers if call is_quantifier begin comment 1. We invoke the relevant function (walk_exists or comment walk_forall) to print the formula set fun = functions at call node_type set res = call fun formula args=none keyword kwargs comme...
def _push_with_children_to_stack(self, formula, **kwargs): # Deal with quantifiers if formula.is_quantifier(): # 1. We invoke the relevant function (walk_exists or # walk_forall) to print the formula fun = self.functions[formula.node_type()] res = fun(f...
Python
nomic_cornstack_python_v1
from typing import List class Solution begin function maxProfit self prices begin if not prices or length prices == 1 begin return 0 end else comment 股票价格一直在降的情况 if sorted prices reverse=true == prices begin return 0 end set max_profit = 0 set acculated_profit = 0 set low = prices at 0 for p in prices at slice : - 1 :...
from typing import List class Solution: def maxProfit(self, prices: List[int]) -> int: if not prices or len(prices) == 1: return 0 # 股票价格一直在降的情况 elif sorted(prices, reverse=True) == prices: return 0 max_profit = 0 acculated_profit = 0 low = p...
Python
zaydzuhri_stack_edu_python
import streamlit as st import pandas as pd import numpy as np from sklearn import svm from sklearn import metrics from sklearn import tree from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB function main begin set feat_list = list set df = read csv string diabetes.csv from s...
import streamlit as st import pandas as pd import numpy as np from sklearn import svm from sklearn import metrics from sklearn import tree from sklearn.ensemble import RandomForestClassifier from sklearn.naive_bayes import GaussianNB def main(): feat_list=[] df=pd.read_csv('diabetes.csv') from ...
Python
zaydzuhri_stack_edu_python
function getFuelMass self begin return sum generator expression call getFuelMass for c in self end function
def getFuelMass(self): return sum((c.getFuelMass() for c in self))
Python
nomic_cornstack_python_v1
comment 圧縮した文字列 t に対して len(t) - 1 が答え from itertools import groupby set groups = list set uniquekeys = list for tuple k g in group by s begin append groups list g append uniquekeys k end comment print(groups) comment print(uniquekeys) print length uniquekeys - 1
# 圧縮した文字列 t に対して len(t) - 1 が答え from itertools import groupby groups = [] uniquekeys = [] for k, g in groupby(s): groups.append(list(g)) uniquekeys.append(k) # print(groups) # print(uniquekeys) print(len(uniquekeys) - 1)
Python
zaydzuhri_stack_edu_python
import math set diferenca_max = 0 for angulo in range 0 91 1 begin set senbhas = 4 * angulo * 180 - angulo / 40500 - angulo * 180 - angulo set senpyth = sin angulo set diferenca = absolute senpyth - senbhas print diferenca if diferenca > diferenca_max begin set diferenca_max = diferenca end end print diferenca_max
import math diferenca_max = 0 for angulo in range(0,91,1): senbhas = (4*angulo*(180-angulo))/(40500-(angulo*(180-angulo))) senpyth = math.sin(angulo) diferenca = abs(senpyth-senbhas) print(diferenca) if diferenca > diferenca_max: diferenca_max = diferenca print(diferenca_max)
Python
zaydzuhri_stack_edu_python
function calculate n m parVicinities sentVicinities begin global _N global _M global _euclidean if n <= _N and m <= _M begin return end set _N = n set _M = m set _euclidean = call ndarray n * m dtype=list tuple string x uint16 tuple string y uint16 tuple string euclidean float16 comment the next position to be filled i...
def calculate(n, m, parVicinities, sentVicinities): global _N global _M global _euclidean if (n <= _N) and (m <= _M): return _N = n _M = m _euclidean = numpy.ndarray(n * m, dtype=[('x', numpy.uint16), ('y', numpy.uint16), ('euclidean', numpy.float16)]) ...
Python
nomic_cornstack_python_v1
function __init__ self frame=1 begin set _frame = frame set _ticks = list end function
def __init__(self, frame=1): self._frame = frame self._ticks = []
Python
nomic_cornstack_python_v1
string Plots a values from the IMU along with a rolling average of the previous N values. import collections import random import time import numpy as np import matplotlib.pyplot as plt from devices.imu import IMU set SERIAL_DEV = string /dev/ttyUSB0 set SERIAL_BAUD = 57600 set DATA_POINTS = 150 set AVG_COUNT = 17 set ...
""" Plots a values from the IMU along with a rolling average of the previous N values.""" import collections import random import time import numpy as np import matplotlib.pyplot as plt from devices.imu import IMU SERIAL_DEV = '/dev/ttyUSB0' SERIAL_BAUD = 57600 DATA_POINTS = 150 AVG_COUNT = 17 prev_data_points = coll...
Python
zaydzuhri_stack_edu_python
function run self begin while not _is_terminated begin debug string Start in LoadImageAgent. set start_time = time call load_images sleep max _check_interval - time - start_time 0 debug string End in LoadImageAgent. end end function
def run(self) -> None: while not self._is_terminated: logger.debug("Start in LoadImageAgent.") start_time = time.time() self.load_images() time.sleep(max(self._check_interval - (time.time() - start_time), 0)) logger.debug("End in LoadImageAgent.")
Python
nomic_cornstack_python_v1
function iter_file infile begin with call open_zipped infile as bob begin set out = dict set nexts = string for line in bob begin set f = split right strip line string if not nexts begin set nexts = f at 1 set out at f at 1 = list tuple f at 0 decimal f at 3 continue end if f at 1 == nexts begin append out at f at 1 ...
def iter_file(infile): with open_zipped(infile) as bob: out = {} nexts = '' for line in bob: f = line.rstrip().split('\t') if not nexts: nexts = f[1] out[f[1]] = [(f[0], float(f[3]))] continue if f[1] == ne...
Python
nomic_cornstack_python_v1
function __init__ self n=4 begin set n = n set nodes_generated = 0 set frontier = list set explored = list end function
def __init__(self, n=4): self.n = n self.nodes_generated = 0 self.frontier = [] self.explored = []
Python
nomic_cornstack_python_v1
string Install the following requirements into your virtual environemnt `pip install click redis` Usage: To load data into redis python redis_dump.py load [filepath] To dump data into redis python redis_dump.py dump [filepath] --search '*txt' from rejson import Client , Path import logging function main action filepath...
""" Install the following requirements into your virtual environemnt `pip install click redis` Usage: To load data into redis python redis_dump.py load [filepath] To dump data into redis python redis_dump.py dump [filepath] --search '*txt' """ from rejson import Client, Path import logging def main(action, filepath,...
Python
zaydzuhri_stack_edu_python
async function process inbox begin async function message_loop begin set tuple msg rc = await call receive call reply string Got { msg } return await call message_loop end function comment start the loop return await call message_loop end function
async def process(inbox: MailboxProcessor[Tuple[int, AsyncReplyChannel[str]]]): async def message_loop() -> None: msg, rc = await inbox.receive() rc.reply(f"Got {msg}") return await message_loop() # start the loop return await message_loop()
Python
nomic_cornstack_python_v1
function director self begin return am_i_director end function
def director(self): return(self.am_i_director)
Python
nomic_cornstack_python_v1
function test_transfers_load network_dir network_date begin set gtfs_feed = call get_gtfs_feed network_dir network_date set out_dir = join path EXAMPLE_DIR string output string test_gtfs_transfer_load try begin make directories out_dir end except OSError begin if not is directory path out_dir begin raise end end set tr...
def test_transfers_load(network_dir, network_date): gtfs_feed = get_gtfs_feed(network_dir, network_date) out_dir = os.path.join(EXAMPLE_DIR, 'output', 'test_gtfs_transfer_load') try: os.makedirs(out_dir) except OSError: if not os.path.isdir(out_dir): raise transfers = Tra...
Python
nomic_cornstack_python_v1
function request self token begin pass end function
def request(self, token): pass
Python
nomic_cornstack_python_v1
import tkinter as tk from tkinter import * import tkinter.messagebox set trace = 0 set TITLE_FONT = tuple string Helvetica 22 string bold comment Creates the canvas for the shapes set canvas = call Canvas width=800 height=800 class SampleApp extends Tk begin function __init__ self *args **kwargs begin call __init__ sel...
import tkinter as tk from tkinter import * import tkinter.messagebox trace = 0 TITLE_FONT = ("Helvetica", 22, "bold") #Creates the canvas for the shapes canvas = Canvas(width=800, height=800) class SampleApp(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) ...
Python
zaydzuhri_stack_edu_python
function get_event_type self event_payload begin return event_payload at METASTOCK_EVENT_TYPE_KEY end function
def get_event_type(self, event_payload: dict): return event_payload[METASTOCK_EVENT_TYPE_KEY]
Python
nomic_cornstack_python_v1
function test_detection_learner_init od_detection_dataset begin set learner = call DetectionLearner od_detection_dataset assert type learner == DetectionLearner end function
def test_detection_learner_init(od_detection_dataset): learner = DetectionLearner(od_detection_dataset) assert type(learner) == DetectionLearner
Python
nomic_cornstack_python_v1
function count_neighbour seq_list sim_cutoff=0.8 begin comment [sequence] = number of neighbours. set d_count_neighbour = dict set seq_list_len = length seq_list for i in range seq_list_len begin set pepi = seq_list at i for j in range i seq_list_len begin set pepj = seq_list at j set count = 0 if call is_similar pepi...
def count_neighbour(seq_list, sim_cutoff=0.80): d_count_neighbour = {} # [sequence] = number of neighbours. seq_list_len = len(seq_list) for i in range(seq_list_len): pepi = seq_list[i] for j in range(i, seq_list_len): pepj = seq_list[j] count = 0 if (is_...
Python
nomic_cornstack_python_v1
function make_charge_scalar spectrum_in begin if spectrum_in is none begin return none end set spectrum = clone spectrum_in comment Avoid pyteomics ChargeList if is instance get spectrum string charge none list begin set string charge integer get spectrum string charge at 0 end return spectrum end function
def make_charge_scalar(spectrum_in: SpectrumType) -> SpectrumType: if spectrum_in is None: return None spectrum = spectrum_in.clone() # Avoid pyteomics ChargeList if isinstance(spectrum.get("charge", None), list): spectrum.set("charge", int(spectrum.get("charge")[0])) return spect...
Python
nomic_cornstack_python_v1
import RPi.GPIO as GPIO import time call setmode BCM setup GPIO 10 IN setup GPIO 4 IN comment Upon entering, beam 1 is broken before beam 2 set first = false set second = false set direction = string empty set count = 0 while true begin if input 4 == 0 begin set first = true set direction = string exit end if input 10 ...
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(10, GPIO.IN) GPIO.setup(4, GPIO.IN) #Upon entering, beam 1 is broken before beam 2 first = False second = False direction = "empty" count = 0 while True: if GPIO.input(4) == 0: first = True direction = "exit" if GPIO.input(...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding:UTF-8 import hashlib import hmac set sk = string sk set msg = string 2 function get_authorization sk msg begin set hashing = hex digest call new sk msg sha1 return hashing end function
#!/usr/bin/env python #coding:UTF-8 import hashlib import hmac sk = "sk" msg = "2" def get_authorization(sk, msg): hashing = hmac.new(sk, msg, hashlib.sha1).hexdigest() return hashing
Python
zaydzuhri_stack_edu_python
comment Script con los metodos de Back-End from datetime import datetime from taller_1.models import * from django.db.models import Count import random import gzip import pickle from taller_1.models import User_info , Artist , Homologacion_user , Homologacion_artist , Ratings , RatingTemporal import numpy as np import ...
# Script con los metodos de Back-End from datetime import datetime from taller_1.models import * from django.db.models import Count import random import gzip import pickle from taller_1.models import User_info, Artist, Homologacion_user, Homologacion_artist, Ratings, RatingTemporal import numpy as np import pand...
Python
zaydzuhri_stack_edu_python
function test_empty_context get_input begin set inp = get_input set out = join string call contextual_map keyword inp comment quantifier == all set exp = string x * length inp at string iterable if inp at string quantifier == any begin set exp = inp at string iterable end assert out == exp end function
def test_empty_context(get_input): inp = get_input out = ''.join(contextual_map(**inp)) exp = 'x' * len(inp['iterable']) # quantifier == all if inp['quantifier'] == any: exp = inp['iterable'] assert out == exp
Python
nomic_cornstack_python_v1
from cryptography.fernet import Fernet function callKey begin with open string filekey.key string rb as filekey begin set key = read filekey end set fernet = call Fernet key return fernet end function function encrypt flpath begin set fernet = call callKey with open flpath string rb as file begin set original = read fi...
from cryptography.fernet import Fernet def callKey(): with open('filekey.key', 'rb') as filekey: key = filekey.read() fernet = Fernet(key) return fernet def encrypt(flpath): fernet=callKey() with open(flpath, 'rb') as file: original = file.read() encrypted = fernet.encrypt(ori...
Python
zaydzuhri_stack_edu_python
function types self begin set count = call c_ulonglong 0 set type_list = call BNGetPlatformTypes handle count set result = dict for i in call xrange 0 value begin set name = call _from_core_struct name set result at name = type call BNNewTypeReference type end call BNFreeTypeList type_list value return result end func...
def types(self): count = ctypes.c_ulonglong(0) type_list = core.BNGetPlatformTypes(self.handle, count) result = {} for i in xrange(0, count.value): name = types.QualifiedName._from_core_struct(type_list[i].name) result[name] = types.Type(core.BNNewTypeReference(type_list[i].type)) core.BNFreeTypeList(ty...
Python
nomic_cornstack_python_v1
import random import copy comment Hat Class class Hat begin function __init__ self **kwargs begin set balls_dict = dictionary set contents = list update balls_dict kwargs if balls_dict == dict or sum values balls_dict < 1 begin print string Must enter at least one ball. end else begin for tuple k v in items balls_dict...
import random import copy # Hat Class class Hat: def __init__(self, **kwargs): self.balls_dict = dict() self.contents = list() self.balls_dict.update(kwargs) if self.balls_dict == {} or sum(self.balls_dict.values()) < 1: print('Must enter at least one ball.') e...
Python
zaydzuhri_stack_edu_python
function bug_fixing_recency br prev_reports begin set most_rr = call most_recent_report prev_reports if br and most_rr begin return 1 / decimal call get_months_between fixdate fixdate + 1 end return 0 end function
def bug_fixing_recency(br, prev_reports): most_rr = most_recent_report(prev_reports) if br and most_rr: return 1 / float( get_months_between(br.fixdate, most_rr.fixdate) + 1 ) return 0
Python
nomic_cornstack_python_v1
import config import glob import tensorflow as tf import re import cv2 import numpy as np comment 含中文路径读取图片方法 function cv_imread filepath begin set img = call imdecode call fromfile filepath dtype=uint8 - 1 return img end function comment 把数据打包,转换成tfrecords格式,以便后续高效读取 function convert_to_tfrecords begin set writer = ca...
import config import glob import tensorflow as tf import re import cv2 import numpy as np #含中文路径读取图片方法 def cv_imread(filepath): img = cv2.imdecode(np.fromfile(filepath,dtype=np.uint8),-1) return img #把数据打包,转换成tfrecords格式,以便后续高效读取 def convert_to_tfrecords(): writer = tf.python_io.TFRecordWriter('./data.tf...
Python
zaydzuhri_stack_edu_python
comment -*- coding: UTF-8 -*- string @author:liux @time:2020/07/23 @func: 创建数据样本、简单示例,过滤网站的恶意留言 import numpy as np class SimpleBayes begin decorator staticmethod function create_dataset begin set postingList = list list string my string dog string has string flea string problems string help string please list string ma...
# -*- coding: UTF-8 -*- """ @author:liux @time:2020/07/23 @func: 创建数据样本、简单示例,过滤网站的恶意留言 """ import numpy as np class SimpleBayes: @staticmethod def create_dataset(): postingList = [['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'], ['maybe', 'not', 'take', 'him', 'to',...
Python
zaydzuhri_stack_edu_python
function move l dx dy begin global x y for _ in range 1 l + 1 begin set y = y + dy set x = x + dx if tuple x y in memo begin return true end else begin add memo tuple x y end end return false end function set memo = set set s = split input string , set tuple x y = tuple 0 0 comment north set d = 0 for ss in s begin set...
def move(l,dx,dy): global x,y for _ in range(1, l+1): y += dy x += dx if (x,y) in memo: return True else: memo.add((x,y)) return False memo = set() s = input().split(", ") x,y = 0,0 d = 0 #north for ss in s: t = ss[0] l = int(ss[1:]) tl = t is 'L' if d is 0: d = 1 if tl else 2 elif d is 1: d = 3 if t...
Python
zaydzuhri_stack_edu_python
function _join_data_lines lines skip begin string Join all the data lines into a byte string set lines = list map strip lines set blank_lines = call count_header_blanks lines skip set body = lines at slice skip + blank_lines + 2 : : return join string body end function
def _join_data_lines(lines, skip): """ Join all the data lines into a byte string """ lines = list(map(str.strip, lines)) blank_lines = count_header_blanks(lines, skip) body = lines[skip + blank_lines + 2:] return '\n'.join(body)
Python
jtatman_500k
comment encoding:utf-8 import multiprocessing import logging call basicConfig level=DEBUG set logger = call getLogger class MonitorProcesos begin function __init__ self begin set busquedas_pendientes = queue set resultados_pendientes = queue set contador = queue end function comment crear búsqueda function activar_busq...
#encoding:utf-8 import multiprocessing import logging logging.basicConfig(level=logging.DEBUG) logger=logging.getLogger() class MonitorProcesos: def __init__(self): self.busquedas_pendientes=multiprocessing.Queue() self.resultados_pendientes=multiprocessing.Queue() self.contador=multipr...
Python
zaydzuhri_stack_edu_python
function have_only_two_digits_number_equal password begin for tuple index digits in enumerate password at slice 0 : - 1 : begin if digits == password at index + 1 begin if index == 0 or digits != password at index - 1 and index == length password - 2 or digits != password at index + 2 begin return true end end end retu...
def have_only_two_digits_number_equal(password): for index, digits in enumerate(password[0:-1]): if digits == password[index+1]: if (index == 0 or digits != password[index-1]) and (index==len(password)-2 or digits != password[index+2]): return True return False def never_de...
Python
zaydzuhri_stack_edu_python
function get_longer old new begin try begin set pngs = tuple string \begin string \end set old_parts = set comprehension x for x in split sep_RE old if x if x not in pngs set new_parts = set comprehension y for y in split sep_RE new if y if y not in pngs if new_parts == old_parts and new != old and any generator expres...
def get_longer(old, new): try: pngs = ('\\begin', '\\end') old_parts = {x for x in sep_RE.split(old) if x if x not in pngs} new_parts = {y for y in sep_RE.split(new) if y if y not in pngs} if new_parts == old_parts and new != old and any('\\begin' in c for c ...
Python
nomic_cornstack_python_v1
set x = string input string > set sorted_list = replace x string string set sorted_list = sorted sorted_list set x_sorted = join string sorted_list print x_sorted
x = str(input(">")) sorted_list = x.replace(" ", "") sorted_list = sorted(sorted_list) x_sorted = "".join(sorted_list) print(x_sorted)
Python
zaydzuhri_stack_edu_python
class Foo extends object begin string docstring for Foo. decorator classmethod function class_method s begin print call repr s end function function member_method self begin print call repr self end function end class set f = call Foo call member_method call class_method
class Foo(object): """docstring for Foo.""" @classmethod def class_method(s): print(repr(s)) def member_method(self): print(repr(self)) f=Foo() f.member_method() f.class_method()
Python
zaydzuhri_stack_edu_python
function st self i j s begin if s == string / begin set first = tuple i + 1 j set second = tuple i j + 1 end else if s == string \ begin set first = tuple i j set second = tuple i + 1 j + 1 end return tuple first second end function
def st(self, i, j, s): if s == '/': first = i+1, j second = i, j+1 elif s == '\\': first = i, j second = i+1, j+1 return first, second
Python
nomic_cornstack_python_v1
string Binary Search from random import randrange comment COUNT = 0 #counter for counting number of steps function binarysearch data key begin string Simple recursive binary search. Returns the value that was searched for comment global COUNT #access count on global scope comment COUNT = COUNT + 1 #increment count on e...
""" Binary Search """ from random import randrange # COUNT = 0 #counter for counting number of steps def binarysearch(data, key): """ Simple recursive binary search. Returns the value that was searched for """ # global COUNT #access count on global scope # COUNT = COUNT + 1 #increment ...
Python
zaydzuhri_stack_edu_python
function nested_regions query_set search_space buffer_radius minimum_corner maximum_corner begin function region_indices points low_side high_side begin string return indices of all points between low_side and high_side set all_masks = list comment we can cheat a little here. if no points would be excluded by applying...
def nested_regions( query_set, search_space, buffer_radius, minimum_corner, maximum_corner): def region_indices(points, low_side, high_side): """ return indices of all points between low_side and high_side """ all_masks = [] # we can ...
Python
nomic_cornstack_python_v1
comment Your code here! for x in start_list begin append square_list x ^ 2 end sort square_list
# Your code here! for x in start_list: square_list.append(x ** 2) square_list.sort()
Python
zaydzuhri_stack_edu_python
import configparser import psycopg2 from sql_tables import drop_table_queries , create_table_queries function drop_tables cur conn begin string Function drops existing tables listed in 'drop_table_queries' list from 'sql_tables.py'. for query in drop_table_queries begin execute cur query commit conn end end function fu...
import configparser import psycopg2 from sql_tables import drop_table_queries, create_table_queries def drop_tables(cur, conn): """Function drops existing tables listed in 'drop_table_queries' list from 'sql_tables.py'.""" for query in drop_table_queries: cur.execute(query) conn.commit() def...
Python
zaydzuhri_stack_edu_python
comment -*- coding: utf-8 -*- string Task one import random import time comment Variable for counting the # of times quincunx appears. set count = 0 set start = time comment n counts the # of times of rolling the dice. for n in range 1 10 ^ 6 + 1 begin set k = call randrange 1 7 comment If quincunx appears, count. if k...
# -*- coding: utf-8 -*- """ Task one """ import random import time count = 0 # Variable for counting the # of times quincunx appears. start = time.time() for n in range(1,10**6+1): # n counts the # of times of rolling the dice. k = random.randrange(1,7) if k == 5: # If quincunx appears, count. cou...
Python
zaydzuhri_stack_edu_python
function __coord_cqt_hz n fmin=none bins_per_octave=12 **_kwargs begin string Get CQT bin frequencies if fmin is none begin set fmin = call note_to_hz string C1 end comment we drop by half a bin so that CQT bins are centered vertically return call cqt_frequencies n + 1 fmin=fmin / 2.0 ^ 0.5 / bins_per_octave bins_per_o...
def __coord_cqt_hz(n, fmin=None, bins_per_octave=12, **_kwargs): '''Get CQT bin frequencies''' if fmin is None: fmin = core.note_to_hz('C1') # we drop by half a bin so that CQT bins are centered vertically return core.cqt_frequencies(n+1, fmin=fmin / 2.0**(0.5/bi...
Python
jtatman_500k
function availableShips passengerCount begin set total_ships = list set next = string https://swapi-api.hbtn.io/api/starships/ while next begin set r = get requests next if status_code != 200 begin break end set data = json r set ships = data at string results for ship in ships begin set passengers = replace ship at s...
def availableShips(passengerCount): total_ships = [] next = "https://swapi-api.hbtn.io/api/starships/" while next: r = requests.get(next) if r.status_code != 200: break data = r.json() ships = data['results'] for ship in ships: passengers = shi...
Python
nomic_cornstack_python_v1
function toString self begin string Converts the data about this view widget into a string value. :return <str> set xprofile = call toXml call xmlindent xprofile return call tostring xprofile end function
def toString(self): """ Converts the data about this view widget into a string value. :return <str> """ xprofile = self.toXml() projex.text.xmlindent(xprofile) return ElementTree.tostring(xprofile)
Python
jtatman_500k
from gurobipy import * from functions import powerset class TSP begin function __init__ self begin set model = model end function function setVars self pending_nodes begin set tuple x nodes = tuple dict list for u in pending_nodes begin append nodes u for v in pending_nodes begin if u < v begin set x at tuple u v = c...
from gurobipy import * from functions import powerset class TSP: def __init__(self): self.model = Model() def setVars(self, pending_nodes): self.x, self.nodes = {}, [] for u in pending_nodes: self.nodes.append(u) for v in pending_nodes: if u <...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment The line at the very top tells the cpu that will be excuting this job comment which python to use and how to find it. comment Without that line this sould just be a simple text file and you would comment specifically need to type on the command line: python name_of_file.py comment T...
#!/usr/bin/env python ####################################################################################### # The line at the very top tells the cpu that will be excuting this job # which python to use and how to find it. # Without that line this sould just be a simple text file and you would # specifically need to ...
Python
zaydzuhri_stack_edu_python
function int_to_padded_hex_byte integer begin string Convert an int to a 0-padded hex byte string example: 65 == 41, 10 == 0A Returns: The hex byte as string (ex: "0C") set to_hex = hexadecimal integer set xpos = find to_hex string x set hex_byte = upper to_hex at slice xpos + 1 : length to_hex : if length hex_byte == ...
def int_to_padded_hex_byte(integer): """ Convert an int to a 0-padded hex byte string example: 65 == 41, 10 == 0A Returns: The hex byte as string (ex: "0C") """ to_hex = hex(integer) xpos = to_hex.find('x') hex_byte = to_hex[xpos+1 : len(to_hex)].upper() if len(hex_byte)...
Python
jtatman_500k
import numpy as np from matplotlib import pyplot as plt set f = 20 set fs = 50 set m = array range 0 100 0.1 set x = call rand 500 set X = list set w = array range - 1 * pi pi 0.01 * pi for i in range length w begin set s = 0 for n in range 0 length x begin set s = s + x at n * exp - 1 * 1j * w at i * n end append X s...
import numpy as np from matplotlib import pyplot as plt f=20 fs=50 m=np.arange(0,100,0.1) x=np.random.rand(500) X=[] w=np.arange(-1*np.pi,np.pi,0.01*np.pi) for i in range (len(w)): s=0 for n in range (0,len(x)) : s=s+x[n]*np.exp(-1*1j*w[i]*n) X.append(s) X[i]=s plt.subplot(211) plt.stem(w,np.abs(X)) plt.subplot(2...
Python
zaydzuhri_stack_edu_python
import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression import pickle comment loading the data set cars = read csv string D:/Python/Assignments codes/3.2 Multi Linear/Cars.csv comment 1. VOL: Cubic feet of cab space comment 2. HP: Engine horsepower comment 3. MPG: Average miles per gall...
import pandas as pd import numpy as np from sklearn.linear_model import LinearRegression import pickle # loading the data cars = pd.read_csv('D:/Python/Assignments codes/3.2 Multi Linear/Cars.csv') # 1. VOL: Cubic feet of cab space # 2. HP: Engine horsepower # 3. MPG: Average miles per gallon # ...
Python
zaydzuhri_stack_edu_python
function name self name begin set _name = name end function
def name(self, name): self._name = name
Python
nomic_cornstack_python_v1
from methods import * function main begin set g = call build_graph_from_file string input.txt print string Drzewo spinające dfs call spanning_tree g print string Czy spójny comment is_connected(g) set wg = call build_weighted_digraph_from_file string input4.txt comment wg.getEdgesByWeightsAsc() print string Kruskal com...
from methods import * def main(): g = build_graph_from_file('input.txt') print("Drzewo spinające dfs") spanning_tree(g) print("Czy spójny") #is_connected(g) wg = build_weighted_digraph_from_file('input4.txt') #wg.getEdgesByWeightsAsc() print("Kruskal") #kruskal(wg) dg = bui...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/python3 comment coding: utf-8 string Funciones utilizadas para entrenar una Red import logging from keras.models import Sequential from keras.layers import Dense , Dropout from keras.utils.np_utils import to_categorical from keras.callbacks import EarlyStopping from sklearn.model_selection import trai...
#!/usr/bin/python3 # coding: utf-8 """ Funciones utilizadas para entrenar una Red """ import logging from keras.models import Sequential from keras.layers import Dense, Dropout from keras.utils.np_utils import to_categorical from keras.callbacks import EarlyStopping from sklearn.model_selection import train_test_split ...
Python
zaydzuhri_stack_edu_python
comment !/usr/bin/env python comment coding: utf-8 comment In[1]: set word = string banana comment In[3]: set index = count word string a comment In[4]: index
#!/usr/bin/env python # coding: utf-8 # In[1]: word = 'banana' # In[3]: index = word.count('a') # In[4]: index
Python
zaydzuhri_stack_edu_python
import datetime function add_gigasecond dateTimeObj begin set a = dateTimeObj + time delta 0 10 ^ 9 return a end function
import datetime def add_gigasecond(dateTimeObj): a = dateTimeObj + datetime.timedelta(0,10**9) return a
Python
zaydzuhri_stack_edu_python
function grad_basis self bc index=s_ at slice : : begin comment (NQ,NC,ldof) set gphi0 = call grad_basis bc set shape = list shape set shape at - 2 = shape at - 2 + 1 set gphi = zeros shape dtype=string float comment 把不同类型的自由度区分开来 set dofFlags = call dof_flags_1 comment 面不连续自由度的编号 set tuple idx = call nonzero dofFlag...
def grad_basis(self, bc, index=np.s_[:]): gphi0 = self.space.grad_basis(bc) #(NQ,NC,ldof) shape = list(gphi0.shape) shape[-2]+=1 gphi = np.zeros(shape,dtype='float') dofFlags = self.dof_flags_1() # 把不同类型的自由度区分开来 idx, = np.nonzero(dofFlags[0]) # 面不连续自由度的编号 #构建面上不连...
Python
nomic_cornstack_python_v1
function magnetisation field begin set norm_field = call Field mesh dim=1 value=array != 0 set volume = call integral norm_field * dV direction=string xyz return call integral field * dV / volume direction=string xyz end function
def magnetisation(field): norm_field = df.Field(field.mesh, dim=1, value=(field.norm.array != 0)) volume = df.integral(norm_field * df.dV, direction='xyz') return df.integral(field * df.dV / volume, direction='xyz')
Python
nomic_cornstack_python_v1
comment -*- coding: utf-8 -*- import math set a = integer input string Digite a: set b = integer input string Digite b: set anterior = a set atual = b set resto = anterior % atual while resto != 0 begin set anterior = atual set atual = resto set resto = anterior % atual end print string MDC(%d,%d)=%d % tuple a b atual
# -*- coding: utf-8 -*- import math a=int(input('Digite a:')) b=int(input('Digite b:')) anterior=a atual=b resto=anterior%atual while resto!=0: anterior=atual atual=resto resto=anterior%atual print("MDC(%d,%d)=%d"%(a,b,atual))
Python
zaydzuhri_stack_edu_python
comment coding: utf-8 function count list begin return length list end function function min iterable key=lambda x -> x default=0 begin if length iterable == 0 begin raise call ValueError string Argument `iterable`'s length should be at least 1. end set ret = default for elem in iterable begin if call key ret > call ke...
# coding: utf-8 def count(list): return len(list) def min(iterable, key = lambda x: x, default = 0): if len(iterable) == 0: raise ValueError("Argument `iterable`'s length should be at least 1.") ret = default for elem in iterable: if key(ret) > key(elem) : ret = elem return ret def max(iterable, ...
Python
zaydzuhri_stack_edu_python
function _get_mpls_enabled self begin return __mpls_enabled end function
def _get_mpls_enabled(self): return self.__mpls_enabled
Python
nomic_cornstack_python_v1
function main height begin if height == 1 begin set row = list 0 1 0 end end function
def main(height): if height == 1: row = [0,1,0]
Python
zaydzuhri_stack_edu_python
import os import shutil import tempfile from functools import wraps from homework_checker.base import Assignment comment # Chcemy napisać sprawdzarkę do testu znajomości stolic europejskich. comment # Format listy stolic taki jak w pliku stolice.csv comment # Format pytań taki jak w pliku pytania.csv comment # Format o...
import os import shutil import tempfile from functools import wraps from homework_checker.base import Assignment # # Chcemy napisać sprawdzarkę do testu znajomości stolic europejskich. # # Format listy stolic taki jak w pliku stolice.csv # # Format pytań taki jak w pliku pytania.csv # # Format odpowiedzi taki jak w p...
Python
zaydzuhri_stack_edu_python
function addAtTail self val begin set cur = call linkNode val comment first node if tail == none begin set next = cur set prev = head set tail = cur end else begin set next = cur set prev = tail comment update tail set tail = cur end end function comment self.printList()
def addAtTail(self, val): cur = linkNode(val) if self.tail == None: # first node self.head.next = cur cur.prev = self.head self.tail = cur else: self.tail.next = cur cur.prev = self.tail self.tail = cur # update tail ...
Python
nomic_cornstack_python_v1
import pytz import time import datetime set tz = call timezone string America/New_York set a = string format time now tz string %Y-%m-%d %H:%M:%S print a set a = now tz + time delta days=1 print a set a = string format time now string %Y-%m-%d %H:%M:%S print a print today set dd = today - time delta days=1 print dd com...
import pytz import time import datetime tz = pytz.timezone('America/New_York') a = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S") print(a) a = datetime.datetime.now(tz) + datetime.timedelta(days=1) print(a) a = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") print(a) print(datetime.date.today()) dd = dat...
Python
zaydzuhri_stack_edu_python
import tensorflow as tf import tensorflow.examples.tutorials.mnist.input_data as input_data set mnist = call read_data_sets string MNIST_data/ one_hot=true set x = call placeholder float32 list none 784 set y_actual = call placeholder float32 shape=list none 10 comment 初始化权值W set W = call Variable zeros list 784 10 com...
import tensorflow as tf import tensorflow.examples.tutorials.mnist.input_data as input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) x = tf.placeholder(tf.float32, [None, 784]) y_actual = tf.placeholder(tf.float32, shape=[None, 10]) W = tf.Variable(tf.zeros([784,10])) #初始化权值W b = tf.V...
Python
zaydzuhri_stack_edu_python
function _resolve_artifact_value_operator self op begin set resolved_artifact = call resolve expression if not is instance resolved_artifact ValueArtifact begin raise call ValueError string ArtifactValueOperator expects the expression to evaluate to a value artifact.Got { type resolved_artifact } end return read resolv...
def _resolve_artifact_value_operator( self, op: placeholder_pb2.ArtifactValueOperator) -> str: resolved_artifact = self.resolve(op.expression) if not isinstance(resolved_artifact, value_artifact.ValueArtifact): raise ValueError("ArtifactValueOperator expects the expression " "...
Python
nomic_cornstack_python_v1
comment Function to add two numbers function add num1 num2 begin string This function perform addition if type num1 == type string s or type num2 == type string s begin return 0 end set addition = num1 + num2 return addition end function comment Function to subtract two numbers function subtract num1 num2 begin string ...
# Function to add two numbers def add(num1, num2): "This function perform addition" if type(num1) == type("s") or type(num2) == type("s"): return 0 addition = num1 + num2 return addition # Function to subtract two numbers def subtract(num1, num2): "This function perform subtraction" if...
Python
zaydzuhri_stack_edu_python
function class_adjustment self begin set ABILITIES_ORDER = call get_abilities_order ch_class for key in SAVES_LVLS begin set SAVES_LVLS at key = call get_class_saves key ch_class end set CLASS_SKILLS = call get_class_skills ch_class set SKILL_POINTS_MOD = call get_skillp_modifier ch_class set HIT_DIE = call get_hit_die...
def class_adjustment(self): self.ABILITIES_ORDER = fetch_data.get_abilities_order(self.ch_class) for key in self.SAVES_LVLS: self.SAVES_LVLS[key] = fetch_data.get_class_saves(key, self.ch_class) self.CLASS_SKILLS = fetch_data.get_class_skills(self.ch_class) self.SKILL_POINT...
Python
nomic_cornstack_python_v1
function __cmp__ self other begin for i in range 0 call dimensionality begin if self at i < other at i begin return - 1 end if self at i > other at i begin return 1 end end return 0 end function
def __cmp__(self, other): for i in range(0, self.dimensionality()): if self[i] < other[i]: return -1 if self[i] > other[i]: return 1 return 0
Python
nomic_cornstack_python_v1
string print(type('7')) print(type(7)) print(type(7.1)) print(isinstance('7',str)) print(isinstance(7,int)) print(isinstance(7.1,float)) print(isinstance(7,str)) print(isinstance('7',int)) print(isinstance('7.1',float)) print(type('7') == str) print(type(7) == int) print(type(7.1) == float) print(type(7) == str) print(...
""" print(type('7')) print(type(7)) print(type(7.1)) print(isinstance('7',str)) print(isinstance(7,int)) print(isinstance(7.1,float)) print(isinstance(7,str)) print(isinstance('7',int)) print(isinstance('7.1',float)) print(type('7') == str) print(type(7) == int) print(type(7.1) == float) print(type(7) == str) pri...
Python
zaydzuhri_stack_edu_python
comment generate files for images, V-A values and landmark points for AFEW-VA dataset import os import os.path as path import zipfile import json set currentDir = get current directory comment create the data folder that will hold all the data files set dataFolder = join path absolute path path join path currentDir str...
#generate files for images, V-A values and landmark points for AFEW-VA dataset import os import os.path as path import zipfile import json currentDir = os.getcwd() #create the data folder that will hold all the data files dataFolder = path.join(path.abspath(path.join(currentDir,'..')), 'data/dataFolder') if not os.p...
Python
zaydzuhri_stack_edu_python
function main begin string Sets parameters set args_parser = call ArgumentParser call add_argument string -p string --predict required=true help=string Is it a prediction? call add_argument string --predict_file_name help=string Path to the prediction file required=false call add_argument string --output_folder help=st...
def main(): """ Sets parameters """ args_parser = argparse.ArgumentParser() args_parser.add_argument( "-p", "--predict", required=True, help="Is it a prediction?") args_parser.add_argument( '--predict_file_name', help='Path to the prediction f...
Python
nomic_cornstack_python_v1
function karat_test begin set failed = 0 for trial in range 100 begin set x = call randrange 100 10000 set y = call randrange 100 10000 if call karat x y != x * y begin set failed = failed + 1 end end end function
def karat_test(): failed = 0 for trial in range(100): x = randrange(100, 10000) y = randrange(100, 10000) if karat(x, y) != x*y: failed += 1
Python
nomic_cornstack_python_v1
function json_pretty self begin return dumps definition indent=4 cls=JSONEncoder end function
def json_pretty(self): return json.dumps(self.definition, indent=4, cls=JSONEncoder)
Python
nomic_cornstack_python_v1
from collections import defaultdict set N = integer input set xy = list comprehension list map int split input for i in range N set d = default dictionary int for tuple i tuple xi yi in enumerate xy begin for tuple j tuple xj yj in enumerate xy begin set tuple p q = tuple xi - xj yi - yj set d at tuple p q = d at tuple...
from collections import defaultdict N = int(input()) xy = [list(map(int, input().split())) for i in range(N)] d = defaultdict(int) for i, (xi, yi) in enumerate(xy): for j, (xj, yj) in enumerate(xy): p, q = xi - xj, yi - yj d[(p, q)] += 1 d.pop((0, 0)) ans = N for k in d: ans = min(ans, N-d[k]) print(ans...
Python
zaydzuhri_stack_edu_python
function forward self x begin set detection_feed = list x for layer in additional_layers begin set x = call layer x append detection_feed x end set tuple locs confs = call _reshape_bbox detection_feed loc conf return tuple locs confs end function
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: detection_feed = [x] for layer in self.additional_layers: x = layer(x) detection_feed.append(x) locs, confs = self._reshape_bbox(detection_feed, self.loc, self.conf) return locs, confs
Python
nomic_cornstack_python_v1
comment !/usr/bin/env python3 comment coding=utf-8 comment Author: @maris comment Created Time: May 18 2017 18:55:41 PM CST comment File Name:spider.py comment Description:把元数据同步到ipfs import sys import re import json import time import io import requests import ipfshttpclient import base64 comment 文档https://ipfs.io/ipn...
#!/usr/bin/env python3 #coding=utf-8 ######################################################################### # Author: @maris # Created Time: May 18 2017 18:55:41 PM CST # File Name:spider.py # Description:把元数据同步到ipfs ######################################################################### import sys import re impo...
Python
zaydzuhri_stack_edu_python
function __init__ self servers_lst alias=none session=none begin set session = session if alias begin set alias = alias end else begin set alias = call GetAlias session=session end set servers_lst = servers_lst end function
def __init__(self,servers_lst,alias=None,session=None): self.session = session if alias: self.alias = alias else: self.alias = clc.v2.Account.GetAlias(session=self.session) self.servers_lst = servers_lst
Python
nomic_cornstack_python_v1
function evaluate self begin function readJson begin set path_to_cand_file = join path _pathToData _candName set cand_list = loads read open path_to_cand_file string r set res = default dictionary list for id_cap in cand_list begin extend res at id_cap at string image_id id_cap at string captions end return res end fun...
def evaluate(self): def readJson(): path_to_cand_file = os.path.join(self._pathToData, self._candName) cand_list = json.loads(open(path_to_cand_file, 'r').read()) res = defaultdict(list) for id_cap in cand_list: res[id_cap['image_id']].extend(id_...
Python
nomic_cornstack_python_v1
from math import e import numpy as np import csv import pandas as pd from pandas import DataFrame from csv_handle import contain_row comment from csv_handle import contain_col from scipy.integrate import quad import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split comment ------------------...
from math import e import numpy as np import csv import pandas as pd from pandas import DataFrame from csv_handle import contain_row #from csv_handle import contain_col from scipy.integrate import quad import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split #--------------------Methods----...
Python
zaydzuhri_stack_edu_python
function _tagchain_is_linked self left_tag_name mid_tag_name estimators left_tag_val=true mid_tag_val=true begin for tuple _ est in estimators begin if call get_tag mid_tag_name == mid_tag_val begin return tuple true true end if not call get_tag left_tag_name == left_tag_val begin return tuple false false end end retur...
def _tagchain_is_linked( self, left_tag_name, mid_tag_name, estimators, left_tag_val=True, mid_tag_val=True, ): for _, est in estimators: if est.get_tag(mid_tag_name) == mid_tag_val: return True, True if not est.get_tag(...
Python
nomic_cornstack_python_v1
function record self record_meta begin if string ft.onto.base_ontology.Phrase not in keys record_meta begin set record_meta at string ft.onto.base_ontology.Phrase = set end end function
def record(self, record_meta: Dict[str, Set[str]]): if "ft.onto.base_ontology.Phrase" not in record_meta.keys(): record_meta["ft.onto.base_ontology.Phrase"] = set()
Python
nomic_cornstack_python_v1
function user_story_07 self begin for ind in values individuals begin if age >= 150 begin print string US07 - { name } is age { age } , which is over 150 years old, on line { _age_line } end end end function
def user_story_07(self): for ind in self.individuals.values(): if ind.age >= 150: print(f'US07 - {ind.name} is age {ind.age}, which is over 150 years old, on line {ind._age_line}')
Python
nomic_cornstack_python_v1
function load self index_start index_end begin debug format string Loading data buffer from indexes {} to {}. index_start index_end set index_start = index_start set index_end = index_end try begin assert index_start >= 0 and index_start < n_bursts_l1a and index_end > index_start end except AssertionError begin error s...
def load(self,index_start,index_end): logging.debug("Loading data buffer from indexes {} to {}.".format(index_start,index_end)) self.index_start=index_start self.index_end=index_end try: assert(self.index_start>=0 and self.index_start<self.n_bursts_l1a and self.index_end>s...
Python
nomic_cornstack_python_v1
function recv self begin set buf = call recvfrom 65565 set p = call Packet data=buf return p end function
def recv(self): self.buf = self.sock_in.recvfrom(65565) p = Packet(data=self.buf) return p
Python
nomic_cornstack_python_v1