uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
617de9ae19dcd2d74986e2a9
train
class
class UploadCommand(Command): description = 'Build, install and upload tag to git with cleanup.' user_options = [] def run(self): try: self.status('Removing previous builds...') rmtree(os.path.join(base_path, 'dist')) except OSError: pass self.st...
class UploadCommand(Command):
description = 'Build, install and upload tag to git with cleanup.' user_options = [] def run(self): try: self.status('Removing previous builds...') rmtree(os.path.join(base_path, 'dist')) except OSError: pass self.status('Building Source and Whee...
except Exception: REQUIREMENTS = [] try: with io.open(os.path.join(base_path, 'README.md'), encoding='utf-8') as f: LONG_DESCRIPTION = '\n' + f.read() except FileNotFoundError: LONG_DESCRIPTION = SHORT_DESCRIPION class UploadCommand(Command):
64
64
213
5
58
titu1994/PyCTakesParser
setup.py
Python
UploadCommand
UploadCommand
57
92
57
57
8fc5ce6353dfa619c53082e65d7cc6a844b5d844
bigcode/the-stack
train
4a67fda79a57254a2dda83d1
train
function
def parse_imported_config_squid(imported_cfg, cfg_file_ver, cfg_ver): json_configfile_id = '{"id":' tag_current = "" array_entry_id = [] array_tags = [] array_values = [] array_switch = [] array_switch_position = [] items_to_remove = [] base_cfg_tags = parse_config_file_squid("", ...
def parse_imported_config_squid(imported_cfg, cfg_file_ver, cfg_ver):
json_configfile_id = '{"id":' tag_current = "" array_entry_id = [] array_tags = [] array_values = [] array_switch = [] array_switch_position = [] items_to_remove = [] base_cfg_tags = parse_config_file_squid("", cfg_file_ver, cfg_ver) for line in imported_cfg: line_cu...
, json_config) json_config.write(JSON_CONFIGFILE_SWITCH_POSITION) json.dump(array_switch_position, json_config) json_config.write(JSON_CONFIGFILE_BUILTWITH_NOTE) json.dump(array_warning_message, json_config) json_config.write(JSON_CONFIGFILE_WARNING_NOTE) json.dump(array_...
185
185
617
18
166
itworks99/sucker
srv/parser.py
Python
parse_imported_config_squid
parse_imported_config_squid
347
439
347
347
ff30b18d2ab8e184a0244fb9ad6bc4f2b6e58435
bigcode/the-stack
train
01d6217d390261687e48b2fa
train
function
def list_available_config_files(directory): config_file_versions = [] for file_name in os.listdir(directory): if file_name.startswith("squid"): line = file_name.strip("squid").strip(".conf") if len(line) > 2: line = line[:2] + "." + line[2:] line = li...
def list_available_config_files(directory):
config_file_versions = [] for file_name in os.listdir(directory): if file_name.startswith("squid"): line = file_name.strip("squid").strip(".conf") if len(line) > 2: line = line[:2] + "." + line[2:] line = line[:1] + "." + line[1:] config_f...
_tr_tr_d = "on|off|transparent|truncate|delete" config_time_units = "time-units" disabled_config_line = "#" section_number = 0 tag_en = 0 pass_records_to_arrays = False main_cfg_sect_start = False def list_available_config_files(directory):
64
64
95
7
56
itworks99/sucker
srv/parser.py
Python
list_available_config_files
list_available_config_files
50
60
50
50
a9eac79ff6e5cba4dc2a36390937e34135268a8a
bigcode/the-stack
train
b88c1d05d975c563f9c8be6e
train
function
def parse_config_file_squid(action, config_file_versions, config_ver): global tag_en, section_number, pass_records_to_arrays, main_cfg_sect_start default_squid_config_path = "srv/templates/squid" + config_ver + ".conf" config_sections_default = [] squid_version = [] help_section_text = "" help...
def parse_config_file_squid(action, config_file_versions, config_ver):
global tag_en, section_number, pass_records_to_arrays, main_cfg_sect_start default_squid_config_path = "srv/templates/squid" + config_ver + ".conf" config_sections_default = [] squid_version = [] help_section_text = "" help_section_started = False def extract_config_version(line_current_l...
n" TXT_RETURN = "\r" TXT_TAB = "\t" config_section_start = "# --" config_tag = "# TAG:" config_default_value = "#Default:" config_version_line = "WELCOME TO SQUID" config_note = "# Note: This option is only available" config_warning = "# WARNING:" config_on_off = "on|off" config_on_off_warn = "on|off|warn" config_on...
256
256
2,055
15
240
itworks99/sucker
srv/parser.py
Python
parse_config_file_squid
parse_config_file_squid
63
344
63
63
4d1a5c5ccf91712b0a98838b20bbd37f67da1979
bigcode/the-stack
train
65779d78ec837a14dfacd04d
train
function
@pytest.fixture def servers_nonlegacy(request): "Returns a new APIHandler with a filter manager" # Create tmpdir and delete after tmpdir = tempfile.mkdtemp() # Make the command output = "%s/output" % tmpdir cmd = "cat >> %s" % output # Write the configuration port = random.randrange(10...
@pytest.fixture def servers_nonlegacy(request):
"Returns a new APIHandler with a filter manager" # Create tmpdir and delete after tmpdir = tempfile.mkdtemp() # Make the command output = "%s/output" % tmpdir cmd = "cat >> %s" % output # Write the configuration port = random.randrange(10000, 65000) config_path = os.path.join(tmpdi...
) conn.settimeout(1) conn.connect(("localhost", port)) connected = True break except Exception as e: print(e) time.sleep(0.5) # Die now if not connected: raise EnvironmentError("Failed to connect!") # Make a second con...
117
117
392
9
107
msaf1980/statsite
integ/test_extended_counters.py
Python
servers_nonlegacy
servers_nonlegacy
82
144
82
83
e4cdbcc8b7117bc8ebe4854c5073ae6b099d1a26
bigcode/the-stack
train
04050a9b1e41a3bbb14460e9
train
function
def wait_file(path, timeout=5): "Waits on a file to be make" start = time.time() while not os.path.isfile(path) and time.time() - start < timeout: time.sleep(0.1) if not os.path.isfile(path): raise Exception("Timed out waiting for file %s" % path) while os.path.getsize(path) == 0 and...
def wait_file(path, timeout=5):
"Waits on a file to be make" start = time.time() while not os.path.isfile(path) and time.time() - start < timeout: time.sleep(0.1) if not os.path.isfile(path): raise Exception("Timed out waiting for file %s" % path) while os.path.getsize(path) == 0 and time.time() - start < timeout: ...
raise EnvironmentError("Failed to connect!") # Make a second connection conn2 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) conn2.connect(("localhost", port)) # Return the connection return conn, conn2, output def wait_file(path, timeout=5):
64
64
102
9
54
msaf1980/statsite
integ/test_extended_counters.py
Python
wait_file
wait_file
147
155
147
147
8118225c7ff75464943bc32fde7e30fac0cebb34
bigcode/the-stack
train
3acbb2d96606f7ef5a9ee87b
train
class
class TestInteg(object): def test_counters(self, servers): "Tests adding counters with (legacy behaviour)" server, _, output = servers server.sendall("foobar:100|c\n") server.sendall("foobar:200|c\n") server.sendall("foobar:300|c\n") wait_file(output) out = o...
class TestInteg(object):
def test_counters(self, servers): "Tests adding counters with (legacy behaviour)" server, _, output = servers server.sendall("foobar:100|c\n") server.sendall("foobar:200|c\n") server.sendall("foobar:300|c\n") wait_file(output) out = open(output).read() ...
OCK_DGRAM) conn2.connect(("localhost", port)) # Return the connection return conn, conn2, output def wait_file(path, timeout=5): "Waits on a file to be make" start = time.time() while not os.path.isfile(path) and time.time() - start < timeout: time.sleep(0.1) if not os.path.isfile...
136
136
456
6
130
msaf1980/statsite
integ/test_extended_counters.py
Python
TestInteg
TestInteg
158
205
158
158
4c79191eef5c69a424439261fcb6abf3b99b7aa2
bigcode/the-stack
train
5b29829463162a3367f8a7b1
train
function
@pytest.fixture def servers(request): "Returns a new APIHandler with a filter manager" # Create tmpdir and delete after tmpdir = tempfile.mkdtemp() # Make the command output = "%s/output" % tmpdir cmd = "cat >> %s" % output # Write the configuration port = random.randrange(10000, 65000...
@pytest.fixture def servers(request):
"Returns a new APIHandler with a filter manager" # Create tmpdir and delete after tmpdir = tempfile.mkdtemp() # Make the command output = "%s/output" % tmpdir cmd = "cat >> %s" % output # Write the configuration port = random.randrange(10000, 65000) config_path = os.path.join(tmpdi...
import os import os.path import shutil import socket import subprocess import sys import tempfile import time import random try: import pytest except ImportError: print >> sys.stderr, "Integ tests require pytests!" sys.exit(1) @pytest.fixture def servers(request):
65
114
383
7
58
msaf1980/statsite
integ/test_extended_counters.py
Python
servers
servers
18
79
18
19
4da91bf5d18b9ef2fae8fe2fbbee897f594f1a1f
bigcode/the-stack
train
d3b198abb996dd7f0bbcc96e
train
function
def add_all_commands(parser): """Add all spack subcommands to the parser.""" for cmd in spack.cmd.all_commands(): parser.add_command(cmd)
def add_all_commands(parser):
"""Add all spack subcommands to the parser.""" for cmd in spack.cmd.all_commands(): parser.add_command(cmd)
to getcwd, or spack prefix if no cwd.""" global spack_working_dir try: spack_working_dir = os.getcwd() except OSError: os.chdir(spack.paths.prefix) spack_working_dir = spack.paths.prefix def add_all_commands(parser):
64
64
34
6
57
bm3d/spack
lib/spack/spack/main.py
Python
add_all_commands
add_all_commands
103
106
103
103
721e9f1394ea925532ff9cc84faccf68033a292d
bigcode/the-stack
train
c5cb01df95e5d971aba5a18e
train
function
def index_commands(): """create an index of commands by section for this help level""" index = {} for command in spack.cmd.all_commands(): cmd_module = spack.cmd.get_module(command) # make sure command modules have required properties for p in required_command_properties: ...
def index_commands():
"""create an index of commands by section for this help level""" index = {} for command in spack.cmd.all_commands(): cmd_module = spack.cmd.get_module(command) # make sure command modules have required properties for p in required_command_properties: prop = getattr(cmd_m...
() except OSError: os.chdir(spack.paths.prefix) spack_working_dir = spack.paths.prefix def add_all_commands(parser): """Add all spack subcommands to the parser.""" for cmd in spack.cmd.all_commands(): parser.add_command(cmd) def index_commands():
64
64
161
4
60
bm3d/spack
lib/spack/spack/main.py
Python
index_commands
index_commands
109
130
109
109
9392d180044ef09f22fdc32402db35346e9bd909
bigcode/the-stack
train
b17b5e921f98d5820421f97f
train
function
def main(argv=None): """This is the entry point for the Spack command. Args: argv (list of str or None): command line arguments, NOT including the executable name. If None, parses from sys.argv. """ # Create a parser with a simple positional argument first. We'll # lazily load ...
def main(argv=None):
"""This is the entry point for the Spack command. Args: argv (list of str or None): command line arguments, NOT including the executable name. If None, parses from sys.argv. """ # Create a parser with a simple positional argument first. We'll # lazily load the subcommand(s) we ...
upstreams') or {} for install_properties in other_spack_instances.values(): upstream_module_roots = install_properties.get('modules', {}) for module_type, root in upstream_module_roots.items(): module_to_roots[module_type].append(root) for name, paths in module_to_roots.items(): ...
231
231
773
5
226
bm3d/spack
lib/spack/spack/main.py
Python
main
main
616
717
616
616
1dcb8ce15866025c51037bcd58533920f8236cb7
bigcode/the-stack
train
6048cf9e89a2669c317b1c98
train
function
def allows_unknown_args(command): """Implements really simple argument injection for unknown arguments. Commands may add an optional argument called "unknown args" to indicate they can handle unknonwn args, and we'll pass the unknown args in. """ info = dict(inspect.getmembers(command)) var...
def allows_unknown_args(command):
"""Implements really simple argument injection for unknown arguments. Commands may add an optional argument called "unknown args" to indicate they can handle unknonwn args, and we'll pass the unknown args in. """ info = dict(inspect.getmembers(command)) varnames = info['__code__'].co_varnam...
tty.warn("You asked for --insecure. Will NOT check SSL certificates.") spack.config.set('config:verify_ssl', False, scope='command_line') # when to use color (takes always, auto, or never) color.set_color_when(args.color) def allows_unknown_args(command):
64
64
112
6
58
bm3d/spack
lib/spack/spack/main.py
Python
allows_unknown_args
allows_unknown_args
427
437
427
427
4c38e71cffee7eafa4f2dbc3d3e2976fc4442a82
bigcode/the-stack
train
aaa652be58e35d0eb9e6ebab
train
function
def setup_main_options(args): """Configure spack globals based on the basic options.""" # Set up environment based on args. tty.set_verbose(args.verbose) tty.set_debug(args.debug) tty.set_stacktrace(args.stacktrace) # debug must be set first so that it can even affect behvaior of # errors r...
def setup_main_options(args):
"""Configure spack globals based on the basic options.""" # Set up environment based on args. tty.set_verbose(args.verbose) tty.set_debug(args.debug) tty.set_stacktrace(args.stacktrace) # debug must be set first so that it can even affect behvaior of # errors raised by spack.config. if ...
'--stacktrace', action='store_true', help="add stacktraces to all printed statements") parser.add_argument( '-V', '--version', action='store_true', help='show version number and exit') parser.add_argument( '--print-shell-vars', action='store', help="print info needed by ...
86
86
287
6
79
bm3d/spack
lib/spack/spack/main.py
Python
setup_main_options
setup_main_options
392
424
392
392
b67c3848aeec1663f80d66018134938367b8c5ef
bigcode/the-stack
train
df060e88562dd7075a37a149
train
function
def _invoke_command(command, parser, args, unknown_args): """Run a spack command *without* setting spack global options.""" if allows_unknown_args(command): return_val = command(parser, args, unknown_args) else: if unknown_args: tty.die('unrecognized arguments: %s' % ' '.join(unk...
def _invoke_command(command, parser, args, unknown_args):
"""Run a spack command *without* setting spack global options.""" if allows_unknown_args(command): return_val = command(parser, args, unknown_args) else: if unknown_args: tty.die('unrecognized arguments: %s' % ' '.join(unknown_args)) return_val = command(parser, args) ...
.getmembers(command)) varnames = info['__code__'].co_varnames argcount = info['__code__'].co_argcount return (argcount == 3 and varnames[2] == 'unknown_args') def _invoke_command(command, parser, args, unknown_args):
64
64
111
13
51
bm3d/spack
lib/spack/spack/main.py
Python
_invoke_command
_invoke_command
440
450
440
440
cfbc4a90e42233daf6263d3ab4647fa41999e378
bigcode/the-stack
train
448f5506dd8232f133e79f0a
train
function
def print_setup_info(*info): """Print basic information needed by setup-env.[c]sh. Args: info (list of str): list of things to print: comma-separated list of 'csh', 'sh', or 'modules' This is in ``main.py`` to make it fast; the setup scripts need to invoke spack in login scripts, a...
def print_setup_info(*info):
"""Print basic information needed by setup-env.[c]sh. Args: info (list of str): list of things to print: comma-separated list of 'csh', 'sh', or 'modules' This is in ``main.py`` to make it fast; the setup scripts need to invoke spack in login scripts, and it needs to be quick. ...
s' % args.lines) nlines = -1 # allow comma-separated list of fields sortby = ['time'] if args.sorted_profile: sortby = args.sorted_profile.split(',') for stat in sortby: if stat not in stat_names: tty.die("Invalid sort field: %s" % stat) try: ...
157
157
525
7
150
bm3d/spack
lib/spack/spack/main.py
Python
print_setup_info
print_setup_info
556
613
556
556
5966167676d2bb8b7beaea4706057620e582879d
bigcode/the-stack
train
dfdefbcaef74ea9c5ac662af
train
function
def make_argument_parser(**kwargs): """Create an basic argument parser without any subcommands added.""" parser = SpackArgumentParser( formatter_class=SpackHelpFormatter, add_help=False, description=( "A flexible package manager that supports multiple versions,\n" "config...
def make_argument_parser(**kwargs):
"""Create an basic argument parser without any subcommands added.""" parser = SpackArgumentParser( formatter_class=SpackHelpFormatter, add_help=False, description=( "A flexible package manager that supports multiple versions,\n" "configurations, platforms, and compilers."...
1].dest == 'command': self._remove_action(self._actions[-1]) self.subparsers = self.add_subparsers(metavar='COMMAND', dest="command") # each command module implements a parser() function, to which we # pass its subparser for ...
256
256
860
7
249
bm3d/spack
lib/spack/spack/main.py
Python
make_argument_parser
make_argument_parser
303
389
303
303
fa77dcfe68ea3529f9e5ca31d20e6954bc77ac95
bigcode/the-stack
train
e5644a1471a61893a4ce101c
train
class
class SpackCommandError(Exception): """Raised when SpackCommand execution fails."""
class SpackCommandError(Exception):
"""Raised when SpackCommand execution fails."""
if spack.config.get('config:debug'): raise sys.stderr.write('\n') tty.die("Keyboard interrupt.") except SystemExit as e: if spack.config.get('config:debug'): traceback.print_exc() return e.code class SpackCommandError(Exception):
64
64
17
7
56
bm3d/spack
lib/spack/spack/main.py
Python
SpackCommandError
SpackCommandError
720
721
720
720
6d093659a8968fd0cd96b23080cd1dbed75d746f
bigcode/the-stack
train
428f7f36363946c67d2e9c41
train
class
class SpackHelpFormatter(argparse.RawTextHelpFormatter): def _format_actions_usage(self, actions, groups): """Formatter with more concise usage strings.""" usage = super( SpackHelpFormatter, self)._format_actions_usage(actions, groups) # compress single-character flags that are ...
class SpackHelpFormatter(argparse.RawTextHelpFormatter):
def _format_actions_usage(self, actions, groups): """Formatter with more concise usage strings.""" usage = super( SpackHelpFormatter, self)._format_actions_usage(actions, groups) # compress single-character flags that are not mutually exclusive # at the beginning of the ...
and higher levels for level in reversed(levels): level_sections = index.setdefault(level, {}) commands = level_sections.setdefault(cmd_module.section, []) commands.append(command) if level == cmd_module.level: break return index class SpackHe...
64
64
131
12
51
bm3d/spack
lib/spack/spack/main.py
Python
SpackHelpFormatter
SpackHelpFormatter
133
146
133
133
47d488a5cbb89630fbc8dc36bc1c00fbc1c4c94a
bigcode/the-stack
train
ffd2c295ff13e80cd746dedc
train
function
def _profile_wrapper(command, parser, args, unknown_args): import cProfile try: nlines = int(args.lines) except ValueError: if args.lines != 'all': tty.die('Invalid number for --lines: %s' % args.lines) nlines = -1 # allow comma-separated list of fields sortby =...
def _profile_wrapper(command, parser, args, unknown_args):
import cProfile try: nlines = int(args.lines) except ValueError: if args.lines != 'all': tty.die('Invalid number for --lines: %s' % args.lines) nlines = -1 # allow comma-separated list of fields sortby = ['time'] if args.sorted_profile: sortby = args...
SpackCommandError( "Command exited with code %d: %s(%s)" % ( self.returncode, self.command_name, ', '.join("'%s'" % a for a in argv))) return out.getvalue() def _profile_wrapper(command, parser, args, unknown_args):
64
64
204
13
51
bm3d/spack
lib/spack/spack/main.py
Python
_profile_wrapper
_profile_wrapper
523
553
523
523
40f628c15df43d31246fc8188c159acb1a40eed2
bigcode/the-stack
train
12bb809df2a74a62c6b696a2
train
class
class SpackCommand(object): """Callable object that invokes a spack command (for testing). Example usage:: install = SpackCommand('install') install('-v', 'mpich') Use this to invoke Spack commands directly from Python and check their output. """ def __init__(self, command_nam...
class SpackCommand(object):
"""Callable object that invokes a spack command (for testing). Example usage:: install = SpackCommand('install') install('-v', 'mpich') Use this to invoke Spack commands directly from Python and check their output. """ def __init__(self, command_name): """Create a new ...
count return (argcount == 3 and varnames[2] == 'unknown_args') def _invoke_command(command, parser, args, unknown_args): """Run a spack command *without* setting spack global options.""" if allows_unknown_args(command): return_val = command(parser, args, unknown_args) else: if unknown_...
138
138
461
6
131
bm3d/spack
lib/spack/spack/main.py
Python
SpackCommand
SpackCommand
453
520
453
453
284625213e76dcfb233e676fcd7ef7253a1419dc
bigcode/the-stack
train
f3cb921e6dd0680cdf4c3c46
train
class
class SpackArgumentParser(argparse.ArgumentParser): def format_help_sections(self, level): """Format help on sections for a particular verbosity level. Args: level (str): 'short' or 'long' (more commands shown for long) """ if level not in levels: raise Value...
class SpackArgumentParser(argparse.ArgumentParser):
def format_help_sections(self, level): """Format help on sections for a particular verbosity level. Args: level (str): 'short' or 'long' (more commands shown for long) """ if level not in levels: raise ValueError("level must be one of: %s" % levels) ...
sure command modules have required properties for p in required_command_properties: prop = getattr(cmd_module, p, None) if not prop: tty.die("Command doesn't define a property '%s': %s" % (p, command)) # add commands to lists for their le...
256
256
1,217
10
245
bm3d/spack
lib/spack/spack/main.py
Python
SpackArgumentParser
SpackArgumentParser
149
300
149
149
ab0a91f49f214900df06972727b8ed1c99c441b7
bigcode/the-stack
train
984ab4896a9e2cd6280e4560
train
function
def set_working_dir(): """Change the working directory to getcwd, or spack prefix if no cwd.""" global spack_working_dir try: spack_working_dir = os.getcwd() except OSError: os.chdir(spack.paths.prefix) spack_working_dir = spack.paths.prefix
def set_working_dir():
"""Change the working directory to getcwd, or spack prefix if no cwd.""" global spack_working_dir try: spack_working_dir = os.getcwd() except OSError: os.chdir(spack.paths.prefix) spack_working_dir = spack.paths.prefix
install', 'clean'], 'packaging': ['create', 'edit'] } #: Properties that commands are required to set. required_command_properties = ['level', 'section', 'description'] #: Recorded directory where spack command was originally invoked spack_working_dir = None def set_working_dir():
64
64
70
6
57
bm3d/spack
lib/spack/spack/main.py
Python
set_working_dir
set_working_dir
93
100
93
93
db10c28876d03ff66aea83d5f755384ca17ceb1c
bigcode/the-stack
train
461dcf702fe0850c42671987
train
class
class Reaction(EqualityMixin): """A nuclear reaction A Reaction object represents a single reaction channel for a nuclide with an associated cross section and, if present, a secondary angle and energy distribution. Parameters ---------- mt : int The ENDF MT number for this reaction...
class Reaction(EqualityMixin):
"""A nuclear reaction A Reaction object represents a single reaction channel for a nuclide with an associated cross section and, if present, a secondary angle and energy distribution. Parameters ---------- mt : int The ENDF MT number for this reaction. Attributes ---------...
): photon = Product('photon') items, xs = get_tab1_record(file_obj) # Re-interpolate photon production cross section and neutron cross # section to union energy grid energy = np.union1d(xs.x, rx.xs['0K'].x) photon_prod_xs = xs(energy) ...
256
256
3,545
6
249
ypark234/openmc
openmc/data/reaction.py
Python
Reaction
Reaction
765
1,193
765
765
b453ae6ec3e850ab63e0253934ffd8cc5fd0cde9
bigcode/the-stack
train
2d0fb8c1610bddcf735518f4
train
function
def _get_products(ev, mt): """Generate products from MF=6 in an ENDF evaluation Parameters ---------- ev : openmc.data.endf.Evaluation ENDF evaluation to read from mt : int The MT value of the reaction to get products for Returns ------- products : list of openmc.data.P...
def _get_products(ev, mt):
"""Generate products from MF=6 in an ENDF evaluation Parameters ---------- ev : openmc.data.endf.Evaluation ENDF evaluation to read from mt : int The MT value of the reaction to get products for Returns ------- products : list of openmc.data.Product Products of ...
tc)', 799: '(n,3Hec)', 849: '(n,ac)', 891: '(n,2nc)', 901: 'heating-local'} REACTION_NAME.update({i: '(n,n{})'.format(i - 50) for i in range(50, 91)}) REACTION_NAME.update({i: '(n,p{})'.format(i - 600) for i in range(600, 649)}) REACTION_NAME.update({i: '(n,d{})'.format(i - 650) for i in range(650, 699...
246
247
824
8
239
ypark234/openmc
openmc/data/reaction.py
Python
_get_products
_get_products
68
187
68
68
a97cdfddc0f4f8081b2446a9d451804f4fb5280f
bigcode/the-stack
train
cb437ef7122000baba02a50c
train
function
def _get_photon_products_endf(ev, rx): """Generate photon products from an ENDF evaluation Parameters ---------- ev : openmc.data.endf.Evaluation ENDF evaluation to read from rx : openmc.data.Reaction Reaction that generates photons Returns ------- products : list of op...
def _get_photon_products_endf(ev, rx):
"""Generate photon products from an ENDF evaluation Parameters ---------- ev : openmc.data.endf.Evaluation ENDF evaluation to read from rx : openmc.data.Reaction Reaction that generates photons Returns ------- products : list of openmc.Products Photons produced ...
{0}".format( mftype)) # ================================================================== # Photon energy distribution location_start = int(ace.xss[ace.jxs[18] + i]) distribution = AngleEnergy.from_ace(ace, ace.jxs[19], location_start) assert isinstance(distri...
245
245
819
12
232
ypark234/openmc
openmc/data/reaction.py
Python
_get_photon_products_endf
_get_photon_products_endf
654
762
654
654
b674215799c0f08105e8fc30da6608bc5da4250b
bigcode/the-stack
train
55ce115e665a8d585757e0c0
train
function
def _get_activation_products(ev, rx): """Generate activation products from an ENDF evaluation Parameters ---------- ev : openmc.data.endf.Evaluation The ENDF evaluation rx : openmc.data.Reaction Reaction which generates activation products Returns ------- products : lis...
def _get_activation_products(ev, rx):
"""Generate activation products from an ENDF evaluation Parameters ---------- ev : openmc.data.endf.Evaluation The ENDF evaluation rx : openmc.data.Reaction Reaction which generates activation products Returns ------- products : list of openmc.data.Product Activ...
d(yield_.x, applicability.x) energy = energy[energy <= max_energy] # Calculate group yield group_yield = yield_(energy) * applicability(energy) delayed_neutron.yield_ = Tabulated1D(energy, group_yield) elif ...
187
187
625
9
177
ypark234/openmc
openmc/data/reaction.py
Python
_get_activation_products
_get_activation_products
469
553
469
469
d7c8f9d0a57f834589cdc29715a422c90b9b09a5
bigcode/the-stack
train
80f8774874410a0f69b98a68
train
function
def _get_fission_products_endf(ev): """Generate fission products from an ENDF evaluation Parameters ---------- ev : openmc.data.endf.Evaluation Returns ------- products : list of openmc.data.Product Prompt and delayed fission neutrons derived_products : list of openmc.data.Prod...
def _get_fission_products_endf(ev):
"""Generate fission products from an ENDF evaluation Parameters ---------- ev : openmc.data.endf.Evaluation Returns ------- products : list of openmc.data.Product Prompt and delayed fission neutrons derived_products : list of openmc.data.Product "Total" fission neutron ...
d(yield_delayed.x, group_probability.x) energy = energy[energy <= max_energy] # Calculate group yield group_yield = yield_delayed(energy) * group_probability(energy) delayed_neutron.yield_ = Tabulated1D(energy, group_yield) # Advance position...
256
256
1,187
10
245
ypark234/openmc
openmc/data/reaction.py
Python
_get_fission_products_endf
_get_fission_products_endf
327
466
327
327
9ff98ef9b8bda9dc2193a40ac577be9e947de3ec
bigcode/the-stack
train
4faf54836025c8842a325be8
train
function
def _get_fission_products_ace(ace): """Generate fission products from an ACE table Parameters ---------- ace : openmc.data.ace.Table ACE table to read from Returns ------- products : list of openmc.data.Product Prompt and delayed fission neutrons derived_products : list...
def _get_fission_products_ace(ace):
"""Generate fission products from an ACE table Parameters ---------- ace : openmc.data.ace.Table ACE table to read from Returns ------- products : list of openmc.data.Product Prompt and delayed fission neutrons derived_products : list of openmc.data.Product "Tot...
== 0: mu.append(Legendre(values)) elif lang == 12: mu.append(Tabular(values[::2], values[1::2])) elif lang == 14: mu.append(Tabular(values[::2], values[1::2], 'log-linear')) an...
256
256
1,236
11
244
ypark234/openmc
openmc/data/reaction.py
Python
_get_fission_products_ace
_get_fission_products_ace
190
324
190
190
2b3b666b6d538ca63ab5a15d3c78d07712225e6d
bigcode/the-stack
train
334ec24ef9c94b1e86fdf1f3
train
function
def _get_photon_products_ace(ace, rx): """Generate photon products from an ACE table Parameters ---------- ace : openmc.data.ace.Table ACE table to read from rx : openmc.data.Reaction Reaction that generates photons Returns ------- photons : list of openmc.Products ...
def _get_photon_products_ace(ace, rx):
"""Generate photon products from an ACE table Parameters ---------- ace : openmc.data.ace.Table ACE table to read from rx : openmc.data.Reaction Reaction that generates photons Returns ------- photons : list of openmc.Products Photons produced from reaction with...
: name = '{}{}'.format(symbol, A) p = Product(name) if mf == 9: p.yield_ = xs else: # Re-interpolate production cross section and neutron cross # section to union energy grid energy = np.union1d(xs.x, rx...
239
239
799
13
225
ypark234/openmc
openmc/data/reaction.py
Python
_get_photon_products_ace
_get_photon_products_ace
556
651
556
556
b035ff4e264f95628991e58e06b1daf841e63167
bigcode/the-stack
train
ceec47f99f059b8b378cc772
train
function
def during_execution_memory_sampler(): import time import memory_profiler global keep_watching, peak_memory_usage peak_memory_usage = -1 keep_watching = True n = 0 WAIT_BETWEEN_SAMPLES_SECS = 0.001 MAX_ITERATIONS = 60.0 / WAIT_BETWEEN_SAMPLES_SECS while True: mem_usage = mem...
def during_execution_memory_sampler():
import time import memory_profiler global keep_watching, peak_memory_usage peak_memory_usage = -1 keep_watching = True n = 0 WAIT_BETWEEN_SAMPLES_SECS = 0.001 MAX_ITERATIONS = 60.0 / WAIT_BETWEEN_SAMPLES_SECS while True: mem_usage = memory_profiler.memory_usage()[0] ...
_TYPE, perf_average), perf_values) print("perf value for {} averages to {:,}/second".format(perf_process.EVENT_TYPE, perf_average)) else: print("perf - no results to report, possibly the collection time was too short?") previous_call_memory_usage = new_memory_usage def during_execution_memory_sa...
69
69
233
6
62
jni/numpy-skimage-tutorial
ipython_memory_usage/ipython_memory_usage_perf.py
Python
during_execution_memory_sampler
during_execution_memory_sampler
64
85
64
64
c744faadc6f776688010d102fd12356e0677fc23
bigcode/the-stack
train
c3a999402b6561fdbcb555d2
train
function
def pre_run_cell(): """Capture current time before we execute the current command""" import time import os global perf_proc, t1 # t1 records the start time of this execution cycle t1 = time.time() # start a thread that samples RAM usage until the current command finishes import threadin...
def pre_run_cell():
"""Capture current time before we execute the current command""" import time import os global perf_proc, t1 # t1 records the start time of this execution cycle t1 = time.time() # start a thread that samples RAM usage until the current command finishes import threading ipython_memory...
we don't want this to carry on running) if n > MAX_ITERATIONS: print("{} SOMETHING WEIRD HAPPENED AND THIS RAN FOR TOO LONG, THIS THREAD IS KILLING ITSELF".format(__file__)) break n += 1 def pre_run_cell():
64
64
125
5
58
jni/numpy-skimage-tutorial
ipython_memory_usage/ipython_memory_usage_perf.py
Python
pre_run_cell
pre_run_cell
88
103
88
88
1cc2d82647e2d9c1a6fdcabe9108bf0c119426b0
bigcode/the-stack
train
670e4c2a8fabc80c7f681a74
train
function
def watch_memory(): import time # bring in the global memory usage value from the previous iteration global previous_call_memory_usage, peak_memory_usage, keep_watching, perf_proc nbr_commands = len(In) new_memory_usage = memory_profiler.memory_usage()[0] memory_delta = new_memory_usage - previo...
def watch_memory():
import time # bring in the global memory usage value from the previous iteration global previous_call_memory_usage, peak_memory_usage, keep_watching, perf_proc nbr_commands = len(In) new_memory_usage = memory_profiler.memory_usage()[0] memory_delta = new_memory_usage - previous_call_memory_usage...
interrogate the CPU's performance counters""" from __future__ import division # 1/2 == 0.5, as in Py3 from __future__ import absolute_import # avoid hiding global modules with locals from __future__ import print_function # force use of print("hello") from __future__ import unicode_literals # force unadorned string...
177
177
593
4
172
jni/numpy-skimage-tutorial
ipython_memory_usage/ipython_memory_usage_perf.py
Python
watch_memory
watch_memory
22
61
22
22
23da0d48422a19dbbab80d786cd956c7feda4102
bigcode/the-stack
train
20a34b06cf5ff79bbfe682c5
train
function
@pytest.mark.sampledata def test_numberly(pd): import bokeh.sampledata.perceptions as bsp assert isinstance(bsp.numberly, pd.DataFrame) # check detail for package data assert len(bsp.numberly) == 46
@pytest.mark.sampledata def test_numberly(pd):
import bokeh.sampledata.perceptions as bsp assert isinstance(bsp.numberly, pd.DataFrame) # check detail for package data assert len(bsp.numberly) == 46
#----------------------------------------------------------------------------- # Setup #----------------------------------------------------------------------------- ALL = ( 'numberly', 'probly', ) #----------------------------------------------------------------------------- # General API #------------------...
64
64
54
11
53
axil/bokeh
bokeh/sampledata/tests/test_perceptions.py
Python
test_numberly
test_numberly
45
51
45
46
7f75389723e504f0b481c8ad038bacc1ae03c6dc
bigcode/the-stack
train
14048e9bc61fd80043c7f1e5
train
function
@pytest.mark.sampledata def test_probly(pd): import bokeh.sampledata.perceptions as bsp assert isinstance(bsp.probly, pd.DataFrame) # check detail for package data assert len(bsp.probly) == 46
@pytest.mark.sampledata def test_probly(pd):
import bokeh.sampledata.perceptions as bsp assert isinstance(bsp.probly, pd.DataFrame) # check detail for package data assert len(bsp.probly) == 46
.mark.sampledata def test_numberly(pd): import bokeh.sampledata.perceptions as bsp assert isinstance(bsp.numberly, pd.DataFrame) # check detail for package data assert len(bsp.numberly) == 46 @pytest.mark.sampledata def test_probly(pd):
64
64
54
11
52
axil/bokeh
bokeh/sampledata/tests/test_perceptions.py
Python
test_probly
test_probly
53
59
53
54
c3bba031a6ceff492975edc3bcfa106a86a8686b
bigcode/the-stack
train
aac7ae0ee05fa63f54302a4c
train
function
def check_again_chunk(sentence): end_length = len(sentence) start_length = 0 sent_to = re.search('to ',sentence) sent_AT = re.search(' AT ',sentence) sent_at = re.search('at ', sentence) sent_need = re.search('need ',sentence) if sent_to: start_length = sent_to.end() if sent_AT: ...
def check_again_chunk(sentence):
end_length = len(sentence) start_length = 0 sent_to = re.search('to ',sentence) sent_AT = re.search(' AT ',sentence) sent_at = re.search('at ', sentence) sent_need = re.search('need ',sentence) if sent_to: start_length = sent_to.end() if sent_AT: end_length = sent_AT.star...
True: sent_to_found.append(sent_n.start()-min_length) max_length = min(sent_to_found) return sentence[length + min_length:length + min_length + max_length] except AttributeError: pass ##Check if more than two start/end phrases are present def check_again_chunk(sentence):
64
64
124
6
57
surajtripathy/Custom-Phrase-Detector
chunk.py
Python
check_again_chunk
check_again_chunk
90
105
90
90
33617ef7561273cdb5805758a10865731b1cbbad
bigcode/the-stack
train
256ed949f97dd25e417be5fe
train
function
def chunked(sentence): try: length = 0 sent_to = re.search('to ',sentence[length:]) sent_for = re.search('for ',sentence[length:]) sent_of = re.search('of ',sentence[length:]) sent_about = re.search('about ', sentence[length:]) sent_at = re.search('at ',sentence[lengt...
def chunked(sentence):
try: length = 0 sent_to = re.search('to ',sentence[length:]) sent_for = re.search('for ',sentence[length:]) sent_of = re.search('of ',sentence[length:]) sent_about = re.search('about ', sentence[length:]) sent_at = re.search('at ',sentence[length:]) sent_on =r...
''' Author : Suraj Tripathy ''' import re ##Check for important keywords like to for of at on etc for start and end of phrases def chunked(sentence):
36
199
664
5
30
surajtripathy/Custom-Phrase-Detector
chunk.py
Python
chunked
chunked
7
88
7
7
2935d0903837d85f51110bdc86ff53cfbbef0122
bigcode/the-stack
train
178be2a8aa088d15f2cf3bad
train
class
class Coinbase(FeedSource): def _fetch(self): feed = {} for base in self.bases: for quote in self.quotes: if quote == base: continue pair = '{}-{}'.format(quote.upper(), base.upper()) url = "https://api.pro.coinbase.com...
class Coinbase(FeedSource):
def _fetch(self): feed = {} for base in self.bases: for quote in self.quotes: if quote == base: continue pair = '{}-{}'.format(quote.upper(), base.upper()) url = "https://api.pro.coinbase.com/products/{}/ticker".format(...
import requests from . import FeedSource, _request_headers class Coinbase(FeedSource):
19
64
152
6
12
bitshares/nbs-pricefeed
bitshares_pricefeed/sources/coinbase.py
Python
Coinbase
Coinbase
4
20
4
4
85f3551837945adc5c6c66b15f670b80c31da089
bigcode/the-stack
train
782873c55872bbb1d4bef904
train
class
class Solution: def climbStairs(self, n: int) -> int: a, b = 1, 0 for _ in range(n + 1): a, b = a + b, a return b
class Solution:
def climbStairs(self, n: int) -> int: a, b = 1, 0 for _ in range(n + 1): a, b = a + b, a return b
class Solution:
3
64
52
3
0
lyphui/Just-Code
src/0070.climbing-stairs/climbing-stairs.py
Python
Solution
Solution
1
6
1
1
c968c5aef31c879f66e84a884cea2f16ab1ce25c
bigcode/the-stack
train
eb9c92c1c6a3adf75eecfa47
train
class
class QtumTransactionPrioritizationTest(BitcoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 self.extra_args = [['-staking=1', '-rpcmaxgasprice=10000000']] def skip_test_if_missing_module(self): self.skip_if_no_wallet() def rest...
class QtumTransactionPrioritizationTest(BitcoinTestFramework):
def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 self.extra_args = [['-staking=1', '-rpcmaxgasprice=10000000']] def skip_test_if_missing_module(self): self.skip_if_no_wallet() def restart_node(self): self.stop_nodes() self.start_no...
#!/usr/bin/env python3 from test_framework.test_framework import BitcoinTestFramework from test_framework.util import * from test_framework.script import * from test_framework.mininode import * from test_framework.address import * from test_framework.qtum import * import sys import random import time class QtumTransac...
71
256
3,585
13
57
100milliondollars/NeuQ
test/functional/qtum_transaction_prioritization.py
Python
QtumTransactionPrioritizationTest
QtumTransactionPrioritizationTest
13
289
13
13
9a385788b56617112fba95ead3e52a8186e9bd92
bigcode/the-stack
train
5b4361903febe78fabd2bf20
train
function
@pytest.mark.xfail(reason="Continue not implemented.") def test_nested_while_break(capsys: pytest.CaptureFixture) -> None: interpreter = Lox() interpreter.run(TEST_SRC) assert not interpreter.had_error assert not interpreter.had_runtime_error all_out = capsys.readouterr().out.splitlines() asse...
@pytest.mark.xfail(reason="Continue not implemented.") def test_nested_while_break(capsys: pytest.CaptureFixture) -> None:
interpreter = Lox() interpreter.run(TEST_SRC) assert not interpreter.had_error assert not interpreter.had_runtime_error all_out = capsys.readouterr().out.splitlines() assert all_out == EXPECTED_STDOUTS
inner // expect: 10 """ ) EXPECTED_STDOUTS = ["0", "inner", "10", "1", "inner", "10"] @pytest.mark.xfail(reason="Continue not implemented.") def test_nested_while_break(capsys: pytest.CaptureFixture) -> None:
63
64
82
28
35
sco1/pylox
tests/continue/test_nested_while_continue.py
Python
test_nested_while_break
test_nested_while_break
38
47
38
39
13f18db14aea8cf8d620567da417aea89a799631
bigcode/the-stack
train
bb3433729164cc2646bed76e
train
function
def ins_to_sem_compatibility(sem_labels_for_instances, num_sem_labels, stuff_sem_cls_ids, stuff_penalisation=1.0): """ Returns the compatibility matrix for the instance_labels -> semantic_labels bipartite potentials in BCRF. Args: sem_labels_for_instances: Semantic labels of the instances. 0th in...
def ins_to_sem_compatibility(sem_labels_for_instances, num_sem_labels, stuff_sem_cls_ids, stuff_penalisation=1.0):
""" Returns the compatibility matrix for the instance_labels -> semantic_labels bipartite potentials in BCRF. Args: sem_labels_for_instances: Semantic labels of the instances. 0th instance must be 'no_instance' with label -1 num_sem_labels: The total number of semantic labels ...
from itertools import islice import numpy as np def ins_to_sem_compatibility(sem_labels_for_instances, num_sem_labels, stuff_sem_cls_ids, stuff_penalisation=1.0):
42
114
382
31
10
sahan-liyanaarachchi/bcrf-detectron
crf/compatibility_transform.py
Python
ins_to_sem_compatibility
ins_to_sem_compatibility
6
33
6
6
434a9397c05c87a511395626208120652462bb3a
bigcode/the-stack
train
51df81fe1cadf99f47fb1353
train
class
class Mode(Enum): SHOW = 1 DRAW = 2 ERASE = 3
class Mode(Enum):
SHOW = 1 DRAW = 2 ERASE = 3
ImageViewerTool from core import settings from PyQt5.QtCore import QEvent from PyQt5.QtCore import Qt from enum import Enum import cv2 import numpy as np from skimage.draw import circle import skimage.measure RADIUS = 22 class Mode(Enum):
64
64
23
4
59
IvanKosik/ImageVision
image_vision/plugins/image_viewer/tools/smart_brush_segmentation/smart_brush_segmentation_tool.py
Python
Mode
Mode
16
19
16
16
f53eaa9d243b2641c57391c4362d49d637ad3e25
bigcode/the-stack
train
34fd4526ed959266b953f4c1
train
class
class SmartBrushSegmentationTool(ImageViewerTool): def __init__(self, viewer, parent=None): super().__init__(viewer, parent) self.mode = Mode.SHOW self.radius = RADIUS self.paint_central_pixel_cluster = True self.paint_dark_cluster = False self.paint_connected_com...
class SmartBrushSegmentationTool(ImageViewerTool):
def __init__(self, viewer, parent=None): super().__init__(viewer, parent) self.mode = Mode.SHOW self.radius = RADIUS self.paint_central_pixel_cluster = True self.paint_dark_cluster = False self.paint_connected_component = True def _activation(self): s...
from plugins.image_viewer.tools.image_viewer_tool import ImageViewerTool from core import settings from PyQt5.QtCore import QEvent from PyQt5.QtCore import Qt from enum import Enum import cv2 import numpy as np from skimage.draw import circle import skimage.measure RADIUS = 22 class Mode(Enum): SHOW = 1 DR...
104
256
1,145
10
93
IvanKosik/ImageVision
image_vision/plugins/image_viewer/tools/smart_brush_segmentation/smart_brush_segmentation_tool.py
Python
SmartBrushSegmentationTool
SmartBrushSegmentationTool
22
150
22
22
f276ba8b8eae0dc787c36e98282ead270c065930
bigcode/the-stack
train
7ece6d2187196d1b598a2f40
train
class
class IntLambdaData(SerialJ): schema = [ {'name': 'prop4', 'type': (int, lambda x: x % 2 == 0)} ]
class IntLambdaData(SerialJ):
schema = [ {'name': 'prop4', 'type': (int, lambda x: x % 2 == 0)} ]
from serial_j import SerialJ class IntLambdaData(SerialJ):
15
64
39
8
6
junpuf/serial-j
examples/type/int_lambda_data.py
Python
IntLambdaData
IntLambdaData
4
7
4
4
a45ae21db67198f90b2359c0698626f7fe10caea
bigcode/the-stack
train
3f3280d5f346b45968b33616
train
class
class BertPoolOutMax(nn.Module): def __init__(self, config, gpu_list, *args, **params): super(BertPoolOutMax, self).__init__() self.max_para_c = config.getint('model', 'max_para_c') self.max_para_q = config.getint('model', 'max_para_q') self.step = config.getint('model', 'step')...
class BertPoolOutMax(nn.Module):
def __init__(self, config, gpu_list, *args, **params): super(BertPoolOutMax, self).__init__() self.max_para_c = config.getint('model', 'max_para_c') self.max_para_q = config.getint('model', 'max_para_q') self.step = config.getint('model', 'step') self.max_len = config.ge...
# -*- coding: utf-8 -*- __author__ = 'yshao' import torch import torch.nn as nn import torch.nn.functional as F from pytorch_pretrained_bert import BertModel class BertPoolOutMax(nn.Module):
54
174
581
8
45
climberwb/bert-pli
model/nlp/BertPoolOutMax.py
Python
BertPoolOutMax
BertPoolOutMax
11
58
11
11
3514122901bb450278b16d76b5f4a043ca659a47
bigcode/the-stack
train
e0df65f76f01ad9f2e81d1ac
train
class
class Function: """ class that represents a membership function in a variable """ def __init__(self, label = ""): """ constructor """ self.points = [] self.label = label self.fs = 0.0 self.cog = 0.0 def add_point(self, point): """ appends a points to the the list of points and sorts th...
class Function:
""" class that represents a membership function in a variable """ def __init__(self, label = ""): """ constructor """ self.points = [] self.label = label self.fs = 0.0 self.cog = 0.0 def add_point(self, point): """ appends a points to the the list of points and sorts the list ...
''' This file is part of pyfuzz. Copyright 2009 Frederic Morcos <fred.morcos@gmail.com> pyfuzz is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) ...
188
256
879
3
185
fredmorcos/attic
Projects/PyFuzz/function.py
Python
Function
Function
20
108
20
20
09ba0ba317a9928a054b00102bdb38069f22f87e
bigcode/the-stack
train
b081e19cb614c454208f6edf
train
class
class ShortLinkReq(BaseSchema): # Share swagger.json title = fields.Str(required=False) url = fields.Str(required=False) hash = fields.Str(required=False) active = fields.Boolean(required=False) expire_at = fields.Str(required=False) enable_tracking = fields.Bo...
class ShortLinkReq(BaseSchema): # Share swagger.json
title = fields.Str(required=False) url = fields.Str(required=False) hash = fields.Str(required=False) active = fields.Boolean(required=False) expire_at = fields.Str(required=False) enable_tracking = fields.Boolean(required=False) personalized = fields.Boolean(re...
from ..enums import * from ..models.BaseSchema import BaseSchema from .CampaignShortLink import CampaignShortLink from .Redirects import Redirects from .Attribution import Attribution from .SocialMediaTags import SocialMediaTags class ShortLinkReq(BaseSchema): # Share swagger.json
64
64
148
14
49
kavish-d/fdk-client-python
fdk_client/platform/models/ShortLinkReq.py
Python
ShortLinkReq
ShortLinkReq
33
59
33
36
f72f398283cb3bbf93487b12680d71e17967a194
bigcode/the-stack
train
eb036120ea3079c7add2de6f
train
function
def test_create_multidict_proxy_from_multidict_proxy_from_mdict(_multidict): d = _multidict.MultiDict(key='val') p = _multidict.MultiDictProxy(d) assert p == d p2 = _multidict.MultiDictProxy(p) assert p2 == p
def test_create_multidict_proxy_from_multidict_proxy_from_mdict(_multidict):
d = _multidict.MultiDict(key='val') p = _multidict.MultiDictProxy(d) assert p == d p2 = _multidict.MultiDictProxy(p) assert p2 == p
_from_cimultidict(_multidict): d = _multidict.CIMultiDict(key='val') p = _multidict.MultiDictProxy(d) assert p == d def test_create_multidict_proxy_from_multidict_proxy_from_mdict(_multidict):
64
64
71
20
43
blueyed/multidict
tests/test_types.py
Python
test_create_multidict_proxy_from_multidict_proxy_from_mdict
test_create_multidict_proxy_from_multidict_proxy_from_mdict
31
36
31
31
6260899c973523f38bfc51e605caa95e58d29204
bigcode/the-stack
train
b634ae2849f64d62eaf65e49
train
function
def test_dicts(_multidict): assert issubclass(_multidict.CIMultiDict, _multidict.MultiDict)
def test_dicts(_multidict):
assert issubclass(_multidict.CIMultiDict, _multidict.MultiDict)
import pytest def test_proxies(_multidict): assert issubclass(_multidict.CIMultiDictProxy, _multidict.MultiDictProxy) def test_dicts(_multidict):
44
64
30
9
35
blueyed/multidict
tests/test_types.py
Python
test_dicts
test_dicts
8
9
8
8
8e2c5618920996b929722d9b1a86692c6a0eaef8
bigcode/the-stack
train
3d8832bb47b93404311ae73b
train
function
def test_create_cimultidict_proxy_from_cimultidict_proxy_from_ci(_multidict): d = _multidict.CIMultiDict(key='val') p = _multidict.CIMultiDictProxy(d) assert p == d p2 = _multidict.CIMultiDictProxy(p) assert p2 == p
def test_create_cimultidict_proxy_from_cimultidict_proxy_from_ci(_multidict):
d = _multidict.CIMultiDict(key='val') p = _multidict.CIMultiDictProxy(d) assert p == d p2 = _multidict.CIMultiDictProxy(p) assert p2 == p
='val') p = _multidict.MultiDictProxy(d) assert p == d p2 = _multidict.MultiDictProxy(p) assert p2 == p def test_create_cimultidict_proxy_from_cimultidict_proxy_from_ci(_multidict):
64
64
80
23
40
blueyed/multidict
tests/test_types.py
Python
test_create_cimultidict_proxy_from_cimultidict_proxy_from_ci
test_create_cimultidict_proxy_from_cimultidict_proxy_from_ci
39
44
39
39
753dc8dffb1ebedfce54fd626a9b518e1caea73b
bigcode/the-stack
train
8ff68a613c5d2181e936854e
train
function
def test_create_multidict_proxy_from_nonmultidict(_multidict): with pytest.raises(TypeError): _multidict.MultiDictProxy({})
def test_create_multidict_proxy_from_nonmultidict(_multidict):
with pytest.raises(TypeError): _multidict.MultiDictProxy({})
idict.MultiDictProxy, _multidict.MultiDict) def test_dict_not_inherited_from_proxy(_multidict): assert not issubclass(_multidict.MultiDict, _multidict.MultiDictProxy) def test_create_multidict_proxy_from_nonmultidict(_multidict):
64
64
33
17
47
blueyed/multidict
tests/test_types.py
Python
test_create_multidict_proxy_from_nonmultidict
test_create_multidict_proxy_from_nonmultidict
20
22
20
20
a19bc5461e9cdc23a6999437857ce7a3b354264f
bigcode/the-stack
train
7c156db3305dc87c39537882
train
function
def test_proxies(_multidict): assert issubclass(_multidict.CIMultiDictProxy, _multidict.MultiDictProxy)
def test_proxies(_multidict):
assert issubclass(_multidict.CIMultiDictProxy, _multidict.MultiDictProxy)
import pytest def test_proxies(_multidict):
12
64
32
9
2
blueyed/multidict
tests/test_types.py
Python
test_proxies
test_proxies
4
5
4
4
1c402b1f2e41debf6f65e0684f7aecdec93401f8
bigcode/the-stack
train
071906e5f155565eaf4543b5
train
function
def test_dict_not_inherited_from_proxy(_multidict): assert not issubclass(_multidict.MultiDict, _multidict.MultiDictProxy)
def test_dict_not_inherited_from_proxy(_multidict):
assert not issubclass(_multidict.MultiDict, _multidict.MultiDictProxy)
class(_multidict.CIMultiDict, _multidict.MultiDict) def test_proxy_not_inherited_from_dict(_multidict): assert not issubclass(_multidict.MultiDictProxy, _multidict.MultiDict) def test_dict_not_inherited_from_proxy(_multidict):
64
64
34
13
51
blueyed/multidict
tests/test_types.py
Python
test_dict_not_inherited_from_proxy
test_dict_not_inherited_from_proxy
16
17
16
16
8f49cc5f0d6b8bd88a203d8081b57d08b8391305
bigcode/the-stack
train
92d22e3e8f0b20109950297a
train
function
def test_create_multidict_proxy_from_cimultidict(_multidict): d = _multidict.CIMultiDict(key='val') p = _multidict.MultiDictProxy(d) assert p == d
def test_create_multidict_proxy_from_cimultidict(_multidict):
d = _multidict.CIMultiDict(key='val') p = _multidict.MultiDictProxy(d) assert p == d
ict.MultiDict, _multidict.MultiDictProxy) def test_create_multidict_proxy_from_nonmultidict(_multidict): with pytest.raises(TypeError): _multidict.MultiDictProxy({}) def test_create_multidict_proxy_from_cimultidict(_multidict):
63
64
51
18
46
blueyed/multidict
tests/test_types.py
Python
test_create_multidict_proxy_from_cimultidict
test_create_multidict_proxy_from_cimultidict
25
28
25
25
c9d4ea0b5160764251acda9b6b2a7deaca16e4dc
bigcode/the-stack
train
c4cd9b0abf7bc372c915f4d2
train
function
def test_create_ci_multidict_proxy_from_multidict(_multidict): d = _multidict.MultiDict(key='val') with pytest.raises(TypeError): _multidict.CIMultiDictProxy(d)
def test_create_ci_multidict_proxy_from_multidict(_multidict):
d = _multidict.MultiDict(key='val') with pytest.raises(TypeError): _multidict.CIMultiDictProxy(d)
(p) assert p2 == p def test_create_cimultidict_proxy_from_nonmultidict(_multidict): with pytest.raises(TypeError): _multidict.CIMultiDictProxy({}) def test_create_ci_multidict_proxy_from_multidict(_multidict):
63
64
49
17
47
blueyed/multidict
tests/test_types.py
Python
test_create_ci_multidict_proxy_from_multidict
test_create_ci_multidict_proxy_from_multidict
52
55
52
52
f1cfa765439a16c91b2ef708a3dd645ca82232d1
bigcode/the-stack
train
d19a3f45909833b0e589ce34
train
function
def test_proxy_not_inherited_from_dict(_multidict): assert not issubclass(_multidict.MultiDictProxy, _multidict.MultiDict)
def test_proxy_not_inherited_from_dict(_multidict):
assert not issubclass(_multidict.MultiDictProxy, _multidict.MultiDict)
issubclass(_multidict.CIMultiDictProxy, _multidict.MultiDictProxy) def test_dicts(_multidict): assert issubclass(_multidict.CIMultiDict, _multidict.MultiDict) def test_proxy_not_inherited_from_dict(_multidict):
64
64
34
13
51
blueyed/multidict
tests/test_types.py
Python
test_proxy_not_inherited_from_dict
test_proxy_not_inherited_from_dict
12
13
12
12
de0098677f3dd8c7cab65470b4abb09cf05203da
bigcode/the-stack
train
4735de0abce127dcbcb4043a
train
function
def test_create_cimultidict_proxy_from_nonmultidict(_multidict): with pytest.raises(TypeError): _multidict.CIMultiDictProxy({})
def test_create_cimultidict_proxy_from_nonmultidict(_multidict):
with pytest.raises(TypeError): _multidict.CIMultiDictProxy({})
='val') p = _multidict.CIMultiDictProxy(d) assert p == d p2 = _multidict.CIMultiDictProxy(p) assert p2 == p def test_create_cimultidict_proxy_from_nonmultidict(_multidict):
64
64
37
19
44
blueyed/multidict
tests/test_types.py
Python
test_create_cimultidict_proxy_from_nonmultidict
test_create_cimultidict_proxy_from_nonmultidict
47
49
47
47
b322a675e02ee62e67bceba694aab00fa5e2e838
bigcode/the-stack
train
a663bb8cc149ddd2b9811320
train
function
def iter_buffers(layer: Module, recursive: bool = True ) -> Iterator[Tensor]: return layer.buffers(recurse=recursive)
def iter_buffers(layer: Module, recursive: bool = True ) -> Iterator[Tensor]:
return layer.buffers(recurse=recursive)
Tensor] ) -> Optional[Tensor]: layer.register_buffer(name, value) return value def get_buffer(layer: Module, name: str) -> Optional[Tensor]: return getattr(layer, name) def iter_buffers(layer: Module, recursive: bool = True ) -> Iterator[Tensor]:
64
64
30
20
44
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
iter_buffers
iter_buffers
205
207
205
206
e2039c4e6f4054caa294f04529eb6679831cd5e8
bigcode/the-stack
train
f62cb1c124941ce8335b2ec2
train
class
class NormedWeightStore(_BaseNormedWeightStore): """A module that carries the weight-normed `weight`, without `g`.""" def __init__(self, shape: List[int], initializer: TensorInitArgType, axis: int = 1, device: Optional[str] = None, ...
class NormedWeightStore(_BaseNormedWeightStore):
"""A module that carries the weight-normed `weight`, without `g`.""" def __init__(self, shape: List[int], initializer: TensorInitArgType, axis: int = 1, device: Optional[str] = None, epsilon: float = EPSILON): device =...
axis} vs ' f'shape` {shape!r}.') if axis < 0: axis += r super().__init__(shape) self.reduce_axis = [a for a in range(0, r) if a != axis] self.epsilon = epsilon class NormedWeightStore(_BaseNormedWeightStore):
74
74
249
12
61
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
NormedWeightStore
NormedWeightStore
345
374
345
345
129f3b948c2c6d58a8dd47ff87ddea082b8291ef
bigcode/the-stack
train
121ca946a8d8c7cfb6e6e926
train
class
class ParamStore(Module): """ Base class for a component that stores a trainable parameter, or a set of trainable parameters that can be used to derive virtually "a parameter" (e.g., weight-normed `weight`). """ __constants__ = ('shape',) shape: List[int] def __init__(self, shape: Lis...
class ParamStore(Module):
""" Base class for a component that stores a trainable parameter, or a set of trainable parameters that can be used to derive virtually "a parameter" (e.g., weight-normed `weight`). """ __constants__ = ('shape',) shape: List[int] def __init__(self, shape: List[int]): super()._...
[str] = None): super().__init__() self.device = device or current_device() def forward(self) -> Tensor: # pragma: no cover zero_shape: List[int] = [] return zeros(zero_shape, dtype='float32', device=self.device) class ParamStore(Module):
64
64
163
5
59
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
ParamStore
ParamStore
247
272
247
247
88bcdcca8d2cf18a246ef1e6cb418fb97a5ec248
bigcode/the-stack
train
b5c41182286752d14cb5211d
train
class
class NormedAndScaledWeightStore(_BaseNormedWeightStore): """A module that carries the weight-normed `weight`, with `v` and `g`.""" def __init__(self, shape: List[int], initializer: TensorInitArgType, axis: int = 1, device: Optional[str] = Non...
class NormedAndScaledWeightStore(_BaseNormedWeightStore):
"""A module that carries the weight-normed `weight`, with `v` and `g`.""" def __init__(self, shape: List[int], initializer: TensorInitArgType, axis: int = 1, device: Optional[str] = None, epsilon: float = EPSILON): dev...
_ignore def set(self, value: TensorOrData) -> None: with no_grad(): v, _ = weight_norm_decompose( as_tensor(value, dtype=get_dtype(self.v), device=get_device(self.v)), self.reduce_axis, self.epsilon, ) assign_data(self.v, v)...
82
82
276
14
68
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
NormedAndScaledWeightStore
NormedAndScaledWeightStore
377
408
377
377
963b9bf55700e9856c361fa5c37ae4287dce73b0
bigcode/the-stack
train
29cbb6fa370625c0fe7c7391
train
function
@jit def weight_norm_decompose(weight: Tensor, reduce_axis: List[int], epsilon: float ) -> Tuple[Tensor, Tensor]: """ Decompose `weight` by "weight-norm", i.e., into direction part `v` and norm part `v_norm`. Args: we...
@jit def weight_norm_decompose(weight: Tensor, reduce_axis: List[int], epsilon: float ) -> Tuple[Tensor, Tensor]:
""" Decompose `weight` by "weight-norm", i.e., into direction part `v` and norm part `v_norm`. Args: weight: The weight to be decomposed. reduce_axis: The axis to be reduced when calculating the weight norm. epsilon: Infinitesimal constant to avoid dividing zero. Returns: ...
@jit_ignore def set(self, value: TensorOrData) -> None: with no_grad(): assign_data(self.value, value) @jit def weight_norm_decompose(weight: Tensor, reduce_axis: List[int], epsilon: float ) -> Tuple[Tensor, Tensor]:
64
64
170
33
31
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
weight_norm_decompose
weight_norm_decompose
299
318
299
303
bf2a437b56976fb82e992a4d8c5d9abac3fc7011
bigcode/the-stack
train
235117aa827ead8e291b9e0d
train
class
class Sequential(torch_nn.Sequential): def __init__(self, *layers: Union[Module, Sequence[Module]]): from tensorkit.layers import flatten_nested_layers super().__init__(*flatten_nested_layers(layers))
class Sequential(torch_nn.Sequential):
def __init__(self, *layers: Union[Module, Sequence[Module]]): from tensorkit.layers import flatten_nested_layers super().__init__(*flatten_nested_layers(layers))
) or \ isinstance(attr_val, Tensor) or \ is_jit_layer(attr_val): continue if self._is_attr_included_in_repr(attr, attr_val): buf.append(f'{attr}={attr_val!r}') return ', '.join(buf) class Sequential(torch_nn.Sequential):
64
64
47
6
58
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
Sequential
Sequential
520
524
520
521
c7808422ebb0d0675f49b148168a93a7bb10c3a4
bigcode/the-stack
train
18f256d320dd32c9af44f2e6
train
function
def batch_norm_reset(model: Module): """ Reset the running statistics of Batch Norm modules in a model recursively. JIT compiled Batch Norm modules are not supported. Args: model: The root module of the module. Returns: The `model` itself. """ def fn(m: Module): if ...
def batch_norm_reset(model: Module):
""" Reset the running statistics of Batch Norm modules in a model recursively. JIT compiled Batch Norm modules are not supported. Args: model: The root module of the module. Returns: The `model` itself. """ def fn(m: Module): if is_batch_norm(m): m.runni...
module. JIT compiled Batch Norm module is not recognized by this method. Args: module: The module to be checked. Returns: Whether or not `module` is a Batch Norm module. """ return has_batch_norm(module, recursive=False) def batch_norm_reset(model: Module):
64
64
123
8
56
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
batch_norm_reset
batch_norm_reset
1,043
1,061
1,043
1,043
2432a9efc990eeaf728d88d56d9004b91842916a
bigcode/the-stack
train
c048fcfaee32cb2331eb4dab
train
function
def layer_to_device(layer: Module, device: Optional[str] = None) -> Module: """ Move the specified module or layer to the given device. The module or layer may be changed in-place. Args: layer: The module or layer to be moved. device: The device, to where move the module or layer. ...
def layer_to_device(layer: Module, device: Optional[str] = None) -> Module:
""" Move the specified module or layer to the given device. The module or layer may be changed in-place. Args: layer: The module or layer to be moved. device: The device, to where move the module or layer. If not specified, will move to ``T.current_device()``. Returns: ...
it_layer(layer: Module) -> bool: """Check whether or not `layer` is a JIT compiled layer.""" return isinstance(layer, (torch.jit.ScriptModule, torch.jit.RecursiveScriptModule)) def layer_to_device(layer: Module, device: Optional[str] = None) -> Module:
64
64
122
19
45
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
layer_to_device
layer_to_device
143
159
143
143
43d484487f0878c9a5f120ac18224da381835341
bigcode/the-stack
train
9e8d2d0e520be6bdf970267f
train
class
class LinearConvTranspose1d(LinearConvTransposeNd): def _get_spatial_ndims(self) -> int: return 1 @jit_method def _deconv_transform(self, input: Tensor, weight: Tensor, bias: Optional[Tensor] ) ...
class LinearConvTranspose1d(LinearConvTransposeNd):
def _get_spatial_ndims(self) -> int: return 1 @jit_method def _deconv_transform(self, input: Tensor, weight: Tensor, bias: Optional[Tensor] ) -> Tensor: return torch.nn.functional.conv_tr...
length < 0: raise ValueError('Too large `padding` at axis {}: ({}, {})'. format(a, p1, p2)) input = torch.narrow(input, a, p1, length) return input class LinearConvTranspose1d(LinearConvTransposeNd):
64
64
114
12
51
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
LinearConvTranspose1d
LinearConvTranspose1d
867
882
867
868
2872feff0e67de259082b3d7e6b360fbc5c16ea4
bigcode/the-stack
train
ffe1aa004d918420e0150fac
train
function
def jit_compile(m: Module, filter: Optional[Callable[[Module], bool]] = None, filter_key: Optional[Callable[[Module, str], bool]] = None) -> Module: """ Compile `m` and all children modules of `m` with JIT. Args: m: The module. filter: ``(m: Module) -> bool`...
def jit_compile(m: Module, filter: Optional[Callable[[Module], bool]] = None, filter_key: Optional[Callable[[Module, str], bool]] = None) -> Module:
""" Compile `m` and all children modules of `m` with JIT. Args: m: The module. filter: ``(m: Module) -> bool`` Should return True if `m` should be compiled. The `m` module itself will not be affected by this filter. filter_key: ``(parent: Module, attribute: ...
.0 DEFAULT_WEIGHT_INIT = init.kaming_uniform DEFAULT_BIAS_INIT = init.zeros # ---- utils ---- def jit_compile(m: Module, filter: Optional[Callable[[Module], bool]] = None, filter_key: Optional[Callable[[Module, str], bool]] = None) -> Module:
66
66
222
41
24
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
jit_compile
jit_compile
65
87
65
67
0fb85dae622894bbea5e488a5203cceec8f8de3f
bigcode/the-stack
train
f775595b10bb795464e0d239
train
class
class CoreLinear(BaseLayer): """Base class for the core linear layers.""" __constants__ = ('use_bias',) weight_store: Module bias_store: Module use_bias: bool def __init__(self, weight_shape: List[int], bias_shape: List[int], use_bias: bool =...
class CoreLinear(BaseLayer):
"""Base class for the core linear layers.""" __constants__ = ('use_bias',) weight_store: Module bias_store: Module use_bias: bool def __init__(self, weight_shape: List[int], bias_shape: List[int], use_bias: bool = True, weigh...
Module) or \ isinstance(attr_val, Tensor) or \ is_jit_layer(attr_val): continue if self._is_attr_included_in_repr(attr, attr_val): buf.append(f'{attr}={attr_val!r}') return ', '.join(buf) class Sequential(torch_nn.Sequential...
118
118
394
6
111
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
CoreLinear
CoreLinear
528
578
528
528
d3ea551ad023c659027ec93be1e4d7cebf82abc8
bigcode/the-stack
train
422fcd73569b6c6458b5eff5
train
class
class Embedding(BaseLayer): def __init__(self, n_embeddings: int, embedding_size: Union[int, List[int]], initializer: TensorInitArgType = NOT_SET, freeze: bool = False, device: Optional[str] = None, ): n_e...
class Embedding(BaseLayer):
def __init__(self, n_embeddings: int, embedding_size: Union[int, List[int]], initializer: TensorInitArgType = NOT_SET, freeze: bool = False, device: Optional[str] = None, ): n_embeddings = int(n_embeddings)...
noise = torch.bernoulli(keep_prob.expand(noise_shape), out=noise) noise = noise.detach() input = input * noise / keep_prob return input Dropout2d = torch_nn.Dropout2d Dropout3d = torch_nn.Dropout3d # ---- embedding layers ---- class Embedding(BaseLayer):
74
74
249
6
67
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
Embedding
Embedding
1,165
1,194
1,165
1,166
7b4b852f4f980e18c9730649e69a27ee080e2b95
bigcode/the-stack
train
0719faf51f0c3902429d8fef
train
function
def batch_norm_full_init(model: Module, data_generator, step_fn: Callable[[Sequence[Tensor]], None], loop=None) -> Module: """ Run a full epoch to initialize the mean and variance of BatchNorm layers in the given `model` recursively....
def batch_norm_full_init(model: Module, data_generator, step_fn: Callable[[Sequence[Tensor]], None], loop=None) -> Module:
""" Run a full epoch to initialize the mean and variance of BatchNorm layers in the given `model` recursively. JIT compiled BatchNorm layers are not supported. Args: model: The model, whose BatchNorm children to be initialized. data_generator: The epoch data generator. step...
modules are not supported. Args: model: The root module of the module. Returns: The `model` itself. """ def fn(m: Module): if is_batch_norm(m): m.running_mean = torch.zeros_like( m.running_mean, device=m.running_mean.device) m.running_va...
125
125
417
32
92
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
batch_norm_full_init
batch_norm_full_init
1,064
1,124
1,064
1,067
4640b2fee6619f791e24162dd5ea409545cabc46
bigcode/the-stack
train
82eab1a8b111d819ea1c3a4c
train
class
class LinearConvTransposeNd(CoreLinear): __constants__ = CoreLinear.__constants__ + ( 'in_channels', 'out_channels', 'kernel_size', 'stride', 'padding', 'dilation', 'output_padding', '_manual_padding', '_conv_padding', '_is_manual_padding', '_unpad_axis', ) in_channels: int out...
class LinearConvTransposeNd(CoreLinear):
__constants__ = CoreLinear.__constants__ + ( 'in_channels', 'out_channels', 'kernel_size', 'stride', 'padding', 'dilation', 'output_padding', '_manual_padding', '_conv_padding', '_is_manual_padding', '_unpad_axis', ) in_channels: int out_channels: int kernel_size: List[int] ...
: return torch.nn.functional.conv1d( input=input, weight=weight, bias=bias, stride=self.stride, padding=self._conv_padding, dilation=self.dilation ) class LinearConv2d(LinearConvNd): def _get_spatial_ndims(self) -> int: return 2 @jit_method def _conv_trans...
253
253
845
8
245
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
LinearConvTransposeNd
LinearConvTransposeNd
769
864
769
770
d368f67b84a815d41311d5651a581c411a9a6d4b
bigcode/the-stack
train
cbc21f67b149f287b26aba07
train
class
class BaseLayerMeta(type): def __new__(cls, name, parents, dct): if torch.__version__ != '1.3.1': # strange bug, that PyTorch >= 1.4.0 does not support annotations # with type `Module` or `ModuleList` if '__annotations__' in dct: annotations = dct['__anno...
class BaseLayerMeta(type):
def __new__(cls, name, parents, dct): if torch.__version__ != '1.3.1': # strange bug, that PyTorch >= 1.4.0 does not support annotations # with type `Module` or `ModuleList` if '__annotations__' in dct: annotations = dct['__annotations__'] ...
device = device or current_device() if use_bias: return SimpleParamStore(shape, initializer, device) # ---- identity layer ---- class Identity(Module): def forward(self, input: Tensor) -> Tensor: return input # ---- base layers and composition layers ---- class BaseLayerMeta(type):
64
64
133
6
57
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
BaseLayerMeta
BaseLayerMeta
476
489
476
477
f70cff8ae3484b50a799a18b29e3070b7a6f965e
bigcode/the-stack
train
00f40f519798a41a28ac5f53
train
class
class _BaseNormedWeightStore(ParamStore): __constants__ = ParamStore.__constants__ + ('reduce_axis', 'epsilon') reduce_axis: List[int] epsilon: float def __init__(self, shape: List[int], axis: int = 1, epsilon: float = EPSILON): shape = list(...
class _BaseNormedWeightStore(ParamStore):
__constants__ = ParamStore.__constants__ + ('reduce_axis', 'epsilon') reduce_axis: List[int] epsilon: float def __init__(self, shape: List[int], axis: int = 1, epsilon: float = EPSILON): shape = list(map(int, shape)) r = len(shape) ...
)`. """ v_norm = torch.sqrt(reduce_sum(weight ** 2, axis=reduce_axis, keepdims=True)) v = weight / torch.max(v_norm, float_scalar_like(epsilon, v_norm)) return v, v_norm class _BaseNormedWeightStore(ParamStore):
64
64
175
11
52
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
_BaseNormedWeightStore
_BaseNormedWeightStore
321
342
321
322
230e93225cf75e0207fa7ee89c8a5494b4dccb5c
bigcode/the-stack
train
70425b063a4590df19a8a32c
train
function
def get_parameter(layer: Module, name: str) -> Optional[Variable]: return getattr(layer, name)
def get_parameter(layer: Module, name: str) -> Optional[Variable]:
return getattr(layer, name)
) -> Optional[Variable]: if value is not None: v = torch.nn.Parameter(value, requires_grad=requires_grad) else: v = value layer.register_parameter(name, v) return v def get_parameter(layer: Module, name: str) -> Optional[Variable]:
64
64
23
16
47
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
get_parameter
get_parameter
175
176
175
175
1f66ef84ee65432c81e81377f5a3098997de8b54
bigcode/the-stack
train
33e23713b582286ee734b7f3
train
function
def get_parameters(layer: Module, recursive: bool = True) -> List[Variable]: return list(iter_parameters(layer, recursive))
def get_parameters(layer: Module, recursive: bool = True) -> List[Variable]:
return list(iter_parameters(layer, recursive))
, name: str) -> Optional[Variable]: return getattr(layer, name) def iter_parameters(layer: Module, recursive: bool = True ) -> Iterator[Variable]: return layer.parameters(recurse=recursive) def get_parameters(layer: Module, recursive: bool = True) -> List[Variable]:
64
64
27
18
46
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
get_parameters
get_parameters
184
185
184
184
8dec33205bce8fd35606fe7e59bb4b8739666121
bigcode/the-stack
train
4c0479db530adf7351fcada6
train
class
class BatchNorm2d(torch_nn.BatchNorm2d): """Batch normalization for 2D convolutional layers.""" def __init__(self, num_features: int, momentum: float = 0.1, device: Optional[str] = None, epsilon: float = EPSILON): device = device or cu...
class BatchNorm2d(torch_nn.BatchNorm2d):
"""Batch normalization for 2D convolutional layers.""" def __init__(self, num_features: int, momentum: float = 0.1, device: Optional[str] = None, epsilon: float = EPSILON): device = device or current_device() super().__init__(n...
def _check_input_dim(self, input: Tensor): if rank(input) != 3: raise ValueError('`BatchNorm1d` only supports 3d input, ' 'but the input shape is {}'.format(shape(input))) class BatchNorm2d(torch_nn.BatchNorm2d):
63
64
154
12
51
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
BatchNorm2d
BatchNorm2d
960
976
960
960
efc5390354d092b59b9790f388594f5acd054c32
bigcode/the-stack
train
071b3f96cf9fa07786bca619
train
class
class LinearConvNd(CoreLinear): __constants__ = CoreLinear.__constants__ + ( 'in_channels', 'out_channels', 'kernel_size', 'stride', 'padding', 'dilation', '_manual_padding', '_conv_padding', '_is_manual_padding', ) in_channels: int out_channels: int kernel_size: List[int] stri...
class LinearConvNd(CoreLinear):
__constants__ = CoreLinear.__constants__ + ( 'in_channels', 'out_channels', 'kernel_size', 'stride', 'padding', 'dilation', '_manual_padding', '_conv_padding', '_is_manual_padding', ) in_channels: int out_channels: int kernel_size: List[int] stride: List[int] padding: List[T...
_features], bias_shape=[out_features], use_bias=use_bias, weight_norm=weight_norm, weight_init=weight_init, bias_init=bias_init, data_init=data_init, device=device, ) def forward(self, input: Tensor) -> Tensor: weig...
205
205
684
7
198
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
LinearConvNd
LinearConvNd
634
715
634
635
aeca68ff358e7c1fec5233a5f3e91e58b772e27f
bigcode/the-stack
train
bbc60bced46970913fdf1c10
train
class
class LinearConv1d(LinearConvNd): def _get_spatial_ndims(self) -> int: return 1 @jit_method def _conv_transform(self, input: Tensor, weight: Tensor, bias: Optional[Tensor] ) -> Tensor: r...
class LinearConv1d(LinearConvNd):
def _get_spatial_ndims(self) -> int: return 1 @jit_method def _conv_transform(self, input: Tensor, weight: Tensor, bias: Optional[Tensor] ) -> Tensor: return torch.nn.functional.conv1d( ...
def _conv_transform(self, input: Tensor, weight: Tensor, bias: Optional[Tensor] ) -> Tensor: raise NotImplementedError() def _get_spatial_ndims(self) -> int: raise NotImplementedError() class LinearC...
64
64
102
10
54
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
LinearConv1d
LinearConv1d
718
732
718
719
22f94b7fe5d98475a98988116c575d5e30ef2601
bigcode/the-stack
train
a131f3645d4db8f49dfda10b
train
function
def jit_compile_children(m: Module, filter: Optional[Callable[[Module], bool]] = None, filter_key: Optional[Callable[[Module, str], bool]] = None) -> Module: """ Compile all children modules of `m` in-place with JIT. Args: m: The parent module. ...
def jit_compile_children(m: Module, filter: Optional[Callable[[Module], bool]] = None, filter_key: Optional[Callable[[Module, str], bool]] = None) -> Module:
""" Compile all children modules of `m` in-place with JIT. Args: m: The parent module. filter: ``(m: Module) -> bool`` Should return True if `m` should be compiled. filter_key: ``(parent: Module, attribute: str) -> bool``. Should return True if the child `att...
itself will not be affected by this filter. Returns: The compiled `m` module. """ if is_module_jit_enabled(): if isinstance(m, Module) and not is_jit_layer(m): m = jit_compile_children(m, filter, filter_key) m = torch_script(m) return m def jit_compile_children(...
111
111
372
42
68
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
jit_compile_children
jit_compile_children
90
135
90
92
0fc7a47530fd9665f41060bfddb7875f1370c734
bigcode/the-stack
train
3e0a10fc5b22c4cc6dcf9ccf
train
class
class Dropout1d(BaseLayer): """Randomly zero out entire channels of the 1d convolution input.""" __constants__ = ('p', '_keep_prob') p: float _keep_prob: float def __init__(self, p: float = 0.5): super().__init__() self.p = p self._keep_prob = 1. - p def forward(self,...
class Dropout1d(BaseLayer):
"""Randomly zero out entire channels of the 1d convolution input.""" __constants__ = ('p', '_keep_prob') p: float _keep_prob: float def __init__(self, p: float = 0.5): super().__init__() self.p = p self._keep_prob = 1. - p def forward(self, input: Tensor) -> Tensor: ...
elif loop is not None: loop.run(step, data_generator) else: for b in data_generator: step(*b) finally: # restore the momentum model.apply(restore_momentum) return model # ---- dropout layers ---- Dropout = torch_nn....
72
72
243
8
63
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
Dropout1d
Dropout1d
1,131
1,157
1,131
1,131
21fb9608582d5c0871fdf90459764a2a23df38d9
bigcode/the-stack
train
86716bf3376bbe0b3bfb25db
train
function
def iter_parameters(layer: Module, recursive: bool = True ) -> Iterator[Variable]: return layer.parameters(recurse=recursive)
def iter_parameters(layer: Module, recursive: bool = True ) -> Iterator[Variable]:
return layer.parameters(recurse=recursive)
) else: v = value layer.register_parameter(name, v) return v def get_parameter(layer: Module, name: str) -> Optional[Variable]: return getattr(layer, name) def iter_parameters(layer: Module, recursive: bool = True ) -> Iterator[Variable]:
64
64
29
20
44
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
iter_parameters
iter_parameters
179
181
179
180
247da33368add2c150a79d91463a91d29d56239b
bigcode/the-stack
train
34c3f61ad2f7a7dc35718ce1
train
class
class BaseLayer(Module, metaclass=BaseLayerMeta): def _is_attr_included_in_repr(self, attr: str, value: Any) -> bool: return True def extra_repr(self) -> str: buf = [] attributes = list(getattr(self, '__constants__', ())) for attr in getattr(self, '__annotations__', ()): ...
class BaseLayer(Module, metaclass=BaseLayerMeta):
def _is_attr_included_in_repr(self, attr: str, value: Any) -> bool: return True def extra_repr(self) -> str: buf = [] attributes = list(getattr(self, '__constants__', ())) for attr in getattr(self, '__annotations__', ()): if attr not in attributes: a...
['__annotations__'] annotation_keys = list(annotations) for attr in annotation_keys: if annotations[attr] in (Module, ModuleList): annotations.pop(attr) return super().__new__(cls, name, parents, dct) class BaseLayer(Module, metaclass=...
64
64
188
12
52
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
BaseLayer
BaseLayer
492
517
492
493
20ca7d0efabd169a61c346e649c7af42eb83460c
bigcode/the-stack
train
027ab931139213c65527478d
train
class
class NullParamStore(Module): # This module is actually not used in any context. # It is just a place-holder module, to gain JIT support. __constants__ = ('device',) device: str def __init__(self, device: Optional[str] = None): super().__init__() self.device = device or current_de...
class NullParamStore(Module): # This module is actually not used in any context. # It is just a place-holder module, to gain JIT support.
__constants__ = ('device',) device: str def __init__(self, device: Optional[str] = None): super().__init__() self.device = device or current_device() def forward(self) -> Tensor: # pragma: no cover zero_shape: List[int] = [] return zeros(zero_shape, dtype='float32', d...
_mode(layer: Module): layer.train(False) return layer # ---- weight wrapper: a simple weight, or a normed weight ---- class NullParamStore(Module): # This module is actually not used in any context. # It is just a place-holder module, to gain JIT support.
64
64
117
34
29
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
NullParamStore
NullParamStore
230
244
230
233
c2bd4814968cee7e068bf0977d27a0fb31aa9153
bigcode/the-stack
train
9e3d731167330eed9c43ddf2
train
function
def iter_named_parameters(layer: Module, recursive: bool = True ) -> Iterator[Tuple[str, Variable]]: return layer.named_parameters(recurse=recursive)
def iter_named_parameters(layer: Module, recursive: bool = True ) -> Iterator[Tuple[str, Variable]]:
return layer.named_parameters(recurse=recursive)
Iterator[Variable]: return layer.parameters(recurse=recursive) def get_parameters(layer: Module, recursive: bool = True) -> List[Variable]: return list(iter_parameters(layer, recursive)) def iter_named_parameters(layer: Module, recursive: bool = True ) -> Iterator[Tuple[str, Variabl...
64
64
34
24
40
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
iter_named_parameters
iter_named_parameters
188
190
188
189
a9cb4ee02b00e31228bf47e270e2191c18bd2401
bigcode/the-stack
train
2100d8b68471da17c6d0d255
train
class
class Embedding1d(EmbeddingNd): def _get_spatial_ndims(self) -> int: return 1
class Embedding1d(EmbeddingNd):
def _get_spatial_ndims(self) -> int: return 1
got {embedding_size!r}.') embedding_size = list(map(int, embedding_size)) super().__init__(n_embeddings, embedding_size, initializer, freeze, device) def _get_spatial_ndims(self) -> int: raise NotImplementedError() class Embedding1d(EmbeddingNd):
64
64
27
9
55
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
Embedding1d
Embedding1d
1,218
1,221
1,218
1,219
d92fbce9e6bea066006cf2fd911691a8ec1f4905
bigcode/the-stack
train
85f0a5d4f59721cb3358e23e
train
class
class BatchNorm1d(torch_nn.BatchNorm1d): """Batch normalization for 1D convolutional layers.""" def __init__(self, num_features: int, momentum: float = 0.1, device: Optional[str] = None, epsilon: float = EPSILON): device = device or cu...
class BatchNorm1d(torch_nn.BatchNorm1d):
"""Batch normalization for 1D convolutional layers.""" def __init__(self, num_features: int, momentum: float = 0.1, device: Optional[str] = None, epsilon: float = EPSILON): device = device or current_device() super().__init__(n...
) def _check_input_dim(self, input: Tensor): if rank(input) != 2: raise ValueError('`BatchNorm` only supports 2d input, ' 'but the input shape is {}'.format(shape(input))) class BatchNorm1d(torch_nn.BatchNorm1d):
63
64
154
12
51
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
BatchNorm1d
BatchNorm1d
941
957
941
941
6969c5c614067d90982e9c5d10f40c7ec46a7275
bigcode/the-stack
train
9682cb173b6bf3ec17dfb14e
train
class
class LinearConvTranspose3d(LinearConvTransposeNd): def _get_spatial_ndims(self) -> int: return 3 @jit_method def _deconv_transform(self, input: Tensor, weight: Tensor, bias: Optional[Tensor] ) ...
class LinearConvTranspose3d(LinearConvTransposeNd):
def _get_spatial_ndims(self) -> int: return 3 @jit_method def _deconv_transform(self, input: Tensor, weight: Tensor, bias: Optional[Tensor] ) -> Tensor: return torch.nn.functional.conv_tr...
-> Tensor: return torch.nn.functional.conv_transpose2d( input=input, weight=weight, bias=bias, stride=self.stride, padding=self._conv_padding, output_padding=self.output_padding, dilation=self.dilation ) class LinearConvTranspose3d(LinearConvTransposeNd):
64
64
114
12
52
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
LinearConvTranspose3d
LinearConvTranspose3d
903
918
903
904
446481f3d9a0f9888f67a47a64ccb09c036d2213
bigcode/the-stack
train
2e8fb042b9383caf2fd8e718
train
class
class BatchNorm3d(torch_nn.BatchNorm3d): """Batch normalization for 3D convolutional layers.""" def __init__(self, num_features: int, momentum: float = 0.1, device: Optional[str] = None, epsilon: float = EPSILON): device = device or cu...
class BatchNorm3d(torch_nn.BatchNorm3d):
"""Batch normalization for 3D convolutional layers.""" def __init__(self, num_features: int, momentum: float = 0.1, device: Optional[str] = None, epsilon: float = EPSILON): device = device or current_device() super().__init__(n...
def _check_input_dim(self, input: Tensor): if input.dim() != 4: raise ValueError('`BatchNorm2d` only supports 4d input, ' 'but the input shape is {}'.format(shape(input))) class BatchNorm3d(torch_nn.BatchNorm3d):
63
64
154
12
51
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
BatchNorm3d
BatchNorm3d
979
995
979
979
1ac6ad890f280cab3b719a80085b9320f5669bce
bigcode/the-stack
train
52de045f74a6ccfbe70cb465
train
class
class Identity(Module): def forward(self, input: Tensor) -> Tensor: return input
class Identity(Module):
def forward(self, input: Tensor) -> Tensor: return input
place new tensors and variables. Returns: The bias object, or :obj:`None` if `use_bias` is False. """ device = device or current_device() if use_bias: return SimpleParamStore(shape, initializer, device) # ---- identity layer ---- class Identity(Module):
64
64
20
4
59
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
Identity
Identity
469
472
469
470
f4870e7647b324a2412b6f0c9866cee97f07de10
bigcode/the-stack
train
b8cc9163c97d95843f7938b9
train
class
class Embedding3d(EmbeddingNd): def _get_spatial_ndims(self) -> int: return 3
class Embedding3d(EmbeddingNd):
def _get_spatial_ndims(self) -> int: return 3
() class Embedding1d(EmbeddingNd): def _get_spatial_ndims(self) -> int: return 1 class Embedding2d(EmbeddingNd): def _get_spatial_ndims(self) -> int: return 2 class Embedding3d(EmbeddingNd):
64
64
27
9
54
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
Embedding3d
Embedding3d
1,230
1,233
1,230
1,231
37ac919091cd4ba7ce075cbce31c688e7d82d1ae
bigcode/the-stack
train
2b0541982158d4cf9ef0075d
train
class
class BatchNorm(torch_nn.BatchNorm1d): """Batch normalization for dense layers.""" def __init__(self, num_features: int, momentum: float = 0.1, device: Optional[str] = None, epsilon: float = EPSILON): device = device or current_device(...
class BatchNorm(torch_nn.BatchNorm1d):
"""Batch normalization for dense layers.""" def __init__(self, num_features: int, momentum: float = 0.1, device: Optional[str] = None, epsilon: float = EPSILON): device = device or current_device() super().__init__(num_features...
torch.nn.functional.conv_transpose3d( input=input, weight=weight, bias=bias, stride=self.stride, padding=self._conv_padding, output_padding=self.output_padding, dilation=self.dilation ) # ---- normalizer layers ---- class BatchNorm(torch_nn.BatchNorm1d):
64
64
146
10
53
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
BatchNorm
BatchNorm
922
938
922
922
ae0b673828b33c6b03021c56525c5f9c4e790c66
bigcode/the-stack
train
0e1a5f5b4faf865bf7bedc24
train
function
def has_batch_norm(module: Module, recursive: bool = True) -> bool: """ Check whether or not `module` is a Batch Norm module (if `recursive` is False), or any children of `module` is Batch Norm module (if `recursive` is True). JIT compiled Batch Norm module is not recognized by this method. Ar...
def has_batch_norm(module: Module, recursive: bool = True) -> bool:
""" Check whether or not `module` is a Batch Norm module (if `recursive` is False), or any children of `module` is Batch Norm module (if `recursive` is True). JIT compiled Batch Norm module is not recognized by this method. Args: module: The module to be checked. recursive: Whe...
(self, input: Tensor): if rank(input) != 5: raise ValueError('`BatchNorm2d` only supports 5d input, ' 'but the input shape is {}'.format(shape(input))) def has_batch_norm(module: Module, recursive: bool = True) -> bool:
63
64
192
17
46
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
has_batch_norm
has_batch_norm
998
1,026
998
998
4c76b20deffe17a4dca3951000f3b84472361960
bigcode/the-stack
train
d38df20a04513167445ab24a
train
function
def get_bias_store(shape: List[int], initializer: TensorInitArgType = DEFAULT_BIAS_INIT, use_bias: bool = True, device: Optional[str] = None ) -> Optional[ParamStore]: """ Create a module that carries the `bias` parameter. Args: ...
def get_bias_store(shape: List[int], initializer: TensorInitArgType = DEFAULT_BIAS_INIT, use_bias: bool = True, device: Optional[str] = None ) -> Optional[ParamStore]:
""" Create a module that carries the `bias` parameter. Args: shape: The shape of the bias. initializer: The initializer for the bias. use_bias: Whether or not to use the bias? If `False`, will return :obj:`None`. device: The device where to place new tensors and ...
for argument `weight_norm`: ' f'{weight_norm!r}.') def get_bias_store(shape: List[int], initializer: TensorInitArgType = DEFAULT_BIAS_INIT, use_bias: bool = True, device: Optional[str] = None ) -> Optional[ParamStore]:...
63
64
167
47
16
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
get_bias_store
get_bias_store
445
465
445
449
b968940eb06e139e25738cf3d43d409e6888c6b7
bigcode/the-stack
train
aa62339109dbd00f7875b4cf
train
function
def set_train_mode(layer: Module, training: bool = True): layer.train(training) return layer
def set_train_mode(layer: Module, training: bool = True):
layer.train(training) return layer
True) -> List[Variable]: return list(iter_buffers(layer, recursive)) def iter_named_buffers(layer: Module, recursive: bool = True ) -> Iterator[Tuple[str, Tensor]]: return layer.named_buffers(recurse=recursive) def set_train_mode(layer: Module, training: bool = True):
64
64
23
14
50
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
set_train_mode
set_train_mode
219
221
219
219
4079e833fbfa20f1eaada3a32867324d3ecb643f
bigcode/the-stack
train
0ad988ab42e1819a7e76ddab
train
function
def add_buffer(layer: Module, name: str, value: Optional[Tensor] ) -> Optional[Tensor]: layer.register_buffer(name, value) return value
def add_buffer(layer: Module, name: str, value: Optional[Tensor] ) -> Optional[Tensor]:
layer.register_buffer(name, value) return value
(layer, recursive)) def iter_named_parameters(layer: Module, recursive: bool = True ) -> Iterator[Tuple[str, Variable]]: return layer.named_parameters(recurse=recursive) def add_buffer(layer: Module, name: str, value: Optional[Tensor] ) -> Opt...
64
64
38
26
38
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
add_buffer
add_buffer
193
198
193
196
a68c56b589b8622ded893a818afe3980f4a39eb6
bigcode/the-stack
train
7bafa5ed69bbaa01771514e8
train
class
class EmbeddingNd(Embedding): def __init__(self, n_embeddings: int, embedding_size: List[int], initializer: TensorInitArgType = NOT_SET, freeze: bool = False, device: Optional[str] = None, ): spatial_ndims...
class EmbeddingNd(Embedding):
def __init__(self, n_embeddings: int, embedding_size: List[int], initializer: TensorInitArgType = NOT_SET, freeze: bool = False, device: Optional[str] = None, ): spatial_ndims = self._get_spatial_ndims() ...
w = variable(shape=[n_embeddings] + embedding_size, device=device, initializer=initializer) add_parameter(self, 'weight', w, requires_grad=not freeze) def forward(self, input: Tensor) -> Tensor: return embedding(self.weight, input) class EmbeddingNd(Embedding):
64
64
172
7
57
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
EmbeddingNd
EmbeddingNd
1,197
1,215
1,197
1,198
bd98ee8c39d8073071d8e0be002d46bcded0ef8c
bigcode/the-stack
train
bf967183ea89e3127febb841
train
class
class LinearConv3d(LinearConvNd): def _get_spatial_ndims(self) -> int: return 3 @jit_method def _conv_transform(self, input: Tensor, weight: Tensor, bias: Optional[Tensor] ) -> Tensor: r...
class LinearConv3d(LinearConvNd):
def _get_spatial_ndims(self) -> int: return 3 @jit_method def _conv_transform(self, input: Tensor, weight: Tensor, bias: Optional[Tensor] ) -> Tensor: return torch.nn.functional.conv3d( ...
Tensor, bias: Optional[Tensor] ) -> Tensor: return torch.nn.functional.conv2d( input=input, weight=weight, bias=bias, stride=self.stride, padding=self._conv_padding, dilation=self.dilation ) class LinearConv3d(LinearConvNd):
64
64
102
10
54
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
LinearConv3d
LinearConv3d
752
766
752
753
9d1360924b085149c4e9978284d45c28eda04c8d
bigcode/the-stack
train
7ef6b8dd3ebc72218c43da6b
train
function
def iter_named_buffers(layer: Module, recursive: bool = True ) -> Iterator[Tuple[str, Tensor]]: return layer.named_buffers(recurse=recursive)
def iter_named_buffers(layer: Module, recursive: bool = True ) -> Iterator[Tuple[str, Tensor]]:
return layer.named_buffers(recurse=recursive)
[Tensor]: return layer.buffers(recurse=recursive) def get_buffers(layer: Module, recursive: bool = True) -> List[Variable]: return list(iter_buffers(layer, recursive)) def iter_named_buffers(layer: Module, recursive: bool = True ) -> Iterator[Tuple[str, Tensor]]:
64
64
34
24
40
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
iter_named_buffers
iter_named_buffers
214
216
214
215
aacdd2f60470af75b86a6143200b9843020c6e47
bigcode/the-stack
train
ef76f06ca29d44d3e489da57
train
function
def get_weight_store(shape: List[int], initializer: TensorInitArgType = DEFAULT_WEIGHT_INIT, norm_axis: int = 1, weight_norm: WeightNormArgType = False, device: Optional[str] = None, ) -> ParamStore: """ Cre...
def get_weight_store(shape: List[int], initializer: TensorInitArgType = DEFAULT_WEIGHT_INIT, norm_axis: int = 1, weight_norm: WeightNormArgType = False, device: Optional[str] = None, ) -> ParamStore:
""" Create a module which carries the `weight` parameter. Args: shape: The shape of the weight. initializer: The initializer for the weight. norm_axis: The axis, along with to normalize the weight. weight_norm: The mode of weight norm. Use `NormedAndScaledWeightS...
(self.v), device=get_device(self.v)), self.reduce_axis, self.epsilon, ) assign_data(self.v, v) assign_data(self.g, g) def get_weight_store(shape: List[int], initializer: TensorInitArgType = DEFAULT_WEIGHT_INIT, ...
93
93
313
56
37
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
get_weight_store
get_weight_store
411
442
411
416
551a2784bf27871f4fef9950862c5798608960ab
bigcode/the-stack
train
5360b85bf59fddfe71d197e7
train
function
@jit_ignore def _get_manual_and_conv_padding(padding: List[Tuple[int, int]]): if all(p1 == p2 for p1, p2 in padding): return [], [p1 for p1, _ in padding], else: return sum([[p1, p2] for p1, p2 in reversed(padding)], []), [0] * len(padding)
@jit_ignore def _get_manual_and_conv_padding(padding: List[Tuple[int, int]]):
if all(p1 == p2 for p1, p2 in padding): return [], [p1 for p1, _ in padding], else: return sum([[p1, p2] for p1, p2 in reversed(padding)], []), [0] * len(padding)
if self.use_bias: bias: Optional[Tensor] = self.bias_store() else: bias: Optional[Tensor] = None return torch.nn.functional.linear(input, weight, bias) @jit_ignore def _get_manual_and_conv_padding(padding: List[Tuple[int, int]]):
64
64
87
22
42
lizeyan/tensorkit
tensorkit/backend/pytorch_/layers.py
Python
_get_manual_and_conv_padding
_get_manual_and_conv_padding
626
631
626
627
1a8f39c9a4dfb3c5c6ff9399b480b4d98520eea6
bigcode/the-stack
train