index int64 0 50.7k | project_path stringclasses 279
values | completion_path stringlengths 57 199 | signature_postion stringlengths 3 11 | class_position stringlengths 3 11 | function_name stringlengths 1 62 | class_name stringlengths 0 55 | body_position stringlengths 3 11 | body_position_with_comments stringlengths 3 11 | masked_class stringlengths 14 8.32k | masked_class_with_comment stringlengths 14 8.32k | func_body stringlengths 9 6.72k | func_body_with_comment stringlengths 9 6.72k | len_func_body int64 1 643 | len_input int64 10 2.02k | len_output int64 4 1.9k | total int64 20 2.05k | file_code stringlengths 14 442k | file_code_with_comment stringlengths 14 442k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
44,670 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/misc/copy_param.py | 25,26 | 1,69 | soft_copy_param | 27,49 | 26,49 | from chainer import links as L
def copy_param(target_link, source_link):
"""Copy parameters of a link to another link."""
target_params = dict(target_link.namedparams())
for param_name, param in source_link.namedparams():
if target_params[param_name].array is None:
raise TypeError(
... | from chainer import links as L
def copy_param(target_link, source_link):
"""Copy parameters of a link to another link."""
target_params = dict(target_link.namedparams())
for param_name, param in source_link.namedparams():
if target_params[param_name].array is None:
raise TypeError(
... | target_params = dict(target_link.namedparams())
for param_name, param in source_link.namedparams():
if target_params[param_name].array is None:
raise TypeError(
'target_link parameter {} is None. Maybe the model params are '
'not initialized.\nPlease try to fo... | """Soft-copy parameters of a link to another link."""
target_params = dict(target_link.namedparams())
for param_name, param in source_link.namedparams():
if target_params[param_name].array is None:
raise TypeError(
'target_link parameter {} is None. Maybe the model params... | 91 | 534 | 328 | 862 | from chainer import links as L
def copy_param(target_link, source_link):
"""Copy parameters of a link to another link."""
target_params = dict(target_link.namedparams())
for param_name, param in source_link.namedparams():
if target_params[param_name].array is None:
raise TypeError(
... | from chainer import links as L
def copy_param(target_link, source_link):
"""Copy parameters of a link to another link."""
target_params = dict(target_link.namedparams())
for param_name, param in source_link.namedparams():
if target_params[param_name].array is None:
raise TypeError(
... | |
44,671 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/misc/draw_computational_graph.py | 33,34 | 1,53 | draw_computational_graph | 44,53 | 34,53 | import subprocess
import chainer.computational_graph
import chainerrl
def collect_variables(obj):
"""Collect Variable objects inside a given object.
Args:
obj (object): Object to collect Variable objects from.
Returns:
List of Variable objects.
"""
variables = []
if isinstanc... | import subprocess
import chainer.computational_graph
import chainerrl
def collect_variables(obj):
"""Collect Variable objects inside a given object.
Args:
obj (object): Object to collect Variable objects from.
Returns:
List of Variable objects.
"""
variables = []
if isinstanc... | variables = collect_variables(outputs)
g = chainer.computational_graph.build_computational_graph(variables)
gv_filepath = filepath + '.gv'
with open(gv_filepath, 'w') as f:
f.write(g.dump())
if is_graphviz_available():
png_filepath = filepath + '.png'
subprocess.check_call(
... | """Draw a computational graph and write to a given file.
Args:
outputs (object): Output(s) of the computational graph. It must be
a Variable, an ActionValue, a Distribution or a list of them.
filepath (str): Filepath to write a graph without file extention.
A DOT file wi... | 30 | 385 | 143 | 528 | import subprocess
import chainer.computational_graph
import chainerrl
def collect_variables(obj):
"""Collect Variable objects inside a given object.
Args:
obj (object): Object to collect Variable objects from.
Returns:
List of Variable objects.
"""
variables = []
if isinstanc... | import subprocess
import chainer.computational_graph
import chainerrl
def collect_variables(obj):
"""Collect Variable objects inside a given object.
Args:
obj (object): Object to collect Variable objects from.
Returns:
List of Variable objects.
"""
variables = []
if isinstanc... | |
44,672 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/misc/env_modifiers.py | 4,5 | 1,83 | make_rendered | 5,21 | 5,21 | import numpy as np
def make_rendered(env, *render_args, **render_kwargs):
FILL_FUNC_BODYdef make_timestep_limited(env, timestep_limit):
t = [1]
old_step = env.step
old_reset = env.reset
def step(action):
observation, reward, done, info = old_step(action)
if t[0] >= timestep_limit:
... | import numpy as np
def make_rendered(env, *render_args, **render_kwargs):
FILL_FUNC_BODYdef make_timestep_limited(env, timestep_limit):
t = [1]
old_step = env.step
old_reset = env.reset
def step(action):
observation, reward, done, info = old_step(action)
if t[0] >= timestep_limit:
... | base_step = env.step
base_close = env.close
def step(action):
ret = base_step(action)
env.render(*render_args, **render_kwargs)
return ret
def close():
env.render(*render_args, close=True, **render_kwargs)
base_close()
env.step = step
env.close = close
... | base_step = env.step
base_close = env.close
def step(action):
ret = base_step(action)
env.render(*render_args, **render_kwargs)
return ret
def close():
env.render(*render_args, close=True, **render_kwargs)
base_close()
env.step = step
env.close = close
... | 27 | 492 | 119 | 611 | import numpy as np
def make_rendered(env, *render_args, **render_kwargs):
FILL_FUNC_BODYdef make_timestep_limited(env, timestep_limit):
t = [1]
old_step = env.step
old_reset = env.reset
def step(action):
observation, reward, done, info = old_step(action)
if t[0] >= timestep_limit:
... | import numpy as np
def make_rendered(env, *render_args, **render_kwargs):
FILL_FUNC_BODYdef make_timestep_limited(env, timestep_limit):
t = [1]
old_step = env.step
old_reset = env.reset
def step(action):
observation, reward, done, info = old_step(action)
if t[0] >= timestep_limit:
... | |
44,673 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/misc/init_like_torch.py | 5,6 | 1,21 | init_like_torch | 6,21 | 6,21 | from chainer import links as L
import numpy as np
def init_like_torch(link):
FILL_FUNC_BODY | from chainer import links as L
import numpy as np
def init_like_torch(link):
FILL_FUNC_BODY | # Mimic torch's default parameter initialization
# TODO(muupan): Use chainer's initializers when it is merged
for li in link.links():
if isinstance(li, L.Linear):
out_channels, in_channels = li.W.shape
stdv = 1 / np.sqrt(in_channels)
li.W.array[:] = np.random.unif... | # Mimic torch's default parameter initialization
# TODO(muupan): Use chainer's initializers when it is merged
for li in link.links():
if isinstance(li, L.Linear):
out_channels, in_channels = li.W.shape
stdv = 1 / np.sqrt(in_channels)
li.W.array[:] = np.random.unif... | 79 | 37 | 302 | 339 | from chainer import links as L
import numpy as np
def init_like_torch(link):
FILL_FUNC_BODY | from chainer import links as L
import numpy as np
def init_like_torch(link):
FILL_FUNC_BODY | |
44,674 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/misc/is_return_code_zero.py | 5,6 | 1,20 | is_return_code_zero | 10,20 | 6,20 | import os
import subprocess
def is_return_code_zero(args):
FILL_FUNC_BODY | import os
import subprocess
def is_return_code_zero(args):
"""Return true iff the given command's return code is zero.
All the messages to stdout or stderr are suppressed.
"""
FILL_FUNC_BODY | with open(os.devnull, 'wb') as FNULL:
try:
subprocess.check_call(args, stdout=FNULL, stderr=FNULL)
except subprocess.CalledProcessError:
# The given command returned an error
return False
except OSError:
# The given command was not found
... | """Return true iff the given command's return code is zero.
All the messages to stdout or stderr are suppressed.
"""
with open(os.devnull, 'wb') as FNULL:
try:
subprocess.check_call(args, stdout=FNULL, stderr=FNULL)
except subprocess.CalledProcessError:
# The giv... | 33 | 66 | 103 | 169 | import os
import subprocess
def is_return_code_zero(args):
FILL_FUNC_BODY | import os
import subprocess
def is_return_code_zero(args):
"""Return true iff the given command's return code is zero.
All the messages to stdout or stderr are suppressed.
"""
FILL_FUNC_BODY | |
44,675 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/misc/namedpersistent.py | 13,14 | 1,33 | namedpersistent | 26,33 | 14,33 | import chainer
def _namedchildren(link):
if isinstance(link, chainer.Chain):
for name in sorted(link._children):
yield name, link.__dict__[name]
elif isinstance(link, chainer.ChainList):
for idx, child in enumerate(link._children):
yield str(idx), child
def namedpersi... | import chainer
def _namedchildren(link):
if isinstance(link, chainer.Chain):
for name in sorted(link._children):
yield name, link.__dict__[name]
elif isinstance(link, chainer.ChainList):
for idx, child in enumerate(link._children):
yield str(idx), child
def namedpersi... | d = link.__dict__
for name in sorted(link._persistent):
yield '/' + name, d[name]
for name, child in _namedchildren(link):
prefix = '/' + name
for path, persistent in namedpersistent(child):
yield prefix + path, persistent
| """Return a generator of all (path, persistent) pairs for a given link.
This function is adopted from https://github.com/chainer/chainer/pull/6788.
Once it is merged into Chainer, we should use the property instead.
Args:
link (chainer.Link): Link.
Returns:
A generator object that... | 32 | 219 | 81 | 300 | import chainer
def _namedchildren(link):
if isinstance(link, chainer.Chain):
for name in sorted(link._children):
yield name, link.__dict__[name]
elif isinstance(link, chainer.ChainList):
for idx, child in enumerate(link._children):
yield str(idx), child
def namedpersi... | import chainer
def _namedchildren(link):
if isinstance(link, chainer.Chain):
for name in sorted(link._children):
yield name, link.__dict__[name]
elif isinstance(link, chainer.ChainList):
for idx, child in enumerate(link._children):
yield str(idx), child
def namedpersi... | |
44,677 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/misc/prioritized.py | 287,288 | 282,295 | min | MinTreeQueue | 288,295 | 288,295 | class MinTreeQueue(TreeQueue):
def __init__(self):
super().__init__(op=min)
def min(self):
FILL_FUNC_BODY | class MinTreeQueue(TreeQueue):
def __init__(self):
super().__init__(op=min)
def min(self):
FILL_FUNC_BODY | if self.length == 0:
return np.inf
else:
return self.root[2]
# Deprecated
| if self.length == 0:
return np.inf
else:
return self.root[2]
# Deprecated
| 11 | 47 | 41 | 88 | import collections
import numpy as np
from chainerrl.misc.random import sample_n_k
class PrioritizedBuffer (object):
def __init__(self, capacity=None, wait_priority_after_sampling=True,
initial_max_priority=1.0):
self.capacity = capacity
self.data = collections.deque()
... | import collections
import numpy as np
from chainerrl.misc.random import sample_n_k
class PrioritizedBuffer (object):
def __init__(self, capacity=None, wait_priority_after_sampling=True,
initial_max_priority=1.0):
self.capacity = capacity
self.data = collections.deque()
... |
44,678 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/misc/prioritized.py | 40,41 | 8,111 | _sample_indices_and_probabilities | PrioritizedBuffer | 41,70 | 41,70 | class PrioritizedBuffer (object):
def __init__(self, capacity=None, wait_priority_after_sampling=True,
initial_max_priority=1.0):
self.capacity = capacity
self.data = collections.deque()
self.priority_sums = SumTreeQueue()
self.priority_mins = MinTreeQueue()
... | class PrioritizedBuffer (object):
def __init__(self, capacity=None, wait_priority_after_sampling=True,
initial_max_priority=1.0):
self.capacity = capacity
self.data = collections.deque()
self.priority_sums = SumTreeQueue()
self.priority_mins = MinTreeQueue()
... | total_priority = self.priority_sums.sum()
min_prob = self.priority_mins.min() / total_priority
indices = []
priorities = []
if uniform_ratio > 0:
# Mix uniform samples and prioritized samples
n_uniform = np.random.binomial(n, uniform_ratio)
un_... | total_priority = self.priority_sums.sum()
min_prob = self.priority_mins.min() / total_priority
indices = []
priorities = []
if uniform_ratio > 0:
# Mix uniform samples and prioritized samples
n_uniform = np.random.binomial(n, uniform_ratio)
un_... | 85 | 808 | 351 | 1,159 | import collections
import numpy as np
from chainerrl.misc.random import sample_n_k
class PrioritizedBuffer (object):
def __init__(self, capacity=None, wait_priority_after_sampling=True,
initial_max_priority=1.0):
self.capacity = capacity
self.data = collections.deque()
... | import collections
import numpy as np
from chainerrl.misc.random import sample_n_k
class PrioritizedBuffer (object):
def __init__(self, capacity=None, wait_priority_after_sampling=True,
initial_max_priority=1.0):
self.capacity = capacity
self.data = collections.deque()
... |
44,679 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/misc/prioritized.py | 389,390 | 295,416 | prioritized_sample | SumTree | 390,404 | 390,404 | class SumTree (object):
"""Fast weighted sampling.
list-like data structure
append, update are O(log n)
summation over an interval is O(log n) per query
"""
def __init__(self, bd=None, left=None, right=None, s=0.0):
# bounds, left child, right child, sum
self.bd = bd
se... | class SumTree (object):
"""Fast weighted sampling.
list-like data structure
append, update are O(log n)
summation over an interval is O(log n) per query
"""
def __init__(self, bd=None, left=None, right=None, s=0.0):
# bounds, left child, right child, sum
self.bd = bd
se... | assert n >= 0
ixs = []
vals = []
total_val = self.s # save this before it changes by removing
for _ in range(n):
ix, val = self._pick(np.random.uniform(0.0, self.s))
ixs.append(ix)
vals.append(val)
self._write(ix, 0.0)
if n... | assert n >= 0
ixs = []
vals = []
total_val = self.s # save this before it changes by removing
for _ in range(n):
ix, val = self._pick(np.random.uniform(0.0, self.s))
ixs.append(ix)
vals.append(val)
self._write(ix, 0.0)
if n... | 54 | 1,102 | 167 | 1,269 | import collections
import numpy as np
from chainerrl.misc.random import sample_n_k
class PrioritizedBuffer (object):
def __init__(self, capacity=None, wait_priority_after_sampling=True,
initial_max_priority=1.0):
self.capacity = capacity
self.data = collections.deque()
... | import collections
import numpy as np
from chainerrl.misc.random import sample_n_k
class PrioritizedBuffer (object):
def __init__(self, capacity=None, wait_priority_after_sampling=True,
initial_max_priority=1.0):
self.capacity = capacity
self.data = collections.deque()
... |
44,680 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/misc/prioritized.py | 262,263 | 230,282 | prioritized_sample | SumTreeQueue | 263,282 | 263,282 | class SumTreeQueue(TreeQueue):
"""Fast weighted sampling.
queue-like data structure
append, update are O(log n)
summation over an interval is O(log n) per query
"""
def __init__(self):
super().__init__(op=sum)
def sum(self):
if self.length == 0:
return 0.0
... | class SumTreeQueue(TreeQueue):
"""Fast weighted sampling.
queue-like data structure
append, update are O(log n)
summation over an interval is O(log n) per query
"""
def __init__(self):
super().__init__(op=sum)
def sum(self):
if self.length == 0:
return 0.0
... | assert n >= 0
ixs = []
vals = []
if n > 0:
root = self.root
ixl, ixr = self.bounds
for _ in range(n):
ix = _find(ixl, ixr, root, np.random.uniform(0.0, root[2]))
val = self._write(ix, 0.0)
ixs.append(ix)
... | assert n >= 0
ixs = []
vals = []
if n > 0:
root = self.root
ixl, ixr = self.bounds
for _ in range(n):
ix = _find(ixl, ixr, root, np.random.uniform(0.0, root[2]))
val = self._write(ix, 0.0)
ixs.append(ix)
... | 52 | 263 | 180 | 443 | import collections
import numpy as np
from chainerrl.misc.random import sample_n_k
class PrioritizedBuffer (object):
def __init__(self, capacity=None, wait_priority_after_sampling=True,
initial_max_priority=1.0):
self.capacity = capacity
self.data = collections.deque()
... | import collections
import numpy as np
from chainerrl.misc.random import sample_n_k
class PrioritizedBuffer (object):
def __init__(self, capacity=None, wait_priority_after_sampling=True,
initial_max_priority=1.0):
self.capacity = capacity
self.data = collections.deque()
... |
44,681 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/misc/prioritized.py | 193,194 | 152,213 | popleft | TreeQueue | 194,213 | 194,213 | class TreeQueue(object):
"""Queue with Binary Indexed Tree cache
queue-like data structure
append, update are O(log n)
reduction over an interval is O(log n) per query
"""
# node = left_child, right_child, value
def __init__(self, op):
self.length = 0
self.op = op
def... | class TreeQueue(object):
"""Queue with Binary Indexed Tree cache
queue-like data structure
append, update are O(log n)
reduction over an interval is O(log n) per query
"""
# node = left_child, right_child, value
def __init__(self, op):
self.length = 0
self.op = op
def... | assert self.length > 0
ret = self._write(0, None)
ixl, ixr = self.bounds
ixl -= 1
ixr -= 1
self.length -= 1
if self.length == 0:
del self.root
del self.bounds
return ret
ixc = (ixl + ixr) // 2
if ixc == 0:
... | assert self.length > 0
ret = self._write(0, None)
ixl, ixr = self.bounds
ixl -= 1
ixr -= 1
self.length -= 1
if self.length == 0:
del self.root
del self.bounds
return ret
ixc = (ixl + ixr) // 2
if ixc == 0:
... | 56 | 370 | 164 | 534 | import collections
import numpy as np
from chainerrl.misc.random import sample_n_k
class PrioritizedBuffer (object):
def __init__(self, capacity=None, wait_priority_after_sampling=True,
initial_max_priority=1.0):
self.capacity = capacity
self.data = collections.deque()
... | import collections
import numpy as np
from chainerrl.misc.random import sample_n_k
class PrioritizedBuffer (object):
def __init__(self, capacity=None, wait_priority_after_sampling=True,
initial_max_priority=1.0):
self.capacity = capacity
self.data = collections.deque()
... |
44,682 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/misc/random.py | 4,5 | 1,29 | sample_n_k | 6,29 | 5,29 | import numpy as np
def sample_n_k(n, k):
FILL_FUNC_BODY | import numpy as np
def sample_n_k(n, k):
"""Sample k distinct elements uniformly from range(n)"""
FILL_FUNC_BODY |
if not 0 <= k <= n:
raise ValueError("Sample larger than population or is negative")
if k == 0:
return np.empty((0,), dtype=np.int64)
elif 3 * k >= n:
return np.random.choice(n, k, replace=False)
else:
result = np.random.choice(n, 2 * k)
selected = set()
... | """Sample k distinct elements uniformly from range(n)"""
if not 0 <= k <= n:
raise ValueError("Sample larger than population or is negative")
if k == 0:
return np.empty((0,), dtype=np.int64)
elif 3 * k >= n:
return np.random.choice(n, k, replace=False)
else:
result =... | 91 | 44 | 243 | 287 | import numpy as np
def sample_n_k(n, k):
FILL_FUNC_BODY | import numpy as np
def sample_n_k(n, k):
"""Sample k distinct elements uniformly from range(n)"""
FILL_FUNC_BODY | |
44,683 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/policies/gaussian_policy.py | 92,93 | 18,108 | compute_mean_and_var | FCGaussianPolicy | 93,103 | 93,103 | class FCGaussianPolicy(chainer.ChainList, Policy):
"""Gaussian policy that consists of fully-connected layers.
This model has two output layers: the mean layer and the variance layer.
The mean of the Gaussian is computed as follows:
Let y as the output of the mean layer.
If bound_mean=False... | class FCGaussianPolicy(chainer.ChainList, Policy):
"""Gaussian policy that consists of fully-connected layers.
This model has two output layers: the mean layer and the variance layer.
The mean of the Gaussian is computed as follows:
Let y as the output of the mean layer.
If bound_mean=False... | h = x
for layer in self.hidden_layers:
h = self.nonlinearity(layer(h))
mean = self.mean_layer(h)
if self.bound_mean:
mean = bound_by_tanh(mean, self.min_action, self.max_action)
var = F.broadcast_to(F.softplus(self.var_layer(h)), mean.shape) + \
... | h = x
for layer in self.hidden_layers:
h = self.nonlinearity(layer(h))
mean = self.mean_layer(h)
if self.bound_mean:
mean = bound_by_tanh(mean, self.min_action, self.max_action)
var = F.broadcast_to(F.softplus(self.var_layer(h)), mean.shape) + \
... | 30 | 1,031 | 131 | 1,162 | from logging import getLogger
import chainer
from chainer import functions as F
from chainer.initializers import LeCunNormal
from chainer import links as L
import numpy as np
from chainerrl import distribution
from chainerrl.functions.bound_by_tanh import bound_by_tanh
from chainerrl import links
from chainerrl.polic... | from logging import getLogger
import chainer
from chainer import functions as F
from chainer.initializers import LeCunNormal
from chainer import links as L
import numpy as np
from chainerrl import distribution
from chainerrl.functions.bound_by_tanh import bound_by_tanh
from chainerrl import links
from chainerrl.polic... |
44,684 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/policies/gaussian_policy.py | 238,239 | 179,247 | get_var_array | FCGaussianPolicyWithFixedCovariance | 239,242 | 239,242 | class FCGaussianPolicyWithFixedCovariance(links.Sequence, Policy):
"""Gaussian policy that consists of FC layers with fixed covariance.
This model has one output layers: the mean layer.
The mean of the Gaussian is computed in the same way as FCGaussianPolicy.
The variance of the Gaussian must be specif... | class FCGaussianPolicyWithFixedCovariance(links.Sequence, Policy):
"""Gaussian policy that consists of FC layers with fixed covariance.
This model has one output layers: the mean layer.
The mean of the Gaussian is computed in the same way as FCGaussianPolicy.
The variance of the Gaussian must be specif... | self.var = self.xp.asarray(self.var)
return self.xp.broadcast_to(self.var, shape)
| self.var = self.xp.asarray(self.var)
return self.xp.broadcast_to(self.var, shape)
| 6 | 805 | 42 | 847 | from logging import getLogger
import chainer
from chainer import functions as F
from chainer.initializers import LeCunNormal
from chainer import links as L
import numpy as np
from chainerrl import distribution
from chainerrl.functions.bound_by_tanh import bound_by_tanh
from chainerrl import links
from chainerrl.polic... | from logging import getLogger
import chainer
from chainer import functions as F
from chainer.initializers import LeCunNormal
from chainer import links as L
import numpy as np
from chainerrl import distribution
from chainerrl.functions.bound_by_tanh import bound_by_tanh
from chainerrl import links
from chainerrl.polic... |
44,686 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/replay_buffer.py | 81,83 | 75,127 | sample_episodes | AbstractEpisodicReplayBuffer | 95,97 | 83,97 | class AbstractEpisodicReplayBuffer(AbstractReplayBuffer):
"""Defines a common interface of episodic replay buffer.
Episodic replay buffers allows you to append and sample episodes.
"""
@abstractmethod
def sample_episodes(self, n_episodes, max_len=None):
FILL_FUNC_BODY @abstractproperty
def ... | class AbstractEpisodicReplayBuffer(AbstractReplayBuffer):
"""Defines a common interface of episodic replay buffer.
Episodic replay buffers allows you to append and sample episodes.
"""
@abstractmethod
def sample_episodes(self, n_episodes, max_len=None):
"""Sample n unique (sub)episodes fro... | raise NotImplementedError
| """Sample n unique (sub)episodes from this replay buffer.
Args:
n (int): Number of episodes to sample.
max_len (int or None): Maximum length of sampled episodes. If it is
smaller than the length of some episode, the subsequence of the
episode is s... | 2 | 462 | 11 | 473 | from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
import itertools
import numpy as np
from chainerrl.misc.batch_states import batch_states
class AbstractReplayBuffer(object, metaclass=ABCMeta):
"""Defines a common interface of replay buffer.
You can append transitions ... | from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
import itertools
import numpy as np
from chainerrl.misc.batch_states import batch_states
class AbstractReplayBuffer(object, metaclass=ABCMeta):
"""Defines a common interface of replay buffer.
You can append transitions ... |
44,687 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/replay_buffer.py | 36,38 | 11,75 | sample | AbstractReplayBuffer | 45,47 | 38,47 | class AbstractReplayBuffer(object, metaclass=ABCMeta):
"""Defines a common interface of replay buffer.
You can append transitions to the replay buffer and later sample from it.
Replay buffers are typically used in experience replay.
"""
@abstractmethod
def append(self, state, action, reward, n... | class AbstractReplayBuffer(object, metaclass=ABCMeta):
"""Defines a common interface of replay buffer.
You can append transitions to the replay buffer and later sample from it.
Replay buffers are typically used in experience replay.
"""
@abstractmethod
def append(self, state, action, reward, n... | raise NotImplementedError
| """Sample n unique transitions from this replay buffer.
Args:
n (int): Number of transitions to sample.
Returns:
Sequence of n sampled transitions.
"""
raise NotImplementedError
| 2 | 501 | 11 | 512 | from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
import itertools
import numpy as np
from chainerrl.misc.batch_states import batch_states
class AbstractReplayBuffer(object, metaclass=ABCMeta):
"""Defines a common interface of replay buffer.
You can append transitions ... | from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
import itertools
import numpy as np
from chainerrl.misc.batch_states import batch_states
class AbstractReplayBuffer(object, metaclass=ABCMeta):
"""Defines a common interface of replay buffer.
You can append transitions ... |
44,688 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/replay_buffer.py | 262,263 | 230,281 | update_if_necessary | ReplayUpdater | 263,281 | 263,281 | class ReplayUpdater(object):
"""Object that handles update schedule and configurations.
Args:
replay_buffer (ReplayBuffer): Replay buffer
update_func (callable): Callable that accepts one of these:
(1) a list of transition dicts (if episodic_update=False)
(2) a list of l... | class ReplayUpdater(object):
"""Object that handles update schedule and configurations.
Args:
replay_buffer (ReplayBuffer): Replay buffer
update_func (callable): Callable that accepts one of these:
(1) a list of transition dicts (if episodic_update=False)
(2) a list of l... | if len(self.replay_buffer) < self.replay_start_size:
return
if (self.episodic_update
and self.replay_buffer.n_episodes < self.batchsize):
return
if iteration % self.update_interval != 0:
return
for _ in range(self.n_times_update):
... | if len(self.replay_buffer) < self.replay_start_size:
return
if (self.episodic_update
and self.replay_buffer.n_episodes < self.batchsize):
return
if iteration % self.update_interval != 0:
return
for _ in range(self.n_times_update):
... | 36 | 440 | 206 | 646 | from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
import itertools
import numpy as np
from chainerrl.misc.batch_states import batch_states
class AbstractReplayBuffer(object, metaclass=ABCMeta):
"""Defines a common interface of replay buffer.
You can append transitions ... | from abc import ABCMeta
from abc import abstractmethod
from abc import abstractproperty
import itertools
import numpy as np
from chainerrl.misc.batch_states import batch_states
class AbstractReplayBuffer(object, metaclass=ABCMeta):
"""Defines a common interface of replay buffer.
You can append transitions ... |
44,689 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/replay_buffers/episodic.py | 32,33 | 9,84 | sample_episodes | EpisodicReplayBuffer | 33,40 | 33,40 | class EpisodicReplayBuffer(AbstractEpisodicReplayBuffer):
def __init__(self, capacity=None):
self.current_episode = collections.defaultdict(list)
self.episodic_memory = RandomAccessQueue()
self.memory = RandomAccessQueue()
self.capacity = capacity
def append(self, state, action... | class EpisodicReplayBuffer(AbstractEpisodicReplayBuffer):
def __init__(self, capacity=None):
self.current_episode = collections.defaultdict(list)
self.episodic_memory = RandomAccessQueue()
self.memory = RandomAccessQueue()
self.capacity = capacity
def append(self, state, action... | assert len(self.episodic_memory) >= n_episodes
episodes = self.episodic_memory.sample(n_episodes)
if max_len is not None:
return [random_subseq(ep, max_len) for ep in episodes]
else:
return episodes
| assert len(self.episodic_memory) >= n_episodes
episodes = self.episodic_memory.sample(n_episodes)
if max_len is not None:
return [random_subseq(ep, max_len) for ep in episodes]
else:
return episodes
| 22 | 789 | 87 | 876 | import collections
import pickle
from chainerrl.misc.collections import RandomAccessQueue
from chainerrl.replay_buffer import AbstractEpisodicReplayBuffer
from chainerrl.replay_buffer import random_subseq
class EpisodicReplayBuffer(AbstractEpisodicReplayBuffer):
def __init__(self, capacity=None):
self.c... | import collections
import pickle
from chainerrl.misc.collections import RandomAccessQueue
from chainerrl.replay_buffer import AbstractEpisodicReplayBuffer
from chainerrl.replay_buffer import random_subseq
class EpisodicReplayBuffer(AbstractEpisodicReplayBuffer):
def __init__(self, capacity=None):
self.c... |
44,690 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/replay_buffers/prioritized_episodic.py | 53,54 | 10,69 | stop_current_episode | PrioritizedEpisodicReplayBuffer | 54,69 | 54,69 | class PrioritizedEpisodicReplayBuffer (
EpisodicReplayBuffer, PriorityWeightError):
def __init__(self, capacity=None,
alpha=0.6, beta0=0.4, betasteps=2e5, eps=1e-8,
normalize_by_max=True,
default_priority_func=None,
uniform_ratio=0,
... | class PrioritizedEpisodicReplayBuffer (
EpisodicReplayBuffer, PriorityWeightError):
def __init__(self, capacity=None,
alpha=0.6, beta0=0.4, betasteps=2e5, eps=1e-8,
normalize_by_max=True,
default_priority_func=None,
uniform_ratio=0,
... | current_episode = self.current_episode[env_id]
if current_episode:
if self.default_priority_func is not None:
priority = self.default_priority_func(current_episode)
else:
priority = None
self.memory.extend(current_episode)
s... | current_episode = self.current_episode[env_id]
if current_episode:
if self.default_priority_func is not None:
priority = self.default_priority_func(current_episode)
else:
priority = None
self.memory.extend(current_episode)
s... | 49 | 574 | 240 | 814 | import collections
from chainerrl.misc.collections import RandomAccessQueue
from chainerrl.misc.prioritized import PrioritizedBuffer
from chainerrl.replay_buffer import random_subseq
from chainerrl.replay_buffers import EpisodicReplayBuffer
from chainerrl.replay_buffers import PriorityWeightError
class PrioritizedEp... | import collections
from chainerrl.misc.collections import RandomAccessQueue
from chainerrl.misc.prioritized import PrioritizedBuffer
from chainerrl.replay_buffer import random_subseq
from chainerrl.replay_buffers import EpisodicReplayBuffer
from chainerrl.replay_buffers import PriorityWeightError
class PrioritizedEp... |
44,691 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/replay_buffers/replay_buffer.py | 50,51 | 8,82 | stop_current_episode | ReplayBuffer | 51,64 | 51,64 | class ReplayBuffer(replay_buffer.AbstractReplayBuffer):
"""Experience Replay Buffer
As described in
https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf.
Args:
capacity (int): capacity in terms of number of transitions
num_steps (int): Number of timesteps per stored tra... | class ReplayBuffer(replay_buffer.AbstractReplayBuffer):
"""Experience Replay Buffer
As described in
https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf.
Args:
capacity (int): capacity in terms of number of transitions
num_steps (int): Number of timesteps per stored tra... | last_n_transitions = self.last_n_transitions[env_id]
# if n-step transition hist is not full, add transition;
# if n-step hist is indeed full, transition has already been added;
if 0 < len(last_n_transitions) < self.num_steps:
self.memory.append(list(last_n_transitions))
... | last_n_transitions = self.last_n_transitions[env_id]
# if n-step transition hist is not full, add transition;
# if n-step hist is indeed full, transition has already been added;
if 0 < len(last_n_transitions) < self.num_steps:
self.memory.append(list(last_n_transitions))
... | 53 | 660 | 202 | 862 | import collections
import pickle
from chainerrl.misc.collections import RandomAccessQueue
from chainerrl import replay_buffer
class ReplayBuffer(replay_buffer.AbstractReplayBuffer):
"""Experience Replay Buffer
As described in
https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf.
Arg... | import collections
import pickle
from chainerrl.misc.collections import RandomAccessQueue
from chainerrl import replay_buffer
class ReplayBuffer(replay_buffer.AbstractReplayBuffer):
"""Experience Replay Buffer
As described in
https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf.
Arg... |
44,692 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/wrappers/cast_observation.py | 20,21 | 5,25 | observation | CastObservation | 21,25 | 21,25 | class CastObservation(gym.ObservationWrapper):
"""Cast observations to a given type.
Args:
env: Env to wrap.
dtype: Data type object.
Attributes:
original_observation: Observation before casting.
"""
def __init__(self, env, dtype):
super().__init__(env)
sel... | class CastObservation(gym.ObservationWrapper):
"""Cast observations to a given type.
Args:
env: Env to wrap.
dtype: Data type object.
Attributes:
original_observation: Observation before casting.
"""
def __init__(self, env, dtype):
super().__init__(env)
sel... | self.original_observation = observation
return observation.astype(self.dtype, copy=False)
| self.original_observation = observation
return observation.astype(self.dtype, copy=False)
| 6 | 121 | 33 | 154 | import gym
import numpy as np
class CastObservation(gym.ObservationWrapper):
"""Cast observations to a given type.
Args:
env: Env to wrap.
dtype: Data type object.
Attributes:
original_observation: Observation before casting.
"""
def __init__(self, env, dtype):
s... | import gym
import numpy as np
class CastObservation(gym.ObservationWrapper):
"""Cast observations to a given type.
Args:
env: Env to wrap.
dtype: Data type object.
Attributes:
original_observation: Observation before casting.
"""
def __init__(self, env, dtype):
s... |
44,693 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/wrappers/continuing_time_limit.py | 27,28 | 4,41 | step | ContinuingTimeLimit | 28,38 | 28,38 | class ContinuingTimeLimit(gym.Wrapper):
"""TimeLimit wrapper for continuing environments.
This is similar gym.wrappers.TimeLimit, which sets a time limit for
each episode, except that done=False is returned and that
info['needs_reset'] is set to True when past the limit.
Code that calls env.step i... | class ContinuingTimeLimit(gym.Wrapper):
"""TimeLimit wrapper for continuing environments.
This is similar gym.wrappers.TimeLimit, which sets a time limit for
each episode, except that done=False is returned and that
info['needs_reset'] is set to True when past the limit.
Code that calls env.step i... | assert self._elapsed_steps is not None,\
"Cannot call env.step() before calling reset()"
observation, reward, done, info = self.env.step(action)
self._elapsed_steps += 1
if self._max_episode_steps <= self._elapsed_steps:
info['needs_reset'] = True
return... | assert self._elapsed_steps is not None,\
"Cannot call env.step() before calling reset()"
observation, reward, done, info = self.env.step(action)
self._elapsed_steps += 1
if self._max_episode_steps <= self._elapsed_steps:
info['needs_reset'] = True
return... | 32 | 287 | 107 | 394 | import gym
class ContinuingTimeLimit(gym.Wrapper):
"""TimeLimit wrapper for continuing environments.
This is similar gym.wrappers.TimeLimit, which sets a time limit for
each episode, except that done=False is returned and that
info['needs_reset'] is set to True when past the limit.
Code that cal... | import gym
class ContinuingTimeLimit(gym.Wrapper):
"""TimeLimit wrapper for continuing environments.
This is similar gym.wrappers.TimeLimit, which sets a time limit for
each episode, except that done=False is returned and that
info['needs_reset'] is set to True when past the limit.
Code that cal... |
44,694 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/wrappers/normalize_action_space.py | 17,18 | 6,29 | action | NormalizeActionSpace | 18,29 | 18,29 | class NormalizeActionSpace(gym.ActionWrapper):
"""Normalize a Box action space to [-1, 1]^n."""
def __init__(self, env):
super().__init__(env)
assert isinstance(env.action_space, gym.spaces.Box)
self.action_space = gym.spaces.Box(
low=-np.ones_like(env.action_space.low),
... | class NormalizeActionSpace(gym.ActionWrapper):
"""Normalize a Box action space to [-1, 1]^n."""
def __init__(self, env):
super().__init__(env)
assert isinstance(env.action_space, gym.spaces.Box)
self.action_space = gym.spaces.Box(
low=-np.ones_like(env.action_space.low),
... | # action is in [0, 1]
action = action.copy()
# -> [0, 2]
action += 1
# -> [0, orig_high - orig_low]
action *= (self.env.action_space.high - self.env.action_space.low) / 2
# -> [orig_low, orig_high]
return action + self.env.action_space.low
| # action is in [0, 1]
action = action.copy()
# -> [0, 2]
action += 1
# -> [0, orig_high - orig_low]
action *= (self.env.action_space.high - self.env.action_space.low) / 2
# -> [orig_low, orig_high]
return action + self.env.action_space.low
| 37 | 146 | 123 | 269 | import gym
import gym.spaces
import numpy as np
class NormalizeActionSpace(gym.ActionWrapper):
"""Normalize a Box action space to [-1, 1]^n."""
def __init__(self, env):
super().__init__(env)
assert isinstance(env.action_space, gym.spaces.Box)
self.action_space = gym.spaces.Box(
... | import gym
import gym.spaces
import numpy as np
class NormalizeActionSpace(gym.ActionWrapper):
"""Normalize a Box action space to [-1, 1]^n."""
def __init__(self, env):
super().__init__(env)
assert isinstance(env.action_space, gym.spaces.Box)
self.action_space = gym.spaces.Box(
... |
44,695 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/wrappers/render.py | 21,22 | 4,25 | step | Render | 22,25 | 22,25 | class Render(gym.Wrapper):
"""Render env by calling its render method.
Args:
env (gym.Env): Env to wrap.
**kwargs: Keyword arguments passed to the render method.
"""
def __init__(self, env, **kwargs):
super().__init__(env)
self._kwargs = kwargs
def reset(self, **kw... | class Render(gym.Wrapper):
"""Render env by calling its render method.
Args:
env (gym.Env): Env to wrap.
**kwargs: Keyword arguments passed to the render method.
"""
def __init__(self, env, **kwargs):
super().__init__(env)
self._kwargs = kwargs
def reset(self, **kw... | ret = self.env.step(action)
self.env.render(**self._kwargs)
return ret
| ret = self.env.step(action)
self.env.render(**self._kwargs)
return ret
| 6 | 151 | 32 | 183 | import gym
class Render(gym.Wrapper):
"""Render env by calling its render method.
Args:
env (gym.Env): Env to wrap.
**kwargs: Keyword arguments passed to the render method.
"""
def __init__(self, env, **kwargs):
super().__init__(env)
self._kwargs = kwargs
def res... | import gym
class Render(gym.Wrapper):
"""Render env by calling its render method.
Args:
env (gym.Env): Env to wrap.
**kwargs: Keyword arguments passed to the render method.
"""
def __init__(self, env, **kwargs):
super().__init__(env)
self._kwargs = kwargs
def res... |
44,696 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/wrappers/scale_reward.py | 21,22 | 4,24 | reward | ScaleReward | 22,24 | 22,24 | class ScaleReward(gym.RewardWrapper):
"""Scale reward by a scale factor.
Args:
env: Env to wrap.
scale (float): Scale factor.
Attributes:
scale: Scale factor.
original_reward: Reward before casting.
"""
def __init__(self, env, scale):
super().__init__(env)
... | class ScaleReward(gym.RewardWrapper):
"""Scale reward by a scale factor.
Args:
env: Env to wrap.
scale (float): Scale factor.
Attributes:
scale: Scale factor.
original_reward: Reward before casting.
"""
def __init__(self, env, scale):
super().__init__(env)
... | self.original_reward = reward
return self.scale * reward
| self.original_reward = reward
return self.scale * reward
| 7 | 137 | 20 | 157 | import gym
class ScaleReward(gym.RewardWrapper):
"""Scale reward by a scale factor.
Args:
env: Env to wrap.
scale (float): Scale factor.
Attributes:
scale: Scale factor.
original_reward: Reward before casting.
"""
def __init__(self, env, scale):
super()._... | import gym
class ScaleReward(gym.RewardWrapper):
"""Scale reward by a scale factor.
Args:
env: Env to wrap.
scale (float): Scale factor.
Attributes:
scale: Scale factor.
original_reward: Reward before casting.
"""
def __init__(self, env, scale):
super()._... |
44,697 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/wrappers/vector_frame_stack.py | 33,34 | 10,53 | close | VectorEnvWrapper | 34,36 | 34,36 | class VectorEnvWrapper(VectorEnv):
"""VectorEnv analog to gym.Wrapper."""
def __init__(self, env):
self.env = env
self.action_space = self.env.action_space
self.observation_space = self.env.observation_space
def __getattr__(self, name):
if name.startswith('_'):
... | class VectorEnvWrapper(VectorEnv):
"""VectorEnv analog to gym.Wrapper."""
def __init__(self, env):
self.env = env
self.action_space = self.env.action_space
self.observation_space = self.env.observation_space
def __getattr__(self, name):
if name.startswith('_'):
... | return self.env.close()
| return self.env.close()
| 2 | 369 | 12 | 381 | from collections import deque
from gym import spaces
import numpy as np
from chainerrl.env import VectorEnv
from chainerrl.wrappers.atari_wrappers import LazyFrames
class VectorEnvWrapper(VectorEnv):
"""VectorEnv analog to gym.Wrapper."""
def __init__(self, env):
self.env = env
self.action_... | from collections import deque
from gym import spaces
import numpy as np
from chainerrl.env import VectorEnv
from chainerrl.wrappers.atari_wrappers import LazyFrames
class VectorEnvWrapper(VectorEnv):
"""VectorEnv analog to gym.Wrapper."""
def __init__(self, env):
self.env = env
self.action_... |
44,698 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/chainerrl/wrappers/vector_frame_stack.py | 91,92 | 53,102 | step | VectorFrameStack | 92,97 | 92,97 | class VectorFrameStack(VectorEnvWrapper):
"""VectorEnv analog to chainerrl.wrappers.atari_wrappers.FrameStack.
The original `chainerrl.wrappers.atari_wrappers.FrameStack` does not work
properly with `chainerrl.envs.MultiprocessVectorEnv` because LazyFrames
becomes not lazy when passed between processes... | class VectorFrameStack(VectorEnvWrapper):
"""VectorEnv analog to chainerrl.wrappers.atari_wrappers.FrameStack.
The original `chainerrl.wrappers.atari_wrappers.FrameStack` does not work
properly with `chainerrl.envs.MultiprocessVectorEnv` because LazyFrames
becomes not lazy when passed between processes... | batch_ob, reward, done, info = self.env.step(action)
for frames, ob in zip(self.frames, batch_ob):
frames.append(ob)
return self._get_ob(), reward, done, info
| batch_ob, reward, done, info = self.env.step(action)
for frames, ob in zip(self.frames, batch_ob):
frames.append(ob)
return self._get_ob(), reward, done, info
| 18 | 585 | 65 | 650 | from collections import deque
from gym import spaces
import numpy as np
from chainerrl.env import VectorEnv
from chainerrl.wrappers.atari_wrappers import LazyFrames
class VectorEnvWrapper(VectorEnv):
"""VectorEnv analog to gym.Wrapper."""
def __init__(self, env):
self.env = env
self.action_... | from collections import deque
from gym import spaces
import numpy as np
from chainerrl.env import VectorEnv
from chainerrl.wrappers.atari_wrappers import LazyFrames
class VectorEnvWrapper(VectorEnv):
"""VectorEnv analog to gym.Wrapper."""
def __init__(self, env):
self.env = env
self.action_... |
44,699 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/examples/atari/collect_demos_ale.py | 19,20 | 1,111 | main | 20,109 | 20,109 | import argparse
import os
from chainer import links as L
from chainer import optimizers
import numpy as np
import chainerrl
from chainerrl.action_value import DiscreteActionValue
from chainerrl import agents
from chainerrl import experiments
from chainerrl import links
from chainerrl import misc
from chainerrl import... | import argparse
import os
from chainer import links as L
from chainer import optimizers
import numpy as np
import chainerrl
from chainerrl.action_value import DiscreteActionValue
from chainerrl import agents
from chainerrl import experiments
from chainerrl import links
from chainerrl import misc
from chainerrl import... | parser = argparse.ArgumentParser()
parser.add_argument('--env', type=str, default='BreakoutNoFrameskip-v4',
help='OpenAI Atari domain to perform algorithm on.')
parser.add_argument('--outdir', type=str, default='results',
help='Directory path to save output fi... | parser = argparse.ArgumentParser()
parser.add_argument('--env', type=str, default='BreakoutNoFrameskip-v4',
help='OpenAI Atari domain to perform algorithm on.')
parser.add_argument('--outdir', type=str, default='results',
help='Directory path to save output fi... | 254 | 136 | 1,173 | 1,309 | import argparse
import os
from chainer import links as L
from chainer import optimizers
import numpy as np
import chainerrl
from chainerrl.action_value import DiscreteActionValue
from chainerrl import agents
from chainerrl import experiments
from chainerrl import links
from chainerrl import misc
from chainerrl import... | import argparse
import os
from chainer import links as L
from chainer import optimizers
import numpy as np
import chainerrl
from chainerrl.action_value import DiscreteActionValue
from chainerrl import agents
from chainerrl import experiments
from chainerrl import links
from chainerrl import misc
from chainerrl import... | |
44,701 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/examples/atari/reproduction/a3c/train_a3c.py | 33,34 | 24,38 | pi_and_v | A3CFF | 34,38 | 34,38 | class A3CFF(chainer.ChainList, a3c.A3CModel):
def __init__(self, n_actions):
self.head = links.NIPSDQNHead()
self.pi = policies.FCSoftmaxPolicy(
self.head.n_output_channels, n_actions)
self.v = v_functions.FCVFunction(self.head.n_output_channels)
super().__init__(self.he... | class A3CFF(chainer.ChainList, a3c.A3CModel):
def __init__(self, n_actions):
self.head = links.NIPSDQNHead()
self.pi = policies.FCSoftmaxPolicy(
self.head.n_output_channels, n_actions)
self.v = v_functions.FCVFunction(self.head.n_output_channels)
super().__init__(self.he... | out = self.head(state)
return self.pi(out), self.v(out)
| out = self.head(state)
return self.pi(out), self.v(out)
| 6 | 148 | 31 | 179 | import argparse
import os
# Prevent numpy from using multiple threads
os.environ['OMP_NUM_THREADS'] = '1' # NOQA
import chainer
import gym
import numpy as np
import chainerrl
from chainerrl.agents import a3c
from chainerrl import experiments
from chainerrl import links
from chainerrl import misc
from chainerrl.opti... | import argparse
import os
# Prevent numpy from using multiple threads
os.environ['OMP_NUM_THREADS'] = '1' # NOQA
import chainer
import gym
import numpy as np
import chainerrl
from chainerrl.agents import a3c
from chainerrl import experiments
from chainerrl import links
from chainerrl import misc
from chainerrl.opti... |
44,706 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/examples/atari/train_a2c_ale.py | 37,38 | 26,42 | pi_and_v | A2CFF | 38,42 | 38,42 | class A2CFF(chainer.ChainList, a2c.A2CModel):
def __init__(self, n_actions):
self.action_space = 1
self.head = links.NIPSDQNHead()
self.pi = policy.FCSoftmaxPolicy(
self.head.n_output_channels, n_actions)
self.v = v_function.FCVFunction(self.head.n_output_channels)
... | class A2CFF(chainer.ChainList, a2c.A2CModel):
def __init__(self, n_actions):
self.action_space = 1
self.head = links.NIPSDQNHead()
self.pi = policy.FCSoftmaxPolicy(
self.head.n_output_channels, n_actions)
self.v = v_function.FCVFunction(self.head.n_output_channels)
... | out = self.head(state)
return self.pi(out), self.v(out)
| out = self.head(state)
return self.pi(out), self.v(out)
| 6 | 158 | 31 | 189 | import argparse
import functools
import logging
import chainer
import numpy as np
import chainerrl
from chainerrl.agents import a2c
from chainerrl import experiments
from chainerrl import links
from chainerrl import misc
from chainerrl.optimizers.nonbias_weight_decay import NonbiasWeightDecay
from chainerrl.optimizer... | import argparse
import functools
import logging
import chainer
import numpy as np
import chainerrl
from chainerrl.agents import a2c
from chainerrl import experiments
from chainerrl import links
from chainerrl import misc
from chainerrl.optimizers.nonbias_weight_decay import NonbiasWeightDecay
from chainerrl.optimizer... |
44,708 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/examples/atari/train_a3c_ale.py | 36,37 | 27,41 | pi_and_v | A3CFF | 37,41 | 37,41 | class A3CFF(chainer.ChainList, a3c.A3CModel):
def __init__(self, n_actions):
self.head = links.NIPSDQNHead()
self.pi = policy.FCSoftmaxPolicy(
self.head.n_output_channels, n_actions)
self.v = v_function.FCVFunction(self.head.n_output_channels)
super().__init__(self.head,... | class A3CFF(chainer.ChainList, a3c.A3CModel):
def __init__(self, n_actions):
self.head = links.NIPSDQNHead()
self.pi = policy.FCSoftmaxPolicy(
self.head.n_output_channels, n_actions)
self.v = v_function.FCVFunction(self.head.n_output_channels)
super().__init__(self.head,... | out = self.head(state)
return self.pi(out), self.v(out)
| out = self.head(state)
return self.pi(out), self.v(out)
| 6 | 148 | 31 | 179 | import argparse
import os
# Prevent numpy from using multiple threads
os.environ['OMP_NUM_THREADS'] = '1' # NOQA
import chainer
from chainer import links as L
import gym
import gym.wrappers
import numpy as np
import chainerrl
from chainerrl.agents import a3c
from chainerrl import experiments
from chainerrl import l... | import argparse
import os
# Prevent numpy from using multiple threads
os.environ['OMP_NUM_THREADS'] = '1' # NOQA
import chainer
from chainer import links as L
import gym
import gym.wrappers
import numpy as np
import chainerrl
from chainerrl.agents import a3c
from chainerrl import experiments
from chainerrl import l... |
44,709 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/examples/atari/train_a3c_ale.py | 52,53 | 41,58 | pi_and_v | A3CLSTM | 53,58 | 53,58 | class A3CLSTM(chainer.ChainList, a3c.A3CModel, RecurrentChainMixin):
def __init__(self, n_actions):
self.head = links.NIPSDQNHead()
self.pi = policy.FCSoftmaxPolicy(
self.head.n_output_channels, n_actions)
self.v = v_function.FCVFunction(self.head.n_output_channels)
self... | class A3CLSTM(chainer.ChainList, a3c.A3CModel, RecurrentChainMixin):
def __init__(self, n_actions):
self.head = links.NIPSDQNHead()
self.pi = policy.FCSoftmaxPolicy(
self.head.n_output_channels, n_actions)
self.v = v_function.FCVFunction(self.head.n_output_channels)
self... | h = self.head(state)
h = self.lstm(h)
return self.pi(h), self.v(h)
| h = self.head(state)
h = self.lstm(h)
return self.pi(h), self.v(h)
| 9 | 197 | 44 | 241 | import argparse
import os
# Prevent numpy from using multiple threads
os.environ['OMP_NUM_THREADS'] = '1' # NOQA
import chainer
from chainer import links as L
import gym
import gym.wrappers
import numpy as np
import chainerrl
from chainerrl.agents import a3c
from chainerrl import experiments
from chainerrl import l... | import argparse
import os
# Prevent numpy from using multiple threads
os.environ['OMP_NUM_THREADS'] = '1' # NOQA
import chainer
from chainer import links as L
import gym
import gym.wrappers
import numpy as np
import chainerrl
from chainerrl.agents import a3c
from chainerrl import experiments
from chainerrl import l... |
44,719 | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl | /home/hieuvd/dung_repo/raw/stars_03/chainer_chainerrl/chainerrl/examples/gym/train_iqn_gym.py | 25,26 | 1,151 | main | 26,149 | 26,149 | """An example of training Categorical DQN against OpenAI Gym Envs.
This script is an example of training an IQN agent against OpenAI
Gym envs. Only discrete spaces are supported.
To solve CartPole-v0, run:
python train_categorical_dqn_gym.py --env CartPole-v0
"""
import argparse
import sys
import chainer.functi... | """An example of training Categorical DQN against OpenAI Gym Envs.
This script is an example of training an IQN agent against OpenAI
Gym envs. Only discrete spaces are supported.
To solve CartPole-v0, run:
python train_categorical_dqn_gym.py --env CartPole-v0
"""
import argparse
import sys
import chainer.functi... | import logging
logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument('--outdir', type=str, default='results',
help='Directory path to save output files.'
' If it does not exist, it will be created.')
pars... | import logging
logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument('--outdir', type=str, default='results',
help='Directory path to save output files.'
' If it does not exist, it will be created.')
pars... | 294 | 194 | 1,773 | 1,967 | """An example of training Categorical DQN against OpenAI Gym Envs.
This script is an example of training an IQN agent against OpenAI
Gym envs. Only discrete spaces are supported.
To solve CartPole-v0, run:
python train_categorical_dqn_gym.py --env CartPole-v0
"""
import argparse
import sys
import chainer.functi... | """An example of training Categorical DQN against OpenAI Gym Envs.
This script is an example of training an IQN agent against OpenAI
Gym envs. Only discrete spaces are supported.
To solve CartPole-v0, run:
python train_categorical_dqn_gym.py --env CartPole-v0
"""
import argparse
import sys
import chainer.functi... | |
44,756 | /home/hieuvd/dung_repo/raw/stars_03/codingo_VHostScan/VHostScan | /home/hieuvd/dung_repo/raw/stars_03/codingo_VHostScan/VHostScan/VHostScan/lib/helpers/file_helper.py | 34,35 | 1,66 | parse_word_list_argument | 35,49 | 35,49 | import json
import os
from pkg_resources import resource_filename
DEFAULT_UA_LIST = resource_filename(
'VHostScan', 'lib/ua-random-list.txt')
class file_helper(object):
"""description of class"""
def __init__(self, output_file):
self.output_file = output_file
def check_directory(self):
... | import json
import os
from pkg_resources import resource_filename
DEFAULT_UA_LIST = resource_filename(
'VHostScan', 'lib/ua-random-list.txt')
class file_helper(object):
"""description of class"""
def __init__(self, output_file):
self.output_file = output_file
def check_directory(self):
... | if not argument:
return []
if ',' in argument:
files = [arg.strip() for arg in argument.split(',')]
else:
files = [argument.strip()]
return [
path for path in files
if os.path.exists(path)
]
| if not argument:
return []
if ',' in argument:
files = [arg.strip() for arg in argument.split(',')]
else:
files = [argument.strip()]
return [
path for path in files
if os.path.exists(path)
]
| 30 | 378 | 94 | 472 | import json
import os
from pkg_resources import resource_filename
DEFAULT_UA_LIST = resource_filename(
'VHostScan', 'lib/ua-random-list.txt')
class file_helper(object):
"""description of class"""
def __init__(self, output_file):
self.output_file = output_file
def check_directory(self):
... | import json
import os
from pkg_resources import resource_filename
DEFAULT_UA_LIST = resource_filename(
'VHostScan', 'lib/ua-random-list.txt')
class file_helper(object):
"""description of class"""
def __init__(self, output_file):
self.output_file = output_file
def check_directory(self):
... | |
44,757 | /home/hieuvd/dung_repo/raw/stars_03/codingo_VHostScan/VHostScan | /home/hieuvd/dung_repo/raw/stars_03/codingo_VHostScan/VHostScan/VHostScan/lib/helpers/file_helper.py | 26,27 | 10,34 | write_file | file_helper | 27,34 | 27,34 | class file_helper(object):
"""description of class"""
def __init__(self, output_file):
self.output_file = output_file
def check_directory(self):
directory = os.path.dirname(self.output_file)
if directory != '':
try:
os.stat(directory)
except:... | class file_helper(object):
"""description of class"""
def __init__(self, output_file):
self.output_file = output_file
def check_directory(self):
directory = os.path.dirname(self.output_file)
if directory != '':
try:
os.stat(directory)
except:... | # check if host directory exists, if not create it
self.check_directory()
with open(self.output_file, "w") as o:
o.write(contents)
| # check if host directory exists, if not create it
self.check_directory()
with open(self.output_file, "w") as o:
o.write(contents)
| 17 | 144 | 56 | 200 | import json
import os
from pkg_resources import resource_filename
DEFAULT_UA_LIST = resource_filename(
'VHostScan', 'lib/ua-random-list.txt')
class file_helper(object):
"""description of class"""
def __init__(self, output_file):
self.output_file = output_file
def check_directory(self):
... | import json
import os
from pkg_resources import resource_filename
DEFAULT_UA_LIST = resource_filename(
'VHostScan', 'lib/ua-random-list.txt')
class file_helper(object):
"""description of class"""
def __init__(self, output_file):
self.output_file = output_file
def check_directory(self):
... |
44,758 | /home/hieuvd/dung_repo/raw/stars_03/codingo_VHostScan/VHostScan | /home/hieuvd/dung_repo/raw/stars_03/codingo_VHostScan/VHostScan/VHostScan/lib/helpers/output_helper.py | 55,56 | 12,157 | output_json | output_helper | 56,88 | 56,88 | class output_helper(object):
def __init__(self, scanner, arguments):
self.scanner = scanner
self.arguments = arguments
def write_normal(self, filename):
file = file_helper(filename)
output = self.generate_header()
output += self.output_normal_likely()
if(self.a... | class output_helper(object):
def __init__(self, scanner, arguments):
self.scanner = scanner
self.arguments = arguments
def write_normal(self, filename):
file = file_helper(filename)
output = self.generate_header()
output += self.output_normal_likely()
if(self.a... | file = file_helper(filename)
output = dict()
output['Target'] = self.scanner.target
output['Base Host'] = self.scanner.base_host
output['Port'] = self.scanner.port
output['Real Port'] = self.scanner.real_port
output['Ignore HTTP Codes'] = self.scanner.ignore_http_... | file = file_helper(filename)
output = dict()
output['Target'] = self.scanner.target
output['Base Host'] = self.scanner.base_host
output['Port'] = self.scanner.port
output['Real Port'] = self.scanner.real_port
output['Ignore HTTP Codes'] = self.scanner.ignore_http_... | 80 | 995 | 374 | 1,369 | import itertools
import json
import time
import numpy as np
from fuzzywuzzy import fuzz
from ..core.discovered_host import *
from .file_helper import *
class output_helper(object):
def __init__(self, scanner, arguments):
self.scanner = scanner
self.arguments = arguments
def write_normal(sel... | import itertools
import json
import time
import numpy as np
from fuzzywuzzy import fuzz
from ..core.discovered_host import *
from .file_helper import *
class output_helper(object):
def __init__(self, scanner, arguments):
self.scanner = scanner
self.arguments = arguments
def write_normal(sel... |
44,759 | /home/hieuvd/dung_repo/raw/stars_03/codingo_VHostScan/VHostScan | /home/hieuvd/dung_repo/raw/stars_03/codingo_VHostScan/VHostScan/VHostScan/lib/helpers/wordlist_helper.py | 21,25 | 12,82 | get_wordlist | WordList | 25,73 | 25,73 | class WordList:
def __init__(self):
self.wordlist = []
self.wordlist_types = []
def get_stdin_wordlist(self):
return list(line for line in sys.stdin.read().splitlines()) \
if not sys.stdin.isatty() else []
def get_wordlist(self,
wordlist_files=None,... | class WordList:
def __init__(self):
self.wordlist = []
self.wordlist_types = []
def get_stdin_wordlist(self):
return list(line for line in sys.stdin.read().splitlines()) \
if not sys.stdin.isatty() else []
def get_wordlist(self,
wordlist_files=None,... |
default_wordlist_file = DEFAULT_WORDLIST_FILE
stdin_words = self.get_stdin_wordlist()
if stdin_words:
self.set_words(words_type='stdin', words=stdin_words)
default_wordlist_file = None
combined_files = wordlist_files or default_wordlist_file
combined = ... |
default_wordlist_file = DEFAULT_WORDLIST_FILE
stdin_words = self.get_stdin_wordlist()
if stdin_words:
self.set_words(words_type='stdin', words=stdin_words)
default_wordlist_file = None
combined_files = wordlist_files or default_wordlist_file
combined = ... | 104 | 206 | 477 | 683 | import sys
from ipaddress import ip_address
from pkg_resources import resource_filename
from .file_helper import get_combined_word_lists
DEFAULT_WORDLIST_FILE = resource_filename(
'VHostScan', 'wordlists/virtual-host-scanning.txt')
class WordList:
def __init__(self):
self.wordlist = []
self... | import sys
from ipaddress import ip_address
from pkg_resources import resource_filename
from .file_helper import get_combined_word_lists
DEFAULT_WORDLIST_FILE = resource_filename(
'VHostScan', 'wordlists/virtual-host-scanning.txt')
class WordList:
def __init__(self):
self.wordlist = []
self... |
44,760 | /home/hieuvd/dung_repo/raw/stars_03/codingo_VHostScan/VHostScan | /home/hieuvd/dung_repo/raw/stars_03/codingo_VHostScan/VHostScan/VHostScan/lib/input.py | 14,16 | 5,152 | setup_parser | cli_argument_parser | 17,152 | 16,152 | class cli_argument_parser(object):
""" __Doc__ append to parser class """
def __init__(self):
self._parser = self.setup_parser()
def parse(self, argv):
""" __Doc__ return parse function """
return self._parser.parse_args(argv)
@staticmethod
def setup_parser():
FILL_FUNC_BOD... | class cli_argument_parser(object):
""" __Doc__ append to parser class """
def __init__(self):
self._parser = self.setup_parser()
def parse(self, argv):
""" __Doc__ return parse function """
return self._parser.parse_args(argv)
@staticmethod
def setup_parser():
""" _... | parser = ArgumentParser()
parser.add_argument(
'-t', dest='target_hosts', required=True,
help='Set a target range of addresses to target. Ex 10.11.1.1-255'
),
parser.add_argument(
'-w', dest='wordlists',
help='Set the wordlists to use (de... | """ __Doc__ setup parse function """
parser = ArgumentParser()
parser.add_argument(
'-t', dest='target_hosts', required=True,
help='Set a target range of addresses to target. Ex 10.11.1.1-255'
),
parser.add_argument(
'-w', dest='wordlists',
... | 415 | 110 | 1,507 | 1,617 | """ __Doc__ Create parser linklist file """
from argparse import ArgumentParser
class cli_argument_parser(object):
""" __Doc__ append to parser class """
def __init__(self):
self._parser = self.setup_parser()
def parse(self, argv):
""" __Doc__ return parse function """
return self... | """ __Doc__ Create parser linklist file """
from argparse import ArgumentParser
class cli_argument_parser(object):
""" __Doc__ append to parser class """
def __init__(self):
self._parser = self.setup_parser()
def parse(self, argv):
""" __Doc__ return parse function """
return self... |
44,761 | /home/hieuvd/dung_repo/raw/stars_03/codingo_VHostScan/VHostScan | /home/hieuvd/dung_repo/raw/stars_03/codingo_VHostScan/VHostScan/setup.py | 6,7 | 1,42 | dependencies | 8,12 | 7,12 | """ __Doc__ File handle class """
from setuptools import find_packages, setup
from VHostScan.lib.core.__version__ import __version__
def dependencies(imported_file):
FILL_FUNC_BODYwith open("README.md") as file:
num_installed = False
try:
import numpy
num_installed = True
except ImportErro... | """ __Doc__ File handle class """
from setuptools import find_packages, setup
from VHostScan.lib.core.__version__ import __version__
def dependencies(imported_file):
""" __Doc__ Handles dependencies """
FILL_FUNC_BODYwith open("README.md") as file:
num_installed = False
try:
import numpy
n... | with open(imported_file) as file:
return file.read().splitlines()
| """ __Doc__ Handles dependencies """
with open(imported_file) as file:
return file.read().splitlines()
| 6 | 386 | 29 | 415 | """ __Doc__ File handle class """
from setuptools import find_packages, setup
from VHostScan.lib.core.__version__ import __version__
def dependencies(imported_file):
FILL_FUNC_BODYwith open("README.md") as file:
num_installed = False
try:
import numpy
num_installed = True
except ImportErro... | """ __Doc__ File handle class """
from setuptools import find_packages, setup
from VHostScan.lib.core.__version__ import __version__
def dependencies(imported_file):
""" __Doc__ Handles dependencies """
FILL_FUNC_BODYwith open("README.md") as file:
num_installed = False
try:
import numpy
n... | |
44,788 | /home/hieuvd/dung_repo/raw/stars_03/csurfer_pyheat/pyheat | /home/hieuvd/dung_repo/raw/stars_03/csurfer_pyheat/pyheat/pyheat/commandline.py | 31,32 | 1,53 | main | 33,51 | 32,51 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
pyheat as a command
~~~~~~~~~~~~~~~~~~
Usage:
>>> pyheat --help
usage: pyheat [-h] [-o OUT] pyfile
positional arguments:
pyfile Python file to be profiled
optional arguments:
-h, --help show this help message and exit
-o O... | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
pyheat as a command
~~~~~~~~~~~~~~~~~~
Usage:
>>> pyheat --help
usage: pyheat [-h] [-o OUT] pyfile
positional arguments:
pyfile Python file to be profiled
optional arguments:
-h, --help show this help message and exit
-o O... | # Create command line parser.
parser = argparse.ArgumentParser()
# Adding command line arguments.
parser.add_argument('-o', '--out', help='Output file', default=None)
parser.add_argument('pyfile', help='Python file to be profiled', default=None)
# Parse command line arguments.
arguments = pa... | """Starting point for the program execution."""
# Create command line parser.
parser = argparse.ArgumentParser()
# Adding command line arguments.
parser.add_argument('-o', '--out', help='Output file', default=None)
parser.add_argument('pyfile', help='Python file to be profiled', default=None)
... | 54 | 222 | 209 | 431 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
pyheat as a command
~~~~~~~~~~~~~~~~~~
Usage:
>>> pyheat --help
usage: pyheat [-h] [-o OUT] pyfile
positional arguments:
pyfile Python file to be profiled
optional arguments:
-h, --help show this help message and exit
-o O... | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
pyheat as a command
~~~~~~~~~~~~~~~~~~
Usage:
>>> pyheat --help
usage: pyheat [-h] [-o OUT] pyfile
positional arguments:
pyfile Python file to be profiled
optional arguments:
-h, --help show this help message and exit
-o O... | |
44,789 | /home/hieuvd/dung_repo/raw/stars_03/csurfer_pyheat/pyheat | /home/hieuvd/dung_repo/raw/stars_03/csurfer_pyheat/pyheat/pyheat/pyheat.py | 53,54 | 16,186 | show_heatmap | PyHeat | 62,79 | 54,79 | class PyHeat(object):
"""Class to display the python file provided as a heatmap highlighting the
most time consuming parts of the file.
"""
class FileDetails(object):
"""Class to keep track of useful file related details used in creating
heatmaps.
"""
def __init__(self,... | class PyHeat(object):
"""Class to display the python file provided as a heatmap highlighting the
most time consuming parts of the file.
"""
class FileDetails(object):
"""Class to keep track of useful file related details used in creating
heatmaps.
"""
def __init__(self,... | if output_file is None:
if enable_scroll:
# Add a new axes which will be used as scroll bar.
axpos = plt.axes([0.12, 0.1, 0.625, 0.03])
spos = Slider(axpos, 'Scroll', 10, len(self.pyfile.lines))
def update(val):
"""... | """Method to actually display the heatmap created.
@param blocking: When set to False makes an unblocking plot show.
@param output_file: If not None the heatmap image is output to this
file. Supported formats: (eps, pdf, pgf, png, ps, raw, rgba, svg,
svgz)
@param enable_... | 54 | 1,762 | 214 | 1,976 | # -*- coding: utf-8 -*-
"""
pyheat.pyheat
~~~~~~~~~~~
Class definitions to view python file as a heatmap highlighting
the most time consuming parts of the file.
"""
import matplotlib.pyplot as plt
import numpy as np
import pprofile
from matplotlib.widgets import Slider
class PyHeat(object):
"""Class to display ... | # -*- coding: utf-8 -*-
"""
pyheat.pyheat
~~~~~~~~~~~
Class definitions to view python file as a heatmap highlighting
the most time consuming parts of the file.
"""
import matplotlib.pyplot as plt
import numpy as np
import pprofile
from matplotlib.widgets import Slider
class PyHeat(object):
"""Class to display ... |
44,790 | /home/hieuvd/dung_repo/raw/stars_03/curvefi_curve-contract/curve-contract | /home/hieuvd/dung_repo/raw/stars_03/curvefi_curve-contract/curve-contract/brownie_hooks.py | 28,29 | 1,56 | brownie_load_source | 29,56 | 29,56 | """
Compile-time hook used to set `StableSwap` constants.
This file should not be modified directly. Values are set based on the
`pooldata.json` file within each template subdirectory.
"""
import json
def _load_pool_data(path):
with path.parent.joinpath('pooldata.json').open() as fp:
data = json.load(fp... | """
Compile-time hook used to set `StableSwap` constants.
This file should not be modified directly. Values are set based on the
`pooldata.json` file within each template subdirectory.
"""
import json
def _load_pool_data(path):
with path.parent.joinpath('pooldata.json').open() as fp:
data = json.load(fp... |
if "pool-templates" not in path.parts:
# compile-time substitution only applies to pool templates
return source
data_path = path.parent.joinpath('pooldata.json')
pool_data = _load_pool_data(data_path)
replacements = {
'___N_COINS___': pool_data['n_coins'],
'___PRECISIO... |
if "pool-templates" not in path.parts:
# compile-time substitution only applies to pool templates
return source
data_path = path.parent.joinpath('pooldata.json')
pool_data = _load_pool_data(data_path)
replacements = {
'___N_COINS___': pool_data['n_coins'],
'___PRECISIO... | 80 | 290 | 370 | 660 | """
Compile-time hook used to set `StableSwap` constants.
This file should not be modified directly. Values are set based on the
`pooldata.json` file within each template subdirectory.
"""
import json
def _load_pool_data(path):
with path.parent.joinpath('pooldata.json').open() as fp:
data = json.load(fp... | """
Compile-time hook used to set `StableSwap` constants.
This file should not be modified directly. Values are set based on the
`pooldata.json` file within each template subdirectory.
"""
import json
def _load_pool_data(path):
with path.parent.joinpath('pooldata.json').open() as fp:
data = json.load(fp... | |
44,791 | /home/hieuvd/dung_repo/raw/stars_03/damiafuentes_DJITelloPy/DJITelloPy | /home/hieuvd/dung_repo/raw/stars_03/damiafuentes_DJITelloPy/DJITelloPy/djitellopy/enforce_types.py | 25,26 | 1,66 | enforce_types | 28,66 | 26,66 | """
This file is based on a StackOverflow post by @301_Moved_Permanently.
See https://stackoverflow.com/a/50622643
The code was adapted to be able to wrap all methods of a class by simply
adding the decorator to the class itself.
"""
import inspect
import typing
from contextlib import suppress
from functools import w... | """
This file is based on a StackOverflow post by @301_Moved_Permanently.
See https://stackoverflow.com/a/50622643
The code was adapted to be able to wrap all methods of a class by simply
adding the decorator to the class itself.
"""
import inspect
import typing
from contextlib import suppress
from functools import w... | def check_types(spec, *args, **kwargs):
parameters = dict(zip(spec.args, args))
parameters.update(kwargs)
for name, value in parameters.items():
with suppress(KeyError): # Assume un-annotated parameters can be any type
type_hint = spec.annotations[name]
... | """Class decorator adding type checks to all member functions
"""
def check_types(spec, *args, **kwargs):
parameters = dict(zip(spec.args, args))
parameters.update(kwargs)
for name, value in parameters.items():
with suppress(KeyError): # Assume un-annotated parameters ca... | 109 | 242 | 433 | 675 | """
This file is based on a StackOverflow post by @301_Moved_Permanently.
See https://stackoverflow.com/a/50622643
The code was adapted to be able to wrap all methods of a class by simply
adding the decorator to the class itself.
"""
import inspect
import typing
from contextlib import suppress
from functools import w... | """
This file is based on a StackOverflow post by @301_Moved_Permanently.
See https://stackoverflow.com/a/50622643
The code was adapted to be able to wrap all methods of a class by simply
adding the decorator to the class itself.
"""
import inspect
import typing
from contextlib import suppress
from functools import w... | |
44,792 | /home/hieuvd/dung_repo/raw/stars_03/damiafuentes_DJITelloPy/DJITelloPy | /home/hieuvd/dung_repo/raw/stars_03/damiafuentes_DJITelloPy/DJITelloPy/djitellopy/swarm.py | 23,25 | 12,160 | fromFile | TelloSwarm | 30,35 | 25,35 | @enforce_types
class TelloSwarm:
"""Swarm library for controlling multiple Tellos simultaneously
"""
tellos: List[Tello]
barrier: Barrier
funcBarier: Barrier
funcQueues: List[Queue]
threads: List[Thread]
@staticmethod
def fromFile(path: str):
FILL_FUNC_BODY @staticmethod
def... | @enforce_types
class TelloSwarm:
"""Swarm library for controlling multiple Tellos simultaneously
"""
tellos: List[Tello]
barrier: Barrier
funcBarier: Barrier
funcQueues: List[Queue]
threads: List[Thread]
@staticmethod
def fromFile(path: str):
"""Create TelloSwarm from file.... | with open(path, 'r') as fd:
ips = fd.readlines()
return TelloSwarm.fromIps(ips)
| """Create TelloSwarm from file. The file should contain one IP address per line.
Arguments:
path: path to the file
"""
with open(path, 'r') as fd:
ips = fd.readlines()
return TelloSwarm.fromIps(ips)
| 10 | 1,178 | 46 | 1,224 | """Library for controlling multiple DJI Ryze Tello drones.
"""
from threading import Thread, Barrier
from queue import Queue
from typing import List, Callable
from .tello import Tello, TelloException
from .enforce_types import enforce_types
@enforce_types
class TelloSwarm:
"""Swarm library for controlling multi... | """Library for controlling multiple DJI Ryze Tello drones.
"""
from threading import Thread, Barrier
from queue import Queue
from typing import List, Callable
from .tello import Tello, TelloException
from .enforce_types import enforce_types
@enforce_types
class TelloSwarm:
"""Swarm library for controlling multi... |
44,793 | /home/hieuvd/dung_repo/raw/stars_03/damiafuentes_DJITelloPy/DJITelloPy | /home/hieuvd/dung_repo/raw/stars_03/damiafuentes_DJITelloPy/DJITelloPy/djitellopy/tello.py | 1065,1066 | 1034,1113 | update_frame | BackgroundFrameRead | 1069,1082 | 1066,1082 | class BackgroundFrameRead:
"""
This class read frames using PyAV in background. Use
backgroundFrameRead.frame to get the current frame.
"""
def __init__(self, tello, address, with_queue = False, maxsize = 32):
self.address = address
self.lock = Lock()
self.frame = np.zeros([... | class BackgroundFrameRead:
"""
This class read frames using PyAV in background. Use
backgroundFrameRead.frame to get the current frame.
"""
def __init__(self, tello, address, with_queue = False, maxsize = 32):
self.address = address
self.lock = Lock()
self.frame = np.zeros([... | try:
for frame in self.container.decode(video=0):
if self.with_queue:
self.frames.append(np.array(frame.to_image()))
else:
self.frame = np.array(frame.to_image())
if self.stopped:
self.contai... | """Thread worker function to retrieve frames using PyAV
Internal method, you normally wouldn't call this yourself.
"""
try:
for frame in self.container.decode(video=0):
if self.with_queue:
self.frames.append(np.array(frame.to_image()))
... | 35 | 592 | 143 | 735 | """Library for interacting with DJI Ryze Tello drones.
"""
# coding=utf-8
import logging
import socket
import time
from collections import deque
from threading import Thread, Lock
from typing import Optional, Union, Type, Dict
from .enforce_types import enforce_types
import av
import numpy as np
threads_initialize... | """Library for interacting with DJI Ryze Tello drones.
"""
# coding=utf-8
import logging
import socket
import time
from collections import deque
from threading import Thread, Lock
from typing import Optional, Union, Type, Dict
from .enforce_types import enforce_types
import av
import numpy as np
threads_initialize... |
44,806 | /home/hieuvd/dung_repo/raw/stars_03/defaultnamehere_zzzzz/zzzzz | /home/hieuvd/dung_repo/raw/stars_03/defaultnamehere_zzzzz/zzzzz/graph.py | 24,25 | 18,59 | to_csv | Grapher | 25,52 | 25,52 | class Grapher():
def __init__(self):
if not os.path.exists(CSV_OUTPUT_DIR):
os.makedirs(CSV_OUTPUT_DIR)
def to_csv(self, uid, start_time, end_time):
FILL_FUNC_BODY def generate_all_csvs(self, start_time, end_time):
for filename in os.listdir(LOG_DATA_DIR):
print(file... | class Grapher():
def __init__(self):
if not os.path.exists(CSV_OUTPUT_DIR):
os.makedirs(CSV_OUTPUT_DIR)
def to_csv(self, uid, start_time, end_time):
FILL_FUNC_BODY def generate_all_csvs(self, start_time, end_time):
for filename in os.listdir(LOG_DATA_DIR):
print(file... |
# The user's history.
status_history = history.StatusHistory(uid)
# Their Facebook username.
#uname = fbapi.get_user_name(uid)
# Generate a CSV from the multiple linear timeseries
with open("generated_graphs/csv/{uid}.csv".format(uid=uid), "w") as f:
f.wr... |
# The user's history.
status_history = history.StatusHistory(uid)
# Their Facebook username.
#uname = fbapi.get_user_name(uid)
# Generate a CSV from the multiple linear timeseries
with open("generated_graphs/csv/{uid}.csv".format(uid=uid), "w") as f:
f.wr... | 86 | 155 | 322 | 477 |
import datetime
import os
import history
import fbapi
import status
LOG_DATA_DIR = "log"
CSV_OUTPUT_DIR = "generated_graphs/csv"
# LOL TIMEZONES TOO HARD
UTC_OFFSET = 11
ONE_DAY_SECONDS = 60 * 60 * 24
class Grapher():
def __init__(self):
if not os.path.exists(CSV_OUTPUT_DIR):
os.makedirs... |
import datetime
import os
import history
import fbapi
import status
LOG_DATA_DIR = "log"
CSV_OUTPUT_DIR = "generated_graphs/csv"
# LOL TIMEZONES TOO HARD
UTC_OFFSET = 11
ONE_DAY_SECONDS = 60 * 60 * 24
class Grapher():
def __init__(self):
if not os.path.exists(CSV_OUTPUT_DIR):
os.makedirs... |
44,807 | /home/hieuvd/dung_repo/raw/stars_03/defaultnamehere_zzzzz/zzzzz | /home/hieuvd/dung_repo/raw/stars_03/defaultnamehere_zzzzz/zzzzz/history.py | 21,22 | 8,73 | create_time_map | StatusHistory | 22,27 | 22,27 | class StatusHistory():
"""Object representing the history for a particular user. History stored sparse."""
EPOCH_TIME = 1452556800
# Save the start time so computation time doesn't offset the measured time.
START_TIME = int(time.time())
def __init__(self, uid):
with open("log/{uid}.txt".... | class StatusHistory():
"""Object representing the history for a particular user. History stored sparse."""
EPOCH_TIME = 1452556800
# Save the start time so computation time doesn't offset the measured time.
START_TIME = int(time.time())
def __init__(self, uid):
with open("log/{uid}.txt".... | status_map = {}
for item in status_list:
status_map[int(float(item["time"]))] = item["status"]
return status_map
| status_map = {}
for item in status_list:
status_map[int(float(item["time"]))] = item["status"]
return status_map
| 12 | 708 | 49 | 757 |
import bisect
import time
import status
class StatusHistory():
"""Object representing the history for a particular user. History stored sparse."""
EPOCH_TIME = 1452556800
# Save the start time so computation time doesn't offset the measured time.
START_TIME = int(time.time())
def __init__(se... |
import bisect
import time
import status
class StatusHistory():
"""Object representing the history for a particular user. History stored sparse."""
EPOCH_TIME = 1452556800
# Save the start time so computation time doesn't offset the measured time.
START_TIME = int(time.time())
def __init__(se... |
44,808 | /home/hieuvd/dung_repo/raw/stars_03/defaultnamehere_zzzzz/zzzzz | /home/hieuvd/dung_repo/raw/stars_03/defaultnamehere_zzzzz/zzzzz/status.py | 47,48 | 10,69 | is_online | Status | 48,50 | 48,50 | class Status():
"""The status of a user."""
value_map = {
"offline": StatusLevel.OFFLINE,
"invisible": StatusLevel.INVISIBLE,
"idle": StatusLevel.IDLE,
"active": StatusLevel.ACTIVE
}
statuses = "status webStatus messengerStatus fbAppStatus otherStatus".split()
stat... | class Status():
"""The status of a user."""
value_map = {
"offline": StatusLevel.OFFLINE,
"invisible": StatusLevel.INVISIBLE,
"idle": StatusLevel.IDLE,
"active": StatusLevel.ACTIVE
}
statuses = "status webStatus messengerStatus fbAppStatus otherStatus".split()
stat... | return self._status["status"] == StatusLevel.ACTIVE
| return self._status["status"] == StatusLevel.ACTIVE
| 4 | 497 | 18 | 515 | import json
class StatusLevel():
OFFLINE = 0
INVISIBLE = 1
IDLE = 2
ACTIVE = 3
class Status():
"""The status of a user."""
value_map = {
"offline": StatusLevel.OFFLINE,
"invisible": StatusLevel.INVISIBLE,
"idle": StatusLevel.IDLE,
"active": StatusLevel.ACTIVE
... | import json
class StatusLevel():
OFFLINE = 0
INVISIBLE = 1
IDLE = 2
ACTIVE = 3
class Status():
"""The status of a user."""
value_map = {
"offline": StatusLevel.OFFLINE,
"invisible": StatusLevel.INVISIBLE,
"idle": StatusLevel.IDLE,
"active": StatusLevel.ACTIVE
... |
44,814 | /home/hieuvd/dung_repo/raw/stars_03/django-es_django-elasticsearch-dsl/django-elasticsearch-dsl | /home/hieuvd/dung_repo/raw/stars_03/django-es_django-elasticsearch-dsl/django-elasticsearch-dsl/django_elasticsearch_dsl/apps.py | 13,14 | 8,37 | ready | DEDConfig | 14,26 | 14,26 | class DEDConfig(AppConfig):
name = 'django_elasticsearch_dsl'
verbose_name = "Django elasticsearch-dsl"
signal_processor = None
def ready(self):
FILL_FUNC_BODY @classmethod
def autosync_enabled(cls):
return getattr(settings, 'ELASTICSEARCH_DSL_AUTOSYNC', True)
@classmethod
def d... | class DEDConfig(AppConfig):
name = 'django_elasticsearch_dsl'
verbose_name = "Django elasticsearch-dsl"
signal_processor = None
def ready(self):
FILL_FUNC_BODY @classmethod
def autosync_enabled(cls):
return getattr(settings, 'ELASTICSEARCH_DSL_AUTOSYNC', True)
@classmethod
def d... | self.module.autodiscover()
connections.configure(**settings.ELASTICSEARCH_DSL)
# Setup the signal processor.
if not self.signal_processor:
signal_processor_path = getattr(
settings,
'ELASTICSEARCH_DSL_SIGNAL_PROCESSOR',
'django_... | self.module.autodiscover()
connections.configure(**settings.ELASTICSEARCH_DSL)
# Setup the signal processor.
if not self.signal_processor:
signal_processor_path = getattr(
settings,
'ELASTICSEARCH_DSL_SIGNAL_PROCESSOR',
'django_... | 23 | 196 | 156 | 352 | from django.apps import AppConfig
from django.conf import settings
from django.utils.module_loading import import_string
from elasticsearch_dsl.connections import connections
class DEDConfig(AppConfig):
name = 'django_elasticsearch_dsl'
verbose_name = "Django elasticsearch-dsl"
signal_processor = None
... | from django.apps import AppConfig
from django.conf import settings
from django.utils.module_loading import import_string
from elasticsearch_dsl.connections import connections
class DEDConfig(AppConfig):
name = 'django_elasticsearch_dsl'
verbose_name = "Django elasticsearch-dsl"
signal_processor = None
... |
44,815 | /home/hieuvd/dung_repo/raw/stars_03/django-es_django-elasticsearch-dsl/django-elasticsearch-dsl | /home/hieuvd/dung_repo/raw/stars_03/django-es_django-elasticsearch-dsl/django-elasticsearch-dsl/django_elasticsearch_dsl/documents.py | 245,246 | 59,267 | update | DocType | 249,267 | 246,267 | class DocType(DSLDocument):
_prepared_fields = []
def __init__(self, related_instance_to_ignore=None, **kwargs):
super(DocType, self).__init__(**kwargs)
self._related_instance_to_ignore = related_instance_to_ignore
self._prepared_fields = self.init_prepare()
def __eq__(self, other)... | class DocType(DSLDocument):
_prepared_fields = []
def __init__(self, related_instance_to_ignore=None, **kwargs):
super(DocType, self).__init__(**kwargs)
self._related_instance_to_ignore = related_instance_to_ignore
self._prepared_fields = self.init_prepare()
def __eq__(self, other)... | if refresh is not None:
kwargs['refresh'] = refresh
elif self.django.auto_refresh:
kwargs['refresh'] = self.django.auto_refresh
if isinstance(thing, models.Model):
object_list = [thing]
else:
object_list = thing
return self._bulk(... | """
Update each document in ES for a model, iterable of models or queryset
"""
if refresh is not None:
kwargs['refresh'] = refresh
elif self.django.auto_refresh:
kwargs['refresh'] = self.django.auto_refresh
if isinstance(thing, models.Model):
... | 40 | 1,878 | 156 | 2,034 | from __future__ import unicode_literals
from collections import deque
from fnmatch import fnmatch
from functools import partial
from django import VERSION as DJANGO_VERSION
from django.db import models
from elasticsearch.helpers import bulk, parallel_bulk
from elasticsearch_dsl import Document as DSLDocument
from six... | from __future__ import unicode_literals
from collections import deque
from fnmatch import fnmatch
from functools import partial
from django import VERSION as DJANGO_VERSION
from django.db import models
from elasticsearch.helpers import bulk, parallel_bulk
from elasticsearch_dsl import Document as DSLDocument
from six... |
44,816 | /home/hieuvd/dung_repo/raw/stars_03/django-es_django-elasticsearch-dsl/django-elasticsearch-dsl | /home/hieuvd/dung_repo/raw/stars_03/django-es_django-elasticsearch-dsl/django-elasticsearch-dsl/django_elasticsearch_dsl/indices.py | 17,18 | 10,29 | document | Index | 21,25 | 18,25 | @python_2_unicode_compatible
class Index(DSLIndex):
def __init__(self, *args, **kwargs):
super(Index, self).__init__(*args, **kwargs)
default_index_settings = deepcopy(DEDConfig.default_index_settings())
self.settings(**default_index_settings)
def document(self, document):
FILL_FUNC_BOD... | @python_2_unicode_compatible
class Index(DSLIndex):
def __init__(self, *args, **kwargs):
super(Index, self).__init__(*args, **kwargs)
default_index_settings = deepcopy(DEDConfig.default_index_settings())
self.settings(**default_index_settings)
def document(self, document):
"""
... | document = super(Index, self).document(document)
registry.register_document(document)
return document
| """
Extend to register the document in the global document registry
"""
document = super(Index, self).document(document)
registry.register_document(document)
return document
| 7 | 144 | 33 | 177 | from copy import deepcopy
from elasticsearch_dsl import Index as DSLIndex
from six import python_2_unicode_compatible
from .apps import DEDConfig
from .registries import registry
@python_2_unicode_compatible
class Index(DSLIndex):
def __init__(self, *args, **kwargs):
super(Index, self).__init__(*args, *... | from copy import deepcopy
from elasticsearch_dsl import Index as DSLIndex
from six import python_2_unicode_compatible
from .apps import DEDConfig
from .registries import registry
@python_2_unicode_compatible
class Index(DSLIndex):
def __init__(self, *args, **kwargs):
super(Index, self).__init__(*args, *... |
44,818 | /home/hieuvd/dung_repo/raw/stars_03/django-es_django-elasticsearch-dsl/django-elasticsearch-dsl | /home/hieuvd/dung_repo/raw/stars_03/django-es_django-elasticsearch-dsl/django-elasticsearch-dsl/django_elasticsearch_dsl/registries.py | 96,97 | 15,184 | update_related | DocumentRegistry | 100,113 | 97,113 | class DocumentRegistry(object):
"""
Registry of models classes to a set of Document classes.
"""
def __init__(self):
self._indices = defaultdict(set)
self._models = defaultdict(set)
self._related_models = defaultdict(set)
def register(self, index, doc_class):
"""Regi... | class DocumentRegistry(object):
"""
Registry of models classes to a set of Document classes.
"""
def __init__(self):
self._indices = defaultdict(set)
self._models = defaultdict(set)
self._related_models = defaultdict(set)
def register(self, index, doc_class):
"""Regi... | if not DEDConfig.autosync_enabled():
return
for doc in self._get_related_doc(instance):
doc_instance = doc()
try:
related = doc_instance.get_instances_from_related(instance)
except ObjectDoesNotExist:
related = None
... | """
Update docs that have related_models.
"""
if not DEDConfig.autosync_enabled():
return
for doc in self._get_related_doc(instance):
doc_instance = doc()
try:
related = doc_instance.get_instances_from_related(instance)
... | 27 | 1,549 | 114 | 1,663 | from collections import defaultdict
from copy import deepcopy
from itertools import chain
from django.core.exceptions import ObjectDoesNotExist
from django.core.exceptions import ImproperlyConfigured
from elasticsearch_dsl import AttrDict
from six import itervalues, iterkeys, iteritems
from django_elasticsearch_dsl.... | from collections import defaultdict
from copy import deepcopy
from itertools import chain
from django.core.exceptions import ObjectDoesNotExist
from django.core.exceptions import ImproperlyConfigured
from elasticsearch_dsl import AttrDict
from six import itervalues, iterkeys, iteritems
from django_elasticsearch_dsl.... |
44,819 | /home/hieuvd/dung_repo/raw/stars_03/django-es_django-elasticsearch-dsl/django-elasticsearch-dsl | /home/hieuvd/dung_repo/raw/stars_03/django-es_django-elasticsearch-dsl/django-elasticsearch-dsl/django_elasticsearch_dsl/search.py | 17,18 | 7,60 | filter_queryset | Search | 22,47 | 18,47 | class Search(DSLSearch):
def __init__(self, **kwargs):
self._model = kwargs.pop('model', None)
super(Search, self).__init__(**kwargs)
def _clone(self):
s = super(Search, self)._clone()
s._model = self._model
return s
def filter_queryset(self, queryset, keep_search_o... | class Search(DSLSearch):
def __init__(self, **kwargs):
self._model = kwargs.pop('model', None)
super(Search, self).__init__(**kwargs)
def _clone(self):
s = super(Search, self)._clone()
s._model = self._model
return s
def filter_queryset(self, queryset, keep_search_o... | s = self
if s._model is not queryset.model:
raise TypeError(
'Unexpected queryset model '
'(should be: %s, got: %s)' % (s._model, queryset.model)
)
# Do not query again if the es result is already cached
if not hasattr(self, '_resp... | """
Filter an existing django queryset using the elasticsearch result.
It costs a query to the sql db.
"""
s = self
if s._model is not queryset.model:
raise TypeError(
'Unexpected queryset model '
'(should be: %s, got: %s)' % (s... | 85 | 278 | 275 | 553 | from django.db.models import Case, When
from django.db.models.fields import IntegerField
from elasticsearch_dsl import Search as DSLSearch
class Search(DSLSearch):
def __init__(self, **kwargs):
self._model = kwargs.pop('model', None)
super(Search, self).__init__(**kwargs)
def _clone(self):
... | from django.db.models import Case, When
from django.db.models.fields import IntegerField
from elasticsearch_dsl import Search as DSLSearch
class Search(DSLSearch):
def __init__(self, **kwargs):
self._model = kwargs.pop('model', None)
super(Search, self).__init__(**kwargs)
def _clone(self):
... |
45,020 | /home/hieuvd/dung_repo/raw/stars_03/edtechre_pybroker/pybroker | /home/hieuvd/dung_repo/raw/stars_03/edtechre_pybroker/pybroker/src/pybroker/context.py | 455,458 | 415,519 | signals | PosSizeContext | 458,512 | 458,512 | class PosSizeContext(BaseContext):
r"""Holds data for a position size handler set with
:meth:`pybroker.Strategy.set_pos_size_handler`. Used to set position sizes
when placing orders from buy and sell signals.
Attributes:
sessions: ``dict`` used to store custom data for all symbols.
"""
... | class PosSizeContext(BaseContext):
r"""Holds data for a position size handler set with
:meth:`pybroker.Strategy.set_pos_size_handler`. Used to set position sizes
when placing orders from buy and sell signals.
Attributes:
sessions: ``dict`` used to store custom data for all symbols.
"""
... | r"""Returns :class:`Iterator` of :class:`.ExecSignal`\ s containing
data for buy and sell signals.
"""
if signal_type is not None:
if signal_type != "buy" and signal_type != "sell":
raise ValueError(f"Unknown signal_type: {signal_type!r}.")
if (
... | r"""Returns :class:`Iterator` of :class:`.ExecSignal`\ s containing
data for buy and sell signals.
"""
if signal_type is not None:
if signal_type != "buy" and signal_type != "sell":
raise ValueError(f"Unknown signal_type: {signal_type!r}.")
if (
... | 162 | 528 | 618 | 1,146 | """Contains context related classes. A context provides data during the
execution of a :class:`pybroker.strategy.Strategy`."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
import numpy as np
import pandas as ... | """Contains context related classes. A context provides data during the
execution of a :class:`pybroker.strategy.Strategy`."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
import numpy as np
import pandas as ... |
45,022 | /home/hieuvd/dung_repo/raw/stars_03/edtechre_pybroker/pybroker | /home/hieuvd/dung_repo/raw/stars_03/edtechre_pybroker/pybroker/src/pybroker/data.py | 334,342 | 314,387 | _fetch_data | Alpaca | 343,387 | 342,387 | class Alpaca(DataSource):
"""Retrieves stock data from `Alpaca <https://alpaca.markets/>`_."""
__EST: Final = "US/Eastern"
def __init__(self, api_key: str, api_secret: str):
super().__init__()
self._api = alpaca_stock.StockHistoricalDataClient(api_key, api_secret)
def query(
s... | class Alpaca(DataSource):
"""Retrieves stock data from `Alpaca <https://alpaca.markets/>`_."""
__EST: Final = "US/Eastern"
def __init__(self, api_key: str, api_secret: str):
super().__init__()
self._api = alpaca_stock.StockHistoricalDataClient(api_key, api_secret)
def query(
s... | amount, unit = _parse_alpaca_timeframe(timeframe)
adj_enum = None
if adjust is not None:
for member in Adjustment:
if member.value == adjust:
adj_enum = member
break
if adj_enum is None:
raise ValueEr... | """:meta private:"""
amount, unit = _parse_alpaca_timeframe(timeframe)
adj_enum = None
if adjust is not None:
for member in Adjustment:
if member.value == adjust:
adj_enum = member
break
if adj_enum is None:
... | 92 | 312 | 473 | 785 | r"""Contains :class:`.DataSource`\ s used to fetch external data."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
import alpaca.data.historical.stock as alpaca_stock
import alpaca.data.historical.crypto as al... | r"""Contains :class:`.DataSource`\ s used to fetch external data."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
import alpaca.data.historical.stock as alpaca_stock
import alpaca.data.historical.crypto as al... |
45,023 | /home/hieuvd/dung_repo/raw/stars_03/edtechre_pybroker/pybroker | /home/hieuvd/dung_repo/raw/stars_03/edtechre_pybroker/pybroker/src/pybroker/data.py | 428,436 | 387,460 | _fetch_data | AlpacaCrypto | 437,460 | 436,460 | class AlpacaCrypto(DataSource):
"""Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_.
Args:
api_key: Alpaca API key.
api_secret: Alpaca API secret.
"""
TRADE_COUNT: Final = "trade_count"
COLUMNS: Final = (
DataCol.SYMBOL.value,
DataCol.DATE.value,
... | class AlpacaCrypto(DataSource):
"""Retrieves crypto data from `Alpaca <https://alpaca.markets/>`_.
Args:
api_key: Alpaca API key.
api_secret: Alpaca API secret.
"""
TRADE_COUNT: Final = "trade_count"
COLUMNS: Final = (
DataCol.SYMBOL.value,
DataCol.DATE.value,
... | amount, unit = _parse_alpaca_timeframe(timeframe)
request = CryptoBarsRequest(
symbol_or_symbols=list(symbols),
start=start_date,
end=end_date,
timeframe=TimeFrame(amount, unit),
limit=None,
)
df = self._api.get_crypto_bars(requ... | """:meta private:"""
amount, unit = _parse_alpaca_timeframe(timeframe)
request = CryptoBarsRequest(
symbol_or_symbols=list(symbols),
start=start_date,
end=end_date,
timeframe=TimeFrame(amount, unit),
limit=None,
)
df = s... | 51 | 495 | 288 | 783 | r"""Contains :class:`.DataSource`\ s used to fetch external data."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
import alpaca.data.historical.stock as alpaca_stock
import alpaca.data.historical.crypto as al... | r"""Contains :class:`.DataSource`\ s used to fetch external data."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
import alpaca.data.historical.stock as alpaca_stock
import alpaca.data.historical.crypto as al... |
45,024 | /home/hieuvd/dung_repo/raw/stars_03/edtechre_pybroker/pybroker | /home/hieuvd/dung_repo/raw/stars_03/edtechre_pybroker/pybroker/src/pybroker/data.py | 169,177 | 158,292 | query | DataSource | 200,248 | 177,248 | class DataSource(ABC, DataSourceCacheMixin):
"""Base class for querying data from an external source. Extend this class
and override :meth:`._fetch_data` to implement a custom
:class:`.DataSource` that can be used with
:class:`pybroker.strategy.Strategy`.
"""
def __init__(self):
self._s... | class DataSource(ABC, DataSourceCacheMixin):
"""Base class for querying data from an external source. Extend this class
and override :meth:`._fetch_data` to implement a custom
:class:`.DataSource` that can be used with
:class:`pybroker.strategy.Strategy`.
"""
def __init__(self):
self._s... | start_date = to_datetime(start_date)
end_date = to_datetime(end_date)
verify_date_range(start_date, end_date)
if isinstance(symbols, str) and not symbols:
raise ValueError("Symbols cannot be empty.")
unique_syms = (
frozenset((symbols,))
if isi... | """Queries data. Cached data is returned if caching is enabled by
calling :meth:`pybroker.cache.enable_data_source_cache`.
Args:
symbols: Symbols of the data to query.
start_date: Start date of the data to query (inclusive).
end_date: End date of the data to ... | 112 | 904 | 610 | 1,514 | r"""Contains :class:`.DataSource`\ s used to fetch external data."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
import alpaca.data.historical.stock as alpaca_stock
import alpaca.data.historical.crypto as al... | r"""Contains :class:`.DataSource`\ s used to fetch external data."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
import alpaca.data.historical.stock as alpaca_stock
import alpaca.data.historical.crypto as al... |
45,025 | /home/hieuvd/dung_repo/raw/stars_03/edtechre_pybroker/pybroker | /home/hieuvd/dung_repo/raw/stars_03/edtechre_pybroker/pybroker/src/pybroker/data.py | 108,116 | 33,158 | set_cached | DataSourceCacheMixin | 136,158 | 116,158 | class DataSourceCacheMixin:
"""Mixin that implements fetching and storing cached :class:`.DataSource`
data.
"""
def get_cached(
self,
symbols: Iterable[str],
timeframe: str,
start_date: Union[str, datetime, pd.Timestamp, np.datetime64],
end_date: Union[str, datet... | class DataSourceCacheMixin:
"""Mixin that implements fetching and storing cached :class:`.DataSource`
data.
"""
def get_cached(
self,
symbols: Iterable[str],
timeframe: str,
start_date: Union[str, datetime, pd.Timestamp, np.datetime64],
end_date: Union[str, datet... | if data.empty:
return
scope = StaticScope.instance()
cache = scope.data_source_cache
if cache is None:
return
start_date = to_datetime(start_date)
end_date = to_datetime(end_date)
tf_seconds = to_seconds(timeframe)
for sym in data[D... | """Stores data to disk cache when caching is enabled with
:meth:`pybroker.cache.enable_data_source_cache`.
Args:
timeframe: Formatted string that specifies the timeframe
resolution of the data to cache. The timeframe string supports
the following unit... | 44 | 1,127 | 238 | 1,365 | r"""Contains :class:`.DataSource`\ s used to fetch external data."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
import alpaca.data.historical.stock as alpaca_stock
import alpaca.data.historical.crypto as al... | r"""Contains :class:`.DataSource`\ s used to fetch external data."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
import alpaca.data.historical.stock as alpaca_stock
import alpaca.data.historical.crypto as al... |
45,026 | /home/hieuvd/dung_repo/raw/stars_03/edtechre_pybroker/pybroker | /home/hieuvd/dung_repo/raw/stars_03/edtechre_pybroker/pybroker/src/pybroker/data.py | 497,505 | 460,551 | _fetch_data | YFinance | 506,551 | 505,551 | class YFinance(DataSource):
r"""Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_\ .
Attributes:
ADJ_CLOSE: Column name of adjusted close prices.
"""
ADJ_CLOSE: Final = "adj_close"
__TIMEFRAME: Final = "1d"
def __init__(self):
super().__init__()
self._s... | class YFinance(DataSource):
r"""Retrieves data from `Yahoo Finance <https://finance.yahoo.com/>`_\ .
Attributes:
ADJ_CLOSE: Column name of adjusted close prices.
"""
ADJ_CLOSE: Final = "adj_close"
__TIMEFRAME: Final = "1d"
def __init__(self):
super().__init__()
self._s... | df = yfinance.download(list(symbols), start=start_date, end=end_date)
if df.columns.empty:
return pd.DataFrame(
columns=[
DataCol.SYMBOL.value,
DataCol.DATE.value,
DataCol.OPEN.value,
DataCol.HIGH... | """:meta private:"""
df = yfinance.download(list(symbols), start=start_date, end=end_date)
if df.columns.empty:
return pd.DataFrame(
columns=[
DataCol.SYMBOL.value,
DataCol.DATE.value,
DataCol.OPEN.value,
... | 115 | 457 | 669 | 1,126 | r"""Contains :class:`.DataSource`\ s used to fetch external data."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
import alpaca.data.historical.stock as alpaca_stock
import alpaca.data.historical.crypto as al... | r"""Contains :class:`.DataSource`\ s used to fetch external data."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
import alpaca.data.historical.stock as alpaca_stock
import alpaca.data.historical.crypto as al... |
45,029 | /home/hieuvd/dung_repo/raw/stars_03/edtechre_pybroker/pybroker | /home/hieuvd/dung_repo/raw/stars_03/edtechre_pybroker/pybroker/src/pybroker/ext/data.py | 28,36 | 19,94 | _fetch_data | AKShare | 37,94 | 36,94 | class AKShare(DataSource):
r"""Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_."""
_tf_to_period = {
"": "daily",
"1day": "daily",
"1week": "weekly",
}
def _fetch_data(
self,
symbols: frozenset[str],
start_date: datetime,
end_date:... | class AKShare(DataSource):
r"""Retrieves data from `AKShare <https://akshare.akfamily.xyz/>`_."""
_tf_to_period = {
"": "daily",
"1day": "daily",
"1week": "weekly",
}
def _fetch_data(
self,
symbols: frozenset[str],
start_date: datetime,
end_date:... | start_date_str = to_datetime(start_date).strftime("%Y%m%d")
end_date_str = to_datetime(end_date).strftime("%Y%m%d")
symbols_list = list(symbols)
symbols_simple = [item.split(".")[0] for item in symbols_list]
result = pd.DataFrame()
formatted_tf = self._format_timeframe(ti... | """:meta private:"""
start_date_str = to_datetime(start_date).strftime("%Y%m%d")
end_date_str = to_datetime(end_date).strftime("%Y%m%d")
symbols_list = list(symbols)
symbols_simple = [item.split(".")[0] for item in symbols_list]
result = pd.DataFrame()
formatted_t... | 113 | 163 | 674 | 837 | r"""Contains extension classes."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
from datetime import datetime
from typing import Optional
import akshare
import pandas as pd
from pybroker.common import DataC... | r"""Contains extension classes."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
from datetime import datetime
from typing import Optional
import akshare
import pandas as pd
from pybroker.common import DataC... |
45,033 | /home/hieuvd/dung_repo/raw/stars_03/edtechre_pybroker/pybroker | /home/hieuvd/dung_repo/raw/stars_03/edtechre_pybroker/pybroker/src/pybroker/slippage.py | 47,53 | 29,59 | apply_slippage | RandomSlippageModel | 53,59 | 53,59 | class RandomSlippageModel(SlippageModel):
"""Implements a simple random slippage model.
Args:
min_pct: Min percentage of slippage.
max_pct: Max percentage of slippage.
"""
def __init__(self, min_pct: float, max_pct: float):
if min_pct < 0 or min_pct > 100:
raise Val... | class RandomSlippageModel(SlippageModel):
"""Implements a simple random slippage model.
Args:
min_pct: Min percentage of slippage.
max_pct: Max percentage of slippage.
"""
def __init__(self, min_pct: float, max_pct: float):
if min_pct < 0 or min_pct > 100:
raise Val... | if buy_shares or sell_shares:
slippage_pct = Decimal(random.uniform(self.min_pct, self.max_pct))
if buy_shares:
ctx.buy_shares = buy_shares - slippage_pct * buy_shares
if sell_shares:
ctx.sell_shares = sell_shares - slippage_pct * sell_shares
| if buy_shares or sell_shares:
slippage_pct = Decimal(random.uniform(self.min_pct, self.max_pct))
if buy_shares:
ctx.buy_shares = buy_shares - slippage_pct * buy_shares
if sell_shares:
ctx.sell_shares = sell_shares - slippage_pct * sell_shares
| 26 | 307 | 114 | 421 | """Implements slippage models."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
import random
from pybroker.context import ExecContext
from abc import ABC, abstractmethod
from decimal import Decimal
from typin... | """Implements slippage models."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
import random
from pybroker.context import ExecContext
from abc import ABC, abstractmethod
from decimal import Decimal
from typin... |
45,034 | /home/hieuvd/dung_repo/raw/stars_03/edtechre_pybroker/pybroker | /home/hieuvd/dung_repo/raw/stars_03/edtechre_pybroker/pybroker/src/pybroker/vect.py | 14,16 | 1,129 | _verify_input | 16,22 | 16,22 | """Contains vectorized utility functions."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
import numpy as np
from numba import njit
from numpy.typing import NDArray
@njit
def _verify_input(array: NDArray[np... | """Contains vectorized utility functions."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
import numpy as np
from numba import njit
from numpy.typing import NDArray
@njit
def _verify_input(array: NDArray[np... | if n <= 0:
raise ValueError("n needs to be >= 1.")
if n > len(array):
raise ValueError("n is greater than array length.")
| if n <= 0:
raise ValueError("n needs to be >= 1.")
if n > len(array):
raise ValueError("n is greater than array length.")
| 22 | 1,282 | 50 | 1,332 | """Contains vectorized utility functions."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
import numpy as np
from numba import njit
from numpy.typing import NDArray
@njit
def _verify_input(array: NDArray[np... | """Contains vectorized utility functions."""
"""Copyright (C) 2023 Edward West. All rights reserved.
This code is licensed under Apache 2.0 with Commons Clause license
(see LICENSE for details).
"""
import numpy as np
from numba import njit
from numpy.typing import NDArray
@njit
def _verify_input(array: NDArray[np... | |
45,088 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/hubconf.py | 75,76 | 1,144 | load_state_dict_from_url | 76,94 | 76,94 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from tqdm import tqdm
import torch
import hashlib
import os
import re
import shutil
import sys
import tempfile
try:
f... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from tqdm import tqdm
import torch
import hashlib
import os
import re
import shutil
import sys
import tempfile
try:
f... | r"""
function from https://pytorch.org/docs/stable/model_zoo.html
"""
if model_dir is None:
torch_home = os.path.expanduser(os.getenv('TORCH_HOME', '~/.torch'))
model_dir = os.getenv('TORCH_MODEL_ZOO', os.path.join(torch_home, 'models'))
if not os.path.exists(model_dir):
os.m... | r"""
function from https://pytorch.org/docs/stable/model_zoo.html
"""
if model_dir is None:
torch_home = os.path.expanduser(os.getenv('TORCH_HOME', '~/.torch'))
model_dir = os.getenv('TORCH_MODEL_ZOO', os.path.join(torch_home, 'models'))
if not os.path.exists(model_dir):
os.m... | 50 | 1,569 | 291 | 1,860 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from tqdm import tqdm
import torch
import hashlib
import os
import re
import shutil
import sys
import tempfile
try:
f... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from tqdm import tqdm
import torch
import hashlib
import os
import re
import shutil
import sys
import tempfile
try:
f... | |
45,090 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_evaluate/Res.py | 65,66 | 44,84 | forward | BasicBlock | 66,84 | 66,84 | class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(BasicBlock, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
if groups ... | class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(BasicBlock, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
if groups ... | identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return o... | identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return o... | 34 | 309 | 127 | 436 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
'''
Code from : https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
'''
import torch.nn as nn
... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
'''
Code from : https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
'''
import torch.nn as nn
... |
45,091 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_evaluate/Res.py | 104,105 | 84,127 | forward | Bottleneck | 105,127 | 105,127 | class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(Bottleneck, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
width = in... | class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(Bottleneck, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
width = in... | identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
identity = se... | identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
identity = se... | 43 | 314 | 165 | 479 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
'''
Code from : https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
'''
import torch.nn as nn
... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
'''
Code from : https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
'''
import torch.nn as nn
... |
45,092 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_evaluate/Res.py | 180,181 | 127,222 | _make_layer | ResNet | 181,204 | 181,204 | class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
groups=1, width_per_group=64, replace_stride_with_dilation=None,
norm_layer=None):
super(ResNet, self).__init__()
if norm_layer is None:
norm_layer = ... | class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
groups=1, width_per_group=64, replace_stride_with_dilation=None,
norm_layer=None):
super(ResNet, self).__init__()
if norm_layer is None:
norm_layer = ... | norm_layer = self._norm_layer
downsample = None
previous_dilation = self.dilation
if dilate:
self.dilation *= stride
stride = 1
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
conv1x1(sel... | norm_layer = self._norm_layer
downsample = None
previous_dilation = self.dilation
if dilate:
self.dilation *= stride
stride = 1
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
conv1x1(sel... | 68 | 1,065 | 288 | 1,353 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
'''
Code from : https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
'''
import torch.nn as nn
... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
'''
Code from : https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
'''
import torch.nn as nn
... |
45,093 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_evaluate/resnext_wsl.py | 38,39 | 1,84 | resnext101_32x8d_wsl | 45,50 | 39,50 |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Optional list of dependencies required by the package
'''
Code From : https://github.com/facebookresearch/WSL-Image... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Optional list of dependencies required by the package
'''
Code From : https://github.com/facebookresearch/WSL-Image... | kwargs['groups'] = 32
kwargs['width_per_group'] = 8
return _resnext('resnext101_32x8d', Bottleneck, [3, 4, 23, 3], True, progress, **kwargs)
| """Constructs a ResNeXt-101 32x8 model pre-trained on weakly-supervised data
and finetuned on ImageNet from Figure 5 in
`"Exploring the Limits of Weakly Supervised Pretraining" <https://arxiv.org/abs/1805.00932>`_
Args:
progress (bool): If True, displays a progress bar of the download to stderr.... | 16 | 1,287 | 77 | 1,364 |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Optional list of dependencies required by the package
'''
Code From : https://github.com/facebookresearch/WSL-Image... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Optional list of dependencies required by the package
'''
Code From : https://github.com/facebookresearch/WSL-Image... | |
45,094 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_evaluate/samplers.py | 85,86 | 1,101 | list_collate | 89,101 | 86,101 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | elem_type = type(batch[0])
if isinstance(batch[0], torch.Tensor):
return batch
elif elem_type.__module__ == 'numpy':
if elem_type.__name__ == 'ndarray':
return list_collate([torch.from_numpy(b) for b in batch])
elif isinstance(batch[0], Mapping):
return {key: list_col... | """
Collate into a list instead of a tensor to deal with variable-sized inputs
"""
elem_type = type(batch[0])
if isinstance(batch[0], torch.Tensor):
return batch
elif elem_type.__module__ == 'numpy':
if elem_type.__name__ == 'ndarray':
return list_collate([torch.from_... | 50 | 899 | 187 | 1,086 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | |
45,095 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_evaluate/samplers.py | 48,49 | 15,85 | shuffler | RASampler | 49,63 | 49,63 | class RASampler(torch.utils.data.Sampler):
"""
Batch Sampler with Repeated Augmentations (RA)
- dataset_len: original length of the dataset
- batch_size
- repetitions: instances per image
- len_factor: multiplicative factor for epoch size
"""
def __init__(self,dataset,num_replicas, rank... | class RASampler(torch.utils.data.Sampler):
"""
Batch Sampler with Repeated Augmentations (RA)
- dataset_len: original length of the dataset
- batch_size
- repetitions: instances per image
- len_factor: multiplicative factor for epoch size
"""
def __init__(self,dataset,num_replicas, rank... | if self.shuffle:
new_perm = lambda: iter(np.random.permutation(self.dataset_len))
else:
new_perm = lambda: iter(np.arange(self.dataset_len))
shuffle = new_perm()
while True:
try:
index = next(shuffle)
except StopIteration:
... | if self.shuffle:
new_perm = lambda: iter(np.random.permutation(self.dataset_len))
else:
new_perm = lambda: iter(np.arange(self.dataset_len))
shuffle = new_perm()
while True:
try:
index = next(shuffle)
except StopIteration:
... | 34 | 611 | 148 | 759 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... |
45,096 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_evaluate/transforms.py | 46,47 | 1,86 | get_transforms | 47,85 | 47,85 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
class Resize(transforms.Re... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
class Resize(transforms.Re... | mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
if backbone is not None and backbone in ['pnasnet5large', 'nasnetamobile']:
mean, std = [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]
transformations = {}
if 'train' in need:
if kind == 'torch':
transformations['train'] = transform... | mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
if backbone is not None and backbone in ['pnasnet5large', 'nasnetamobile']:
mean, std = [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]
transformations = {}
if 'train' in need:
if kind == 'torch':
transformations['train'] = transform... | 115 | 427 | 528 | 955 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
class Resize(transforms.Re... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
class Resize(transforms.Re... | |
45,097 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_evaluate/transforms.py | 23,25 | 12,46 | target_size | Resize | 25,32 | 25,32 | class Resize(transforms.Resize):
"""
Resize with a ``largest=False'' argument
allowing to resize to a common largest side without cropping
"""
def __init__(self, size, largest=False, **kwargs):
super().__init__(size, **kwargs)
self.largest = largest
@staticmethod
def targe... | class Resize(transforms.Resize):
"""
Resize with a ``largest=False'' argument
allowing to resize to a common largest side without cropping
"""
def __init__(self, size, largest=False, **kwargs):
super().__init__(size, **kwargs)
self.largest = largest
@staticmethod
def targe... | if h < w and largest:
w, h = size, int(size * h / w)
else:
w, h = int(size * w / h), size
size = (h, w)
return size
| if h < w and largest:
w, h = size, int(size * h / w)
else:
w, h = int(size * w / h), size
size = (h, w)
return size
| 31 | 231 | 65 | 296 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
class Resize(transforms.Re... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
class Resize(transforms.Re... |
45,099 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_extract/Res.py | 65,66 | 44,84 | forward | BasicBlock | 66,84 | 66,84 | class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(BasicBlock, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
if groups ... | class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(BasicBlock, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
if groups ... | identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return o... | identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return o... | 34 | 309 | 127 | 436 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
'''
Code from : https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
'''
import torch.nn as nn
... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
'''
Code from : https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
'''
import torch.nn as nn
... |
45,100 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_extract/Res.py | 104,105 | 84,127 | forward | Bottleneck | 105,127 | 105,127 | class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(Bottleneck, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
width = in... | class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(Bottleneck, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
width = in... | identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
identity = se... | identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
identity = se... | 43 | 314 | 165 | 479 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
'''
Code from : https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
'''
import torch.nn as nn
... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
'''
Code from : https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
'''
import torch.nn as nn
... |
45,101 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_extract/Res.py | 180,181 | 127,222 | _make_layer | ResNet | 181,204 | 181,204 | class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
groups=1, width_per_group=64, replace_stride_with_dilation=None,
norm_layer=None):
super(ResNet, self).__init__()
if norm_layer is None:
norm_layer = ... | class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
groups=1, width_per_group=64, replace_stride_with_dilation=None,
norm_layer=None):
super(ResNet, self).__init__()
if norm_layer is None:
norm_layer = ... | norm_layer = self._norm_layer
downsample = None
previous_dilation = self.dilation
if dilate:
self.dilation *= stride
stride = 1
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
conv1x1(sel... | norm_layer = self._norm_layer
downsample = None
previous_dilation = self.dilation
if dilate:
self.dilation *= stride
stride = 1
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
conv1x1(sel... | 68 | 1,070 | 288 | 1,358 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
'''
Code from : https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
'''
import torch.nn as nn
... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
'''
Code from : https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
'''
import torch.nn as nn
... |
45,102 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_extract/resnext_wsl.py | 31,32 | 1,84 | _resnext | 32,38 | 32,38 |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Optional list of dependencies required by the package
'''
Code From : https://github.com/facebookresearch/WSL-Image... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Optional list of dependencies required by the package
'''
Code From : https://github.com/facebookresearch/WSL-Image... | model = ResNet(block, layers, **kwargs)
state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)
model.load_state_dict(state_dict)
return model
| model = ResNet(block, layers, **kwargs)
state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)
model.load_state_dict(state_dict)
return model
| 12 | 1,298 | 67 | 1,365 |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Optional list of dependencies required by the package
'''
Code From : https://github.com/facebookresearch/WSL-Image... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Optional list of dependencies required by the package
'''
Code From : https://github.com/facebookresearch/WSL-Image... | |
45,103 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_extract/samplers.py | 85,86 | 1,101 | list_collate | 89,101 | 86,101 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | elem_type = type(batch[0])
if isinstance(batch[0], torch.Tensor):
return batch
elif elem_type.__module__ == 'numpy':
if elem_type.__name__ == 'ndarray':
return list_collate([torch.from_numpy(b) for b in batch])
elif isinstance(batch[0], Mapping):
return {key: list_col... | """
Collate into a list instead of a tensor to deal with variable-sized inputs
"""
elem_type = type(batch[0])
if isinstance(batch[0], torch.Tensor):
return batch
elif elem_type.__module__ == 'numpy':
if elem_type.__name__ == 'ndarray':
return list_collate([torch.from_... | 50 | 899 | 187 | 1,086 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | |
45,104 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_extract/samplers.py | 48,49 | 15,85 | shuffler | RASampler | 49,63 | 49,63 | class RASampler(torch.utils.data.Sampler):
"""
Batch Sampler with Repeated Augmentations (RA)
- dataset_len: original length of the dataset
- batch_size
- repetitions: instances per image
- len_factor: multiplicative factor for epoch size
"""
def __init__(self,dataset,num_replicas, rank... | class RASampler(torch.utils.data.Sampler):
"""
Batch Sampler with Repeated Augmentations (RA)
- dataset_len: original length of the dataset
- batch_size
- repetitions: instances per image
- len_factor: multiplicative factor for epoch size
"""
def __init__(self,dataset,num_replicas, rank... | if self.shuffle:
new_perm = lambda: iter(np.random.permutation(self.dataset_len))
else:
new_perm = lambda: iter(np.arange(self.dataset_len))
shuffle = new_perm()
while True:
try:
index = next(shuffle)
except StopIteration:
... | if self.shuffle:
new_perm = lambda: iter(np.random.permutation(self.dataset_len))
else:
new_perm = lambda: iter(np.arange(self.dataset_len))
shuffle = new_perm()
while True:
try:
index = next(shuffle)
except StopIteration:
... | 34 | 611 | 148 | 759 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... |
45,105 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_extract/transforms.py | 45,46 | 1,85 | get_transforms | 46,84 | 46,84 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
class Resize(transforms.Res... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
class Resize(transforms.Res... | mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
if backbone is not None and backbone in ['pnasnet5large', 'nasnetamobile']:
mean, std = [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]
transformations = {}
if 'train' in need:
if kind == 'torch':
transformations['train'] = transform... | mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
if backbone is not None and backbone in ['pnasnet5large', 'nasnetamobile']:
mean, std = [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]
transformations = {}
if 'train' in need:
if kind == 'torch':
transformations['train'] = transform... | 115 | 426 | 528 | 954 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
class Resize(transforms.Res... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
class Resize(transforms.Res... | |
45,106 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_extract/transforms.py | 22,24 | 11,45 | target_size | Resize | 24,31 | 24,31 | class Resize(transforms.Resize):
"""
Resize with a ``largest=False'' argument
allowing to resize to a common largest side without cropping
"""
def __init__(self, size, largest=False, **kwargs):
super().__init__(size, **kwargs)
self.largest = largest
@staticmethod
def targe... | class Resize(transforms.Resize):
"""
Resize with a ``largest=False'' argument
allowing to resize to a common largest side without cropping
"""
def __init__(self, size, largest=False, **kwargs):
super().__init__(size, **kwargs)
self.largest = largest
@staticmethod
def targe... | if h < w and largest:
w, h = size, int(size * h / w)
else:
w, h = int(size * w / h), size
size = (h, w)
return size
| if h < w and largest:
w, h = size, int(size * h / w)
else:
w, h = int(size * w / h), size
size = (h, w)
return size
| 31 | 231 | 65 | 296 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
class Resize(transforms.Res... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
class Resize(transforms.Res... |
45,108 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_finetune/Res.py | 62,63 | 41,81 | forward | BasicBlock | 63,81 | 63,81 | class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(BasicBlock, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
if groups ... | class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(BasicBlock, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
if groups ... | identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return o... | identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return o... | 34 | 309 | 127 | 436 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch.nn as nn
try:
from torch.hub import load_state_dict_from_url
except ImportError:
from torch.utils.mo... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch.nn as nn
try:
from torch.hub import load_state_dict_from_url
except ImportError:
from torch.utils.mo... |
45,109 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_finetune/Res.py | 101,102 | 81,124 | forward | Bottleneck | 102,124 | 102,124 | class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(Bottleneck, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
width = in... | class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, groups=1,
base_width=64, dilation=1, norm_layer=None):
super(Bottleneck, self).__init__()
if norm_layer is None:
norm_layer = nn.BatchNorm2d
width = in... | identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
identity = se... | identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
out = self.relu(out)
out = self.conv3(out)
out = self.bn3(out)
if self.downsample is not None:
identity = se... | 43 | 314 | 165 | 479 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch.nn as nn
try:
from torch.hub import load_state_dict_from_url
except ImportError:
from torch.utils.mo... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch.nn as nn
try:
from torch.hub import load_state_dict_from_url
except ImportError:
from torch.utils.mo... |
45,110 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_finetune/Res.py | 177,178 | 124,219 | _make_layer | ResNet | 178,201 | 178,201 | class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
groups=1, width_per_group=64, replace_stride_with_dilation=None,
norm_layer=None):
super(ResNet, self).__init__()
if norm_layer is None:
norm_layer = ... | class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False,
groups=1, width_per_group=64, replace_stride_with_dilation=None,
norm_layer=None):
super(ResNet, self).__init__()
if norm_layer is None:
norm_layer = ... | norm_layer = self._norm_layer
downsample = None
previous_dilation = self.dilation
if dilate:
self.dilation *= stride
stride = 1
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
conv1x1(sel... | norm_layer = self._norm_layer
downsample = None
previous_dilation = self.dilation
if dilate:
self.dilation *= stride
stride = 1
if stride != 1 or self.inplanes != planes * block.expansion:
downsample = nn.Sequential(
conv1x1(sel... | 68 | 1,065 | 288 | 1,353 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch.nn as nn
try:
from torch.hub import load_state_dict_from_url
except ImportError:
from torch.utils.mo... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch.nn as nn
try:
from torch.hub import load_state_dict_from_url
except ImportError:
from torch.utils.mo... |
45,111 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_finetune/resnext_wsl.py | 31,32 | 1,84 | _resnext | 32,38 | 32,38 |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Optional list of dependencies required by the package
'''
Code From : https://github.com/facebookresearch/WSL-Image... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Optional list of dependencies required by the package
'''
Code From : https://github.com/facebookresearch/WSL-Image... | model = ResNet(block, layers, **kwargs)
state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)
model.load_state_dict(state_dict)
return model
| model = ResNet(block, layers, **kwargs)
state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)
model.load_state_dict(state_dict)
return model
| 12 | 1,298 | 67 | 1,365 |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Optional list of dependencies required by the package
'''
Code From : https://github.com/facebookresearch/WSL-Image... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# Optional list of dependencies required by the package
'''
Code From : https://github.com/facebookresearch/WSL-Image... | |
45,112 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_finetune/samplers.py | 85,86 | 1,101 | list_collate | 89,101 | 86,101 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | elem_type = type(batch[0])
if isinstance(batch[0], torch.Tensor):
return batch
elif elem_type.__module__ == 'numpy':
if elem_type.__name__ == 'ndarray':
return list_collate([torch.from_numpy(b) for b in batch])
elif isinstance(batch[0], Mapping):
return {key: list_col... | """
Collate into a list instead of a tensor to deal with variable-sized inputs
"""
elem_type = type(batch[0])
if isinstance(batch[0], torch.Tensor):
return batch
elif elem_type.__module__ == 'numpy':
if elem_type.__name__ == 'ndarray':
return list_collate([torch.from_... | 50 | 899 | 187 | 1,086 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | |
45,113 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_finetune/samplers.py | 48,49 | 15,85 | shuffler | RASampler | 49,63 | 49,63 | class RASampler(torch.utils.data.Sampler):
"""
Batch Sampler with Repeated Augmentations (RA)
- dataset_len: original length of the dataset
- batch_size
- repetitions: instances per image
- len_factor: multiplicative factor for epoch size
"""
def __init__(self,dataset,num_replicas, rank... | class RASampler(torch.utils.data.Sampler):
"""
Batch Sampler with Repeated Augmentations (RA)
- dataset_len: original length of the dataset
- batch_size
- repetitions: instances per image
- len_factor: multiplicative factor for epoch size
"""
def __init__(self,dataset,num_replicas, rank... | if self.shuffle:
new_perm = lambda: iter(np.random.permutation(self.dataset_len))
else:
new_perm = lambda: iter(np.arange(self.dataset_len))
shuffle = new_perm()
while True:
try:
index = next(shuffle)
except StopIteration:
... | if self.shuffle:
new_perm = lambda: iter(np.random.permutation(self.dataset_len))
else:
new_perm = lambda: iter(np.arange(self.dataset_len))
shuffle = new_perm()
while True:
try:
index = next(shuffle)
except StopIteration:
... | 34 | 611 | 148 | 759 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... |
45,114 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_finetune/transforms.py | 46,47 | 1,86 | get_transforms | 47,85 | 47,85 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
import numpy as np
class R... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
import numpy as np
class R... | mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
if backbone is not None and backbone in ['pnasnet5large', 'nasnetamobile']:
mean, std = [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]
transformations = {}
if 'train' in need:
if kind == 'torch':
transformations['train'] = transform... | mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
if backbone is not None and backbone in ['pnasnet5large', 'nasnetamobile']:
mean, std = [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]
transformations = {}
if 'train' in need:
if kind == 'torch':
transformations['train'] = transform... | 115 | 432 | 529 | 961 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
import numpy as np
class R... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
import numpy as np
class R... | |
45,115 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_finetune/transforms.py | 24,26 | 13,46 | target_size | Resize | 26,33 | 26,33 | class Resize(transforms.Resize):
"""
Resize with a ``largest=False'' argument
allowing to resize to a common largest side without cropping
"""
def __init__(self, size, largest=False, **kwargs):
super().__init__(size, **kwargs)
self.largest = largest
@staticmethod
def targe... | class Resize(transforms.Resize):
"""
Resize with a ``largest=False'' argument
allowing to resize to a common largest side without cropping
"""
def __init__(self, size, largest=False, **kwargs):
super().__init__(size, **kwargs)
self.largest = largest
@staticmethod
def targe... | if h < w and largest:
w, h = size, int(size * h / w)
else:
w, h = int(size * w / h), size
size = (h, w)
return size
| if h < w and largest:
w, h = size, int(size * h / w)
else:
w, h = int(size * w / h), size
size = (h, w)
return size
| 31 | 230 | 65 | 295 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
import numpy as np
class R... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
import numpy as np
class R... |
45,116 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_resnet50_scratch/samplers.py | 85,86 | 1,101 | list_collate | 89,101 | 86,101 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | elem_type = type(batch[0])
if isinstance(batch[0], torch.Tensor):
return batch
elif elem_type.__module__ == 'numpy':
if elem_type.__name__ == 'ndarray':
return list_collate([torch.from_numpy(b) for b in batch])
elif isinstance(batch[0], Mapping):
return {key: list_col... | """
Collate into a list instead of a tensor to deal with variable-sized inputs
"""
elem_type = type(batch[0])
if isinstance(batch[0], torch.Tensor):
return batch
elif elem_type.__module__ == 'numpy':
if elem_type.__name__ == 'ndarray':
return list_collate([torch.from_... | 50 | 899 | 187 | 1,086 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | |
45,117 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_resnet50_scratch/samplers.py | 48,49 | 15,85 | shuffler | RASampler | 49,63 | 49,63 | class RASampler(torch.utils.data.Sampler):
"""
Batch Sampler with Repeated Augmentations (RA)
- dataset_len: original length of the dataset
- batch_size
- repetitions: instances per image
- len_factor: multiplicative factor for epoch size
"""
def __init__(self,dataset,num_replicas, rank... | class RASampler(torch.utils.data.Sampler):
"""
Batch Sampler with Repeated Augmentations (RA)
- dataset_len: original length of the dataset
- batch_size
- repetitions: instances per image
- len_factor: multiplicative factor for epoch size
"""
def __init__(self,dataset,num_replicas, rank... | if self.shuffle:
new_perm = lambda: iter(np.random.permutation(self.dataset_len))
else:
new_perm = lambda: iter(np.arange(self.dataset_len))
shuffle = new_perm()
while True:
try:
index = next(shuffle)
except StopIteration:
... | if self.shuffle:
new_perm = lambda: iter(np.random.permutation(self.dataset_len))
else:
new_perm = lambda: iter(np.arange(self.dataset_len))
shuffle = new_perm()
while True:
try:
index = next(shuffle)
except StopIteration:
... | 34 | 611 | 148 | 759 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
from torch.utils.data.sampler import BatchSampler
import torch
import numpy as np
from torch.utils.data.dataloader import ... |
45,118 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_resnet50_scratch/transforms.py | 48,49 | 1,88 | get_transforms | 49,87 | 49,87 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
import numpy as np
class ... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
import numpy as np
class ... | mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
if backbone is not None and backbone in ['pnasnet5large', 'nasnetamobile']:
mean, std = [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]
transformations = {}
if 'train' in need:
if kind == 'torch':
transformations['train'] = transform... | mean, std = [0.485, 0.456, 0.406], [0.229, 0.224, 0.225]
if backbone is not None and backbone in ['pnasnet5large', 'nasnetamobile']:
mean, std = [0.5, 0.5, 0.5], [0.5, 0.5, 0.5]
transformations = {}
if 'train' in need:
if kind == 'torch':
transformations['train'] = transform... | 107 | 434 | 512 | 946 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
import numpy as np
class ... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
import numpy as np
class ... | |
45,119 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/imnet_resnet50_scratch/transforms.py | 25,27 | 14,48 | target_size | Resize | 27,34 | 27,34 | class Resize(transforms.Resize):
"""
Resize with a ``largest=False'' argument
allowing to resize to a common largest side without cropping
"""
def __init__(self, size, largest=False, **kwargs):
super().__init__(size, **kwargs)
self.largest = largest
@staticmethod
def targe... | class Resize(transforms.Resize):
"""
Resize with a ``largest=False'' argument
allowing to resize to a common largest side without cropping
"""
def __init__(self, size, largest=False, **kwargs):
super().__init__(size, **kwargs)
self.largest = largest
@staticmethod
def targe... | if h < w and largest:
w, h = size, int(size * h / w)
else:
w, h = int(size * w / h), size
size = (h, w)
return size
| if h < w and largest:
w, h = size, int(size * h / w)
else:
w, h = int(size * w / h), size
size = (h, w)
return size
| 31 | 231 | 65 | 296 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
import numpy as np
class ... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
import numpy as np
class ... |
45,120 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/main_evaluate_imnet.py | 15,16 | 1,79 | run | 16,63 | 16,63 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import uuid
from pathlib import Path
from imnet_evaluate import TrainerConfig, ClusterConfig, Trainer
from argpa... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import uuid
from pathlib import Path
from imnet_evaluate import TrainerConfig, ClusterConfig, Trainer
from argpa... | cluster_cfg = ClusterConfig(dist_backend="nccl", dist_url="")
shared_folder=None
data_folder_Path=None
if Path(str(shared_folder_path)).is_dir():
shared_folder=Path(shared_folder_path+"/evaluate/")
else:
raise RuntimeError("No shared folder available")
if Path(str(imnet_path)).is... | cluster_cfg = ClusterConfig(dist_backend="nccl", dist_url="")
shared_folder=None
data_folder_Path=None
if Path(str(shared_folder_path)).is_dir():
shared_folder=Path(shared_folder_path+"/evaluate/")
else:
raise RuntimeError("No shared folder available")
if Path(str(imnet_path)).is... | 83 | 684 | 522 | 1,206 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import uuid
from pathlib import Path
from imnet_evaluate import TrainerConfig, ClusterConfig, Trainer
from argpa... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import uuid
from pathlib import Path
from imnet_evaluate import TrainerConfig, ClusterConfig, Trainer
from argpa... | |
45,121 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/main_evaluate_softmax.py | 11,12 | 1,37 | run | 12,30 | 12,30 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import numpy as np
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
def run(path,name,version):
FILL_F... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import numpy as np
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
def run(path,name,version):
FILL_F... | if version=='v1':
softmax=np.load(path+name+'_softmax.npy')
else:
softmax=np.load(path+name+'_softmax_v2.npy')
label=np.load(path+'labels.npy')
assert softmax.shape[0] == 50000,"Error ImageNet validation set doesn't match"
correct=0.0
for i in range(softmax.shape[0]):
... | if version=='v1':
softmax=np.load(path+name+'_softmax.npy')
else:
softmax=np.load(path+name+'_softmax_v2.npy')
label=np.load(path+'labels.npy')
assert softmax.shape[0] == 50000,"Error ImageNet validation set doesn't match"
correct=0.0
for i in range(softmax.shape[0]):
... | 30 | 334 | 220 | 554 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import numpy as np
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
def run(path,name,version):
FILL_F... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import numpy as np
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
def run(path,name,version):
FILL_F... | |
45,122 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/main_extract.py | 14,15 | 1,78 | run | 15,62 | 15,62 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import uuid
from pathlib import Path
from imnet_extract import TrainerConfig, ClusterConfig, Trainer
from argpar... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import uuid
from pathlib import Path
from imnet_extract import TrainerConfig, ClusterConfig, Trainer
from argpar... | shared_folder=None
data_folder_Path=None
if Path(str(shared_folder_path)).is_dir():
shared_folder=Path(shared_folder_path+"/extract/")
else:
raise RuntimeError("No shared folder available")
if Path(str(dataset_path)).is_dir():
data_folder_Path=Path(str(dataset_path))
else... | shared_folder=None
data_folder_Path=None
if Path(str(shared_folder_path)).is_dir():
shared_folder=Path(shared_folder_path+"/extract/")
else:
raise RuntimeError("No shared folder available")
if Path(str(dataset_path)).is_dir():
data_folder_Path=Path(str(dataset_path))
else... | 80 | 788 | 520 | 1,308 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import uuid
from pathlib import Path
from imnet_extract import TrainerConfig, ClusterConfig, Trainer
from argpar... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import uuid
from pathlib import Path
from imnet_extract import TrainerConfig, ClusterConfig, Trainer
from argpar... | |
45,123 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/main_finetune.py | 15,16 | 1,86 | run | 16,66 | 16,66 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import uuid
from pathlib import Path
from imnet_finetune import TrainerConfig, ClusterConfig, Trainer
from argpa... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import uuid
from pathlib import Path
from imnet_finetune import TrainerConfig, ClusterConfig, Trainer
from argpa... | cluster_cfg = ClusterConfig(dist_backend="nccl", dist_url="")
shared_folder=None
data_folder_Path=None
if Path(str(shared_folder_path)).is_dir():
shared_folder=Path(shared_folder_path+"/finetune/")
else:
raise RuntimeError("No shared folder available")
if Path(str(imnet_path)).is... | cluster_cfg = ClusterConfig(dist_backend="nccl", dist_url="")
shared_folder=None
data_folder_Path=None
if Path(str(shared_folder_path)).is_dir():
shared_folder=Path(shared_folder_path+"/finetune/")
else:
raise RuntimeError("No shared folder available")
if Path(str(imnet_path)).is... | 86 | 843 | 565 | 1,408 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import uuid
from pathlib import Path
from imnet_finetune import TrainerConfig, ClusterConfig, Trainer
from argpa... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import uuid
from pathlib import Path
from imnet_finetune import TrainerConfig, ClusterConfig, Trainer
from argpa... | |
45,124 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/main_resnet50_scratch.py | 14,15 | 1,77 | run | 15,61 | 15,61 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import uuid
from pathlib import Path
from imnet_resnet50_scratch import TrainerConfig, ClusterConfig, Trainer
fr... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import uuid
from pathlib import Path
from imnet_resnet50_scratch import TrainerConfig, ClusterConfig, Trainer
fr... | cluster_cfg = ClusterConfig(dist_backend="nccl", dist_url="")
shared_folder=None
data_folder_Path=None
if Path(str(shared_folder_path)).is_dir():
shared_folder=Path(shared_folder_path+"/training/")
else:
raise RuntimeError("No shared folder available")
if Path(str(imnet_path)).is... | cluster_cfg = ClusterConfig(dist_backend="nccl", dist_url="")
shared_folder=None
data_folder_Path=None
if Path(str(shared_folder_path)).is_dir():
shared_folder=Path(shared_folder_path+"/training/")
else:
raise RuntimeError("No shared folder available")
if Path(str(imnet_path)).is... | 83 | 668 | 522 | 1,190 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import uuid
from pathlib import Path
from imnet_resnet50_scratch import TrainerConfig, ClusterConfig, Trainer
fr... | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import os
import uuid
from pathlib import Path
from imnet_resnet50_scratch import TrainerConfig, ClusterConfig, Trainer
fr... | |
45,126 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_FixRes/FixRes/transforms_v2.py | 106,108 | 95,126 | target_size | Resize | 108,115 | 108,115 | class Resize(transforms.Resize):
"""
Resize with a ``largest=False'' argument
allowing to resize to a common largest side without cropping
"""
def __init__(self, size, largest=False, **kwargs):
super().__init__(size, **kwargs)
self.largest = largest
@staticmethod
def targe... | class Resize(transforms.Resize):
"""
Resize with a ``largest=False'' argument
allowing to resize to a common largest side without cropping
"""
def __init__(self, size, largest=False, **kwargs):
super().__init__(size, **kwargs)
self.largest = largest
@staticmethod
def targe... | if h < w and largest:
w, h = size, int(size * h / w)
else:
w, h = int(size * w / h), size
size = (h, w)
return size
| if h < w and largest:
w, h = size, int(size * h / w)
else:
w, h = int(size * w / h), size
size = (h, w)
return size
| 31 | 228 | 65 | 293 |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
import torch
import math
im... |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
import torch
import torchvision.transforms.functional as F
from torchvision import transforms
import torch
import math
im... |
45,186 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/albef/model.py | 129,136 | 70,148 | forward | ALBEFDecoder | 136,148 | 136,148 | class ALBEFDecoder(nn.Module):
"""
Generate the prediction scores for answers from image and question hidden states.
Args:
text_embeddings (ALBEFTextEmbeddings): Instantiated ALBEFTextEmbeddings.
multimodal_encoder (ALBEFMultimodalEncoder): Instantiated ALBEFMultimodalEncoder.
predi... | class ALBEFDecoder(nn.Module):
"""
Generate the prediction scores for answers from image and question hidden states.
Args:
text_embeddings (ALBEFTextEmbeddings): Instantiated ALBEFTextEmbeddings.
multimodal_encoder (ALBEFMultimodalEncoder): Instantiated ALBEFMultimodalEncoder.
predi... | hidden_states = self.text_embeddings(input_ids)
attention_mask = self.get_extended_attention_mask_for_decoder(attention_mask)
decoder_output = self.multimodal_encoder(
hidden_states=hidden_states,
attention_mask=attention_mask,
encoder_hidden_states=encoder_hi... | hidden_states = self.text_embeddings(input_ids)
attention_mask = self.get_extended_attention_mask_for_decoder(attention_mask)
decoder_output = self.multimodal_encoder(
hidden_states=hidden_states,
attention_mask=attention_mask,
encoder_hidden_states=encoder_hi... | 19 | 765 | 153 | 918 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import copy
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import torch
import torch.nn.... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import copy
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import torch
import torch.nn.... |
45,189 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/albef/model.py | 62,63 | 32,70 | forward | PredictionHead | 63,70 | 63,70 | class PredictionHead(nn.Module):
"""
Predict the following token autoregressively.
Args:
vocab_size (int): The number of different tokens the prediction_head can predict.
hidden_size (int): The hidden size of the prediction_head.
layer_norm_eps (float): The epsilon used by the predi... | class PredictionHead(nn.Module):
"""
Predict the following token autoregressively.
Args:
vocab_size (int): The number of different tokens the prediction_head can predict.
hidden_size (int): The hidden size of the prediction_head.
layer_norm_eps (float): The epsilon used by the predi... | hidden_states = self.dense(hidden_states)
hidden_states = self.transform_act_fn(hidden_states)
hidden_states = self.layer_norm(hidden_states)
hidden_states = self.decoder(hidden_states)
return hidden_states
| hidden_states = self.dense(hidden_states)
hidden_states = self.transform_act_fn(hidden_states)
hidden_states = self.layer_norm(hidden_states)
hidden_states = self.decoder(hidden_states)
return hidden_states
| 14 | 371 | 79 | 450 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import copy
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import torch
import torch.nn.... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import copy
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import torch
import torch.nn.... |
45,190 | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal | /home/hieuvd/dung_repo/raw/stars_03/facebookresearch_multimodal/multimodal/examples/albef/utils.py | 61,62 | 1,128 | init_distributed_mode | 62,92 | 62,92 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed un... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed un... | if "RANK" in os.environ and "WORLD_SIZE" in os.environ:
args["rank"] = int(os.environ["RANK"])
args["world_size"] = int(os.environ["WORLD_SIZE"])
args["gpu"] = int(os.environ["LOCAL_RANK"])
elif "SLURM_PROCID" in os.environ:
args["rank"] = int(os.environ["SLURM_PROCID"])
... | if "RANK" in os.environ and "WORLD_SIZE" in os.environ:
args["rank"] = int(os.environ["RANK"])
args["world_size"] = int(os.environ["WORLD_SIZE"])
args["gpu"] = int(os.environ["LOCAL_RANK"])
elif "SLURM_PROCID" in os.environ:
args["rank"] = int(os.environ["SLURM_PROCID"])
... | 65 | 839 | 379 | 1,218 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed un... | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed un... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.