id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
21,927
from .validate import Validator, validated from collections import ChainMap class Structure(metaclass=StructureMeta): _fields = () _types = () def __setattr__(self, name, value): if name.startswith('_') or name in self._fields: super().__setattr__(name, value) else: r...
null
21,928
from abc import ABC, abstractmethod class TableFormatter(ABC): def headings(self, headers): pass def row(self, rowdata): pass def print_table(records, fields, formatter): if not isinstance(formatter, TableFormatter): raise RuntimeError('Expected a TableFormatter') formatter.hea...
null
21,929
from inspect import signature from functools import wraps def enforce(**annotations): retcheck = annotations.pop('return_', None) def decorate(func): sig = signature(func) @wraps(func) def wrapper(*args, **kwargs): bound = sig.bind(*args, **kwargs) errors = [] ...
null
21,930
from inspect import signature from functools import wraps def add(x:Integer, y:Integer) -> Integer: return x + y
null
21,931
from inspect import signature from functools import wraps def div(x:Integer, y:Integer) -> Integer: return x / y
null
21,932
from inspect import signature from functools import wraps def sub(x, y): return x - y
null
21,933
import csv import logging def csv_as_dicts(lines, types, *, headers=None): return convert_csv(lines, lambda headers, row: { name: func(val) for name, func, val in zip(headers, types, row) }) The provided code snippet includes necessary dependencies for implementing the `read_csv_as_dicts` f...
Read CSV data into a list of dictionaries with optional type conversion
21,934
import csv import logging def csv_as_instances(lines, cls, *, headers=None): return convert_csv(lines, lambda headers, row: cls.from_row(row)) The provided code snippet includes necessary dependencies for implementing the `read_csv_as_instances` function. Write a Python function `def read_cs...
Read CSV data into a list of instances
21,935
from validate import Validator, validated from collections import ChainMap class Validator: def check(cls, value): return value def validated(func): sig = signature(func) # Gather the function annotations annotations = { name:val for name, val in func.__annotations__.items() ...
Class decorator that scans a class definition for Validators and builds a _fields variable that captures their definition order.
21,936
from validate import Validator, validated from collections import ChainMap class Structure(metaclass=StructureMeta): _fields = () _types = () def __setattr__(self, name, value): if name.startswith('_') or name in self._fields: super().__setattr__(name, value) else: ra...
null
21,937
from inspect import signature from functools import wraps def isvalidator(item): return isinstance(item, type) and issubclass(item, Validator) def validated(func): sig = signature(func) # Gather the function annotations annotations = { name:val for name, val in func.__annotations__.items() ...
null
21,944
import os import time The provided code snippet includes necessary dependencies for implementing the `follow` function. Write a Python function `def follow(filename)` to solve the following problem: Generator that produces a sequence of lines being written at the end of a file. Here is the function: def follow(filen...
Generator that produces a sequence of lines being written at the end of a file.
21,945
import csv def csv_as_dicts(lines, types, *, headers=None): return convert_csv(lines, lambda headers, row: { name: func(val) for name, func, val in zip(headers, types, row) }) The provided code snippet includes necessary dependencies for implementing the `read_csv_as_dicts` function. Write ...
Read CSV data into a list of dictionaries with optional type conversion
21,946
import csv def csv_as_instances(lines, cls, *, headers=None): return convert_csv(lines, lambda headers, row: cls.from_row(row)) The provided code snippet includes necessary dependencies for implementing the `read_csv_as_instances` function. Write a Python function `def read_csv_as_instances(...
Read CSV data into a list of instances
21,947
import csv The provided code snippet includes necessary dependencies for implementing the `read_rides_as_tuples` function. Write a Python function `def read_rides_as_tuples(filename)` to solve the following problem: Read the bus ride data as a list of tuples Here is the function: def read_rides_as_tuples(filename): ...
Read the bus ride data as a list of tuples
21,948
import csv The provided code snippet includes necessary dependencies for implementing the `read_rides_as_dicts` function. Write a Python function `def read_rides_as_dicts(filename)` to solve the following problem: Read the bus ride data as a list of dicts Here is the function: def read_rides_as_dicts(filename): ...
Read the bus ride data as a list of dicts
21,949
import csv class Row: # Uncomment to see effect of slots # __slots__ = ('route', 'date', 'daytype', 'rides') def __init__(self, route, date, daytype, rides): self.route = route self.date = date self.daytype = daytype self.rides = rides The provided code snippet includes nece...
Read the bus ride data as a list of instances
21,950
def portfolio_cost(filename): total_cost = 0.0 with open(filename) as f: for line in f: fields = line.split() try: nshares = int(fields[1]) price = float(fields[2]) total_cost = total_cost + nshares * price # This cat...
null
21,953
from abc import ABC, abstractmethod class TableFormatter(ABC): def headings(self, headers): def row(self, rowdata): from .formats.text import TextTableFormatter from .formats.csv import CSVTableFormatter from .formats.html import HTMLTableFormatter def print_table(records, fields, formatter): if not isin...
null
21,954
from abc import ABC, abstractmethod from .formats.text import TextTableFormatter from .formats.csv import CSVTableFormatter from .formats.html import HTMLTableFormatter class ColumnFormatMixin: def row(self, rowdata): class UpperHeadersMixin: def headings(self, headers): class TextTableFormatter(TableFormatt...
null
21,962
from validate import Validator, validated from collections import ChainMap class Structure(metaclass=StructureMeta): _fields = () _types = () def __setattr__(self, name, value): if name.startswith('_') or name in self._fields: super().__setattr__(name, value) else: ra...
null
21,964
from abc import ABC, abstractmethod class TextTableFormatter(TableFormatter): def headings(self, headers): print(' '.join('%10s' % h for h in headers)) print(('-'*10 + ' ')*len(headers)) def row(self, rowdata): print(' '.join('%10s' % d for d in rowdata)) class CSVTableFormatter(TableFor...
null
21,972
from abc import ABC, abstractmethod class TableFormatter(ABC): def headings(self, headers): pass def row(self, rowdata): pass def print_table(records, fields, formatter): if not isinstance(formatter, TableFormatter): raise TypeError('Expected a TableFormatter') formatter.headin...
null
21,973
from abc import ABC, abstractmethod class TextTableFormatter(TableFormatter): def headings(self, headers): def row(self, rowdata): class CSVTableFormatter(TableFormatter): def headings(self, headers): def row(self, rowdata): class HTMLTableFormatter(TableFormatter): def headings(self, headers):...
null
21,974
import csv from abc import ABC, abstractmethod class DictCSVParser(CSVParser): def __init__(self, types): def make_record(self, headers, row): def read_csv_as_dicts(filename, types): parser = DictCSVParser(types) return parser.parse(filename)
null
21,975
import csv from abc import ABC, abstractmethod class InstanceCSVParser(CSVParser): def __init__(self, cls): self.cls = cls def make_record(self, headers, row): return self.cls.from_row(row) def read_csv_as_instances(filename, cls): parser = InstanceCSVParser(cls) return parser.parse(fil...
null
21,978
def print_table(records, fields, formatter): formatter.headings(fields) for r in records: rowdata = [getattr(r, fieldname) for fieldname in fields] formatter.row(rowdata)
null
21,979
class TextTableFormatter(TableFormatter): def headings(self, headers): def row(self, rowdata): class CSVTableFormatter(TableFormatter): def headings(self, headers): def row(self, rowdata): class HTMLTableFormatter(TableFormatter): def headings(self, headers): def row(self, rowdata): def c...
null
21,980
import csv The provided code snippet includes necessary dependencies for implementing the `read_csv_as_dicts` function. Write a Python function `def read_csv_as_dicts(filename, types)` to solve the following problem: Read a CSV file into a list of dicts with column type conversion Here is the function: def read_csv_...
Read a CSV file into a list of dicts with column type conversion
21,981
import csv The provided code snippet includes necessary dependencies for implementing the `read_csv_as_instances` function. Write a Python function `def read_csv_as_instances(filename, cls)` to solve the following problem: Read a CSV file into a list of instances Here is the function: def read_csv_as_instances(filen...
Read a CSV file into a list of instances
21,982
import sys import random chars = '\|/' def draw(rows, columns): for r in range(rows): print(''.join(random.choice(chars) for _ in range(columns)))
null
21,984
class TextTableFormatter(TableFormatter): def headings(self, headers): print(' '.join('%10s' % h for h in headers)) print(('-'*10 + ' ')*len(headers)) def row(self, rowdata): print(' '.join('%10s' % d for d in rowdata)) class CSVTableFormatter(TableFormatter): def headings(self, head...
null
21,987
def typedproperty(name, expected_type): private_name = '_' + name @property def value(self): return getattr(self, private_name) @value.setter def value(self, val): if not isinstance(val, expected_type): raise TypeError(f'Expected {expected_type}') setattr(self...
null
21,989
from abc import ABC, abstractmethod class TextTableFormatter(TableFormatter): def headings(self, headers): def row(self, rowdata): class CSVTableFormatter(TableFormatter): def headings(self, headers): def row(self, rowdata): class HTMLTableFormatter(TableFormatter): def headings(self, headers):...
null
21,990
import csv from abc import ABC, abstractmethod class DictCSVParser(CSVParser): def __init__(self, types): self.types = types def make_record(self, headers, row): return { name: func(val) for name, func, val in zip(headers, self.types, row) } def read_csv_as_dicts(filename, types): parser = ...
null
21,992
def print_table(records, fields): # Print the table headers in a 10-character wide field for fieldname in fields: print('%10s' % fieldname, end=' ') print() # Print the separator bars print(('-'*10 + ' ')*len(fields)) # Output the table contents for r in records: for fiel...
null
21,993
class Stock: types = (str, int, float) def __init__(self, name, shares, price): self.name = name self.shares = shares self.price = price def from_row(cls, row): values = [func(val) for func, val in zip(cls.types, row)] return cls(*values) def cost(self): r...
Read a CSV file of stock data into a list of Stocks
21,996
def logged(func): print('Adding logging to', func.__name__) def wrapper(*args,**kwargs): print('Calling', func.__name__) return func(*args,**kwargs) return wrapper
null
21,997
from logcall import logged def add(x,y): return x+y
null
21,998
from logcall import logged def sub(x,y): return x-y
null
21,999
from inspect import signature def isvalidator(item): return isinstance(item, type) and issubclass(item, Validator) def validated(func): sig = signature(func) # Gather the function annotations annotations = { name:val for name, val in func.__annotations__.items() if isvalidator(val)...
null
22,001
class Integer(Typed): expected_type = int from inspect import signature def div(x:Integer, y:Integer) -> Integer: return x / y
null
22,002
from functools import wraps logged = logformat('Calling {func.__name__}') def logformat(fmt): def logged(func): print('Adding logging to', func.__name__) @wraps(func) def wrapper(*args,**kwargs): print(fmt.format(func=func)) return func(*args, **kwargs) retur...
null
22,003
from logcall import logged, logformat def add(x,y): return x+y
null
22,004
from logcall import logged, logformat def sub(x,y): return x-y
null
22,005
from logcall import logged, logformat def mul(x,y): return x*y
null
22,008
class Integer(Typed): from inspect import signature from functools import wraps def add(x:Integer, y:Integer) -> Integer: return x + y
null
22,009
class Integer(Typed): expected_type = int from inspect import signature from functools import wraps def div(x:Integer, y:Integer) -> Integer: return x / y
null
22,014
import csv def read_portfolio(filename): portfolio = [] with open(filename) as f: rows = csv.reader(f) headers = next(rows) for row in rows: record = { 'name' : row[0], 'shares' : int(row[1]), 'price' : float(row[2]) ...
null
22,015
class Stock: def __init__(self, name, shares, price): self.name = name self.shares = shares self.price = price def cost(self): return self.shares * self.price def sell(self, nshares): self.shares -= nshares The provided code snippet includes necessary dependencies fo...
Read a CSV file of stock data into a list of Stocks
22,016
The provided code snippet includes necessary dependencies for implementing the `print_portfolio` function. Write a Python function `def print_portfolio(portfolio)` to solve the following problem: Make a nicely formatted table showing stock data Here is the function: def print_portfolio(portfolio): ''' Make ...
Make a nicely formatted table showing stock data
22,023
import os import time import csv def receive(expected_type): msg = yield assert isinstance(msg, expected_type), 'Expected type %s' % (expected_type) return msg from functools import wraps def printer(): while True: item = yield from receive(object) print(item)
null
22,024
from socket import * from select import select from collections import deque from types import coroutine tasks = deque() recv_wait = {} send_wait = {} def run(): while any([tasks, recv_wait, send_wait]): while not tasks: can_recv, can_send, _ = select(recv_wait, send_wait, []) for...
null
22,025
from socket import * from select import select from collections import deque from types import coroutine tasks = deque() class GenSocket: def __init__(self, sock): def accept(self): def recv(self, maxsize): def send(self, data): def __getattr__(self, name): async def tcp_server(address, ha...
null
22,026
from socket import * from select import select from collections import deque from types import coroutine async def echo_handler(client, address): print('Connection from', address) while True: data = await client.recv(1000) if not data: break await client.send(b'GOT:' + data)...
null
22,027
from inspect import signature from functools import wraps def isvalidator(item): def validated(func): sig = signature(func) # Gather the function annotations annotations = { name:val for name, val in func.__annotations__.items() if isvalidator(val) } # Get the return annotation (i...
null
22,032
from socket import * from select import select from collections import deque tasks = deque() recv_wait = {} send_wait = {} def run(): while any([tasks, recv_wait, send_wait]): while not tasks: can_recv, can_send, _ = select(recv_wait, send_wait, []) for s in can_recv: ...
null
22,033
from socket import * from select import select from collections import deque tasks = deque() class GenSocket: def __init__(self, sock): self.sock = sock def accept(self): yield 'recv', self.sock client, addr = self.sock.accept() return GenSocket(client), addr def recv(sel...
null
22,034
from socket import * from select import select from collections import deque def echo_handler(client, address): print('Connection from', address) while True: data = yield from client.recv(1000) if not data: break yield from client.send(b'GOT:' + data) print('Connection c...
null
22,035
from structure import Structure from validate import String, Integer, Float from cofollow import consumer, follow, receive from tableformat import create_formatter import csv def receive(expected_type): msg = yield assert isinstance(msg, expected_type), 'Expected type %s' % (expected_type) return msg def ...
null
22,036
from structure import Structure from validate import String, Integer, Float class Ticker(Structure): name = String() price = Float() date = String() time = String() change = Float() open = Float() high = Float() low = Float() volume = Integer() from cofollow import consumer, follow, ...
null
22,037
from structure import Structure from validate import String, Integer, Float class Ticker(Structure): from cofollow import consumer, follow, receive from tableformat import create_formatter import csv def receive(expected_type): def negchange(target): while True: record = yield from receive(Ticker) ...
null
22,038
from structure import Structure from validate import String, Integer, Float class Ticker(Structure): name = String() price = Float() date = String() time = String() change = Float() open = Float() high = Float() low = Float() volume = Integer() from cofollow import consumer, follow, ...
null
22,039
from abc import ABC, abstractmethod import csv import logging class DictCSVParser(CSVParser): def __init__(self, types): def make_record(self, headers, row): def read_csv_as_dicts(filename, types): parser = DictCSVParser(types) return parser.parse(filename)
null
22,040
from abc import ABC, abstractmethod import csv import logging class InstanceCSVParser(CSVParser): def __init__(self, cls): self.cls = cls def make_record(self, headers, row): return self.cls.from_row(row) def read_csv_as_instances(filename, cls): parser = InstanceCSVParser(cls) return p...
null
22,041
print(portfolio_cost('../../Data/portfolio3.dat')) def portfolio_cost(filename): total_cost = 0.0 with open(filename) as f: for line in f: fields = line.split() try: nshares = int(fields[1]) price = float(fields[2]) total_c...
null
22,046
import os import time from functools import wraps def follow(filename, target): with open(filename, 'r') as f: f.seek(0,os.SEEK_END) while True: line = f.readline() if line != '': target.send(line) else: time.sleep(0.1)
null
22,047
import os import time from functools import wraps def consumer(func): @wraps(func) def start(*args,**kwargs): f = func(*args,**kwargs) f.send(None) return f return start
null
22,048
import os import time from functools import wraps def printer(): while True: item = yield print(item)
null
22,054
from structure import Structure from cofollow import consumer, follow from tableformat import create_formatter import csv def to_csv(target): def producer(): while True: yield line reader = csv.reader(producer()) while True: line = yield target.send(next(reader))
null
22,055
from structure import Structure class Ticker(Structure): name = String() price = Float() date = String() time = String() change = Float() open = Float() high = Float() low = Float() volume = Integer() from cofollow import consumer, follow from tableformat import create_formatter impo...
null
22,056
from structure import Structure from cofollow import consumer, follow from tableformat import create_formatter import csv def negchange(target): while True: record = yield if record.change < 0: target.send(record)
null
22,057
from structure import Structure from cofollow import consumer, follow from tableformat import create_formatter import csv def create_formatter(name, column_formats=None, upper_headers=False): if name == 'text': formatter_cls = TextTableFormatter elif name == 'csv': formatter_cls = CSVTableForma...
null
22,067
import os import time import csv The provided code snippet includes necessary dependencies for implementing the `follow` function. Write a Python function `def follow(filename)` to solve the following problem: Generator that produces a sequence of lines being written at the end of a file. Here is the function: def f...
Generator that produces a sequence of lines being written at the end of a file.
22,069
from collections import deque tasks = deque() def run(): while tasks: task = tasks.popleft() try: next(task) tasks.append(task) except StopIteration: print('Task done')
null
22,070
from collections import deque def countdown(n): while n > 0: print('T-minus', n) yield n -= 1
null
22,071
from collections import deque def countup(n): x = 0 while x < n: print('Up we go', x) yield x += 1
null
22,073
from socket import * from select import select from collections import deque tasks = deque() def tcp_server(address, handler): sock = socket(AF_INET, SOCK_STREAM) sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) sock.bind(address) sock.listen(5) while True: yield 'recv', sock client, ad...
null
22,074
from socket import * from select import select from collections import deque def echo_handler(client, address): print('Connection from', address) while True: yield 'recv', client data = client.recv(1000) if not data: break yield 'send', client client.send(b'G...
null
22,075
from validate import Validator, validated class Validator: def check(cls, value): return value def validated(func): sig = signature(func) # Gather the function annotations annotations = { name:val for name, val in func.__annotations__.items() if isvalidator(val) } # G...
Class decorator that scans a class definition for Validators and builds a _fields variable that captures their definition order.
22,078
class Integer(Typed): expected_type = int from inspect import signature from functools import wraps def add(x:Integer, y:Integer) -> Integer: return x + y
null
22,083
def print_table(records, fields): print(' '.join('%10s' % fieldname for fieldname in fields)) print(('-'*10 + ' ')*len(fields)) for record in records: print(' '.join('%10s' % getattr(record, fieldname) for fieldname in fields))
null
22,085
import collections import csv class DataCollection(collections.abc.Sequence): def __init__(self, columns): self.column_names = list(columns) self.column_data = list(columns.values()) def __len__(self): return len(self.column_data[0]) def __getitem__(self, index): return dict(...
null
22,087
x = 42 print("Loaded simplemod") def foo(): print("x is %s" % x)
null
22,090
from abc import ABC, abstractmethod class TableFormatter(ABC): _formats = { } def __init_subclass__(cls): name = cls.__module__.split('.')[-1] TableFormatter._formats[name] = cls def headings(self, headers): pass def row(self, rowdata): pass def print_table(records, fiel...
null
22,091
from abc import ABC, abstractmethod class TableFormatter(ABC): _formats = { } def __init_subclass__(cls): name = cls.__module__.split('.')[-1] TableFormatter._formats[name] = cls def headings(self, headers): pass def row(self, rowdata): pass class ColumnFormatMixin: f...
null
22,099
from validate import Validator, validated class Structure: _fields = () _types = () def __setattr__(self, name, value): if name.startswith('_') or name in self._fields: super().__setattr__(name, value) else: raise AttributeError('No attribute %s' % name) def __rep...
null
22,105
import math import time import threading def minutes(tm): am_pm = tm[-2:] fields = tm[:-2].split(":") hour = int(fields[0]) minute = int(fields[1]) if hour == 12: hour = 0 if am_pm == 'pm': hour += 12 return hour*60 + minute def minutes_to_str(m): frac,m = math.modf(m) ...
null
22,106
import math import time import threading def minutes(tm): am_pm = tm[-2:] fields = tm[:-2].split(":") hour = int(fields[0]) minute = int(fields[1]) if hour == 12: hour = 0 if am_pm == 'pm': hour += 12 return hour*60 + minute def read_history(filename): result = [] for ...
null
22,107
import math import time import threading def csv_record(fields): s = '"%s",%0.2f,"%s","%s",%0.2f,%0.2f,%0.2f,%0.2f,%d' % tuple(fields) return s
null
22,109
import torch import torch.nn as nn import torch.nn.functional as F from .base_model import BaseModel from .blocks import ( FeatureFusionBlock, FeatureFusionBlock_custom, Interpolate, _make_encoder, forward_vit, ) class FeatureFusionBlock_custom(nn.Module): def __init__( self, ...
null
22,110
import torch import torch.nn as nn import timm import types import math import torch.nn.functional as F activations = {} def forward_flex(self, x): def forward_vit(pretrained, x): b, c, h, w = x.shape glob = pretrained.model.forward_flex(x) layer_1 = pretrained.activations["1"] layer_2 = pretrained.a...
null
22,111
import torch import torch.nn as nn import timm import types import math import torch.nn.functional as F def _make_vit_b16_backbone( model, features=[96, 192, 384, 768], size=[384, 384], hooks=[2, 5, 8, 11], vit_features=768, use_readout="ignore", start_index=1, enable_attention_hooks=Fal...
null
22,112
import torch import torch.nn as nn import timm import types import math import torch.nn.functional as F def _make_vit_b16_backbone( model, features=[96, 192, 384, 768], size=[384, 384], hooks=[2, 5, 8, 11], vit_features=768, use_readout="ignore", start_index=1, enable_attention_hooks=Fal...
null
22,113
import torch import torch.nn as nn from .vit import ( _make_pretrained_vitb_rn50_384, _make_pretrained_vitl16_384, _make_pretrained_vitb16_384, forward_vit, ) def _make_scratch(in_shape, out_shape, groups=1, expand=False): def _make_pretrained_resnext101_wsl(use_pretrained): def _make_pretrained_vitb_r...
null
22,114
import os import glob import torch import cv2 import argparse import util.io from torchvision.transforms import Compose from dpt.models import DPTDepthModel from dpt.midas_net import MidasNet_large from dpt.transforms import Resize, NormalizeImage, PrepareForNet class DPTDepthModel(DPT): def __init__( self...
Run MonoDepthNN to compute depth maps. Args: input_path (str): path to input folder output_path (str): path to output folder model_path (str): path to saved model
22,115
from PIL import Image def _get_voc_pallete(num_cls): n = num_cls pallete = [0]*(n*3) for j in range(0,n): lab = j pallete[j*3+0] = 0 pallete[j*3+1] = 0 pallete[j*3+2] = 0 i = 0 while (lab > 0): pallete[j*3+0] |= (((...
null
22,116
import matplotlib.pyplot as plt from dpt.vit import get_mean_attention_map def get_mean_attention_map(attn, token, shape): attn = attn[:, :, token, 1:] attn = attn.unflatten(2, torch.Size([shape[2] // 16, shape[3] // 16])).float() attn = torch.nn.functional.interpolate( attn, size=shape[2:], mode="...
null
22,117
import sys import re import numpy as np import cv2 import torch from PIL import Image from .pallete import get_mask_pallete The provided code snippet includes necessary dependencies for implementing the `read_pfm` function. Write a Python function `def read_pfm(path)` to solve the following problem: Read pfm file. Arg...
Read pfm file. Args: path (str): path to file Returns: tuple: (data, scale)
22,118
import sys import re import numpy as np import cv2 import torch from PIL import Image from .pallete import get_mask_pallete The provided code snippet includes necessary dependencies for implementing the `resize_image` function. Write a Python function `def resize_image(img)` to solve the following problem: Resize imag...
Resize image and make it fit for network. Args: img (array): image Returns: tensor: data ready for network