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 |
|---|---|---|---|---|---|---|---|---|---|
053e486a69fc33d5ac8caaa3cdb85797abecaa34c8f7f8b9d8cea880122a0338 | def test_case_1(self):
'Verify a newly running remote application takes over.'
self._store_data()
self._start_application()
status = self.data.status
status.start(self.application, self.computer)
self.data.status = status
assert self.data.status.is_running(self.application, self.computer)
computer = Computer('other', 'Other.local', 'AA:BB:CC:DD:EE:FF')
status = self.data.status
status.start(self.application, computer)
self.data.status = status
assert self.data.status.is_running(self.application, computer)
cli.run(self.path, cleanup=False)
assert (not self._is_application_running())
data = self._fetch_data()
assert (not data.status.is_running(self.application, self.computer))
assert data.status.is_running(self.application, computer) | Verify a newly running remote application takes over. | tests/test_all.py | test_case_1 | jacebrowning/mine | 18 | python | def test_case_1(self):
self._store_data()
self._start_application()
status = self.data.status
status.start(self.application, self.computer)
self.data.status = status
assert self.data.status.is_running(self.application, self.computer)
computer = Computer('other', 'Other.local', 'AA:BB:CC:DD:EE:FF')
status = self.data.status
status.start(self.application, computer)
self.data.status = status
assert self.data.status.is_running(self.application, computer)
cli.run(self.path, cleanup=False)
assert (not self._is_application_running())
data = self._fetch_data()
assert (not data.status.is_running(self.application, self.computer))
assert data.status.is_running(self.application, computer) | def test_case_1(self):
self._store_data()
self._start_application()
status = self.data.status
status.start(self.application, self.computer)
self.data.status = status
assert self.data.status.is_running(self.application, self.computer)
computer = Computer('other', 'Other.local', 'AA:BB:CC:DD:EE:FF')
status = self.data.status
status.start(self.application, computer)
self.data.status = status
assert self.data.status.is_running(self.application, computer)
cli.run(self.path, cleanup=False)
assert (not self._is_application_running())
data = self._fetch_data()
assert (not data.status.is_running(self.application, self.computer))
assert data.status.is_running(self.application, computer)<|docstring|>Verify a newly running remote application takes over.<|endoftext|> |
9706317d99cfc70414b80a0747e750df2662226139587644c5153eaa56aa6e8e | def test_case_2(self):
'Verify a newly running local application takes over.'
self._store_data()
computer = Computer('other', 'Other.local', 'AA:BB:CC:DD:EE:FF')
status = self.data.status
status.start(self.application, computer)
self.data.status = status
assert self.data.status.is_running(self.application, computer)
self._start_application()
cli.run(self.path, cleanup=False)
assert self._is_application_running()
data = self._fetch_data()
assert data.status.is_running(self.application, self.computer)
assert data.status.is_running(self.application, computer) | Verify a newly running local application takes over. | tests/test_all.py | test_case_2 | jacebrowning/mine | 18 | python | def test_case_2(self):
self._store_data()
computer = Computer('other', 'Other.local', 'AA:BB:CC:DD:EE:FF')
status = self.data.status
status.start(self.application, computer)
self.data.status = status
assert self.data.status.is_running(self.application, computer)
self._start_application()
cli.run(self.path, cleanup=False)
assert self._is_application_running()
data = self._fetch_data()
assert data.status.is_running(self.application, self.computer)
assert data.status.is_running(self.application, computer) | def test_case_2(self):
self._store_data()
computer = Computer('other', 'Other.local', 'AA:BB:CC:DD:EE:FF')
status = self.data.status
status.start(self.application, computer)
self.data.status = status
assert self.data.status.is_running(self.application, computer)
self._start_application()
cli.run(self.path, cleanup=False)
assert self._is_application_running()
data = self._fetch_data()
assert data.status.is_running(self.application, self.computer)
assert data.status.is_running(self.application, computer)<|docstring|>Verify a newly running local application takes over.<|endoftext|> |
9aea5eae8cf12a9577cbad843a7a61b39a229bd22ab5dc2fda80fa73f53a5dea | def test_case_3(self):
'Verify an already running local application is ignored.'
self._store_data()
status = self.data.status
status.start(self.application, self.computer)
self.data.status = status
self._start_application()
cli.run(self.path)
assert self._is_application_running()
data = self._fetch_data()
assert data.status.is_running(self.application, self.computer) | Verify an already running local application is ignored. | tests/test_all.py | test_case_3 | jacebrowning/mine | 18 | python | def test_case_3(self):
self._store_data()
status = self.data.status
status.start(self.application, self.computer)
self.data.status = status
self._start_application()
cli.run(self.path)
assert self._is_application_running()
data = self._fetch_data()
assert data.status.is_running(self.application, self.computer) | def test_case_3(self):
self._store_data()
status = self.data.status
status.start(self.application, self.computer)
self.data.status = status
self._start_application()
cli.run(self.path)
assert self._is_application_running()
data = self._fetch_data()
assert data.status.is_running(self.application, self.computer)<|docstring|>Verify an already running local application is ignored.<|endoftext|> |
bf5102fc11c02df6eb02531493a6ad949e066617f7af6a14f5d9314699d497a2 | def test_case_4(self):
'Verify a newly stopped local application is noted.'
self._store_data()
status = self.data.status
status.start(self.application, self.computer)
self.data.status = status
self._stop_application()
cli.run(self.path)
assert (not self._is_application_running())
data = self._fetch_data()
assert (not data.status.is_running(self.application, self.computer)) | Verify a newly stopped local application is noted. | tests/test_all.py | test_case_4 | jacebrowning/mine | 18 | python | def test_case_4(self):
self._store_data()
status = self.data.status
status.start(self.application, self.computer)
self.data.status = status
self._stop_application()
cli.run(self.path)
assert (not self._is_application_running())
data = self._fetch_data()
assert (not data.status.is_running(self.application, self.computer)) | def test_case_4(self):
self._store_data()
status = self.data.status
status.start(self.application, self.computer)
self.data.status = status
self._stop_application()
cli.run(self.path)
assert (not self._is_application_running())
data = self._fetch_data()
assert (not data.status.is_running(self.application, self.computer))<|docstring|>Verify a newly stopped local application is noted.<|endoftext|> |
112c908de9f8172e5c11dafe2fd6fb0d822bb8de9536e5e8b9d88508218e1cc3 | def test_case_6(self):
'Verify an already stopped local application is ignored.'
self._store_data()
self._stop_application()
cli.run(self.path)
assert (not self._is_application_running())
data = self._fetch_data()
assert (not data.status.is_running(self.application, self.computer)) | Verify an already stopped local application is ignored. | tests/test_all.py | test_case_6 | jacebrowning/mine | 18 | python | def test_case_6(self):
self._store_data()
self._stop_application()
cli.run(self.path)
assert (not self._is_application_running())
data = self._fetch_data()
assert (not data.status.is_running(self.application, self.computer)) | def test_case_6(self):
self._store_data()
self._stop_application()
cli.run(self.path)
assert (not self._is_application_running())
data = self._fetch_data()
assert (not data.status.is_running(self.application, self.computer))<|docstring|>Verify an already stopped local application is ignored.<|endoftext|> |
544b8bf8287f3892f2d585f7dd52d8c1169eb76a35dc292124d494dc720ee324 | def page_sizes(size):
"Convert size string into a Reportlab pagesize.\n\n Arguments:\n - size - A string representing a standard page size, eg 'A4' or 'LETTER'\n\n "
sizes = {'A0': pagesizes.A0, 'A1': pagesizes.A1, 'A2': pagesizes.A2, 'A3': pagesizes.A3, 'A4': pagesizes.A4, 'A5': pagesizes.A5, 'A6': pagesizes.A6, 'B0': pagesizes.B0, 'B1': pagesizes.B1, 'B2': pagesizes.B2, 'B3': pagesizes.B3, 'B4': pagesizes.B4, 'B5': pagesizes.B5, 'B6': pagesizes.B6, 'ELEVENSEVENTEEN': pagesizes.ELEVENSEVENTEEN, 'LEGAL': pagesizes.LEGAL, 'LETTER': pagesizes.LETTER}
try:
return sizes[size]
except KeyError:
raise ValueError(f'{size} not in list of page sizes') from None | Convert size string into a Reportlab pagesize.
Arguments:
- size - A string representing a standard page size, eg 'A4' or 'LETTER' | Bio/Graphics/GenomeDiagram/_AbstractDrawer.py | page_sizes | sgalpha01/biopython | 2,856 | python | def page_sizes(size):
"Convert size string into a Reportlab pagesize.\n\n Arguments:\n - size - A string representing a standard page size, eg 'A4' or 'LETTER'\n\n "
sizes = {'A0': pagesizes.A0, 'A1': pagesizes.A1, 'A2': pagesizes.A2, 'A3': pagesizes.A3, 'A4': pagesizes.A4, 'A5': pagesizes.A5, 'A6': pagesizes.A6, 'B0': pagesizes.B0, 'B1': pagesizes.B1, 'B2': pagesizes.B2, 'B3': pagesizes.B3, 'B4': pagesizes.B4, 'B5': pagesizes.B5, 'B6': pagesizes.B6, 'ELEVENSEVENTEEN': pagesizes.ELEVENSEVENTEEN, 'LEGAL': pagesizes.LEGAL, 'LETTER': pagesizes.LETTER}
try:
return sizes[size]
except KeyError:
raise ValueError(f'{size} not in list of page sizes') from None | def page_sizes(size):
"Convert size string into a Reportlab pagesize.\n\n Arguments:\n - size - A string representing a standard page size, eg 'A4' or 'LETTER'\n\n "
sizes = {'A0': pagesizes.A0, 'A1': pagesizes.A1, 'A2': pagesizes.A2, 'A3': pagesizes.A3, 'A4': pagesizes.A4, 'A5': pagesizes.A5, 'A6': pagesizes.A6, 'B0': pagesizes.B0, 'B1': pagesizes.B1, 'B2': pagesizes.B2, 'B3': pagesizes.B3, 'B4': pagesizes.B4, 'B5': pagesizes.B5, 'B6': pagesizes.B6, 'ELEVENSEVENTEEN': pagesizes.ELEVENSEVENTEEN, 'LEGAL': pagesizes.LEGAL, 'LETTER': pagesizes.LETTER}
try:
return sizes[size]
except KeyError:
raise ValueError(f'{size} not in list of page sizes') from None<|docstring|>Convert size string into a Reportlab pagesize.
Arguments:
- size - A string representing a standard page size, eg 'A4' or 'LETTER'<|endoftext|> |
5315fa45d6fe81a7e1a6d638ec8a40f34ca80e648f314fa845b25186a559e8ce | def _stroke_and_fill_colors(color, border):
'Deal with border and fill colors (PRIVATE).'
if (not isinstance(color, colors.Color)):
raise ValueError(f'Invalid color {color!r}')
if ((color == colors.white) and (border is None)):
strokecolor = colors.black
elif (border is None):
strokecolor = color
elif border:
if (not isinstance(border, colors.Color)):
raise ValueError(f'Invalid border color {border!r}')
strokecolor = border
else:
strokecolor = None
return (strokecolor, color) | Deal with border and fill colors (PRIVATE). | Bio/Graphics/GenomeDiagram/_AbstractDrawer.py | _stroke_and_fill_colors | sgalpha01/biopython | 2,856 | python | def _stroke_and_fill_colors(color, border):
if (not isinstance(color, colors.Color)):
raise ValueError(f'Invalid color {color!r}')
if ((color == colors.white) and (border is None)):
strokecolor = colors.black
elif (border is None):
strokecolor = color
elif border:
if (not isinstance(border, colors.Color)):
raise ValueError(f'Invalid border color {border!r}')
strokecolor = border
else:
strokecolor = None
return (strokecolor, color) | def _stroke_and_fill_colors(color, border):
if (not isinstance(color, colors.Color)):
raise ValueError(f'Invalid color {color!r}')
if ((color == colors.white) and (border is None)):
strokecolor = colors.black
elif (border is None):
strokecolor = color
elif border:
if (not isinstance(border, colors.Color)):
raise ValueError(f'Invalid border color {border!r}')
strokecolor = border
else:
strokecolor = None
return (strokecolor, color)<|docstring|>Deal with border and fill colors (PRIVATE).<|endoftext|> |
74fd76dcf1dff97062133e71f43b5b000383517da1a98908eddbea4cd4f0a85a | def draw_box(point1, point2, color=colors.lightgreen, border=None, colour=None, **kwargs):
'Draw a box.\n\n Arguments:\n - point1, point2 - coordinates for opposite corners of the box\n (x,y tuples)\n - color /colour - The color for the box (colour takes priority\n over color)\n - border - Border color for the box\n\n Returns a closed path object, beginning at (x1,y1) going round\n the four points in order, and filling with the passed color.\n '
(x1, y1) = point1
(x2, y2) = point2
if (colour is not None):
color = colour
del colour
(strokecolor, color) = _stroke_and_fill_colors(color, border)
(x1, y1, x2, y2) = (min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2))
return Polygon([x1, y1, x2, y1, x2, y2, x1, y2], strokeColor=strokecolor, fillColor=color, strokewidth=0, **kwargs) | Draw a box.
Arguments:
- point1, point2 - coordinates for opposite corners of the box
(x,y tuples)
- color /colour - The color for the box (colour takes priority
over color)
- border - Border color for the box
Returns a closed path object, beginning at (x1,y1) going round
the four points in order, and filling with the passed color. | Bio/Graphics/GenomeDiagram/_AbstractDrawer.py | draw_box | sgalpha01/biopython | 2,856 | python | def draw_box(point1, point2, color=colors.lightgreen, border=None, colour=None, **kwargs):
'Draw a box.\n\n Arguments:\n - point1, point2 - coordinates for opposite corners of the box\n (x,y tuples)\n - color /colour - The color for the box (colour takes priority\n over color)\n - border - Border color for the box\n\n Returns a closed path object, beginning at (x1,y1) going round\n the four points in order, and filling with the passed color.\n '
(x1, y1) = point1
(x2, y2) = point2
if (colour is not None):
color = colour
del colour
(strokecolor, color) = _stroke_and_fill_colors(color, border)
(x1, y1, x2, y2) = (min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2))
return Polygon([x1, y1, x2, y1, x2, y2, x1, y2], strokeColor=strokecolor, fillColor=color, strokewidth=0, **kwargs) | def draw_box(point1, point2, color=colors.lightgreen, border=None, colour=None, **kwargs):
'Draw a box.\n\n Arguments:\n - point1, point2 - coordinates for opposite corners of the box\n (x,y tuples)\n - color /colour - The color for the box (colour takes priority\n over color)\n - border - Border color for the box\n\n Returns a closed path object, beginning at (x1,y1) going round\n the four points in order, and filling with the passed color.\n '
(x1, y1) = point1
(x2, y2) = point2
if (colour is not None):
color = colour
del colour
(strokecolor, color) = _stroke_and_fill_colors(color, border)
(x1, y1, x2, y2) = (min(x1, x2), min(y1, y2), max(x1, x2), max(y1, y2))
return Polygon([x1, y1, x2, y1, x2, y2, x1, y2], strokeColor=strokecolor, fillColor=color, strokewidth=0, **kwargs)<|docstring|>Draw a box.
Arguments:
- point1, point2 - coordinates for opposite corners of the box
(x,y tuples)
- color /colour - The color for the box (colour takes priority
over color)
- border - Border color for the box
Returns a closed path object, beginning at (x1,y1) going round
the four points in order, and filling with the passed color.<|endoftext|> |
7dacb114fb38a6b4436281fddf07e6c2fab6e27e0c272185c30074fe98311156 | def draw_cut_corner_box(point1, point2, corner=0.5, color=colors.lightgreen, border=None, **kwargs):
'Draw a box with the corners cut off.'
(x1, y1) = point1
(x2, y2) = point2
if (not corner):
return draw_box(point1, point2, color, border)
elif (corner < 0):
raise ValueError('Arrow head length ratio should be positive')
(strokecolor, color) = _stroke_and_fill_colors(color, border)
boxheight = (y2 - y1)
boxwidth = (x2 - x1)
x_corner = min(((boxheight * 0.5) * corner), (boxwidth * 0.5))
y_corner = min(((boxheight * 0.5) * corner), (boxheight * 0.5))
points = [x1, (y1 + y_corner), x1, (y2 - y_corner), (x1 + x_corner), y2, (x2 - x_corner), y2, x2, (y2 - y_corner), x2, (y1 + y_corner), (x2 - x_corner), y1, (x1 + x_corner), y1]
return Polygon(deduplicate(points), strokeColor=strokecolor, strokeWidth=1, strokeLineJoin=1, fillColor=color, **kwargs) | Draw a box with the corners cut off. | Bio/Graphics/GenomeDiagram/_AbstractDrawer.py | draw_cut_corner_box | sgalpha01/biopython | 2,856 | python | def draw_cut_corner_box(point1, point2, corner=0.5, color=colors.lightgreen, border=None, **kwargs):
(x1, y1) = point1
(x2, y2) = point2
if (not corner):
return draw_box(point1, point2, color, border)
elif (corner < 0):
raise ValueError('Arrow head length ratio should be positive')
(strokecolor, color) = _stroke_and_fill_colors(color, border)
boxheight = (y2 - y1)
boxwidth = (x2 - x1)
x_corner = min(((boxheight * 0.5) * corner), (boxwidth * 0.5))
y_corner = min(((boxheight * 0.5) * corner), (boxheight * 0.5))
points = [x1, (y1 + y_corner), x1, (y2 - y_corner), (x1 + x_corner), y2, (x2 - x_corner), y2, x2, (y2 - y_corner), x2, (y1 + y_corner), (x2 - x_corner), y1, (x1 + x_corner), y1]
return Polygon(deduplicate(points), strokeColor=strokecolor, strokeWidth=1, strokeLineJoin=1, fillColor=color, **kwargs) | def draw_cut_corner_box(point1, point2, corner=0.5, color=colors.lightgreen, border=None, **kwargs):
(x1, y1) = point1
(x2, y2) = point2
if (not corner):
return draw_box(point1, point2, color, border)
elif (corner < 0):
raise ValueError('Arrow head length ratio should be positive')
(strokecolor, color) = _stroke_and_fill_colors(color, border)
boxheight = (y2 - y1)
boxwidth = (x2 - x1)
x_corner = min(((boxheight * 0.5) * corner), (boxwidth * 0.5))
y_corner = min(((boxheight * 0.5) * corner), (boxheight * 0.5))
points = [x1, (y1 + y_corner), x1, (y2 - y_corner), (x1 + x_corner), y2, (x2 - x_corner), y2, x2, (y2 - y_corner), x2, (y1 + y_corner), (x2 - x_corner), y1, (x1 + x_corner), y1]
return Polygon(deduplicate(points), strokeColor=strokecolor, strokeWidth=1, strokeLineJoin=1, fillColor=color, **kwargs)<|docstring|>Draw a box with the corners cut off.<|endoftext|> |
af229b1799215a1123eba0c5e6160396e4c1f1853259a4f97341d1e5f9f05d11 | def draw_polygon(list_of_points, color=colors.lightgreen, border=None, colour=None, **kwargs):
'Draw polygon.\n\n Arguments:\n - list_of_point - list of (x,y) tuples for the corner coordinates\n - color / colour - The color for the box\n\n Returns a closed path object, beginning at (x1,y1) going round\n the four points in order, and filling with the passed colour.\n\n '
if (colour is not None):
color = colour
del colour
(strokecolor, color) = _stroke_and_fill_colors(color, border)
xy_list = []
for (x, y) in list_of_points:
xy_list.append(x)
xy_list.append(y)
return Polygon(deduplicate(xy_list), strokeColor=strokecolor, fillColor=color, strokewidth=0, **kwargs) | Draw polygon.
Arguments:
- list_of_point - list of (x,y) tuples for the corner coordinates
- color / colour - The color for the box
Returns a closed path object, beginning at (x1,y1) going round
the four points in order, and filling with the passed colour. | Bio/Graphics/GenomeDiagram/_AbstractDrawer.py | draw_polygon | sgalpha01/biopython | 2,856 | python | def draw_polygon(list_of_points, color=colors.lightgreen, border=None, colour=None, **kwargs):
'Draw polygon.\n\n Arguments:\n - list_of_point - list of (x,y) tuples for the corner coordinates\n - color / colour - The color for the box\n\n Returns a closed path object, beginning at (x1,y1) going round\n the four points in order, and filling with the passed colour.\n\n '
if (colour is not None):
color = colour
del colour
(strokecolor, color) = _stroke_and_fill_colors(color, border)
xy_list = []
for (x, y) in list_of_points:
xy_list.append(x)
xy_list.append(y)
return Polygon(deduplicate(xy_list), strokeColor=strokecolor, fillColor=color, strokewidth=0, **kwargs) | def draw_polygon(list_of_points, color=colors.lightgreen, border=None, colour=None, **kwargs):
'Draw polygon.\n\n Arguments:\n - list_of_point - list of (x,y) tuples for the corner coordinates\n - color / colour - The color for the box\n\n Returns a closed path object, beginning at (x1,y1) going round\n the four points in order, and filling with the passed colour.\n\n '
if (colour is not None):
color = colour
del colour
(strokecolor, color) = _stroke_and_fill_colors(color, border)
xy_list = []
for (x, y) in list_of_points:
xy_list.append(x)
xy_list.append(y)
return Polygon(deduplicate(xy_list), strokeColor=strokecolor, fillColor=color, strokewidth=0, **kwargs)<|docstring|>Draw polygon.
Arguments:
- list_of_point - list of (x,y) tuples for the corner coordinates
- color / colour - The color for the box
Returns a closed path object, beginning at (x1,y1) going round
the four points in order, and filling with the passed colour.<|endoftext|> |
ffb778083d3a5602925b8dd38c6e48657c71962346571f5386437fc8cd2220a9 | def draw_arrow(point1, point2, color=colors.lightgreen, border=None, shaft_height_ratio=0.4, head_length_ratio=0.5, orientation='right', colour=None, **kwargs):
"Draw an arrow.\n\n Returns a closed path object representing an arrow enclosed by the\n box with corners at {point1=(x1,y1), point2=(x2,y2)}, a shaft height\n given by shaft_height_ratio (relative to box height), a head length\n given by head_length_ratio (also relative to box height), and\n an orientation that may be 'left' or 'right'.\n "
(x1, y1) = point1
(x2, y2) = point2
if ((shaft_height_ratio < 0) or (1 < shaft_height_ratio)):
raise ValueError('Arrow shaft height ratio should be in range 0 to 1')
if (head_length_ratio < 0):
raise ValueError('Arrow head length ratio should be positive')
if (colour is not None):
color = colour
del colour
(strokecolor, color) = _stroke_and_fill_colors(color, border)
(xmin, ymin) = (min(x1, x2), min(y1, y2))
(xmax, ymax) = (max(x1, x2), max(y1, y2))
if (orientation == 'right'):
(x1, x2, y1, y2) = (xmin, xmax, ymin, ymax)
elif (orientation == 'left'):
(x1, x2, y1, y2) = (xmax, xmin, ymin, ymax)
else:
raise ValueError(f"Invalid orientation {orientation!r}, should be 'left' or 'right'")
boxheight = (y2 - y1)
boxwidth = (x2 - x1)
shaftheight = (boxheight * shaft_height_ratio)
headlength = min((abs(boxheight) * head_length_ratio), abs(boxwidth))
if (boxwidth < 0):
headlength *= (- 1)
shafttop = (0.5 * (boxheight + shaftheight))
shaftbase = (boxheight - shafttop)
headbase = (boxwidth - headlength)
midheight = (0.5 * boxheight)
points = [x1, (y1 + shafttop), (x1 + headbase), (y1 + shafttop), (x1 + headbase), y2, x2, (y1 + midheight), (x1 + headbase), y1, (x1 + headbase), (y1 + shaftbase), x1, (y1 + shaftbase)]
return Polygon(deduplicate(points), strokeColor=strokecolor, strokeWidth=1, strokeLineJoin=1, fillColor=color, **kwargs) | Draw an arrow.
Returns a closed path object representing an arrow enclosed by the
box with corners at {point1=(x1,y1), point2=(x2,y2)}, a shaft height
given by shaft_height_ratio (relative to box height), a head length
given by head_length_ratio (also relative to box height), and
an orientation that may be 'left' or 'right'. | Bio/Graphics/GenomeDiagram/_AbstractDrawer.py | draw_arrow | sgalpha01/biopython | 2,856 | python | def draw_arrow(point1, point2, color=colors.lightgreen, border=None, shaft_height_ratio=0.4, head_length_ratio=0.5, orientation='right', colour=None, **kwargs):
"Draw an arrow.\n\n Returns a closed path object representing an arrow enclosed by the\n box with corners at {point1=(x1,y1), point2=(x2,y2)}, a shaft height\n given by shaft_height_ratio (relative to box height), a head length\n given by head_length_ratio (also relative to box height), and\n an orientation that may be 'left' or 'right'.\n "
(x1, y1) = point1
(x2, y2) = point2
if ((shaft_height_ratio < 0) or (1 < shaft_height_ratio)):
raise ValueError('Arrow shaft height ratio should be in range 0 to 1')
if (head_length_ratio < 0):
raise ValueError('Arrow head length ratio should be positive')
if (colour is not None):
color = colour
del colour
(strokecolor, color) = _stroke_and_fill_colors(color, border)
(xmin, ymin) = (min(x1, x2), min(y1, y2))
(xmax, ymax) = (max(x1, x2), max(y1, y2))
if (orientation == 'right'):
(x1, x2, y1, y2) = (xmin, xmax, ymin, ymax)
elif (orientation == 'left'):
(x1, x2, y1, y2) = (xmax, xmin, ymin, ymax)
else:
raise ValueError(f"Invalid orientation {orientation!r}, should be 'left' or 'right'")
boxheight = (y2 - y1)
boxwidth = (x2 - x1)
shaftheight = (boxheight * shaft_height_ratio)
headlength = min((abs(boxheight) * head_length_ratio), abs(boxwidth))
if (boxwidth < 0):
headlength *= (- 1)
shafttop = (0.5 * (boxheight + shaftheight))
shaftbase = (boxheight - shafttop)
headbase = (boxwidth - headlength)
midheight = (0.5 * boxheight)
points = [x1, (y1 + shafttop), (x1 + headbase), (y1 + shafttop), (x1 + headbase), y2, x2, (y1 + midheight), (x1 + headbase), y1, (x1 + headbase), (y1 + shaftbase), x1, (y1 + shaftbase)]
return Polygon(deduplicate(points), strokeColor=strokecolor, strokeWidth=1, strokeLineJoin=1, fillColor=color, **kwargs) | def draw_arrow(point1, point2, color=colors.lightgreen, border=None, shaft_height_ratio=0.4, head_length_ratio=0.5, orientation='right', colour=None, **kwargs):
"Draw an arrow.\n\n Returns a closed path object representing an arrow enclosed by the\n box with corners at {point1=(x1,y1), point2=(x2,y2)}, a shaft height\n given by shaft_height_ratio (relative to box height), a head length\n given by head_length_ratio (also relative to box height), and\n an orientation that may be 'left' or 'right'.\n "
(x1, y1) = point1
(x2, y2) = point2
if ((shaft_height_ratio < 0) or (1 < shaft_height_ratio)):
raise ValueError('Arrow shaft height ratio should be in range 0 to 1')
if (head_length_ratio < 0):
raise ValueError('Arrow head length ratio should be positive')
if (colour is not None):
color = colour
del colour
(strokecolor, color) = _stroke_and_fill_colors(color, border)
(xmin, ymin) = (min(x1, x2), min(y1, y2))
(xmax, ymax) = (max(x1, x2), max(y1, y2))
if (orientation == 'right'):
(x1, x2, y1, y2) = (xmin, xmax, ymin, ymax)
elif (orientation == 'left'):
(x1, x2, y1, y2) = (xmax, xmin, ymin, ymax)
else:
raise ValueError(f"Invalid orientation {orientation!r}, should be 'left' or 'right'")
boxheight = (y2 - y1)
boxwidth = (x2 - x1)
shaftheight = (boxheight * shaft_height_ratio)
headlength = min((abs(boxheight) * head_length_ratio), abs(boxwidth))
if (boxwidth < 0):
headlength *= (- 1)
shafttop = (0.5 * (boxheight + shaftheight))
shaftbase = (boxheight - shafttop)
headbase = (boxwidth - headlength)
midheight = (0.5 * boxheight)
points = [x1, (y1 + shafttop), (x1 + headbase), (y1 + shafttop), (x1 + headbase), y2, x2, (y1 + midheight), (x1 + headbase), y1, (x1 + headbase), (y1 + shaftbase), x1, (y1 + shaftbase)]
return Polygon(deduplicate(points), strokeColor=strokecolor, strokeWidth=1, strokeLineJoin=1, fillColor=color, **kwargs)<|docstring|>Draw an arrow.
Returns a closed path object representing an arrow enclosed by the
box with corners at {point1=(x1,y1), point2=(x2,y2)}, a shaft height
given by shaft_height_ratio (relative to box height), a head length
given by head_length_ratio (also relative to box height), and
an orientation that may be 'left' or 'right'.<|endoftext|> |
b9054e3706397516162d41dbfb2ba6604b6a688b46798ef37ead9081ff69cb22 | def deduplicate(points):
'Remove adjacent duplicate points.\n\n This is important for use with the Polygon class since reportlab has a\n bug with duplicate points.\n\n Arguments:\n - points - list of points [x1, y1, x2, y2,...]\n\n Returns a list in the same format with consecutive duplicates removed\n '
assert ((len(points) % 2) == 0)
if (len(points) < 2):
return points
newpoints = points[0:2]
for (x, y) in zip(islice(points, 2, None, 2), islice(points, 3, None, 2)):
if ((x != newpoints[(- 2)]) or (y != newpoints[(- 1)])):
newpoints.append(x)
newpoints.append(y)
return newpoints | Remove adjacent duplicate points.
This is important for use with the Polygon class since reportlab has a
bug with duplicate points.
Arguments:
- points - list of points [x1, y1, x2, y2,...]
Returns a list in the same format with consecutive duplicates removed | Bio/Graphics/GenomeDiagram/_AbstractDrawer.py | deduplicate | sgalpha01/biopython | 2,856 | python | def deduplicate(points):
'Remove adjacent duplicate points.\n\n This is important for use with the Polygon class since reportlab has a\n bug with duplicate points.\n\n Arguments:\n - points - list of points [x1, y1, x2, y2,...]\n\n Returns a list in the same format with consecutive duplicates removed\n '
assert ((len(points) % 2) == 0)
if (len(points) < 2):
return points
newpoints = points[0:2]
for (x, y) in zip(islice(points, 2, None, 2), islice(points, 3, None, 2)):
if ((x != newpoints[(- 2)]) or (y != newpoints[(- 1)])):
newpoints.append(x)
newpoints.append(y)
return newpoints | def deduplicate(points):
'Remove adjacent duplicate points.\n\n This is important for use with the Polygon class since reportlab has a\n bug with duplicate points.\n\n Arguments:\n - points - list of points [x1, y1, x2, y2,...]\n\n Returns a list in the same format with consecutive duplicates removed\n '
assert ((len(points) % 2) == 0)
if (len(points) < 2):
return points
newpoints = points[0:2]
for (x, y) in zip(islice(points, 2, None, 2), islice(points, 3, None, 2)):
if ((x != newpoints[(- 2)]) or (y != newpoints[(- 1)])):
newpoints.append(x)
newpoints.append(y)
return newpoints<|docstring|>Remove adjacent duplicate points.
This is important for use with the Polygon class since reportlab has a
bug with duplicate points.
Arguments:
- points - list of points [x1, y1, x2, y2,...]
Returns a list in the same format with consecutive duplicates removed<|endoftext|> |
3b11b9aa596693137b26c74c03a29048e9250614253c03cef07da6e706996c9c | def angle2trig(theta):
'Convert angle to a reportlab ready tuple.\n\n Arguments:\n - theta - Angle in degrees, counter clockwise from horizontal\n\n Returns a representation of the passed angle in a format suitable\n for ReportLab rotations (i.e. cos(theta), sin(theta), -sin(theta),\n cos(theta) tuple)\n '
c = cos(((theta * pi) / 180))
s = sin(((theta * pi) / 180))
return (c, s, (- s), c) | Convert angle to a reportlab ready tuple.
Arguments:
- theta - Angle in degrees, counter clockwise from horizontal
Returns a representation of the passed angle in a format suitable
for ReportLab rotations (i.e. cos(theta), sin(theta), -sin(theta),
cos(theta) tuple) | Bio/Graphics/GenomeDiagram/_AbstractDrawer.py | angle2trig | sgalpha01/biopython | 2,856 | python | def angle2trig(theta):
'Convert angle to a reportlab ready tuple.\n\n Arguments:\n - theta - Angle in degrees, counter clockwise from horizontal\n\n Returns a representation of the passed angle in a format suitable\n for ReportLab rotations (i.e. cos(theta), sin(theta), -sin(theta),\n cos(theta) tuple)\n '
c = cos(((theta * pi) / 180))
s = sin(((theta * pi) / 180))
return (c, s, (- s), c) | def angle2trig(theta):
'Convert angle to a reportlab ready tuple.\n\n Arguments:\n - theta - Angle in degrees, counter clockwise from horizontal\n\n Returns a representation of the passed angle in a format suitable\n for ReportLab rotations (i.e. cos(theta), sin(theta), -sin(theta),\n cos(theta) tuple)\n '
c = cos(((theta * pi) / 180))
s = sin(((theta * pi) / 180))
return (c, s, (- s), c)<|docstring|>Convert angle to a reportlab ready tuple.
Arguments:
- theta - Angle in degrees, counter clockwise from horizontal
Returns a representation of the passed angle in a format suitable
for ReportLab rotations (i.e. cos(theta), sin(theta), -sin(theta),
cos(theta) tuple)<|endoftext|> |
d10421553dbe67d9d9e493dee97fa3326ed15a7b42db91396fbb2458edf9becf | def intermediate_points(start, end, graph_data):
"Generate intermediate points describing provided graph data..\n\n Returns a list of (start, end, value) tuples describing the passed\n graph data as 'bins' between position midpoints.\n "
newdata = []
newdata.append((start, (graph_data[0][0] + ((graph_data[1][0] - graph_data[0][0]) / 2.0)), graph_data[0][1]))
for index in range(1, (len(graph_data) - 1)):
(lastxval, lastyval) = graph_data[(index - 1)]
(xval, yval) = graph_data[index]
(nextxval, nextyval) = graph_data[(index + 1)]
newdata.append(((lastxval + ((xval - lastxval) / 2.0)), (xval + ((nextxval - xval) / 2.0)), yval))
newdata.append(((xval + ((nextxval - xval) / 2.0)), end, graph_data[(- 1)][1]))
return newdata | Generate intermediate points describing provided graph data..
Returns a list of (start, end, value) tuples describing the passed
graph data as 'bins' between position midpoints. | Bio/Graphics/GenomeDiagram/_AbstractDrawer.py | intermediate_points | sgalpha01/biopython | 2,856 | python | def intermediate_points(start, end, graph_data):
"Generate intermediate points describing provided graph data..\n\n Returns a list of (start, end, value) tuples describing the passed\n graph data as 'bins' between position midpoints.\n "
newdata = []
newdata.append((start, (graph_data[0][0] + ((graph_data[1][0] - graph_data[0][0]) / 2.0)), graph_data[0][1]))
for index in range(1, (len(graph_data) - 1)):
(lastxval, lastyval) = graph_data[(index - 1)]
(xval, yval) = graph_data[index]
(nextxval, nextyval) = graph_data[(index + 1)]
newdata.append(((lastxval + ((xval - lastxval) / 2.0)), (xval + ((nextxval - xval) / 2.0)), yval))
newdata.append(((xval + ((nextxval - xval) / 2.0)), end, graph_data[(- 1)][1]))
return newdata | def intermediate_points(start, end, graph_data):
"Generate intermediate points describing provided graph data..\n\n Returns a list of (start, end, value) tuples describing the passed\n graph data as 'bins' between position midpoints.\n "
newdata = []
newdata.append((start, (graph_data[0][0] + ((graph_data[1][0] - graph_data[0][0]) / 2.0)), graph_data[0][1]))
for index in range(1, (len(graph_data) - 1)):
(lastxval, lastyval) = graph_data[(index - 1)]
(xval, yval) = graph_data[index]
(nextxval, nextyval) = graph_data[(index + 1)]
newdata.append(((lastxval + ((xval - lastxval) / 2.0)), (xval + ((nextxval - xval) / 2.0)), yval))
newdata.append(((xval + ((nextxval - xval) / 2.0)), end, graph_data[(- 1)][1]))
return newdata<|docstring|>Generate intermediate points describing provided graph data..
Returns a list of (start, end, value) tuples describing the passed
graph data as 'bins' between position midpoints.<|endoftext|> |
1322c3ab93fecb5831e390e5013f8082d045b52787ae23393d34ebfdb03181dd | def __init__(self, parent, pagesize='A3', orientation='landscape', x=0.05, y=0.05, xl=None, xr=None, yt=None, yb=None, start=None, end=None, tracklines=0, cross_track_links=None):
"Create the object.\n\n Arguments:\n - parent Diagram object containing the data that the drawer draws\n - pagesize String describing the ISO size of the image, or a tuple\n of pixels\n - orientation String describing the required orientation of the\n final drawing ('landscape' or 'portrait')\n - x Float (0->1) describing the relative size of the X\n margins to the page\n - y Float (0->1) describing the relative size of the Y\n margins to the page\n - xl Float (0->1) describing the relative size of the left X\n margin to the page (overrides x)\n - xr Float (0->1) describing the relative size of the right X\n margin to the page (overrides x)\n - yt Float (0->1) describing the relative size of the top Y\n margin to the page (overrides y)\n - yb Float (0->1) describing the relative size of the lower Y\n margin to the page (overrides y)\n - start Int, the position to begin drawing the diagram at\n - end Int, the position to stop drawing the diagram at\n - tracklines Boolean flag to show (or not) lines delineating tracks\n on the diagram\n - cross_track_links List of tuples each with four entries (track A,\n feature A, track B, feature B) to be linked.\n\n "
self._parent = parent
self.set_page_size(pagesize, orientation)
self.set_margins(x, y, xl, xr, yt, yb)
self.set_bounds(start, end)
self.tracklines = tracklines
if (cross_track_links is None):
cross_track_links = []
else:
self.cross_track_links = cross_track_links | Create the object.
Arguments:
- parent Diagram object containing the data that the drawer draws
- pagesize String describing the ISO size of the image, or a tuple
of pixels
- orientation String describing the required orientation of the
final drawing ('landscape' or 'portrait')
- x Float (0->1) describing the relative size of the X
margins to the page
- y Float (0->1) describing the relative size of the Y
margins to the page
- xl Float (0->1) describing the relative size of the left X
margin to the page (overrides x)
- xr Float (0->1) describing the relative size of the right X
margin to the page (overrides x)
- yt Float (0->1) describing the relative size of the top Y
margin to the page (overrides y)
- yb Float (0->1) describing the relative size of the lower Y
margin to the page (overrides y)
- start Int, the position to begin drawing the diagram at
- end Int, the position to stop drawing the diagram at
- tracklines Boolean flag to show (or not) lines delineating tracks
on the diagram
- cross_track_links List of tuples each with four entries (track A,
feature A, track B, feature B) to be linked. | Bio/Graphics/GenomeDiagram/_AbstractDrawer.py | __init__ | sgalpha01/biopython | 2,856 | python | def __init__(self, parent, pagesize='A3', orientation='landscape', x=0.05, y=0.05, xl=None, xr=None, yt=None, yb=None, start=None, end=None, tracklines=0, cross_track_links=None):
"Create the object.\n\n Arguments:\n - parent Diagram object containing the data that the drawer draws\n - pagesize String describing the ISO size of the image, or a tuple\n of pixels\n - orientation String describing the required orientation of the\n final drawing ('landscape' or 'portrait')\n - x Float (0->1) describing the relative size of the X\n margins to the page\n - y Float (0->1) describing the relative size of the Y\n margins to the page\n - xl Float (0->1) describing the relative size of the left X\n margin to the page (overrides x)\n - xr Float (0->1) describing the relative size of the right X\n margin to the page (overrides x)\n - yt Float (0->1) describing the relative size of the top Y\n margin to the page (overrides y)\n - yb Float (0->1) describing the relative size of the lower Y\n margin to the page (overrides y)\n - start Int, the position to begin drawing the diagram at\n - end Int, the position to stop drawing the diagram at\n - tracklines Boolean flag to show (or not) lines delineating tracks\n on the diagram\n - cross_track_links List of tuples each with four entries (track A,\n feature A, track B, feature B) to be linked.\n\n "
self._parent = parent
self.set_page_size(pagesize, orientation)
self.set_margins(x, y, xl, xr, yt, yb)
self.set_bounds(start, end)
self.tracklines = tracklines
if (cross_track_links is None):
cross_track_links = []
else:
self.cross_track_links = cross_track_links | def __init__(self, parent, pagesize='A3', orientation='landscape', x=0.05, y=0.05, xl=None, xr=None, yt=None, yb=None, start=None, end=None, tracklines=0, cross_track_links=None):
"Create the object.\n\n Arguments:\n - parent Diagram object containing the data that the drawer draws\n - pagesize String describing the ISO size of the image, or a tuple\n of pixels\n - orientation String describing the required orientation of the\n final drawing ('landscape' or 'portrait')\n - x Float (0->1) describing the relative size of the X\n margins to the page\n - y Float (0->1) describing the relative size of the Y\n margins to the page\n - xl Float (0->1) describing the relative size of the left X\n margin to the page (overrides x)\n - xr Float (0->1) describing the relative size of the right X\n margin to the page (overrides x)\n - yt Float (0->1) describing the relative size of the top Y\n margin to the page (overrides y)\n - yb Float (0->1) describing the relative size of the lower Y\n margin to the page (overrides y)\n - start Int, the position to begin drawing the diagram at\n - end Int, the position to stop drawing the diagram at\n - tracklines Boolean flag to show (or not) lines delineating tracks\n on the diagram\n - cross_track_links List of tuples each with four entries (track A,\n feature A, track B, feature B) to be linked.\n\n "
self._parent = parent
self.set_page_size(pagesize, orientation)
self.set_margins(x, y, xl, xr, yt, yb)
self.set_bounds(start, end)
self.tracklines = tracklines
if (cross_track_links is None):
cross_track_links = []
else:
self.cross_track_links = cross_track_links<|docstring|>Create the object.
Arguments:
- parent Diagram object containing the data that the drawer draws
- pagesize String describing the ISO size of the image, or a tuple
of pixels
- orientation String describing the required orientation of the
final drawing ('landscape' or 'portrait')
- x Float (0->1) describing the relative size of the X
margins to the page
- y Float (0->1) describing the relative size of the Y
margins to the page
- xl Float (0->1) describing the relative size of the left X
margin to the page (overrides x)
- xr Float (0->1) describing the relative size of the right X
margin to the page (overrides x)
- yt Float (0->1) describing the relative size of the top Y
margin to the page (overrides y)
- yb Float (0->1) describing the relative size of the lower Y
margin to the page (overrides y)
- start Int, the position to begin drawing the diagram at
- end Int, the position to stop drawing the diagram at
- tracklines Boolean flag to show (or not) lines delineating tracks
on the diagram
- cross_track_links List of tuples each with four entries (track A,
feature A, track B, feature B) to be linked.<|endoftext|> |
8be1aa6a7c14e5828b6d259a3d0a889672f7aac9c67cf6ef43b994a4c23c7a3c | def set_page_size(self, pagesize, orientation):
"Set page size of the drawing..\n\n Arguments:\n - pagesize Size of the output image, a tuple of pixels (width,\n height, or a string in the reportlab.lib.pagesizes\n set of ISO sizes.\n - orientation String: 'landscape' or 'portrait'\n\n "
if isinstance(pagesize, str):
pagesize = page_sizes(pagesize)
elif isinstance(pagesize, tuple):
pass
else:
raise ValueError(f'Page size {pagesize} not recognised')
(shortside, longside) = (min(pagesize), max(pagesize))
orientation = orientation.lower()
if (orientation not in ('landscape', 'portrait')):
raise ValueError(f'Orientation {orientation} not recognised')
if (orientation == 'landscape'):
self.pagesize = (longside, shortside)
else:
self.pagesize = (shortside, longside) | Set page size of the drawing..
Arguments:
- pagesize Size of the output image, a tuple of pixels (width,
height, or a string in the reportlab.lib.pagesizes
set of ISO sizes.
- orientation String: 'landscape' or 'portrait' | Bio/Graphics/GenomeDiagram/_AbstractDrawer.py | set_page_size | sgalpha01/biopython | 2,856 | python | def set_page_size(self, pagesize, orientation):
"Set page size of the drawing..\n\n Arguments:\n - pagesize Size of the output image, a tuple of pixels (width,\n height, or a string in the reportlab.lib.pagesizes\n set of ISO sizes.\n - orientation String: 'landscape' or 'portrait'\n\n "
if isinstance(pagesize, str):
pagesize = page_sizes(pagesize)
elif isinstance(pagesize, tuple):
pass
else:
raise ValueError(f'Page size {pagesize} not recognised')
(shortside, longside) = (min(pagesize), max(pagesize))
orientation = orientation.lower()
if (orientation not in ('landscape', 'portrait')):
raise ValueError(f'Orientation {orientation} not recognised')
if (orientation == 'landscape'):
self.pagesize = (longside, shortside)
else:
self.pagesize = (shortside, longside) | def set_page_size(self, pagesize, orientation):
"Set page size of the drawing..\n\n Arguments:\n - pagesize Size of the output image, a tuple of pixels (width,\n height, or a string in the reportlab.lib.pagesizes\n set of ISO sizes.\n - orientation String: 'landscape' or 'portrait'\n\n "
if isinstance(pagesize, str):
pagesize = page_sizes(pagesize)
elif isinstance(pagesize, tuple):
pass
else:
raise ValueError(f'Page size {pagesize} not recognised')
(shortside, longside) = (min(pagesize), max(pagesize))
orientation = orientation.lower()
if (orientation not in ('landscape', 'portrait')):
raise ValueError(f'Orientation {orientation} not recognised')
if (orientation == 'landscape'):
self.pagesize = (longside, shortside)
else:
self.pagesize = (shortside, longside)<|docstring|>Set page size of the drawing..
Arguments:
- pagesize Size of the output image, a tuple of pixels (width,
height, or a string in the reportlab.lib.pagesizes
set of ISO sizes.
- orientation String: 'landscape' or 'portrait'<|endoftext|> |
0ef06d1a4883496b0d49c68ca36eda3d3dbe0bcee735fdd2de9011b0d35159b4 | def set_margins(self, x, y, xl, xr, yt, yb):
'Set page margins.\n\n Arguments:\n - x Float(0->1), Absolute X margin as % of page\n - y Float(0->1), Absolute Y margin as % of page\n - xl Float(0->1), Left X margin as % of page\n - xr Float(0->1), Right X margin as % of page\n - yt Float(0->1), Top Y margin as % of page\n - yb Float(0->1), Bottom Y margin as % of page\n\n Set the page margins as proportions of the page 0->1, and also\n set the page limits x0, y0 and xlim, ylim, and page center\n xorigin, yorigin, as well as overall page width and height\n '
xmargin_l = (xl or x)
xmargin_r = (xr or x)
ymargin_top = (yt or y)
ymargin_btm = (yb or y)
(self.x0, self.y0) = ((self.pagesize[0] * xmargin_l), (self.pagesize[1] * ymargin_btm))
(self.xlim, self.ylim) = ((self.pagesize[0] * (1 - xmargin_r)), (self.pagesize[1] * (1 - ymargin_top)))
self.pagewidth = (self.xlim - self.x0)
self.pageheight = (self.ylim - self.y0)
(self.xcenter, self.ycenter) = ((self.x0 + (self.pagewidth / 2.0)), (self.y0 + (self.pageheight / 2.0))) | Set page margins.
Arguments:
- x Float(0->1), Absolute X margin as % of page
- y Float(0->1), Absolute Y margin as % of page
- xl Float(0->1), Left X margin as % of page
- xr Float(0->1), Right X margin as % of page
- yt Float(0->1), Top Y margin as % of page
- yb Float(0->1), Bottom Y margin as % of page
Set the page margins as proportions of the page 0->1, and also
set the page limits x0, y0 and xlim, ylim, and page center
xorigin, yorigin, as well as overall page width and height | Bio/Graphics/GenomeDiagram/_AbstractDrawer.py | set_margins | sgalpha01/biopython | 2,856 | python | def set_margins(self, x, y, xl, xr, yt, yb):
'Set page margins.\n\n Arguments:\n - x Float(0->1), Absolute X margin as % of page\n - y Float(0->1), Absolute Y margin as % of page\n - xl Float(0->1), Left X margin as % of page\n - xr Float(0->1), Right X margin as % of page\n - yt Float(0->1), Top Y margin as % of page\n - yb Float(0->1), Bottom Y margin as % of page\n\n Set the page margins as proportions of the page 0->1, and also\n set the page limits x0, y0 and xlim, ylim, and page center\n xorigin, yorigin, as well as overall page width and height\n '
xmargin_l = (xl or x)
xmargin_r = (xr or x)
ymargin_top = (yt or y)
ymargin_btm = (yb or y)
(self.x0, self.y0) = ((self.pagesize[0] * xmargin_l), (self.pagesize[1] * ymargin_btm))
(self.xlim, self.ylim) = ((self.pagesize[0] * (1 - xmargin_r)), (self.pagesize[1] * (1 - ymargin_top)))
self.pagewidth = (self.xlim - self.x0)
self.pageheight = (self.ylim - self.y0)
(self.xcenter, self.ycenter) = ((self.x0 + (self.pagewidth / 2.0)), (self.y0 + (self.pageheight / 2.0))) | def set_margins(self, x, y, xl, xr, yt, yb):
'Set page margins.\n\n Arguments:\n - x Float(0->1), Absolute X margin as % of page\n - y Float(0->1), Absolute Y margin as % of page\n - xl Float(0->1), Left X margin as % of page\n - xr Float(0->1), Right X margin as % of page\n - yt Float(0->1), Top Y margin as % of page\n - yb Float(0->1), Bottom Y margin as % of page\n\n Set the page margins as proportions of the page 0->1, and also\n set the page limits x0, y0 and xlim, ylim, and page center\n xorigin, yorigin, as well as overall page width and height\n '
xmargin_l = (xl or x)
xmargin_r = (xr or x)
ymargin_top = (yt or y)
ymargin_btm = (yb or y)
(self.x0, self.y0) = ((self.pagesize[0] * xmargin_l), (self.pagesize[1] * ymargin_btm))
(self.xlim, self.ylim) = ((self.pagesize[0] * (1 - xmargin_r)), (self.pagesize[1] * (1 - ymargin_top)))
self.pagewidth = (self.xlim - self.x0)
self.pageheight = (self.ylim - self.y0)
(self.xcenter, self.ycenter) = ((self.x0 + (self.pagewidth / 2.0)), (self.y0 + (self.pageheight / 2.0)))<|docstring|>Set page margins.
Arguments:
- x Float(0->1), Absolute X margin as % of page
- y Float(0->1), Absolute Y margin as % of page
- xl Float(0->1), Left X margin as % of page
- xr Float(0->1), Right X margin as % of page
- yt Float(0->1), Top Y margin as % of page
- yb Float(0->1), Bottom Y margin as % of page
Set the page margins as proportions of the page 0->1, and also
set the page limits x0, y0 and xlim, ylim, and page center
xorigin, yorigin, as well as overall page width and height<|endoftext|> |
088848e7db950b45ebbec2a7ca741ad5fc59acd1d61fe669d3ae9ba0d36ce2bb | def set_bounds(self, start, end):
'Set start and end points for the drawing as a whole.\n\n Arguments:\n - start - The first base (or feature mark) to draw from\n - end - The last base (or feature mark) to draw to\n\n '
(low, high) = self._parent.range()
if ((start is not None) and (end is not None) and (start > end)):
(start, end) = (end, start)
if ((start is None) or (start < 0)):
start = 0
if ((end is None) or (end < 0)):
end = (high + 1)
(self.start, self.end) = (int(start), int(end))
self.length = ((self.end - self.start) + 1) | Set start and end points for the drawing as a whole.
Arguments:
- start - The first base (or feature mark) to draw from
- end - The last base (or feature mark) to draw to | Bio/Graphics/GenomeDiagram/_AbstractDrawer.py | set_bounds | sgalpha01/biopython | 2,856 | python | def set_bounds(self, start, end):
'Set start and end points for the drawing as a whole.\n\n Arguments:\n - start - The first base (or feature mark) to draw from\n - end - The last base (or feature mark) to draw to\n\n '
(low, high) = self._parent.range()
if ((start is not None) and (end is not None) and (start > end)):
(start, end) = (end, start)
if ((start is None) or (start < 0)):
start = 0
if ((end is None) or (end < 0)):
end = (high + 1)
(self.start, self.end) = (int(start), int(end))
self.length = ((self.end - self.start) + 1) | def set_bounds(self, start, end):
'Set start and end points for the drawing as a whole.\n\n Arguments:\n - start - The first base (or feature mark) to draw from\n - end - The last base (or feature mark) to draw to\n\n '
(low, high) = self._parent.range()
if ((start is not None) and (end is not None) and (start > end)):
(start, end) = (end, start)
if ((start is None) or (start < 0)):
start = 0
if ((end is None) or (end < 0)):
end = (high + 1)
(self.start, self.end) = (int(start), int(end))
self.length = ((self.end - self.start) + 1)<|docstring|>Set start and end points for the drawing as a whole.
Arguments:
- start - The first base (or feature mark) to draw from
- end - The last base (or feature mark) to draw to<|endoftext|> |
cb96256046ca8c50a28db19ea6121bc6ae12fb6b32608137a5163b112850e825 | def is_in_bounds(self, value):
'Check if given value is within the region selected for drawing.\n\n Arguments:\n - value - A base position\n\n '
if ((value >= self.start) and (value <= self.end)):
return 1
return 0 | Check if given value is within the region selected for drawing.
Arguments:
- value - A base position | Bio/Graphics/GenomeDiagram/_AbstractDrawer.py | is_in_bounds | sgalpha01/biopython | 2,856 | python | def is_in_bounds(self, value):
'Check if given value is within the region selected for drawing.\n\n Arguments:\n - value - A base position\n\n '
if ((value >= self.start) and (value <= self.end)):
return 1
return 0 | def is_in_bounds(self, value):
'Check if given value is within the region selected for drawing.\n\n Arguments:\n - value - A base position\n\n '
if ((value >= self.start) and (value <= self.end)):
return 1
return 0<|docstring|>Check if given value is within the region selected for drawing.
Arguments:
- value - A base position<|endoftext|> |
e3afb525ab73f31585e07ba6b1511138aee4441a7005b6abd31f146ca0bbb3a0 | def __len__(self):
'Return the length of the region to be drawn.'
return self.length | Return the length of the region to be drawn. | Bio/Graphics/GenomeDiagram/_AbstractDrawer.py | __len__ | sgalpha01/biopython | 2,856 | python | def __len__(self):
return self.length | def __len__(self):
return self.length<|docstring|>Return the length of the region to be drawn.<|endoftext|> |
484f003eab315579eda292d79c2b76970aaf4090d163a06402f30c05634022e8 | def split_into_chunks(s, k):
'Splits a sentence into lines that are no longer than k characters, without breaking lines.\n\n >>> split_into_chunks("This is a test", 10)\n [\'This is a\', \'test\']\n >>> split_into_chunks("This is technology", 10)\n [\'This is\', \'technology\']\n >>> split_into_chunks("These are cool technologies", 10)\n\n '
result = []
current = []
current_length = (- 1)
for word in s.split():
new_length = len(word)
if (new_length > k):
return
elif (((current_length + 1) + new_length) > k):
result.append(' '.join(current))
current = [word]
current_length = new_length
else:
current.append(word)
current_length += (new_length + 1)
result.append(' '.join(current))
return result | Splits a sentence into lines that are no longer than k characters, without breaking lines.
>>> split_into_chunks("This is a test", 10)
['This is a', 'test']
>>> split_into_chunks("This is technology", 10)
['This is', 'technology']
>>> split_into_chunks("These are cool technologies", 10) | src/split_text.py | split_into_chunks | redfast00/daily-algorithm-challenge | 0 | python | def split_into_chunks(s, k):
'Splits a sentence into lines that are no longer than k characters, without breaking lines.\n\n >>> split_into_chunks("This is a test", 10)\n [\'This is a\', \'test\']\n >>> split_into_chunks("This is technology", 10)\n [\'This is\', \'technology\']\n >>> split_into_chunks("These are cool technologies", 10)\n\n '
result = []
current = []
current_length = (- 1)
for word in s.split():
new_length = len(word)
if (new_length > k):
return
elif (((current_length + 1) + new_length) > k):
result.append(' '.join(current))
current = [word]
current_length = new_length
else:
current.append(word)
current_length += (new_length + 1)
result.append(' '.join(current))
return result | def split_into_chunks(s, k):
'Splits a sentence into lines that are no longer than k characters, without breaking lines.\n\n >>> split_into_chunks("This is a test", 10)\n [\'This is a\', \'test\']\n >>> split_into_chunks("This is technology", 10)\n [\'This is\', \'technology\']\n >>> split_into_chunks("These are cool technologies", 10)\n\n '
result = []
current = []
current_length = (- 1)
for word in s.split():
new_length = len(word)
if (new_length > k):
return
elif (((current_length + 1) + new_length) > k):
result.append(' '.join(current))
current = [word]
current_length = new_length
else:
current.append(word)
current_length += (new_length + 1)
result.append(' '.join(current))
return result<|docstring|>Splits a sentence into lines that are no longer than k characters, without breaking lines.
>>> split_into_chunks("This is a test", 10)
['This is a', 'test']
>>> split_into_chunks("This is technology", 10)
['This is', 'technology']
>>> split_into_chunks("These are cool technologies", 10)<|endoftext|> |
3d7ceb3f0fdfb164f45e8379b1d992041c357bf014671b12e2dc1fc2d83df5f5 | def tokenize(self, sequence: str) -> List[str]:
'Break up a sequence of words into word-level tokens.\n '
normalized = self.normalizer.normalize_str(sequence)
tokenized = self.pre_tokenizer.pre_tokenize_str(normalized)
return [word for (word, _) in tokenized] | Break up a sequence of words into word-level tokens. | kbot.py | tokenize | almonds0166/Kotobot2 | 0 | python | def tokenize(self, sequence: str) -> List[str]:
'\n '
normalized = self.normalizer.normalize_str(sequence)
tokenized = self.pre_tokenizer.pre_tokenize_str(normalized)
return [word for (word, _) in tokenized] | def tokenize(self, sequence: str) -> List[str]:
'\n '
normalized = self.normalizer.normalize_str(sequence)
tokenized = self.pre_tokenizer.pre_tokenize_str(normalized)
return [word for (word, _) in tokenized]<|docstring|>Break up a sequence of words into word-level tokens.<|endoftext|> |
e29f228cf59b961d21afe0bf9dde6f417142fde61081c57c9aa836ea209f19bb | @router.get('/', response_model=List[schemas.User])
def read_users(db: Session=Depends(deps.get_db), skip: int=0, limit: int=100, current_user: models.User=Depends(deps.get_current_active_superuser)) -> Any:
'\n Retrieve users.\n '
users = crud.user.get_multi(db, skip=skip, limit=limit)
return users | Retrieve users. | backend/app/app/api/api_V1/endpoints/users.py | read_users | zhkuo24/full-stack-fastapi-demo | 7 | python | @router.get('/', response_model=List[schemas.User])
def read_users(db: Session=Depends(deps.get_db), skip: int=0, limit: int=100, current_user: models.User=Depends(deps.get_current_active_superuser)) -> Any:
'\n \n '
users = crud.user.get_multi(db, skip=skip, limit=limit)
return users | @router.get('/', response_model=List[schemas.User])
def read_users(db: Session=Depends(deps.get_db), skip: int=0, limit: int=100, current_user: models.User=Depends(deps.get_current_active_superuser)) -> Any:
'\n \n '
users = crud.user.get_multi(db, skip=skip, limit=limit)
return users<|docstring|>Retrieve users.<|endoftext|> |
938f053178ac12c5d8670944b1d8db4d2085c98352cef6adc5c98f9834cd02d2 | @router.post('/', response_model=schemas.User)
def create_user(*, db: Session=Depends(deps.get_db), user_in: schemas.UserCreate, current_user: models.User=Depends(deps.get_current_active_superuser)) -> Any:
'\n create new user\n '
user = crud.user.get_by_email(db, email=user_in.email)
if user:
raise HTTPException(status_code=400, detail='The user with this username already exists in the system.')
user = crud.user.create(db, obj_in=user_in)
if (settings.EMAILS_ENABLED and user_in.email):
send_new_account_email(email_to=user_in.email, username=user_in.email, password=user_in.password)
return user | create new user | backend/app/app/api/api_V1/endpoints/users.py | create_user | zhkuo24/full-stack-fastapi-demo | 7 | python | @router.post('/', response_model=schemas.User)
def create_user(*, db: Session=Depends(deps.get_db), user_in: schemas.UserCreate, current_user: models.User=Depends(deps.get_current_active_superuser)) -> Any:
'\n \n '
user = crud.user.get_by_email(db, email=user_in.email)
if user:
raise HTTPException(status_code=400, detail='The user with this username already exists in the system.')
user = crud.user.create(db, obj_in=user_in)
if (settings.EMAILS_ENABLED and user_in.email):
send_new_account_email(email_to=user_in.email, username=user_in.email, password=user_in.password)
return user | @router.post('/', response_model=schemas.User)
def create_user(*, db: Session=Depends(deps.get_db), user_in: schemas.UserCreate, current_user: models.User=Depends(deps.get_current_active_superuser)) -> Any:
'\n \n '
user = crud.user.get_by_email(db, email=user_in.email)
if user:
raise HTTPException(status_code=400, detail='The user with this username already exists in the system.')
user = crud.user.create(db, obj_in=user_in)
if (settings.EMAILS_ENABLED and user_in.email):
send_new_account_email(email_to=user_in.email, username=user_in.email, password=user_in.password)
return user<|docstring|>create new user<|endoftext|> |
1104bde2d6dbb07bf84ec2844abb52e8ec2a69906a244bf93d58ee07423e08a5 | @router.put('/me', response_model=schemas.User)
def update_user_me(*, db: Session=Depends(deps.get_db), password: str=Body(None), full_name: str=Body(None), email: EmailStr=Body(None), current_user: models.User=Depends(deps.get_current_active_user)) -> Any:
'\n update own user\n '
current_user_data = jsonable_encoder(current_user)
user_in = schemas.UserUpdate(**current_user_data)
if (password is not None):
user_in.password = password
if (full_name is not None):
user_in.full_name = full_name
if (email is not None):
user_in.email = email
user = crud.user.update(db, db_obj=current_user, obj_in=user_in)
return user | update own user | backend/app/app/api/api_V1/endpoints/users.py | update_user_me | zhkuo24/full-stack-fastapi-demo | 7 | python | @router.put('/me', response_model=schemas.User)
def update_user_me(*, db: Session=Depends(deps.get_db), password: str=Body(None), full_name: str=Body(None), email: EmailStr=Body(None), current_user: models.User=Depends(deps.get_current_active_user)) -> Any:
'\n \n '
current_user_data = jsonable_encoder(current_user)
user_in = schemas.UserUpdate(**current_user_data)
if (password is not None):
user_in.password = password
if (full_name is not None):
user_in.full_name = full_name
if (email is not None):
user_in.email = email
user = crud.user.update(db, db_obj=current_user, obj_in=user_in)
return user | @router.put('/me', response_model=schemas.User)
def update_user_me(*, db: Session=Depends(deps.get_db), password: str=Body(None), full_name: str=Body(None), email: EmailStr=Body(None), current_user: models.User=Depends(deps.get_current_active_user)) -> Any:
'\n \n '
current_user_data = jsonable_encoder(current_user)
user_in = schemas.UserUpdate(**current_user_data)
if (password is not None):
user_in.password = password
if (full_name is not None):
user_in.full_name = full_name
if (email is not None):
user_in.email = email
user = crud.user.update(db, db_obj=current_user, obj_in=user_in)
return user<|docstring|>update own user<|endoftext|> |
2272ba27462b4614503a021f2f81f1ac1ec9f54ee8c92adf1bdfd082b9370bf0 | @router.get('/me', response_model=schemas.User)
def read_user_me(db: Session=Depends(deps.get_db), current_user: models.User=Depends(deps.get_current_active_user)) -> Any:
'\n Get current user.\n '
return current_user | Get current user. | backend/app/app/api/api_V1/endpoints/users.py | read_user_me | zhkuo24/full-stack-fastapi-demo | 7 | python | @router.get('/me', response_model=schemas.User)
def read_user_me(db: Session=Depends(deps.get_db), current_user: models.User=Depends(deps.get_current_active_user)) -> Any:
'\n \n '
return current_user | @router.get('/me', response_model=schemas.User)
def read_user_me(db: Session=Depends(deps.get_db), current_user: models.User=Depends(deps.get_current_active_user)) -> Any:
'\n \n '
return current_user<|docstring|>Get current user.<|endoftext|> |
b9b6c8d05342c3f94878065178f1fd7219a914cdeb6b5dd95998c21e04e29d0f | @router.post('/open', response_model=schemas.User)
def create_user_open(*, db: Session=Depends(deps.get_db), password: str=Body(...), email: EmailStr=Body(...), full_name: str=Body(...)) -> Any:
'\n create new user without the need to be logged in\n '
if (not settings.USERS_OPEN_REGISTRATION):
raise HTTPException(status_code=403, detail='Open user registration is forbidden on this server')
user = crud.user.get_by_email(db, email=email)
if user:
raise HTTPException(status_code=400, detail='The user with this username already exists in the system')
user_in = schemas.UserCreate(password=password, email=email, full_name=full_name)
user = crud.user.create(db, obj_in=user_in)
return user | create new user without the need to be logged in | backend/app/app/api/api_V1/endpoints/users.py | create_user_open | zhkuo24/full-stack-fastapi-demo | 7 | python | @router.post('/open', response_model=schemas.User)
def create_user_open(*, db: Session=Depends(deps.get_db), password: str=Body(...), email: EmailStr=Body(...), full_name: str=Body(...)) -> Any:
'\n \n '
if (not settings.USERS_OPEN_REGISTRATION):
raise HTTPException(status_code=403, detail='Open user registration is forbidden on this server')
user = crud.user.get_by_email(db, email=email)
if user:
raise HTTPException(status_code=400, detail='The user with this username already exists in the system')
user_in = schemas.UserCreate(password=password, email=email, full_name=full_name)
user = crud.user.create(db, obj_in=user_in)
return user | @router.post('/open', response_model=schemas.User)
def create_user_open(*, db: Session=Depends(deps.get_db), password: str=Body(...), email: EmailStr=Body(...), full_name: str=Body(...)) -> Any:
'\n \n '
if (not settings.USERS_OPEN_REGISTRATION):
raise HTTPException(status_code=403, detail='Open user registration is forbidden on this server')
user = crud.user.get_by_email(db, email=email)
if user:
raise HTTPException(status_code=400, detail='The user with this username already exists in the system')
user_in = schemas.UserCreate(password=password, email=email, full_name=full_name)
user = crud.user.create(db, obj_in=user_in)
return user<|docstring|>create new user without the need to be logged in<|endoftext|> |
21f7095035a1cc2eea4424a186ed7e0ea1a0bf6a9802fdac212a1098cec156de | @router.get('/{user_id}', response_model=schemas.User)
def read_user_by_id(user_id: int, current_user: models.User=Depends(deps.get_current_active_user), db: Session=Depends(deps.get_db)) -> Any:
'\n Get a specific user by id.\n '
user = crud.user.get(db, _id=user_id)
if (user == current_user):
return user
if (not crud.user.is_superuser(current_user)):
raise HTTPException(status_code=400, detail="The user doesn't have enough privileges")
return user | Get a specific user by id. | backend/app/app/api/api_V1/endpoints/users.py | read_user_by_id | zhkuo24/full-stack-fastapi-demo | 7 | python | @router.get('/{user_id}', response_model=schemas.User)
def read_user_by_id(user_id: int, current_user: models.User=Depends(deps.get_current_active_user), db: Session=Depends(deps.get_db)) -> Any:
'\n \n '
user = crud.user.get(db, _id=user_id)
if (user == current_user):
return user
if (not crud.user.is_superuser(current_user)):
raise HTTPException(status_code=400, detail="The user doesn't have enough privileges")
return user | @router.get('/{user_id}', response_model=schemas.User)
def read_user_by_id(user_id: int, current_user: models.User=Depends(deps.get_current_active_user), db: Session=Depends(deps.get_db)) -> Any:
'\n \n '
user = crud.user.get(db, _id=user_id)
if (user == current_user):
return user
if (not crud.user.is_superuser(current_user)):
raise HTTPException(status_code=400, detail="The user doesn't have enough privileges")
return user<|docstring|>Get a specific user by id.<|endoftext|> |
826afbaf95166d369e36cf4c9b8ee60923ebbcb854809fa42b8cf50d42a32409 | @router.put('/{user_id}', response_model=schemas.User)
def update_user(*, db: Session=Depends(deps.get_db), user_id: int, user_in: schemas.UserUpdate, current_user: models.User=Depends(deps.get_current_active_superuser)) -> Any:
'\n Update a user.\n '
user = crud.user.get(db, _id=user_id)
if (not user):
raise HTTPException(status_code=404, detail='The user with this username does not exist in the system')
user = crud.user.update(db, db_obj=user, obj_in=user_in)
return user | Update a user. | backend/app/app/api/api_V1/endpoints/users.py | update_user | zhkuo24/full-stack-fastapi-demo | 7 | python | @router.put('/{user_id}', response_model=schemas.User)
def update_user(*, db: Session=Depends(deps.get_db), user_id: int, user_in: schemas.UserUpdate, current_user: models.User=Depends(deps.get_current_active_superuser)) -> Any:
'\n \n '
user = crud.user.get(db, _id=user_id)
if (not user):
raise HTTPException(status_code=404, detail='The user with this username does not exist in the system')
user = crud.user.update(db, db_obj=user, obj_in=user_in)
return user | @router.put('/{user_id}', response_model=schemas.User)
def update_user(*, db: Session=Depends(deps.get_db), user_id: int, user_in: schemas.UserUpdate, current_user: models.User=Depends(deps.get_current_active_superuser)) -> Any:
'\n \n '
user = crud.user.get(db, _id=user_id)
if (not user):
raise HTTPException(status_code=404, detail='The user with this username does not exist in the system')
user = crud.user.update(db, db_obj=user, obj_in=user_in)
return user<|docstring|>Update a user.<|endoftext|> |
5674ac506dd1ba4af1f94b469a10d84cca5bf2b8e9d4f4e84aa7928feba36af6 | def rank(df, value_cols: Union[(str, List[str])], group_cols: List[str]=None, rank_cols_names: List[str]=None, method='min', ascending: bool=True):
"\n This function creates rank columns based on numeric values to be ranked.\n\n ---\n\n ### Parameters\n\n *mandatory :*\n - `value_cols` (*list*): name(s) of the columns used\n\n *optional :*\n - `group_cols` (*list*): name(s) of the column(s) used to\n create each group inside which independent ranking needs to be applied\n - `rank_cols_names` (*list*): the names of the added ranking columns.\n If not filled, the ranking will be named after the value_cols with a '_rank' suffix\n - `method` (*str*): method to use when encountering equal values:\n - `'min'` (default): lowest rank in group\n - `'max'`: highest rank in group\n - `'average'`: average rank of group\n - `'first'`: ranks assigned in order the values appear in the series\n - `'dense'`: like 'min', but rank always increases by 1 between groups\n - `ascending` (*boolean*): whether the rank should be determined based on\n ascending (default) or descending order\n\n ---\n\n ### Example\n\n **Input**\n\n | ENTITY | YEAR | VALUE_1 | VALUE_2 |\n | :---: | :---: | :---: | :---: |\n | A | 2017 | 10 | 3 |\n | A | 2017 | 20 | 1 |\n | A | 2018 | 10 | 5 |\n | A | 2018 | 30 | 4 |\n | B | 2017 | 60 | 4 |\n | B | 2017 | 40 | 3 |\n | B | 2018 | 50 | 7 |\n | B | 2018 | 50 | 6 |\n\n ```cson\n rank :\n value_cols: 'VALUE_1'\n ```\n\n **Output**\n\n | ENTITY | YEAR | VALUE_1 | VALUE_2 | VALUE_1_rank\n | :---: | :---: | :---: | :---: | :---: |\n | A | 2017 | 10 | 3 | 1 |\n | A | 2017 | 20 | 1 | 3 |\n | A | 2018 | 10 | 5 | 1 |\n | A | 2018 | 30 | 4 | 4 |\n | B | 2017 | 60 | 4 | 8 |\n | B | 2017 | 40 | 3 | 5 |\n | B | 2018 | 50 | 7 | 6 |\n | B | 2018 | 50 | 6 | 6 |\n "
value_cols = ([value_cols] if (not isinstance(value_cols, list)) else value_cols)
for col in value_cols:
if (not np.issubdtype(df[col].dtype, np.number)):
raise TypeError(f'{col} specified in value_cols must be of numeric type')
if (rank_cols_names is None):
rank_cols_names = [(x + '_rank') for x in value_cols]
if (group_cols is None):
df[rank_cols_names] = df[value_cols].rank(method=method, ascending=ascending)
else:
df[rank_cols_names] = df.groupby(group_cols)[value_cols].rank(method=method, ascending=ascending)
if (method != 'average'):
df[rank_cols_names] = df[rank_cols_names].astype('int')
return df | This function creates rank columns based on numeric values to be ranked.
---
### Parameters
*mandatory :*
- `value_cols` (*list*): name(s) of the columns used
*optional :*
- `group_cols` (*list*): name(s) of the column(s) used to
create each group inside which independent ranking needs to be applied
- `rank_cols_names` (*list*): the names of the added ranking columns.
If not filled, the ranking will be named after the value_cols with a '_rank' suffix
- `method` (*str*): method to use when encountering equal values:
- `'min'` (default): lowest rank in group
- `'max'`: highest rank in group
- `'average'`: average rank of group
- `'first'`: ranks assigned in order the values appear in the series
- `'dense'`: like 'min', but rank always increases by 1 between groups
- `ascending` (*boolean*): whether the rank should be determined based on
ascending (default) or descending order
---
### Example
**Input**
| ENTITY | YEAR | VALUE_1 | VALUE_2 |
| :---: | :---: | :---: | :---: |
| A | 2017 | 10 | 3 |
| A | 2017 | 20 | 1 |
| A | 2018 | 10 | 5 |
| A | 2018 | 30 | 4 |
| B | 2017 | 60 | 4 |
| B | 2017 | 40 | 3 |
| B | 2018 | 50 | 7 |
| B | 2018 | 50 | 6 |
```cson
rank :
value_cols: 'VALUE_1'
```
**Output**
| ENTITY | YEAR | VALUE_1 | VALUE_2 | VALUE_1_rank
| :---: | :---: | :---: | :---: | :---: |
| A | 2017 | 10 | 3 | 1 |
| A | 2017 | 20 | 1 | 3 |
| A | 2018 | 10 | 5 | 1 |
| A | 2018 | 30 | 4 | 4 |
| B | 2017 | 60 | 4 | 8 |
| B | 2017 | 40 | 3 | 5 |
| B | 2018 | 50 | 7 | 6 |
| B | 2018 | 50 | 6 | 6 | | toucan_data_sdk/utils/postprocess/rank.py | rank | ToucanToco/toucan-data-sdk | 9 | python | def rank(df, value_cols: Union[(str, List[str])], group_cols: List[str]=None, rank_cols_names: List[str]=None, method='min', ascending: bool=True):
"\n This function creates rank columns based on numeric values to be ranked.\n\n ---\n\n ### Parameters\n\n *mandatory :*\n - `value_cols` (*list*): name(s) of the columns used\n\n *optional :*\n - `group_cols` (*list*): name(s) of the column(s) used to\n create each group inside which independent ranking needs to be applied\n - `rank_cols_names` (*list*): the names of the added ranking columns.\n If not filled, the ranking will be named after the value_cols with a '_rank' suffix\n - `method` (*str*): method to use when encountering equal values:\n - `'min'` (default): lowest rank in group\n - `'max'`: highest rank in group\n - `'average'`: average rank of group\n - `'first'`: ranks assigned in order the values appear in the series\n - `'dense'`: like 'min', but rank always increases by 1 between groups\n - `ascending` (*boolean*): whether the rank should be determined based on\n ascending (default) or descending order\n\n ---\n\n ### Example\n\n **Input**\n\n | ENTITY | YEAR | VALUE_1 | VALUE_2 |\n | :---: | :---: | :---: | :---: |\n | A | 2017 | 10 | 3 |\n | A | 2017 | 20 | 1 |\n | A | 2018 | 10 | 5 |\n | A | 2018 | 30 | 4 |\n | B | 2017 | 60 | 4 |\n | B | 2017 | 40 | 3 |\n | B | 2018 | 50 | 7 |\n | B | 2018 | 50 | 6 |\n\n ```cson\n rank :\n value_cols: 'VALUE_1'\n ```\n\n **Output**\n\n | ENTITY | YEAR | VALUE_1 | VALUE_2 | VALUE_1_rank\n | :---: | :---: | :---: | :---: | :---: |\n | A | 2017 | 10 | 3 | 1 |\n | A | 2017 | 20 | 1 | 3 |\n | A | 2018 | 10 | 5 | 1 |\n | A | 2018 | 30 | 4 | 4 |\n | B | 2017 | 60 | 4 | 8 |\n | B | 2017 | 40 | 3 | 5 |\n | B | 2018 | 50 | 7 | 6 |\n | B | 2018 | 50 | 6 | 6 |\n "
value_cols = ([value_cols] if (not isinstance(value_cols, list)) else value_cols)
for col in value_cols:
if (not np.issubdtype(df[col].dtype, np.number)):
raise TypeError(f'{col} specified in value_cols must be of numeric type')
if (rank_cols_names is None):
rank_cols_names = [(x + '_rank') for x in value_cols]
if (group_cols is None):
df[rank_cols_names] = df[value_cols].rank(method=method, ascending=ascending)
else:
df[rank_cols_names] = df.groupby(group_cols)[value_cols].rank(method=method, ascending=ascending)
if (method != 'average'):
df[rank_cols_names] = df[rank_cols_names].astype('int')
return df | def rank(df, value_cols: Union[(str, List[str])], group_cols: List[str]=None, rank_cols_names: List[str]=None, method='min', ascending: bool=True):
"\n This function creates rank columns based on numeric values to be ranked.\n\n ---\n\n ### Parameters\n\n *mandatory :*\n - `value_cols` (*list*): name(s) of the columns used\n\n *optional :*\n - `group_cols` (*list*): name(s) of the column(s) used to\n create each group inside which independent ranking needs to be applied\n - `rank_cols_names` (*list*): the names of the added ranking columns.\n If not filled, the ranking will be named after the value_cols with a '_rank' suffix\n - `method` (*str*): method to use when encountering equal values:\n - `'min'` (default): lowest rank in group\n - `'max'`: highest rank in group\n - `'average'`: average rank of group\n - `'first'`: ranks assigned in order the values appear in the series\n - `'dense'`: like 'min', but rank always increases by 1 between groups\n - `ascending` (*boolean*): whether the rank should be determined based on\n ascending (default) or descending order\n\n ---\n\n ### Example\n\n **Input**\n\n | ENTITY | YEAR | VALUE_1 | VALUE_2 |\n | :---: | :---: | :---: | :---: |\n | A | 2017 | 10 | 3 |\n | A | 2017 | 20 | 1 |\n | A | 2018 | 10 | 5 |\n | A | 2018 | 30 | 4 |\n | B | 2017 | 60 | 4 |\n | B | 2017 | 40 | 3 |\n | B | 2018 | 50 | 7 |\n | B | 2018 | 50 | 6 |\n\n ```cson\n rank :\n value_cols: 'VALUE_1'\n ```\n\n **Output**\n\n | ENTITY | YEAR | VALUE_1 | VALUE_2 | VALUE_1_rank\n | :---: | :---: | :---: | :---: | :---: |\n | A | 2017 | 10 | 3 | 1 |\n | A | 2017 | 20 | 1 | 3 |\n | A | 2018 | 10 | 5 | 1 |\n | A | 2018 | 30 | 4 | 4 |\n | B | 2017 | 60 | 4 | 8 |\n | B | 2017 | 40 | 3 | 5 |\n | B | 2018 | 50 | 7 | 6 |\n | B | 2018 | 50 | 6 | 6 |\n "
value_cols = ([value_cols] if (not isinstance(value_cols, list)) else value_cols)
for col in value_cols:
if (not np.issubdtype(df[col].dtype, np.number)):
raise TypeError(f'{col} specified in value_cols must be of numeric type')
if (rank_cols_names is None):
rank_cols_names = [(x + '_rank') for x in value_cols]
if (group_cols is None):
df[rank_cols_names] = df[value_cols].rank(method=method, ascending=ascending)
else:
df[rank_cols_names] = df.groupby(group_cols)[value_cols].rank(method=method, ascending=ascending)
if (method != 'average'):
df[rank_cols_names] = df[rank_cols_names].astype('int')
return df<|docstring|>This function creates rank columns based on numeric values to be ranked.
---
### Parameters
*mandatory :*
- `value_cols` (*list*): name(s) of the columns used
*optional :*
- `group_cols` (*list*): name(s) of the column(s) used to
create each group inside which independent ranking needs to be applied
- `rank_cols_names` (*list*): the names of the added ranking columns.
If not filled, the ranking will be named after the value_cols with a '_rank' suffix
- `method` (*str*): method to use when encountering equal values:
- `'min'` (default): lowest rank in group
- `'max'`: highest rank in group
- `'average'`: average rank of group
- `'first'`: ranks assigned in order the values appear in the series
- `'dense'`: like 'min', but rank always increases by 1 between groups
- `ascending` (*boolean*): whether the rank should be determined based on
ascending (default) or descending order
---
### Example
**Input**
| ENTITY | YEAR | VALUE_1 | VALUE_2 |
| :---: | :---: | :---: | :---: |
| A | 2017 | 10 | 3 |
| A | 2017 | 20 | 1 |
| A | 2018 | 10 | 5 |
| A | 2018 | 30 | 4 |
| B | 2017 | 60 | 4 |
| B | 2017 | 40 | 3 |
| B | 2018 | 50 | 7 |
| B | 2018 | 50 | 6 |
```cson
rank :
value_cols: 'VALUE_1'
```
**Output**
| ENTITY | YEAR | VALUE_1 | VALUE_2 | VALUE_1_rank
| :---: | :---: | :---: | :---: | :---: |
| A | 2017 | 10 | 3 | 1 |
| A | 2017 | 20 | 1 | 3 |
| A | 2018 | 10 | 5 | 1 |
| A | 2018 | 30 | 4 | 4 |
| B | 2017 | 60 | 4 | 8 |
| B | 2017 | 40 | 3 | 5 |
| B | 2018 | 50 | 7 | 6 |
| B | 2018 | 50 | 6 | 6 |<|endoftext|> |
fd30a8a11a59427ee8bb771561e79678af9dadfd4a0f308ea804da558aa329e2 | def _compute_uvtuv_z(z, uvtuv):
' compute uvtuv_z\n\n Parameters\n ----------\n z : array, shape (n_atoms, n_times_valid) temporal components\n uvtuv : array, shape (n_atoms, n_atoms, 2 * n_times_atom - 1) precomputed\n operator\n\n Return\n ------\n uvtuv_z : array, shape (n_atoms, n_times_valid) computed operator image\n '
(n_atoms, n_times_valid) = z.shape
uvtuv_z = np.empty((n_atoms, n_times_valid))
for k0 in range(n_atoms):
_sum = np.convolve(z[(0, :)], uvtuv[(k0, 0, :)], mode='same')
for k in range(1, n_atoms):
_sum += np.convolve(z[(k, :)], uvtuv[(k0, k, :)], mode='same')
uvtuv_z[(k0, :)] = _sum
return uvtuv_z | compute uvtuv_z
Parameters
----------
z : array, shape (n_atoms, n_times_valid) temporal components
uvtuv : array, shape (n_atoms, n_atoms, 2 * n_times_atom - 1) precomputed
operator
Return
------
uvtuv_z : array, shape (n_atoms, n_times_valid) computed operator image | hemolearn/utils.py | _compute_uvtuv_z | hemolearn/hemolearn | 0 | python | def _compute_uvtuv_z(z, uvtuv):
' compute uvtuv_z\n\n Parameters\n ----------\n z : array, shape (n_atoms, n_times_valid) temporal components\n uvtuv : array, shape (n_atoms, n_atoms, 2 * n_times_atom - 1) precomputed\n operator\n\n Return\n ------\n uvtuv_z : array, shape (n_atoms, n_times_valid) computed operator image\n '
(n_atoms, n_times_valid) = z.shape
uvtuv_z = np.empty((n_atoms, n_times_valid))
for k0 in range(n_atoms):
_sum = np.convolve(z[(0, :)], uvtuv[(k0, 0, :)], mode='same')
for k in range(1, n_atoms):
_sum += np.convolve(z[(k, :)], uvtuv[(k0, k, :)], mode='same')
uvtuv_z[(k0, :)] = _sum
return uvtuv_z | def _compute_uvtuv_z(z, uvtuv):
' compute uvtuv_z\n\n Parameters\n ----------\n z : array, shape (n_atoms, n_times_valid) temporal components\n uvtuv : array, shape (n_atoms, n_atoms, 2 * n_times_atom - 1) precomputed\n operator\n\n Return\n ------\n uvtuv_z : array, shape (n_atoms, n_times_valid) computed operator image\n '
(n_atoms, n_times_valid) = z.shape
uvtuv_z = np.empty((n_atoms, n_times_valid))
for k0 in range(n_atoms):
_sum = np.convolve(z[(0, :)], uvtuv[(k0, 0, :)], mode='same')
for k in range(1, n_atoms):
_sum += np.convolve(z[(k, :)], uvtuv[(k0, k, :)], mode='same')
uvtuv_z[(k0, :)] = _sum
return uvtuv_z<|docstring|>compute uvtuv_z
Parameters
----------
z : array, shape (n_atoms, n_times_valid) temporal components
uvtuv : array, shape (n_atoms, n_atoms, 2 * n_times_atom - 1) precomputed
operator
Return
------
uvtuv_z : array, shape (n_atoms, n_times_valid) computed operator image<|endoftext|> |
4f6eccdd732048b73df0cb3ebb0ae8a29ec0b183b2418d20f1d0e9e397fdf9c7 | def lipschitz_est(AtA, shape, nb_iter=30, tol=1e-06, verbose=False):
' Estimate the Lipschitz constant of the operator AtA.\n\n Parameters\n ----------\n AtA : func, the operator\n shape : tuple, the dimension variable space\n nb_iter : int, default(=30), the maximum number of iteration for the\n estimation\n tol : float, default(=1.0e-6), the tolerance to do early stopping\n verbose : bool, default(=False), the verbose\n\n Return\n ------\n L : float, Lipschitz constant of the operator\n '
x_old = np.random.randn(*shape)
converge = False
for _ in range(nb_iter):
x_new = (AtA(x_old) / np.linalg.norm(x_old))
if (np.abs((np.linalg.norm(x_new) - np.linalg.norm(x_old))) < tol):
converge = True
break
x_old = x_new
if ((not converge) and verbose):
print('Spectral radius estimation did not converge')
return np.linalg.norm(x_new) | Estimate the Lipschitz constant of the operator AtA.
Parameters
----------
AtA : func, the operator
shape : tuple, the dimension variable space
nb_iter : int, default(=30), the maximum number of iteration for the
estimation
tol : float, default(=1.0e-6), the tolerance to do early stopping
verbose : bool, default(=False), the verbose
Return
------
L : float, Lipschitz constant of the operator | hemolearn/utils.py | lipschitz_est | hemolearn/hemolearn | 0 | python | def lipschitz_est(AtA, shape, nb_iter=30, tol=1e-06, verbose=False):
' Estimate the Lipschitz constant of the operator AtA.\n\n Parameters\n ----------\n AtA : func, the operator\n shape : tuple, the dimension variable space\n nb_iter : int, default(=30), the maximum number of iteration for the\n estimation\n tol : float, default(=1.0e-6), the tolerance to do early stopping\n verbose : bool, default(=False), the verbose\n\n Return\n ------\n L : float, Lipschitz constant of the operator\n '
x_old = np.random.randn(*shape)
converge = False
for _ in range(nb_iter):
x_new = (AtA(x_old) / np.linalg.norm(x_old))
if (np.abs((np.linalg.norm(x_new) - np.linalg.norm(x_old))) < tol):
converge = True
break
x_old = x_new
if ((not converge) and verbose):
print('Spectral radius estimation did not converge')
return np.linalg.norm(x_new) | def lipschitz_est(AtA, shape, nb_iter=30, tol=1e-06, verbose=False):
' Estimate the Lipschitz constant of the operator AtA.\n\n Parameters\n ----------\n AtA : func, the operator\n shape : tuple, the dimension variable space\n nb_iter : int, default(=30), the maximum number of iteration for the\n estimation\n tol : float, default(=1.0e-6), the tolerance to do early stopping\n verbose : bool, default(=False), the verbose\n\n Return\n ------\n L : float, Lipschitz constant of the operator\n '
x_old = np.random.randn(*shape)
converge = False
for _ in range(nb_iter):
x_new = (AtA(x_old) / np.linalg.norm(x_old))
if (np.abs((np.linalg.norm(x_new) - np.linalg.norm(x_old))) < tol):
converge = True
break
x_old = x_new
if ((not converge) and verbose):
print('Spectral radius estimation did not converge')
return np.linalg.norm(x_new)<|docstring|>Estimate the Lipschitz constant of the operator AtA.
Parameters
----------
AtA : func, the operator
shape : tuple, the dimension variable space
nb_iter : int, default(=30), the maximum number of iteration for the
estimation
tol : float, default(=1.0e-6), the tolerance to do early stopping
verbose : bool, default(=False), the verbose
Return
------
L : float, Lipschitz constant of the operator<|endoftext|> |
bbf795e8e0a51a3ef9a873a85884ecc0c3006f3a1da7c61abbd51526909e65d4 | def fwhm(t_r, hrf):
'Return the full width at half maximum of the HRF.\n\n Parameters\n ----------\n t : array, shape (n_times_atom, ), the time\n hrf : array, shape (n_times_atom, ), HRF\n\n Return\n ------\n s : float, the full width at half maximum of the HRF\n '
(peaks_in_idx, _) = find_peaks(hrf)
(fwhm_in_idx, _, _, _) = peak_widths(hrf, peaks_in_idx, rel_height=0.5)
fwhm_in_idx = fwhm_in_idx[0]
return (t_r * int(fwhm_in_idx)) | Return the full width at half maximum of the HRF.
Parameters
----------
t : array, shape (n_times_atom, ), the time
hrf : array, shape (n_times_atom, ), HRF
Return
------
s : float, the full width at half maximum of the HRF | hemolearn/utils.py | fwhm | hemolearn/hemolearn | 0 | python | def fwhm(t_r, hrf):
'Return the full width at half maximum of the HRF.\n\n Parameters\n ----------\n t : array, shape (n_times_atom, ), the time\n hrf : array, shape (n_times_atom, ), HRF\n\n Return\n ------\n s : float, the full width at half maximum of the HRF\n '
(peaks_in_idx, _) = find_peaks(hrf)
(fwhm_in_idx, _, _, _) = peak_widths(hrf, peaks_in_idx, rel_height=0.5)
fwhm_in_idx = fwhm_in_idx[0]
return (t_r * int(fwhm_in_idx)) | def fwhm(t_r, hrf):
'Return the full width at half maximum of the HRF.\n\n Parameters\n ----------\n t : array, shape (n_times_atom, ), the time\n hrf : array, shape (n_times_atom, ), HRF\n\n Return\n ------\n s : float, the full width at half maximum of the HRF\n '
(peaks_in_idx, _) = find_peaks(hrf)
(fwhm_in_idx, _, _, _) = peak_widths(hrf, peaks_in_idx, rel_height=0.5)
fwhm_in_idx = fwhm_in_idx[0]
return (t_r * int(fwhm_in_idx))<|docstring|>Return the full width at half maximum of the HRF.
Parameters
----------
t : array, shape (n_times_atom, ), the time
hrf : array, shape (n_times_atom, ), HRF
Return
------
s : float, the full width at half maximum of the HRF<|endoftext|> |
bdf32fa69f489517a16e7930bb8bf2f094f4625c762a5b8ba160a118a575804f | def tp(t_r, hrf):
' Return time to peak oh the signal of the HRF.\n\n Parameters\n ----------\n t : array, shape (n_times_atom, ), the time\n hrf : array, shape (n_times_atom, ), HRF\n\n Return\n ------\n s : float, time to peak oh the signal of the HRF\n '
n_times_atom = len(hrf)
t = np.linspace(0.0, (t_r * n_times_atom), n_times_atom)
return t[np.argmax(hrf)] | Return time to peak oh the signal of the HRF.
Parameters
----------
t : array, shape (n_times_atom, ), the time
hrf : array, shape (n_times_atom, ), HRF
Return
------
s : float, time to peak oh the signal of the HRF | hemolearn/utils.py | tp | hemolearn/hemolearn | 0 | python | def tp(t_r, hrf):
' Return time to peak oh the signal of the HRF.\n\n Parameters\n ----------\n t : array, shape (n_times_atom, ), the time\n hrf : array, shape (n_times_atom, ), HRF\n\n Return\n ------\n s : float, time to peak oh the signal of the HRF\n '
n_times_atom = len(hrf)
t = np.linspace(0.0, (t_r * n_times_atom), n_times_atom)
return t[np.argmax(hrf)] | def tp(t_r, hrf):
' Return time to peak oh the signal of the HRF.\n\n Parameters\n ----------\n t : array, shape (n_times_atom, ), the time\n hrf : array, shape (n_times_atom, ), HRF\n\n Return\n ------\n s : float, time to peak oh the signal of the HRF\n '
n_times_atom = len(hrf)
t = np.linspace(0.0, (t_r * n_times_atom), n_times_atom)
return t[np.argmax(hrf)]<|docstring|>Return time to peak oh the signal of the HRF.
Parameters
----------
t : array, shape (n_times_atom, ), the time
hrf : array, shape (n_times_atom, ), HRF
Return
------
s : float, time to peak oh the signal of the HRF<|endoftext|> |
13f802bd2ce9d7f4ff5816b81dee715766c83fc0d31f1384d3f032537d284a9a | def add_gaussian_noise(signal, snr, random_state=None):
' Add a Gaussian noise to inout signal to output a noisy signal with the\n targeted SNR.\n\n Parameters\n ----------\n signal : array, the given signal on which add a Guassian noise.\n snr : float, the expected SNR for the output signal.\n random_state : int or None (default=None),\n Whether to impose a seed on the random generation or not (for\n reproductability).\n\n Return\n ------\n noisy_signal : array, the noisy produced signal.\n noise : array, the additif produced noise.\n '
rng = check_random_state(random_state)
s_shape = signal.shape
noise = rng.randn(*s_shape)
true_snr_num = np.linalg.norm(signal)
true_snr_deno = np.linalg.norm(noise)
true_snr = (true_snr_num / (true_snr_deno + np.finfo(np.float).eps))
std_dev = ((1.0 / np.sqrt((10 ** (snr / 10.0)))) * true_snr)
noise = (std_dev * noise)
noisy_signal = (signal + noise)
return (noisy_signal, noise) | Add a Gaussian noise to inout signal to output a noisy signal with the
targeted SNR.
Parameters
----------
signal : array, the given signal on which add a Guassian noise.
snr : float, the expected SNR for the output signal.
random_state : int or None (default=None),
Whether to impose a seed on the random generation or not (for
reproductability).
Return
------
noisy_signal : array, the noisy produced signal.
noise : array, the additif produced noise. | hemolearn/utils.py | add_gaussian_noise | hemolearn/hemolearn | 0 | python | def add_gaussian_noise(signal, snr, random_state=None):
' Add a Gaussian noise to inout signal to output a noisy signal with the\n targeted SNR.\n\n Parameters\n ----------\n signal : array, the given signal on which add a Guassian noise.\n snr : float, the expected SNR for the output signal.\n random_state : int or None (default=None),\n Whether to impose a seed on the random generation or not (for\n reproductability).\n\n Return\n ------\n noisy_signal : array, the noisy produced signal.\n noise : array, the additif produced noise.\n '
rng = check_random_state(random_state)
s_shape = signal.shape
noise = rng.randn(*s_shape)
true_snr_num = np.linalg.norm(signal)
true_snr_deno = np.linalg.norm(noise)
true_snr = (true_snr_num / (true_snr_deno + np.finfo(np.float).eps))
std_dev = ((1.0 / np.sqrt((10 ** (snr / 10.0)))) * true_snr)
noise = (std_dev * noise)
noisy_signal = (signal + noise)
return (noisy_signal, noise) | def add_gaussian_noise(signal, snr, random_state=None):
' Add a Gaussian noise to inout signal to output a noisy signal with the\n targeted SNR.\n\n Parameters\n ----------\n signal : array, the given signal on which add a Guassian noise.\n snr : float, the expected SNR for the output signal.\n random_state : int or None (default=None),\n Whether to impose a seed on the random generation or not (for\n reproductability).\n\n Return\n ------\n noisy_signal : array, the noisy produced signal.\n noise : array, the additif produced noise.\n '
rng = check_random_state(random_state)
s_shape = signal.shape
noise = rng.randn(*s_shape)
true_snr_num = np.linalg.norm(signal)
true_snr_deno = np.linalg.norm(noise)
true_snr = (true_snr_num / (true_snr_deno + np.finfo(np.float).eps))
std_dev = ((1.0 / np.sqrt((10 ** (snr / 10.0)))) * true_snr)
noise = (std_dev * noise)
noisy_signal = (signal + noise)
return (noisy_signal, noise)<|docstring|>Add a Gaussian noise to inout signal to output a noisy signal with the
targeted SNR.
Parameters
----------
signal : array, the given signal on which add a Guassian noise.
snr : float, the expected SNR for the output signal.
random_state : int or None (default=None),
Whether to impose a seed on the random generation or not (for
reproductability).
Return
------
noisy_signal : array, the noisy produced signal.
noise : array, the additif produced noise.<|endoftext|> |
452b586c2f7ed945e08ca984175bf0bc1c9192ba6d7abaa79153e2c95ef90604 | def sort_by_expl_var(u, z, v, hrf_rois):
' Sorted the temporal the spatial maps and the associated activation by\n explained variance.\n\n Parameters\n ----------\n u : array, shape (n_atoms, n_voxels), spatial maps\n z : array, shape (n_atoms, n_times_valid), temporal components\n v : array, shape (n_hrf_rois, n_times_atom), HRFs\n hrf_rois : dict (key: ROIs labels, value: indices of voxels of the ROI)\n atlas HRF\n\n Return\n ------\n u : array, shape (n_atoms, n_voxels), the order spatial maps\n z : array, shape (n_atoms, n_times_valid), the order temporal components\n variances : array, shape (n_atoms, ) the order variances for each\n components\n '
(rois_idx, _, n_hrf_rois) = split_atlas(hrf_rois)
(n_atoms, n_voxels) = u.shape
(_, n_times_valid) = z.shape
(n_hrf_rois, n_times_atom) = v.shape
n_times = ((n_times_valid + n_times_atom) - 1)
variances = np.empty(n_atoms)
for k in range(n_atoms):
X_hat = np.empty((n_voxels, n_times))
for m in range(n_hrf_rois):
voxels_idx = rois_idx[(m, 1:rois_idx[(m, 0)])]
for j in voxels_idx:
X_hat[(j, :)] = np.convolve((u[(k, j)] * v[(m, :)]), z[(k, :)])
variances[k] = np.var(X_hat)
order = np.argsort(variances)[::(- 1)]
return (u[(order, :)], z[(order, :)], variances[order]) | Sorted the temporal the spatial maps and the associated activation by
explained variance.
Parameters
----------
u : array, shape (n_atoms, n_voxels), spatial maps
z : array, shape (n_atoms, n_times_valid), temporal components
v : array, shape (n_hrf_rois, n_times_atom), HRFs
hrf_rois : dict (key: ROIs labels, value: indices of voxels of the ROI)
atlas HRF
Return
------
u : array, shape (n_atoms, n_voxels), the order spatial maps
z : array, shape (n_atoms, n_times_valid), the order temporal components
variances : array, shape (n_atoms, ) the order variances for each
components | hemolearn/utils.py | sort_by_expl_var | hemolearn/hemolearn | 0 | python | def sort_by_expl_var(u, z, v, hrf_rois):
' Sorted the temporal the spatial maps and the associated activation by\n explained variance.\n\n Parameters\n ----------\n u : array, shape (n_atoms, n_voxels), spatial maps\n z : array, shape (n_atoms, n_times_valid), temporal components\n v : array, shape (n_hrf_rois, n_times_atom), HRFs\n hrf_rois : dict (key: ROIs labels, value: indices of voxels of the ROI)\n atlas HRF\n\n Return\n ------\n u : array, shape (n_atoms, n_voxels), the order spatial maps\n z : array, shape (n_atoms, n_times_valid), the order temporal components\n variances : array, shape (n_atoms, ) the order variances for each\n components\n '
(rois_idx, _, n_hrf_rois) = split_atlas(hrf_rois)
(n_atoms, n_voxels) = u.shape
(_, n_times_valid) = z.shape
(n_hrf_rois, n_times_atom) = v.shape
n_times = ((n_times_valid + n_times_atom) - 1)
variances = np.empty(n_atoms)
for k in range(n_atoms):
X_hat = np.empty((n_voxels, n_times))
for m in range(n_hrf_rois):
voxels_idx = rois_idx[(m, 1:rois_idx[(m, 0)])]
for j in voxels_idx:
X_hat[(j, :)] = np.convolve((u[(k, j)] * v[(m, :)]), z[(k, :)])
variances[k] = np.var(X_hat)
order = np.argsort(variances)[::(- 1)]
return (u[(order, :)], z[(order, :)], variances[order]) | def sort_by_expl_var(u, z, v, hrf_rois):
' Sorted the temporal the spatial maps and the associated activation by\n explained variance.\n\n Parameters\n ----------\n u : array, shape (n_atoms, n_voxels), spatial maps\n z : array, shape (n_atoms, n_times_valid), temporal components\n v : array, shape (n_hrf_rois, n_times_atom), HRFs\n hrf_rois : dict (key: ROIs labels, value: indices of voxels of the ROI)\n atlas HRF\n\n Return\n ------\n u : array, shape (n_atoms, n_voxels), the order spatial maps\n z : array, shape (n_atoms, n_times_valid), the order temporal components\n variances : array, shape (n_atoms, ) the order variances for each\n components\n '
(rois_idx, _, n_hrf_rois) = split_atlas(hrf_rois)
(n_atoms, n_voxels) = u.shape
(_, n_times_valid) = z.shape
(n_hrf_rois, n_times_atom) = v.shape
n_times = ((n_times_valid + n_times_atom) - 1)
variances = np.empty(n_atoms)
for k in range(n_atoms):
X_hat = np.empty((n_voxels, n_times))
for m in range(n_hrf_rois):
voxels_idx = rois_idx[(m, 1:rois_idx[(m, 0)])]
for j in voxels_idx:
X_hat[(j, :)] = np.convolve((u[(k, j)] * v[(m, :)]), z[(k, :)])
variances[k] = np.var(X_hat)
order = np.argsort(variances)[::(- 1)]
return (u[(order, :)], z[(order, :)], variances[order])<|docstring|>Sorted the temporal the spatial maps and the associated activation by
explained variance.
Parameters
----------
u : array, shape (n_atoms, n_voxels), spatial maps
z : array, shape (n_atoms, n_times_valid), temporal components
v : array, shape (n_hrf_rois, n_times_atom), HRFs
hrf_rois : dict (key: ROIs labels, value: indices of voxels of the ROI)
atlas HRF
Return
------
u : array, shape (n_atoms, n_voxels), the order spatial maps
z : array, shape (n_atoms, n_times_valid), the order temporal components
variances : array, shape (n_atoms, ) the order variances for each
components<|endoftext|> |
729c5435a5a921e6d17d398d9ad7f032c571a2e3f52f2eafa9b3205726dc8712 | def _set_up_test(seed):
' General set up function for the tests.\n\n Parameters\n ----------\n seed : None, int, random-instance, (default=None), random-instance\n or random-seed used to initialize the analysis\n\n Return\n ------\n kwargs : dict, the setting to make unitary tests the keys are (t_r,\n n_hrf_rois, n_atoms, n_voxels, n_times, n_times_atom, n_times_valid,\n rois_idx, X, z, u, H, v, B, C)\n '
rng = check_random_state(None)
t_r = 1.0
n_hrf_rois = 2
(n_atoms, n_voxels) = (4, 200)
(n_times, n_times_atom) = (100, 20)
n_times_valid = ((n_times - n_times_atom) + 1)
labels = np.arange(n_hrf_rois, dtype=int)
indices = np.split(np.arange(n_voxels, dtype=int), n_hrf_rois)
hrf_rois = dict(zip(labels, indices))
(rois_idx, _, n_hrf_rois) = split_atlas(hrf_rois)
X = rng.randn(n_voxels, n_times)
u = rng.randn(n_atoms, n_voxels)
z = rng.randn(n_atoms, n_times_valid)
v = np.r_[[scaled_hrf(delta=1.0, t_r=t_r, n_times_atom=n_times_atom) for _ in range(n_hrf_rois)]]
H = np.empty((n_hrf_rois, n_times, n_times_valid))
for m in range(n_hrf_rois):
H[(m, ...)] = make_toeplitz(v[m], n_times_valid)
(B, C) = _precompute_B_C(X, z, H, rois_idx)
kwargs = dict(t_r=t_r, n_hrf_rois=n_hrf_rois, n_atoms=n_atoms, n_voxels=n_voxels, n_times=n_times, rng=rng, n_times_atom=n_times_atom, n_times_valid=n_times_valid, rois_idx=rois_idx, X=X, z=z, u=u, H=H, v=v, B=B, C=C)
return kwargs | General set up function for the tests.
Parameters
----------
seed : None, int, random-instance, (default=None), random-instance
or random-seed used to initialize the analysis
Return
------
kwargs : dict, the setting to make unitary tests the keys are (t_r,
n_hrf_rois, n_atoms, n_voxels, n_times, n_times_atom, n_times_valid,
rois_idx, X, z, u, H, v, B, C) | hemolearn/utils.py | _set_up_test | hemolearn/hemolearn | 0 | python | def _set_up_test(seed):
' General set up function for the tests.\n\n Parameters\n ----------\n seed : None, int, random-instance, (default=None), random-instance\n or random-seed used to initialize the analysis\n\n Return\n ------\n kwargs : dict, the setting to make unitary tests the keys are (t_r,\n n_hrf_rois, n_atoms, n_voxels, n_times, n_times_atom, n_times_valid,\n rois_idx, X, z, u, H, v, B, C)\n '
rng = check_random_state(None)
t_r = 1.0
n_hrf_rois = 2
(n_atoms, n_voxels) = (4, 200)
(n_times, n_times_atom) = (100, 20)
n_times_valid = ((n_times - n_times_atom) + 1)
labels = np.arange(n_hrf_rois, dtype=int)
indices = np.split(np.arange(n_voxels, dtype=int), n_hrf_rois)
hrf_rois = dict(zip(labels, indices))
(rois_idx, _, n_hrf_rois) = split_atlas(hrf_rois)
X = rng.randn(n_voxels, n_times)
u = rng.randn(n_atoms, n_voxels)
z = rng.randn(n_atoms, n_times_valid)
v = np.r_[[scaled_hrf(delta=1.0, t_r=t_r, n_times_atom=n_times_atom) for _ in range(n_hrf_rois)]]
H = np.empty((n_hrf_rois, n_times, n_times_valid))
for m in range(n_hrf_rois):
H[(m, ...)] = make_toeplitz(v[m], n_times_valid)
(B, C) = _precompute_B_C(X, z, H, rois_idx)
kwargs = dict(t_r=t_r, n_hrf_rois=n_hrf_rois, n_atoms=n_atoms, n_voxels=n_voxels, n_times=n_times, rng=rng, n_times_atom=n_times_atom, n_times_valid=n_times_valid, rois_idx=rois_idx, X=X, z=z, u=u, H=H, v=v, B=B, C=C)
return kwargs | def _set_up_test(seed):
' General set up function for the tests.\n\n Parameters\n ----------\n seed : None, int, random-instance, (default=None), random-instance\n or random-seed used to initialize the analysis\n\n Return\n ------\n kwargs : dict, the setting to make unitary tests the keys are (t_r,\n n_hrf_rois, n_atoms, n_voxels, n_times, n_times_atom, n_times_valid,\n rois_idx, X, z, u, H, v, B, C)\n '
rng = check_random_state(None)
t_r = 1.0
n_hrf_rois = 2
(n_atoms, n_voxels) = (4, 200)
(n_times, n_times_atom) = (100, 20)
n_times_valid = ((n_times - n_times_atom) + 1)
labels = np.arange(n_hrf_rois, dtype=int)
indices = np.split(np.arange(n_voxels, dtype=int), n_hrf_rois)
hrf_rois = dict(zip(labels, indices))
(rois_idx, _, n_hrf_rois) = split_atlas(hrf_rois)
X = rng.randn(n_voxels, n_times)
u = rng.randn(n_atoms, n_voxels)
z = rng.randn(n_atoms, n_times_valid)
v = np.r_[[scaled_hrf(delta=1.0, t_r=t_r, n_times_atom=n_times_atom) for _ in range(n_hrf_rois)]]
H = np.empty((n_hrf_rois, n_times, n_times_valid))
for m in range(n_hrf_rois):
H[(m, ...)] = make_toeplitz(v[m], n_times_valid)
(B, C) = _precompute_B_C(X, z, H, rois_idx)
kwargs = dict(t_r=t_r, n_hrf_rois=n_hrf_rois, n_atoms=n_atoms, n_voxels=n_voxels, n_times=n_times, rng=rng, n_times_atom=n_times_atom, n_times_valid=n_times_valid, rois_idx=rois_idx, X=X, z=z, u=u, H=H, v=v, B=B, C=C)
return kwargs<|docstring|>General set up function for the tests.
Parameters
----------
seed : None, int, random-instance, (default=None), random-instance
or random-seed used to initialize the analysis
Return
------
kwargs : dict, the setting to make unitary tests the keys are (t_r,
n_hrf_rois, n_atoms, n_voxels, n_times, n_times_atom, n_times_valid,
rois_idx, X, z, u, H, v, B, C)<|endoftext|> |
6ee0de50aa1a710c51a49e2d3767099ec1363df53036d3a93164cf30a341cca4 | def th(x, t, absolute=True):
'Return threshold level to retain t entries of array x.'
if isinstance(t, str):
t = (float(t[:(- 1)]) / 100.0)
elif isinstance(t, float):
pass
else:
raise ValueError(f"t (={t}) type not understtod: shoud be a float between 0 and 1 or a string such as '80%'")
n = (- int((t * len(x.flatten()))))
if absolute:
return np.sort(np.abs(x.flatten()))[n]
else:
return np.sort(x.flatten())[n] | Return threshold level to retain t entries of array x. | hemolearn/utils.py | th | hemolearn/hemolearn | 0 | python | def th(x, t, absolute=True):
if isinstance(t, str):
t = (float(t[:(- 1)]) / 100.0)
elif isinstance(t, float):
pass
else:
raise ValueError(f"t (={t}) type not understtod: shoud be a float between 0 and 1 or a string such as '80%'")
n = (- int((t * len(x.flatten()))))
if absolute:
return np.sort(np.abs(x.flatten()))[n]
else:
return np.sort(x.flatten())[n] | def th(x, t, absolute=True):
if isinstance(t, str):
t = (float(t[:(- 1)]) / 100.0)
elif isinstance(t, float):
pass
else:
raise ValueError(f"t (={t}) type not understtod: shoud be a float between 0 and 1 or a string such as '80%'")
n = (- int((t * len(x.flatten()))))
if absolute:
return np.sort(np.abs(x.flatten()))[n]
else:
return np.sort(x.flatten())[n]<|docstring|>Return threshold level to retain t entries of array x.<|endoftext|> |
ba493dea4199857414e7858e097aa3e0e3a952ef5f54d65d48ba90586ae6e647 | def profile_me(func):
' Profiling decorator, produce a report <func-name>.profile to be open as\n `python -m snakeviz <func-name>.profile`\n\n Parameters\n ----------\n func : func, function to profile\n '
def profiled_func(*args, **kwargs):
filename = (func.__name__ + '.profile')
prof = cProfile.Profile()
ret = prof.runcall(func, *args, **kwargs)
prof.dump_stats(filename)
return ret
return profiled_func | Profiling decorator, produce a report <func-name>.profile to be open as
`python -m snakeviz <func-name>.profile`
Parameters
----------
func : func, function to profile | hemolearn/utils.py | profile_me | hemolearn/hemolearn | 0 | python | def profile_me(func):
' Profiling decorator, produce a report <func-name>.profile to be open as\n `python -m snakeviz <func-name>.profile`\n\n Parameters\n ----------\n func : func, function to profile\n '
def profiled_func(*args, **kwargs):
filename = (func.__name__ + '.profile')
prof = cProfile.Profile()
ret = prof.runcall(func, *args, **kwargs)
prof.dump_stats(filename)
return ret
return profiled_func | def profile_me(func):
' Profiling decorator, produce a report <func-name>.profile to be open as\n `python -m snakeviz <func-name>.profile`\n\n Parameters\n ----------\n func : func, function to profile\n '
def profiled_func(*args, **kwargs):
filename = (func.__name__ + '.profile')
prof = cProfile.Profile()
ret = prof.runcall(func, *args, **kwargs)
prof.dump_stats(filename)
return ret
return profiled_func<|docstring|>Profiling decorator, produce a report <func-name>.profile to be open as
`python -m snakeviz <func-name>.profile`
Parameters
----------
func : func, function to profile<|endoftext|> |
7a1335f4caab157eb46d6093b77d2b4a019f65fc2e50e9b5d1fa0c06becefe7a | def parse_args():
'Parse in command line arguments'
parser = argparse.ArgumentParser(description='Demonstrate mask-rcnn results')
parser.add_argument('--dataset', default='coco2017', help='training dataset')
parser.add_argument('--cfg', dest='cfg_file', default='../configs/baselines/e2e_faster_rcnn_R-50-FPN_1x.yaml', help='optional config file')
parser.add_argument('--set', dest='set_cfgs', help='set config keys, will overwrite config in the cfg_file', default=[], nargs='+')
parser.add_argument('--no_cuda', dest='cuda', help='whether use CUDA', action='store_false')
parser.add_argument('--load_ckpt', help='path of checkpoint to load', default='../trained_weight/best_model.pth')
parser.add_argument('--load_detectron', help='path to the detectron weight pickle file')
parser.add_argument('--image_dir', help='directory to load images for demo', default='../test/')
parser.add_argument('--images', nargs='+', help='images to infer. Must not use with --image_dir')
parser.add_argument('--output_dir', help='directory to save demo results', default=' ')
parser.add_argument('--merge_pdfs', type=distutils.util.strtobool, default=False)
args = parser.parse_args()
return args | Parse in command line arguments | tools/infer_simple.py | parse_args | LcenArthas/CWCV2019-Amur-Tiger-Detection | 18 | python | def parse_args():
parser = argparse.ArgumentParser(description='Demonstrate mask-rcnn results')
parser.add_argument('--dataset', default='coco2017', help='training dataset')
parser.add_argument('--cfg', dest='cfg_file', default='../configs/baselines/e2e_faster_rcnn_R-50-FPN_1x.yaml', help='optional config file')
parser.add_argument('--set', dest='set_cfgs', help='set config keys, will overwrite config in the cfg_file', default=[], nargs='+')
parser.add_argument('--no_cuda', dest='cuda', help='whether use CUDA', action='store_false')
parser.add_argument('--load_ckpt', help='path of checkpoint to load', default='../trained_weight/best_model.pth')
parser.add_argument('--load_detectron', help='path to the detectron weight pickle file')
parser.add_argument('--image_dir', help='directory to load images for demo', default='../test/')
parser.add_argument('--images', nargs='+', help='images to infer. Must not use with --image_dir')
parser.add_argument('--output_dir', help='directory to save demo results', default=' ')
parser.add_argument('--merge_pdfs', type=distutils.util.strtobool, default=False)
args = parser.parse_args()
return args | def parse_args():
parser = argparse.ArgumentParser(description='Demonstrate mask-rcnn results')
parser.add_argument('--dataset', default='coco2017', help='training dataset')
parser.add_argument('--cfg', dest='cfg_file', default='../configs/baselines/e2e_faster_rcnn_R-50-FPN_1x.yaml', help='optional config file')
parser.add_argument('--set', dest='set_cfgs', help='set config keys, will overwrite config in the cfg_file', default=[], nargs='+')
parser.add_argument('--no_cuda', dest='cuda', help='whether use CUDA', action='store_false')
parser.add_argument('--load_ckpt', help='path of checkpoint to load', default='../trained_weight/best_model.pth')
parser.add_argument('--load_detectron', help='path to the detectron weight pickle file')
parser.add_argument('--image_dir', help='directory to load images for demo', default='../test/')
parser.add_argument('--images', nargs='+', help='images to infer. Must not use with --image_dir')
parser.add_argument('--output_dir', help='directory to save demo results', default=' ')
parser.add_argument('--merge_pdfs', type=distutils.util.strtobool, default=False)
args = parser.parse_args()
return args<|docstring|>Parse in command line arguments<|endoftext|> |
3114d1e61744a31089d332ad0e02b26a027181305f304b5f70ce1e11cb264947 | def main():
'main function'
if os.path.exists('../reid_test/'):
shutil.rmtree('../reid_test/')
os.makedirs('../reid_test/')
if os.path.exists('../output'):
shutil.rmtree('../output/')
os.makedirs('../output/')
if (not torch.cuda.is_available()):
sys.exit('Need a CUDA device to run the code.')
args = parse_args()
print('Called with args:')
print(args)
assert (args.image_dir or args.images)
assert (bool(args.image_dir) ^ bool(args.images))
if args.dataset.startswith('coco'):
dataset = datasets.get_coco_dataset()
cfg.MODEL.NUM_CLASSES = len(dataset.classes)
elif args.dataset.startswith('keypoints_coco'):
dataset = datasets.get_coco_dataset()
cfg.MODEL.NUM_CLASSES = 2
else:
raise ValueError('Unexpected dataset name: {}'.format(args.dataset))
print('load cfg from file: {}'.format(args.cfg_file))
cfg_from_file(args.cfg_file)
if (args.set_cfgs is not None):
cfg_from_list(args.set_cfgs)
assert (bool(args.load_ckpt) ^ bool(args.load_detectron)), 'Exactly one of --load_ckpt and --load_detectron should be specified.'
cfg.MODEL.LOAD_IMAGENET_PRETRAINED_WEIGHTS = False
assert_and_infer_cfg()
maskRCNN = Generalized_RCNN()
if args.cuda:
maskRCNN.cuda()
if args.load_ckpt:
load_name = args.load_ckpt
print(('loading checkpoint %s' % load_name))
checkpoint = torch.load(load_name, map_location=(lambda storage, loc: storage))
net_utils.load_ckpt(maskRCNN, checkpoint['model'])
if args.load_detectron:
print(('loading detectron weights %s' % args.load_detectron))
load_detectron_weight(maskRCNN, args.load_detectron)
maskRCNN = mynn.DataParallel(maskRCNN, cpu_keywords=['im_info', 'roidb'], minibatch=True, device_ids=[0])
maskRCNN.eval()
if args.image_dir:
imglist = misc_utils.get_imagelist_from_dir(args.image_dir)
else:
imglist = args.images
num_images = len(imglist)
if (not os.path.exists(args.output_dir)):
os.makedirs(args.output_dir)
for i in tqdm(xrange(num_images)):
im = cv2.imread(imglist[i])
assert (im is not None)
timers = defaultdict(Timer)
(cls_boxes, cls_segms, cls_keyps) = im_detect_all(maskRCNN, im, timers=timers)
(im_name, _) = os.path.splitext(os.path.basename(imglist[i]))
vis_utils.vis_one_image(im[(:, :, ::(- 1))], im_name, args.output_dir, cls_boxes, cls_segms, cls_keyps, dataset=dataset, box_alpha=0.9, show_class=True, thresh=0.1, kp_thresh=2)
if (args.merge_pdfs and (num_images > 1)):
merge_out_path = '{}/results.pdf'.format(args.output_dir)
if os.path.exists(merge_out_path):
os.remove(merge_out_path)
command = 'pdfunite {}/*.pdf {}'.format(args.output_dir, merge_out_path)
subprocess.call(command, shell=True) | main function | tools/infer_simple.py | main | LcenArthas/CWCV2019-Amur-Tiger-Detection | 18 | python | def main():
if os.path.exists('../reid_test/'):
shutil.rmtree('../reid_test/')
os.makedirs('../reid_test/')
if os.path.exists('../output'):
shutil.rmtree('../output/')
os.makedirs('../output/')
if (not torch.cuda.is_available()):
sys.exit('Need a CUDA device to run the code.')
args = parse_args()
print('Called with args:')
print(args)
assert (args.image_dir or args.images)
assert (bool(args.image_dir) ^ bool(args.images))
if args.dataset.startswith('coco'):
dataset = datasets.get_coco_dataset()
cfg.MODEL.NUM_CLASSES = len(dataset.classes)
elif args.dataset.startswith('keypoints_coco'):
dataset = datasets.get_coco_dataset()
cfg.MODEL.NUM_CLASSES = 2
else:
raise ValueError('Unexpected dataset name: {}'.format(args.dataset))
print('load cfg from file: {}'.format(args.cfg_file))
cfg_from_file(args.cfg_file)
if (args.set_cfgs is not None):
cfg_from_list(args.set_cfgs)
assert (bool(args.load_ckpt) ^ bool(args.load_detectron)), 'Exactly one of --load_ckpt and --load_detectron should be specified.'
cfg.MODEL.LOAD_IMAGENET_PRETRAINED_WEIGHTS = False
assert_and_infer_cfg()
maskRCNN = Generalized_RCNN()
if args.cuda:
maskRCNN.cuda()
if args.load_ckpt:
load_name = args.load_ckpt
print(('loading checkpoint %s' % load_name))
checkpoint = torch.load(load_name, map_location=(lambda storage, loc: storage))
net_utils.load_ckpt(maskRCNN, checkpoint['model'])
if args.load_detectron:
print(('loading detectron weights %s' % args.load_detectron))
load_detectron_weight(maskRCNN, args.load_detectron)
maskRCNN = mynn.DataParallel(maskRCNN, cpu_keywords=['im_info', 'roidb'], minibatch=True, device_ids=[0])
maskRCNN.eval()
if args.image_dir:
imglist = misc_utils.get_imagelist_from_dir(args.image_dir)
else:
imglist = args.images
num_images = len(imglist)
if (not os.path.exists(args.output_dir)):
os.makedirs(args.output_dir)
for i in tqdm(xrange(num_images)):
im = cv2.imread(imglist[i])
assert (im is not None)
timers = defaultdict(Timer)
(cls_boxes, cls_segms, cls_keyps) = im_detect_all(maskRCNN, im, timers=timers)
(im_name, _) = os.path.splitext(os.path.basename(imglist[i]))
vis_utils.vis_one_image(im[(:, :, ::(- 1))], im_name, args.output_dir, cls_boxes, cls_segms, cls_keyps, dataset=dataset, box_alpha=0.9, show_class=True, thresh=0.1, kp_thresh=2)
if (args.merge_pdfs and (num_images > 1)):
merge_out_path = '{}/results.pdf'.format(args.output_dir)
if os.path.exists(merge_out_path):
os.remove(merge_out_path)
command = 'pdfunite {}/*.pdf {}'.format(args.output_dir, merge_out_path)
subprocess.call(command, shell=True) | def main():
if os.path.exists('../reid_test/'):
shutil.rmtree('../reid_test/')
os.makedirs('../reid_test/')
if os.path.exists('../output'):
shutil.rmtree('../output/')
os.makedirs('../output/')
if (not torch.cuda.is_available()):
sys.exit('Need a CUDA device to run the code.')
args = parse_args()
print('Called with args:')
print(args)
assert (args.image_dir or args.images)
assert (bool(args.image_dir) ^ bool(args.images))
if args.dataset.startswith('coco'):
dataset = datasets.get_coco_dataset()
cfg.MODEL.NUM_CLASSES = len(dataset.classes)
elif args.dataset.startswith('keypoints_coco'):
dataset = datasets.get_coco_dataset()
cfg.MODEL.NUM_CLASSES = 2
else:
raise ValueError('Unexpected dataset name: {}'.format(args.dataset))
print('load cfg from file: {}'.format(args.cfg_file))
cfg_from_file(args.cfg_file)
if (args.set_cfgs is not None):
cfg_from_list(args.set_cfgs)
assert (bool(args.load_ckpt) ^ bool(args.load_detectron)), 'Exactly one of --load_ckpt and --load_detectron should be specified.'
cfg.MODEL.LOAD_IMAGENET_PRETRAINED_WEIGHTS = False
assert_and_infer_cfg()
maskRCNN = Generalized_RCNN()
if args.cuda:
maskRCNN.cuda()
if args.load_ckpt:
load_name = args.load_ckpt
print(('loading checkpoint %s' % load_name))
checkpoint = torch.load(load_name, map_location=(lambda storage, loc: storage))
net_utils.load_ckpt(maskRCNN, checkpoint['model'])
if args.load_detectron:
print(('loading detectron weights %s' % args.load_detectron))
load_detectron_weight(maskRCNN, args.load_detectron)
maskRCNN = mynn.DataParallel(maskRCNN, cpu_keywords=['im_info', 'roidb'], minibatch=True, device_ids=[0])
maskRCNN.eval()
if args.image_dir:
imglist = misc_utils.get_imagelist_from_dir(args.image_dir)
else:
imglist = args.images
num_images = len(imglist)
if (not os.path.exists(args.output_dir)):
os.makedirs(args.output_dir)
for i in tqdm(xrange(num_images)):
im = cv2.imread(imglist[i])
assert (im is not None)
timers = defaultdict(Timer)
(cls_boxes, cls_segms, cls_keyps) = im_detect_all(maskRCNN, im, timers=timers)
(im_name, _) = os.path.splitext(os.path.basename(imglist[i]))
vis_utils.vis_one_image(im[(:, :, ::(- 1))], im_name, args.output_dir, cls_boxes, cls_segms, cls_keyps, dataset=dataset, box_alpha=0.9, show_class=True, thresh=0.1, kp_thresh=2)
if (args.merge_pdfs and (num_images > 1)):
merge_out_path = '{}/results.pdf'.format(args.output_dir)
if os.path.exists(merge_out_path):
os.remove(merge_out_path)
command = 'pdfunite {}/*.pdf {}'.format(args.output_dir, merge_out_path)
subprocess.call(command, shell=True)<|docstring|>main function<|endoftext|> |
6585d99184bbd512365a148b98e83a001125d1f3ebf4da66f2671999c91f5353 | def match_networks(target_params, networks):
'Finds the WiFi networks that match a given set of parameters in a list\n of WiFi networks.\n\n To be considered a match, a network needs to have all the target parameters\n and the values of those parameters need to equal to those of the target\n parameters.\n\n Args:\n target_params: The target parameters to match networks against.\n networks: A list of dict objects representing WiFi networks.\n\n Returns:\n The networks that match the target parameters.\n '
results = []
for n in networks:
for (k, v) in target_params.items():
if (k not in n):
continue
if (n[k] != v):
continue
results.append(n)
return results | Finds the WiFi networks that match a given set of parameters in a list
of WiFi networks.
To be considered a match, a network needs to have all the target parameters
and the values of those parameters need to equal to those of the target
parameters.
Args:
target_params: The target parameters to match networks against.
networks: A list of dict objects representing WiFi networks.
Returns:
The networks that match the target parameters. | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | match_networks | Keneral/atools | 0 | python | def match_networks(target_params, networks):
'Finds the WiFi networks that match a given set of parameters in a list\n of WiFi networks.\n\n To be considered a match, a network needs to have all the target parameters\n and the values of those parameters need to equal to those of the target\n parameters.\n\n Args:\n target_params: The target parameters to match networks against.\n networks: A list of dict objects representing WiFi networks.\n\n Returns:\n The networks that match the target parameters.\n '
results = []
for n in networks:
for (k, v) in target_params.items():
if (k not in n):
continue
if (n[k] != v):
continue
results.append(n)
return results | def match_networks(target_params, networks):
'Finds the WiFi networks that match a given set of parameters in a list\n of WiFi networks.\n\n To be considered a match, a network needs to have all the target parameters\n and the values of those parameters need to equal to those of the target\n parameters.\n\n Args:\n target_params: The target parameters to match networks against.\n networks: A list of dict objects representing WiFi networks.\n\n Returns:\n The networks that match the target parameters.\n '
results = []
for n in networks:
for (k, v) in target_params.items():
if (k not in n):
continue
if (n[k] != v):
continue
results.append(n)
return results<|docstring|>Finds the WiFi networks that match a given set of parameters in a list
of WiFi networks.
To be considered a match, a network needs to have all the target parameters
and the values of those parameters need to equal to those of the target
parameters.
Args:
target_params: The target parameters to match networks against.
networks: A list of dict objects representing WiFi networks.
Returns:
The networks that match the target parameters.<|endoftext|> |
14b5f4c07207b8500d1591a8ba746133a51a2ad7322eda0812f394c0c3599889 | def wifi_toggle_state(ad, new_state=None):
'Toggles the state of wifi.\n\n Args:\n ad: An AndroidDevice object.\n new_state: Wifi state to set to. If None, opposite of the current state.\n\n Returns:\n True if the toggle was successful, False otherwise.\n '
if (new_state == ad.droid.wifiCheckState()):
return True
ad.droid.wifiStartTrackingStateChange()
log.info('Setting wifi state to {}'.format(new_state))
ad.droid.wifiToggleState(new_state)
try:
event = ad.ed.pop_event(WifiEventNames.SUPPLICANT_CON_CHANGED, SHORT_TIMEOUT)
return (event['data']['Connected'] == new_state)
except Empty:
return (new_state == ad.droid.wifiCheckState())
finally:
ad.droid.wifiStopTrackingStateChange() | Toggles the state of wifi.
Args:
ad: An AndroidDevice object.
new_state: Wifi state to set to. If None, opposite of the current state.
Returns:
True if the toggle was successful, False otherwise. | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | wifi_toggle_state | Keneral/atools | 0 | python | def wifi_toggle_state(ad, new_state=None):
'Toggles the state of wifi.\n\n Args:\n ad: An AndroidDevice object.\n new_state: Wifi state to set to. If None, opposite of the current state.\n\n Returns:\n True if the toggle was successful, False otherwise.\n '
if (new_state == ad.droid.wifiCheckState()):
return True
ad.droid.wifiStartTrackingStateChange()
log.info('Setting wifi state to {}'.format(new_state))
ad.droid.wifiToggleState(new_state)
try:
event = ad.ed.pop_event(WifiEventNames.SUPPLICANT_CON_CHANGED, SHORT_TIMEOUT)
return (event['data']['Connected'] == new_state)
except Empty:
return (new_state == ad.droid.wifiCheckState())
finally:
ad.droid.wifiStopTrackingStateChange() | def wifi_toggle_state(ad, new_state=None):
'Toggles the state of wifi.\n\n Args:\n ad: An AndroidDevice object.\n new_state: Wifi state to set to. If None, opposite of the current state.\n\n Returns:\n True if the toggle was successful, False otherwise.\n '
if (new_state == ad.droid.wifiCheckState()):
return True
ad.droid.wifiStartTrackingStateChange()
log.info('Setting wifi state to {}'.format(new_state))
ad.droid.wifiToggleState(new_state)
try:
event = ad.ed.pop_event(WifiEventNames.SUPPLICANT_CON_CHANGED, SHORT_TIMEOUT)
return (event['data']['Connected'] == new_state)
except Empty:
return (new_state == ad.droid.wifiCheckState())
finally:
ad.droid.wifiStopTrackingStateChange()<|docstring|>Toggles the state of wifi.
Args:
ad: An AndroidDevice object.
new_state: Wifi state to set to. If None, opposite of the current state.
Returns:
True if the toggle was successful, False otherwise.<|endoftext|> |
44ab890c3aead1894e9d9a6e628ec31c3ba1c50cbddf992d4359b35b29203e84 | def reset_wifi(ad):
'Clears all saved networks on a device.\n\n Args:\n ad: An AndroidDevice object.\n\n Raises:\n WifiTestUtilsError is raised if forget network operation failed.\n '
ad.droid.wifiToggleState(True)
networks = ad.droid.wifiGetConfiguredNetworks()
if (not networks):
return
for n in networks:
ad.droid.wifiForgetNetwork(n['networkId'])
try:
event = ad.ed.pop_event(WifiEventNames.WIFI_FORGET_NW_SUCCESS, SHORT_TIMEOUT)
except Empty:
raise WifiTestUtilsError('Failed to remove network {}.'.format(n)) | Clears all saved networks on a device.
Args:
ad: An AndroidDevice object.
Raises:
WifiTestUtilsError is raised if forget network operation failed. | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | reset_wifi | Keneral/atools | 0 | python | def reset_wifi(ad):
'Clears all saved networks on a device.\n\n Args:\n ad: An AndroidDevice object.\n\n Raises:\n WifiTestUtilsError is raised if forget network operation failed.\n '
ad.droid.wifiToggleState(True)
networks = ad.droid.wifiGetConfiguredNetworks()
if (not networks):
return
for n in networks:
ad.droid.wifiForgetNetwork(n['networkId'])
try:
event = ad.ed.pop_event(WifiEventNames.WIFI_FORGET_NW_SUCCESS, SHORT_TIMEOUT)
except Empty:
raise WifiTestUtilsError('Failed to remove network {}.'.format(n)) | def reset_wifi(ad):
'Clears all saved networks on a device.\n\n Args:\n ad: An AndroidDevice object.\n\n Raises:\n WifiTestUtilsError is raised if forget network operation failed.\n '
ad.droid.wifiToggleState(True)
networks = ad.droid.wifiGetConfiguredNetworks()
if (not networks):
return
for n in networks:
ad.droid.wifiForgetNetwork(n['networkId'])
try:
event = ad.ed.pop_event(WifiEventNames.WIFI_FORGET_NW_SUCCESS, SHORT_TIMEOUT)
except Empty:
raise WifiTestUtilsError('Failed to remove network {}.'.format(n))<|docstring|>Clears all saved networks on a device.
Args:
ad: An AndroidDevice object.
Raises:
WifiTestUtilsError is raised if forget network operation failed.<|endoftext|> |
66d7dac1affd087f79e076290c7b05909daf08156e1a80cb5b6bf73631ae2d2c | def wifi_forget_network(ad, net_ssid):
'Remove configured Wifi network on an android device.\n\n Args:\n ad: android_device object for forget network.\n net_ssid: ssid of network to be forget\n\n Raises:\n WifiTestUtilsError is raised if forget network operation failed.\n '
(droid, ed) = (ad.droid, ad.ed)
droid.wifiToggleState(True)
networks = droid.wifiGetConfiguredNetworks()
if (not networks):
return
for n in networks:
if (net_ssid in n[WifiEnums.SSID_KEY]):
droid.wifiForgetNetwork(n['networkId'])
try:
event = ed.pop_event(WifiEventNames.WIFI_FORGET_NW_SUCCESS, SHORT_TIMEOUT)
except Empty:
raise WifiTestUtilsError(('Failed to remove network %s.' % n)) | Remove configured Wifi network on an android device.
Args:
ad: android_device object for forget network.
net_ssid: ssid of network to be forget
Raises:
WifiTestUtilsError is raised if forget network operation failed. | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | wifi_forget_network | Keneral/atools | 0 | python | def wifi_forget_network(ad, net_ssid):
'Remove configured Wifi network on an android device.\n\n Args:\n ad: android_device object for forget network.\n net_ssid: ssid of network to be forget\n\n Raises:\n WifiTestUtilsError is raised if forget network operation failed.\n '
(droid, ed) = (ad.droid, ad.ed)
droid.wifiToggleState(True)
networks = droid.wifiGetConfiguredNetworks()
if (not networks):
return
for n in networks:
if (net_ssid in n[WifiEnums.SSID_KEY]):
droid.wifiForgetNetwork(n['networkId'])
try:
event = ed.pop_event(WifiEventNames.WIFI_FORGET_NW_SUCCESS, SHORT_TIMEOUT)
except Empty:
raise WifiTestUtilsError(('Failed to remove network %s.' % n)) | def wifi_forget_network(ad, net_ssid):
'Remove configured Wifi network on an android device.\n\n Args:\n ad: android_device object for forget network.\n net_ssid: ssid of network to be forget\n\n Raises:\n WifiTestUtilsError is raised if forget network operation failed.\n '
(droid, ed) = (ad.droid, ad.ed)
droid.wifiToggleState(True)
networks = droid.wifiGetConfiguredNetworks()
if (not networks):
return
for n in networks:
if (net_ssid in n[WifiEnums.SSID_KEY]):
droid.wifiForgetNetwork(n['networkId'])
try:
event = ed.pop_event(WifiEventNames.WIFI_FORGET_NW_SUCCESS, SHORT_TIMEOUT)
except Empty:
raise WifiTestUtilsError(('Failed to remove network %s.' % n))<|docstring|>Remove configured Wifi network on an android device.
Args:
ad: android_device object for forget network.
net_ssid: ssid of network to be forget
Raises:
WifiTestUtilsError is raised if forget network operation failed.<|endoftext|> |
c874f89ed45e627e60a5c746c917eeeeb312ebc4d6045ba8b0d786c2291c5181 | def wifi_test_device_init(ad):
"Initializes an android device for wifi testing.\n\n 0. Make sure SL4A connection is established on the android device.\n 1. Disable location service's WiFi scan.\n 2. Turn WiFi on.\n 3. Clear all saved networks.\n 4. Set country code to US.\n 5. Enable WiFi verbose logging.\n 6. Sync device time with computer time.\n 7. Turn off cellular data.\n "
require_sl4a((ad,))
ad.droid.wifiScannerToggleAlwaysAvailable(False)
msg = "Failed to turn off location service's scan."
assert (not ad.droid.wifiScannerIsAlwaysAvailable()), msg
msg = ('Failed to turn WiFi on %s' % ad.serial)
assert wifi_toggle_state(ad, True), msg
reset_wifi(ad)
msg = 'Failed to clear configured networks.'
assert (not ad.droid.wifiGetConfiguredNetworks()), msg
ad.droid.wifiEnableVerboseLogging(1)
msg = 'Failed to enable WiFi verbose logging.'
assert (ad.droid.wifiGetVerboseLoggingLevel() == 1), msg
ad.droid.wifiScannerToggleAlwaysAvailable(False)
sync_device_time(ad)
ad.droid.telephonyToggleDataConnection(False)
ad.adb.shell(('halutil -country %s' % WifiEnums.CountryCode.US)) | Initializes an android device for wifi testing.
0. Make sure SL4A connection is established on the android device.
1. Disable location service's WiFi scan.
2. Turn WiFi on.
3. Clear all saved networks.
4. Set country code to US.
5. Enable WiFi verbose logging.
6. Sync device time with computer time.
7. Turn off cellular data. | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | wifi_test_device_init | Keneral/atools | 0 | python | def wifi_test_device_init(ad):
"Initializes an android device for wifi testing.\n\n 0. Make sure SL4A connection is established on the android device.\n 1. Disable location service's WiFi scan.\n 2. Turn WiFi on.\n 3. Clear all saved networks.\n 4. Set country code to US.\n 5. Enable WiFi verbose logging.\n 6. Sync device time with computer time.\n 7. Turn off cellular data.\n "
require_sl4a((ad,))
ad.droid.wifiScannerToggleAlwaysAvailable(False)
msg = "Failed to turn off location service's scan."
assert (not ad.droid.wifiScannerIsAlwaysAvailable()), msg
msg = ('Failed to turn WiFi on %s' % ad.serial)
assert wifi_toggle_state(ad, True), msg
reset_wifi(ad)
msg = 'Failed to clear configured networks.'
assert (not ad.droid.wifiGetConfiguredNetworks()), msg
ad.droid.wifiEnableVerboseLogging(1)
msg = 'Failed to enable WiFi verbose logging.'
assert (ad.droid.wifiGetVerboseLoggingLevel() == 1), msg
ad.droid.wifiScannerToggleAlwaysAvailable(False)
sync_device_time(ad)
ad.droid.telephonyToggleDataConnection(False)
ad.adb.shell(('halutil -country %s' % WifiEnums.CountryCode.US)) | def wifi_test_device_init(ad):
"Initializes an android device for wifi testing.\n\n 0. Make sure SL4A connection is established on the android device.\n 1. Disable location service's WiFi scan.\n 2. Turn WiFi on.\n 3. Clear all saved networks.\n 4. Set country code to US.\n 5. Enable WiFi verbose logging.\n 6. Sync device time with computer time.\n 7. Turn off cellular data.\n "
require_sl4a((ad,))
ad.droid.wifiScannerToggleAlwaysAvailable(False)
msg = "Failed to turn off location service's scan."
assert (not ad.droid.wifiScannerIsAlwaysAvailable()), msg
msg = ('Failed to turn WiFi on %s' % ad.serial)
assert wifi_toggle_state(ad, True), msg
reset_wifi(ad)
msg = 'Failed to clear configured networks.'
assert (not ad.droid.wifiGetConfiguredNetworks()), msg
ad.droid.wifiEnableVerboseLogging(1)
msg = 'Failed to enable WiFi verbose logging.'
assert (ad.droid.wifiGetVerboseLoggingLevel() == 1), msg
ad.droid.wifiScannerToggleAlwaysAvailable(False)
sync_device_time(ad)
ad.droid.telephonyToggleDataConnection(False)
ad.adb.shell(('halutil -country %s' % WifiEnums.CountryCode.US))<|docstring|>Initializes an android device for wifi testing.
0. Make sure SL4A connection is established on the android device.
1. Disable location service's WiFi scan.
2. Turn WiFi on.
3. Clear all saved networks.
4. Set country code to US.
5. Enable WiFi verbose logging.
6. Sync device time with computer time.
7. Turn off cellular data.<|endoftext|> |
a94cfe491d153bfec1fd40e2b40b3e4715720258e3095b21af3e438c0e346fc2 | def sort_wifi_scan_results(results, key='level'):
'Sort wifi scan results by key.\n\n Args:\n results: A list of results to sort.\n key: Name of the field to sort the results by.\n\n Returns:\n A list of results in sorted order.\n '
return sorted(results, (lambda d: ((key not in d), d[key]))) | Sort wifi scan results by key.
Args:
results: A list of results to sort.
key: Name of the field to sort the results by.
Returns:
A list of results in sorted order. | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | sort_wifi_scan_results | Keneral/atools | 0 | python | def sort_wifi_scan_results(results, key='level'):
'Sort wifi scan results by key.\n\n Args:\n results: A list of results to sort.\n key: Name of the field to sort the results by.\n\n Returns:\n A list of results in sorted order.\n '
return sorted(results, (lambda d: ((key not in d), d[key]))) | def sort_wifi_scan_results(results, key='level'):
'Sort wifi scan results by key.\n\n Args:\n results: A list of results to sort.\n key: Name of the field to sort the results by.\n\n Returns:\n A list of results in sorted order.\n '
return sorted(results, (lambda d: ((key not in d), d[key])))<|docstring|>Sort wifi scan results by key.
Args:
results: A list of results to sort.
key: Name of the field to sort the results by.
Returns:
A list of results in sorted order.<|endoftext|> |
ae71e2944589e356006b4b726318ef84014e20cc26ae46abc4b8918a5e50eaa4 | def start_wifi_connection_scan(ad):
'Starts a wifi connection scan and wait for results to become available.\n\n Args:\n ad: An AndroidDevice object.\n '
ad.droid.wifiStartScan()
ad.ed.pop_event('WifiManagerScanResultsAvailable', 60) | Starts a wifi connection scan and wait for results to become available.
Args:
ad: An AndroidDevice object. | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | start_wifi_connection_scan | Keneral/atools | 0 | python | def start_wifi_connection_scan(ad):
'Starts a wifi connection scan and wait for results to become available.\n\n Args:\n ad: An AndroidDevice object.\n '
ad.droid.wifiStartScan()
ad.ed.pop_event('WifiManagerScanResultsAvailable', 60) | def start_wifi_connection_scan(ad):
'Starts a wifi connection scan and wait for results to become available.\n\n Args:\n ad: An AndroidDevice object.\n '
ad.droid.wifiStartScan()
ad.ed.pop_event('WifiManagerScanResultsAvailable', 60)<|docstring|>Starts a wifi connection scan and wait for results to become available.
Args:
ad: An AndroidDevice object.<|endoftext|> |
99c147da1389b58186c16703c3f66b876ac644ee991c25812ca5ca0855d20d48 | def start_wifi_background_scan(ad, scan_setting):
'Starts wifi background scan.\n\n Args:\n ad: android_device object to initiate connection on.\n scan_setting: A dict representing the settings of the scan.\n\n Returns:\n If scan was started successfully, event data of success event is returned.\n '
(droid, ed) = (ad.droids[0], ad.eds[0])
idx = droid.wifiScannerStartBackgroundScan(scan_setting)
event = ed.pop_event('WifiScannerScan{}onSuccess'.format(idx), SHORT_TIMEOUT)
return event['data'] | Starts wifi background scan.
Args:
ad: android_device object to initiate connection on.
scan_setting: A dict representing the settings of the scan.
Returns:
If scan was started successfully, event data of success event is returned. | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | start_wifi_background_scan | Keneral/atools | 0 | python | def start_wifi_background_scan(ad, scan_setting):
'Starts wifi background scan.\n\n Args:\n ad: android_device object to initiate connection on.\n scan_setting: A dict representing the settings of the scan.\n\n Returns:\n If scan was started successfully, event data of success event is returned.\n '
(droid, ed) = (ad.droids[0], ad.eds[0])
idx = droid.wifiScannerStartBackgroundScan(scan_setting)
event = ed.pop_event('WifiScannerScan{}onSuccess'.format(idx), SHORT_TIMEOUT)
return event['data'] | def start_wifi_background_scan(ad, scan_setting):
'Starts wifi background scan.\n\n Args:\n ad: android_device object to initiate connection on.\n scan_setting: A dict representing the settings of the scan.\n\n Returns:\n If scan was started successfully, event data of success event is returned.\n '
(droid, ed) = (ad.droids[0], ad.eds[0])
idx = droid.wifiScannerStartBackgroundScan(scan_setting)
event = ed.pop_event('WifiScannerScan{}onSuccess'.format(idx), SHORT_TIMEOUT)
return event['data']<|docstring|>Starts wifi background scan.
Args:
ad: android_device object to initiate connection on.
scan_setting: A dict representing the settings of the scan.
Returns:
If scan was started successfully, event data of success event is returned.<|endoftext|> |
a09f39d95549650953758f6bd769555bfbf92efb07845a64bd41689aa038704a | def start_wifi_tethering(ad, ssid, password, band=None):
'Starts wifi tethering on an android_device.\n\n Args:\n ad: android_device to start wifi tethering on.\n ssid: The SSID the soft AP should broadcast.\n password: The password the soft AP should use.\n band: The band the soft AP should be set on. It should be either\n WifiEnums.WIFI_CONFIG_APBAND_2G or WifiEnums.WIFI_CONFIG_APBAND_5G.\n\n Returns:\n True if soft AP was started successfully, False otherwise.\n '
(droid, ed) = (ad.droid, ad.ed)
droid.wifiStartTrackingStateChange()
config = {WifiEnums.SSID_KEY: ssid}
if password:
config[WifiEnums.PWD_KEY] = password
if band:
config[WifiEnums.APBAND_KEY] = band
if (not droid.wifiSetApEnabled(True, config)):
return False
ed.pop_event('WifiManagerApEnabled', 30)
ed.wait_for_event('TetherStateChanged', (lambda x: x['data']['ACTIVE_TETHER']), 30)
droid.wifiStopTrackingStateChange()
return True | Starts wifi tethering on an android_device.
Args:
ad: android_device to start wifi tethering on.
ssid: The SSID the soft AP should broadcast.
password: The password the soft AP should use.
band: The band the soft AP should be set on. It should be either
WifiEnums.WIFI_CONFIG_APBAND_2G or WifiEnums.WIFI_CONFIG_APBAND_5G.
Returns:
True if soft AP was started successfully, False otherwise. | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | start_wifi_tethering | Keneral/atools | 0 | python | def start_wifi_tethering(ad, ssid, password, band=None):
'Starts wifi tethering on an android_device.\n\n Args:\n ad: android_device to start wifi tethering on.\n ssid: The SSID the soft AP should broadcast.\n password: The password the soft AP should use.\n band: The band the soft AP should be set on. It should be either\n WifiEnums.WIFI_CONFIG_APBAND_2G or WifiEnums.WIFI_CONFIG_APBAND_5G.\n\n Returns:\n True if soft AP was started successfully, False otherwise.\n '
(droid, ed) = (ad.droid, ad.ed)
droid.wifiStartTrackingStateChange()
config = {WifiEnums.SSID_KEY: ssid}
if password:
config[WifiEnums.PWD_KEY] = password
if band:
config[WifiEnums.APBAND_KEY] = band
if (not droid.wifiSetApEnabled(True, config)):
return False
ed.pop_event('WifiManagerApEnabled', 30)
ed.wait_for_event('TetherStateChanged', (lambda x: x['data']['ACTIVE_TETHER']), 30)
droid.wifiStopTrackingStateChange()
return True | def start_wifi_tethering(ad, ssid, password, band=None):
'Starts wifi tethering on an android_device.\n\n Args:\n ad: android_device to start wifi tethering on.\n ssid: The SSID the soft AP should broadcast.\n password: The password the soft AP should use.\n band: The band the soft AP should be set on. It should be either\n WifiEnums.WIFI_CONFIG_APBAND_2G or WifiEnums.WIFI_CONFIG_APBAND_5G.\n\n Returns:\n True if soft AP was started successfully, False otherwise.\n '
(droid, ed) = (ad.droid, ad.ed)
droid.wifiStartTrackingStateChange()
config = {WifiEnums.SSID_KEY: ssid}
if password:
config[WifiEnums.PWD_KEY] = password
if band:
config[WifiEnums.APBAND_KEY] = band
if (not droid.wifiSetApEnabled(True, config)):
return False
ed.pop_event('WifiManagerApEnabled', 30)
ed.wait_for_event('TetherStateChanged', (lambda x: x['data']['ACTIVE_TETHER']), 30)
droid.wifiStopTrackingStateChange()
return True<|docstring|>Starts wifi tethering on an android_device.
Args:
ad: android_device to start wifi tethering on.
ssid: The SSID the soft AP should broadcast.
password: The password the soft AP should use.
band: The band the soft AP should be set on. It should be either
WifiEnums.WIFI_CONFIG_APBAND_2G or WifiEnums.WIFI_CONFIG_APBAND_5G.
Returns:
True if soft AP was started successfully, False otherwise.<|endoftext|> |
b31ecdb7e32ce36480118616cac9220251fdc15bcc52b71853580d8d975bfbd9 | def stop_wifi_tethering(ad):
'Stops wifi tethering on an android_device.\n\n Args:\n ad: android_device to stop wifi tethering on.\n '
(droid, ed) = (ad.droid, ad.ed)
droid.wifiStartTrackingStateChange()
droid.wifiSetApEnabled(False, None)
ed.pop_event('WifiManagerApDisabled', 30)
ed.wait_for_event('TetherStateChanged', (lambda x: (not x['data']['ACTIVE_TETHER'])), 30)
droid.wifiStopTrackingStateChange() | Stops wifi tethering on an android_device.
Args:
ad: android_device to stop wifi tethering on. | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | stop_wifi_tethering | Keneral/atools | 0 | python | def stop_wifi_tethering(ad):
'Stops wifi tethering on an android_device.\n\n Args:\n ad: android_device to stop wifi tethering on.\n '
(droid, ed) = (ad.droid, ad.ed)
droid.wifiStartTrackingStateChange()
droid.wifiSetApEnabled(False, None)
ed.pop_event('WifiManagerApDisabled', 30)
ed.wait_for_event('TetherStateChanged', (lambda x: (not x['data']['ACTIVE_TETHER'])), 30)
droid.wifiStopTrackingStateChange() | def stop_wifi_tethering(ad):
'Stops wifi tethering on an android_device.\n\n Args:\n ad: android_device to stop wifi tethering on.\n '
(droid, ed) = (ad.droid, ad.ed)
droid.wifiStartTrackingStateChange()
droid.wifiSetApEnabled(False, None)
ed.pop_event('WifiManagerApDisabled', 30)
ed.wait_for_event('TetherStateChanged', (lambda x: (not x['data']['ACTIVE_TETHER'])), 30)
droid.wifiStopTrackingStateChange()<|docstring|>Stops wifi tethering on an android_device.
Args:
ad: android_device to stop wifi tethering on.<|endoftext|> |
785af781dffddbb9707699c32655de62aa695b6cf5ed0f3ec48b15be1a61889d | def wifi_connect(ad, network):
'Connect an Android device to a wifi network.\n\n Initiate connection to a wifi network, wait for the "connected" event, then\n confirm the connected ssid is the one requested.\n\n Args:\n ad: android_device object to initiate connection on.\n network: A dictionary representing the network to connect to. The\n dictionary must have the key "SSID".\n '
assert (WifiEnums.SSID_KEY in network), ("Key '%s' must be present in network definition." % WifiEnums.SSID_KEY)
ad.droid.wifiStartTrackingStateChange()
try:
assert ad.droid.wifiConnect(network), 'WiFi connect returned false.'
connect_result = ad.ed.pop_event(WifiEventNames.WIFI_CONNECTED)
log.debug(('Connection result: %s.' % connect_result))
expected_ssid = network[WifiEnums.SSID_KEY]
actual_ssid = connect_result['data'][WifiEnums.SSID_KEY]
assert (actual_ssid == expected_ssid), ('Expected to connect to %s, connected to %s' % (expected_ssid, actual_ssid))
log.info(('Successfully connected to %s' % actual_ssid))
finally:
ad.droid.wifiStopTrackingStateChange() | Connect an Android device to a wifi network.
Initiate connection to a wifi network, wait for the "connected" event, then
confirm the connected ssid is the one requested.
Args:
ad: android_device object to initiate connection on.
network: A dictionary representing the network to connect to. The
dictionary must have the key "SSID". | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | wifi_connect | Keneral/atools | 0 | python | def wifi_connect(ad, network):
'Connect an Android device to a wifi network.\n\n Initiate connection to a wifi network, wait for the "connected" event, then\n confirm the connected ssid is the one requested.\n\n Args:\n ad: android_device object to initiate connection on.\n network: A dictionary representing the network to connect to. The\n dictionary must have the key "SSID".\n '
assert (WifiEnums.SSID_KEY in network), ("Key '%s' must be present in network definition." % WifiEnums.SSID_KEY)
ad.droid.wifiStartTrackingStateChange()
try:
assert ad.droid.wifiConnect(network), 'WiFi connect returned false.'
connect_result = ad.ed.pop_event(WifiEventNames.WIFI_CONNECTED)
log.debug(('Connection result: %s.' % connect_result))
expected_ssid = network[WifiEnums.SSID_KEY]
actual_ssid = connect_result['data'][WifiEnums.SSID_KEY]
assert (actual_ssid == expected_ssid), ('Expected to connect to %s, connected to %s' % (expected_ssid, actual_ssid))
log.info(('Successfully connected to %s' % actual_ssid))
finally:
ad.droid.wifiStopTrackingStateChange() | def wifi_connect(ad, network):
'Connect an Android device to a wifi network.\n\n Initiate connection to a wifi network, wait for the "connected" event, then\n confirm the connected ssid is the one requested.\n\n Args:\n ad: android_device object to initiate connection on.\n network: A dictionary representing the network to connect to. The\n dictionary must have the key "SSID".\n '
assert (WifiEnums.SSID_KEY in network), ("Key '%s' must be present in network definition." % WifiEnums.SSID_KEY)
ad.droid.wifiStartTrackingStateChange()
try:
assert ad.droid.wifiConnect(network), 'WiFi connect returned false.'
connect_result = ad.ed.pop_event(WifiEventNames.WIFI_CONNECTED)
log.debug(('Connection result: %s.' % connect_result))
expected_ssid = network[WifiEnums.SSID_KEY]
actual_ssid = connect_result['data'][WifiEnums.SSID_KEY]
assert (actual_ssid == expected_ssid), ('Expected to connect to %s, connected to %s' % (expected_ssid, actual_ssid))
log.info(('Successfully connected to %s' % actual_ssid))
finally:
ad.droid.wifiStopTrackingStateChange()<|docstring|>Connect an Android device to a wifi network.
Initiate connection to a wifi network, wait for the "connected" event, then
confirm the connected ssid is the one requested.
Args:
ad: android_device object to initiate connection on.
network: A dictionary representing the network to connect to. The
dictionary must have the key "SSID".<|endoftext|> |
d10288704fcdcf3fbf262134307fb0b178b1731e7efc4294478e835fec25a154 | def start_wifi_single_scan(ad, scan_setting):
'Starts wifi single shot scan.\n\n Args:\n ad: android_device object to initiate connection on.\n scan_setting: A dict representing the settings of the scan.\n\n Returns:\n If scan was started successfully, event data of success event is returned.\n '
(droid, ed) = (ad.droid, ad.ed)
idx = droid.wifiScannerStartScan(scan_setting)
event = ed.pop_event('WifiScannerScan{}onSuccess'.format(idx), SHORT_TIMEOUT)
log.debug('event {}'.format(event))
return event['data'] | Starts wifi single shot scan.
Args:
ad: android_device object to initiate connection on.
scan_setting: A dict representing the settings of the scan.
Returns:
If scan was started successfully, event data of success event is returned. | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | start_wifi_single_scan | Keneral/atools | 0 | python | def start_wifi_single_scan(ad, scan_setting):
'Starts wifi single shot scan.\n\n Args:\n ad: android_device object to initiate connection on.\n scan_setting: A dict representing the settings of the scan.\n\n Returns:\n If scan was started successfully, event data of success event is returned.\n '
(droid, ed) = (ad.droid, ad.ed)
idx = droid.wifiScannerStartScan(scan_setting)
event = ed.pop_event('WifiScannerScan{}onSuccess'.format(idx), SHORT_TIMEOUT)
log.debug('event {}'.format(event))
return event['data'] | def start_wifi_single_scan(ad, scan_setting):
'Starts wifi single shot scan.\n\n Args:\n ad: android_device object to initiate connection on.\n scan_setting: A dict representing the settings of the scan.\n\n Returns:\n If scan was started successfully, event data of success event is returned.\n '
(droid, ed) = (ad.droid, ad.ed)
idx = droid.wifiScannerStartScan(scan_setting)
event = ed.pop_event('WifiScannerScan{}onSuccess'.format(idx), SHORT_TIMEOUT)
log.debug('event {}'.format(event))
return event['data']<|docstring|>Starts wifi single shot scan.
Args:
ad: android_device object to initiate connection on.
scan_setting: A dict representing the settings of the scan.
Returns:
If scan was started successfully, event data of success event is returned.<|endoftext|> |
65b20247de976baa87b64dc4e031031fa0ca80a1336878f321e979d8fb270ffe | def track_connection(ad, network_ssid, check_connection_count):
'Track wifi connection to network changes for given number of counts\n\n Args:\n ad: android_device object for forget network.\n network_ssid: network ssid to which connection would be tracked\n check_connection_count: Integer for maximum number network connection\n check.\n Returns:\n\n True if connection to given network happen, else return False.\n '
(droid, ed) = (ad.droid, ad.ed)
droid.wifiStartTrackingStateChange()
while (check_connection_count > 0):
connect_network = ed.pop_event('WifiNetworkConnected', 120)
log.info('connect_network {}'.format(connect_network))
if ((WifiEnums.SSID_KEY in connect_network['data']) and (connect_network['data'][WifiEnums.SSID_KEY] == network_ssid)):
return True
check_connection_count -= 1
droid.wifiStopTrackingStateChange()
return False | Track wifi connection to network changes for given number of counts
Args:
ad: android_device object for forget network.
network_ssid: network ssid to which connection would be tracked
check_connection_count: Integer for maximum number network connection
check.
Returns:
True if connection to given network happen, else return False. | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | track_connection | Keneral/atools | 0 | python | def track_connection(ad, network_ssid, check_connection_count):
'Track wifi connection to network changes for given number of counts\n\n Args:\n ad: android_device object for forget network.\n network_ssid: network ssid to which connection would be tracked\n check_connection_count: Integer for maximum number network connection\n check.\n Returns:\n\n True if connection to given network happen, else return False.\n '
(droid, ed) = (ad.droid, ad.ed)
droid.wifiStartTrackingStateChange()
while (check_connection_count > 0):
connect_network = ed.pop_event('WifiNetworkConnected', 120)
log.info('connect_network {}'.format(connect_network))
if ((WifiEnums.SSID_KEY in connect_network['data']) and (connect_network['data'][WifiEnums.SSID_KEY] == network_ssid)):
return True
check_connection_count -= 1
droid.wifiStopTrackingStateChange()
return False | def track_connection(ad, network_ssid, check_connection_count):
'Track wifi connection to network changes for given number of counts\n\n Args:\n ad: android_device object for forget network.\n network_ssid: network ssid to which connection would be tracked\n check_connection_count: Integer for maximum number network connection\n check.\n Returns:\n\n True if connection to given network happen, else return False.\n '
(droid, ed) = (ad.droid, ad.ed)
droid.wifiStartTrackingStateChange()
while (check_connection_count > 0):
connect_network = ed.pop_event('WifiNetworkConnected', 120)
log.info('connect_network {}'.format(connect_network))
if ((WifiEnums.SSID_KEY in connect_network['data']) and (connect_network['data'][WifiEnums.SSID_KEY] == network_ssid)):
return True
check_connection_count -= 1
droid.wifiStopTrackingStateChange()
return False<|docstring|>Track wifi connection to network changes for given number of counts
Args:
ad: android_device object for forget network.
network_ssid: network ssid to which connection would be tracked
check_connection_count: Integer for maximum number network connection
check.
Returns:
True if connection to given network happen, else return False.<|endoftext|> |
2ee883c13318d356fd4cc9a5e8e2d5df272248d9ee570e32c3a9ec18bf18fc16 | def get_scan_time_and_channels(wifi_chs, scan_setting, stime_channel):
'Calculate the scan time required based on the band or channels in scan\n setting\n\n Args:\n wifi_chs: Object of channels supported\n scan_setting: scan setting used for start scan\n stime_channel: scan time per channel\n\n Returns:\n scan_time: time required for completing a scan\n scan_channels: channel used for scanning\n '
scan_time = 0
scan_channels = []
if (('band' in scan_setting) and ('channels' not in scan_setting)):
scan_channels = wifi_chs.band_to_freq(scan_setting['band'])
elif (('channels' in scan_setting) and ('band' not in scan_setting)):
scan_channels = scan_setting['channels']
scan_time = (len(scan_channels) * stime_channel)
for channel in scan_channels:
if (channel in WifiEnums.DFS_5G_FREQUENCIES):
scan_time += 132
return (scan_time, scan_channels) | Calculate the scan time required based on the band or channels in scan
setting
Args:
wifi_chs: Object of channels supported
scan_setting: scan setting used for start scan
stime_channel: scan time per channel
Returns:
scan_time: time required for completing a scan
scan_channels: channel used for scanning | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | get_scan_time_and_channels | Keneral/atools | 0 | python | def get_scan_time_and_channels(wifi_chs, scan_setting, stime_channel):
'Calculate the scan time required based on the band or channels in scan\n setting\n\n Args:\n wifi_chs: Object of channels supported\n scan_setting: scan setting used for start scan\n stime_channel: scan time per channel\n\n Returns:\n scan_time: time required for completing a scan\n scan_channels: channel used for scanning\n '
scan_time = 0
scan_channels = []
if (('band' in scan_setting) and ('channels' not in scan_setting)):
scan_channels = wifi_chs.band_to_freq(scan_setting['band'])
elif (('channels' in scan_setting) and ('band' not in scan_setting)):
scan_channels = scan_setting['channels']
scan_time = (len(scan_channels) * stime_channel)
for channel in scan_channels:
if (channel in WifiEnums.DFS_5G_FREQUENCIES):
scan_time += 132
return (scan_time, scan_channels) | def get_scan_time_and_channels(wifi_chs, scan_setting, stime_channel):
'Calculate the scan time required based on the band or channels in scan\n setting\n\n Args:\n wifi_chs: Object of channels supported\n scan_setting: scan setting used for start scan\n stime_channel: scan time per channel\n\n Returns:\n scan_time: time required for completing a scan\n scan_channels: channel used for scanning\n '
scan_time = 0
scan_channels = []
if (('band' in scan_setting) and ('channels' not in scan_setting)):
scan_channels = wifi_chs.band_to_freq(scan_setting['band'])
elif (('channels' in scan_setting) and ('band' not in scan_setting)):
scan_channels = scan_setting['channels']
scan_time = (len(scan_channels) * stime_channel)
for channel in scan_channels:
if (channel in WifiEnums.DFS_5G_FREQUENCIES):
scan_time += 132
return (scan_time, scan_channels)<|docstring|>Calculate the scan time required based on the band or channels in scan
setting
Args:
wifi_chs: Object of channels supported
scan_setting: scan setting used for start scan
stime_channel: scan time per channel
Returns:
scan_time: time required for completing a scan
scan_channels: channel used for scanning<|endoftext|> |
1b7279446e76ca60d1a1c62b5e4f529b2e144562e3839eecc4a9a0e059c62357 | def start_wifi_track_bssid(ad, track_setting):
'Start tracking Bssid for the given settings.\n\n Args:\n ad: android_device object.\n track_setting: Setting for which the bssid tracking should be started\n\n Returns:\n If tracking started successfully, event data of success event is returned.\n '
(droid, ed) = (ad.droid, ad.ed)
idx = droid.wifiScannerStartTrackingBssids(track_setting['bssidInfos'], track_setting['apLostThreshold'])
event = ed.pop_event('WifiScannerBssid{}onSuccess'.format(idx), SHORT_TIMEOUT)
return event['data'] | Start tracking Bssid for the given settings.
Args:
ad: android_device object.
track_setting: Setting for which the bssid tracking should be started
Returns:
If tracking started successfully, event data of success event is returned. | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | start_wifi_track_bssid | Keneral/atools | 0 | python | def start_wifi_track_bssid(ad, track_setting):
'Start tracking Bssid for the given settings.\n\n Args:\n ad: android_device object.\n track_setting: Setting for which the bssid tracking should be started\n\n Returns:\n If tracking started successfully, event data of success event is returned.\n '
(droid, ed) = (ad.droid, ad.ed)
idx = droid.wifiScannerStartTrackingBssids(track_setting['bssidInfos'], track_setting['apLostThreshold'])
event = ed.pop_event('WifiScannerBssid{}onSuccess'.format(idx), SHORT_TIMEOUT)
return event['data'] | def start_wifi_track_bssid(ad, track_setting):
'Start tracking Bssid for the given settings.\n\n Args:\n ad: android_device object.\n track_setting: Setting for which the bssid tracking should be started\n\n Returns:\n If tracking started successfully, event data of success event is returned.\n '
(droid, ed) = (ad.droid, ad.ed)
idx = droid.wifiScannerStartTrackingBssids(track_setting['bssidInfos'], track_setting['apLostThreshold'])
event = ed.pop_event('WifiScannerBssid{}onSuccess'.format(idx), SHORT_TIMEOUT)
return event['data']<|docstring|>Start tracking Bssid for the given settings.
Args:
ad: android_device object.
track_setting: Setting for which the bssid tracking should be started
Returns:
If tracking started successfully, event data of success event is returned.<|endoftext|> |
e5c4823b2b51abc1f4a9e20808e553107457ea3e85a7840883cc156370313490 | def convert_pem_key_to_pkcs8(in_file, out_file):
'Converts the key file generated by us to the format required by\n Android using openssl.\n\n The input file must have the extension "pem". The output file must\n have the extension "der".\n\n Args:\n in_file: The original key file.\n out_file: The full path to the converted key file, including\n filename.\n '
cmd = 'openssl pkcs8 -inform PEM -in {} -outform DER -out {} -nocrypt -topk8'.format(in_file, out_file)
exe_cmd(cmd) | Converts the key file generated by us to the format required by
Android using openssl.
The input file must have the extension "pem". The output file must
have the extension "der".
Args:
in_file: The original key file.
out_file: The full path to the converted key file, including
filename. | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | convert_pem_key_to_pkcs8 | Keneral/atools | 0 | python | def convert_pem_key_to_pkcs8(in_file, out_file):
'Converts the key file generated by us to the format required by\n Android using openssl.\n\n The input file must have the extension "pem". The output file must\n have the extension "der".\n\n Args:\n in_file: The original key file.\n out_file: The full path to the converted key file, including\n filename.\n '
cmd = 'openssl pkcs8 -inform PEM -in {} -outform DER -out {} -nocrypt -topk8'.format(in_file, out_file)
exe_cmd(cmd) | def convert_pem_key_to_pkcs8(in_file, out_file):
'Converts the key file generated by us to the format required by\n Android using openssl.\n\n The input file must have the extension "pem". The output file must\n have the extension "der".\n\n Args:\n in_file: The original key file.\n out_file: The full path to the converted key file, including\n filename.\n '
cmd = 'openssl pkcs8 -inform PEM -in {} -outform DER -out {} -nocrypt -topk8'.format(in_file, out_file)
exe_cmd(cmd)<|docstring|>Converts the key file generated by us to the format required by
Android using openssl.
The input file must have the extension "pem". The output file must
have the extension "der".
Args:
in_file: The original key file.
out_file: The full path to the converted key file, including
filename.<|endoftext|> |
7be680ef1f92a7da878a766a2038d2f035d2223091d1b6fe0ae5fc05446e8f78 | def check_internet_connection(ad, ping_addr):
'Validate internet connection by pinging the address provided.\n\n Args:\n ad: android_device object.\n ping_addr: address on internet for pinging.\n\n Returns:\n True, if address ping successful\n '
(droid, ed) = (ad.droid, ad.ed)
ping = droid.httpPing(ping_addr)
log.info('Http ping result: {}'.format(ping))
return ping | Validate internet connection by pinging the address provided.
Args:
ad: android_device object.
ping_addr: address on internet for pinging.
Returns:
True, if address ping successful | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | check_internet_connection | Keneral/atools | 0 | python | def check_internet_connection(ad, ping_addr):
'Validate internet connection by pinging the address provided.\n\n Args:\n ad: android_device object.\n ping_addr: address on internet for pinging.\n\n Returns:\n True, if address ping successful\n '
(droid, ed) = (ad.droid, ad.ed)
ping = droid.httpPing(ping_addr)
log.info('Http ping result: {}'.format(ping))
return ping | def check_internet_connection(ad, ping_addr):
'Validate internet connection by pinging the address provided.\n\n Args:\n ad: android_device object.\n ping_addr: address on internet for pinging.\n\n Returns:\n True, if address ping successful\n '
(droid, ed) = (ad.droid, ad.ed)
ping = droid.httpPing(ping_addr)
log.info('Http ping result: {}'.format(ping))
return ping<|docstring|>Validate internet connection by pinging the address provided.
Args:
ad: android_device object.
ping_addr: address on internet for pinging.
Returns:
True, if address ping successful<|endoftext|> |
fadc630de8ea4223730a3d40e06670ff4cf52034eb1306a1fbd8584b275d5a70 | def verify_wifi_connection_info(ad, expected_con):
'Verifies that the information of the currently connected wifi network is\n as expected.\n\n Args:\n expected_con: A dict representing expected key-value pairs for wifi\n connection. e.g. {"SSID": "test_wifi"}\n '
current_con = ad.droid.wifiGetConnectionInfo()
case_insensitive = ['BSSID', 'supplicant_state']
log.debug(('Current connection: %s' % current_con))
for (k, expected_v) in expected_con.items():
if (k == 'password'):
continue
msg = ('Field %s does not exist in wifi connection info %s.' % (k, current_con))
if (k not in current_con):
raise signals.TestFailure(msg)
actual_v = current_con[k]
if (k in case_insensitive):
actual_v = actual_v.lower()
expected_v = expected_v.lower()
msg = ('Expected %s to be %s, actual %s is %s.' % (k, expected_v, k, actual_v))
if (actual_v != expected_v):
raise signals.TestFailure(msg) | Verifies that the information of the currently connected wifi network is
as expected.
Args:
expected_con: A dict representing expected key-value pairs for wifi
connection. e.g. {"SSID": "test_wifi"} | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | verify_wifi_connection_info | Keneral/atools | 0 | python | def verify_wifi_connection_info(ad, expected_con):
'Verifies that the information of the currently connected wifi network is\n as expected.\n\n Args:\n expected_con: A dict representing expected key-value pairs for wifi\n connection. e.g. {"SSID": "test_wifi"}\n '
current_con = ad.droid.wifiGetConnectionInfo()
case_insensitive = ['BSSID', 'supplicant_state']
log.debug(('Current connection: %s' % current_con))
for (k, expected_v) in expected_con.items():
if (k == 'password'):
continue
msg = ('Field %s does not exist in wifi connection info %s.' % (k, current_con))
if (k not in current_con):
raise signals.TestFailure(msg)
actual_v = current_con[k]
if (k in case_insensitive):
actual_v = actual_v.lower()
expected_v = expected_v.lower()
msg = ('Expected %s to be %s, actual %s is %s.' % (k, expected_v, k, actual_v))
if (actual_v != expected_v):
raise signals.TestFailure(msg) | def verify_wifi_connection_info(ad, expected_con):
'Verifies that the information of the currently connected wifi network is\n as expected.\n\n Args:\n expected_con: A dict representing expected key-value pairs for wifi\n connection. e.g. {"SSID": "test_wifi"}\n '
current_con = ad.droid.wifiGetConnectionInfo()
case_insensitive = ['BSSID', 'supplicant_state']
log.debug(('Current connection: %s' % current_con))
for (k, expected_v) in expected_con.items():
if (k == 'password'):
continue
msg = ('Field %s does not exist in wifi connection info %s.' % (k, current_con))
if (k not in current_con):
raise signals.TestFailure(msg)
actual_v = current_con[k]
if (k in case_insensitive):
actual_v = actual_v.lower()
expected_v = expected_v.lower()
msg = ('Expected %s to be %s, actual %s is %s.' % (k, expected_v, k, actual_v))
if (actual_v != expected_v):
raise signals.TestFailure(msg)<|docstring|>Verifies that the information of the currently connected wifi network is
as expected.
Args:
expected_con: A dict representing expected key-value pairs for wifi
connection. e.g. {"SSID": "test_wifi"}<|endoftext|> |
bc705ea7b9ec8a8b6ee9f0c0c40d5a4e7e41858a1f62066c856189cba6695008 | def eap_connect(config, ad, validate_con=True, ping_addr=DEFAULT_PING_ADDR):
'Connects to an enterprise network and verify connection.\n\n This logic expect the enterprise network to have Internet access.\n\n Args:\n config: A dict representing a wifi enterprise configuration.\n ad: The android_device to operate with.\n validate_con: If True, validate Internet connection after connecting to\n the network.\n\n Returns:\n True if the connection is successful and Internet access works.\n '
(droid, ed) = (ad.droid, ad.ed)
start_wifi_connection_scan(ad)
expect_ssid = None
if (WifiEnums.SSID_KEY in config):
expect_ssid = config[WifiEnums.SSID_KEY]
log.info(('Connecting to %s.' % expect_ssid))
else:
log.info('Connecting.')
log.debug(pprint.pformat(config, indent=4))
ad.droid.wifiEnterpriseConnect(config)
try:
event = ed.pop_event('WifiManagerEnterpriseConnectOnSuccess', 30)
log.info('Started connecting...')
event = ed.pop_event(WifiEventNames.WIFI_CONNECTED, 60)
except Empty:
asserts.fail(('Failed to connect to %s' % config))
log.debug(event)
if expect_ssid:
actual_ssid = event['data'][WifiEnums.SSID_KEY]
asserts.assert_equal(expect_ssid, actual_ssid, 'SSID mismatch.')
else:
log.info(('Connected to %s.' % expect_ssid))
if validate_con:
log.info('Checking Internet access.')
time.sleep(4)
ping = ad.droid.httpPing(ping_addr)
log.info('Http ping result: {}'.format(ping))
asserts.assert_true(ping, 'No Internet access.') | Connects to an enterprise network and verify connection.
This logic expect the enterprise network to have Internet access.
Args:
config: A dict representing a wifi enterprise configuration.
ad: The android_device to operate with.
validate_con: If True, validate Internet connection after connecting to
the network.
Returns:
True if the connection is successful and Internet access works. | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | eap_connect | Keneral/atools | 0 | python | def eap_connect(config, ad, validate_con=True, ping_addr=DEFAULT_PING_ADDR):
'Connects to an enterprise network and verify connection.\n\n This logic expect the enterprise network to have Internet access.\n\n Args:\n config: A dict representing a wifi enterprise configuration.\n ad: The android_device to operate with.\n validate_con: If True, validate Internet connection after connecting to\n the network.\n\n Returns:\n True if the connection is successful and Internet access works.\n '
(droid, ed) = (ad.droid, ad.ed)
start_wifi_connection_scan(ad)
expect_ssid = None
if (WifiEnums.SSID_KEY in config):
expect_ssid = config[WifiEnums.SSID_KEY]
log.info(('Connecting to %s.' % expect_ssid))
else:
log.info('Connecting.')
log.debug(pprint.pformat(config, indent=4))
ad.droid.wifiEnterpriseConnect(config)
try:
event = ed.pop_event('WifiManagerEnterpriseConnectOnSuccess', 30)
log.info('Started connecting...')
event = ed.pop_event(WifiEventNames.WIFI_CONNECTED, 60)
except Empty:
asserts.fail(('Failed to connect to %s' % config))
log.debug(event)
if expect_ssid:
actual_ssid = event['data'][WifiEnums.SSID_KEY]
asserts.assert_equal(expect_ssid, actual_ssid, 'SSID mismatch.')
else:
log.info(('Connected to %s.' % expect_ssid))
if validate_con:
log.info('Checking Internet access.')
time.sleep(4)
ping = ad.droid.httpPing(ping_addr)
log.info('Http ping result: {}'.format(ping))
asserts.assert_true(ping, 'No Internet access.') | def eap_connect(config, ad, validate_con=True, ping_addr=DEFAULT_PING_ADDR):
'Connects to an enterprise network and verify connection.\n\n This logic expect the enterprise network to have Internet access.\n\n Args:\n config: A dict representing a wifi enterprise configuration.\n ad: The android_device to operate with.\n validate_con: If True, validate Internet connection after connecting to\n the network.\n\n Returns:\n True if the connection is successful and Internet access works.\n '
(droid, ed) = (ad.droid, ad.ed)
start_wifi_connection_scan(ad)
expect_ssid = None
if (WifiEnums.SSID_KEY in config):
expect_ssid = config[WifiEnums.SSID_KEY]
log.info(('Connecting to %s.' % expect_ssid))
else:
log.info('Connecting.')
log.debug(pprint.pformat(config, indent=4))
ad.droid.wifiEnterpriseConnect(config)
try:
event = ed.pop_event('WifiManagerEnterpriseConnectOnSuccess', 30)
log.info('Started connecting...')
event = ed.pop_event(WifiEventNames.WIFI_CONNECTED, 60)
except Empty:
asserts.fail(('Failed to connect to %s' % config))
log.debug(event)
if expect_ssid:
actual_ssid = event['data'][WifiEnums.SSID_KEY]
asserts.assert_equal(expect_ssid, actual_ssid, 'SSID mismatch.')
else:
log.info(('Connected to %s.' % expect_ssid))
if validate_con:
log.info('Checking Internet access.')
time.sleep(4)
ping = ad.droid.httpPing(ping_addr)
log.info('Http ping result: {}'.format(ping))
asserts.assert_true(ping, 'No Internet access.')<|docstring|>Connects to an enterprise network and verify connection.
This logic expect the enterprise network to have Internet access.
Args:
config: A dict representing a wifi enterprise configuration.
ad: The android_device to operate with.
validate_con: If True, validate Internet connection after connecting to
the network.
Returns:
True if the connection is successful and Internet access works.<|endoftext|> |
7c7531a2a69db3d9f5e040d6516d6c994b1372576f587264d991c4a4b5c4d679 | def expand_enterprise_config_by_phase2(config):
'Take an enterprise config and generate a list of configs, each with\n a different phase2 auth type.\n\n Args:\n config: A dict representing enterprise config.\n\n Returns\n A list of enterprise configs.\n '
results = []
phase2_types = WifiEnums.EapPhase2
if (config[WifiEnums.Enterprise.EAP] == WifiEnums.Eap.PEAP):
phase2_types = [WifiEnums.EapPhase2.GTC, WifiEnums.EapPhase2.MSCHAPV2]
for phase2_type in phase2_types:
if ((WifiEnums.Enterprise.FQDN in config) and (phase2_type == WifiEnums.EapPhase2.GTC)):
continue
c = dict(config)
c[WifiEnums.Enterprise.PHASE2] = phase2_type
results.append(c)
return results | Take an enterprise config and generate a list of configs, each with
a different phase2 auth type.
Args:
config: A dict representing enterprise config.
Returns
A list of enterprise configs. | test/connectivity/acts/framework/acts/test_utils/wifi/wifi_test_utils.py | expand_enterprise_config_by_phase2 | Keneral/atools | 0 | python | def expand_enterprise_config_by_phase2(config):
'Take an enterprise config and generate a list of configs, each with\n a different phase2 auth type.\n\n Args:\n config: A dict representing enterprise config.\n\n Returns\n A list of enterprise configs.\n '
results = []
phase2_types = WifiEnums.EapPhase2
if (config[WifiEnums.Enterprise.EAP] == WifiEnums.Eap.PEAP):
phase2_types = [WifiEnums.EapPhase2.GTC, WifiEnums.EapPhase2.MSCHAPV2]
for phase2_type in phase2_types:
if ((WifiEnums.Enterprise.FQDN in config) and (phase2_type == WifiEnums.EapPhase2.GTC)):
continue
c = dict(config)
c[WifiEnums.Enterprise.PHASE2] = phase2_type
results.append(c)
return results | def expand_enterprise_config_by_phase2(config):
'Take an enterprise config and generate a list of configs, each with\n a different phase2 auth type.\n\n Args:\n config: A dict representing enterprise config.\n\n Returns\n A list of enterprise configs.\n '
results = []
phase2_types = WifiEnums.EapPhase2
if (config[WifiEnums.Enterprise.EAP] == WifiEnums.Eap.PEAP):
phase2_types = [WifiEnums.EapPhase2.GTC, WifiEnums.EapPhase2.MSCHAPV2]
for phase2_type in phase2_types:
if ((WifiEnums.Enterprise.FQDN in config) and (phase2_type == WifiEnums.EapPhase2.GTC)):
continue
c = dict(config)
c[WifiEnums.Enterprise.PHASE2] = phase2_type
results.append(c)
return results<|docstring|>Take an enterprise config and generate a list of configs, each with
a different phase2 auth type.
Args:
config: A dict representing enterprise config.
Returns
A list of enterprise configs.<|endoftext|> |
fba4b848e631d3323d2c61cedecdbc71b422523d6a700e58c5b8e36460784e45 | def get_receivers(ids: Optional[Sequence[str]]=None, key_word: Optional[str]=None, name_regex: Optional[str]=None, output_file: Optional[str]=None, status: Optional[int]=None, opts: Optional[pulumi.InvokeOptions]=None) -> AwaitableGetReceiversResult:
'\n This data source provides the Direct Mail Receiverses of the current Alibaba Cloud user.\n\n > **NOTE:** Available in v1.125.0+.\n\n ## Example Usage\n\n Basic Usage\n\n ```python\n import pulumi\n import pulumi_alicloud as alicloud\n\n example = alicloud.directmail.get_receivers(ids=["ca73b1e4fb0df7c935a5097a****"],\n name_regex="the_resource_name")\n pulumi.export("firstDirectMailReceiversId", example.receiverses[0].id)\n ```\n\n\n :param Sequence[str] ids: A list of Receivers IDs.\n :param str key_word: The key word.\n :param str name_regex: A regex string to filter results by Receivers name.\n :param int status: The status of the resource.\n '
__args__ = dict()
__args__['ids'] = ids
__args__['keyWord'] = key_word
__args__['nameRegex'] = name_regex
__args__['outputFile'] = output_file
__args__['status'] = status
if (opts is None):
opts = pulumi.InvokeOptions()
if (opts.version is None):
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('alicloud:directmail/getReceivers:getReceivers', __args__, opts=opts, typ=GetReceiversResult).value
return AwaitableGetReceiversResult(id=__ret__.id, ids=__ret__.ids, key_word=__ret__.key_word, name_regex=__ret__.name_regex, names=__ret__.names, output_file=__ret__.output_file, receiverses=__ret__.receiverses, status=__ret__.status) | This data source provides the Direct Mail Receiverses of the current Alibaba Cloud user.
> **NOTE:** Available in v1.125.0+.
## Example Usage
Basic Usage
```python
import pulumi
import pulumi_alicloud as alicloud
example = alicloud.directmail.get_receivers(ids=["ca73b1e4fb0df7c935a5097a****"],
name_regex="the_resource_name")
pulumi.export("firstDirectMailReceiversId", example.receiverses[0].id)
```
:param Sequence[str] ids: A list of Receivers IDs.
:param str key_word: The key word.
:param str name_regex: A regex string to filter results by Receivers name.
:param int status: The status of the resource. | sdk/python/pulumi_alicloud/directmail/get_receivers.py | get_receivers | pulumi/pulumi-alicloud | 42 | python | def get_receivers(ids: Optional[Sequence[str]]=None, key_word: Optional[str]=None, name_regex: Optional[str]=None, output_file: Optional[str]=None, status: Optional[int]=None, opts: Optional[pulumi.InvokeOptions]=None) -> AwaitableGetReceiversResult:
'\n This data source provides the Direct Mail Receiverses of the current Alibaba Cloud user.\n\n > **NOTE:** Available in v1.125.0+.\n\n ## Example Usage\n\n Basic Usage\n\n ```python\n import pulumi\n import pulumi_alicloud as alicloud\n\n example = alicloud.directmail.get_receivers(ids=["ca73b1e4fb0df7c935a5097a****"],\n name_regex="the_resource_name")\n pulumi.export("firstDirectMailReceiversId", example.receiverses[0].id)\n ```\n\n\n :param Sequence[str] ids: A list of Receivers IDs.\n :param str key_word: The key word.\n :param str name_regex: A regex string to filter results by Receivers name.\n :param int status: The status of the resource.\n '
__args__ = dict()
__args__['ids'] = ids
__args__['keyWord'] = key_word
__args__['nameRegex'] = name_regex
__args__['outputFile'] = output_file
__args__['status'] = status
if (opts is None):
opts = pulumi.InvokeOptions()
if (opts.version is None):
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('alicloud:directmail/getReceivers:getReceivers', __args__, opts=opts, typ=GetReceiversResult).value
return AwaitableGetReceiversResult(id=__ret__.id, ids=__ret__.ids, key_word=__ret__.key_word, name_regex=__ret__.name_regex, names=__ret__.names, output_file=__ret__.output_file, receiverses=__ret__.receiverses, status=__ret__.status) | def get_receivers(ids: Optional[Sequence[str]]=None, key_word: Optional[str]=None, name_regex: Optional[str]=None, output_file: Optional[str]=None, status: Optional[int]=None, opts: Optional[pulumi.InvokeOptions]=None) -> AwaitableGetReceiversResult:
'\n This data source provides the Direct Mail Receiverses of the current Alibaba Cloud user.\n\n > **NOTE:** Available in v1.125.0+.\n\n ## Example Usage\n\n Basic Usage\n\n ```python\n import pulumi\n import pulumi_alicloud as alicloud\n\n example = alicloud.directmail.get_receivers(ids=["ca73b1e4fb0df7c935a5097a****"],\n name_regex="the_resource_name")\n pulumi.export("firstDirectMailReceiversId", example.receiverses[0].id)\n ```\n\n\n :param Sequence[str] ids: A list of Receivers IDs.\n :param str key_word: The key word.\n :param str name_regex: A regex string to filter results by Receivers name.\n :param int status: The status of the resource.\n '
__args__ = dict()
__args__['ids'] = ids
__args__['keyWord'] = key_word
__args__['nameRegex'] = name_regex
__args__['outputFile'] = output_file
__args__['status'] = status
if (opts is None):
opts = pulumi.InvokeOptions()
if (opts.version is None):
opts.version = _utilities.get_version()
__ret__ = pulumi.runtime.invoke('alicloud:directmail/getReceivers:getReceivers', __args__, opts=opts, typ=GetReceiversResult).value
return AwaitableGetReceiversResult(id=__ret__.id, ids=__ret__.ids, key_word=__ret__.key_word, name_regex=__ret__.name_regex, names=__ret__.names, output_file=__ret__.output_file, receiverses=__ret__.receiverses, status=__ret__.status)<|docstring|>This data source provides the Direct Mail Receiverses of the current Alibaba Cloud user.
> **NOTE:** Available in v1.125.0+.
## Example Usage
Basic Usage
```python
import pulumi
import pulumi_alicloud as alicloud
example = alicloud.directmail.get_receivers(ids=["ca73b1e4fb0df7c935a5097a****"],
name_regex="the_resource_name")
pulumi.export("firstDirectMailReceiversId", example.receiverses[0].id)
```
:param Sequence[str] ids: A list of Receivers IDs.
:param str key_word: The key word.
:param str name_regex: A regex string to filter results by Receivers name.
:param int status: The status of the resource.<|endoftext|> |
bcf5b51a327014088b63f706e1dc3987198031e1f0241bd10b06cf4dd5bcb53c | @property
@pulumi.getter
def id(self) -> str:
'\n The provider-assigned unique ID for this managed resource.\n '
return pulumi.get(self, 'id') | The provider-assigned unique ID for this managed resource. | sdk/python/pulumi_alicloud/directmail/get_receivers.py | id | pulumi/pulumi-alicloud | 42 | python | @property
@pulumi.getter
def id(self) -> str:
'\n \n '
return pulumi.get(self, 'id') | @property
@pulumi.getter
def id(self) -> str:
'\n \n '
return pulumi.get(self, 'id')<|docstring|>The provider-assigned unique ID for this managed resource.<|endoftext|> |
58a8cf604b4ca4470fcb288c0f5daee5c60047a1d979428bfc1f1ca679204354 | def __init__(self, *args, **kwargs):
'UsageCWSResponse - a model defined in OpenAPI\n\n Keyword Args:\n usage ([UsageCWSHour]): [optional] Get hourly usage for Cloud Workload Security.\n '
super().__init__(kwargs)
self._check_pos_args(args) | UsageCWSResponse - a model defined in OpenAPI
Keyword Args:
usage ([UsageCWSHour]): [optional] Get hourly usage for Cloud Workload Security. | code/venv/lib/python3.8/site-packages/datadog_api_client/v1/model/usage_cws_response.py | __init__ | Valisback/hiring-engineers | 0 | python | def __init__(self, *args, **kwargs):
'UsageCWSResponse - a model defined in OpenAPI\n\n Keyword Args:\n usage ([UsageCWSHour]): [optional] Get hourly usage for Cloud Workload Security.\n '
super().__init__(kwargs)
self._check_pos_args(args) | def __init__(self, *args, **kwargs):
'UsageCWSResponse - a model defined in OpenAPI\n\n Keyword Args:\n usage ([UsageCWSHour]): [optional] Get hourly usage for Cloud Workload Security.\n '
super().__init__(kwargs)
self._check_pos_args(args)<|docstring|>UsageCWSResponse - a model defined in OpenAPI
Keyword Args:
usage ([UsageCWSHour]): [optional] Get hourly usage for Cloud Workload Security.<|endoftext|> |
c2caf952a05ea5df35d76800e48b78b18fefec3d0036693f5f260f138b223766 | @classmethod
def _from_openapi_data(cls, *args, **kwargs):
'Helper creating a new instance from a response.'
self = super(UsageCWSResponse, cls)._from_openapi_data(kwargs)
self._check_pos_args(args)
return self | Helper creating a new instance from a response. | code/venv/lib/python3.8/site-packages/datadog_api_client/v1/model/usage_cws_response.py | _from_openapi_data | Valisback/hiring-engineers | 0 | python | @classmethod
def _from_openapi_data(cls, *args, **kwargs):
self = super(UsageCWSResponse, cls)._from_openapi_data(kwargs)
self._check_pos_args(args)
return self | @classmethod
def _from_openapi_data(cls, *args, **kwargs):
self = super(UsageCWSResponse, cls)._from_openapi_data(kwargs)
self._check_pos_args(args)
return self<|docstring|>Helper creating a new instance from a response.<|endoftext|> |
55693cf17a42c1257a7634a73dc9988b5b00d7742e215741e4f5f1fd97a647f6 | def run(self):
'Main method for this class, which processes a list of objects.'
for obj in self.repo.resources(self.resource).tree.walk:
self.updated = False
obj_json = obj.json()
for date in obj_json.get('dates'):
self.replace_circa(date)
self.replace_undated(date)
self.replace_months(date)
self.remove_strings(date)
if (self.touch or self.updated):
self.save_obj(obj_json) | Main method for this class, which processes a list of objects. | archivessnake/replace_date_expressions.py | run | kngreaves/scripts | 15 | python | def run(self):
for obj in self.repo.resources(self.resource).tree.walk:
self.updated = False
obj_json = obj.json()
for date in obj_json.get('dates'):
self.replace_circa(date)
self.replace_undated(date)
self.replace_months(date)
self.remove_strings(date)
if (self.touch or self.updated):
self.save_obj(obj_json) | def run(self):
for obj in self.repo.resources(self.resource).tree.walk:
self.updated = False
obj_json = obj.json()
for date in obj_json.get('dates'):
self.replace_circa(date)
self.replace_undated(date)
self.replace_months(date)
self.remove_strings(date)
if (self.touch or self.updated):
self.save_obj(obj_json)<|docstring|>Main method for this class, which processes a list of objects.<|endoftext|> |
fab28d0e21cec2ee9778e882628ec5972f6901c8f334298214464b50bce52fdb | def save_obj(self, obj_json):
'Saves an updated object to ArchivesSpace'
updated = self.aspace.client.post(obj_json['uri'], json=obj_json)
if (updated.status_code == 200):
print('Archival object {} updated'.format(obj_json['uri']))
else:
print(updated.json()) | Saves an updated object to ArchivesSpace | archivessnake/replace_date_expressions.py | save_obj | kngreaves/scripts | 15 | python | def save_obj(self, obj_json):
updated = self.aspace.client.post(obj_json['uri'], json=obj_json)
if (updated.status_code == 200):
print('Archival object {} updated'.format(obj_json['uri']))
else:
print(updated.json()) | def save_obj(self, obj_json):
updated = self.aspace.client.post(obj_json['uri'], json=obj_json)
if (updated.status_code == 200):
print('Archival object {} updated'.format(obj_json['uri']))
else:
print(updated.json())<|docstring|>Saves an updated object to ArchivesSpace<|endoftext|> |
a7ddaf4a06b1b71f0b3bef7af46277e2b55ccc3a1d7ee10f2f38a1445ca3c0b2 | def bin_centers(bin_edges: np.ndarray) -> np.ndarray:
'Get bin centers given bin edges.\n\n Parameters\n ----------\n bin_edges : numpy.ndarray\n edges defining binning\n\n Returns\n -------\n numpy.ndarray\n the centers associated with the edges\n\n Examples\n --------\n >>> import numpy as np\n >>> from tdub.hist import bin_centers\n >>> bin_edges = np.linspace(25, 225, 11)\n >>> centers = bin_centers(bin_edges)\n >>> bin_edges\n array([ 25., 45., 65., 85., 105., 125., 145., 165., 185., 205., 225.])\n >>> centers\n array([ 35., 55., 75., 95., 115., 135., 155., 175., 195., 215.])\n\n '
return ((bin_edges[1:] + bin_edges[:(- 1)]) * 0.5) | Get bin centers given bin edges.
Parameters
----------
bin_edges : numpy.ndarray
edges defining binning
Returns
-------
numpy.ndarray
the centers associated with the edges
Examples
--------
>>> import numpy as np
>>> from tdub.hist import bin_centers
>>> bin_edges = np.linspace(25, 225, 11)
>>> centers = bin_centers(bin_edges)
>>> bin_edges
array([ 25., 45., 65., 85., 105., 125., 145., 165., 185., 205., 225.])
>>> centers
array([ 35., 55., 75., 95., 115., 135., 155., 175., 195., 215.]) | src/tdub/hist.py | bin_centers | douglasdavis/tdub | 0 | python | def bin_centers(bin_edges: np.ndarray) -> np.ndarray:
'Get bin centers given bin edges.\n\n Parameters\n ----------\n bin_edges : numpy.ndarray\n edges defining binning\n\n Returns\n -------\n numpy.ndarray\n the centers associated with the edges\n\n Examples\n --------\n >>> import numpy as np\n >>> from tdub.hist import bin_centers\n >>> bin_edges = np.linspace(25, 225, 11)\n >>> centers = bin_centers(bin_edges)\n >>> bin_edges\n array([ 25., 45., 65., 85., 105., 125., 145., 165., 185., 205., 225.])\n >>> centers\n array([ 35., 55., 75., 95., 115., 135., 155., 175., 195., 215.])\n\n '
return ((bin_edges[1:] + bin_edges[:(- 1)]) * 0.5) | def bin_centers(bin_edges: np.ndarray) -> np.ndarray:
'Get bin centers given bin edges.\n\n Parameters\n ----------\n bin_edges : numpy.ndarray\n edges defining binning\n\n Returns\n -------\n numpy.ndarray\n the centers associated with the edges\n\n Examples\n --------\n >>> import numpy as np\n >>> from tdub.hist import bin_centers\n >>> bin_edges = np.linspace(25, 225, 11)\n >>> centers = bin_centers(bin_edges)\n >>> bin_edges\n array([ 25., 45., 65., 85., 105., 125., 145., 165., 185., 205., 225.])\n >>> centers\n array([ 35., 55., 75., 95., 115., 135., 155., 175., 195., 215.])\n\n '
return ((bin_edges[1:] + bin_edges[:(- 1)]) * 0.5)<|docstring|>Get bin centers given bin edges.
Parameters
----------
bin_edges : numpy.ndarray
edges defining binning
Returns
-------
numpy.ndarray
the centers associated with the edges
Examples
--------
>>> import numpy as np
>>> from tdub.hist import bin_centers
>>> bin_edges = np.linspace(25, 225, 11)
>>> centers = bin_centers(bin_edges)
>>> bin_edges
array([ 25., 45., 65., 85., 105., 125., 145., 165., 185., 205., 225.])
>>> centers
array([ 35., 55., 75., 95., 115., 135., 155., 175., 195., 215.])<|endoftext|> |
b74005ddac9fe9f66bd57a9699a768dad93f0a8258ef2efadd6a60bd519c9539 | def to_uniform_bins(bin_edges: np.ndarray):
'Convert a set of variable width bins to arbitrary uniform bins.\n\n This will create a set of bin edges such that the bin centers are\n at whole numbers, i.e. 5 variable width bins will return an array\n from 0.5 to 5.5: [0.5, 1.5, 2.5, 3.5, 4.5, 5.5].\n\n Parameters\n ----------\n bin_edges : numpy.ndarray\n Array of bin edges.\n\n Returns\n -------\n numpy.ndarray\n The new set of uniform bins\n\n Examples\n --------\n >>> import numpy as np\n >>> from tdub.hist import to_uniform_bins\n >>> var_width = [0, 1, 3, 7, 15]\n >>> to_uniform_bins(var_width)\n array([0.5, 1.5, 2.5, 3.5, 4.5])\n\n '
return np.arange(0.5, (len(bin_edges) + 0.5), dtype=np.float64) | Convert a set of variable width bins to arbitrary uniform bins.
This will create a set of bin edges such that the bin centers are
at whole numbers, i.e. 5 variable width bins will return an array
from 0.5 to 5.5: [0.5, 1.5, 2.5, 3.5, 4.5, 5.5].
Parameters
----------
bin_edges : numpy.ndarray
Array of bin edges.
Returns
-------
numpy.ndarray
The new set of uniform bins
Examples
--------
>>> import numpy as np
>>> from tdub.hist import to_uniform_bins
>>> var_width = [0, 1, 3, 7, 15]
>>> to_uniform_bins(var_width)
array([0.5, 1.5, 2.5, 3.5, 4.5]) | src/tdub/hist.py | to_uniform_bins | douglasdavis/tdub | 0 | python | def to_uniform_bins(bin_edges: np.ndarray):
'Convert a set of variable width bins to arbitrary uniform bins.\n\n This will create a set of bin edges such that the bin centers are\n at whole numbers, i.e. 5 variable width bins will return an array\n from 0.5 to 5.5: [0.5, 1.5, 2.5, 3.5, 4.5, 5.5].\n\n Parameters\n ----------\n bin_edges : numpy.ndarray\n Array of bin edges.\n\n Returns\n -------\n numpy.ndarray\n The new set of uniform bins\n\n Examples\n --------\n >>> import numpy as np\n >>> from tdub.hist import to_uniform_bins\n >>> var_width = [0, 1, 3, 7, 15]\n >>> to_uniform_bins(var_width)\n array([0.5, 1.5, 2.5, 3.5, 4.5])\n\n '
return np.arange(0.5, (len(bin_edges) + 0.5), dtype=np.float64) | def to_uniform_bins(bin_edges: np.ndarray):
'Convert a set of variable width bins to arbitrary uniform bins.\n\n This will create a set of bin edges such that the bin centers are\n at whole numbers, i.e. 5 variable width bins will return an array\n from 0.5 to 5.5: [0.5, 1.5, 2.5, 3.5, 4.5, 5.5].\n\n Parameters\n ----------\n bin_edges : numpy.ndarray\n Array of bin edges.\n\n Returns\n -------\n numpy.ndarray\n The new set of uniform bins\n\n Examples\n --------\n >>> import numpy as np\n >>> from tdub.hist import to_uniform_bins\n >>> var_width = [0, 1, 3, 7, 15]\n >>> to_uniform_bins(var_width)\n array([0.5, 1.5, 2.5, 3.5, 4.5])\n\n '
return np.arange(0.5, (len(bin_edges) + 0.5), dtype=np.float64)<|docstring|>Convert a set of variable width bins to arbitrary uniform bins.
This will create a set of bin edges such that the bin centers are
at whole numbers, i.e. 5 variable width bins will return an array
from 0.5 to 5.5: [0.5, 1.5, 2.5, 3.5, 4.5, 5.5].
Parameters
----------
bin_edges : numpy.ndarray
Array of bin edges.
Returns
-------
numpy.ndarray
The new set of uniform bins
Examples
--------
>>> import numpy as np
>>> from tdub.hist import to_uniform_bins
>>> var_width = [0, 1, 3, 7, 15]
>>> to_uniform_bins(var_width)
array([0.5, 1.5, 2.5, 3.5, 4.5])<|endoftext|> |
47d12b129574ef9847ff4b3c364e5cda172342f0587f7e2520a9c69abd0492af | def edges_and_centers(bins: (int | Iterable), range: (tuple[(float, float)] | None)=None) -> tuple[(np.ndarray, np.ndarray)]:
'Create arrays for edges and bin centers.\n\n Parameters\n ----------\n bins : int or sequence of scalers\n the number of bins or sequence representing bin edges\n range : tuple(float, float), optional\n the minimum and maximum defining the bin range (used if bins is integral)\n\n Returns\n -------\n :py:obj:`numpy.ndarray`\n the bin edges\n :py:obj:`numpy.ndarray`\n the bin centers\n\n Examples\n --------\n from bin multiplicity and a range\n\n >>> from tdub.hist import edges_and_centers\n >>> edges, centers = edges_and_centers(bins=20, range=(25, 225))\n\n from pre-existing edges\n\n >>> edges, centers = edges_and_centers(np.linspace(0, 10, 21))\n\n '
if isinstance(bins, int):
if (range is None):
raise ValueError('for integral bins we require the range argument')
edges = np.linspace(range[0], range[1], (bins + 1))
else:
edges = np.asarray(bins)
if (not np.all((edges[1:] >= edges[:(- 1)]))):
raise ValueError('bins edges must monotonically increase')
centers = bin_centers(edges)
return (edges, centers) | Create arrays for edges and bin centers.
Parameters
----------
bins : int or sequence of scalers
the number of bins or sequence representing bin edges
range : tuple(float, float), optional
the minimum and maximum defining the bin range (used if bins is integral)
Returns
-------
:py:obj:`numpy.ndarray`
the bin edges
:py:obj:`numpy.ndarray`
the bin centers
Examples
--------
from bin multiplicity and a range
>>> from tdub.hist import edges_and_centers
>>> edges, centers = edges_and_centers(bins=20, range=(25, 225))
from pre-existing edges
>>> edges, centers = edges_and_centers(np.linspace(0, 10, 21)) | src/tdub/hist.py | edges_and_centers | douglasdavis/tdub | 0 | python | def edges_and_centers(bins: (int | Iterable), range: (tuple[(float, float)] | None)=None) -> tuple[(np.ndarray, np.ndarray)]:
'Create arrays for edges and bin centers.\n\n Parameters\n ----------\n bins : int or sequence of scalers\n the number of bins or sequence representing bin edges\n range : tuple(float, float), optional\n the minimum and maximum defining the bin range (used if bins is integral)\n\n Returns\n -------\n :py:obj:`numpy.ndarray`\n the bin edges\n :py:obj:`numpy.ndarray`\n the bin centers\n\n Examples\n --------\n from bin multiplicity and a range\n\n >>> from tdub.hist import edges_and_centers\n >>> edges, centers = edges_and_centers(bins=20, range=(25, 225))\n\n from pre-existing edges\n\n >>> edges, centers = edges_and_centers(np.linspace(0, 10, 21))\n\n '
if isinstance(bins, int):
if (range is None):
raise ValueError('for integral bins we require the range argument')
edges = np.linspace(range[0], range[1], (bins + 1))
else:
edges = np.asarray(bins)
if (not np.all((edges[1:] >= edges[:(- 1)]))):
raise ValueError('bins edges must monotonically increase')
centers = bin_centers(edges)
return (edges, centers) | def edges_and_centers(bins: (int | Iterable), range: (tuple[(float, float)] | None)=None) -> tuple[(np.ndarray, np.ndarray)]:
'Create arrays for edges and bin centers.\n\n Parameters\n ----------\n bins : int or sequence of scalers\n the number of bins or sequence representing bin edges\n range : tuple(float, float), optional\n the minimum and maximum defining the bin range (used if bins is integral)\n\n Returns\n -------\n :py:obj:`numpy.ndarray`\n the bin edges\n :py:obj:`numpy.ndarray`\n the bin centers\n\n Examples\n --------\n from bin multiplicity and a range\n\n >>> from tdub.hist import edges_and_centers\n >>> edges, centers = edges_and_centers(bins=20, range=(25, 225))\n\n from pre-existing edges\n\n >>> edges, centers = edges_and_centers(np.linspace(0, 10, 21))\n\n '
if isinstance(bins, int):
if (range is None):
raise ValueError('for integral bins we require the range argument')
edges = np.linspace(range[0], range[1], (bins + 1))
else:
edges = np.asarray(bins)
if (not np.all((edges[1:] >= edges[:(- 1)]))):
raise ValueError('bins edges must monotonically increase')
centers = bin_centers(edges)
return (edges, centers)<|docstring|>Create arrays for edges and bin centers.
Parameters
----------
bins : int or sequence of scalers
the number of bins or sequence representing bin edges
range : tuple(float, float), optional
the minimum and maximum defining the bin range (used if bins is integral)
Returns
-------
:py:obj:`numpy.ndarray`
the bin edges
:py:obj:`numpy.ndarray`
the bin centers
Examples
--------
from bin multiplicity and a range
>>> from tdub.hist import edges_and_centers
>>> edges, centers = edges_and_centers(bins=20, range=(25, 225))
from pre-existing edges
>>> edges, centers = edges_and_centers(np.linspace(0, 10, 21))<|endoftext|> |
d8792fa57a5989680c05b97485f83bc7b93f826ac0d6691a27b20d9ef0fa5961 | def __init__(self, nominal: np.ndarray, up: np.ndarray, down: np.ndarray) -> None:
'Class constructor.'
self.nominal = nominal
self.up = up
self.down = down
self.percent_diff_up = (((up - nominal) / nominal) * 100.0)
self.percent_diff_down = (((down - nominal) / nominal) * 100.0) | Class constructor. | src/tdub/hist.py | __init__ | douglasdavis/tdub | 0 | python | def __init__(self, nominal: np.ndarray, up: np.ndarray, down: np.ndarray) -> None:
self.nominal = nominal
self.up = up
self.down = down
self.percent_diff_up = (((up - nominal) / nominal) * 100.0)
self.percent_diff_down = (((down - nominal) / nominal) * 100.0) | def __init__(self, nominal: np.ndarray, up: np.ndarray, down: np.ndarray) -> None:
self.nominal = nominal
self.up = up
self.down = down
self.percent_diff_up = (((up - nominal) / nominal) * 100.0)
self.percent_diff_down = (((down - nominal) / nominal) * 100.0)<|docstring|>Class constructor.<|endoftext|> |
b125a655435e1d674dc6a9d64d1b65dfc3805da7bf9652af542c64b9b3bc51e3 | @property
def percent_diff_min(self) -> float:
'float: minimum for percent difference.'
return float(np.amin([self.percent_diff_up, self.percent_diff_down])) | float: minimum for percent difference. | src/tdub/hist.py | percent_diff_min | douglasdavis/tdub | 0 | python | @property
def percent_diff_min(self) -> float:
return float(np.amin([self.percent_diff_up, self.percent_diff_down])) | @property
def percent_diff_min(self) -> float:
return float(np.amin([self.percent_diff_up, self.percent_diff_down]))<|docstring|>float: minimum for percent difference.<|endoftext|> |
6e749c80ebf8e51bf3bda3f2980af4a1df7cea9e3dc6f7f502d0217a4bf3b85b | @property
def percent_diff_max(self) -> float:
'float: maximum for percent difference.'
return float(np.amax([self.percent_diff_up, self.percent_diff_down])) | float: maximum for percent difference. | src/tdub/hist.py | percent_diff_max | douglasdavis/tdub | 0 | python | @property
def percent_diff_max(self) -> float:
return float(np.amax([self.percent_diff_up, self.percent_diff_down])) | @property
def percent_diff_max(self) -> float:
return float(np.amax([self.percent_diff_up, self.percent_diff_down]))<|docstring|>float: maximum for percent difference.<|endoftext|> |
1a1c6463ec893c5b511e5a6ad998b576a93beb1cf0c3bcaa9a16a2ce1d23634c | @property
def template_max(self) -> float:
'float: maximum height of a variation.'
return float(np.amax(np.concatenate([self.up, self.down]))) | float: maximum height of a variation. | src/tdub/hist.py | template_max | douglasdavis/tdub | 0 | python | @property
def template_max(self) -> float:
return float(np.amax(np.concatenate([self.up, self.down]))) | @property
def template_max(self) -> float:
return float(np.amax(np.concatenate([self.up, self.down])))<|docstring|>float: maximum height of a variation.<|endoftext|> |
48e7f43fde82e4068402b4ff1f43b9ee9cd9c304403902128a5091cef08c47d0 | @staticmethod
def one_sided(nominal: np.ndarray, up: np.ndarray) -> SystematicComparison:
'Generate components of a systematic comparion plot.\n\n Parameters\n ----------\n nominal : numpy.ndarray\n Histogram bin counts for the nominal template.\n up : numpy.ndarray\n Histogram bin counts for the "up" variation.\n\n Returns\n -------\n SystematicComparison\n The complete description of the comparison\n\n '
diffs = (nominal - up)
down = (nominal + diffs)
return SystematicComparison(nominal, up, down) | Generate components of a systematic comparion plot.
Parameters
----------
nominal : numpy.ndarray
Histogram bin counts for the nominal template.
up : numpy.ndarray
Histogram bin counts for the "up" variation.
Returns
-------
SystematicComparison
The complete description of the comparison | src/tdub/hist.py | one_sided | douglasdavis/tdub | 0 | python | @staticmethod
def one_sided(nominal: np.ndarray, up: np.ndarray) -> SystematicComparison:
'Generate components of a systematic comparion plot.\n\n Parameters\n ----------\n nominal : numpy.ndarray\n Histogram bin counts for the nominal template.\n up : numpy.ndarray\n Histogram bin counts for the "up" variation.\n\n Returns\n -------\n SystematicComparison\n The complete description of the comparison\n\n '
diffs = (nominal - up)
down = (nominal + diffs)
return SystematicComparison(nominal, up, down) | @staticmethod
def one_sided(nominal: np.ndarray, up: np.ndarray) -> SystematicComparison:
'Generate components of a systematic comparion plot.\n\n Parameters\n ----------\n nominal : numpy.ndarray\n Histogram bin counts for the nominal template.\n up : numpy.ndarray\n Histogram bin counts for the "up" variation.\n\n Returns\n -------\n SystematicComparison\n The complete description of the comparison\n\n '
diffs = (nominal - up)
down = (nominal + diffs)
return SystematicComparison(nominal, up, down)<|docstring|>Generate components of a systematic comparion plot.
Parameters
----------
nominal : numpy.ndarray
Histogram bin counts for the nominal template.
up : numpy.ndarray
Histogram bin counts for the "up" variation.
Returns
-------
SystematicComparison
The complete description of the comparison<|endoftext|> |
4999864a9499bc25b05cc15df4bca794644a848707dccb25c9e7b2227983c6a5 | def create_app():
'\n Create a Character Sheeter app.\n\n The Character Sheeter app currently relies on two sub-apps:\n - layout: a character sheet layout, that serves as a base for a character sheet construction\n - sheet: a character sheet, containing data that defines a player character\n '
app = Flask(__name__)
app.config.from_pyfile('../settings.py')
app.register_blueprint(layout_bp, url_prefix='/layouts')
app.register_blueprint(sheet_bp, url_prefix='/sheets')
app.register_blueprint(user_bp, url_prefix='/users')
db.init_app(app)
ma.init_app(app)
migrate.init_app(app)
login_manager.init_app(app)
return app | Create a Character Sheeter app.
The Character Sheeter app currently relies on two sub-apps:
- layout: a character sheet layout, that serves as a base for a character sheet construction
- sheet: a character sheet, containing data that defines a player character | sheeter/app_factory.py | create_app | rudolfce/character-sheeter | 0 | python | def create_app():
'\n Create a Character Sheeter app.\n\n The Character Sheeter app currently relies on two sub-apps:\n - layout: a character sheet layout, that serves as a base for a character sheet construction\n - sheet: a character sheet, containing data that defines a player character\n '
app = Flask(__name__)
app.config.from_pyfile('../settings.py')
app.register_blueprint(layout_bp, url_prefix='/layouts')
app.register_blueprint(sheet_bp, url_prefix='/sheets')
app.register_blueprint(user_bp, url_prefix='/users')
db.init_app(app)
ma.init_app(app)
migrate.init_app(app)
login_manager.init_app(app)
return app | def create_app():
'\n Create a Character Sheeter app.\n\n The Character Sheeter app currently relies on two sub-apps:\n - layout: a character sheet layout, that serves as a base for a character sheet construction\n - sheet: a character sheet, containing data that defines a player character\n '
app = Flask(__name__)
app.config.from_pyfile('../settings.py')
app.register_blueprint(layout_bp, url_prefix='/layouts')
app.register_blueprint(sheet_bp, url_prefix='/sheets')
app.register_blueprint(user_bp, url_prefix='/users')
db.init_app(app)
ma.init_app(app)
migrate.init_app(app)
login_manager.init_app(app)
return app<|docstring|>Create a Character Sheeter app.
The Character Sheeter app currently relies on two sub-apps:
- layout: a character sheet layout, that serves as a base for a character sheet construction
- sheet: a character sheet, containing data that defines a player character<|endoftext|> |
c4c789958e575118f22e3ed5220639e3e8c7eb33ae427be25b5bd49a147ade6e | def __init__(self, model_name='u2net', model_dir=None):
"\n Creates a u2net model using either u2net or u2netp (smaller) architectures.\n By default it will use the pretrained network, stored in '~/.u2net'.\n :param model_name: {u2net, u2netp}\n :param model_dir: Specify a different directory to use a custom model.\n "
if (model_name == 'u2net'):
self.model = U2NET(3, 1)
elif (model_name == 'u2netp'):
self.model = U2NETP(3, 1)
if (not model_dir):
model_dir = os.path.join(u2net.U2NET_MODEL_DIR, (model_name + '.pth'))
else:
model_dir = os.path.join(model_dir, (model_name + '.pth'))
if torch.cuda.is_available():
self.model.load_state_dict(torch.load(model_dir))
self.model.cuda()
else:
self.model.load_state_dict(torch.load(model_dir, map_location='cpu'))
self.model.eval() | Creates a u2net model using either u2net or u2netp (smaller) architectures.
By default it will use the pretrained network, stored in '~/.u2net'.
:param model_name: {u2net, u2netp}
:param model_dir: Specify a different directory to use a custom model. | u2net/u2net.py | __init__ | David-Estevez/u2net | 0 | python | def __init__(self, model_name='u2net', model_dir=None):
"\n Creates a u2net model using either u2net or u2netp (smaller) architectures.\n By default it will use the pretrained network, stored in '~/.u2net'.\n :param model_name: {u2net, u2netp}\n :param model_dir: Specify a different directory to use a custom model.\n "
if (model_name == 'u2net'):
self.model = U2NET(3, 1)
elif (model_name == 'u2netp'):
self.model = U2NETP(3, 1)
if (not model_dir):
model_dir = os.path.join(u2net.U2NET_MODEL_DIR, (model_name + '.pth'))
else:
model_dir = os.path.join(model_dir, (model_name + '.pth'))
if torch.cuda.is_available():
self.model.load_state_dict(torch.load(model_dir))
self.model.cuda()
else:
self.model.load_state_dict(torch.load(model_dir, map_location='cpu'))
self.model.eval() | def __init__(self, model_name='u2net', model_dir=None):
"\n Creates a u2net model using either u2net or u2netp (smaller) architectures.\n By default it will use the pretrained network, stored in '~/.u2net'.\n :param model_name: {u2net, u2netp}\n :param model_dir: Specify a different directory to use a custom model.\n "
if (model_name == 'u2net'):
self.model = U2NET(3, 1)
elif (model_name == 'u2netp'):
self.model = U2NETP(3, 1)
if (not model_dir):
model_dir = os.path.join(u2net.U2NET_MODEL_DIR, (model_name + '.pth'))
else:
model_dir = os.path.join(model_dir, (model_name + '.pth'))
if torch.cuda.is_available():
self.model.load_state_dict(torch.load(model_dir))
self.model.cuda()
else:
self.model.load_state_dict(torch.load(model_dir, map_location='cpu'))
self.model.eval()<|docstring|>Creates a u2net model using either u2net or u2netp (smaller) architectures.
By default it will use the pretrained network, stored in '~/.u2net'.
:param model_name: {u2net, u2netp}
:param model_dir: Specify a different directory to use a custom model.<|endoftext|> |
5df5c6b3fd422044d98b8796aaabac5bd0469704d4d73efa709bdcdd255eb732 | def predict(self, image, do_resize=True, prediction_size=320):
'\n Predict segmentation mask from an image.\n :param image: An image that has already been loaded (normalized and RGB format).\n :param do_resize: If true, resizes the input image to perform the segmentation (faster).\n :param prediction_size: If resizing is enabled, selects the size used for the prediction.\n :return: Segmentation mask of the salient object(s). It will be of the same size as input, even if resizing is enabled for the prediction.\n '
if do_resize:
(h, w) = image.shape[:2]
if (h < w):
(new_h, new_w) = (((prediction_size * h) // w), prediction_size)
else:
(new_h, new_w) = (prediction_size, ((prediction_size * w) // h))
image = resize(image, (new_h, new_w), anti_aliasing=True)
image = (image / np.max(image))
image[(:, :, 0)] = ((image[(:, :, 0)] - 0.485) / 0.229)
image[(:, :, 1)] = ((image[(:, :, 1)] - 0.456) / 0.224)
image[(:, :, 2)] = ((image[(:, :, 2)] - 0.406) / 0.225)
img_tensor = torch.from_numpy(image.transpose((2, 0, 1))).unsqueeze(0).float()
if torch.cuda.is_available():
img_tensor.cuda()
(d1, d2, d3, d4, d5, d6, d7) = self.model(img_tensor)
pred = d1[(:, 0, :, :)]
pred = ((pred - torch.min(pred)) / (torch.max(pred) - torch.min(pred)))
mask = pred.detach().numpy().transpose((1, 2, 0))[(..., 0)]
del d1, d2, d3, d4, d5, d6, d7
if do_resize:
mask = resize(mask, (h, w), anti_aliasing=True)
return mask | Predict segmentation mask from an image.
:param image: An image that has already been loaded (normalized and RGB format).
:param do_resize: If true, resizes the input image to perform the segmentation (faster).
:param prediction_size: If resizing is enabled, selects the size used for the prediction.
:return: Segmentation mask of the salient object(s). It will be of the same size as input, even if resizing is enabled for the prediction. | u2net/u2net.py | predict | David-Estevez/u2net | 0 | python | def predict(self, image, do_resize=True, prediction_size=320):
'\n Predict segmentation mask from an image.\n :param image: An image that has already been loaded (normalized and RGB format).\n :param do_resize: If true, resizes the input image to perform the segmentation (faster).\n :param prediction_size: If resizing is enabled, selects the size used for the prediction.\n :return: Segmentation mask of the salient object(s). It will be of the same size as input, even if resizing is enabled for the prediction.\n '
if do_resize:
(h, w) = image.shape[:2]
if (h < w):
(new_h, new_w) = (((prediction_size * h) // w), prediction_size)
else:
(new_h, new_w) = (prediction_size, ((prediction_size * w) // h))
image = resize(image, (new_h, new_w), anti_aliasing=True)
image = (image / np.max(image))
image[(:, :, 0)] = ((image[(:, :, 0)] - 0.485) / 0.229)
image[(:, :, 1)] = ((image[(:, :, 1)] - 0.456) / 0.224)
image[(:, :, 2)] = ((image[(:, :, 2)] - 0.406) / 0.225)
img_tensor = torch.from_numpy(image.transpose((2, 0, 1))).unsqueeze(0).float()
if torch.cuda.is_available():
img_tensor.cuda()
(d1, d2, d3, d4, d5, d6, d7) = self.model(img_tensor)
pred = d1[(:, 0, :, :)]
pred = ((pred - torch.min(pred)) / (torch.max(pred) - torch.min(pred)))
mask = pred.detach().numpy().transpose((1, 2, 0))[(..., 0)]
del d1, d2, d3, d4, d5, d6, d7
if do_resize:
mask = resize(mask, (h, w), anti_aliasing=True)
return mask | def predict(self, image, do_resize=True, prediction_size=320):
'\n Predict segmentation mask from an image.\n :param image: An image that has already been loaded (normalized and RGB format).\n :param do_resize: If true, resizes the input image to perform the segmentation (faster).\n :param prediction_size: If resizing is enabled, selects the size used for the prediction.\n :return: Segmentation mask of the salient object(s). It will be of the same size as input, even if resizing is enabled for the prediction.\n '
if do_resize:
(h, w) = image.shape[:2]
if (h < w):
(new_h, new_w) = (((prediction_size * h) // w), prediction_size)
else:
(new_h, new_w) = (prediction_size, ((prediction_size * w) // h))
image = resize(image, (new_h, new_w), anti_aliasing=True)
image = (image / np.max(image))
image[(:, :, 0)] = ((image[(:, :, 0)] - 0.485) / 0.229)
image[(:, :, 1)] = ((image[(:, :, 1)] - 0.456) / 0.224)
image[(:, :, 2)] = ((image[(:, :, 2)] - 0.406) / 0.225)
img_tensor = torch.from_numpy(image.transpose((2, 0, 1))).unsqueeze(0).float()
if torch.cuda.is_available():
img_tensor.cuda()
(d1, d2, d3, d4, d5, d6, d7) = self.model(img_tensor)
pred = d1[(:, 0, :, :)]
pred = ((pred - torch.min(pred)) / (torch.max(pred) - torch.min(pred)))
mask = pred.detach().numpy().transpose((1, 2, 0))[(..., 0)]
del d1, d2, d3, d4, d5, d6, d7
if do_resize:
mask = resize(mask, (h, w), anti_aliasing=True)
return mask<|docstring|>Predict segmentation mask from an image.
:param image: An image that has already been loaded (normalized and RGB format).
:param do_resize: If true, resizes the input image to perform the segmentation (faster).
:param prediction_size: If resizing is enabled, selects the size used for the prediction.
:return: Segmentation mask of the salient object(s). It will be of the same size as input, even if resizing is enabled for the prediction.<|endoftext|> |
219d4a0a3fe5653cff4d8908d2e9a15ca96833b7fd47117dd43906e6a31b5a3d | def build_bi_gram_cnt(train_text):
'\n count the uni word and word pair\n :param train_text: filename for train\n '
def update_cnt(last_index, cur_index):
Bigram.uni_cnt[cur_index] += 1
Bigram.bi_cnt[last_index][cur_index] += 1
if (Bigram.bi_cnt[last_index][cur_index] == 1):
Bigram.kn_diff_bi_row[0][last_index] += 1
Bigram.kn_diff_bi_col[0][cur_index] += 1
elif (Bigram.bi_cnt[last_index][cur_index] == 2):
Bigram.kn_diff_bi_row[1][last_index] += 1
Bigram.kn_diff_bi_row[0][last_index] -= 1
elif (Bigram.bi_cnt[last_index][cur_index] == 3):
Bigram.kn_diff_bi_row[2][last_index] += 1
Bigram.kn_diff_bi_row[1][last_index] -= 1
line_num = 0
for line in train_text:
lwords = TextParse.from_segment(line)
last_index = Bigram.SINDEX
Bigram.uni_cnt[last_index] += 1
for word in lwords:
cur_index = Bigram.find_word_dic(word)
if (cur_index == (- 1)):
continue
update_cnt(last_index, cur_index)
last_index = cur_index
cur_index = Bigram.EINDEX
update_cnt(last_index, cur_index)
line_num += 1
if (DEBUG and ((line_num % 100) == 0)):
print(('line: ' + str(line_num))) | count the uni word and word pair
:param train_text: filename for train | Source/bigram.py | build_bi_gram_cnt | laddie132/RITE_zh-CN | 5 | python | def build_bi_gram_cnt(train_text):
'\n count the uni word and word pair\n :param train_text: filename for train\n '
def update_cnt(last_index, cur_index):
Bigram.uni_cnt[cur_index] += 1
Bigram.bi_cnt[last_index][cur_index] += 1
if (Bigram.bi_cnt[last_index][cur_index] == 1):
Bigram.kn_diff_bi_row[0][last_index] += 1
Bigram.kn_diff_bi_col[0][cur_index] += 1
elif (Bigram.bi_cnt[last_index][cur_index] == 2):
Bigram.kn_diff_bi_row[1][last_index] += 1
Bigram.kn_diff_bi_row[0][last_index] -= 1
elif (Bigram.bi_cnt[last_index][cur_index] == 3):
Bigram.kn_diff_bi_row[2][last_index] += 1
Bigram.kn_diff_bi_row[1][last_index] -= 1
line_num = 0
for line in train_text:
lwords = TextParse.from_segment(line)
last_index = Bigram.SINDEX
Bigram.uni_cnt[last_index] += 1
for word in lwords:
cur_index = Bigram.find_word_dic(word)
if (cur_index == (- 1)):
continue
update_cnt(last_index, cur_index)
last_index = cur_index
cur_index = Bigram.EINDEX
update_cnt(last_index, cur_index)
line_num += 1
if (DEBUG and ((line_num % 100) == 0)):
print(('line: ' + str(line_num))) | def build_bi_gram_cnt(train_text):
'\n count the uni word and word pair\n :param train_text: filename for train\n '
def update_cnt(last_index, cur_index):
Bigram.uni_cnt[cur_index] += 1
Bigram.bi_cnt[last_index][cur_index] += 1
if (Bigram.bi_cnt[last_index][cur_index] == 1):
Bigram.kn_diff_bi_row[0][last_index] += 1
Bigram.kn_diff_bi_col[0][cur_index] += 1
elif (Bigram.bi_cnt[last_index][cur_index] == 2):
Bigram.kn_diff_bi_row[1][last_index] += 1
Bigram.kn_diff_bi_row[0][last_index] -= 1
elif (Bigram.bi_cnt[last_index][cur_index] == 3):
Bigram.kn_diff_bi_row[2][last_index] += 1
Bigram.kn_diff_bi_row[1][last_index] -= 1
line_num = 0
for line in train_text:
lwords = TextParse.from_segment(line)
last_index = Bigram.SINDEX
Bigram.uni_cnt[last_index] += 1
for word in lwords:
cur_index = Bigram.find_word_dic(word)
if (cur_index == (- 1)):
continue
update_cnt(last_index, cur_index)
last_index = cur_index
cur_index = Bigram.EINDEX
update_cnt(last_index, cur_index)
line_num += 1
if (DEBUG and ((line_num % 100) == 0)):
print(('line: ' + str(line_num)))<|docstring|>count the uni word and word pair
:param train_text: filename for train<|endoftext|> |
e18d260aee9a019658093b4e86346d019ade3a6dff97a725dd6f5d4d34f4852e | def build_arg_cg98():
'\n calculate the arguments of KN smoothing defined by Chen and Goodman\n '
kn_n = [0, 0, 0, 0]
points = Bigram.bi_cnt.nonzero()
x = points[0]
y = points[1]
Bigram.kn_diff_bi = len(x)
for i in range(len(x)):
cx = x[i]
cy = y[i]
if (4 >= Bigram.bi_cnt[cx][cy] > 0):
kn_n[(Bigram.bi_cnt[cx][cy] - 1)] += 1
for i in range(4):
if (kn_n[i] == 0):
return
Y = ((kn_n[0] * 1.0) / (kn_n[0] + (2 * kn_n[1])))
Bigram.kn_d_cg98[0] = (1 - ((((2 * Y) * kn_n[1]) * 1.0) / kn_n[0]))
Bigram.kn_d_cg98[1] = (2 - ((((3 * Y) * kn_n[2]) * 1.0) / kn_n[1]))
Bigram.kn_d_cg98[2] = (3 - ((((4 * Y) * kn_n[3]) * 1.0) / kn_n[2])) | calculate the arguments of KN smoothing defined by Chen and Goodman | Source/bigram.py | build_arg_cg98 | laddie132/RITE_zh-CN | 5 | python | def build_arg_cg98():
'\n \n '
kn_n = [0, 0, 0, 0]
points = Bigram.bi_cnt.nonzero()
x = points[0]
y = points[1]
Bigram.kn_diff_bi = len(x)
for i in range(len(x)):
cx = x[i]
cy = y[i]
if (4 >= Bigram.bi_cnt[cx][cy] > 0):
kn_n[(Bigram.bi_cnt[cx][cy] - 1)] += 1
for i in range(4):
if (kn_n[i] == 0):
return
Y = ((kn_n[0] * 1.0) / (kn_n[0] + (2 * kn_n[1])))
Bigram.kn_d_cg98[0] = (1 - ((((2 * Y) * kn_n[1]) * 1.0) / kn_n[0]))
Bigram.kn_d_cg98[1] = (2 - ((((3 * Y) * kn_n[2]) * 1.0) / kn_n[1]))
Bigram.kn_d_cg98[2] = (3 - ((((4 * Y) * kn_n[3]) * 1.0) / kn_n[2])) | def build_arg_cg98():
'\n \n '
kn_n = [0, 0, 0, 0]
points = Bigram.bi_cnt.nonzero()
x = points[0]
y = points[1]
Bigram.kn_diff_bi = len(x)
for i in range(len(x)):
cx = x[i]
cy = y[i]
if (4 >= Bigram.bi_cnt[cx][cy] > 0):
kn_n[(Bigram.bi_cnt[cx][cy] - 1)] += 1
for i in range(4):
if (kn_n[i] == 0):
return
Y = ((kn_n[0] * 1.0) / (kn_n[0] + (2 * kn_n[1])))
Bigram.kn_d_cg98[0] = (1 - ((((2 * Y) * kn_n[1]) * 1.0) / kn_n[0]))
Bigram.kn_d_cg98[1] = (2 - ((((3 * Y) * kn_n[2]) * 1.0) / kn_n[1]))
Bigram.kn_d_cg98[2] = (3 - ((((4 * Y) * kn_n[3]) * 1.0) / kn_n[2]))<|docstring|>calculate the arguments of KN smoothing defined by Chen and Goodman<|endoftext|> |
f76bec2ed4ed00d3b491c92e6c7b39dab7f2cbe7a4840866a508e3be95de12e1 | @staticmethod
def find_word_dic(word):
'\n find word in bigram word dictionary or insert it\n :return: pos in dictionary\n '
if (len(Bigram.words_dic) >= MAX_DICT_LEN):
return (- 1)
if (word not in Bigram.words_dic):
Bigram.words_dic.append(word)
return Bigram.words_dic.index(word) | find word in bigram word dictionary or insert it
:return: pos in dictionary | Source/bigram.py | find_word_dic | laddie132/RITE_zh-CN | 5 | python | @staticmethod
def find_word_dic(word):
'\n find word in bigram word dictionary or insert it\n :return: pos in dictionary\n '
if (len(Bigram.words_dic) >= MAX_DICT_LEN):
return (- 1)
if (word not in Bigram.words_dic):
Bigram.words_dic.append(word)
return Bigram.words_dic.index(word) | @staticmethod
def find_word_dic(word):
'\n find word in bigram word dictionary or insert it\n :return: pos in dictionary\n '
if (len(Bigram.words_dic) >= MAX_DICT_LEN):
return (- 1)
if (word not in Bigram.words_dic):
Bigram.words_dic.append(word)
return Bigram.words_dic.index(word)<|docstring|>find word in bigram word dictionary or insert it
:return: pos in dictionary<|endoftext|> |
b35184386ff94e34e95a55604ab6dbbf415528f372fb5338525653e22fa9687d | @staticmethod
def calc_prob(word1, word2):
'\n calculate the bigram probability of word2/word1\n :return: probability in [0,1]\n '
if ((word1 not in Bigram.words_dic) or (word2 not in Bigram.words_dic)):
return (- 1)
index1 = Bigram.words_dic.index(word1)
index2 = Bigram.words_dic.index(word2)
return Bigram._calc_prob_mod_kn(index1, index2) | calculate the bigram probability of word2/word1
:return: probability in [0,1] | Source/bigram.py | calc_prob | laddie132/RITE_zh-CN | 5 | python | @staticmethod
def calc_prob(word1, word2):
'\n calculate the bigram probability of word2/word1\n :return: probability in [0,1]\n '
if ((word1 not in Bigram.words_dic) or (word2 not in Bigram.words_dic)):
return (- 1)
index1 = Bigram.words_dic.index(word1)
index2 = Bigram.words_dic.index(word2)
return Bigram._calc_prob_mod_kn(index1, index2) | @staticmethod
def calc_prob(word1, word2):
'\n calculate the bigram probability of word2/word1\n :return: probability in [0,1]\n '
if ((word1 not in Bigram.words_dic) or (word2 not in Bigram.words_dic)):
return (- 1)
index1 = Bigram.words_dic.index(word1)
index2 = Bigram.words_dic.index(word2)
return Bigram._calc_prob_mod_kn(index1, index2)<|docstring|>calculate the bigram probability of word2/word1
:return: probability in [0,1]<|endoftext|> |
5873c42e4f0e297a1da7a7b51c369157741f825abdfa730732c4fc031371c02d | @staticmethod
def _calc_prob_add_one(index1, index2):
'\n add one smoothing\n :return: probability in [0,1]\n '
return (((Bigram.bi_cnt[index1][index2] + 1) * 1.0) / Bigram.uni_cnt[index1]) | add one smoothing
:return: probability in [0,1] | Source/bigram.py | _calc_prob_add_one | laddie132/RITE_zh-CN | 5 | python | @staticmethod
def _calc_prob_add_one(index1, index2):
'\n add one smoothing\n :return: probability in [0,1]\n '
return (((Bigram.bi_cnt[index1][index2] + 1) * 1.0) / Bigram.uni_cnt[index1]) | @staticmethod
def _calc_prob_add_one(index1, index2):
'\n add one smoothing\n :return: probability in [0,1]\n '
return (((Bigram.bi_cnt[index1][index2] + 1) * 1.0) / Bigram.uni_cnt[index1])<|docstring|>add one smoothing
:return: probability in [0,1]<|endoftext|> |
52517282cdab40748eef28b463ce61ac893a6b9dee3c10c20ac7d233c2f6d673 | @staticmethod
def _calc_prob_mod_kn(index1, index2):
'\n Modified Kneser-Ney Smoothing, high speed but need the pre-training model\n :return: probability in [0,1]\n '
def D(x):
if (x >= 3):
return Bigram.kn_d_cg98[2]
elif (x == 0):
return 0
return Bigram.kn_d_cg98[(x - 1)]
prob_high = ((max((Bigram.bi_cnt[index1][index2] - D(Bigram.bi_cnt[index1][index2])), 0) * 1.0) / Bigram.uni_cnt[index1])
lamb = (((((Bigram.kn_d_cg98[0] * Bigram.kn_diff_bi_row[0][index1]) + (Bigram.kn_d_cg98[1] * Bigram.kn_diff_bi_row[1][index1])) + (Bigram.kn_d_cg98[2] * Bigram.kn_diff_bi_row[2][index1])) * 1.0) / Bigram.uni_cnt[index1])
prop_low = ((Bigram.kn_diff_bi_col[0][index2] * 1.0) / Bigram.kn_diff_bi)
return (prob_high + (lamb * prop_low)) | Modified Kneser-Ney Smoothing, high speed but need the pre-training model
:return: probability in [0,1] | Source/bigram.py | _calc_prob_mod_kn | laddie132/RITE_zh-CN | 5 | python | @staticmethod
def _calc_prob_mod_kn(index1, index2):
'\n Modified Kneser-Ney Smoothing, high speed but need the pre-training model\n :return: probability in [0,1]\n '
def D(x):
if (x >= 3):
return Bigram.kn_d_cg98[2]
elif (x == 0):
return 0
return Bigram.kn_d_cg98[(x - 1)]
prob_high = ((max((Bigram.bi_cnt[index1][index2] - D(Bigram.bi_cnt[index1][index2])), 0) * 1.0) / Bigram.uni_cnt[index1])
lamb = (((((Bigram.kn_d_cg98[0] * Bigram.kn_diff_bi_row[0][index1]) + (Bigram.kn_d_cg98[1] * Bigram.kn_diff_bi_row[1][index1])) + (Bigram.kn_d_cg98[2] * Bigram.kn_diff_bi_row[2][index1])) * 1.0) / Bigram.uni_cnt[index1])
prop_low = ((Bigram.kn_diff_bi_col[0][index2] * 1.0) / Bigram.kn_diff_bi)
return (prob_high + (lamb * prop_low)) | @staticmethod
def _calc_prob_mod_kn(index1, index2):
'\n Modified Kneser-Ney Smoothing, high speed but need the pre-training model\n :return: probability in [0,1]\n '
def D(x):
if (x >= 3):
return Bigram.kn_d_cg98[2]
elif (x == 0):
return 0
return Bigram.kn_d_cg98[(x - 1)]
prob_high = ((max((Bigram.bi_cnt[index1][index2] - D(Bigram.bi_cnt[index1][index2])), 0) * 1.0) / Bigram.uni_cnt[index1])
lamb = (((((Bigram.kn_d_cg98[0] * Bigram.kn_diff_bi_row[0][index1]) + (Bigram.kn_d_cg98[1] * Bigram.kn_diff_bi_row[1][index1])) + (Bigram.kn_d_cg98[2] * Bigram.kn_diff_bi_row[2][index1])) * 1.0) / Bigram.uni_cnt[index1])
prop_low = ((Bigram.kn_diff_bi_col[0][index2] * 1.0) / Bigram.kn_diff_bi)
return (prob_high + (lamb * prop_low))<|docstring|>Modified Kneser-Ney Smoothing, high speed but need the pre-training model
:return: probability in [0,1]<|endoftext|> |
a4e56ffabf2fd525f48787d4201a48d7e3eb9765611787dc6d57ae276b14182a | @staticmethod
def _calc_prob_mod_kn_slow(index1, index2):
'\n Modified Kneser-Ney Smoothing, slower speed but more general\n :return: probability in [0,1]\n '
def D(x):
if (x >= 3):
return Bigram.kn_d_cg98[2]
elif (x == 0):
return 0
return Bigram.kn_d_cg98[(x - 1)]
prob_high = ((max((Bigram.bi_cnt[index1][index2] - D(Bigram.bi_cnt[index1][index2])), 0) * 1.0) / Bigram.uni_cnt[index1])
n = [0, 0, 0]
for i in range(len(Bigram.words_dic)):
if (Bigram.bi_cnt[index1][i] == 1):
n[0] += 1
elif (Bigram.bi_cnt[index1][i] == 2):
n[1] += 1
elif (Bigram.bi_cnt[index1][i] >= 3):
n[2] += 1
lamb = (((((Bigram.kn_d_cg98[0] * n[0]) + (Bigram.kn_d_cg98[1] * n[1])) + (Bigram.kn_d_cg98[2] * n[2])) * 1.0) / Bigram.uni_cnt[index1])
temp_cnt = 0
for i in range(len(Bigram.words_dic)):
if (Bigram.bi_cnt[i][index2] > 0):
temp_cnt += 1
prop_low = ((temp_cnt * 1.0) / Bigram.kn_diff_bi)
return (prob_high + (lamb * prop_low)) | Modified Kneser-Ney Smoothing, slower speed but more general
:return: probability in [0,1] | Source/bigram.py | _calc_prob_mod_kn_slow | laddie132/RITE_zh-CN | 5 | python | @staticmethod
def _calc_prob_mod_kn_slow(index1, index2):
'\n Modified Kneser-Ney Smoothing, slower speed but more general\n :return: probability in [0,1]\n '
def D(x):
if (x >= 3):
return Bigram.kn_d_cg98[2]
elif (x == 0):
return 0
return Bigram.kn_d_cg98[(x - 1)]
prob_high = ((max((Bigram.bi_cnt[index1][index2] - D(Bigram.bi_cnt[index1][index2])), 0) * 1.0) / Bigram.uni_cnt[index1])
n = [0, 0, 0]
for i in range(len(Bigram.words_dic)):
if (Bigram.bi_cnt[index1][i] == 1):
n[0] += 1
elif (Bigram.bi_cnt[index1][i] == 2):
n[1] += 1
elif (Bigram.bi_cnt[index1][i] >= 3):
n[2] += 1
lamb = (((((Bigram.kn_d_cg98[0] * n[0]) + (Bigram.kn_d_cg98[1] * n[1])) + (Bigram.kn_d_cg98[2] * n[2])) * 1.0) / Bigram.uni_cnt[index1])
temp_cnt = 0
for i in range(len(Bigram.words_dic)):
if (Bigram.bi_cnt[i][index2] > 0):
temp_cnt += 1
prop_low = ((temp_cnt * 1.0) / Bigram.kn_diff_bi)
return (prob_high + (lamb * prop_low)) | @staticmethod
def _calc_prob_mod_kn_slow(index1, index2):
'\n Modified Kneser-Ney Smoothing, slower speed but more general\n :return: probability in [0,1]\n '
def D(x):
if (x >= 3):
return Bigram.kn_d_cg98[2]
elif (x == 0):
return 0
return Bigram.kn_d_cg98[(x - 1)]
prob_high = ((max((Bigram.bi_cnt[index1][index2] - D(Bigram.bi_cnt[index1][index2])), 0) * 1.0) / Bigram.uni_cnt[index1])
n = [0, 0, 0]
for i in range(len(Bigram.words_dic)):
if (Bigram.bi_cnt[index1][i] == 1):
n[0] += 1
elif (Bigram.bi_cnt[index1][i] == 2):
n[1] += 1
elif (Bigram.bi_cnt[index1][i] >= 3):
n[2] += 1
lamb = (((((Bigram.kn_d_cg98[0] * n[0]) + (Bigram.kn_d_cg98[1] * n[1])) + (Bigram.kn_d_cg98[2] * n[2])) * 1.0) / Bigram.uni_cnt[index1])
temp_cnt = 0
for i in range(len(Bigram.words_dic)):
if (Bigram.bi_cnt[i][index2] > 0):
temp_cnt += 1
prop_low = ((temp_cnt * 1.0) / Bigram.kn_diff_bi)
return (prob_high + (lamb * prop_low))<|docstring|>Modified Kneser-Ney Smoothing, slower speed but more general
:return: probability in [0,1]<|endoftext|> |
ad426fc223fc0bb420ebc299810173692d8f78095d79dc3cc27270fc91d22e9b | def __init__(self, ai_settings, screen, ship):
'Create a Bullet at position of ship'
super(Bullet, self).__init__()
self.screen = screen
self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height)
self.rect.centerx = ship.rect.centerx
self.rect.top = ship.rect.top
self.y = float(self.rect.y)
self.color = ai_settings.bullet_color
self.speed_factor = ai_settings.bullet_speed_factor | Create a Bullet at position of ship | Alien/bullet.py | __init__ | Jerry12228/Source | 0 | python | def __init__(self, ai_settings, screen, ship):
super(Bullet, self).__init__()
self.screen = screen
self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height)
self.rect.centerx = ship.rect.centerx
self.rect.top = ship.rect.top
self.y = float(self.rect.y)
self.color = ai_settings.bullet_color
self.speed_factor = ai_settings.bullet_speed_factor | def __init__(self, ai_settings, screen, ship):
super(Bullet, self).__init__()
self.screen = screen
self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height)
self.rect.centerx = ship.rect.centerx
self.rect.top = ship.rect.top
self.y = float(self.rect.y)
self.color = ai_settings.bullet_color
self.speed_factor = ai_settings.bullet_speed_factor<|docstring|>Create a Bullet at position of ship<|endoftext|> |
0eb6d8a45e505bb0210ec24ae5290c3626d703d3da3f0c6ab7eeb085a74d0df0 | def update(self):
'Move bullet up'
self.y -= self.speed_factor
self.rect.y = self.y | Move bullet up | Alien/bullet.py | update | Jerry12228/Source | 0 | python | def update(self):
self.y -= self.speed_factor
self.rect.y = self.y | def update(self):
self.y -= self.speed_factor
self.rect.y = self.y<|docstring|>Move bullet up<|endoftext|> |
98de56bfb7a5c94f6d6205d3e568a1efae49b93fe3bab8bd0ac0a257860491b6 | def draw_bullet(self):
'Draw a bullet on the screen'
pygame.draw.rect(self.screen, self.color, self.rect) | Draw a bullet on the screen | Alien/bullet.py | draw_bullet | Jerry12228/Source | 0 | python | def draw_bullet(self):
pygame.draw.rect(self.screen, self.color, self.rect) | def draw_bullet(self):
pygame.draw.rect(self.screen, self.color, self.rect)<|docstring|>Draw a bullet on the screen<|endoftext|> |
5847fa9cee363998e71dbe2067849d6c7884e34f3eae2f1bb46998ae5be43ba2 | def store_trajectory(self, transistions):
'\n Stores transitions\n :param transistions: a list of dictionaries encoding transitions. Keys can be anything\n '
assert (transistions[(- 1)]['done'] > 0), 'Last transition must be end of trajectory'
for transition in transistions:
self.store_transition(transition) | Stores transitions
:param transistions: a list of dictionaries encoding transitions. Keys can be anything | rsa/utils/replay_buffer.py | store_trajectory | zaynahjaved/AWAC | 0 | python | def store_trajectory(self, transistions):
'\n Stores transitions\n :param transistions: a list of dictionaries encoding transitions. Keys can be anything\n '
assert (transistions[(- 1)]['done'] > 0), 'Last transition must be end of trajectory'
for transition in transistions:
self.store_transition(transition) | def store_trajectory(self, transistions):
'\n Stores transitions\n :param transistions: a list of dictionaries encoding transitions. Keys can be anything\n '
assert (transistions[(- 1)]['done'] > 0), 'Last transition must be end of trajectory'
for transition in transistions:
self.store_transition(transition)<|docstring|>Stores transitions
:param transistions: a list of dictionaries encoding transitions. Keys can be anything<|endoftext|> |
12b898e40c51737cb070be3cd04d63f335e30455019ad0278c50d5a27331a7a2 | def sample_positive(self, batch_size, key, ensemble=0):
'\n Samples only from the entries where the array corresponding to key is nonzero\n I added this method so I could sample only from data entries in the safe set\n '
assert (len(self.data[key].shape) == 1), 'cannot sample positive from array with >1d values'
nonzeros = self.data[key].nonzero()[0]
if (ensemble == 0):
indices = np.random.randint(len(nonzeros), size=batch_size)
elif (ensemble > 0):
indices = np.random.randint(len(nonzeros), size=(ensemble, batch_size))
else:
raise ValueError('ensemble size cannot be negative')
return self._im_to_float({key: self.data[key][nonzeros[indices]] for key in self.data}) | Samples only from the entries where the array corresponding to key is nonzero
I added this method so I could sample only from data entries in the safe set | rsa/utils/replay_buffer.py | sample_positive | zaynahjaved/AWAC | 0 | python | def sample_positive(self, batch_size, key, ensemble=0):
'\n Samples only from the entries where the array corresponding to key is nonzero\n I added this method so I could sample only from data entries in the safe set\n '
assert (len(self.data[key].shape) == 1), 'cannot sample positive from array with >1d values'
nonzeros = self.data[key].nonzero()[0]
if (ensemble == 0):
indices = np.random.randint(len(nonzeros), size=batch_size)
elif (ensemble > 0):
indices = np.random.randint(len(nonzeros), size=(ensemble, batch_size))
else:
raise ValueError('ensemble size cannot be negative')
return self._im_to_float({key: self.data[key][nonzeros[indices]] for key in self.data}) | def sample_positive(self, batch_size, key, ensemble=0):
'\n Samples only from the entries where the array corresponding to key is nonzero\n I added this method so I could sample only from data entries in the safe set\n '
assert (len(self.data[key].shape) == 1), 'cannot sample positive from array with >1d values'
nonzeros = self.data[key].nonzero()[0]
if (ensemble == 0):
indices = np.random.randint(len(nonzeros), size=batch_size)
elif (ensemble > 0):
indices = np.random.randint(len(nonzeros), size=(ensemble, batch_size))
else:
raise ValueError('ensemble size cannot be negative')
return self._im_to_float({key: self.data[key][nonzeros[indices]] for key in self.data})<|docstring|>Samples only from the entries where the array corresponding to key is nonzero
I added this method so I could sample only from data entries in the safe set<|endoftext|> |
df6e19c5cdf0da265559b75a4cfeea4c20c68489bd982972ecd837524ef044b5 | def sample_negative(self, batch_size, key, ensemble=0):
'\n Samples only from the entries where the array corresponding to key is zero\n I added this method so I could sample only from data entries in the safe set\n '
assert (len(self.data[key].shape) == 1), 'cannot sample positive from array with >1d values'
zeros = (1 - self.data[key]).nonzero()[0]
if (ensemble == 0):
indices = np.random.randint(len(zeros), size=batch_size)
elif (ensemble > 0):
indices = np.random.randint(len(zeros), size=(ensemble, batch_size))
else:
raise ValueError('ensemble size cannot be negative')
return self._im_to_float({key: self.data[key][zeros[indices]] for key in self.data}) | Samples only from the entries where the array corresponding to key is zero
I added this method so I could sample only from data entries in the safe set | rsa/utils/replay_buffer.py | sample_negative | zaynahjaved/AWAC | 0 | python | def sample_negative(self, batch_size, key, ensemble=0):
'\n Samples only from the entries where the array corresponding to key is zero\n I added this method so I could sample only from data entries in the safe set\n '
assert (len(self.data[key].shape) == 1), 'cannot sample positive from array with >1d values'
zeros = (1 - self.data[key]).nonzero()[0]
if (ensemble == 0):
indices = np.random.randint(len(zeros), size=batch_size)
elif (ensemble > 0):
indices = np.random.randint(len(zeros), size=(ensemble, batch_size))
else:
raise ValueError('ensemble size cannot be negative')
return self._im_to_float({key: self.data[key][zeros[indices]] for key in self.data}) | def sample_negative(self, batch_size, key, ensemble=0):
'\n Samples only from the entries where the array corresponding to key is zero\n I added this method so I could sample only from data entries in the safe set\n '
assert (len(self.data[key].shape) == 1), 'cannot sample positive from array with >1d values'
zeros = (1 - self.data[key]).nonzero()[0]
if (ensemble == 0):
indices = np.random.randint(len(zeros), size=batch_size)
elif (ensemble > 0):
indices = np.random.randint(len(zeros), size=(ensemble, batch_size))
else:
raise ValueError('ensemble size cannot be negative')
return self._im_to_float({key: self.data[key][zeros[indices]] for key in self.data})<|docstring|>Samples only from the entries where the array corresponding to key is zero
I added this method so I could sample only from data entries in the safe set<|endoftext|> |
3e4b59f3ae1c9f7e2e758e39179eb6132474617b006b8611e5d81f6ff0863638 | def set_loggable_level_for_tag(tag, level='VERBOSE'):
'\n Set the minimum loggable level for a tag.\n\n :param tag: TAG name\n :param level: Log level.\n '
level = level.upper()
if (not is_valid_log_level(level)):
raise ValueError(('Unknown log level %s' % level))
return adb.set_property(_LOG_TAG_PROPERTY.format(tag=tag), level) | Set the minimum loggable level for a tag.
:param tag: TAG name
:param level: Log level. | androtoolbox/log.py | set_loggable_level_for_tag | gregthedoe/androtoolbox | 0 | python | def set_loggable_level_for_tag(tag, level='VERBOSE'):
'\n Set the minimum loggable level for a tag.\n\n :param tag: TAG name\n :param level: Log level.\n '
level = level.upper()
if (not is_valid_log_level(level)):
raise ValueError(('Unknown log level %s' % level))
return adb.set_property(_LOG_TAG_PROPERTY.format(tag=tag), level) | def set_loggable_level_for_tag(tag, level='VERBOSE'):
'\n Set the minimum loggable level for a tag.\n\n :param tag: TAG name\n :param level: Log level.\n '
level = level.upper()
if (not is_valid_log_level(level)):
raise ValueError(('Unknown log level %s' % level))
return adb.set_property(_LOG_TAG_PROPERTY.format(tag=tag), level)<|docstring|>Set the minimum loggable level for a tag.
:param tag: TAG name
:param level: Log level.<|endoftext|> |
5b95137f0761ccb59cf6ed66c52202b1ab742ff8e236bbda2f0e6f6839d5d4a0 | def set_loggable_level_for_tags(tags, default_level='VERBOSE'):
'\n Set the minimum log level for a set of tags.\n\n :param tags: A mapping of tags and their minimum loggable level.\n :param default_level: If `tags` is a list use this level as the default.\n '
try:
for (tag, level) in tags.iteritems():
set_loggable_level_for_tag(tag, level)
except AttributeError:
for tag in tags:
set_loggable_level_for_tag(tag, default_level) | Set the minimum log level for a set of tags.
:param tags: A mapping of tags and their minimum loggable level.
:param default_level: If `tags` is a list use this level as the default. | androtoolbox/log.py | set_loggable_level_for_tags | gregthedoe/androtoolbox | 0 | python | def set_loggable_level_for_tags(tags, default_level='VERBOSE'):
'\n Set the minimum log level for a set of tags.\n\n :param tags: A mapping of tags and their minimum loggable level.\n :param default_level: If `tags` is a list use this level as the default.\n '
try:
for (tag, level) in tags.iteritems():
set_loggable_level_for_tag(tag, level)
except AttributeError:
for tag in tags:
set_loggable_level_for_tag(tag, default_level) | def set_loggable_level_for_tags(tags, default_level='VERBOSE'):
'\n Set the minimum log level for a set of tags.\n\n :param tags: A mapping of tags and their minimum loggable level.\n :param default_level: If `tags` is a list use this level as the default.\n '
try:
for (tag, level) in tags.iteritems():
set_loggable_level_for_tag(tag, level)
except AttributeError:
for tag in tags:
set_loggable_level_for_tag(tag, default_level)<|docstring|>Set the minimum log level for a set of tags.
:param tags: A mapping of tags and their minimum loggable level.
:param default_level: If `tags` is a list use this level as the default.<|endoftext|> |
59dfa9df704711e411b21aa3c47dbcbc223e942c4906e5da7a0e0915b1dabfcb | def residual_block(x, training, dilation_rate, nb_filters, kernel_size, dropout_rate=0):
'Defines the residual block for the WaveNet TCN\n Args:\n x: The previous layer in the model\n training: boolean indicating whether the layer should behave in training mode or in inference mode\n dilation_rate: The dilation power of 2 we are using for this residual block\n nb_filters: The number of convolutional filters to use in this block\n kernel_size: The size of the convolutional kernel\n dropout_rate: Float between 0 and 1. Fraction of the input units to drop.\n Returns:\n A tuple where the first element is the residual model layer, and the second\n is the skip connection.\n '
prev_x = x
for k in range(2):
x = Conv1D(filters=nb_filters, kernel_size=kernel_size, dilation_rate=dilation_rate, kernel_initializer='he_normal', padding='causal')(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = SpatialDropout1D(rate=dropout_rate)(inputs=x, training=training)
prev_x = Conv1D(nb_filters, 1, padding='same')(prev_x)
res_x = keras.layers.add([prev_x, x])
res_x = Activation('relu')(res_x)
return (res_x, x) | Defines the residual block for the WaveNet TCN
Args:
x: The previous layer in the model
training: boolean indicating whether the layer should behave in training mode or in inference mode
dilation_rate: The dilation power of 2 we are using for this residual block
nb_filters: The number of convolutional filters to use in this block
kernel_size: The size of the convolutional kernel
dropout_rate: Float between 0 and 1. Fraction of the input units to drop.
Returns:
A tuple where the first element is the residual model layer, and the second
is the skip connection. | src/tcn.py | residual_block | zhaipro/ActionRecognition | 5 | python | def residual_block(x, training, dilation_rate, nb_filters, kernel_size, dropout_rate=0):
'Defines the residual block for the WaveNet TCN\n Args:\n x: The previous layer in the model\n training: boolean indicating whether the layer should behave in training mode or in inference mode\n dilation_rate: The dilation power of 2 we are using for this residual block\n nb_filters: The number of convolutional filters to use in this block\n kernel_size: The size of the convolutional kernel\n dropout_rate: Float between 0 and 1. Fraction of the input units to drop.\n Returns:\n A tuple where the first element is the residual model layer, and the second\n is the skip connection.\n '
prev_x = x
for k in range(2):
x = Conv1D(filters=nb_filters, kernel_size=kernel_size, dilation_rate=dilation_rate, kernel_initializer='he_normal', padding='causal')(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = SpatialDropout1D(rate=dropout_rate)(inputs=x, training=training)
prev_x = Conv1D(nb_filters, 1, padding='same')(prev_x)
res_x = keras.layers.add([prev_x, x])
res_x = Activation('relu')(res_x)
return (res_x, x) | def residual_block(x, training, dilation_rate, nb_filters, kernel_size, dropout_rate=0):
'Defines the residual block for the WaveNet TCN\n Args:\n x: The previous layer in the model\n training: boolean indicating whether the layer should behave in training mode or in inference mode\n dilation_rate: The dilation power of 2 we are using for this residual block\n nb_filters: The number of convolutional filters to use in this block\n kernel_size: The size of the convolutional kernel\n dropout_rate: Float between 0 and 1. Fraction of the input units to drop.\n Returns:\n A tuple where the first element is the residual model layer, and the second\n is the skip connection.\n '
prev_x = x
for k in range(2):
x = Conv1D(filters=nb_filters, kernel_size=kernel_size, dilation_rate=dilation_rate, kernel_initializer='he_normal', padding='causal')(x)
x = BatchNormalization()(x)
x = Activation('relu')(x)
x = SpatialDropout1D(rate=dropout_rate)(inputs=x, training=training)
prev_x = Conv1D(nb_filters, 1, padding='same')(prev_x)
res_x = keras.layers.add([prev_x, x])
res_x = Activation('relu')(res_x)
return (res_x, x)<|docstring|>Defines the residual block for the WaveNet TCN
Args:
x: The previous layer in the model
training: boolean indicating whether the layer should behave in training mode or in inference mode
dilation_rate: The dilation power of 2 we are using for this residual block
nb_filters: The number of convolutional filters to use in this block
kernel_size: The size of the convolutional kernel
dropout_rate: Float between 0 and 1. Fraction of the input units to drop.
Returns:
A tuple where the first element is the residual model layer, and the second
is the skip connection.<|endoftext|> |
a130dad7226ba7fbb39d3930d55a3eff030901ceeb379969c121a6f09652fe49 | def json(self):
'\n Return SubjectDto in JSON\n '
return {'id': self.id, 'name': self.name} | Return SubjectDto in JSON | web-app/src/api/v1/dtos/SubjectDto.py | json | philipp-mos/iubh-quiz-app | 0 | python | def json(self):
'\n \n '
return {'id': self.id, 'name': self.name} | def json(self):
'\n \n '
return {'id': self.id, 'name': self.name}<|docstring|>Return SubjectDto in JSON<|endoftext|> |
46e508c0a1fff9476f5a82301d767d4932854d5e8225aea64d22f05fbae03c42 | def load_data(self, annotation_json, images_dir):
' Load the coco-like dataset from json\n Args:\n annotation_json: The path to the coco annotations json file\n images_dir: The directory holding the images referred to by the json file\n '
json_file = open(annotation_json)
coco_json = json.load(json_file)
json_file.close()
source_name = 'coco_like'
for category in coco_json['categories']:
class_id = category['id']
class_name = category['name']
if (class_id < 1):
print('Error: Class id for "{}" cannot be less than one. (0 is reserved for the background)'.format(class_name))
return
self.add_class(source_name, class_id, class_name)
annotations = {}
for annotation in coco_json['annotations']:
image_id = annotation['image_id']
if (image_id not in annotations):
annotations[image_id] = []
annotations[image_id].append(annotation)
seen_images = {}
for image in coco_json['images']:
image_id = image['id']
if (image_id in seen_images):
print('Warning: Skipping duplicate image id: {}'.format(image))
else:
seen_images[image_id] = image
try:
image_file_name = image['file_name']
image_width = image['width']
image_height = image['height']
except KeyError as key:
print('Warning: Skipping image (id: {}) with missing key: {}'.format(image_id, key))
image_path = os.path.abspath(os.path.join(images_dir, image_file_name))
image_annotations = annotations[image_id]
self.add_image(source=source_name, image_id=image_id, path=image_path, width=image_width, height=image_height, annotations=image_annotations) | Load the coco-like dataset from json
Args:
annotation_json: The path to the coco annotations json file
images_dir: The directory holding the images referred to by the json file | datasets/hw4.py | load_data | ruoyuryc/CS_IOC5008_HW4 | 0 | python | def load_data(self, annotation_json, images_dir):
' Load the coco-like dataset from json\n Args:\n annotation_json: The path to the coco annotations json file\n images_dir: The directory holding the images referred to by the json file\n '
json_file = open(annotation_json)
coco_json = json.load(json_file)
json_file.close()
source_name = 'coco_like'
for category in coco_json['categories']:
class_id = category['id']
class_name = category['name']
if (class_id < 1):
print('Error: Class id for "{}" cannot be less than one. (0 is reserved for the background)'.format(class_name))
return
self.add_class(source_name, class_id, class_name)
annotations = {}
for annotation in coco_json['annotations']:
image_id = annotation['image_id']
if (image_id not in annotations):
annotations[image_id] = []
annotations[image_id].append(annotation)
seen_images = {}
for image in coco_json['images']:
image_id = image['id']
if (image_id in seen_images):
print('Warning: Skipping duplicate image id: {}'.format(image))
else:
seen_images[image_id] = image
try:
image_file_name = image['file_name']
image_width = image['width']
image_height = image['height']
except KeyError as key:
print('Warning: Skipping image (id: {}) with missing key: {}'.format(image_id, key))
image_path = os.path.abspath(os.path.join(images_dir, image_file_name))
image_annotations = annotations[image_id]
self.add_image(source=source_name, image_id=image_id, path=image_path, width=image_width, height=image_height, annotations=image_annotations) | def load_data(self, annotation_json, images_dir):
' Load the coco-like dataset from json\n Args:\n annotation_json: The path to the coco annotations json file\n images_dir: The directory holding the images referred to by the json file\n '
json_file = open(annotation_json)
coco_json = json.load(json_file)
json_file.close()
source_name = 'coco_like'
for category in coco_json['categories']:
class_id = category['id']
class_name = category['name']
if (class_id < 1):
print('Error: Class id for "{}" cannot be less than one. (0 is reserved for the background)'.format(class_name))
return
self.add_class(source_name, class_id, class_name)
annotations = {}
for annotation in coco_json['annotations']:
image_id = annotation['image_id']
if (image_id not in annotations):
annotations[image_id] = []
annotations[image_id].append(annotation)
seen_images = {}
for image in coco_json['images']:
image_id = image['id']
if (image_id in seen_images):
print('Warning: Skipping duplicate image id: {}'.format(image))
else:
seen_images[image_id] = image
try:
image_file_name = image['file_name']
image_width = image['width']
image_height = image['height']
except KeyError as key:
print('Warning: Skipping image (id: {}) with missing key: {}'.format(image_id, key))
image_path = os.path.abspath(os.path.join(images_dir, image_file_name))
image_annotations = annotations[image_id]
self.add_image(source=source_name, image_id=image_id, path=image_path, width=image_width, height=image_height, annotations=image_annotations)<|docstring|>Load the coco-like dataset from json
Args:
annotation_json: The path to the coco annotations json file
images_dir: The directory holding the images referred to by the json file<|endoftext|> |
c371556f3ac3fe9225ea559dfa83745b77cff6090df9b9367d322ece0f6ffa20 | def load_mask(self, image_id):
' Load instance masks for the given image.\n MaskRCNN expects masks in the form of a bitmap [height, width, instances].\n Args:\n image_id: The id of the image to load masks for\n Returns:\n masks: A bool array of shape [height, width, instance count] with\n one mask per instance.\n class_ids: a 1D array of class IDs of the instance masks.\n '
image_info = self.image_info[image_id]
annotations = image_info['annotations']
instance_masks = []
class_ids = []
for annotation in annotations:
class_id = annotation['category_id']
mask = Image.new('1', (image_info['width'], image_info['height']))
mask_draw = ImageDraw.ImageDraw(mask, '1')
for segmentation in annotation['segmentation']:
mask_draw.polygon(segmentation, fill=1)
bool_array = (np.array(mask) > 0)
instance_masks.append(bool_array)
class_ids.append(class_id)
mask = np.dstack(instance_masks)
class_ids = np.array(class_ids, dtype=np.int32)
return (mask, class_ids) | Load instance masks for the given image.
MaskRCNN expects masks in the form of a bitmap [height, width, instances].
Args:
image_id: The id of the image to load masks for
Returns:
masks: A bool array of shape [height, width, instance count] with
one mask per instance.
class_ids: a 1D array of class IDs of the instance masks. | datasets/hw4.py | load_mask | ruoyuryc/CS_IOC5008_HW4 | 0 | python | def load_mask(self, image_id):
' Load instance masks for the given image.\n MaskRCNN expects masks in the form of a bitmap [height, width, instances].\n Args:\n image_id: The id of the image to load masks for\n Returns:\n masks: A bool array of shape [height, width, instance count] with\n one mask per instance.\n class_ids: a 1D array of class IDs of the instance masks.\n '
image_info = self.image_info[image_id]
annotations = image_info['annotations']
instance_masks = []
class_ids = []
for annotation in annotations:
class_id = annotation['category_id']
mask = Image.new('1', (image_info['width'], image_info['height']))
mask_draw = ImageDraw.ImageDraw(mask, '1')
for segmentation in annotation['segmentation']:
mask_draw.polygon(segmentation, fill=1)
bool_array = (np.array(mask) > 0)
instance_masks.append(bool_array)
class_ids.append(class_id)
mask = np.dstack(instance_masks)
class_ids = np.array(class_ids, dtype=np.int32)
return (mask, class_ids) | def load_mask(self, image_id):
' Load instance masks for the given image.\n MaskRCNN expects masks in the form of a bitmap [height, width, instances].\n Args:\n image_id: The id of the image to load masks for\n Returns:\n masks: A bool array of shape [height, width, instance count] with\n one mask per instance.\n class_ids: a 1D array of class IDs of the instance masks.\n '
image_info = self.image_info[image_id]
annotations = image_info['annotations']
instance_masks = []
class_ids = []
for annotation in annotations:
class_id = annotation['category_id']
mask = Image.new('1', (image_info['width'], image_info['height']))
mask_draw = ImageDraw.ImageDraw(mask, '1')
for segmentation in annotation['segmentation']:
mask_draw.polygon(segmentation, fill=1)
bool_array = (np.array(mask) > 0)
instance_masks.append(bool_array)
class_ids.append(class_id)
mask = np.dstack(instance_masks)
class_ids = np.array(class_ids, dtype=np.int32)
return (mask, class_ids)<|docstring|>Load instance masks for the given image.
MaskRCNN expects masks in the form of a bitmap [height, width, instances].
Args:
image_id: The id of the image to load masks for
Returns:
masks: A bool array of shape [height, width, instance count] with
one mask per instance.
class_ids: a 1D array of class IDs of the instance masks.<|endoftext|> |
100fa8afdb38211203981fb6243b52026f8d0ad940cd4b3e8605abecd1f27f7b | def load_data(self, annotation_json, images_dir):
' Load the coco-like dataset from json\n Args:\n annotation_json: The path to the coco annotations json file\n images_dir: The directory holding the images referred to by the json file\n '
json_file = open(annotation_json)
coco_json = json.load(json_file)
json_file.close()
source_name = 'coco_like'
for category in coco_json['categories']:
class_id = category['id']
class_name = category['name']
if (class_id < 1):
print('Error: Class id for "{}" cannot be less than one. (0 is reserved for the background)'.format(class_name))
return
self.add_class(source_name, class_id, class_name)
seen_images = {}
for image in coco_json['images']:
image_id = image['id']
if (image_id in seen_images):
print('Warning: Skipping duplicate image id: {}'.format(image))
else:
seen_images[image_id] = image
try:
image_file_name = image['file_name']
image_width = image['width']
image_height = image['height']
except KeyError as key:
print('Warning: Skipping image (id: {}) with missing key: {}'.format(image_id, key))
image_path = os.path.abspath(os.path.join(images_dir, image_file_name))
self.add_image(source=source_name, image_id=image_id, path=image_path, width=image_width, height=image_height) | Load the coco-like dataset from json
Args:
annotation_json: The path to the coco annotations json file
images_dir: The directory holding the images referred to by the json file | datasets/hw4.py | load_data | ruoyuryc/CS_IOC5008_HW4 | 0 | python | def load_data(self, annotation_json, images_dir):
' Load the coco-like dataset from json\n Args:\n annotation_json: The path to the coco annotations json file\n images_dir: The directory holding the images referred to by the json file\n '
json_file = open(annotation_json)
coco_json = json.load(json_file)
json_file.close()
source_name = 'coco_like'
for category in coco_json['categories']:
class_id = category['id']
class_name = category['name']
if (class_id < 1):
print('Error: Class id for "{}" cannot be less than one. (0 is reserved for the background)'.format(class_name))
return
self.add_class(source_name, class_id, class_name)
seen_images = {}
for image in coco_json['images']:
image_id = image['id']
if (image_id in seen_images):
print('Warning: Skipping duplicate image id: {}'.format(image))
else:
seen_images[image_id] = image
try:
image_file_name = image['file_name']
image_width = image['width']
image_height = image['height']
except KeyError as key:
print('Warning: Skipping image (id: {}) with missing key: {}'.format(image_id, key))
image_path = os.path.abspath(os.path.join(images_dir, image_file_name))
self.add_image(source=source_name, image_id=image_id, path=image_path, width=image_width, height=image_height) | def load_data(self, annotation_json, images_dir):
' Load the coco-like dataset from json\n Args:\n annotation_json: The path to the coco annotations json file\n images_dir: The directory holding the images referred to by the json file\n '
json_file = open(annotation_json)
coco_json = json.load(json_file)
json_file.close()
source_name = 'coco_like'
for category in coco_json['categories']:
class_id = category['id']
class_name = category['name']
if (class_id < 1):
print('Error: Class id for "{}" cannot be less than one. (0 is reserved for the background)'.format(class_name))
return
self.add_class(source_name, class_id, class_name)
seen_images = {}
for image in coco_json['images']:
image_id = image['id']
if (image_id in seen_images):
print('Warning: Skipping duplicate image id: {}'.format(image))
else:
seen_images[image_id] = image
try:
image_file_name = image['file_name']
image_width = image['width']
image_height = image['height']
except KeyError as key:
print('Warning: Skipping image (id: {}) with missing key: {}'.format(image_id, key))
image_path = os.path.abspath(os.path.join(images_dir, image_file_name))
self.add_image(source=source_name, image_id=image_id, path=image_path, width=image_width, height=image_height)<|docstring|>Load the coco-like dataset from json
Args:
annotation_json: The path to the coco annotations json file
images_dir: The directory holding the images referred to by the json file<|endoftext|> |
c371556f3ac3fe9225ea559dfa83745b77cff6090df9b9367d322ece0f6ffa20 | def load_mask(self, image_id):
' Load instance masks for the given image.\n MaskRCNN expects masks in the form of a bitmap [height, width, instances].\n Args:\n image_id: The id of the image to load masks for\n Returns:\n masks: A bool array of shape [height, width, instance count] with\n one mask per instance.\n class_ids: a 1D array of class IDs of the instance masks.\n '
image_info = self.image_info[image_id]
annotations = image_info['annotations']
instance_masks = []
class_ids = []
for annotation in annotations:
class_id = annotation['category_id']
mask = Image.new('1', (image_info['width'], image_info['height']))
mask_draw = ImageDraw.ImageDraw(mask, '1')
for segmentation in annotation['segmentation']:
mask_draw.polygon(segmentation, fill=1)
bool_array = (np.array(mask) > 0)
instance_masks.append(bool_array)
class_ids.append(class_id)
mask = np.dstack(instance_masks)
class_ids = np.array(class_ids, dtype=np.int32)
return (mask, class_ids) | Load instance masks for the given image.
MaskRCNN expects masks in the form of a bitmap [height, width, instances].
Args:
image_id: The id of the image to load masks for
Returns:
masks: A bool array of shape [height, width, instance count] with
one mask per instance.
class_ids: a 1D array of class IDs of the instance masks. | datasets/hw4.py | load_mask | ruoyuryc/CS_IOC5008_HW4 | 0 | python | def load_mask(self, image_id):
' Load instance masks for the given image.\n MaskRCNN expects masks in the form of a bitmap [height, width, instances].\n Args:\n image_id: The id of the image to load masks for\n Returns:\n masks: A bool array of shape [height, width, instance count] with\n one mask per instance.\n class_ids: a 1D array of class IDs of the instance masks.\n '
image_info = self.image_info[image_id]
annotations = image_info['annotations']
instance_masks = []
class_ids = []
for annotation in annotations:
class_id = annotation['category_id']
mask = Image.new('1', (image_info['width'], image_info['height']))
mask_draw = ImageDraw.ImageDraw(mask, '1')
for segmentation in annotation['segmentation']:
mask_draw.polygon(segmentation, fill=1)
bool_array = (np.array(mask) > 0)
instance_masks.append(bool_array)
class_ids.append(class_id)
mask = np.dstack(instance_masks)
class_ids = np.array(class_ids, dtype=np.int32)
return (mask, class_ids) | def load_mask(self, image_id):
' Load instance masks for the given image.\n MaskRCNN expects masks in the form of a bitmap [height, width, instances].\n Args:\n image_id: The id of the image to load masks for\n Returns:\n masks: A bool array of shape [height, width, instance count] with\n one mask per instance.\n class_ids: a 1D array of class IDs of the instance masks.\n '
image_info = self.image_info[image_id]
annotations = image_info['annotations']
instance_masks = []
class_ids = []
for annotation in annotations:
class_id = annotation['category_id']
mask = Image.new('1', (image_info['width'], image_info['height']))
mask_draw = ImageDraw.ImageDraw(mask, '1')
for segmentation in annotation['segmentation']:
mask_draw.polygon(segmentation, fill=1)
bool_array = (np.array(mask) > 0)
instance_masks.append(bool_array)
class_ids.append(class_id)
mask = np.dstack(instance_masks)
class_ids = np.array(class_ids, dtype=np.int32)
return (mask, class_ids)<|docstring|>Load instance masks for the given image.
MaskRCNN expects masks in the form of a bitmap [height, width, instances].
Args:
image_id: The id of the image to load masks for
Returns:
masks: A bool array of shape [height, width, instance count] with
one mask per instance.
class_ids: a 1D array of class IDs of the instance masks.<|endoftext|> |
664fd65ffe04b9318f11593b5b58cc598e0cf10616c316627c1d6dde5f192f53 | def unsqueeze(tensor, dim):
'\n Add a dimension of value 1 in the input tensor at the specified position\n\n Parameters\n ----------\n tensor : Tensor\n the input tensor\n dim : int\n dimension to expand\n\n Returns\n -------\n Tensor\n the unsqueezed input\n\n Raises\n ------\n AssertError\n if tensor does not belongs to Numpy or PyTorch\n '
if isnumpy(tensor):
return numpy.expand_dims(tensor, axis=dim)
if istorch(tensor):
return tensor.unsqueeze(dim)
assert False, 'Unknown data type' | Add a dimension of value 1 in the input tensor at the specified position
Parameters
----------
tensor : Tensor
the input tensor
dim : int
dimension to expand
Returns
-------
Tensor
the unsqueezed input
Raises
------
AssertError
if tensor does not belongs to Numpy or PyTorch | ACME/utility/unsqueeze.py | unsqueeze | mauriziokovacic/ACME | 3 | python | def unsqueeze(tensor, dim):
'\n Add a dimension of value 1 in the input tensor at the specified position\n\n Parameters\n ----------\n tensor : Tensor\n the input tensor\n dim : int\n dimension to expand\n\n Returns\n -------\n Tensor\n the unsqueezed input\n\n Raises\n ------\n AssertError\n if tensor does not belongs to Numpy or PyTorch\n '
if isnumpy(tensor):
return numpy.expand_dims(tensor, axis=dim)
if istorch(tensor):
return tensor.unsqueeze(dim)
assert False, 'Unknown data type' | def unsqueeze(tensor, dim):
'\n Add a dimension of value 1 in the input tensor at the specified position\n\n Parameters\n ----------\n tensor : Tensor\n the input tensor\n dim : int\n dimension to expand\n\n Returns\n -------\n Tensor\n the unsqueezed input\n\n Raises\n ------\n AssertError\n if tensor does not belongs to Numpy or PyTorch\n '
if isnumpy(tensor):
return numpy.expand_dims(tensor, axis=dim)
if istorch(tensor):
return tensor.unsqueeze(dim)
assert False, 'Unknown data type'<|docstring|>Add a dimension of value 1 in the input tensor at the specified position
Parameters
----------
tensor : Tensor
the input tensor
dim : int
dimension to expand
Returns
-------
Tensor
the unsqueezed input
Raises
------
AssertError
if tensor does not belongs to Numpy or PyTorch<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.