id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
187,782
import math import numbers import random from fractions import Fraction from decimal import Decimal from itertools import groupby, repeat from bisect import bisect_left, bisect_right from math import hypot, sqrt, fabs, exp, erf, tau, log, fsum from operator import itemgetter from collections import Counter, namedtuple ...
Return the high median of data. When the number of data points is odd, the middle value is returned. When it is even, the larger of the two middle values is returned. >>> median_high([1, 3, 5]) 3 >>> median_high([1, 3, 5, 7]) 5
187,783
import math import numbers import random from fractions import Fraction from decimal import Decimal from itertools import groupby, repeat from bisect import bisect_left, bisect_right from math import hypot, sqrt, fabs, exp, erf, tau, log, fsum from operator import itemgetter from collections import Counter, namedtuple ...
Return the 50th percentile (median) of grouped continuous data. >>> median_grouped([1, 2, 2, 3, 4, 4, 4, 4, 4, 5]) 3.7 >>> median_grouped([52, 52, 53, 54]) 52.5 This calculates the median as the 50th percentile, and should be used when your data is continuous and grouped. In the above example, the values 1, 2, 3, etc. ...
187,784
import math import numbers import random from fractions import Fraction from decimal import Decimal from itertools import groupby, repeat from bisect import bisect_left, bisect_right from math import hypot, sqrt, fabs, exp, erf, tau, log, fsum from operator import itemgetter from collections import Counter, namedtuple ...
Return the most common data point from discrete or nominal data. ``mode`` assumes discrete data, and returns a single value. This is the standard treatment of the mode as commonly taught in schools: >>> mode([1, 1, 2, 3, 3, 3, 3, 4]) 3 This also works with nominal (non-numeric) data: >>> mode(["red", "blue", "blue", "r...
187,785
import math import numbers import random from fractions import Fraction from decimal import Decimal from itertools import groupby, repeat from bisect import bisect_left, bisect_right from math import hypot, sqrt, fabs, exp, erf, tau, log, fsum from operator import itemgetter from collections import Counter, namedtuple ...
Return a list of the most frequently occurring values. Will return more than one result if there are multiple modes or an empty list if *data* is empty. >>> multimode('aabbbbbbbbcc') ['b'] >>> multimode('aabbbbccddddeeffffgg') ['b', 'd', 'f'] >>> multimode('') []
187,786
import math import numbers import random from fractions import Fraction from decimal import Decimal from itertools import groupby, repeat from bisect import bisect_left, bisect_right from math import hypot, sqrt, fabs, exp, erf, tau, log, fsum from operator import itemgetter from collections import Counter, namedtuple ...
Divide *data* into *n* continuous intervals with equal probability. Returns a list of (n - 1) cut points separating the intervals. Set *n* to 4 for quartiles (the default). Set *n* to 10 for deciles. Set *n* to 100 for percentiles which gives the 99 cuts points that separate *data* in to 100 equal sized groups. The *da...
187,787
import math import numbers import random from fractions import Fraction from decimal import Decimal from itertools import groupby, repeat from bisect import bisect_left, bisect_right from math import hypot, sqrt, fabs, exp, erf, tau, log, fsum from operator import itemgetter from collections import Counter, namedtuple ...
Return the square root of the population variance. See ``pvariance`` for arguments and other details. >>> pstdev([1.5, 2.5, 2.5, 2.75, 3.25, 4.75]) 0.986893273527251
187,788
import math import numbers import random from fractions import Fraction from decimal import Decimal from itertools import groupby, repeat from bisect import bisect_left, bisect_right from math import hypot, sqrt, fabs, exp, erf, tau, log, fsum from operator import itemgetter from collections import Counter, namedtuple ...
Covariance Return the sample covariance of two inputs *x* and *y*. Covariance is a measure of the joint variability of two inputs. >>> x = [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> y = [1, 2, 3, 1, 2, 3, 1, 2, 3] >>> covariance(x, y) 0.75 >>> z = [9, 8, 7, 6, 5, 4, 3, 2, 1] >>> covariance(x, z) -7.5 >>> covariance(z, x) -7.5
187,789
import math import numbers import random from fractions import Fraction from decimal import Decimal from itertools import groupby, repeat from bisect import bisect_left, bisect_right from math import hypot, sqrt, fabs, exp, erf, tau, log, fsum from operator import itemgetter from collections import Counter, namedtuple ...
Pearson's correlation coefficient Return the Pearson's correlation coefficient for two inputs. Pearson's correlation coefficient *r* takes values between -1 and +1. It measures the strength and direction of the linear relationship, where +1 means very strong, positive linear relationship, -1 very strong, negative linea...
187,790
import math import numbers import random from fractions import Fraction from decimal import Decimal from itertools import groupby, repeat from bisect import bisect_left, bisect_right from math import hypot, sqrt, fabs, exp, erf, tau, log, fsum from operator import itemgetter from collections import Counter, namedtuple ...
Slope and intercept for simple linear regression. Return the slope and intercept of simple linear regression parameters estimated using ordinary least squares. Simple linear regression describes relationship between an independent variable *x* and a dependent variable *y* in terms of linear function: y = slope * x + in...
187,791
import math import numbers import random from fractions import Fraction from decimal import Decimal from itertools import groupby, repeat from bisect import bisect_left, bisect_right from math import hypot, sqrt, fabs, exp, erf, tau, log, fsum from operator import itemgetter from collections import Counter, namedtuple ...
null
187,812
import os import re import time import random import socket import datetime import urllib.parse from email._parseaddr import quote from email._parseaddr import AddressList as _AddressList from email._parseaddr import mktime_tz from email._parseaddr import parsedate, parsedate_tz, _parsedate_tz from email.charset import...
null
187,823
from base64 import b64encode from binascii import b2a_base64, a2b_base64 NL = '\n' EMPTYSTRING = '' def decode(string): """Decode a raw base64 string, returning a bytes object. This function does not parse a full MIME header value encoded with base64 (like =?iso-8859-1?b?bmloISBuaWgh?=) -- please use the hi...
r"""Encode a string with base64. Each line will be wrapped at, at most, maxlinelen characters (defaults to 76 characters). Each line of encoded text will end with eol, which defaults to "\n". Set this to "\r\n" if you will be using the result of this function directly in an email.
187,836
import re import base64 import binascii import functools from string import ascii_letters, digits from email import errors def decode(ew): """Decode encoded word and return (string, charset, lang, defects) tuple. An RFC 2047/2243 encoded word has the form: =?charset*lang?cte?encoded_string?= where '...
null
187,838
import re import sys import urllib.parse from string import hexdigits from operator import itemgetter from email import _encoded_words as _ew from email import errors from email import utils CFWS_LEADER = WSP | set('(') class AddressList(TokenList): token_type = 'address-list' def addresses(self): ret...
address_list = (address *("," address)) / obs-addr-list obs-addr-list = *([CFWS] ",") address *("," [address / CFWS]) We depart from the formal grammar here by continuing to parse until the end of the input, assuming the input to be entirely composed of an address-list. This is always true in email parsing, and allows ...
187,839
import re import sys import urllib.parse from string import hexdigits from operator import itemgetter from email import _encoded_words as _ew from email import errors from email import utils class MessageID(MsgID): token_type = 'message-id' class InvalidMessageID(MessageID): token_type = 'invalid-message-id' ...
message-id = "Message-ID:" msg-id CRLF
187,840
import re import sys import urllib.parse from string import hexdigits from operator import itemgetter from email import _encoded_words as _ew from email import errors from email import utils CFWS_LEADER = WSP | set('(') class MIMEVersion(TokenList): token_type = 'mime-version' major = None minor = None cl...
mime-version = [CFWS] 1*digit [CFWS] "." [CFWS] 1*digit [CFWS]
187,841
import re import sys import urllib.parse from string import hexdigits from operator import itemgetter from email import _encoded_words as _ew from email import errors from email import utils class ContentType(ParameterizedHeaderValue): token_type = 'content-type' as_ew_allowed = False maintype = 'text' ...
maintype "/" subtype *( ";" parameter ) The maintype and substype are tokens. Theoretically they could be checked against the official IANA list + x-token, but we don't do that.
187,842
import re import sys import urllib.parse from string import hexdigits from operator import itemgetter from email import _encoded_words as _ew from email import errors from email import utils class ContentDisposition(ParameterizedHeaderValue): token_type = 'content-disposition' as_ew_allowed = False conten...
disposition-type *( ";" parameter )
187,843
import re import sys import urllib.parse from string import hexdigits from operator import itemgetter from email import _encoded_words as _ew from email import errors from email import utils PHRASE_ENDS = SPECIALS - set('."(') class ContentTransferEncoding(TokenList): token_type = 'content-transfer-encoding' ...
mechanism
187,844
import re import sys import urllib.parse from string import hexdigits from operator import itemgetter from email import _encoded_words as _ew from email import errors from email import utils SPECIALS = set(r'()<>@,:;.\"[]') class Terminal(str): as_ew_allowed = True ew_combine_allowed = True syntactic_brea...
Return string of contents of parse_tree folded according to RFC rules.
187,845
import abc from email import header from email import charset as _charset from email.utils import _has_surrogates def _append_doc(doc, added_doc): def _extend_docstrings(cls): if cls.__doc__ and cls.__doc__.startswith('+'): cls.__doc__ = _append_doc(cls.__bases__[0].__doc__, cls.__doc__) for name, attr...
null
187,859
from builtins import open as _builtin_open from codecs import lookup, BOM_UTF8 import collections import functools from io import TextIOWrapper import itertools as _itertools import re import sys from token import * from token import EXACT_TOKEN_TYPES import token def group(*choices): return '(' + '|'.join(choices) + '...
null
187,860
from builtins import open as _builtin_open from codecs import lookup, BOM_UTF8 import collections import functools from io import TextIOWrapper import itertools as _itertools import re import sys from token import * from token import EXACT_TOKEN_TYPES import token for t in _all_string_prefixes(): for u in (t + '"',...
null
187,861
from builtins import open as _builtin_open from codecs import lookup, BOM_UTF8 import collections import functools from io import TextIOWrapper import itertools as _itertools import re import sys from token import * from token import EXACT_TOKEN_TYPES import token class Untokenizer: def __init__(self): self...
Transform tokens back into Python source code. It returns a bytes object, encoded using the ENCODING token, which is the first token sequence output by tokenize. Each element returned by the iterable must be a token sequence with at least two elements, a token number and token value. If only two tokens are passed, the ...
187,876
import re from tkinter import StringVar, TclError from idlelib.searchbase import SearchDialogBase from idlelib import searchengine def replace(text, insert_tags=None): """Create or reuse a singleton ReplaceDialog instance. The singleton dialog saves user entries and preferences across instances. Args: ...
null
187,877
from idlelib.delegator import Delegator from idlelib.redirector import WidgetRedirector class Percolator: def __init__(self, text): # XXX would be nice to inherit from Delegator self.text = text self.redir = WidgetRedirector(text) self.top = self.bottom = Delegator(text) self...
null
187,891
import io import os import shlex import sys import tempfile import tokenize from tkinter import filedialog from tkinter import messagebox from tkinter.simpledialog import askstring import idlelib from idlelib.config import idleConf from idlelib.util import py_extensions class IOBinding: # One instance per editor Window...
null
187,892
import importlib.abc import importlib.util import os import platform import re import string import sys import tokenize import traceback import webbrowser from tkinter import * from tkinter.font import Font from tkinter.ttk import Scrollbar from tkinter import simpledialog from tkinter import messagebox from idlelib.co...
Format sys.version_info to produce the Sphinx version string used to install the chm docs
187,893
import importlib.abc import importlib.util import os import platform import re import string import sys import tokenize import traceback import webbrowser from tkinter import * from tkinter.font import Font from tkinter.ttk import Scrollbar from tkinter import simpledialog from tkinter import messagebox from idlelib.co...
null
187,894
import importlib.abc import importlib.util import os import platform import re import string import sys import tokenize import traceback import webbrowser from tkinter import * from tkinter.font import Font from tkinter.ttk import Scrollbar from tkinter import simpledialog from tkinter import messagebox from idlelib.co...
Return a line's indentation as (# chars, effective # of spaces). The effective # of spaces is the length after properly "expanding" the tabs into spaces, as done by str.expandtabs(tabwidth).
187,895
import importlib.abc import importlib.util import os import platform import re import string import sys import tokenize import traceback import webbrowser from tkinter import * from tkinter.font import Font from tkinter.ttk import Scrollbar from tkinter import simpledialog from tkinter import messagebox from idlelib.co...
null
187,896
import importlib.abc import importlib.util import os import platform import re import string import sys import tokenize import traceback import webbrowser from tkinter import * from tkinter.font import Font from tkinter.ttk import Scrollbar from tkinter import simpledialog from tkinter import messagebox from idlelib.co...
null
187,897
import importlib.abc import importlib.util import os import platform import re import string import sys import tokenize import traceback import webbrowser from tkinter import * from tkinter.font import Font from tkinter.ttk import Scrollbar from tkinter import simpledialog from tkinter import messagebox from idlelib.co...
null
187,898
import contextlib import functools import io import linecache import queue import sys import textwrap import time import traceback import _thread as thread import threading import warnings import idlelib from idlelib import autocomplete from idlelib import calltip from idlelib import debugger_r from idlelib import ...
Process any tk events that are ready to be dispatched if tkinter has been imported, a tcl interpreter has been created and tk has been loaded.
187,899
import contextlib import functools import io import linecache import queue import sys import textwrap import time import traceback import _thread as thread import threading import warnings import idlelib from idlelib import autocomplete from idlelib import calltip from idlelib import debugger_r from idlelib import ...
null
187,900
import contextlib import functools import io import linecache import queue import sys import textwrap import time import traceback import _thread as thread import threading import warnings import idlelib from idlelib import autocomplete from idlelib import calltip from idlelib import debugger_r from idlelib import ...
null
187,901
import contextlib import functools import io import linecache import queue import sys import textwrap import time import traceback import _thread as thread import threading import warnings import idlelib from idlelib import autocomplete from idlelib import calltip from idlelib import debugger_r from idlelib import ...
Exit subprocess, possibly after first clearing exit functions. If config-main.cfg/.def 'General' 'delete-exitfunc' is True, then any functions registered with atexit will be removed before exiting. (VPython support)
187,902
import contextlib import functools import io import linecache import queue import sys import textwrap import time import traceback import _thread as thread import threading import warnings import idlelib from idlelib import autocomplete from idlelib import calltip from idlelib import debugger_r from idlelib import ...
Install wrappers to always add 30 to the recursion limit.
187,903
import contextlib import functools import io import linecache import queue import sys import textwrap import time import traceback import _thread as thread import threading import warnings import idlelib from idlelib import autocomplete from idlelib import calltip from idlelib import debugger_r from idlelib import ...
Uninstall the recursion limit wrappers from the sys module. IDLE only uses this for tests. Users can import run and call this to remove the wrapping.
187,904
import os from tkinter import messagebox class FileList: def __init__(self, root): def open(self, filename, action=None): def gotofileline(self, filename, lineno=None): def new(self, filename=None): def close_all_callback(self, *args, **kwds): def unregister_maybe_terminate(self, edit): ...
null
187,905
import contextlib import functools import itertools import tkinter as tk from tkinter.font import Font from idlelib.config import idleConf from idlelib.delegator import Delegator from idlelib import macosx def get_lineno(text, index): """Return the line number of an index in a Tk text widget.""" text_index = te...
Return the number of the last line in a Tk text widget.
187,906
import contextlib import functools import itertools import tkinter as tk from tkinter.font import Font from idlelib.config import idleConf from idlelib.delegator import Delegator from idlelib import macosx The provided code snippet includes necessary dependencies for implementing the `get_displaylines` function. Write...
Display height, in lines, of a logical line in a Tk text widget.
187,907
import contextlib import functools import itertools import tkinter as tk from tkinter.font import Font from idlelib.config import idleConf from idlelib.delegator import Delegator from idlelib import macosx The provided code snippet includes necessary dependencies for implementing the `get_widget_padding` function. Wri...
Get the total padding of a Tk widget, including its border.
187,908
import contextlib import functools import itertools import tkinter as tk from tkinter.font import Font from idlelib.config import idleConf from idlelib.delegator import Delegator from idlelib import macosx def temp_enable_text_widget(text): text.configure(state=tk.NORMAL) try: yield finally: ...
null
187,909
import contextlib import functools import itertools import tkinter as tk from tkinter.font import Font from idlelib.config import idleConf from idlelib.delegator import Delegator from idlelib import macosx class LineNumbers(BaseSideBar): """Line numbers support for editor windows.""" def __init__(self, editwin)...
null
187,914
import os import sys import webbrowser from platform import python_version, architecture from tkinter import Toplevel, Frame, Label, Button, PhotoImage from tkinter import SUNKEN, TOP, BOTTOM, LEFT, X, BOTH, W, EW, NSEW, E from idlelib import textview def architecture(executable=sys.executable, bits='', linkage=''): ...
Return bits for platform.
187,928
import builtins import keyword import re import time from idlelib.config import idleConf from idlelib.delegator import Delegator def any(name, alternates): prog = make_pat() def make_pat(): kw = r"\b" + any("KEYWORD", keyword.kwlist) + r"\b" match_softkw = ( r"^[ \t]*" + # at beginning of line + possi...
null
187,929
import builtins import keyword import re import time from idlelib.config import idleConf from idlelib.delegator import Delegator The provided code snippet includes necessary dependencies for implementing the `matched_named_groups` function. Write a Python function `def matched_named_groups(re_match)` to solve the foll...
Get only the non-empty named groups from an re.Match object.
187,930
import builtins import keyword import re import time from idlelib.config import idleConf from idlelib.delegator import Delegator def color_config(text): """Set color options of Text widget. If ColorDelegator is used, this should be called first. """ # Called from htest, TextFrame, Editor, and Turtledemo...
null
187,933
import string from idlelib.delegator import Delegator class UndoDelegator(Delegator): def __init__(self): def setdelegate(self, delegate): def dump_event(self, event): def reset_undo(self): def set_saved(self, flag): def get_saved(self): def set_saved_change_hook(self, hook): def...
null
187,948
import os import sys import importlib.util import py_compile import struct import filecmp from functools import partial from pathlib import Path def compile_dir(dir, maxlevels=None, ddir=None, force=False, rx=None, quiet=0, legacy=False, optimize=-1, workers=1, invalidation_mode=None, *,...
Byte-compile all module on sys.path. Arguments (all optional): skip_curdir: if true, skip current directory (default True) maxlevels: max recursion level (default 0) force: as for compile_dir() (default False) quiet: as for compile_dir() (default 0) legacy: as for compile_dir() (default False) optimize: as for compile_...
187,949
import io import math import mmap import os import re import struct import sys import time from collections import deque, OrderedDict from importlib.util import spec_from_file_location, decode_source from os import path from types import CodeType def _float_equals(a, b): if math.isnan(a) and math.isnan(b): ...
null
187,950
import io import math import mmap import os import re import struct import sys import time from collections import deque, OrderedDict from importlib.util import spec_from_file_location, decode_source from os import path from types import CodeType def _align_file(file, align=8): len = file.tell() padding = (((l...
null
187,951
import io import math import mmap import os import re import struct import sys import time from collections import deque, OrderedDict from importlib.util import spec_from_file_location, decode_source from os import path from types import CodeType class PyIceImporter: def __init__(self, import_path): self.pa...
null
187,952
import io import math import mmap import os import re import struct import sys import time from collections import deque, OrderedDict from importlib.util import spec_from_file_location, decode_source from os import path from types import CodeType class PyIceImporter: def __init__(self, import_path): def find_...
null
187,964
from datetime import tzinfo, timedelta, datetime import time as _time def first_sunday_on_or_after(dt): days_to_go = 6 - dt.weekday() if days_to_go: dt += timedelta(days_to_go) return dt DSTSTART_2007 = datetime(1, 3, 8, 2) DSTEND_2007 = datetime(1, 11, 1, 2) DSTSTART_1987_2006 = datetime(1, 4, 1, 2...
null
187,974
import os import re import sys import getopt from string import ascii_letters from os.path import join, splitext, abspath, exists from collections import defaultdict checkers = {} checker_props = {'severity': 1, 'falsepositives': False} The provided code snippet includes necessary dependencies for implementing the `ch...
Decorator to register a function as a checker.
187,975
import os import re import sys import getopt from string import ascii_letters from os.path import join, splitext, abspath, exists from collections import defaultdict The provided code snippet includes necessary dependencies for implementing the `check_syntax` function. Write a Python function `def check_syntax(fn, lin...
Check Python examples for valid syntax.
187,976
import os import re import sys import getopt from string import ascii_letters from os.path import join, splitext, abspath, exists from collections import defaultdict seems_directive_re = re.compile(r'(?<!\.)\.\. %s([^a-z:]|:(?!:))' % all_directives) default_role_re = re.compile(r'(^| )`\w([^`]*?\w)?`($| )') The provid...
Check for suspicious reST constructs.
187,977
import os import re import sys import getopt from string import ascii_letters from os.path import join, splitext, abspath, exists from collections import defaultdict The provided code snippet includes necessary dependencies for implementing the `check_whitespace` function. Write a Python function `def check_whitespace...
Check for whitespace and line length issues.
187,978
import os import re import sys import getopt from string import ascii_letters from os.path import join, splitext, abspath, exists from collections import defaultdict The provided code snippet includes necessary dependencies for implementing the `check_line_length` function. Write a Python function `def check_line_leng...
Check for line length; this checker is not run by default.
187,979
import os import re import sys import getopt from string import ascii_letters from os.path import join, splitext, abspath, exists from collections import defaultdict leaked_markup_re = re.compile(r'[a-z]::\s|`|\.\.\s*\w+:') The provided code snippet includes necessary dependencies for implementing the `check_leaked_ma...
Check HTML files for leaked reST markup; this only works if the HTML files have been built.
187,980
import os import re import sys import getopt from string import ascii_letters from os.path import join, splitext, abspath, exists from collections import defaultdict def hide_literal_blocks(lines): """Tool to remove literal blocks from given lines. It yields empty lines in place of blocks, so line numbers are ...
r"""Check for missing 'backslash-space' between a code sample a letter. Good: ``Point``\ s Bad: ``Point``s
187,981
from pygments.lexer import RegexLexer, bygroups, include from pygments.token import Comment, Generic, Keyword, Name, Operator, Punctuation, Text from sphinx.highlighting import lexers class PEGLexer(RegexLexer): """Pygments Lexer for PEG grammar (.gram) files This lexer strips the following elements from the gr...
null
187,982
import re import io from os import getenv, path from time import asctime from pprint import pformat from docutils.io import StringOutput from docutils.parsers.rst import Directive from docutils.utils import new_document from docutils import nodes, utils from sphinx import addnodes from sphinx.builders import Builder fr...
null
187,986
import json import os.path from docutils.nodes import definition_list_item from sphinx.addnodes import glossary from sphinx.util import logging def process_glossary_nodes(app, doctree, fromdocname): if app.builder.format != 'html': return terms = {} for node in doctree.traverse(glossary): fo...
null
187,987
from os import path from docutils import nodes from docutils.parsers.rst import directives from docutils.parsers.rst import Directive from docutils.statemachine import StringList import csv from sphinx import addnodes from sphinx.domains.c import CObject def init_annotations(app): def setup(app): app.add_config_va...
null
187,988
import pathlib import re from html.entities import codepoint2name from sphinx.util.logging import getLogger def escape_for_chm(app, pagename, templatename, context, doctree): # only works for .chm output if getattr(app.builder, 'name', '') != 'htmlhelp': return # escape the `body` part to 7-bit ASCI...
null
187,989
import os import sys from pathlib import Path from pygments.lexer import RegexLexer, bygroups, include, words from pygments.token import (Comment, Generic, Keyword, Name, Operator, Punctuation, Text) from asdl import builtin_types from sphinx.highlighting import lexers class ASDLLexer(RegexL...
null
187,995
import copy import math import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions import Normal def create_masks( input_size, hidden_size, n_hidden, input_order="sequential", input_degrees=None ): # MADE paper sec 4: # degrees of connections between layers -- ensure at mos...
null
187,996
from functools import partial from inspect import isfunction import numpy as np import torch from torch import nn, einsum import torch.nn.functional as F def default(val, d): if val is not None: return val return d() if isfunction(d) else d
null
187,997
from functools import partial from inspect import isfunction import numpy as np import torch from torch import nn, einsum import torch.nn.functional as F def extract(a, t, x_shape): b, *_ = t.shape out = a.gather(-1, t) return out.reshape(b, *((1,) * (len(x_shape) - 1)))
null
187,998
from functools import partial from inspect import isfunction import numpy as np import torch from torch import nn, einsum import torch.nn.functional as F def noise_like(shape, device, repeat=False): repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat( shape[0], *((1,) * (len(shape) - ...
null
187,999
from functools import partial from inspect import isfunction import numpy as np import torch from torch import nn, einsum import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `cosine_beta_schedule` function. Write a Python function `def cosine_beta_schedule(tim...
cosine schedule as proposed in https://openreview.net/forum?id=-NEXDKk8gZ
188,000
import json import os from pathlib import Path from functools import lru_cache import numpy as np import pandas as pd from gluonts.dataset.field_names import FieldName from gluonts.dataset.repository._util import metadata, save_to_file from gluonts.time_feature.holiday import squared_exponential_kernel from pts.feature...
null
188,001
from typing import List import numpy as np import pandas as pd from pandas.tseries.frequencies import to_offset from gluonts.core.component import validated from gluonts.time_feature import TimeFeature, norm_freq_str class FourierDateFeatures(TimeFeature): def __init__(self, freq: str) -> None: super().__in...
null
188,002
from typing import List, Optional from pandas.tseries.frequencies import to_offset def lags_for_fourier_time_features_from_frequency( freq_str: str, num_lags: Optional[int] = None ) -> List[int]: offset = to_offset(freq_str) multiple, granularity = offset.n, offset.name if granularity == "M": ...
null
188,003
The provided code snippet includes necessary dependencies for implementing the `broadcast_shape` function. Write a Python function `def broadcast_shape(*shapes, **kwargs)` to solve the following problem: Similar to ``np.broadcast()`` but for shapes. Equivalent to ``np.broadcast(*map(np.empty, shapes)).shape``. :param...
Similar to ``np.broadcast()`` but for shapes. Equivalent to ``np.broadcast(*map(np.empty, shapes)).shape``. :param tuple shapes: shapes of tensors. :param bool strict: whether to use extend-but-not-resize broadcasting. :returns: broadcasted shape :rtype: tuple :raises: ValueError
188,004
import inspect from typing import Optional import torch import torch.nn as nn def get_module_forward_input_names(module: nn.Module): params = inspect.signature(module.forward).parameters param_names = [k for k, v in params.items() if not str(v).startswith("*")] return param_names
null
188,005
import inspect from typing import Optional import torch import torch.nn as nn The provided code snippet includes necessary dependencies for implementing the `weighted_average` function. Write a Python function `def weighted_average( x: torch.Tensor, weights: Optional[torch.Tensor] = None, dim=None ) -> torch.Tenso...
Computes the weighted average of a given tensor across a given dim, masking values associated with weight zero, meaning instead of `nan * 0 = nan` you will get `0 * 0 = 0`. Parameters ---------- x Input tensor, of which the average must be computed. weights Weights tensor, of the same shape as `x`. dim The dim along wh...
188,006
from typing import List, Tuple import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from gluonts.time_feature import get_seasonality def linspace( backcast_length: int, forecast_length: int ) -> Tuple[np.ndarray, np.ndarray]: lin_space = np.linspace( -backcast_length, ...
null
188,007
from typing import List, Optional, Tuple, Union import numpy as np import torch import torch.nn as nn from torch.distributions import Distribution from gluonts.core.component import validated from gluonts.torch.distributions.distribution_output import DistributionOutput from pts.model import weighted_average from pts.m...
null
188,008
from typing import List, Optional, Tuple, Union import numpy as np import torch import torch.nn as nn from torch.distributions import Distribution from gluonts.core.component import validated from gluonts.torch.modules.distribution_output import DistributionOutput from pts.model import weighted_average from pts.modules...
null
188,009
from typing import List, Optional, Tuple import torch import torch.nn as nn from gluonts.core.component import validated from gluonts.torch.modules.distribution_output import DistributionOutput from pts.modules import MeanScaler, NOPScaler, FeatureEmbedder def prod(xs): p = 1 for x in xs: p *= x re...
null
188,010
from itertools import chain from typing import List, Optional, Dict import numpy as np import torch from gluonts.core.component import validated from gluonts.dataset.field_names import FieldName from gluonts.model.forecast_generator import QuantileForecastGenerator from gluonts.model.predictor import Predictor from glu...
null
188,011
import os import subprocess from os.path import join import yaml import tempfile import argparse from skimage.io import imread import numpy as np import librosa from util import util from tqdm import tqdm import torch from collections import OrderedDict import cv2 from moviepy.video.io.ffmpeg_tools import ffmpeg_extrac...
null
188,012
import os import subprocess from os.path import join from tqdm import tqdm import numpy as np import torch from collections import OrderedDict import librosa from skimage.io import imread import cv2 import scipy.io as sio import argparse import yaml import albumentations as A import albumentations.pytorch from pathlib ...
null
188,013
import sys from . import audio_funcs import numpy as np from math import cos, sin import torch from numpy.linalg import solve from scipy.ndimage import gaussian_filter1d from sklearn.neighbors import KDTree import time from tqdm import tqdm The provided code snippet includes necessary dependencies for implementing the...
compute mel for an audio sequence.
188,014
import sys from . import audio_funcs import numpy as np from math import cos, sin import torch from numpy.linalg import solve from scipy.ndimage import gaussian_filter1d from sklearn.neighbors import KDTree import time from tqdm import tqdm The provided code snippet includes necessary dependencies for implementing the...
compute KNN for feat in feat base
188,015
import sys from . import audio_funcs import numpy as np from math import cos, sin import torch from numpy.linalg import solve from scipy.ndimage import gaussian_filter1d from sklearn.neighbors import KDTree import time from tqdm import tqdm def KNN_with_torch(feats, feat_database, K=10): feats = torch.from_numpy(f...
null
188,016
import sys from . import audio_funcs import numpy as np from math import cos, sin import torch from numpy.linalg import solve from scipy.ndimage import gaussian_filter1d from sklearn.neighbors import KDTree import time from tqdm import tqdm def solve_LLE_projection(feat, feat_base): '''find LLE projection weights g...
null
188,017
import sys from . import audio_funcs import numpy as np from math import cos, sin import torch from numpy.linalg import solve from scipy.ndimage import gaussian_filter1d from sklearn.neighbors import KDTree import time from tqdm import tqdm def solve_LLE_projection(feat, feat_base): def compute_LLE_projection_all_fram...
null
188,018
import sys from . import audio_funcs import numpy as np from math import cos, sin import torch from numpy.linalg import solve from scipy.ndimage import gaussian_filter1d from sklearn.neighbors import KDTree import time from tqdm import tqdm def angle2matrix(angles, gradient='false'): ''' get rotation matrix from th...
project 2d landmarks given predicted 3d landmarks & headposes and user-defined camera & viewpoint parameters
188,019
import sys from . import audio_funcs import numpy as np from math import cos, sin import torch from numpy.linalg import solve from scipy.ndimage import gaussian_filter1d from sklearn.neighbors import KDTree import time from tqdm import tqdm The provided code snippet includes necessary dependencies for implementing the...
smooth the input 3d landmarks using gaussian filters on each dimension. Args: pts3d: [N, 73, 3]
188,020
import sys from . import audio_funcs import numpy as np from math import cos, sin import torch from numpy.linalg import solve from scipy.ndimage import gaussian_filter1d from sklearn.neighbors import KDTree import time from tqdm import tqdm lower_mouth = [53, 54, 55, 56, 57, 58, 59, 60] upper_mouth = [46, 47, 48, 49, 5...
mouth region AMP to control the reaction amplitude. method: 'XY', 'delta', 'XYZ', 'LowerMore' or 'CloseSmall'
188,021
import sys from . import audio_funcs import numpy as np from math import cos, sin import torch from numpy.linalg import solve from scipy.ndimage import gaussian_filter1d from sklearn.neighbors import KDTree import time from tqdm import tqdm upper_outer_lip = list(range(47, 52)) upper_inner_lip = [63, 62, 61] lower_inne...
solve the generated intersec lips, usually happens in mouth AMP usage. Args: pts3d: [N, 73, 3]
188,022
import sys from . import audio_funcs import numpy as np from math import cos, sin import torch from numpy.linalg import solve from scipy.ndimage import gaussian_filter1d from sklearn.neighbors import KDTree import time from tqdm import tqdm def headpose_smooth(headpose, smooth_sigmas=[0,0], method='gaussian'): rot...
null
188,023
import os import os.path import math import torch import torch.utils.data import numpy as np import librosa from librosa.filters import mel as librosa_mel_fn import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `mu_law_encoding` function. Write a Python functio...
encode the original audio via mu-law companding and mu-bits quantization
188,024
import os import os.path import math import torch import torch.utils.data import numpy as np import librosa from librosa.filters import mel as librosa_mel_fn import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `mu_law_decoding` function. Write a Python functio...
inverse the mu-law compressed and quantized data.
188,025
import os import os.path import math import torch import torch.utils.data import numpy as np import librosa from librosa.filters import mel as librosa_mel_fn import torch.nn.functional as F The provided code snippet includes necessary dependencies for implementing the `inject_gaussian_noise` function. Write a Python f...
inject random gaussian noise (mean=0, std=1) to audio clip In my test, a reasonable factor region could be [0, 0.01] larger will be too large and smaller could be ignored. Args: data: [n,] original audio sequence noise_factor(float): scaled factor use_torch(bool): optional, if use_torch=True, input data and implementat...