body_hash stringlengths 64 64 | body stringlengths 23 109k | docstring stringlengths 1 57k | path stringlengths 4 198 | name stringlengths 1 115 | repository_name stringlengths 7 111 | repository_stars float64 0 191k | lang stringclasses 1
value | body_without_docstring stringlengths 14 108k | unified stringlengths 45 133k |
|---|---|---|---|---|---|---|---|---|---|
f1404527d8e366310f3a2e686892618e67391d6f72e27778707b1c5bc55d0056 | def controlStep(self, dt: float):
'Invocada desde la libreria "pyenki" para cada robot'
self.myControlStep(dt)
self.enkilock.acquire()
self.myGroundSensorValues = super().groundSensorValues
for idx in range(len(self.myLeds)):
self.setLedIntensity(idx, self.myLeds[idx])
self.enkilock.rele... | Invocada desde la libreria "pyenki" para cada robot | pyplayground/server/RobotThymio2.py | controlStep | titos-carrasco/pyplayground | 0 | python | def controlStep(self, dt: float):
self.myControlStep(dt)
self.enkilock.acquire()
self.myGroundSensorValues = super().groundSensorValues
for idx in range(len(self.myLeds)):
self.setLedIntensity(idx, self.myLeds[idx])
self.enkilock.release() | def controlStep(self, dt: float):
self.myControlStep(dt)
self.enkilock.acquire()
self.myGroundSensorValues = super().groundSensorValues
for idx in range(len(self.myLeds)):
self.setLedIntensity(idx, self.myLeds[idx])
self.enkilock.release()<|docstring|>Invocada desde la libreria "pyenki"... |
32041501a370d7d111c80fddf82ae4986c374e4568e29000abbf13c885889bbe | def find_frequent_itemsets(data_iter, minimum_support_rat, include_support=False):
'\n Find frequent itemsets in the given transactions using FP-growth. This\n function returns a generator instead of an eagerly-populated list of items.\n\n The `transactions` parameter can be any iterable of iterables of it... | Find frequent itemsets in the given transactions using FP-growth. This
function returns a generator instead of an eagerly-populated list of items.
The `transactions` parameter can be any iterable of iterables of items.
`minimum_support` should be an integer specifying the minimum number of
occurrences of an itemset fo... | AssociationAnalysis/fp_growth.py | find_frequent_itemsets | 724686158/MachineLearningTest | 4 | python | def find_frequent_itemsets(data_iter, minimum_support_rat, include_support=False):
'\n Find frequent itemsets in the given transactions using FP-growth. This\n function returns a generator instead of an eagerly-populated list of items.\n\n The `transactions` parameter can be any iterable of iterables of it... | def find_frequent_itemsets(data_iter, minimum_support_rat, include_support=False):
'\n Find frequent itemsets in the given transactions using FP-growth. This\n function returns a generator instead of an eagerly-populated list of items.\n\n The `transactions` parameter can be any iterable of iterables of it... |
2e8776c40691109e6e41a08d6cd605385e9e1f8e29fd3e87fa6a0e30b16b037a | def conditional_tree_from_paths(paths):
'Build a conditional FP-tree from the given prefix paths.'
tree = FPTree()
condition_item = None
items = set()
for path in paths:
if (condition_item is None):
condition_item = path[(- 1)].item
point = tree.root
for node in p... | Build a conditional FP-tree from the given prefix paths. | AssociationAnalysis/fp_growth.py | conditional_tree_from_paths | 724686158/MachineLearningTest | 4 | python | def conditional_tree_from_paths(paths):
tree = FPTree()
condition_item = None
items = set()
for path in paths:
if (condition_item is None):
condition_item = path[(- 1)].item
point = tree.root
for node in path:
next_point = point.search(node.item)
... | def conditional_tree_from_paths(paths):
tree = FPTree()
condition_item = None
items = set()
for path in paths:
if (condition_item is None):
condition_item = path[(- 1)].item
point = tree.root
for node in path:
next_point = point.search(node.item)
... |
70d8a28f5f1d05ea91c461fdcb48935921169a0b5d78b948e200208ea1645871 | @property
def root(self):
'The root node of the tree.'
return self._root | The root node of the tree. | AssociationAnalysis/fp_growth.py | root | 724686158/MachineLearningTest | 4 | python | @property
def root(self):
return self._root | @property
def root(self):
return self._root<|docstring|>The root node of the tree.<|endoftext|> |
317b7ebbf6c2637ce7289467eb26720647613dc3c1267707219c06f9cbc8b803 | def add(self, transaction):
'Add a transaction to the tree.'
point = self._root
for item in transaction:
next_point = point.search(item)
if next_point:
next_point.increment()
else:
next_point = FPNode(self, item)
point.add(next_point)
s... | Add a transaction to the tree. | AssociationAnalysis/fp_growth.py | add | 724686158/MachineLearningTest | 4 | python | def add(self, transaction):
point = self._root
for item in transaction:
next_point = point.search(item)
if next_point:
next_point.increment()
else:
next_point = FPNode(self, item)
point.add(next_point)
self._update_route(next_point)
... | def add(self, transaction):
point = self._root
for item in transaction:
next_point = point.search(item)
if next_point:
next_point.increment()
else:
next_point = FPNode(self, item)
point.add(next_point)
self._update_route(next_point)
... |
c1a2032a399399e388c3e1a2b253b6354769c8d51bff774b923f6416ee19fa34 | def _update_route(self, point):
'Add the given node to the route through all nodes for its item.'
assert (self is point.tree)
try:
route = self._routes[point.item]
route[1].neighbor = point
self._routes[point.item] = self.Route(route[0], point)
except KeyError:
self._rout... | Add the given node to the route through all nodes for its item. | AssociationAnalysis/fp_growth.py | _update_route | 724686158/MachineLearningTest | 4 | python | def _update_route(self, point):
assert (self is point.tree)
try:
route = self._routes[point.item]
route[1].neighbor = point
self._routes[point.item] = self.Route(route[0], point)
except KeyError:
self._routes[point.item] = self.Route(point, point) | def _update_route(self, point):
assert (self is point.tree)
try:
route = self._routes[point.item]
route[1].neighbor = point
self._routes[point.item] = self.Route(route[0], point)
except KeyError:
self._routes[point.item] = self.Route(point, point)<|docstring|>Add the giv... |
918f5d3be6275ae88b0b42c31734371c62ed658d050c98c0dd8986fc86cf3f83 | def items(self):
'\n Generate one 2-tuples for each item represented in the tree. The first\n element of the tuple is the item itself, and the second element is a\n generator that will yield the nodes in the tree that belong to the item.\n '
for item in self._routes.iterkeys():
... | Generate one 2-tuples for each item represented in the tree. The first
element of the tuple is the item itself, and the second element is a
generator that will yield the nodes in the tree that belong to the item. | AssociationAnalysis/fp_growth.py | items | 724686158/MachineLearningTest | 4 | python | def items(self):
'\n Generate one 2-tuples for each item represented in the tree. The first\n element of the tuple is the item itself, and the second element is a\n generator that will yield the nodes in the tree that belong to the item.\n '
for item in self._routes.iterkeys():
... | def items(self):
'\n Generate one 2-tuples for each item represented in the tree. The first\n element of the tuple is the item itself, and the second element is a\n generator that will yield the nodes in the tree that belong to the item.\n '
for item in self._routes.iterkeys():
... |
4b3afb988598ebe331c4b21e68c2c6c40001d7f08043a47fe6860351844ca4ac | def nodes(self, item):
'\n Generate the sequence of nodes that contain the given item.\n '
try:
node = self._routes[item][0]
except KeyError:
return
while node:
(yield node)
node = node.neighbor | Generate the sequence of nodes that contain the given item. | AssociationAnalysis/fp_growth.py | nodes | 724686158/MachineLearningTest | 4 | python | def nodes(self, item):
'\n \n '
try:
node = self._routes[item][0]
except KeyError:
return
while node:
(yield node)
node = node.neighbor | def nodes(self, item):
'\n \n '
try:
node = self._routes[item][0]
except KeyError:
return
while node:
(yield node)
node = node.neighbor<|docstring|>Generate the sequence of nodes that contain the given item.<|endoftext|> |
eca36a4af07ab6a34df8d7130585b857788e3d9050b0b099ba30c4968efc53b6 | def prefix_paths(self, item):
'Generate the prefix paths that end with the given item.'
def collect_path(node):
path = []
while (node and (not node.root)):
path.append(node)
node = node.parent
path.reverse()
return path
return (collect_path(node) for ... | Generate the prefix paths that end with the given item. | AssociationAnalysis/fp_growth.py | prefix_paths | 724686158/MachineLearningTest | 4 | python | def prefix_paths(self, item):
def collect_path(node):
path = []
while (node and (not node.root)):
path.append(node)
node = node.parent
path.reverse()
return path
return (collect_path(node) for node in self.nodes(item)) | def prefix_paths(self, item):
def collect_path(node):
path = []
while (node and (not node.root)):
path.append(node)
node = node.parent
path.reverse()
return path
return (collect_path(node) for node in self.nodes(item))<|docstring|>Generate the prefix... |
5fce995333edd9844dc44fb667a3d5a7be72fa3429cef33d87a0d99486757699 | def add(self, child):
'Add the given FPNode `child` as a child of this node.'
if (not isinstance(child, FPNode)):
raise TypeError('Can only add other FPNodes as children')
if (not (child.item in self._children)):
self._children[child.item] = child
child.parent = self | Add the given FPNode `child` as a child of this node. | AssociationAnalysis/fp_growth.py | add | 724686158/MachineLearningTest | 4 | python | def add(self, child):
if (not isinstance(child, FPNode)):
raise TypeError('Can only add other FPNodes as children')
if (not (child.item in self._children)):
self._children[child.item] = child
child.parent = self | def add(self, child):
if (not isinstance(child, FPNode)):
raise TypeError('Can only add other FPNodes as children')
if (not (child.item in self._children)):
self._children[child.item] = child
child.parent = self<|docstring|>Add the given FPNode `child` as a child of this node.<|endo... |
4af9398fda9f883a72096f6d702d86aa9a447615d9ff885ef20415fa0580d456 | def search(self, item):
'\n Check whether this node contains a child node for the given item.\n If so, that node is returned; otherwise, `None` is returned.\n '
try:
return self._children[item]
except KeyError:
return None | Check whether this node contains a child node for the given item.
If so, that node is returned; otherwise, `None` is returned. | AssociationAnalysis/fp_growth.py | search | 724686158/MachineLearningTest | 4 | python | def search(self, item):
'\n Check whether this node contains a child node for the given item.\n If so, that node is returned; otherwise, `None` is returned.\n '
try:
return self._children[item]
except KeyError:
return None | def search(self, item):
'\n Check whether this node contains a child node for the given item.\n If so, that node is returned; otherwise, `None` is returned.\n '
try:
return self._children[item]
except KeyError:
return None<|docstring|>Check whether this node contains a c... |
e67f0da9dc8fdbca17101acc2e8f4a02fef977993e2f6e7c12cc80aa10977a60 | @property
def tree(self):
'The tree in which this node appears.'
return self._tree | The tree in which this node appears. | AssociationAnalysis/fp_growth.py | tree | 724686158/MachineLearningTest | 4 | python | @property
def tree(self):
return self._tree | @property
def tree(self):
return self._tree<|docstring|>The tree in which this node appears.<|endoftext|> |
49f1980e685fa06e6ee59d96ceb47ae2422244bdb6368374f461862bd87ac329 | @property
def item(self):
'The item contained in this node.'
return self._item | The item contained in this node. | AssociationAnalysis/fp_growth.py | item | 724686158/MachineLearningTest | 4 | python | @property
def item(self):
return self._item | @property
def item(self):
return self._item<|docstring|>The item contained in this node.<|endoftext|> |
1631177a280775e38a13486675b2239bc62e82989a251b9cf3e2be0d186b3e73 | @property
def count(self):
"The count associated with this node's item."
return self._count | The count associated with this node's item. | AssociationAnalysis/fp_growth.py | count | 724686158/MachineLearningTest | 4 | python | @property
def count(self):
return self._count | @property
def count(self):
return self._count<|docstring|>The count associated with this node's item.<|endoftext|> |
25e69039b3c94c205bf00fa431b4ff8789eaa44428ee0dc845b2bde58dc0b263 | def increment(self):
"Increment the count associated with this node's item."
if (self._count is None):
raise ValueError('Root nodes have no associated count.')
self._count += 1 | Increment the count associated with this node's item. | AssociationAnalysis/fp_growth.py | increment | 724686158/MachineLearningTest | 4 | python | def increment(self):
if (self._count is None):
raise ValueError('Root nodes have no associated count.')
self._count += 1 | def increment(self):
if (self._count is None):
raise ValueError('Root nodes have no associated count.')
self._count += 1<|docstring|>Increment the count associated with this node's item.<|endoftext|> |
554598d024d006ed802e4bbf06990fc369ff1c8a15d3ac8993da1eebfb1a212c | @property
def root(self):
'True if this node is the root of a tree; false if otherwise.'
return ((self._item is None) and (self._count is None)) | True if this node is the root of a tree; false if otherwise. | AssociationAnalysis/fp_growth.py | root | 724686158/MachineLearningTest | 4 | python | @property
def root(self):
return ((self._item is None) and (self._count is None)) | @property
def root(self):
return ((self._item is None) and (self._count is None))<|docstring|>True if this node is the root of a tree; false if otherwise.<|endoftext|> |
672aad85cddf8dea25809a8a1783b8a74ce292849f401fb66b03806b86a6121b | @property
def leaf(self):
'True if this node is a leaf in the tree; false if otherwise.'
return (len(self._children) == 0) | True if this node is a leaf in the tree; false if otherwise. | AssociationAnalysis/fp_growth.py | leaf | 724686158/MachineLearningTest | 4 | python | @property
def leaf(self):
return (len(self._children) == 0) | @property
def leaf(self):
return (len(self._children) == 0)<|docstring|>True if this node is a leaf in the tree; false if otherwise.<|endoftext|> |
7f2b95a07c5af73edd5def6e843777853991a2c4e6c045239abf80d658f04803 | @property
def parent(self):
"The node's parent"
return self._parent | The node's parent | AssociationAnalysis/fp_growth.py | parent | 724686158/MachineLearningTest | 4 | python | @property
def parent(self):
return self._parent | @property
def parent(self):
return self._parent<|docstring|>The node's parent<|endoftext|> |
545cc378d45f9d7cd2e8cba56f2a3f5a8f9dab3e89e0ce746eebe14ce95ad5e1 | @property
def neighbor(self):
'\n The node\'s neighbor; the one with the same value that is "to the right"\n of it in the tree.\n '
return self._neighbor | The node's neighbor; the one with the same value that is "to the right"
of it in the tree. | AssociationAnalysis/fp_growth.py | neighbor | 724686158/MachineLearningTest | 4 | python | @property
def neighbor(self):
'\n The node\'s neighbor; the one with the same value that is "to the right"\n of it in the tree.\n '
return self._neighbor | @property
def neighbor(self):
'\n The node\'s neighbor; the one with the same value that is "to the right"\n of it in the tree.\n '
return self._neighbor<|docstring|>The node's neighbor; the one with the same value that is "to the right"
of it in the tree.<|endoftext|> |
5531be5c712139d01acf28c792dab78e1937adef038e8cf63bdb3b0fe1c81e3e | @property
def children(self):
'The nodes that are children of this node.'
return tuple(self._children.itervalues()) | The nodes that are children of this node. | AssociationAnalysis/fp_growth.py | children | 724686158/MachineLearningTest | 4 | python | @property
def children(self):
return tuple(self._children.itervalues()) | @property
def children(self):
return tuple(self._children.itervalues())<|docstring|>The nodes that are children of this node.<|endoftext|> |
bb70fdd3bd05a434d1ce289633a1dbb0884a43df0deac1f94c3bc150b819fbc6 | def run(self):
' XXX: to implement. ' | XXX: to implement. | CreateOutput/main.py | run | miku/batchdata | 8 | python | def run(self):
' ' | def run(self):
' '<|docstring|>XXX: to implement.<|endoftext|> |
566bb4a4b65b58b7fbf68d435c2f9d21e8450362f2b19f04880f0a6d94d2f9fb | def findMonitor(self, xywh0):
'\n find current monitor\n '
s = subprocess.check_output('xrandr').decode()
l = re.findall('(\\d+)x(\\d+)\\+(\\d+)\\+(\\d+)', s)
monitors = [(int(x), int(y), int(w), int(h)) for (w, h, x, y) in l]
if (len(monitors) > 0):
window = ewmh.getActiveWind... | find current monitor | freetile/monitor.py | findMonitor | rbn42/freetile | 10 | python | def findMonitor(self, xywh0):
'\n \n '
s = subprocess.check_output('xrandr').decode()
l = re.findall('(\\d+)x(\\d+)\\+(\\d+)\\+(\\d+)', s)
monitors = [(int(x), int(y), int(w), int(h)) for (w, h, x, y) in l]
if (len(monitors) > 0):
window = ewmh.getActiveWindow()
if wind... | def findMonitor(self, xywh0):
'\n \n '
s = subprocess.check_output('xrandr').decode()
l = re.findall('(\\d+)x(\\d+)\\+(\\d+)\\+(\\d+)', s)
monitors = [(int(x), int(y), int(w), int(h)) for (w, h, x, y) in l]
if (len(monitors) > 0):
window = ewmh.getActiveWindow()
if wind... |
ec82653bf3e2beb053ebd2572bcefc3304e76a67d56854a1444e4feb72158370 | def __init__(self, logger=None):
' Construct the instance\n\n Attributes:\n logger: Inject this logger into the agent rather than using the default.\n '
logger = (logger or logging.getLogger(__name__))
super(AzAgent, self).__init__('az', logger=logger) | Construct the instance
Attributes:
logger: Inject this logger into the agent rather than using the default. | citest/azure_testing/az_agent.py | __init__ | plumpy/citest | 69 | python | def __init__(self, logger=None):
' Construct the instance\n\n Attributes:\n logger: Inject this logger into the agent rather than using the default.\n '
logger = (logger or logging.getLogger(__name__))
super(AzAgent, self).__init__('az', logger=logger) | def __init__(self, logger=None):
' Construct the instance\n\n Attributes:\n logger: Inject this logger into the agent rather than using the default.\n '
logger = (logger or logging.getLogger(__name__))
super(AzAgent, self).__init__('az', logger=logger)<|docstring|>Construct the instance
Attribut... |
4b0a6033a881d45481cb918a79469678fc36df4af6cabdac909ccee3fc3494fa | def build_az_command_args(self, az_resource, az_command, args):
'"Build the Azure command line to be used\n\n Attributes:\n az_resource: The az resource module name (group, vm, etc...)\n az_command: The az action on the resource (list, add, etc..)\n args: All the others args after the command (-g,... | "Build the Azure command line to be used
Attributes:
az_resource: The az resource module name (group, vm, etc...)
az_command: The az action on the resource (list, add, etc..)
args: All the others args after the command (-g, -n, -l, etc...) | citest/azure_testing/az_agent.py | build_az_command_args | plumpy/citest | 69 | python | def build_az_command_args(self, az_resource, az_command, args):
'"Build the Azure command line to be used\n\n Attributes:\n az_resource: The az resource module name (group, vm, etc...)\n az_command: The az action on the resource (list, add, etc..)\n args: All the others args after the command (-g,... | def build_az_command_args(self, az_resource, az_command, args):
'"Build the Azure command line to be used\n\n Attributes:\n az_resource: The az resource module name (group, vm, etc...)\n az_command: The az action on the resource (list, add, etc..)\n args: All the others args after the command (-g,... |
905d646788f0ed3b49d95b805876942575a1db9093ce8d821b7e7b9b16020146 | @task
def docs(ctx, clean=False, browse=False, watch=False):
'Build the docs.'
if clean:
clean_docs(ctx)
if watch:
watch_docs(ctx, browse=browse)
else:
build_docs(ctx, browse=browse) | Build the docs. | tasks.py | docs | KyleJamesWalker/flask-apispec | 627 | python | @task
def docs(ctx, clean=False, browse=False, watch=False):
if clean:
clean_docs(ctx)
if watch:
watch_docs(ctx, browse=browse)
else:
build_docs(ctx, browse=browse) | @task
def docs(ctx, clean=False, browse=False, watch=False):
if clean:
clean_docs(ctx)
if watch:
watch_docs(ctx, browse=browse)
else:
build_docs(ctx, browse=browse)<|docstring|>Build the docs.<|endoftext|> |
e00ef7ec93641c0940ccf22b6589eea9acc021975fd7224c87e21e5aa3320677 | @task
def watch_docs(ctx, browse=False):
'Run build the docs when a file changes.'
try:
import sphinx_autobuild
except ImportError:
print('ERROR: watch task requires the sphinx_autobuild package.')
print('Install it with:')
print(' pip install sphinx-autobuild')
sy... | Run build the docs when a file changes. | tasks.py | watch_docs | KyleJamesWalker/flask-apispec | 627 | python | @task
def watch_docs(ctx, browse=False):
try:
import sphinx_autobuild
except ImportError:
print('ERROR: watch task requires the sphinx_autobuild package.')
print('Install it with:')
print(' pip install sphinx-autobuild')
sys.exit(1)
ctx.run('sphinx-autobuild {... | @task
def watch_docs(ctx, browse=False):
try:
import sphinx_autobuild
except ImportError:
print('ERROR: watch task requires the sphinx_autobuild package.')
print('Install it with:')
print(' pip install sphinx-autobuild')
sys.exit(1)
ctx.run('sphinx-autobuild {... |
46b34ebaa90b4196605c47fa2434ce10314636ca2296ddd8ba782b5793051fcf | def set_up(self, output=None, transform=None):
'\n Sets the file like object.\n\n .. note::\n\n Make sure to pass in instances which allow multiple writes.\n\n :Parameters:\n - `output`: A file like object to use. Default: sys.stderr\n - `transform`: Optional funct... | Sets the file like object.
.. note::
Make sure to pass in instances which allow multiple writes.
:Parameters:
- `output`: A file like object to use. Default: sys.stderr
- `transform`: Optional function to modify the output before write. | src/flask_track_usage/storage/output.py | set_up | amrotork/flask-track-usage | 46 | python | def set_up(self, output=None, transform=None):
'\n Sets the file like object.\n\n .. note::\n\n Make sure to pass in instances which allow multiple writes.\n\n :Parameters:\n - `output`: A file like object to use. Default: sys.stderr\n - `transform`: Optional funct... | def set_up(self, output=None, transform=None):
'\n Sets the file like object.\n\n .. note::\n\n Make sure to pass in instances which allow multiple writes.\n\n :Parameters:\n - `output`: A file like object to use. Default: sys.stderr\n - `transform`: Optional funct... |
af9652ed4a6a6fa7dcf022317e16424bd5ffd3dab64d36d48b1ba1d43eabae2b | def store(self, data):
'\n Executed on "function call".\n\n :Parameters:\n - `data`: Data to store.\n '
self.output.write(self.transform(data))
if self.flushable:
self.output.flush() | Executed on "function call".
:Parameters:
- `data`: Data to store. | src/flask_track_usage/storage/output.py | store | amrotork/flask-track-usage | 46 | python | def store(self, data):
'\n Executed on "function call".\n\n :Parameters:\n - `data`: Data to store.\n '
self.output.write(self.transform(data))
if self.flushable:
self.output.flush() | def store(self, data):
'\n Executed on "function call".\n\n :Parameters:\n - `data`: Data to store.\n '
self.output.write(self.transform(data))
if self.flushable:
self.output.flush()<|docstring|>Executed on "function call".
:Parameters:
- `data`: Data to store.<|en... |
1ac0861bac3f00f09dfee4fddb6f6ba92919ceefc0b1aee1cf29967eae9cc976 | def title_file_string(titles: List[str]) -> str:
'Return string which will be used to generate titles from json'
return (('function change_title(){' + f'''
const titles = {titles};
const index = Math.floor(Math.random() * titles.length);
const title = titles[index];
document.title = title;
document.ge... | Return string which will be used to generate titles from json | bloggen/components.py | title_file_string | akshaybadola/blog_generator | 0 | python | def title_file_string(titles: List[str]) -> str:
return (('function change_title(){' + f'
const titles = {titles};
const index = Math.floor(Math.random() * titles.length);
const title = titles[index];
document.title = title;
document.getElementById("header").children[0].textContent = title;
') + '}') | def title_file_string(titles: List[str]) -> str:
return (('function change_title(){' + f'
const titles = {titles};
const index = Math.floor(Math.random() * titles.length);
const title = titles[index];
document.title = title;
document.getElementById("header").children[0].textContent = title;
') + '}')... |
549ccc3d4502f5bc65537d78ef7f43d197111347e775018580d236fa38313760 | def about_string(abouts: List[str]) -> str:
'Return string which will be used to generate titles from json'
return (('function change_about(){' + f'''
const abouts = {abouts};
const index = Math.floor(Math.random() * abouts.length);
const about = abouts[index];
const element = (document.querySelector("b... | Return string which will be used to generate titles from json | bloggen/components.py | about_string | akshaybadola/blog_generator | 0 | python | def about_string(abouts: List[str]) -> str:
return (('function change_about(){' + f'
const abouts = {abouts};
const index = Math.floor(Math.random() * abouts.length);
const about = abouts[index];
const element = (document.querySelector("body > div.wrapper > div.about > header > div.author-description")... | def about_string(abouts: List[str]) -> str:
return (('function change_about(){' + f'
const abouts = {abouts};
const index = Math.floor(Math.random() * abouts.length);
const about = abouts[index];
const element = (document.querySelector("body > div.wrapper > div.about > header > div.author-description")... |
77c4df3c9d80845ef5b13705cdd0b14d35999a6fb19d98b42d02d57004e62b4c | def snippet_string(snippet: Any, path: str, date: str, tags: List[str]=None) -> str:
'Return string which will be used to generate snippets'
return (f'''
<div class="main parent content snippet">
<span><a href="{path}">
<h4>{snippet.heading}</h4>
{snippet.text}...
</a>
... | Return string which will be used to generate snippets | bloggen/components.py | snippet_string | akshaybadola/blog_generator | 0 | python | def snippet_string(snippet: Any, path: str, date: str, tags: List[str]=None) -> str:
return (f'
<div class="main parent content snippet">
<span><a href="{path}">
<h4>{snippet.heading}</h4>
{snippet.text}...
</a>
</span>
<p></p><br>
<p>Posted on: {date}' + (f', tags: {t... | def snippet_string(snippet: Any, path: str, date: str, tags: List[str]=None) -> str:
return (f'
<div class="main parent content snippet">
<span><a href="{path}">
<h4>{snippet.heading}</h4>
{snippet.text}...
</a>
</span>
<p></p><br>
<p>Posted on: {date}' + (f', tags: {t... |
0fc3cb0ccb0c43d95840ad1196a3f2317a285ce41d459e4648f12a07f821872b | def snippet_string_with_category(snippet: Any, path: str, date: str, category: str, tags: List[str]=None, cat_path_prefix: str='') -> str:
'Return string which will be used to generate snippets with categories beneath it.\n Used for posts'
return (f'''
<div class="main parent content snippet">
<span><a h... | Return string which will be used to generate snippets with categories beneath it.
Used for posts | bloggen/components.py | snippet_string_with_category | akshaybadola/blog_generator | 0 | python | def snippet_string_with_category(snippet: Any, path: str, date: str, category: str, tags: List[str]=None, cat_path_prefix: str=) -> str:
'Return string which will be used to generate snippets with categories beneath it.\n Used for posts'
return (f'
<div class="main parent content snippet">
<span><a href=... | def snippet_string_with_category(snippet: Any, path: str, date: str, category: str, tags: List[str]=None, cat_path_prefix: str=) -> str:
'Return string which will be used to generate snippets with categories beneath it.\n Used for posts'
return (f'
<div class="main parent content snippet">
<span><a href=... |
2106e41fafbfa8a115e57ee9bcfefc67062704c237be90823f56bf7ed768c200 | def article_snippet_with_category(snippet: Any, path: str, date: str, category: str, tags: List[str]=None, cat_path_prefix: str='') -> str:
'Return string which will be used to generate snippets with categories beneath it.\n Used for posts'
return (f'''
<article class="post">
<span><a href="{path}">
... | Return string which will be used to generate snippets with categories beneath it.
Used for posts | bloggen/components.py | article_snippet_with_category | akshaybadola/blog_generator | 0 | python | def article_snippet_with_category(snippet: Any, path: str, date: str, category: str, tags: List[str]=None, cat_path_prefix: str=) -> str:
'Return string which will be used to generate snippets with categories beneath it.\n Used for posts'
return (f'
<article class="post">
<span><a href="{path}">
... | def article_snippet_with_category(snippet: Any, path: str, date: str, category: str, tags: List[str]=None, cat_path_prefix: str=) -> str:
'Return string which will be used to generate snippets with categories beneath it.\n Used for posts'
return (f'
<article class="post">
<span><a href="{path}">
... |
e465744b6280b73a166be96fc3753df6961c4b74b4c7937dd133677eabecd012 | def remove_prefix(state_dict, prefix):
" Old style model is stored with all names of parameters sharing common prefix 'module.' "
f = (lambda x: (x.split(prefix, 1)[(- 1)] if x.startswith(prefix) else x))
return {f(key): value for (key, value) in state_dict.items()} | Old style model is stored with all names of parameters sharing common prefix 'module.' | make_onnx_copy.py | remove_prefix | AbdallahOmarAhmed/face-mask-detection | 2 | python | def remove_prefix(state_dict, prefix):
" "
f = (lambda x: (x.split(prefix, 1)[(- 1)] if x.startswith(prefix) else x))
return {f(key): value for (key, value) in state_dict.items()} | def remove_prefix(state_dict, prefix):
" "
f = (lambda x: (x.split(prefix, 1)[(- 1)] if x.startswith(prefix) else x))
return {f(key): value for (key, value) in state_dict.items()}<|docstring|>Old style model is stored with all names of parameters sharing common prefix 'module.'<|endoftext|> |
8e8b5f83e342e8f71f903229dab11c7d6a88b1fd75901366aa7feac847d7fa48 | def integerReplacement(self, n):
'\n :type n: int\n :rtype: int\n '
def helper(n, d):
if (n in d):
return d[n]
if ((n % 2) == 0):
d[n] = (helper((n / 2), d) + 1)
else:
d[n] = (1 + min(helper((n + 1), d), helper((n - 1), d)))
... | :type n: int
:rtype: int | LeetCodeSolutions/python/397_Integer_Replacement.py | integerReplacement | ChuanleiGuo/AlgorithmsPlayground | 1 | python | def integerReplacement(self, n):
'\n :type n: int\n :rtype: int\n '
def helper(n, d):
if (n in d):
return d[n]
if ((n % 2) == 0):
d[n] = (helper((n / 2), d) + 1)
else:
d[n] = (1 + min(helper((n + 1), d), helper((n - 1), d)))
... | def integerReplacement(self, n):
'\n :type n: int\n :rtype: int\n '
def helper(n, d):
if (n in d):
return d[n]
if ((n % 2) == 0):
d[n] = (helper((n / 2), d) + 1)
else:
d[n] = (1 + min(helper((n + 1), d), helper((n - 1), d)))
... |
1152eb22dceb40879c01dae0ddc3f3bbdb3da4631c95e5f115a79d9812bbfecc | def test_item_get(self):
'Test case for item_get\n\n \n '
response = self.client.open('/item', method='GET')
self.assert200(response, ('Response body is : ' + response.data.decode('utf-8'))) | Test case for item_get | python-flask-server-generated/swagger_server/test/test_default_controller.py | test_item_get | yarnaid/fridge | 0 | python | def test_item_get(self):
'\n\n \n '
response = self.client.open('/item', method='GET')
self.assert200(response, ('Response body is : ' + response.data.decode('utf-8'))) | def test_item_get(self):
'\n\n \n '
response = self.client.open('/item', method='GET')
self.assert200(response, ('Response body is : ' + response.data.decode('utf-8')))<|docstring|>Test case for item_get<|endoftext|> |
3e78d2d1248916939a67ac9a6718dcddf11b6217b1582c4680cf217458680b79 | def ee_collections(collection):
'\n Earth Engine image collection names\n '
dic = {'Sentinel2_TOA': 'COPERNICUS/S2', 'Landsat7_SR': 'LANDSAT/LE07/C01/T1_SR', 'Landsat8_SR': 'LANDSAT/LC08/C01/T1_SR', 'CroplandDataLayers': 'USDA/NASS/CDL', 'NationalLandCoverDatabase': 'USGS/NLCD'}
return dic[collection] | Earth Engine image collection names | notebooks/Google_Cloud_Functions/ee_pre_processing/ee_collection_specifics.py | ee_collections | Skydipper/CNN-tests | 7 | python | def ee_collections(collection):
'\n \n '
dic = {'Sentinel2_TOA': 'COPERNICUS/S2', 'Landsat7_SR': 'LANDSAT/LE07/C01/T1_SR', 'Landsat8_SR': 'LANDSAT/LC08/C01/T1_SR', 'CroplandDataLayers': 'USDA/NASS/CDL', 'NationalLandCoverDatabase': 'USGS/NLCD'}
return dic[collection] | def ee_collections(collection):
'\n \n '
dic = {'Sentinel2_TOA': 'COPERNICUS/S2', 'Landsat7_SR': 'LANDSAT/LE07/C01/T1_SR', 'Landsat8_SR': 'LANDSAT/LC08/C01/T1_SR', 'CroplandDataLayers': 'USDA/NASS/CDL', 'NationalLandCoverDatabase': 'USGS/NLCD'}
return dic[collection]<|docstring|>Earth Engine image col... |
4773306b4a98f886befada81b5714b33e9e384bbc424aeebf509e5eeaf697193 | def ee_bands(collection):
'\n Earth Engine band names\n '
dic = {'Sentinel2_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8A', 'B8', 'B11', 'B12', 'ndvi', 'ndwi'], 'Landsat7_SR': ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'ndvi', 'ndwi'], 'Landsat8_SR': ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B10... | Earth Engine band names | notebooks/Google_Cloud_Functions/ee_pre_processing/ee_collection_specifics.py | ee_bands | Skydipper/CNN-tests | 7 | python | def ee_bands(collection):
'\n \n '
dic = {'Sentinel2_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8A', 'B8', 'B11', 'B12', 'ndvi', 'ndwi'], 'Landsat7_SR': ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'ndvi', 'ndwi'], 'Landsat8_SR': ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B10', 'B11', 'ndvi', 'ndwi... | def ee_bands(collection):
'\n \n '
dic = {'Sentinel2_TOA': ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8A', 'B8', 'B11', 'B12', 'ndvi', 'ndwi'], 'Landsat7_SR': ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'ndvi', 'ndwi'], 'Landsat8_SR': ['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B10', 'B11', 'ndvi', 'ndwi... |
c76de217355370b4813223ac48c05e615712bf8a4d9cb021a0d1e3271ebd38d9 | def ee_bands_rgb(collection):
'\n Earth Engine rgb band names\n '
dic = {'Sentinel2_TOA': ['B4', 'B3', 'B2'], 'Landsat7_SR': ['B3', 'B2', 'B1'], 'Landsat8_SR': ['B4', 'B3', 'B2'], 'CroplandDataLayers': ['landcover'], 'NationalLandCoverDatabase': ['impervious']}
return dic[collection] | Earth Engine rgb band names | notebooks/Google_Cloud_Functions/ee_pre_processing/ee_collection_specifics.py | ee_bands_rgb | Skydipper/CNN-tests | 7 | python | def ee_bands_rgb(collection):
'\n \n '
dic = {'Sentinel2_TOA': ['B4', 'B3', 'B2'], 'Landsat7_SR': ['B3', 'B2', 'B1'], 'Landsat8_SR': ['B4', 'B3', 'B2'], 'CroplandDataLayers': ['landcover'], 'NationalLandCoverDatabase': ['impervious']}
return dic[collection] | def ee_bands_rgb(collection):
'\n \n '
dic = {'Sentinel2_TOA': ['B4', 'B3', 'B2'], 'Landsat7_SR': ['B3', 'B2', 'B1'], 'Landsat8_SR': ['B4', 'B3', 'B2'], 'CroplandDataLayers': ['landcover'], 'NationalLandCoverDatabase': ['impervious']}
return dic[collection]<|docstring|>Earth Engine rgb band names<|end... |
9fccb0288388a2ac7785b453d1f8e45206f5c236c41bd174bbe7342c87005e2e | def ee_bands_normThreshold(collection):
'\n Normalization threshold percentage\n '
dic = {'Sentinel2_TOA': {'B1': 75, 'B2': 75, 'B3': 75, 'B4': 75, 'B5': 80, 'B6': 80, 'B7': 80, 'B8A': 80, 'B8': 80, 'B11': 100, 'B12': 100}, 'Landsat7_SR': {'B1': 95, 'B2': 95, 'B3': 95, 'B4': 100, 'B5': 100, 'B6': 100, 'B7... | Normalization threshold percentage | notebooks/Google_Cloud_Functions/ee_pre_processing/ee_collection_specifics.py | ee_bands_normThreshold | Skydipper/CNN-tests | 7 | python | def ee_bands_normThreshold(collection):
'\n \n '
dic = {'Sentinel2_TOA': {'B1': 75, 'B2': 75, 'B3': 75, 'B4': 75, 'B5': 80, 'B6': 80, 'B7': 80, 'B8A': 80, 'B8': 80, 'B11': 100, 'B12': 100}, 'Landsat7_SR': {'B1': 95, 'B2': 95, 'B3': 95, 'B4': 100, 'B5': 100, 'B6': 100, 'B7': 100}, 'Landsat8_SR': {'B1': 90,... | def ee_bands_normThreshold(collection):
'\n \n '
dic = {'Sentinel2_TOA': {'B1': 75, 'B2': 75, 'B3': 75, 'B4': 75, 'B5': 80, 'B6': 80, 'B7': 80, 'B8A': 80, 'B8': 80, 'B11': 100, 'B12': 100}, 'Landsat7_SR': {'B1': 95, 'B2': 95, 'B3': 95, 'B4': 100, 'B5': 100, 'B6': 100, 'B7': 100}, 'Landsat8_SR': {'B1': 90,... |
c4d6be511f11b94b6bc67468d5e1bdd000b9834cc145d76b75314df5986fa18e | def vizz_params_rgb(collection):
'\n Visualization parameters\n '
dic = {'Sentinel2_TOA': {'min': 0, 'max': 3000, 'bands': ['B4', 'B3', 'B2']}, 'Landsat7_SR': {'min': 0, 'max': 3000, 'gamma': 1.4, 'bands': ['B3', 'B2', 'B1']}, 'Landsat8_SR': {'min': 0, 'max': 3000, 'gamma': 1.4, 'bands': ['B4', 'B3', 'B2'... | Visualization parameters | notebooks/Google_Cloud_Functions/ee_pre_processing/ee_collection_specifics.py | vizz_params_rgb | Skydipper/CNN-tests | 7 | python | def vizz_params_rgb(collection):
'\n \n '
dic = {'Sentinel2_TOA': {'min': 0, 'max': 3000, 'bands': ['B4', 'B3', 'B2']}, 'Landsat7_SR': {'min': 0, 'max': 3000, 'gamma': 1.4, 'bands': ['B3', 'B2', 'B1']}, 'Landsat8_SR': {'min': 0, 'max': 3000, 'gamma': 1.4, 'bands': ['B4', 'B3', 'B2']}, 'CroplandDataLayers'... | def vizz_params_rgb(collection):
'\n \n '
dic = {'Sentinel2_TOA': {'min': 0, 'max': 3000, 'bands': ['B4', 'B3', 'B2']}, 'Landsat7_SR': {'min': 0, 'max': 3000, 'gamma': 1.4, 'bands': ['B3', 'B2', 'B1']}, 'Landsat8_SR': {'min': 0, 'max': 3000, 'gamma': 1.4, 'bands': ['B4', 'B3', 'B2']}, 'CroplandDataLayers'... |
727ac546e7eb7d87f1ab17d0d764885081ae25180f2a5f2bddff0c64ecf0c66c | def vizz_params(collection):
'\n Visualization parameters\n '
dic = {'Sentinel2_TOA': [{'min': 0, 'max': 1, 'bands': ['B4', 'B3', 'B2']}, {'min': 0, 'max': 1, 'bands': ['B1']}, {'min': 0, 'max': 1, 'bands': ['B5']}, {'min': 0, 'max': 1, 'bands': ['B6']}, {'min': 0, 'max': 1, 'bands': ['B7']}, {'min': 0, '... | Visualization parameters | notebooks/Google_Cloud_Functions/ee_pre_processing/ee_collection_specifics.py | vizz_params | Skydipper/CNN-tests | 7 | python | def vizz_params(collection):
'\n \n '
dic = {'Sentinel2_TOA': [{'min': 0, 'max': 1, 'bands': ['B4', 'B3', 'B2']}, {'min': 0, 'max': 1, 'bands': ['B1']}, {'min': 0, 'max': 1, 'bands': ['B5']}, {'min': 0, 'max': 1, 'bands': ['B6']}, {'min': 0, 'max': 1, 'bands': ['B7']}, {'min': 0, 'max': 1, 'bands': ['B8A'... | def vizz_params(collection):
'\n \n '
dic = {'Sentinel2_TOA': [{'min': 0, 'max': 1, 'bands': ['B4', 'B3', 'B2']}, {'min': 0, 'max': 1, 'bands': ['B1']}, {'min': 0, 'max': 1, 'bands': ['B5']}, {'min': 0, 'max': 1, 'bands': ['B6']}, {'min': 0, 'max': 1, 'bands': ['B7']}, {'min': 0, 'max': 1, 'bands': ['B8A'... |
b8d2da52c8f1af10bfd3a3a02088f71b10a3ebaac2e4f8f1900e1fd2da1f5de1 | def CloudMaskS2(image):
"\n European Space Agency (ESA) clouds from 'QA60', i.e. Quality Assessment band at 60m\n parsed by Nick Clinton\n "
AerosolsBands = ['B1']
VIBands = ['B2', 'B3', 'B4']
RedBands = ['B5', 'B6', 'B7', 'B8A']
NIRBands = ['B8']
SWIRBands = ['B11', 'B12']
qa = ima... | European Space Agency (ESA) clouds from 'QA60', i.e. Quality Assessment band at 60m
parsed by Nick Clinton | notebooks/Google_Cloud_Functions/ee_pre_processing/ee_collection_specifics.py | CloudMaskS2 | Skydipper/CNN-tests | 7 | python | def CloudMaskS2(image):
"\n European Space Agency (ESA) clouds from 'QA60', i.e. Quality Assessment band at 60m\n parsed by Nick Clinton\n "
AerosolsBands = ['B1']
VIBands = ['B2', 'B3', 'B4']
RedBands = ['B5', 'B6', 'B7', 'B8A']
NIRBands = ['B8']
SWIRBands = ['B11', 'B12']
qa = ima... | def CloudMaskS2(image):
"\n European Space Agency (ESA) clouds from 'QA60', i.e. Quality Assessment band at 60m\n parsed by Nick Clinton\n "
AerosolsBands = ['B1']
VIBands = ['B2', 'B3', 'B4']
RedBands = ['B5', 'B6', 'B7', 'B8A']
NIRBands = ['B8']
SWIRBands = ['B11', 'B12']
qa = ima... |
c25bc73dfb9020c97066d1722e557d56a136c3a9d921a5147ac32e91b07fbbff | def test_create_file(self):
'Test the creation of a simple XlsxWriter file.'
workbook = Workbook(self.got_filename)
worksheet1 = workbook.add_worksheet()
chartsheet1 = workbook.add_chartsheet()
worksheet2 = workbook.add_worksheet()
chartsheet2 = workbook.add_chartsheet()
chart1 = workbook.ad... | Test the creation of a simple XlsxWriter file. | xlsxwriter/test/comparison/test_chart_bar15.py | test_create_file | patrickziegler/XlsxWriter | 2,766 | python | def test_create_file(self):
workbook = Workbook(self.got_filename)
worksheet1 = workbook.add_worksheet()
chartsheet1 = workbook.add_chartsheet()
worksheet2 = workbook.add_worksheet()
chartsheet2 = workbook.add_chartsheet()
chart1 = workbook.add_chart({'type': 'bar'})
chart2 = workbook.a... | def test_create_file(self):
workbook = Workbook(self.got_filename)
worksheet1 = workbook.add_worksheet()
chartsheet1 = workbook.add_chartsheet()
worksheet2 = workbook.add_worksheet()
chartsheet2 = workbook.add_chartsheet()
chart1 = workbook.add_chart({'type': 'bar'})
chart2 = workbook.a... |
291181ba6c262e1f027dd2c6032ec25bd18e2254a7b4258b9235d1b5fe1e267c | def _handle_zeros_in_scale(scale, copy=True):
'Makes sure that whenever scale is zero, we handle it correctly.\n\n This happens in most scalers when we have constant features.\n '
if np.isscalar(scale):
if (scale == 0.0):
scale = 1.0
return scale
elif (hasattr(scale, 'ndim'... | Makes sure that whenever scale is zero, we handle it correctly.
This happens in most scalers when we have constant features. | mars/learn/preprocessing/_data.py | _handle_zeros_in_scale | hxri/mars | 2,413 | python | def _handle_zeros_in_scale(scale, copy=True):
'Makes sure that whenever scale is zero, we handle it correctly.\n\n This happens in most scalers when we have constant features.\n '
if np.isscalar(scale):
if (scale == 0.0):
scale = 1.0
return scale
elif (hasattr(scale, 'ndim'... | def _handle_zeros_in_scale(scale, copy=True):
'Makes sure that whenever scale is zero, we handle it correctly.\n\n This happens in most scalers when we have constant features.\n '
if np.isscalar(scale):
if (scale == 0.0):
scale = 1.0
return scale
elif (hasattr(scale, 'ndim'... |
e3639ac170d5a2775991273242ac41eb056f39efd587d6f2bb0f177304c712cf | def minmax_scale(X, feature_range=(0, 1), *, axis=0, copy=True, session=None, run_kwargs=None):
'Transform features by scaling each feature to a given range.\n\n This estimator scales and translates each feature individually such\n that it is in the given range on the training set, i.e. between\n zero and ... | Transform features by scaling each feature to a given range.
This estimator scales and translates each feature individually such
that it is in the given range on the training set, i.e. between
zero and one.
The transformation is given by (when ``axis=0``)::
X_std = (X - X.min(axis=0)) / (X.max(axis=0) - X.min(ax... | mars/learn/preprocessing/_data.py | minmax_scale | hxri/mars | 2,413 | python | def minmax_scale(X, feature_range=(0, 1), *, axis=0, copy=True, session=None, run_kwargs=None):
'Transform features by scaling each feature to a given range.\n\n This estimator scales and translates each feature individually such\n that it is in the given range on the training set, i.e. between\n zero and ... | def minmax_scale(X, feature_range=(0, 1), *, axis=0, copy=True, session=None, run_kwargs=None):
'Transform features by scaling each feature to a given range.\n\n This estimator scales and translates each feature individually such\n that it is in the given range on the training set, i.e. between\n zero and ... |
1c570e752ae4cfad848488343810a2e7beffdc60aca2e16ea86aa791a10a346a | def _reset(self):
'Reset internal data-dependent state of the scaler, if necessary.\n\n __init__ parameters are not touched.\n '
if hasattr(self, 'scale_'):
del self.scale_
del self.min_
del self.n_samples_seen_
del self.data_min_
del self.data_max_
... | Reset internal data-dependent state of the scaler, if necessary.
__init__ parameters are not touched. | mars/learn/preprocessing/_data.py | _reset | hxri/mars | 2,413 | python | def _reset(self):
'Reset internal data-dependent state of the scaler, if necessary.\n\n __init__ parameters are not touched.\n '
if hasattr(self, 'scale_'):
del self.scale_
del self.min_
del self.n_samples_seen_
del self.data_min_
del self.data_max_
... | def _reset(self):
'Reset internal data-dependent state of the scaler, if necessary.\n\n __init__ parameters are not touched.\n '
if hasattr(self, 'scale_'):
del self.scale_
del self.min_
del self.n_samples_seen_
del self.data_min_
del self.data_max_
... |
f961568a310dfc95039c22d76f15f7428eba0da5e485d2b53d1eb9b86479af19 | def fit(self, X, y=None, session=None, run_kwargs=None):
'Compute the minimum and maximum to be used for later scaling.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n The data used to compute the per-feature minimum and maximum\n used for l... | Compute the minimum and maximum to be used for later scaling.
Parameters
----------
X : array-like of shape (n_samples, n_features)
The data used to compute the per-feature minimum and maximum
used for later scaling along the features axis.
y : None
Ignored.
Returns
-------
self : object
Fitted scale... | mars/learn/preprocessing/_data.py | fit | hxri/mars | 2,413 | python | def fit(self, X, y=None, session=None, run_kwargs=None):
'Compute the minimum and maximum to be used for later scaling.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n The data used to compute the per-feature minimum and maximum\n used for l... | def fit(self, X, y=None, session=None, run_kwargs=None):
'Compute the minimum and maximum to be used for later scaling.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n The data used to compute the per-feature minimum and maximum\n used for l... |
e91b3e0f3a4996dd8aff4ae32e4842ddd3732ef53e84ac8fd931750f5ec89d7a | def partial_fit(self, X, y=None, session=None, run_kwargs=None):
'Online computation of min and max on X for later scaling.\n\n All of X is processed as a single batch. This is intended for cases\n when :meth:`fit` is not feasible due to very large number of\n `n_samples` or because X is read f... | Online computation of min and max on X for later scaling.
All of X is processed as a single batch. This is intended for cases
when :meth:`fit` is not feasible due to very large number of
`n_samples` or because X is read from a continuous stream.
Parameters
----------
X : array-like of shape (n_samples, n_features)
... | mars/learn/preprocessing/_data.py | partial_fit | hxri/mars | 2,413 | python | def partial_fit(self, X, y=None, session=None, run_kwargs=None):
'Online computation of min and max on X for later scaling.\n\n All of X is processed as a single batch. This is intended for cases\n when :meth:`fit` is not feasible due to very large number of\n `n_samples` or because X is read f... | def partial_fit(self, X, y=None, session=None, run_kwargs=None):
'Online computation of min and max on X for later scaling.\n\n All of X is processed as a single batch. This is intended for cases\n when :meth:`fit` is not feasible due to very large number of\n `n_samples` or because X is read f... |
9073daa309a2f98b9343fd69f5629568a46b56d673f27a1f62f257865b313c97 | def transform(self, X, session=None, run_kwargs=None):
'Scale features of X according to feature_range.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Input data that will be transformed.\n\n Returns\n -------\n Xt : ndarray of sh... | Scale features of X according to feature_range.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data that will be transformed.
Returns
-------
Xt : ndarray of shape (n_samples, n_features)
Transformed data. | mars/learn/preprocessing/_data.py | transform | hxri/mars | 2,413 | python | def transform(self, X, session=None, run_kwargs=None):
'Scale features of X according to feature_range.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Input data that will be transformed.\n\n Returns\n -------\n Xt : ndarray of sh... | def transform(self, X, session=None, run_kwargs=None):
'Scale features of X according to feature_range.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Input data that will be transformed.\n\n Returns\n -------\n Xt : ndarray of sh... |
d24e0258a9f81455593c87b356c18926b959101dad9bbacb11e80c7ec500c014 | def inverse_transform(self, X, session=None, run_kwargs=None):
'Undo the scaling of X according to feature_range.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Input data that will be transformed. It cannot be sparse.\n\n Returns\n ----... | Undo the scaling of X according to feature_range.
Parameters
----------
X : array-like of shape (n_samples, n_features)
Input data that will be transformed. It cannot be sparse.
Returns
-------
Xt : ndarray of shape (n_samples, n_features)
Transformed data. | mars/learn/preprocessing/_data.py | inverse_transform | hxri/mars | 2,413 | python | def inverse_transform(self, X, session=None, run_kwargs=None):
'Undo the scaling of X according to feature_range.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Input data that will be transformed. It cannot be sparse.\n\n Returns\n ----... | def inverse_transform(self, X, session=None, run_kwargs=None):
'Undo the scaling of X according to feature_range.\n\n Parameters\n ----------\n X : array-like of shape (n_samples, n_features)\n Input data that will be transformed. It cannot be sparse.\n\n Returns\n ----... |
f2d7bcd43a249d2dab38a906f720512f446896ba009a970a14cf98d43778090a | def model_fn(model_dir):
'Load the PyTorch model from the `model_dir` directory.'
print('Loading model.')
model_info = {}
model_info_path = os.path.join(model_dir, 'model_info.pth')
with open(model_info_path, 'rb') as f:
model_info = torch.load(f)
print('model_info: {}'.format(model_info... | Load the PyTorch model from the `model_dir` directory. | Project/train/train.py | model_fn | pfrapp/sagemaker-deployment | 0 | python | def model_fn(model_dir):
print('Loading model.')
model_info = {}
model_info_path = os.path.join(model_dir, 'model_info.pth')
with open(model_info_path, 'rb') as f:
model_info = torch.load(f)
print('model_info: {}'.format(model_info))
device = torch.device(('cuda' if torch.cuda.is_av... | def model_fn(model_dir):
print('Loading model.')
model_info = {}
model_info_path = os.path.join(model_dir, 'model_info.pth')
with open(model_info_path, 'rb') as f:
model_info = torch.load(f)
print('model_info: {}'.format(model_info))
device = torch.device(('cuda' if torch.cuda.is_av... |
c1de656b710592176a864f534f2dd3c677d367db031e670d307e123ea8b7d84c | def train(model, train_loader, epochs, optimizer, loss_fn, device):
'\n This is the training method that is called by the PyTorch training script. The parameters\n passed are as follows:\n model - The PyTorch model that we wish to train.\n train_loader - The PyTorch DataLoader that should be used... | This is the training method that is called by the PyTorch training script. The parameters
passed are as follows:
model - The PyTorch model that we wish to train.
train_loader - The PyTorch DataLoader that should be used during training.
epochs - The total number of epochs to train for.
optimizer - The o... | Project/train/train.py | train | pfrapp/sagemaker-deployment | 0 | python | def train(model, train_loader, epochs, optimizer, loss_fn, device):
'\n This is the training method that is called by the PyTorch training script. The parameters\n passed are as follows:\n model - The PyTorch model that we wish to train.\n train_loader - The PyTorch DataLoader that should be used... | def train(model, train_loader, epochs, optimizer, loss_fn, device):
'\n This is the training method that is called by the PyTorch training script. The parameters\n passed are as follows:\n model - The PyTorch model that we wish to train.\n train_loader - The PyTorch DataLoader that should be used... |
3ba99e37009a1bfe848635f4082260512ca2e1f4e0fb6ed7ee0332c3c9f36b28 | def _get_waze_distance(self, Device, DeviceFmZone, from_lat, from_long, to_lat, to_long, route_from):
'\n Example output:\n Time 72.42 minutes, distance 121.33 km.\n (72.41666666666667, 121.325)\n\n See https://github.com/home-assistant/home-assistant/blob\n /master/homeas... | Example output:
Time 72.42 minutes, distance 121.33 km.
(72.41666666666667, 121.325)
See https://github.com/home-assistant/home-assistant/blob
/master/homeassistant/components/sensor/waze_travel_time.py
See https://github.com/kovacsbalu/WazeRouteCalculator | custom_components/icloud3/support/waze - Copy.py | _get_waze_distance | gcobb321/icloud3_v3 | 0 | python | def _get_waze_distance(self, Device, DeviceFmZone, from_lat, from_long, to_lat, to_long, route_from):
'\n Example output:\n Time 72.42 minutes, distance 121.33 km.\n (72.41666666666667, 121.325)\n\n See https://github.com/home-assistant/home-assistant/blob\n /master/homeas... | def _get_waze_distance(self, Device, DeviceFmZone, from_lat, from_long, to_lat, to_long, route_from):
'\n Example output:\n Time 72.42 minutes, distance 121.33 km.\n (72.41666666666667, 121.325)\n\n See https://github.com/home-assistant/home-assistant/blob\n /master/homeas... |
69f8b79f4b0dedbcfd9d33f0b67a7f0917d4a8a8cfa8909eae8a27ad9fce9b8a | def _set_waze_not_available_error(self, err):
' Turn Waze off if connection error '
if (instr(err, 'www.waze.com') and instr(err, 'HTTPSConnectionPool') and instr(err, 'Max retries exceeded') and instr(err, 'TIMEOUT')):
self.waze_status = WAZE_NOT_USED
event_msg = 'iCloud3 Error > Waze Server Er... | Turn Waze off if connection error | custom_components/icloud3/support/waze - Copy.py | _set_waze_not_available_error | gcobb321/icloud3_v3 | 0 | python | def _set_waze_not_available_error(self, err):
' '
if (instr(err, 'www.waze.com') and instr(err, 'HTTPSConnectionPool') and instr(err, 'Max retries exceeded') and instr(err, 'TIMEOUT')):
self.waze_status = WAZE_NOT_USED
event_msg = 'iCloud3 Error > Waze Server Error > Connection error accessing ... | def _set_waze_not_available_error(self, err):
' '
if (instr(err, 'www.waze.com') and instr(err, 'HTTPSConnectionPool') and instr(err, 'Max retries exceeded') and instr(err, 'TIMEOUT')):
self.waze_status = WAZE_NOT_USED
event_msg = 'iCloud3 Error > Waze Server Error > Connection error accessing ... |
1273e908719cbf694c6b876795a3fdae8db55fb1ae7af810739357398ec83543 | def format_waze_time_msg(self, waze_time_from_zone):
'\n Return the message displayed in the waze time field ►►\n '
if (self.waze_status == WAZE_USED):
t = (waze_time_from_zone * 60)
r = 0
if (t > 180):
(t, r) = divmod(t, 60)
t = ((t + 1) if (r > 30)... | Return the message displayed in the waze time field ►► | custom_components/icloud3/support/waze - Copy.py | format_waze_time_msg | gcobb321/icloud3_v3 | 0 | python | def format_waze_time_msg(self, waze_time_from_zone):
'\n \n '
if (self.waze_status == WAZE_USED):
t = (waze_time_from_zone * 60)
r = 0
if (t > 180):
(t, r) = divmod(t, 60)
t = ((t + 1) if (r > 30) else t)
t = (t * 60)
waze_time_ms... | def format_waze_time_msg(self, waze_time_from_zone):
'\n \n '
if (self.waze_status == WAZE_USED):
t = (waze_time_from_zone * 60)
r = 0
if (t > 180):
(t, r) = divmod(t, 60)
t = ((t + 1) if (r > 30) else t)
t = (t * 60)
waze_time_ms... |
474e0aa7402eb865ed9aff60f13993cbe3afc374dc781983910a39d06ada9a3d | def __init__(self, header_bytes: bytes) -> None:
'Initialize an IPv4 header.'
ipv4_header_first_word = unpack('!BBH', header_bytes[:4])
ipv4_header_second_word = unpack('!HH', header_bytes[4:8])
ipv4_header_third_word = unpack('!BBH', header_bytes[8:12])
self.version = (ipv4_header_first_word[0] >> ... | Initialize an IPv4 header. | networking/ipv4.py | __init__ | yossi-r/geneve-proxy | 37 | python | def __init__(self, header_bytes: bytes) -> None:
ipv4_header_first_word = unpack('!BBH', header_bytes[:4])
ipv4_header_second_word = unpack('!HH', header_bytes[4:8])
ipv4_header_third_word = unpack('!BBH', header_bytes[8:12])
self.version = (ipv4_header_first_word[0] >> 4)
if (self.version != 4... | def __init__(self, header_bytes: bytes) -> None:
ipv4_header_first_word = unpack('!BBH', header_bytes[:4])
ipv4_header_second_word = unpack('!HH', header_bytes[4:8])
ipv4_header_third_word = unpack('!BBH', header_bytes[8:12])
self.version = (ipv4_header_first_word[0] >> 4)
if (self.version != 4... |
7b9c2445022ab52d3dbccd3c8f8dbdc2c74cb15d77eb79d4a8ffa2ee328ed947 | def swap_source_dest(self) -> None:
'Store the source IP in the destination field and vice versa.'
tmp = self.source_ip
self.source_ip = self.destination_ip
self.destination_ip = tmp | Store the source IP in the destination field and vice versa. | networking/ipv4.py | swap_source_dest | yossi-r/geneve-proxy | 37 | python | def swap_source_dest(self) -> None:
tmp = self.source_ip
self.source_ip = self.destination_ip
self.destination_ip = tmp | def swap_source_dest(self) -> None:
tmp = self.source_ip
self.source_ip = self.destination_ip
self.destination_ip = tmp<|docstring|>Store the source IP in the destination field and vice versa.<|endoftext|> |
ea93e0014ae7656eea88f54cf9bc5a420d214ec22bea73184d4503fb4e824f68 | def update_checksum(self) -> None:
'Update the checksum field with a newly calculated checksum.'
self.header_checksum = self.calculate_checksum() | Update the checksum field with a newly calculated checksum. | networking/ipv4.py | update_checksum | yossi-r/geneve-proxy | 37 | python | def update_checksum(self) -> None:
self.header_checksum = self.calculate_checksum() | def update_checksum(self) -> None:
self.header_checksum = self.calculate_checksum()<|docstring|>Update the checksum field with a newly calculated checksum.<|endoftext|> |
3dd59a6032974e60177005700ef35933f48f8508b51a43d0f01bff1228130c17 | def calculate_checksum(self) -> bytes:
'Calculate the checksum for this header.'
header_bytes = self.as_bytes(zero_checksum=True)
return self.calculate_checksum_for_bytes(header_bytes) | Calculate the checksum for this header. | networking/ipv4.py | calculate_checksum | yossi-r/geneve-proxy | 37 | python | def calculate_checksum(self) -> bytes:
header_bytes = self.as_bytes(zero_checksum=True)
return self.calculate_checksum_for_bytes(header_bytes) | def calculate_checksum(self) -> bytes:
header_bytes = self.as_bytes(zero_checksum=True)
return self.calculate_checksum_for_bytes(header_bytes)<|docstring|>Calculate the checksum for this header.<|endoftext|> |
65d7c9cb5161dcaed997adf5ab9c9725f78cbe85f7cda8f621f113cbe7e1cde8 | def as_bytes(self, zero_checksum=False) -> bytes:
'Return the byte representation of this IPv4 header.'
byte_array = bytearray((self.ihl * 4))
pack_into('!BBH', byte_array, 0, ((self.version << 4) + self.ihl), ((self.dscp << 2) + self.ecn), self.total_length)
pack_into('!HH', byte_array, 4, self.identif... | Return the byte representation of this IPv4 header. | networking/ipv4.py | as_bytes | yossi-r/geneve-proxy | 37 | python | def as_bytes(self, zero_checksum=False) -> bytes:
byte_array = bytearray((self.ihl * 4))
pack_into('!BBH', byte_array, 0, ((self.version << 4) + self.ihl), ((self.dscp << 2) + self.ecn), self.total_length)
pack_into('!HH', byte_array, 4, self.identification, (self.flags << (13 + self.fragment_offset)))... | def as_bytes(self, zero_checksum=False) -> bytes:
byte_array = bytearray((self.ihl * 4))
pack_into('!BBH', byte_array, 0, ((self.version << 4) + self.ihl), ((self.dscp << 2) + self.ecn), self.total_length)
pack_into('!HH', byte_array, 4, self.identification, (self.flags << (13 + self.fragment_offset)))... |
96c49d9f73d33063d2cddf164cda90b0e84497dab42b2eea72c4523036e7aae2 | def __repr__(self) -> str:
'Generate a string representation for this IPv4 header.'
human_source_ip = ipaddress.IPv4Address(self.source_ip)
human_destination_ip = ipaddress.IPv4Address(self.destination_ip)
return f'IPv4 header with a header size of {(self.ihl * 4)} and a total length of {self.total_leng... | Generate a string representation for this IPv4 header. | networking/ipv4.py | __repr__ | yossi-r/geneve-proxy | 37 | python | def __repr__(self) -> str:
human_source_ip = ipaddress.IPv4Address(self.source_ip)
human_destination_ip = ipaddress.IPv4Address(self.destination_ip)
return f'IPv4 header with a header size of {(self.ihl * 4)} and a total length of {self.total_length} bytes. Version: {self.version}, Flags: {self.flags:b... | def __repr__(self) -> str:
human_source_ip = ipaddress.IPv4Address(self.source_ip)
human_destination_ip = ipaddress.IPv4Address(self.destination_ip)
return f'IPv4 header with a header size of {(self.ihl * 4)} and a total length of {self.total_length} bytes. Version: {self.version}, Flags: {self.flags:b... |
8edcedee85455796ed95cd6612dee5de8fdadedbed06d6fd7b7ccf27dd485ad6 | @classmethod
def verify_checksum(cls, header_bytes: bytes) -> bool:
'Verify the IPv4 checksum for the provided header.'
return (cls.calculate_checksum_for_bytes(header_bytes) == 0) | Verify the IPv4 checksum for the provided header. | networking/ipv4.py | verify_checksum | yossi-r/geneve-proxy | 37 | python | @classmethod
def verify_checksum(cls, header_bytes: bytes) -> bool:
return (cls.calculate_checksum_for_bytes(header_bytes) == 0) | @classmethod
def verify_checksum(cls, header_bytes: bytes) -> bool:
return (cls.calculate_checksum_for_bytes(header_bytes) == 0)<|docstring|>Verify the IPv4 checksum for the provided header.<|endoftext|> |
cd9d65f7295eac690e9ec3b9c9b1e3100a5ded2dff7c42494da87f685dcb77ae | @classmethod
def calculate_checksum_for_bytes(cls, header_bytes: bytes) -> int:
'Calculate the checksum for the provided header.'
def carry_around_add(a, b):
c = (a + b)
return ((c & 65535) + (c >> 16))
s = 0
for i in range(0, len(header_bytes), 2):
w = (header_bytes[(i + 1)] + ... | Calculate the checksum for the provided header. | networking/ipv4.py | calculate_checksum_for_bytes | yossi-r/geneve-proxy | 37 | python | @classmethod
def calculate_checksum_for_bytes(cls, header_bytes: bytes) -> int:
def carry_around_add(a, b):
c = (a + b)
return ((c & 65535) + (c >> 16))
s = 0
for i in range(0, len(header_bytes), 2):
w = (header_bytes[(i + 1)] + (header_bytes[i] << 8))
s = carry_around_... | @classmethod
def calculate_checksum_for_bytes(cls, header_bytes: bytes) -> int:
def carry_around_add(a, b):
c = (a + b)
return ((c & 65535) + (c >> 16))
s = 0
for i in range(0, len(header_bytes), 2):
w = (header_bytes[(i + 1)] + (header_bytes[i] << 8))
s = carry_around_... |
152a5a59be41cbd03f31b3581b7e6c2da7477be561f4a3142e920927a265575c | def items_to_matrix(self):
'Initialize matrix'
for item in self.items:
row = int(item[0])
column = int(item[1])
self.matrix[((row - 1), (column - 1))] = int(item[2]) | Initialize matrix | recommender.py | items_to_matrix | ckpwinters/NaiveRecommender | 0 | python | def items_to_matrix(self):
for item in self.items:
row = int(item[0])
column = int(item[1])
self.matrix[((row - 1), (column - 1))] = int(item[2]) | def items_to_matrix(self):
for item in self.items:
row = int(item[0])
column = int(item[1])
self.matrix[((row - 1), (column - 1))] = int(item[2])<|docstring|>Initialize matrix<|endoftext|> |
1b8f1c966276218c5c3535baac1a6bd8307e6520c20362d5ac5f51ab6f9d3daf | def validate(self, data_sets):
'\n Method to iterate over a list of independent datasets via the iter_data\n generator method so as to apply the holdout technique to each dataset \n and then save the results.\n '
(self.perf, self.cert, radii) = zip(*self.iter_data(data_sets))
sel... | Method to iterate over a list of independent datasets via the iter_data
generator method so as to apply the holdout technique to each dataset
and then save the results. | dist-robust-portfolio/SimSet2.py | validate | MOSEK/Tutorials | 66 | python | def validate(self, data_sets):
'\n Method to iterate over a list of independent datasets via the iter_data\n generator method so as to apply the holdout technique to each dataset \n and then save the results.\n '
(self.perf, self.cert, radii) = zip(*self.iter_data(data_sets))
sel... | def validate(self, data_sets):
'\n Method to iterate over a list of independent datasets via the iter_data\n generator method so as to apply the holdout technique to each dataset \n and then save the results.\n '
(self.perf, self.cert, radii) = zip(*self.iter_data(data_sets))
sel... |
089c07105f22ef15c78fcc260a42c316180cf1e80b81779eb439330195908f4d | def simulate(self, data):
'\n Method called within the iter_data generator.\n\n Returns\n out_perf: out-of-sample performance calculated with validation data\n cert: performance certificate (optimal objective for M)\n eps_holdout: radius selected from holdout method\n '
... | Method called within the iter_data generator.
Returns
out_perf: out-of-sample performance calculated with validation data
cert: performance certificate (optimal objective for M)
eps_holdout: radius selected from holdout method | dist-robust-portfolio/SimSet2.py | simulate | MOSEK/Tutorials | 66 | python | def simulate(self, data):
'\n Method called within the iter_data generator.\n\n Returns\n out_perf: out-of-sample performance calculated with validation data\n cert: performance certificate (optimal objective for M)\n eps_holdout: radius selected from holdout method\n '
... | def simulate(self, data):
'\n Method called within the iter_data generator.\n\n Returns\n out_perf: out-of-sample performance calculated with validation data\n cert: performance certificate (optimal objective for M)\n eps_holdout: radius selected from holdout method\n '
... |
34c03366a22373ae80d04543f9c75cefef326e34c0a68e1d40d31f51719442dd | def solve(self, epsilon):
'\n Method called within the iter_radius generator.\n\n Returns\n out_perf: SA-approx of out-of-sample performance using test data\n x: Portfolio weights\n t: Tau\n self.M.primalObjValue(): performance certificate\n '
self.eps.setValue(e... | Method called within the iter_radius generator.
Returns
out_perf: SA-approx of out-of-sample performance using test data
x: Portfolio weights
t: Tau
self.M.primalObjValue(): performance certificate | dist-robust-portfolio/SimSet2.py | solve | MOSEK/Tutorials | 66 | python | def solve(self, epsilon):
'\n Method called within the iter_radius generator.\n\n Returns\n out_perf: SA-approx of out-of-sample performance using test data\n x: Portfolio weights\n t: Tau\n self.M.primalObjValue(): performance certificate\n '
self.eps.setValue(e... | def solve(self, epsilon):
'\n Method called within the iter_radius generator.\n\n Returns\n out_perf: SA-approx of out-of-sample performance using test data\n x: Portfolio weights\n t: Tau\n self.M.primalObjValue(): performance certificate\n '
self.eps.setValue(e... |
0b44d47be968cb809842aeb060e88866913663e306513fe35c60efd8a95d93f3 | def simulate(self, data):
'\n Method called within the iter_data generator. This method overwrites\n the one defined in the SimSet2_Holdout class.\n\n Returns\n out_perf: out-of-sample performance calculated with validation data\n cert: performance certificate (optimal objective f... | Method called within the iter_data generator. This method overwrites
the one defined in the SimSet2_Holdout class.
Returns
out_perf: out-of-sample performance calculated with validation data
cert: performance certificate (optimal objective for M_N)
eps_kFold: radius selected from k-Fold method | dist-robust-portfolio/SimSet2.py | simulate | MOSEK/Tutorials | 66 | python | def simulate(self, data):
'\n Method called within the iter_data generator. This method overwrites\n the one defined in the SimSet2_Holdout class.\n\n Returns\n out_perf: out-of-sample performance calculated with validation data\n cert: performance certificate (optimal objective f... | def simulate(self, data):
'\n Method called within the iter_data generator. This method overwrites\n the one defined in the SimSet2_Holdout class.\n\n Returns\n out_perf: out-of-sample performance calculated with validation data\n cert: performance certificate (optimal objective f... |
f26bc56eaf7be489eaefb582cf84f70b7597330d80607fcd7a7cc5a60047d527 | def _simulate(self, data):
'\n Method to perform the holdout technique for a given dataset. This \n is called k times within each call to the simulate method. Works\n analogously to the simulate method of SimSet2_Holdout class.\n\n Returns:\n eps_holdout: WasRadius selected in one... | Method to perform the holdout technique for a given dataset. This
is called k times within each call to the simulate method. Works
analogously to the simulate method of SimSet2_Holdout class.
Returns:
eps_holdout: WasRadius selected in one holdout run | dist-robust-portfolio/SimSet2.py | _simulate | MOSEK/Tutorials | 66 | python | def _simulate(self, data):
'\n Method to perform the holdout technique for a given dataset. This \n is called k times within each call to the simulate method. Works\n analogously to the simulate method of SimSet2_Holdout class.\n\n Returns:\n eps_holdout: WasRadius selected in one... | def _simulate(self, data):
'\n Method to perform the holdout technique for a given dataset. This \n is called k times within each call to the simulate method. Works\n analogously to the simulate method of SimSet2_Holdout class.\n\n Returns:\n eps_holdout: WasRadius selected in one... |
2b0dce0786bb084cf487c76b2a8ef36a8ac77c92312f1b645fe2be0d209b79a2 | def __init__(self, layer_ref, cost, weight_shape):
'\n Constructor\n :param layer_ref: Reference to the layer object in TensorFlow\n :param cost: Cost of the layer\n :param weight_shape: Shape of the output activation of the layer\n '
self.layer_ref = layer_ref
self.cost =... | Constructor
:param layer_ref: Reference to the layer object in TensorFlow
:param cost: Cost of the layer
:param weight_shape: Shape of the output activation of the layer | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | __init__ | Abhishekvats1997/aimet | 945 | python | def __init__(self, layer_ref, cost, weight_shape):
'\n Constructor\n :param layer_ref: Reference to the layer object in TensorFlow\n :param cost: Cost of the layer\n :param weight_shape: Shape of the output activation of the layer\n '
self.layer_ref = layer_ref
self.cost =... | def __init__(self, layer_ref, cost, weight_shape):
'\n Constructor\n :param layer_ref: Reference to the layer object in TensorFlow\n :param cost: Cost of the layer\n :param weight_shape: Shape of the output activation of the layer\n '
self.layer_ref = layer_ref
self.cost =... |
eb64cf952ebaf8fbeb24db7dc5526d8c5a33ba406853e7962b7a895af72a0f75 | def __init__(self, graph, checkpoint, metric, output_file='./svd_graph', svd_type='svd', num_layers=0, layers=None, layer_ranks=None, num_ranks=20, gpu=True, debug=False, no_evaluation=False, layer_selection_threshold=0.6):
"\n Constructor for the Svd class\n\n Constructs the Svd class from a set of o... | Constructor for the Svd class
Constructs the Svd class from a set of options passed in at construction. The class takes
a number of named arguments which are detailed below.
:param graph: The file path to the meta graph.
:param checkpoint: The file path to the tensorflow checkpoint file.
:param metric: The metric to ... | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | __init__ | Abhishekvats1997/aimet | 945 | python | def __init__(self, graph, checkpoint, metric, output_file='./svd_graph', svd_type='svd', num_layers=0, layers=None, layer_ranks=None, num_ranks=20, gpu=True, debug=False, no_evaluation=False, layer_selection_threshold=0.6):
"\n Constructor for the Svd class\n\n Constructs the Svd class from a set of o... | def __init__(self, graph, checkpoint, metric, output_file='./svd_graph', svd_type='svd', num_layers=0, layers=None, layer_ranks=None, num_ranks=20, gpu=True, debug=False, no_evaluation=False, layer_selection_threshold=0.6):
"\n Constructor for the Svd class\n\n Constructs the Svd class from a set of o... |
e8d337297746251977400b5e8ee5dbcb6697a59af76a4a3ec4de78702f3c2ecb | def _compute_per_layer_compression_ratio(self, split_layers_shape, output_shape, original_layer_shape, op_type):
'\n Updates the per layer statistics\n\n :param orig_layer: The layer before it was split\n :param split_layers: List of split layers\n :return: The compression ratio of split... | Updates the per layer statistics
:param orig_layer: The layer before it was split
:param split_layers: List of split layers
:return: The compression ratio of split layers | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | _compute_per_layer_compression_ratio | Abhishekvats1997/aimet | 945 | python | def _compute_per_layer_compression_ratio(self, split_layers_shape, output_shape, original_layer_shape, op_type):
'\n Updates the per layer statistics\n\n :param orig_layer: The layer before it was split\n :param split_layers: List of split layers\n :return: The compression ratio of split... | def _compute_per_layer_compression_ratio(self, split_layers_shape, output_shape, original_layer_shape, op_type):
'\n Updates the per layer statistics\n\n :param orig_layer: The layer before it was split\n :param split_layers: List of split layers\n :return: The compression ratio of split... |
98ec91867aa3635539d526d22a3b79c2acf8295152a43f151d00a354e9dc0879 | @staticmethod
def _reset_session(sess):
'\n Reset the given tf.compat.v1.Session\n :param sess: tf.compat.v1.Session\n :return: None\n '
tf.compat.v1.reset_default_graph()
sess.close() | Reset the given tf.compat.v1.Session
:param sess: tf.compat.v1.Session
:return: None | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | _reset_session | Abhishekvats1997/aimet | 945 | python | @staticmethod
def _reset_session(sess):
'\n Reset the given tf.compat.v1.Session\n :param sess: tf.compat.v1.Session\n :return: None\n '
tf.compat.v1.reset_default_graph()
sess.close() | @staticmethod
def _reset_session(sess):
'\n Reset the given tf.compat.v1.Session\n :param sess: tf.compat.v1.Session\n :return: None\n '
tf.compat.v1.reset_default_graph()
sess.close()<|docstring|>Reset the given tf.compat.v1.Session
:param sess: tf.compat.v1.Session
:return: Non... |
b9b49c99a12d4e51378ffdddf1276cf46c681786d7e22d3fa4000272783c1fc6 | @staticmethod
def _load_graph(graph, meta_graph, checkpoint):
'\n Load a graph and checkpoint and create a new tf.compat.v1.Session\n :param graph: TF graph\n :param meta_graph: Meta file\n :param checkpoint: Checkpoint file\n :return: Newly created session\n '
logger.i... | Load a graph and checkpoint and create a new tf.compat.v1.Session
:param graph: TF graph
:param meta_graph: Meta file
:param checkpoint: Checkpoint file
:return: Newly created session | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | _load_graph | Abhishekvats1997/aimet | 945 | python | @staticmethod
def _load_graph(graph, meta_graph, checkpoint):
'\n Load a graph and checkpoint and create a new tf.compat.v1.Session\n :param graph: TF graph\n :param meta_graph: Meta file\n :param checkpoint: Checkpoint file\n :return: Newly created session\n '
logger.i... | @staticmethod
def _load_graph(graph, meta_graph, checkpoint):
'\n Load a graph and checkpoint and create a new tf.compat.v1.Session\n :param graph: TF graph\n :param meta_graph: Meta file\n :param checkpoint: Checkpoint file\n :return: Newly created session\n '
logger.i... |
7608195cc7039298047fe8ec71e75f8aa607603e635f3a89516f1dd942fe13e8 | @staticmethod
def _get_layer_type(op):
'\n Converts TF layer types into corresponding PyMo layer enumerated values\n :param op: TF op\n :return: PyMo enumerated value corresponding to the type of op\n '
if (op.type in _SVD_LAYER_TYPES):
return _SVD_LAYER_TYPES[op.type]
re... | Converts TF layer types into corresponding PyMo layer enumerated values
:param op: TF op
:return: PyMo enumerated value corresponding to the type of op | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | _get_layer_type | Abhishekvats1997/aimet | 945 | python | @staticmethod
def _get_layer_type(op):
'\n Converts TF layer types into corresponding PyMo layer enumerated values\n :param op: TF op\n :return: PyMo enumerated value corresponding to the type of op\n '
if (op.type in _SVD_LAYER_TYPES):
return _SVD_LAYER_TYPES[op.type]
re... | @staticmethod
def _get_layer_type(op):
'\n Converts TF layer types into corresponding PyMo layer enumerated values\n :param op: TF op\n :return: PyMo enumerated value corresponding to the type of op\n '
if (op.type in _SVD_LAYER_TYPES):
return _SVD_LAYER_TYPES[op.type]
re... |
21c0cd4d787a65ad70f0f4f03b49816a4b7b2ebcfef0a6c5c9e0190a469da652 | @staticmethod
def _pick_compression_layers(sess, cost_metric, layer_select_scheme, **kwargs):
'\n Pick layers for SVD compression given parameters\n :param sess: tf.compat.v1.Session\n :param cost_metric: Metric to use for evaluating layer cost (either in terms of memory or mac)\n :param... | Pick layers for SVD compression given parameters
:param sess: tf.compat.v1.Session
:param cost_metric: Metric to use for evaluating layer cost (either in terms of memory or mac)
:param layer_select_scheme: Layer selection scheme to use
:param kwargs: Keyword arguments that depend on which layer selection scheme is spec... | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | _pick_compression_layers | Abhishekvats1997/aimet | 945 | python | @staticmethod
def _pick_compression_layers(sess, cost_metric, layer_select_scheme, **kwargs):
'\n Pick layers for SVD compression given parameters\n :param sess: tf.compat.v1.Session\n :param cost_metric: Metric to use for evaluating layer cost (either in terms of memory or mac)\n :param... | @staticmethod
def _pick_compression_layers(sess, cost_metric, layer_select_scheme, **kwargs):
'\n Pick layers for SVD compression given parameters\n :param sess: tf.compat.v1.Session\n :param cost_metric: Metric to use for evaluating layer cost (either in terms of memory or mac)\n :param... |
ae27db0694e50832bd25831b50f91ba094ac488858f74e7540c94b7906a4feed | @staticmethod
def _create_layer_attributes_list(ops_to_use, sess):
'\n Creates list of layer attributes given a set of TF ops\n :param ops_to_use: TF ops to collect layer attributes for\n :param sess: tf.compat.v1.Session to use\n :return: Created list of layer attributes\n '
... | Creates list of layer attributes given a set of TF ops
:param ops_to_use: TF ops to collect layer attributes for
:param sess: tf.compat.v1.Session to use
:return: Created list of layer attributes | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | _create_layer_attributes_list | Abhishekvats1997/aimet | 945 | python | @staticmethod
def _create_layer_attributes_list(ops_to_use, sess):
'\n Creates list of layer attributes given a set of TF ops\n :param ops_to_use: TF ops to collect layer attributes for\n :param sess: tf.compat.v1.Session to use\n :return: Created list of layer attributes\n '
... | @staticmethod
def _create_layer_attributes_list(ops_to_use, sess):
'\n Creates list of layer attributes given a set of TF ops\n :param ops_to_use: TF ops to collect layer attributes for\n :param sess: tf.compat.v1.Session to use\n :return: Created list of layer attributes\n '
... |
072a26c5a5d43c11ea97622d882e823f519f30079397c796edcfe05596b7800f | @staticmethod
def _compute_network_cost(layer_attributes_list):
'\n Compute aggregate cost of the layers included in the layer attributes list\n :param layer_attributes_list: List of layer attributes\n :return: Computed cost\n '
mac_cost = 0
mem_cost = 0
for layer_attributes ... | Compute aggregate cost of the layers included in the layer attributes list
:param layer_attributes_list: List of layer attributes
:return: Computed cost | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | _compute_network_cost | Abhishekvats1997/aimet | 945 | python | @staticmethod
def _compute_network_cost(layer_attributes_list):
'\n Compute aggregate cost of the layers included in the layer attributes list\n :param layer_attributes_list: List of layer attributes\n :return: Computed cost\n '
mac_cost = 0
mem_cost = 0
for layer_attributes ... | @staticmethod
def _compute_network_cost(layer_attributes_list):
'\n Compute aggregate cost of the layers included in the layer attributes list\n :param layer_attributes_list: List of layer attributes\n :return: Computed cost\n '
mac_cost = 0
mem_cost = 0
for layer_attributes ... |
d01db2f0cfe2d83968f85f44e279a19628195d803358a8a73f1eb44541a891ed | @staticmethod
def _compute_layer_cost(weights_shape, output_dims, op_type):
'\n Compute cost of a layer\n :param weights_shape: Shape of the weights of this layer\n :param output_dims: Shape of the output of this layer\n :param op_type: Type of this TF op\n :return: Computed layer... | Compute cost of a layer
:param weights_shape: Shape of the weights of this layer
:param output_dims: Shape of the output of this layer
:param op_type: Type of this TF op
:return: Computed layer cost | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | _compute_layer_cost | Abhishekvats1997/aimet | 945 | python | @staticmethod
def _compute_layer_cost(weights_shape, output_dims, op_type):
'\n Compute cost of a layer\n :param weights_shape: Shape of the weights of this layer\n :param output_dims: Shape of the output of this layer\n :param op_type: Type of this TF op\n :return: Computed layer... | @staticmethod
def _compute_layer_cost(weights_shape, output_dims, op_type):
'\n Compute cost of a layer\n :param weights_shape: Shape of the weights of this layer\n :param output_dims: Shape of the output of this layer\n :param op_type: Type of this TF op\n :return: Computed layer... |
95b7295794ac79c5a383b4f2ab8a3a76f8c0c98e46afa5de674438060bf95605 | def _compute_compression_ratio(self, sess, cost_metric):
'\n Compute compression ratio\n :param sess: tf.compat.v1.Session\n :return: Computed compression ratio\n '
query = core.OpQuery(sess.graph)
compressible_ops = query.get_weight_ops()
compressible_ops = [op for op in com... | Compute compression ratio
:param sess: tf.compat.v1.Session
:return: Computed compression ratio | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | _compute_compression_ratio | Abhishekvats1997/aimet | 945 | python | def _compute_compression_ratio(self, sess, cost_metric):
'\n Compute compression ratio\n :param sess: tf.compat.v1.Session\n :return: Computed compression ratio\n '
query = core.OpQuery(sess.graph)
compressible_ops = query.get_weight_ops()
compressible_ops = [op for op in com... | def _compute_compression_ratio(self, sess, cost_metric):
'\n Compute compression ratio\n :param sess: tf.compat.v1.Session\n :return: Computed compression ratio\n '
query = core.OpQuery(sess.graph)
compressible_ops = query.get_weight_ops()
compressible_ops = [op for op in com... |
9c8b4ec7964d882751bc4cb27e8ce703d5ca5bf9c5c61367d42fbf7a54f6ab69 | def _store_net_stats(self, sess):
'\n Store layer attributes in the PyMo library instance\n :param sess: tf.compat.v1.Session\n :return: None\n '
if (self._metric == CostMetric.memory):
pymo_metric = pymo.COST_TYPE_MEMORY
else:
pymo_metric = pymo.COST_TYPE_MAC
... | Store layer attributes in the PyMo library instance
:param sess: tf.compat.v1.Session
:return: None | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | _store_net_stats | Abhishekvats1997/aimet | 945 | python | def _store_net_stats(self, sess):
'\n Store layer attributes in the PyMo library instance\n :param sess: tf.compat.v1.Session\n :return: None\n '
if (self._metric == CostMetric.memory):
pymo_metric = pymo.COST_TYPE_MEMORY
else:
pymo_metric = pymo.COST_TYPE_MAC
... | def _store_net_stats(self, sess):
'\n Store layer attributes in the PyMo library instance\n :param sess: tf.compat.v1.Session\n :return: None\n '
if (self._metric == CostMetric.memory):
pymo_metric = pymo.COST_TYPE_MEMORY
else:
pymo_metric = pymo.COST_TYPE_MAC
... |
f86c48418271e97debd07ef0aec9e02ad03f8f22f288cf547382d51563f2c338 | def _compute_objective_score(self, model_perf, compression_score):
'\n Compute objective score of a given compression model\n :param model_perf: Performance of compressed model\n :param compression_score: Compression ratio\n :return: Computed objective score\n '
if ((model_per... | Compute objective score of a given compression model
:param model_perf: Performance of compressed model
:param compression_score: Compression ratio
:return: Computed objective score | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | _compute_objective_score | Abhishekvats1997/aimet | 945 | python | def _compute_objective_score(self, model_perf, compression_score):
'\n Compute objective score of a given compression model\n :param model_perf: Performance of compressed model\n :param compression_score: Compression ratio\n :return: Computed objective score\n '
if ((model_per... | def _compute_objective_score(self, model_perf, compression_score):
'\n Compute objective score of a given compression model\n :param model_perf: Performance of compressed model\n :param compression_score: Compression ratio\n :return: Computed objective score\n '
if ((model_per... |
7a8f6283c3794b98ea83335611327ac6ea9f589de5ce3907f981dafcb147881f | def _split_conv_layer(self, sess, svd_ranks, attr, op_name, bias_op_name=None):
'\n Split a given conv layer given a rank\n :param sess: tf.compat.v1.Session\n :param svd_ranks: Rank to split the layer with (two ranks in case of SSVD)\n :param attr: Reference to the corresponding layer a... | Split a given conv layer given a rank
:param sess: tf.compat.v1.Session
:param svd_ranks: Rank to split the layer with (two ranks in case of SSVD)
:param attr: Reference to the corresponding layer attribute
:param op_name: Name of the op to split
:param bias_op_name: Name of the corresponding bias op (if any)
:return: ... | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | _split_conv_layer | Abhishekvats1997/aimet | 945 | python | def _split_conv_layer(self, sess, svd_ranks, attr, op_name, bias_op_name=None):
'\n Split a given conv layer given a rank\n :param sess: tf.compat.v1.Session\n :param svd_ranks: Rank to split the layer with (two ranks in case of SSVD)\n :param attr: Reference to the corresponding layer a... | def _split_conv_layer(self, sess, svd_ranks, attr, op_name, bias_op_name=None):
'\n Split a given conv layer given a rank\n :param sess: tf.compat.v1.Session\n :param svd_ranks: Rank to split the layer with (two ranks in case of SSVD)\n :param attr: Reference to the corresponding layer a... |
7c09478bbec4692a65dc86c6f092e2ddd39dea0d61adc139bb8cbaa77288811d | def _split_fc_layer(self, sess, svd_ranks, op_name, bias_op_name=None):
'\n Split a given conv layer given a rank\n :param sess: tf.compat.v1.Session\n :param svd_ranks: Rank to split the layer with (two ranks in case of SSVD)\n :param op_name: Name of the op to split\n :param bia... | Split a given conv layer given a rank
:param sess: tf.compat.v1.Session
:param svd_ranks: Rank to split the layer with (two ranks in case of SSVD)
:param op_name: Name of the op to split
:param bias_op_name: Name of the corresponding bias op (if any)
:return: None | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | _split_fc_layer | Abhishekvats1997/aimet | 945 | python | def _split_fc_layer(self, sess, svd_ranks, op_name, bias_op_name=None):
'\n Split a given conv layer given a rank\n :param sess: tf.compat.v1.Session\n :param svd_ranks: Rank to split the layer with (two ranks in case of SSVD)\n :param op_name: Name of the op to split\n :param bia... | def _split_fc_layer(self, sess, svd_ranks, op_name, bias_op_name=None):
'\n Split a given conv layer given a rank\n :param sess: tf.compat.v1.Session\n :param svd_ranks: Rank to split the layer with (two ranks in case of SSVD)\n :param op_name: Name of the op to split\n :param bia... |
4e98851bc1a6023c30a9b5b02214f89f111fec8d1b16e076310ad59257db2e83 | def _split_layers(self, sess, rank_index, use_best_ranks):
'\n Split all the selected layers given a rank index\n :param sess: tf.compat.v1.Session\n :param rank_index: Rank index to use for finding the ranks\n :param use_best_ranks: Use the best rank index (for final compressed network)... | Split all the selected layers given a rank index
:param sess: tf.compat.v1.Session
:param rank_index: Rank index to use for finding the ranks
:param use_best_ranks: Use the best rank index (for final compressed network)
:return: None | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | _split_layers | Abhishekvats1997/aimet | 945 | python | def _split_layers(self, sess, rank_index, use_best_ranks):
'\n Split all the selected layers given a rank index\n :param sess: tf.compat.v1.Session\n :param rank_index: Rank index to use for finding the ranks\n :param use_best_ranks: Use the best rank index (for final compressed network)... | def _split_layers(self, sess, rank_index, use_best_ranks):
'\n Split all the selected layers given a rank index\n :param sess: tf.compat.v1.Session\n :param rank_index: Rank index to use for finding the ranks\n :param use_best_ranks: Use the best rank index (for final compressed network)... |
4b0ad270cf653a10c610117b9e409c682fefb2d41778805a37fdbf3642cbe1ed | def _create_compressed_network(self, sess, rank_index, use_best_ranks):
'\n Create a compressed network for a given rank index\n :param sess: tf.compat.v1.Session\n :param rank_index: Rank index to use for finding the ranks\n :param use_best_ranks: Use the best rank index (for final comp... | Create a compressed network for a given rank index
:param sess: tf.compat.v1.Session
:param rank_index: Rank index to use for finding the ranks
:param use_best_ranks: Use the best rank index (for final compressed network)
:return: None | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | _create_compressed_network | Abhishekvats1997/aimet | 945 | python | def _create_compressed_network(self, sess, rank_index, use_best_ranks):
'\n Create a compressed network for a given rank index\n :param sess: tf.compat.v1.Session\n :param rank_index: Rank index to use for finding the ranks\n :param use_best_ranks: Use the best rank index (for final comp... | def _create_compressed_network(self, sess, rank_index, use_best_ranks):
'\n Create a compressed network for a given rank index\n :param sess: tf.compat.v1.Session\n :param rank_index: Rank index to use for finding the ranks\n :param use_best_ranks: Use the best rank index (for final comp... |
d1dbdc870ef1bcd6c0efbed12f1044348eeeda1315a206f38f3e526e2715e06b | def _perform_rank_selection(self):
'\n Perform rank selection procedure\n :return: None\n '
stats_per_rank_index = list()
self._svd.ComputeNetworkCost()
self._num_ranks = self._svd.SetCandidateRanks(self._num_ranks)
if (not self._num_ranks):
raise RuntimeError('No good c... | Perform rank selection procedure
:return: None | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | _perform_rank_selection | Abhishekvats1997/aimet | 945 | python | def _perform_rank_selection(self):
'\n Perform rank selection procedure\n :return: None\n '
stats_per_rank_index = list()
self._svd.ComputeNetworkCost()
self._num_ranks = self._svd.SetCandidateRanks(self._num_ranks)
if (not self._num_ranks):
raise RuntimeError('No good c... | def _perform_rank_selection(self):
'\n Perform rank selection procedure\n :return: None\n '
stats_per_rank_index = list()
self._svd.ComputeNetworkCost()
self._num_ranks = self._svd.SetCandidateRanks(self._num_ranks)
if (not self._num_ranks):
raise RuntimeError('No good c... |
01217c590a980b961632ea71c75cfb17cd9d4d22f04d5e6f785de9fb98f44503 | def manual_rank_svd(self):
'\n Set provided ranks in the PyMo library\n :return: None\n '
self._svd.ComputeNetworkCost()
if (not self._layer_ranks):
raise ValueError('Layer names MUST be specified in no_eval mode.')
if (not all((isinstance(item, tuple) for item in self._laye... | Set provided ranks in the PyMo library
:return: None | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | manual_rank_svd | Abhishekvats1997/aimet | 945 | python | def manual_rank_svd(self):
'\n Set provided ranks in the PyMo library\n :return: None\n '
self._svd.ComputeNetworkCost()
if (not self._layer_ranks):
raise ValueError('Layer names MUST be specified in no_eval mode.')
if (not all((isinstance(item, tuple) for item in self._laye... | def manual_rank_svd(self):
'\n Set provided ranks in the PyMo library\n :return: None\n '
self._svd.ComputeNetworkCost()
if (not self._layer_ranks):
raise ValueError('Layer names MUST be specified in no_eval mode.')
if (not all((isinstance(item, tuple) for item in self._laye... |
8660513d31a6eced000acc34e8de13d489a92cb22ece51c806ff3f96a9bde3ae | @staticmethod
def _save_graph(sess, saver, output_graph):
'\n Utility function to save a graph\n :param sess: tf.compat.v1.Session\n :param saver: TF save\n :param output_graph: Filename and path for saving the output\n :return:\n '
logger.info('Saving graph: %s', outpu... | Utility function to save a graph
:param sess: tf.compat.v1.Session
:param saver: TF save
:param output_graph: Filename and path for saving the output
:return: | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | _save_graph | Abhishekvats1997/aimet | 945 | python | @staticmethod
def _save_graph(sess, saver, output_graph):
'\n Utility function to save a graph\n :param sess: tf.compat.v1.Session\n :param saver: TF save\n :param output_graph: Filename and path for saving the output\n :return:\n '
logger.info('Saving graph: %s', outpu... | @staticmethod
def _save_graph(sess, saver, output_graph):
'\n Utility function to save a graph\n :param sess: tf.compat.v1.Session\n :param saver: TF save\n :param output_graph: Filename and path for saving the output\n :return:\n '
logger.info('Saving graph: %s', outpu... |
de4adc5d948555a21960a41512b33ffc123df8093bcbfbb2f6461f42ec2b03b4 | def _save_compressed_network(self):
'\n Create and save a compressed network (using the best ranks identified)\n :return:\n '
logger.info('Saving final compressed network')
g = tf.Graph()
with g.as_default():
(sess, saver) = self._load_graph(g, self._default_meta_graph, self... | Create and save a compressed network (using the best ranks identified)
:return: | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | _save_compressed_network | Abhishekvats1997/aimet | 945 | python | def _save_compressed_network(self):
'\n Create and save a compressed network (using the best ranks identified)\n :return:\n '
logger.info('Saving final compressed network')
g = tf.Graph()
with g.as_default():
(sess, saver) = self._load_graph(g, self._default_meta_graph, self... | def _save_compressed_network(self):
'\n Create and save a compressed network (using the best ranks identified)\n :return:\n '
logger.info('Saving final compressed network')
g = tf.Graph()
with g.as_default():
(sess, saver) = self._load_graph(g, self._default_meta_graph, self... |
5b9b46ea1ec12139cf0f8f1b9f43b4f0e3eefa5673e28afd42ddc39a33dba72f | def compress_net(self, generator, eval_names=None, run_graph=graph_eval.evaluate_graph, eval_func=graph_eval.default_eval_func, error_margin=2, iterations=100):
"\n Compresses the network using SVD\n\n Runs rank selection on the network, and compresses it using the method and parameters\n passe... | Compresses the network using SVD
Runs rank selection on the network, and compresses it using the method and parameters
passed during construction of the Svd object.
:param generator: The generator which should be used for generating data for quantization
:param eval_names: The list of names to use for calculating mod... | TrainingExtensions/tensorflow/src/python/aimet_tensorflow/svd.py | compress_net | Abhishekvats1997/aimet | 945 | python | def compress_net(self, generator, eval_names=None, run_graph=graph_eval.evaluate_graph, eval_func=graph_eval.default_eval_func, error_margin=2, iterations=100):
"\n Compresses the network using SVD\n\n Runs rank selection on the network, and compresses it using the method and parameters\n passe... | def compress_net(self, generator, eval_names=None, run_graph=graph_eval.evaluate_graph, eval_func=graph_eval.default_eval_func, error_margin=2, iterations=100):
"\n Compresses the network using SVD\n\n Runs rank selection on the network, and compresses it using the method and parameters\n passe... |
73b26efc51054e10f1dc9cae2241c50ab36697fb5e0880da2d9093faaaaf5bf4 | def get_args():
'Get command-line arguments'
parser = argparse.ArgumentParser(description='Season 11 flir2tif', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('bin', metavar='str', help='Bin file to be converted to TIF')
parser.add_argument('-m', '--metadata', help='Cleaned ... | Get command-line arguments | flir2tif_s11.py | get_args | phytooracle/flir_bin_to_tif_s11 | 0 | python | def get_args():
parser = argparse.ArgumentParser(description='Season 11 flir2tif', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('bin', metavar='str', help='Bin file to be converted to TIF')
parser.add_argument('-m', '--metadata', help='Cleaned metadata file', metavar='met... | def get_args():
parser = argparse.ArgumentParser(description='Season 11 flir2tif', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('bin', metavar='str', help='Bin file to be converted to TIF')
parser.add_argument('-m', '--metadata', help='Cleaned metadata file', metavar='met... |
2be68c5dbcee2614d45319fdafebe6c66d18d9222265e98f7363d482e538eb92 | def main():
'Create TIF here'
args = get_args()
if (not os.path.isdir(args.outdir)):
os.makedirs(args.outdir)
bin_file = args.bin
if (bin_file is not None):
with open(args.metadata, 'r') as mdf:
full_md = json.load(mdf)['lemnatec_measurement_metadata']
extract... | Create TIF here | flir2tif_s11.py | main | phytooracle/flir_bin_to_tif_s11 | 0 | python | def main():
args = get_args()
if (not os.path.isdir(args.outdir)):
os.makedirs(args.outdir)
bin_file = args.bin
if (bin_file is not None):
with open(args.metadata, 'r') as mdf:
full_md = json.load(mdf)['lemnatec_measurement_metadata']
extractor_info = None
... | def main():
args = get_args()
if (not os.path.isdir(args.outdir)):
os.makedirs(args.outdir)
bin_file = args.bin
if (bin_file is not None):
with open(args.metadata, 'r') as mdf:
full_md = json.load(mdf)['lemnatec_measurement_metadata']
extractor_info = None
... |
35715f67f52af31e99bd179182b8b0e2ca2249becedeef91293e33e7e09b574e | def _strip_comment_tags(comments, tags):
'Helper function for `extract` that strips comment tags from strings\n in a list of comment lines. This functions operates in-place.\n '
def _strip(line):
for tag in tags:
if line.startswith(tag):
return line[len(tag):].stri... | Helper function for `extract` that strips comment tags from strings
in a list of comment lines. This functions operates in-place. | _TFL/_Babel/Extract.py | _strip_comment_tags | Tapyr/tapyr | 6 | python | def _strip_comment_tags(comments, tags):
'Helper function for `extract` that strips comment tags from strings\n in a list of comment lines. This functions operates in-place.\n '
def _strip(line):
for tag in tags:
if line.startswith(tag):
return line[len(tag):].stri... | def _strip_comment_tags(comments, tags):
'Helper function for `extract` that strips comment tags from strings\n in a list of comment lines. This functions operates in-place.\n '
def _strip(line):
for tag in tags:
if line.startswith(tag):
return line[len(tag):].stri... |
8f111ba8db923baac0ce03518866ad8218cbd2ca3ce960949ae5566f122cb017 | def collect_args() -> argparse.Namespace:
'Set command line arguments'
parser = argparse.ArgumentParser()
parser.add_argument('--config', help='Config file', type=str, default=(Path(__file__).parent / 'data/params.yaml'))
args = parser.parse_args()
return args | Set command line arguments | omnidet/main.py | collect_args | AtlasGooo2/WoodScape | 348 | python | def collect_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument('--config', help='Config file', type=str, default=(Path(__file__).parent / 'data/params.yaml'))
args = parser.parse_args()
return args | def collect_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument('--config', help='Config file', type=str, default=(Path(__file__).parent / 'data/params.yaml'))
args = parser.parse_args()
return args<|docstring|>Set command line arguments<|endoftext|> |
17d3a44461d0f57d3a561cb17270de6362caa37190eab94fe3ef0732f3f7c7af | @singledispatch
def AmsGrad(machine, learning_rate=0.001, beta1=0.9, beta2=0.999, epscut=1e-07):
'AmsGrad Optimizer.\n In some cases, adaptive learning rate methods such as AdaMax fail\n to converge to the optimal solution because of the exponential\n moving average over past gradients. To addr... | AmsGrad Optimizer.
In some cases, adaptive learning rate methods such as AdaMax fail
to converge to the optimal solution because of the exponential
moving average over past gradients. To address this problem,
Sashank J. Reddi, Satyen Kale and Sanjiv Kumar proposed the
AmsGrad [update algorithm](https://openreview.net/f... | netket/optimizer/ams_grad.py | AmsGrad | ChenAo-Phys/netket | 0 | python | @singledispatch
def AmsGrad(machine, learning_rate=0.001, beta1=0.9, beta2=0.999, epscut=1e-07):
'AmsGrad Optimizer.\n In some cases, adaptive learning rate methods such as AdaMax fail\n to converge to the optimal solution because of the exponential\n moving average over past gradients. To addr... | @singledispatch
def AmsGrad(machine, learning_rate=0.001, beta1=0.9, beta2=0.999, epscut=1e-07):
'AmsGrad Optimizer.\n In some cases, adaptive learning rate methods such as AdaMax fail\n to converge to the optimal solution because of the exponential\n moving average over past gradients. To addr... |
0d2a1d3269a41bfd30f5da6cea9f2d88a8891fe7ff0eab730deafc14d322d189 | def content2string(self) -> str:
'Get a string representation of the content'
contstr = ''
for doc in self.index:
exercises = doc['Exercises']
contstr += ('%s (%d exercises)\n' % (doc['languages']['en']['Title'], len(exercises)))
for exer in exercises:
contstr += (" %s: ... | Get a string representation of the content | lib/content.py | content2string | vsiivola/vesamusictraining | 2 | python | def content2string(self) -> str:
contstr =
for doc in self.index:
exercises = doc['Exercises']
contstr += ('%s (%d exercises)\n' % (doc['languages']['en']['Title'], len(exercises)))
for exer in exercises:
contstr += (" %s: question type '%s', answer type '%s'\n" % (exe... | def content2string(self) -> str:
contstr =
for doc in self.index:
exercises = doc['Exercises']
contstr += ('%s (%d exercises)\n' % (doc['languages']['en']['Title'], len(exercises)))
for exer in exercises:
contstr += (" %s: question type '%s', answer type '%s'\n" % (exe... |
bc8eddb1990f540dcf80dbd5281e5350e46e11789f984527c631d829965c25e2 | def _generate_extra_rounds(self) -> None:
'Generate the transposed extra exercises if requested'
for doc in self.index:
if ('Rounds' in doc):
if (doc['Rounds'][0] != 'normal'):
exercise_template = copy.deepcopy(doc['Exercises'])
roundskip = 0
else:... | Generate the transposed extra exercises if requested | lib/content.py | _generate_extra_rounds | vsiivola/vesamusictraining | 2 | python | def _generate_extra_rounds(self) -> None:
for doc in self.index:
if ('Rounds' in doc):
if (doc['Rounds'][0] != 'normal'):
exercise_template = copy.deepcopy(doc['Exercises'])
roundskip = 0
else:
exercise_template = doc['Exercises']
... | def _generate_extra_rounds(self) -> None:
for doc in self.index:
if ('Rounds' in doc):
if (doc['Rounds'][0] != 'normal'):
exercise_template = copy.deepcopy(doc['Exercises'])
roundskip = 0
else:
exercise_template = doc['Exercises']
... |
a4dc148bc02d30f8ee5d653a3418a967eb320ff836d59b1619ba9591019db48a | @staticmethod
def _augment_missing_info(exer) -> None:
'Fill in default values for the exercise, if missing'
if ((not ('question_type' in exer)) or (exer['question_type'] == 'random')):
(exer['question_type'], exer['answer_type']) = random.choice([('image', 'audio'), ('audio', 'image'), ('audio', 'image... | Fill in default values for the exercise, if missing | lib/content.py | _augment_missing_info | vsiivola/vesamusictraining | 2 | python | @staticmethod
def _augment_missing_info(exer) -> None:
if ((not ('question_type' in exer)) or (exer['question_type'] == 'random')):
(exer['question_type'], exer['answer_type']) = random.choice([('image', 'audio'), ('audio', 'image'), ('audio', 'image')])
exer['generate_check'] = 'random'
fo... | @staticmethod
def _augment_missing_info(exer) -> None:
if ((not ('question_type' in exer)) or (exer['question_type'] == 'random')):
(exer['question_type'], exer['answer_type']) = random.choice([('image', 'audio'), ('audio', 'image'), ('audio', 'image')])
exer['generate_check'] = 'random'
fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.