body stringlengths 26 98.2k | body_hash int64 -9,222,864,604,528,158,000 9,221,803,474B | docstring stringlengths 1 16.8k | path stringlengths 5 230 | name stringlengths 1 96 | repository_name stringlengths 7 89 | lang stringclasses 1
value | body_without_docstring stringlengths 20 98.2k |
|---|---|---|---|---|---|---|---|
def __init__(self, filenames):
'Create a `SequenceFileDataset`.\n\n `SequenceFileDataset` allows a user to read data from a hadoop sequence\n file. A sequence file consists of (key value) pairs sequentially. At\n the moment, `org.apache.hadoop.io.Text` is the only serialization type\n being supported, a... | -758,520,326,914,486,700 | Create a `SequenceFileDataset`.
`SequenceFileDataset` allows a user to read data from a hadoop sequence
file. A sequence file consists of (key value) pairs sequentially. At
the moment, `org.apache.hadoop.io.Text` is the only serialization type
being supported, and there is no compression support.
For example:
```pyt... | tensorflow_io/hadoop/python/ops/hadoop_dataset_ops.py | __init__ | HubBucket-Team/io | python | def __init__(self, filenames):
'Create a `SequenceFileDataset`.\n\n `SequenceFileDataset` allows a user to read data from a hadoop sequence\n file. A sequence file consists of (key value) pairs sequentially. At\n the moment, `org.apache.hadoop.io.Text` is the only serialization type\n being supported, a... |
def create_net(self, shape, scale, ir_version):
'\n ONNX net IR net\n\n Input->ImageScaler->Output => Input->ScaleShift(Power)\n\n '
import onnx
from onnx import helper
from onnx import TensorProto
input = helper.make_tensor_value_info('inp... | 1,688,503,208,243,325,000 | ONNX net IR net
Input->ImageScaler->Output => Input->ScaleShift(Power) | tests/layer_tests/onnx_tests/test_image_scaler.py | create_net | 3Demonica/openvino | python | def create_net(self, shape, scale, ir_version):
'\n ONNX net IR net\n\n Input->ImageScaler->Output => Input->ScaleShift(Power)\n\n '
import onnx
from onnx import helper
from onnx import TensorProto
input = helper.make_tensor_value_info('inp... |
def create_net_const(self, shape, scale, precision, ir_version):
'\n ONNX net IR net\n\n Input->Concat(+scaled const)->Output => Input->Concat(+const)\n\n '
import onnx
from onnx import helper
from onnx import TensorProto
concat_a... | 5,785,908,737,829,401,000 | ONNX net IR net
Input->Concat(+scaled const)->Output => Input->Concat(+const) | tests/layer_tests/onnx_tests/test_image_scaler.py | create_net_const | 3Demonica/openvino | python | def create_net_const(self, shape, scale, precision, ir_version):
'\n ONNX net IR net\n\n Input->Concat(+scaled const)->Output => Input->Concat(+const)\n\n '
import onnx
from onnx import helper
from onnx import TensorProto
concat_a... |
def start(self):
'Starts agent-environment interaction.'
self.callbacks.on_interaction_begin()
while self.should_continue():
self.callbacks.on_episode_begin(self.episode)
self.env.reset()
self.step = 0
while (not self.env.is_terminal()):
self.callbacks.on_step_beg... | -2,936,708,797,581,038,600 | Starts agent-environment interaction. | myelin/core/interactions.py | start | davidrobles/myelin | python | def start(self):
self.callbacks.on_interaction_begin()
while self.should_continue():
self.callbacks.on_episode_begin(self.episode)
self.env.reset()
self.step = 0
while (not self.env.is_terminal()):
self.callbacks.on_step_begin(self.step)
state = self.... |
def _find_boundaries_subpixel(label_img):
'See ``find_boundaries(..., mode=\'subpixel\')``.\n\n Notes\n -----\n This function puts in an empty row and column between each *actual*\n row and column of the image, for a corresponding shape of $2s - 1$\n for every image dimension of size $s$. These "inte... | -8,794,061,428,085,247,000 | See ``find_boundaries(..., mode='subpixel')``.
Notes
-----
This function puts in an empty row and column between each *actual*
row and column of the image, for a corresponding shape of $2s - 1$
for every image dimension of size $s$. These "interstitial" rows
and columns are filled as ``True`` if they separate two labe... | venv/lib/python3.8/site-packages/skimage/segmentation/boundaries.py | _find_boundaries_subpixel | IZ-ZI/-EECS-393-_Attendance-System | python | def _find_boundaries_subpixel(label_img):
'See ``find_boundaries(..., mode=\'subpixel\')``.\n\n Notes\n -----\n This function puts in an empty row and column between each *actual*\n row and column of the image, for a corresponding shape of $2s - 1$\n for every image dimension of size $s$. These "inte... |
def find_boundaries(label_img, connectivity=1, mode='thick', background=0):
"Return bool array where boundaries between labeled regions are True.\n\n Parameters\n ----------\n label_img : array of int or bool\n An array in which different regions are labeled with either different\n integers o... | 9,124,155,518,888,762,000 | Return bool array where boundaries between labeled regions are True.
Parameters
----------
label_img : array of int or bool
An array in which different regions are labeled with either different
integers or boolean values.
connectivity: int in {1, ..., `label_img.ndim`}, optional
A pixel is considered a bou... | venv/lib/python3.8/site-packages/skimage/segmentation/boundaries.py | find_boundaries | IZ-ZI/-EECS-393-_Attendance-System | python | def find_boundaries(label_img, connectivity=1, mode='thick', background=0):
"Return bool array where boundaries between labeled regions are True.\n\n Parameters\n ----------\n label_img : array of int or bool\n An array in which different regions are labeled with either different\n integers o... |
def mark_boundaries(image, label_img, color=(1, 1, 0), outline_color=None, mode='outer', background_label=0):
"Return image with boundaries between labeled regions highlighted.\n\n Parameters\n ----------\n image : (M, N[, 3]) array\n Grayscale or RGB image.\n label_img : (M, N) array of int\n ... | 7,373,605,340,623,127,000 | Return image with boundaries between labeled regions highlighted.
Parameters
----------
image : (M, N[, 3]) array
Grayscale or RGB image.
label_img : (M, N) array of int
Label array where regions are marked by different integer values.
color : length-3 sequence, optional
RGB color of boundaries in the outp... | venv/lib/python3.8/site-packages/skimage/segmentation/boundaries.py | mark_boundaries | IZ-ZI/-EECS-393-_Attendance-System | python | def mark_boundaries(image, label_img, color=(1, 1, 0), outline_color=None, mode='outer', background_label=0):
"Return image with boundaries between labeled regions highlighted.\n\n Parameters\n ----------\n image : (M, N[, 3]) array\n Grayscale or RGB image.\n label_img : (M, N) array of int\n ... |
def format_options(self, ctx, formatter) -> None:
'Writes all the options into the formatter if they exist.'
opts = []
for param in self.get_params(ctx):
rv = param.get_help_record(ctx)
if (rv is not None):
opts.append(rv)
if opts:
with formatter.section('Options'):
... | -7,876,094,872,403,372,000 | Writes all the options into the formatter if they exist. | src/cli.py | format_options | yellowdog/virtual-screening-public | python | def format_options(self, ctx, formatter) -> None:
opts = []
for param in self.get_params(ctx):
rv = param.get_help_record(ctx)
if (rv is not None):
opts.append(rv)
if opts:
with formatter.section('Options'):
self.write_dl(formatter, opts) |
def get_min_fee_rate(self, cost: int) -> float:
'\n Gets the minimum fpc rate that a transaction with specified cost will need in order to get included.\n '
if self.at_full_capacity(cost):
current_cost = self.total_mempool_cost
for (fee_per_cost, spends_with_fpc) in self.sorted_spe... | 6,172,221,950,805,018,000 | Gets the minimum fpc rate that a transaction with specified cost will need in order to get included. | shamrock/full_node/mempool.py | get_min_fee_rate | zcomputerwiz/shamrock-blockchain | python | def get_min_fee_rate(self, cost: int) -> float:
'\n \n '
if self.at_full_capacity(cost):
current_cost = self.total_mempool_cost
for (fee_per_cost, spends_with_fpc) in self.sorted_spends.items():
for (spend_name, item) in spends_with_fpc.items():
current_... |
def remove_from_pool(self, item: MempoolItem):
'\n Removes an item from the mempool.\n '
removals: List[Coin] = item.removals
additions: List[Coin] = item.additions
for rem in removals:
del self.removals[rem.name()]
for add in additions:
del self.additions[add.name()]
... | -3,248,792,043,505,881,600 | Removes an item from the mempool. | shamrock/full_node/mempool.py | remove_from_pool | zcomputerwiz/shamrock-blockchain | python | def remove_from_pool(self, item: MempoolItem):
'\n \n '
removals: List[Coin] = item.removals
additions: List[Coin] = item.additions
for rem in removals:
del self.removals[rem.name()]
for add in additions:
del self.additions[add.name()]
del self.spends[item.name]
... |
def add_to_pool(self, item: MempoolItem):
"\n Adds an item to the mempool by kicking out transactions (if it doesn't fit), in order of increasing fee per cost\n "
while self.at_full_capacity(item.cost):
(fee_per_cost, val) = self.sorted_spends.peekitem(index=0)
to_remove = list(val... | 5,049,865,894,518,057,000 | Adds an item to the mempool by kicking out transactions (if it doesn't fit), in order of increasing fee per cost | shamrock/full_node/mempool.py | add_to_pool | zcomputerwiz/shamrock-blockchain | python | def add_to_pool(self, item: MempoolItem):
"\n \n "
while self.at_full_capacity(item.cost):
(fee_per_cost, val) = self.sorted_spends.peekitem(index=0)
to_remove = list(val.values())[0]
self.remove_from_pool(to_remove)
self.spends[item.name] = item
if (item.fee_per_co... |
def at_full_capacity(self, cost: int) -> bool:
'\n Checks whether the mempool is at full capacity and cannot accept a transaction with size cost.\n '
return ((self.total_mempool_cost + cost) > self.max_size_in_cost) | 4,300,916,430,235,673,000 | Checks whether the mempool is at full capacity and cannot accept a transaction with size cost. | shamrock/full_node/mempool.py | at_full_capacity | zcomputerwiz/shamrock-blockchain | python | def at_full_capacity(self, cost: int) -> bool:
'\n \n '
return ((self.total_mempool_cost + cost) > self.max_size_in_cost) |
@exporter.export
@preprocess_xarray
def resample_nn_1d(a, centers):
'Return one-dimensional nearest-neighbor indexes based on user-specified centers.\n\n Parameters\n ----------\n a : array-like\n 1-dimensional array of numeric values from which to\n extract indexes of nearest-neighbors\n ... | -1,834,903,684,328,060,000 | Return one-dimensional nearest-neighbor indexes based on user-specified centers.
Parameters
----------
a : array-like
1-dimensional array of numeric values from which to
extract indexes of nearest-neighbors
centers : array-like
1-dimensional array of numeric values representing a subset of values to approx... | src/metpy/calc/tools.py | resample_nn_1d | Exi666/MetPy | python | @exporter.export
@preprocess_xarray
def resample_nn_1d(a, centers):
'Return one-dimensional nearest-neighbor indexes based on user-specified centers.\n\n Parameters\n ----------\n a : array-like\n 1-dimensional array of numeric values from which to\n extract indexes of nearest-neighbors\n ... |
@exporter.export
@preprocess_xarray
def nearest_intersection_idx(a, b):
'Determine the index of the point just before two lines with common x values.\n\n Parameters\n ----------\n a : array-like\n 1-dimensional array of y-values for line 1\n b : array-like\n 1-dimensional array of y-values... | -2,360,650,077,986,789,400 | Determine the index of the point just before two lines with common x values.
Parameters
----------
a : array-like
1-dimensional array of y-values for line 1
b : array-like
1-dimensional array of y-values for line 2
Returns
-------
An array of indexes representing the index of the values
just before th... | src/metpy/calc/tools.py | nearest_intersection_idx | Exi666/MetPy | python | @exporter.export
@preprocess_xarray
def nearest_intersection_idx(a, b):
'Determine the index of the point just before two lines with common x values.\n\n Parameters\n ----------\n a : array-like\n 1-dimensional array of y-values for line 1\n b : array-like\n 1-dimensional array of y-values... |
@exporter.export
@preprocess_xarray
@units.wraps(('=A', '=B'), ('=A', '=B', '=B'))
def find_intersections(x, a, b, direction='all', log_x=False):
"Calculate the best estimate of intersection.\n\n Calculates the best estimates of the intersection of two y-value\n data sets that share a common x-value set.\n\n ... | 7,216,288,770,360,933,000 | Calculate the best estimate of intersection.
Calculates the best estimates of the intersection of two y-value
data sets that share a common x-value set.
Parameters
----------
x : array-like
1-dimensional array of numeric x-values
a : array-like
1-dimensional array of y-values for line 1
b : array-like
1-d... | src/metpy/calc/tools.py | find_intersections | Exi666/MetPy | python | @exporter.export
@preprocess_xarray
@units.wraps(('=A', '=B'), ('=A', '=B', '=B'))
def find_intersections(x, a, b, direction='all', log_x=False):
"Calculate the best estimate of intersection.\n\n Calculates the best estimates of the intersection of two y-value\n data sets that share a common x-value set.\n\n ... |
def _next_non_masked_element(a, idx):
'Return the next non masked element of a masked array.\n\n If an array is masked, return the next non-masked element (if the given index is masked).\n If no other unmasked points are after the given masked point, returns none.\n\n Parameters\n ----------\n a : ar... | -2,391,143,805,257,920,500 | Return the next non masked element of a masked array.
If an array is masked, return the next non-masked element (if the given index is masked).
If no other unmasked points are after the given masked point, returns none.
Parameters
----------
a : array-like
1-dimensional array of numeric values
idx : integer
i... | src/metpy/calc/tools.py | _next_non_masked_element | Exi666/MetPy | python | def _next_non_masked_element(a, idx):
'Return the next non masked element of a masked array.\n\n If an array is masked, return the next non-masked element (if the given index is masked).\n If no other unmasked points are after the given masked point, returns none.\n\n Parameters\n ----------\n a : ar... |
def _delete_masked_points(*arrs):
'Delete masked points from arrays.\n\n Takes arrays and removes masked points to help with calculations and plotting.\n\n Parameters\n ----------\n arrs : one or more array-like\n source arrays\n\n Returns\n -------\n arrs : one or more array-like\n ... | 1,146,317,948,787,329,900 | Delete masked points from arrays.
Takes arrays and removes masked points to help with calculations and plotting.
Parameters
----------
arrs : one or more array-like
source arrays
Returns
-------
arrs : one or more array-like
arrays with masked elements removed | src/metpy/calc/tools.py | _delete_masked_points | Exi666/MetPy | python | def _delete_masked_points(*arrs):
'Delete masked points from arrays.\n\n Takes arrays and removes masked points to help with calculations and plotting.\n\n Parameters\n ----------\n arrs : one or more array-like\n source arrays\n\n Returns\n -------\n arrs : one or more array-like\n ... |
@exporter.export
@preprocess_xarray
def reduce_point_density(points, radius, priority=None):
'Return a mask to reduce the density of points in irregularly-spaced data.\n\n This function is used to down-sample a collection of scattered points (e.g. surface\n data), returning a mask that can be used to select t... | -5,638,059,920,344,696,000 | Return a mask to reduce the density of points in irregularly-spaced data.
This function is used to down-sample a collection of scattered points (e.g. surface
data), returning a mask that can be used to select the points from one or more arrays
(e.g. arrays of temperature and dew point). The points selected can be cont... | src/metpy/calc/tools.py | reduce_point_density | Exi666/MetPy | python | @exporter.export
@preprocess_xarray
def reduce_point_density(points, radius, priority=None):
'Return a mask to reduce the density of points in irregularly-spaced data.\n\n This function is used to down-sample a collection of scattered points (e.g. surface\n data), returning a mask that can be used to select t... |
def _get_bound_pressure_height(pressure, bound, heights=None, interpolate=True):
'Calculate the bounding pressure and height in a layer.\n\n Given pressure, optional heights, and a bound, return either the closest pressure/height\n or interpolated pressure/height. If no heights are provided, a standard atmosp... | 8,279,656,246,866,304,000 | Calculate the bounding pressure and height in a layer.
Given pressure, optional heights, and a bound, return either the closest pressure/height
or interpolated pressure/height. If no heights are provided, a standard atmosphere
([NOAA1976]_) is assumed.
Parameters
----------
pressure : `pint.Quantity`
Atmospheric ... | src/metpy/calc/tools.py | _get_bound_pressure_height | Exi666/MetPy | python | def _get_bound_pressure_height(pressure, bound, heights=None, interpolate=True):
'Calculate the bounding pressure and height in a layer.\n\n Given pressure, optional heights, and a bound, return either the closest pressure/height\n or interpolated pressure/height. If no heights are provided, a standard atmosp... |
@exporter.export
@preprocess_xarray
@check_units('[length]')
def get_layer_heights(heights, depth, *args, bottom=None, interpolate=True, with_agl=False):
'Return an atmospheric layer from upper air data with the requested bottom and depth.\n\n This function will subset an upper air dataset to contain only the sp... | 832,905,234,243,500,700 | Return an atmospheric layer from upper air data with the requested bottom and depth.
This function will subset an upper air dataset to contain only the specified layer using
the heights only.
Parameters
----------
heights : array-like
Atmospheric heights
depth : `pint.Quantity`
The thickness of the layer
args... | src/metpy/calc/tools.py | get_layer_heights | Exi666/MetPy | python | @exporter.export
@preprocess_xarray
@check_units('[length]')
def get_layer_heights(heights, depth, *args, bottom=None, interpolate=True, with_agl=False):
'Return an atmospheric layer from upper air data with the requested bottom and depth.\n\n This function will subset an upper air dataset to contain only the sp... |
@exporter.export
@preprocess_xarray
@check_units('[pressure]')
def get_layer(pressure, *args, heights=None, bottom=None, depth=(100 * units.hPa), interpolate=True):
'Return an atmospheric layer from upper air data with the requested bottom and depth.\n\n This function will subset an upper air dataset to contain ... | -6,791,250,193,567,541,000 | Return an atmospheric layer from upper air data with the requested bottom and depth.
This function will subset an upper air dataset to contain only the specified layer. The
bottom of the layer can be specified with a pressure or height above the surface
pressure. The bottom defaults to the surface pressure. The depth ... | src/metpy/calc/tools.py | get_layer | Exi666/MetPy | python | @exporter.export
@preprocess_xarray
@check_units('[pressure]')
def get_layer(pressure, *args, heights=None, bottom=None, depth=(100 * units.hPa), interpolate=True):
'Return an atmospheric layer from upper air data with the requested bottom and depth.\n\n This function will subset an upper air dataset to contain ... |
@exporter.export
@preprocess_xarray
def find_bounding_indices(arr, values, axis, from_below=True):
'Find the indices surrounding the values within arr along axis.\n\n Returns a set of above, below, good. Above and below are lists of arrays of indices.\n These lists are formulated such that they can be used di... | 2,505,778,878,363,609,000 | Find the indices surrounding the values within arr along axis.
Returns a set of above, below, good. Above and below are lists of arrays of indices.
These lists are formulated such that they can be used directly to index into a numpy
array and get the expected results (no extra slices or ellipsis necessary). `good` is
... | src/metpy/calc/tools.py | find_bounding_indices | Exi666/MetPy | python | @exporter.export
@preprocess_xarray
def find_bounding_indices(arr, values, axis, from_below=True):
'Find the indices surrounding the values within arr along axis.\n\n Returns a set of above, below, good. Above and below are lists of arrays of indices.\n These lists are formulated such that they can be used di... |
def _greater_or_close(a, value, **kwargs):
'Compare values for greater or close to boolean masks.\n\n Returns a boolean mask for values greater than or equal to a target within a specified\n absolute or relative tolerance (as in :func:`numpy.isclose`).\n\n Parameters\n ----------\n a : array-like\n ... | -7,560,346,119,085,802,000 | Compare values for greater or close to boolean masks.
Returns a boolean mask for values greater than or equal to a target within a specified
absolute or relative tolerance (as in :func:`numpy.isclose`).
Parameters
----------
a : array-like
Array of values to be compared
value : float
Comparison value
Returns... | src/metpy/calc/tools.py | _greater_or_close | Exi666/MetPy | python | def _greater_or_close(a, value, **kwargs):
'Compare values for greater or close to boolean masks.\n\n Returns a boolean mask for values greater than or equal to a target within a specified\n absolute or relative tolerance (as in :func:`numpy.isclose`).\n\n Parameters\n ----------\n a : array-like\n ... |
def _less_or_close(a, value, **kwargs):
'Compare values for less or close to boolean masks.\n\n Returns a boolean mask for values less than or equal to a target within a specified\n absolute or relative tolerance (as in :func:`numpy.isclose`).\n\n Parameters\n ----------\n a : array-like\n Arr... | -8,507,754,622,202,489,000 | Compare values for less or close to boolean masks.
Returns a boolean mask for values less than or equal to a target within a specified
absolute or relative tolerance (as in :func:`numpy.isclose`).
Parameters
----------
a : array-like
Array of values to be compared
value : float
Comparison value
Returns
-----... | src/metpy/calc/tools.py | _less_or_close | Exi666/MetPy | python | def _less_or_close(a, value, **kwargs):
'Compare values for less or close to boolean masks.\n\n Returns a boolean mask for values less than or equal to a target within a specified\n absolute or relative tolerance (as in :func:`numpy.isclose`).\n\n Parameters\n ----------\n a : array-like\n Arr... |
@exporter.export
@preprocess_xarray
def lat_lon_grid_deltas(longitude, latitude, **kwargs):
'Calculate the delta between grid points that are in a latitude/longitude format.\n\n Calculate the signed delta distance between grid points when the grid spacing is defined by\n delta lat/lon rather than delta x/y\n\... | -3,332,198,802,547,874,000 | Calculate the delta between grid points that are in a latitude/longitude format.
Calculate the signed delta distance between grid points when the grid spacing is defined by
delta lat/lon rather than delta x/y
Parameters
----------
longitude : array_like
array of longitudes defining the grid
latitude : array_like
... | src/metpy/calc/tools.py | lat_lon_grid_deltas | Exi666/MetPy | python | @exporter.export
@preprocess_xarray
def lat_lon_grid_deltas(longitude, latitude, **kwargs):
'Calculate the delta between grid points that are in a latitude/longitude format.\n\n Calculate the signed delta distance between grid points when the grid spacing is defined by\n delta lat/lon rather than delta x/y\n\... |
@exporter.export
def grid_deltas_from_dataarray(f):
'Calculate the horizontal deltas between grid points of a DataArray.\n\n Calculate the signed delta distance between grid points of a DataArray in the horizontal\n directions, whether the grid is lat/lon or x/y.\n\n Parameters\n ----------\n f : `xa... | -876,946,303,530,190,800 | Calculate the horizontal deltas between grid points of a DataArray.
Calculate the signed delta distance between grid points of a DataArray in the horizontal
directions, whether the grid is lat/lon or x/y.
Parameters
----------
f : `xarray.DataArray`
Parsed DataArray on a latitude/longitude grid, in (..., lat, lon... | src/metpy/calc/tools.py | grid_deltas_from_dataarray | Exi666/MetPy | python | @exporter.export
def grid_deltas_from_dataarray(f):
'Calculate the horizontal deltas between grid points of a DataArray.\n\n Calculate the signed delta distance between grid points of a DataArray in the horizontal\n directions, whether the grid is lat/lon or x/y.\n\n Parameters\n ----------\n f : `xa... |
def xarray_derivative_wrap(func):
'Decorate the derivative functions to make them work nicely with DataArrays.\n\n This will automatically determine if the coordinates can be pulled directly from the\n DataArray, or if a call to lat_lon_grid_deltas is needed.\n '
@functools.wraps(func)
def wrapper... | -7,242,021,336,284,623,000 | Decorate the derivative functions to make them work nicely with DataArrays.
This will automatically determine if the coordinates can be pulled directly from the
DataArray, or if a call to lat_lon_grid_deltas is needed. | src/metpy/calc/tools.py | xarray_derivative_wrap | Exi666/MetPy | python | def xarray_derivative_wrap(func):
'Decorate the derivative functions to make them work nicely with DataArrays.\n\n This will automatically determine if the coordinates can be pulled directly from the\n DataArray, or if a call to lat_lon_grid_deltas is needed.\n '
@functools.wraps(func)
def wrapper... |
@exporter.export
@xarray_derivative_wrap
def first_derivative(f, **kwargs):
'Calculate the first derivative of a grid of values.\n\n Works for both regularly-spaced data and grids with varying spacing.\n\n Either `x` or `delta` must be specified, or `f` must be given as an `xarray.DataArray` with\n attache... | -1,198,659,539,310,157,300 | Calculate the first derivative of a grid of values.
Works for both regularly-spaced data and grids with varying spacing.
Either `x` or `delta` must be specified, or `f` must be given as an `xarray.DataArray` with
attached coordinate and projection information. If `f` is an `xarray.DataArray`, and `x` or
`delta` are g... | src/metpy/calc/tools.py | first_derivative | Exi666/MetPy | python | @exporter.export
@xarray_derivative_wrap
def first_derivative(f, **kwargs):
'Calculate the first derivative of a grid of values.\n\n Works for both regularly-spaced data and grids with varying spacing.\n\n Either `x` or `delta` must be specified, or `f` must be given as an `xarray.DataArray` with\n attache... |
@exporter.export
@xarray_derivative_wrap
def second_derivative(f, **kwargs):
'Calculate the second derivative of a grid of values.\n\n Works for both regularly-spaced data and grids with varying spacing.\n\n Either `x` or `delta` must be specified, or `f` must be given as an `xarray.DataArray` with\n attac... | -1,680,862,827,805,037,800 | Calculate the second derivative of a grid of values.
Works for both regularly-spaced data and grids with varying spacing.
Either `x` or `delta` must be specified, or `f` must be given as an `xarray.DataArray` with
attached coordinate and projection information. If `f` is an `xarray.DataArray`, and `x` or
`delta` are ... | src/metpy/calc/tools.py | second_derivative | Exi666/MetPy | python | @exporter.export
@xarray_derivative_wrap
def second_derivative(f, **kwargs):
'Calculate the second derivative of a grid of values.\n\n Works for both regularly-spaced data and grids with varying spacing.\n\n Either `x` or `delta` must be specified, or `f` must be given as an `xarray.DataArray` with\n attac... |
@exporter.export
def gradient(f, **kwargs):
'Calculate the gradient of a grid of values.\n\n Works for both regularly-spaced data, and grids with varying spacing.\n\n Either `coordinates` or `deltas` must be specified, or `f` must be given as an\n `xarray.DataArray` with attached coordinate and projection... | 4,592,195,275,797,524,000 | Calculate the gradient of a grid of values.
Works for both regularly-spaced data, and grids with varying spacing.
Either `coordinates` or `deltas` must be specified, or `f` must be given as an
`xarray.DataArray` with attached coordinate and projection information. If `f` is an
`xarray.DataArray`, and `coordinates` o... | src/metpy/calc/tools.py | gradient | Exi666/MetPy | python | @exporter.export
def gradient(f, **kwargs):
'Calculate the gradient of a grid of values.\n\n Works for both regularly-spaced data, and grids with varying spacing.\n\n Either `coordinates` or `deltas` must be specified, or `f` must be given as an\n `xarray.DataArray` with attached coordinate and projection... |
@exporter.export
def laplacian(f, **kwargs):
'Calculate the laplacian of a grid of values.\n\n Works for both regularly-spaced data, and grids with varying spacing.\n\n Either `coordinates` or `deltas` must be specified, or `f` must be given as an\n `xarray.DataArray` with attached coordinate and projecti... | 874,958,084,346,929,200 | Calculate the laplacian of a grid of values.
Works for both regularly-spaced data, and grids with varying spacing.
Either `coordinates` or `deltas` must be specified, or `f` must be given as an
`xarray.DataArray` with attached coordinate and projection information. If `f` is an
`xarray.DataArray`, and `coordinates` ... | src/metpy/calc/tools.py | laplacian | Exi666/MetPy | python | @exporter.export
def laplacian(f, **kwargs):
'Calculate the laplacian of a grid of values.\n\n Works for both regularly-spaced data, and grids with varying spacing.\n\n Either `coordinates` or `deltas` must be specified, or `f` must be given as an\n `xarray.DataArray` with attached coordinate and projecti... |
def _broadcast_to_axis(arr, axis, ndim):
'Handle reshaping coordinate array to have proper dimensionality.\n\n This puts the values along the specified axis.\n '
if ((arr.ndim == 1) and (arr.ndim < ndim)):
new_shape = ([1] * ndim)
new_shape[axis] = arr.size
arr = arr.reshape(*new_s... | -5,780,615,902,284,994,000 | Handle reshaping coordinate array to have proper dimensionality.
This puts the values along the specified axis. | src/metpy/calc/tools.py | _broadcast_to_axis | Exi666/MetPy | python | def _broadcast_to_axis(arr, axis, ndim):
'Handle reshaping coordinate array to have proper dimensionality.\n\n This puts the values along the specified axis.\n '
if ((arr.ndim == 1) and (arr.ndim < ndim)):
new_shape = ([1] * ndim)
new_shape[axis] = arr.size
arr = arr.reshape(*new_s... |
def _process_gradient_args(f, kwargs):
'Handle common processing of arguments for gradient and gradient-like functions.'
axes = kwargs.get('axes', range(f.ndim))
def _check_length(positions):
if (('axes' in kwargs) and (len(positions) < len(axes))):
raise ValueError('Length of "coordina... | 5,760,192,490,319,572,000 | Handle common processing of arguments for gradient and gradient-like functions. | src/metpy/calc/tools.py | _process_gradient_args | Exi666/MetPy | python | def _process_gradient_args(f, kwargs):
axes = kwargs.get('axes', range(f.ndim))
def _check_length(positions):
if (('axes' in kwargs) and (len(positions) < len(axes))):
raise ValueError('Length of "coordinates" or "deltas" cannot be less than that of "axes".')
elif (('axes' not ... |
def _process_deriv_args(f, kwargs):
'Handle common processing of arguments for derivative functions.'
n = f.ndim
axis = normalize_axis_index(kwargs.get('axis', 0), n)
if (f.shape[axis] < 3):
raise ValueError('f must have at least 3 point along the desired axis.')
if ('delta' in kwargs):
... | -7,415,067,897,977,236,000 | Handle common processing of arguments for derivative functions. | src/metpy/calc/tools.py | _process_deriv_args | Exi666/MetPy | python | def _process_deriv_args(f, kwargs):
n = f.ndim
axis = normalize_axis_index(kwargs.get('axis', 0), n)
if (f.shape[axis] < 3):
raise ValueError('f must have at least 3 point along the desired axis.')
if ('delta' in kwargs):
if ('x' in kwargs):
raise ValueError('Cannot spec... |
@exporter.export
@preprocess_xarray
def parse_angle(input_dir):
'Calculate the meteorological angle from directional text.\n\n Works for abbrieviations or whole words (E -> 90 | South -> 180)\n and also is able to parse 22.5 degreee angles such as ESE/East South East\n\n Parameters\n ----------\n inp... | -2,738,574,353,686,353,400 | Calculate the meteorological angle from directional text.
Works for abbrieviations or whole words (E -> 90 | South -> 180)
and also is able to parse 22.5 degreee angles such as ESE/East South East
Parameters
----------
input_dir : string or array-like
Directional text such as west, [south-west, ne], etc
Returns
... | src/metpy/calc/tools.py | parse_angle | Exi666/MetPy | python | @exporter.export
@preprocess_xarray
def parse_angle(input_dir):
'Calculate the meteorological angle from directional text.\n\n Works for abbrieviations or whole words (E -> 90 | South -> 180)\n and also is able to parse 22.5 degreee angles such as ESE/East South East\n\n Parameters\n ----------\n inp... |
def _clean_direction(dir_list, preprocess=False):
'Handle None if preprocess, else handles anything not in DIR_STRS.'
if preprocess:
return [(UND if (not isinstance(the_dir, str)) else the_dir) for the_dir in dir_list]
else:
return [(UND if (the_dir not in DIR_STRS) else the_dir) for the_dir... | -4,458,721,442,283,602,400 | Handle None if preprocess, else handles anything not in DIR_STRS. | src/metpy/calc/tools.py | _clean_direction | Exi666/MetPy | python | def _clean_direction(dir_list, preprocess=False):
if preprocess:
return [(UND if (not isinstance(the_dir, str)) else the_dir) for the_dir in dir_list]
else:
return [(UND if (the_dir not in DIR_STRS) else the_dir) for the_dir in dir_list] |
def _abbrieviate_direction(ext_dir_str):
'Convert extended (non-abbrievated) directions to abbrieviation.'
return ext_dir_str.upper().replace('_', '').replace('-', '').replace(' ', '').replace('NORTH', 'N').replace('EAST', 'E').replace('SOUTH', 'S').replace('WEST', 'W') | 4,715,359,313,793,490,000 | Convert extended (non-abbrievated) directions to abbrieviation. | src/metpy/calc/tools.py | _abbrieviate_direction | Exi666/MetPy | python | def _abbrieviate_direction(ext_dir_str):
return ext_dir_str.upper().replace('_', ).replace('-', ).replace(' ', ).replace('NORTH', 'N').replace('EAST', 'E').replace('SOUTH', 'S').replace('WEST', 'W') |
@exporter.export
@preprocess_xarray
def angle_to_direction(input_angle, full=False, level=3):
'Convert the meteorological angle to directional text.\n\n Works for angles greater than or equal to 360 (360 -> N | 405 -> NE)\n and rounds to the nearest angle (355 -> N | 404 -> NNE)\n\n Parameters\n -------... | -3,599,905,639,071,405,000 | Convert the meteorological angle to directional text.
Works for angles greater than or equal to 360 (360 -> N | 405 -> NE)
and rounds to the nearest angle (355 -> N | 404 -> NNE)
Parameters
----------
input_angle : numeric or array-like numeric
Angles such as 0, 25, 45, 360, 410, etc
full : boolean
True retur... | src/metpy/calc/tools.py | angle_to_direction | Exi666/MetPy | python | @exporter.export
@preprocess_xarray
def angle_to_direction(input_angle, full=False, level=3):
'Convert the meteorological angle to directional text.\n\n Works for angles greater than or equal to 360 (360 -> N | 405 -> NE)\n and rounds to the nearest angle (355 -> N | 404 -> NNE)\n\n Parameters\n -------... |
def _unabbrieviate_direction(abb_dir_str):
'Convert abbrieviated directions to non-abbrieviated direction.'
return abb_dir_str.upper().replace(UND, 'Undefined ').replace('N', 'North ').replace('E', 'East ').replace('S', 'South ').replace('W', 'West ').replace(' ,', ',').strip() | 3,144,671,443,861,817,000 | Convert abbrieviated directions to non-abbrieviated direction. | src/metpy/calc/tools.py | _unabbrieviate_direction | Exi666/MetPy | python | def _unabbrieviate_direction(abb_dir_str):
return abb_dir_str.upper().replace(UND, 'Undefined ').replace('N', 'North ').replace('E', 'East ').replace('S', 'South ').replace('W', 'West ').replace(' ,', ',').strip() |
def _remove_nans(*variables):
'Remove NaNs from arrays that cause issues with calculations.\n\n Takes a variable number of arguments\n Returns masked arrays in the same order as provided\n '
mask = None
for v in variables:
if (mask is None):
mask = np.isnan(v)
else:
... | 3,602,438,539,218,065,000 | Remove NaNs from arrays that cause issues with calculations.
Takes a variable number of arguments
Returns masked arrays in the same order as provided | src/metpy/calc/tools.py | _remove_nans | Exi666/MetPy | python | def _remove_nans(*variables):
'Remove NaNs from arrays that cause issues with calculations.\n\n Takes a variable number of arguments\n Returns masked arrays in the same order as provided\n '
mask = None
for v in variables:
if (mask is None):
mask = np.isnan(v)
else:
... |
def get_resources(self, circuit: Union[(Circuit, ResultHandle)]) -> ResourcesResult:
'Calculate resource estimates for circuit.\n\n :param circuit: Circuit to calculate or result handle to retrieve for\n :type circuit: Union[Circuit, ResultHandle]\n :return: Resource estimate\n :rtype: D... | 8,368,390,466,831,838,000 | Calculate resource estimates for circuit.
:param circuit: Circuit to calculate or result handle to retrieve for
:type circuit: Union[Circuit, ResultHandle]
:return: Resource estimate
:rtype: Dict[str, int] | modules/pytket-qsharp/pytket/extensions/qsharp/backends/estimator.py | get_resources | dhaycraft/pytket-extensions | python | def get_resources(self, circuit: Union[(Circuit, ResultHandle)]) -> ResourcesResult:
'Calculate resource estimates for circuit.\n\n :param circuit: Circuit to calculate or result handle to retrieve for\n :type circuit: Union[Circuit, ResultHandle]\n :return: Resource estimate\n :rtype: D... |
def parse(self, response):
'\n `parse` should always `yield` a dict that follows the Event Schema\n <https://city-bureau.github.io/city-scrapers/06_event_schema.html>.\n\n Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping\n needs.\n '
month_counter = date... | -7,782,619,201,033,553,000 | `parse` should always `yield` a dict that follows the Event Schema
<https://city-bureau.github.io/city-scrapers/06_event_schema.html>.
Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping
needs. | city_scrapers/spiders/chi_school_community_action_council.py | parse | jim/city-scrapers | python | def parse(self, response):
'\n `parse` should always `yield` a dict that follows the Event Schema\n <https://city-bureau.github.io/city-scrapers/06_event_schema.html>.\n\n Change the `_parse_id`, `_parse_name`, etc methods to fit your scraping\n needs.\n '
month_counter = date... |
def _parse_community_area(self, item):
'\n Parse or generate community area.\n '
if (len(item.css('li').css('strong::text').extract()) == 1):
community_name = item.css('li').css('strong::text').extract()
else:
community_name = item.css('li').css('strong').css('a::text').extract... | 2,955,008,406,036,623,400 | Parse or generate community area. | city_scrapers/spiders/chi_school_community_action_council.py | _parse_community_area | jim/city-scrapers | python | def _parse_community_area(self, item):
'\n \n '
if (len(item.css('li').css('strong::text').extract()) == 1):
community_name = item.css('li').css('strong::text').extract()
else:
community_name = item.css('li').css('strong').css('a::text').extract()
return community_name[0] |
def _parse_name(self, item):
'\n Parse or generate event name.\n '
if (len(item.css('li').css('strong::text').extract()) == 1):
community_name = item.css('li').css('strong::text').extract()
else:
community_name = item.css('li').css('strong').css('a::text').extract()
return ... | -3,257,092,148,956,459,000 | Parse or generate event name. | city_scrapers/spiders/chi_school_community_action_council.py | _parse_name | jim/city-scrapers | python | def _parse_name(self, item):
'\n \n '
if (len(item.css('li').css('strong::text').extract()) == 1):
community_name = item.css('li').css('strong::text').extract()
else:
community_name = item.css('li').css('strong').css('a::text').extract()
return (community_name[0] + ' Commun... |
def _parse_description(self, item):
'\n Parse or generate event description.\n '
return "Community Action Councils, or CACs, consist of 25-30 voting members who are directly involved in developing a strategic plan for educational success within their communities. CAC members include parents; elect... | -792,315,873,038,031,000 | Parse or generate event description. | city_scrapers/spiders/chi_school_community_action_council.py | _parse_description | jim/city-scrapers | python | def _parse_description(self, item):
'\n \n '
return "Community Action Councils, or CACs, consist of 25-30 voting members who are directly involved in developing a strategic plan for educational success within their communities. CAC members include parents; elected officials; faith-based institutio... |
def _parse_classification(self, item):
'\n Parse or generate classification (e.g. public health, education, etc).\n '
return 'Education' | -5,466,161,057,394,642,000 | Parse or generate classification (e.g. public health, education, etc). | city_scrapers/spiders/chi_school_community_action_council.py | _parse_classification | jim/city-scrapers | python | def _parse_classification(self, item):
'\n \n '
return 'Education' |
def _parse_start(self, item, month_counter):
'\n Parse start date and time.\n\n Accepts month_counter as an argument from top level parse function to iterate through all months in the year.\n '
def parse_day(source):
'Parses the source material and retrieves the day of the week tha... | 2,692,572,152,009,959,400 | Parse start date and time.
Accepts month_counter as an argument from top level parse function to iterate through all months in the year. | city_scrapers/spiders/chi_school_community_action_council.py | _parse_start | jim/city-scrapers | python | def _parse_start(self, item, month_counter):
'\n Parse start date and time.\n\n Accepts month_counter as an argument from top level parse function to iterate through all months in the year.\n '
def parse_day(source):
'Parses the source material and retrieves the day of the week tha... |
def _parse_end(self, item):
'\n Parse end date and time.\n '
return 'Estimated 3 hours' | -8,884,588,212,588,568,000 | Parse end date and time. | city_scrapers/spiders/chi_school_community_action_council.py | _parse_end | jim/city-scrapers | python | def _parse_end(self, item):
'\n \n '
return 'Estimated 3 hours' |
def _parse_timezone(self, item):
'\n Parse or generate timzone in tzinfo format.\n '
return 'America/Chicago' | -4,945,136,529,224,096,000 | Parse or generate timzone in tzinfo format. | city_scrapers/spiders/chi_school_community_action_council.py | _parse_timezone | jim/city-scrapers | python | def _parse_timezone(self, item):
'\n \n '
return 'America/Chicago' |
def _parse_all_day(self, item):
'\n Parse or generate all-day status. Defaults to False.\n '
return False | 8,632,466,700,201,192,000 | Parse or generate all-day status. Defaults to False. | city_scrapers/spiders/chi_school_community_action_council.py | _parse_all_day | jim/city-scrapers | python | def _parse_all_day(self, item):
'\n \n '
return False |
def _parse_location(self, item):
'\n Parse or generate location. Latitude and longitude can be\n left blank and will be geocoded later.\n '
source = item.css('li::text').extract()[1]
return {'url': None, 'name': source[(source.find('at') + 2):source.find('(')].replace('the', ''), 'addre... | 2,512,085,160,778,465,300 | Parse or generate location. Latitude and longitude can be
left blank and will be geocoded later. | city_scrapers/spiders/chi_school_community_action_council.py | _parse_location | jim/city-scrapers | python | def _parse_location(self, item):
'\n Parse or generate location. Latitude and longitude can be\n left blank and will be geocoded later.\n '
source = item.css('li::text').extract()[1]
return {'url': None, 'name': source[(source.find('at') + 2):source.find('(')].replace('the', ), 'address... |
def _parse_status(self, item):
'\n Parse or generate status of meeting. Can be one of:\n * cancelled\n * tentative\n * confirmed\n * passed\n By default, return "tentative"\n '
return 'Tentative' | -3,350,006,070,809,307,000 | Parse or generate status of meeting. Can be one of:
* cancelled
* tentative
* confirmed
* passed
By default, return "tentative" | city_scrapers/spiders/chi_school_community_action_council.py | _parse_status | jim/city-scrapers | python | def _parse_status(self, item):
'\n Parse or generate status of meeting. Can be one of:\n * cancelled\n * tentative\n * confirmed\n * passed\n By default, return "tentative"\n '
return 'Tentative' |
def _parse_sources(self, response):
'\n Parse or generate sources.\n '
return [{'url': response.url, 'note': ''}] | 4,178,576,951,971,141,000 | Parse or generate sources. | city_scrapers/spiders/chi_school_community_action_council.py | _parse_sources | jim/city-scrapers | python | def _parse_sources(self, response):
'\n \n '
return [{'url': response.url, 'note': }] |
def parse_day(source):
'Parses the source material and retrieves the day of the week that the meeting occurs.\n '
day_source = source[0]
day_regex = re.compile('[a-zA-Z]+day')
mo = day_regex.search(day_source)
return mo.group().lower() | -1,311,422,417,374,438,700 | Parses the source material and retrieves the day of the week that the meeting occurs. | city_scrapers/spiders/chi_school_community_action_council.py | parse_day | jim/city-scrapers | python | def parse_day(source):
'\n '
day_source = source[0]
day_regex = re.compile('[a-zA-Z]+day')
mo = day_regex.search(day_source)
return mo.group().lower() |
def parse_time(source):
'Parses the source material and retrieves the time that the meeting occurs.\n '
time_source = source[1]
time_regex = re.compile('(1[012]|[1-9]):[0-5][0-9](am|pm)')
mo = time_regex.search(time_source)
return mo.group() | -2,985,683,150,497,293,000 | Parses the source material and retrieves the time that the meeting occurs. | city_scrapers/spiders/chi_school_community_action_council.py | parse_time | jim/city-scrapers | python | def parse_time(source):
'\n '
time_source = source[1]
time_regex = re.compile('(1[012]|[1-9]):[0-5][0-9](am|pm)')
mo = time_regex.search(time_source)
return mo.group() |
def count_days(day, week_count):
'Because the source material provides meeting dates on a reoccuring schedule, we must use the parsed day\n from the parse_day function and the '
today = datetime.today()
week_day = {'monday': 0, 'tuesday': 1, 'wednesday': 2, 'thursday': 3, 'friday': 4, 'saturday':... | 1,578,960,398,309,300,000 | Because the source material provides meeting dates on a reoccuring schedule, we must use the parsed day
from the parse_day function and the | city_scrapers/spiders/chi_school_community_action_council.py | count_days | jim/city-scrapers | python | def count_days(day, week_count):
'Because the source material provides meeting dates on a reoccuring schedule, we must use the parsed day\n from the parse_day function and the '
today = datetime.today()
week_day = {'monday': 0, 'tuesday': 1, 'wednesday': 2, 'thursday': 3, 'friday': 4, 'saturday':... |
def concat_date(meeting_date, time):
'Combines the meeting date with the time the meeting occurs. Function return a datetime\n object.\n '
return dateparse(((((((str(meeting_date.year) + '-') + str(meeting_date.month)) + '-') + str(meeting_date.day)) + ' ') + time)) | -473,956,566,229,258,050 | Combines the meeting date with the time the meeting occurs. Function return a datetime
object. | city_scrapers/spiders/chi_school_community_action_council.py | concat_date | jim/city-scrapers | python | def concat_date(meeting_date, time):
'Combines the meeting date with the time the meeting occurs. Function return a datetime\n object.\n '
return dateparse(((((((str(meeting_date.year) + '-') + str(meeting_date.month)) + '-') + str(meeting_date.day)) + ' ') + time)) |
def get_start(source):
'Combines above defined parse_day, parse_time, count_days, and concat_date functions to get the start\n date from the source. If a start time cannot be found the UNIX epoch date is returned.\n '
day = parse_day(source)
week_count = source[0].strip()[0]
if w... | 5,386,643,088,681,789,000 | Combines above defined parse_day, parse_time, count_days, and concat_date functions to get the start
date from the source. If a start time cannot be found the UNIX epoch date is returned. | city_scrapers/spiders/chi_school_community_action_council.py | get_start | jim/city-scrapers | python | def get_start(source):
'Combines above defined parse_day, parse_time, count_days, and concat_date functions to get the start\n date from the source. If a start time cannot be found the UNIX epoch date is returned.\n '
day = parse_day(source)
week_count = source[0].strip()[0]
if w... |
def Run(self, args):
'Run the list command.'
client = registries.RegistriesClient()
registry_ref = args.CONCEPTS.registry.Parse()
registry = client.Get(registry_ref)
for (idx, credential) in enumerate(registry.credentials):
serializable = resource_projector.MakeSerializable(credential)
... | 5,482,512,737,309,670,000 | Run the list command. | lib/surface/iot/registries/credentials/list.py | Run | bshaffer/google-cloud-sdk | python | def Run(self, args):
client = registries.RegistriesClient()
registry_ref = args.CONCEPTS.registry.Parse()
registry = client.Get(registry_ref)
for (idx, credential) in enumerate(registry.credentials):
serializable = resource_projector.MakeSerializable(credential)
serializable['index'... |
@property
def attention_weights(self) -> List:
'List with the attention weights. Each element of the list is a tuple\n where the first and the second elements are the column and row\n attention weights respectively\n\n The shape of the attention weights is:\n\n - column attention: :m... | 8,980,829,787,046,245,000 | List with the attention weights. Each element of the list is a tuple
where the first and the second elements are the column and row
attention weights respectively
The shape of the attention weights is:
- column attention: :math:`(N, H, F, F)`
- row attention: :math:`(1, H, N, N)`
where *N* is the batch size... | pytorch_widedeep/models/tabular/transformers/saint.py | attention_weights | TangleSpace/pytorch-widedeep | python | @property
def attention_weights(self) -> List:
'List with the attention weights. Each element of the list is a tuple\n where the first and the second elements are the column and row\n attention weights respectively\n\n The shape of the attention weights is:\n\n - column attention: :m... |
def execute_query(filename: str) -> Optional[pd.DataFrame]:
"Run SQL from a file. It will return a Pandas DataFrame if it selected\n anything; otherwise it will return None.\n\n I do not recommend you use this function too often. In general we should be\n using the SQLAlchemy ORM. That said, it's a nice co... | 2,471,230,407,435,967,500 | Run SQL from a file. It will return a Pandas DataFrame if it selected
anything; otherwise it will return None.
I do not recommend you use this function too often. In general we should be
using the SQLAlchemy ORM. That said, it's a nice convenience, and there are
times where this function is genuinely something you wan... | backend/database/core.py | execute_query | stianberghansen/police-data-trust | python | def execute_query(filename: str) -> Optional[pd.DataFrame]:
"Run SQL from a file. It will return a Pandas DataFrame if it selected\n anything; otherwise it will return None.\n\n I do not recommend you use this function too often. In general we should be\n using the SQLAlchemy ORM. That said, it's a nice co... |
@click.group('psql', cls=AppGroup)
@with_appcontext
@click.pass_context
def db_cli(ctx: click.Context):
'Collection of database commands.'
ctx.obj = connect(user=current_app.config['POSTGRES_USER'], password=current_app.config['POSTGRES_PASSWORD'], host=current_app.config['POSTGRES_HOST'], port=current_app.conf... | -4,530,861,317,515,405,000 | Collection of database commands. | backend/database/core.py | db_cli | stianberghansen/police-data-trust | python | @click.group('psql', cls=AppGroup)
@with_appcontext
@click.pass_context
def db_cli(ctx: click.Context):
ctx.obj = connect(user=current_app.config['POSTGRES_USER'], password=current_app.config['POSTGRES_PASSWORD'], host=current_app.config['POSTGRES_HOST'], port=current_app.config['POSTGRES_PORT'], dbname='postg... |
@db_cli.command('create')
@click.option('--overwrite/--no-overwrite', default=False, is_flag=True, show_default=True, help='If true, overwrite the database if it exists.')
@pass_psql_admin_connection
@click.pass_context
@dev_only
def create_database(ctx: click.Context, conn: connection, overwrite: bool=False):
'Cre... | -7,738,917,581,153,133,000 | Create the database from nothing. | backend/database/core.py | create_database | stianberghansen/police-data-trust | python | @db_cli.command('create')
@click.option('--overwrite/--no-overwrite', default=False, is_flag=True, show_default=True, help='If true, overwrite the database if it exists.')
@pass_psql_admin_connection
@click.pass_context
@dev_only
def create_database(ctx: click.Context, conn: connection, overwrite: bool=False):
... |
@db_cli.command('init')
def init_database():
'Initialize the database schemas.\n\n Run this after the database has been created.\n '
database = current_app.config['POSTGRES_DB']
db.create_all()
click.echo(f'Initialized the database {database!r}.') | -6,951,266,486,569,976,000 | Initialize the database schemas.
Run this after the database has been created. | backend/database/core.py | init_database | stianberghansen/police-data-trust | python | @db_cli.command('init')
def init_database():
'Initialize the database schemas.\n\n Run this after the database has been created.\n '
database = current_app.config['POSTGRES_DB']
db.create_all()
click.echo(f'Initialized the database {database!r}.') |
@db_cli.command('gen-examples')
def gen_examples_command():
'Generate 2 incident examples in the database.'
execute_query('example_incidents.sql')
click.echo('Added 2 example incidents to the database.') | 1,115,475,131,648,838,900 | Generate 2 incident examples in the database. | backend/database/core.py | gen_examples_command | stianberghansen/police-data-trust | python | @db_cli.command('gen-examples')
def gen_examples_command():
execute_query('example_incidents.sql')
click.echo('Added 2 example incidents to the database.') |
@db_cli.command('delete')
@click.option('--test-db', '-t', default=False, is_flag=True, help=f'Deletes the database {TestingConfig.POSTGRES_DB!r}.')
@pass_psql_admin_connection
@dev_only
def delete_database(conn: connection, test_db: bool):
'Delete the database.'
if test_db:
database = TestingConfig.POS... | 2,724,078,116,972,836,000 | Delete the database. | backend/database/core.py | delete_database | stianberghansen/police-data-trust | python | @db_cli.command('delete')
@click.option('--test-db', '-t', default=False, is_flag=True, help=f'Deletes the database {TestingConfig.POSTGRES_DB!r}.')
@pass_psql_admin_connection
@dev_only
def delete_database(conn: connection, test_db: bool):
if test_db:
database = TestingConfig.POSTGRES_DB
else:
... |
def params(q={}):
' default model parameters\n '
p = {}
p['tolNR'] = 1e-07
p['tend'] = 1.0
p['dtmax'] = 0.005
p['bndno'] = 17
p['bctype'] = 'pydeadloads'
p.update(q)
return p | -4,516,981,005,381,893,000 | default model parameters | tests/PFEM_Metafor/waterColoumnFallWithFlexibleObstacle_obstacle_Mtf_E_1_0e6_EAS.py | params | mlucio89/CUPyDO | python | def params(q={}):
' \n '
p = {}
p['tolNR'] = 1e-07
p['tend'] = 1.0
p['dtmax'] = 0.005
p['bndno'] = 17
p['bctype'] = 'pydeadloads'
p.update(q)
return p |
def group(seq, groupSize, noneFill=True):
'Groups a given sequence into sublists of length groupSize.'
ret = []
L = []
i = groupSize
for elt in seq:
if (i > 0):
L.append(elt)
else:
ret.append(L)
i = groupSize
L = []
L.append... | -6,485,224,228,336,238,000 | Groups a given sequence into sublists of length groupSize. | plugins/String/test.py | group | AntumDeluge/Limnoria | python | def group(seq, groupSize, noneFill=True):
ret = []
L = []
i = groupSize
for elt in seq:
if (i > 0):
L.append(elt)
else:
ret.append(L)
i = groupSize
L = []
L.append(elt)
i -= 1
if L:
if noneFill:
... |
def __init__(self, ci_estimator: Callable, alpha: float=0.05, init_graph: Union[(nx.Graph, ADMG)]=None, fixed_edges: nx.Graph=None, max_cond_set_size: int=None, **ci_estimator_kwargs):
'Peter and Clarke (PC) algorithm for causal discovery.\n\n Assumes causal sufficiency, that is, all confounders in the\n ... | -6,205,691,413,641,967,000 | Peter and Clarke (PC) algorithm for causal discovery.
Assumes causal sufficiency, that is, all confounders in the
causal graph are observed variables.
Parameters
----------
ci_estimator : Callable
The conditional independence test function. The arguments of the estimator should
be data, node, node to compare,... | causal_networkx/discovery/pcalg.py | __init__ | adam2392/causal-networkx | python | def __init__(self, ci_estimator: Callable, alpha: float=0.05, init_graph: Union[(nx.Graph, ADMG)]=None, fixed_edges: nx.Graph=None, max_cond_set_size: int=None, **ci_estimator_kwargs):
'Peter and Clarke (PC) algorithm for causal discovery.\n\n Assumes causal sufficiency, that is, all confounders in the\n ... |
def learn_skeleton(self, X: pd.DataFrame) -> Tuple[(nx.Graph, Dict[(str, Dict[(str, Set)])])]:
'Learn skeleton from data.\n\n Parameters\n ----------\n X : pd.DataFrame\n Dataset.\n\n Returns\n -------\n skel_graph : nx.Graph\n The skeleton graph.\n ... | 8,793,262,104,481,004,000 | Learn skeleton from data.
Parameters
----------
X : pd.DataFrame
Dataset.
Returns
-------
skel_graph : nx.Graph
The skeleton graph.
sep_set : Dict[str, Dict[str, Set]]
The separating set. | causal_networkx/discovery/pcalg.py | learn_skeleton | adam2392/causal-networkx | python | def learn_skeleton(self, X: pd.DataFrame) -> Tuple[(nx.Graph, Dict[(str, Dict[(str, Set)])])]:
'Learn skeleton from data.\n\n Parameters\n ----------\n X : pd.DataFrame\n Dataset.\n\n Returns\n -------\n skel_graph : nx.Graph\n The skeleton graph.\n ... |
def fit(self, X: pd.DataFrame) -> None:
"Fit PC algorithm on dataset 'X'."
(skel_graph, sep_set) = self.learn_skeleton(X)
graph = self._orient_edges(skel_graph, sep_set)
self.separating_sets_ = sep_set
self.graph_ = graph | -6,594,347,806,976,311,000 | Fit PC algorithm on dataset 'X'. | causal_networkx/discovery/pcalg.py | fit | adam2392/causal-networkx | python | def fit(self, X: pd.DataFrame) -> None:
(skel_graph, sep_set) = self.learn_skeleton(X)
graph = self._orient_edges(skel_graph, sep_set)
self.separating_sets_ = sep_set
self.graph_ = graph |
def _orient_edges(self, skel_graph, sep_set):
'Orient edges in a skeleton graph to estimate the causal DAG, or CPDAG.\n\n Uses the separation sets to orient edges via conditional independence\n testing.\n\n Parameters\n ----------\n skel_graph : nx.Graph\n A skeleton gr... | 7,184,094,386,730,885,000 | Orient edges in a skeleton graph to estimate the causal DAG, or CPDAG.
Uses the separation sets to orient edges via conditional independence
testing.
Parameters
----------
skel_graph : nx.Graph
A skeleton graph. If ``None``, then will initialize PC using a
complete graph. By default None.
sep_set : _type_
... | causal_networkx/discovery/pcalg.py | _orient_edges | adam2392/causal-networkx | python | def _orient_edges(self, skel_graph, sep_set):
'Orient edges in a skeleton graph to estimate the causal DAG, or CPDAG.\n\n Uses the separation sets to orient edges via conditional independence\n testing.\n\n Parameters\n ----------\n skel_graph : nx.Graph\n A skeleton gr... |
def brat_output(docgraph, layer=None, show_relations=True):
"\n converts a document graph with pointing chains into a string representation\n of a brat *.ann file.\n\n Parameters\n ----------\n docgraph : DiscourseDocumentGraph\n a document graph which might contain pointing chains (e.g. coref... | -8,608,024,915,250,498,000 | converts a document graph with pointing chains into a string representation
of a brat *.ann file.
Parameters
----------
docgraph : DiscourseDocumentGraph
a document graph which might contain pointing chains (e.g. coreference links)
layer : str or None
the name of the layer that contains the pointing chains (e.... | src/discoursegraphs/readwrite/brat.py | brat_output | arne-cl/discoursegraphs | python | def brat_output(docgraph, layer=None, show_relations=True):
"\n converts a document graph with pointing chains into a string representation\n of a brat *.ann file.\n\n Parameters\n ----------\n docgraph : DiscourseDocumentGraph\n a document graph which might contain pointing chains (e.g. coref... |
def create_visual_conf(docgraph, pointing_chains):
'\n creates a visual.conf file (as a string)\n for the given document graph.\n '
num_of_entities = len(pointing_chains)
mapsize = max(3, min(12, num_of_entities))
colormap = brewer2mpl.get_map(name='Paired', map_type='Qualitative', number=mapsi... | 8,306,438,556,565,813,000 | creates a visual.conf file (as a string)
for the given document graph. | src/discoursegraphs/readwrite/brat.py | create_visual_conf | arne-cl/discoursegraphs | python | def create_visual_conf(docgraph, pointing_chains):
'\n creates a visual.conf file (as a string)\n for the given document graph.\n '
num_of_entities = len(pointing_chains)
mapsize = max(3, min(12, num_of_entities))
colormap = brewer2mpl.get_map(name='Paired', map_type='Qualitative', number=mapsi... |
def __init__(self, model: Optional[str]='bert-large-uncased', custom_model: PreTrainedModel=None, custom_tokenizer: PreTrainedTokenizer=None, hidden: Union[(List[int], int)]=(- 2), reduce_option: str='mean', sentence_handler: SentenceHandler=SentenceHandler(), random_state: int=12345, hidden_concat: bool=False, gpu_id:... | -3,580,805,947,633,973,000 | This is the parent Bert Summarizer model. New methods should implement this class.
:param model: This parameter is associated with the inherit string parameters from the transformers library.
:param custom_model: If you have a pre-trained model, you can add the model class here.
:param custom_tokenizer: If you have a ... | summarizer/bert.py | __init__ | SelvinDatatonic/bert-extractive-summarizer | python | def __init__(self, model: Optional[str]='bert-large-uncased', custom_model: PreTrainedModel=None, custom_tokenizer: PreTrainedTokenizer=None, hidden: Union[(List[int], int)]=(- 2), reduce_option: str='mean', sentence_handler: SentenceHandler=SentenceHandler(), random_state: int=12345, hidden_concat: bool=False, gpu_id:... |
def __init__(self, model: str='bert-large-uncased', custom_model: PreTrainedModel=None, custom_tokenizer: PreTrainedTokenizer=None, hidden: Union[(List[int], int)]=(- 2), reduce_option: str='mean', sentence_handler: SentenceHandler=SentenceHandler(), random_state: int=12345, hidden_concat: bool=False, gpu_id: int=0):
... | -517,203,160,611,884,800 | This is the main Bert Summarizer class.
:param model: This parameter is associated with the inherit string parameters from the transformers library.
:param custom_model: If you have a pre-trained model, you can add the model class here.
:param custom_tokenizer: If you have a custom tokenizer, you can add the tokenizer... | summarizer/bert.py | __init__ | SelvinDatatonic/bert-extractive-summarizer | python | def __init__(self, model: str='bert-large-uncased', custom_model: PreTrainedModel=None, custom_tokenizer: PreTrainedTokenizer=None, hidden: Union[(List[int], int)]=(- 2), reduce_option: str='mean', sentence_handler: SentenceHandler=SentenceHandler(), random_state: int=12345, hidden_concat: bool=False, gpu_id: int=0):
... |
def __init__(self, transformer_type: str='Bert', transformer_model_key: str='bert-base-uncased', transformer_tokenizer_key: str=None, hidden: Union[(List[int], int)]=(- 2), reduce_option: str='mean', sentence_handler: SentenceHandler=SentenceHandler(), random_state: int=12345, hidden_concat: bool=False, gpu_id: int=0):... | 8,566,804,421,610,568,000 | :param transformer_type: The Transformer type, such as Bert, GPT2, DistilBert, etc.
:param transformer_model_key: The transformer model key. This is the directory for the model.
:param transformer_tokenizer_key: The transformer tokenizer key. This is the tokenizer directory.
:param hidden: The hidden output layers to u... | summarizer/bert.py | __init__ | SelvinDatatonic/bert-extractive-summarizer | python | def __init__(self, transformer_type: str='Bert', transformer_model_key: str='bert-base-uncased', transformer_tokenizer_key: str=None, hidden: Union[(List[int], int)]=(- 2), reduce_option: str='mean', sentence_handler: SentenceHandler=SentenceHandler(), random_state: int=12345, hidden_concat: bool=False, gpu_id: int=0):... |
def fit_predict(self, graph, weights):
"Fits model to a given graph and weights list\n\n Sets :code:`self.model_` to the state of graphtool's Stochastic Block Model the after fitting.\n\n Attributes\n ----------\n graph: graphtool.Graph\n the graph to fit the model to\n ... | -5,015,516,649,301,911,000 | Fits model to a given graph and weights list
Sets :code:`self.model_` to the state of graphtool's Stochastic Block Model the after fitting.
Attributes
----------
graph: graphtool.Graph
the graph to fit the model to
weights: graphtool.EdgePropertyMap<double>
the property map: edge -> weight (double) to fit the... | yyskmultilearn/cluster/graphtool.py | fit_predict | yuan776/scikit-multilearn | python | def fit_predict(self, graph, weights):
"Fits model to a given graph and weights list\n\n Sets :code:`self.model_` to the state of graphtool's Stochastic Block Model the after fitting.\n\n Attributes\n ----------\n graph: graphtool.Graph\n the graph to fit the model to\n ... |
def fit_predict(self, X, y):
"Performs clustering on y and returns list of label lists\n\n Builds a label graph using the provided graph builder's `transform` method\n on `y` and then detects communities using the selected `method`.\n\n Sets :code:`self.weights_` and :code:`self.graph_`.\n\n ... | 6,311,946,468,977,824,000 | Performs clustering on y and returns list of label lists
Builds a label graph using the provided graph builder's `transform` method
on `y` and then detects communities using the selected `method`.
Sets :code:`self.weights_` and :code:`self.graph_`.
Parameters
----------
X : None
currently unused, left for scikit... | yyskmultilearn/cluster/graphtool.py | fit_predict | yuan776/scikit-multilearn | python | def fit_predict(self, X, y):
"Performs clustering on y and returns list of label lists\n\n Builds a label graph using the provided graph builder's `transform` method\n on `y` and then detects communities using the selected `method`.\n\n Sets :code:`self.weights_` and :code:`self.graph_`.\n\n ... |
def __init__(self, x=0, y=0):
'\n Método de inicialização da classe. Deve inicializar os parâmetros x, y, caracter e status\n\n :param x: Posição horizontal inicial do ator\n :param y: Posição vertical inicial do ator\n '
self.y = y
self.x = x
self.status = ATIVO | 5,349,596,299,584,515,000 | Método de inicialização da classe. Deve inicializar os parâmetros x, y, caracter e status
:param x: Posição horizontal inicial do ator
:param y: Posição vertical inicial do ator | atores.py | __init__ | NTMaia/pythonbirds | python | def __init__(self, x=0, y=0):
'\n Método de inicialização da classe. Deve inicializar os parâmetros x, y, caracter e status\n\n :param x: Posição horizontal inicial do ator\n :param y: Posição vertical inicial do ator\n '
self.y = y
self.x = x
self.status = ATIVO |
def calcular_posicao(self, tempo):
'\n Método que calcula a posição do ator em determinado tempo.\n Deve-se imaginar que o tempo começa em 0 e avança de 0,01 segundos\n\n :param tempo: o tempo do jogo\n :return: posição x, y do ator\n '
return (self.x, self.y) | -765,579,988,735,161,700 | Método que calcula a posição do ator em determinado tempo.
Deve-se imaginar que o tempo começa em 0 e avança de 0,01 segundos
:param tempo: o tempo do jogo
:return: posição x, y do ator | atores.py | calcular_posicao | NTMaia/pythonbirds | python | def calcular_posicao(self, tempo):
'\n Método que calcula a posição do ator em determinado tempo.\n Deve-se imaginar que o tempo começa em 0 e avança de 0,01 segundos\n\n :param tempo: o tempo do jogo\n :return: posição x, y do ator\n '
return (self.x, self.y) |
def colidir(self, outro_ator, intervalo=1):
'\n Método que executa lógica de colisão entre dois atores.\n Só deve haver colisão se os dois atores tiverem seus status ativos.\n Para colisão, é considerado um quadrado, com lado igual ao parâmetro intervalo, em volta do ponto onde se\n enco... | 8,285,704,329,622,607,000 | Método que executa lógica de colisão entre dois atores.
Só deve haver colisão se os dois atores tiverem seus status ativos.
Para colisão, é considerado um quadrado, com lado igual ao parâmetro intervalo, em volta do ponto onde se
encontra o ator. Se os atores estiverem dentro desse mesmo quadrado, seus status devem ser... | atores.py | colidir | NTMaia/pythonbirds | python | def colidir(self, outro_ator, intervalo=1):
'\n Método que executa lógica de colisão entre dois atores.\n Só deve haver colisão se os dois atores tiverem seus status ativos.\n Para colisão, é considerado um quadrado, com lado igual ao parâmetro intervalo, em volta do ponto onde se\n enco... |
def __init__(self, x=0, y=0):
'\n Método de inicialização de pássaro.\n\n Deve chamar a inicialização de ator. Além disso, deve armazenar a posição inicial e incializar o tempo de\n lançamento e angulo de lançamento\n\n :param x:\n :param y:\n '
super().__init__(x, y)
... | 1,180,524,789,762,413,600 | Método de inicialização de pássaro.
Deve chamar a inicialização de ator. Além disso, deve armazenar a posição inicial e incializar o tempo de
lançamento e angulo de lançamento
:param x:
:param y: | atores.py | __init__ | NTMaia/pythonbirds | python | def __init__(self, x=0, y=0):
'\n Método de inicialização de pássaro.\n\n Deve chamar a inicialização de ator. Além disso, deve armazenar a posição inicial e incializar o tempo de\n lançamento e angulo de lançamento\n\n :param x:\n :param y:\n '
super().__init__(x, y)
... |
def foi_lancado(self):
'\n Método que retorna verdaeira se o pássaro já foi lançado e falso caso contrário\n\n :return: booleano\n '
return (not (self._tempo_de_lancamento is None)) | 1,224,626,318,226,593,300 | Método que retorna verdaeira se o pássaro já foi lançado e falso caso contrário
:return: booleano | atores.py | foi_lancado | NTMaia/pythonbirds | python | def foi_lancado(self):
'\n Método que retorna verdaeira se o pássaro já foi lançado e falso caso contrário\n\n :return: booleano\n '
return (not (self._tempo_de_lancamento is None)) |
def colidir_com_chao(self):
'\n Método que executa lógica de colisão com o chão. Toda vez que y for menor ou igual a 0,\n o status dos Passaro deve ser alterado para destruido, bem como o seu caracter\n\n '
pass | 3,603,915,454,034,998,300 | Método que executa lógica de colisão com o chão. Toda vez que y for menor ou igual a 0,
o status dos Passaro deve ser alterado para destruido, bem como o seu caracter | atores.py | colidir_com_chao | NTMaia/pythonbirds | python | def colidir_com_chao(self):
'\n Método que executa lógica de colisão com o chão. Toda vez que y for menor ou igual a 0,\n o status dos Passaro deve ser alterado para destruido, bem como o seu caracter\n\n '
pass |
def calcular_posicao(self, tempo):
'\n Método que cálcula a posição do passaro de acordo com o tempo.\n\n Antes do lançamento o pássaro deve retornar o valor de sua posição inicial\n\n Depois do lançamento o pássaro deve calcular de acordo com sua posição inicial, velocidade escalar,\n â... | -5,593,341,986,273,874,000 | Método que cálcula a posição do passaro de acordo com o tempo.
Antes do lançamento o pássaro deve retornar o valor de sua posição inicial
Depois do lançamento o pássaro deve calcular de acordo com sua posição inicial, velocidade escalar,
ângulo de lancamento, gravidade (constante GRAVIDADE) e o tempo do jogo.
Após a... | atores.py | calcular_posicao | NTMaia/pythonbirds | python | def calcular_posicao(self, tempo):
'\n Método que cálcula a posição do passaro de acordo com o tempo.\n\n Antes do lançamento o pássaro deve retornar o valor de sua posição inicial\n\n Depois do lançamento o pássaro deve calcular de acordo com sua posição inicial, velocidade escalar,\n â... |
def lancar(self, angulo, tempo_de_lancamento):
'\n Lógica que lança o pássaro. Deve armazenar o ângulo e o tempo de lançamento para posteriores cálculo.\n O ângulo é passado em graus e deve ser transformado em radianos\n\n :param angulo:\n :param tempo_de_lancamento:\n :return:\n ... | 3,750,786,522,094,327,000 | Lógica que lança o pássaro. Deve armazenar o ângulo e o tempo de lançamento para posteriores cálculo.
O ângulo é passado em graus e deve ser transformado em radianos
:param angulo:
:param tempo_de_lancamento:
:return: | atores.py | lancar | NTMaia/pythonbirds | python | def lancar(self, angulo, tempo_de_lancamento):
'\n Lógica que lança o pássaro. Deve armazenar o ângulo e o tempo de lançamento para posteriores cálculo.\n O ângulo é passado em graus e deve ser transformado em radianos\n\n :param angulo:\n :param tempo_de_lancamento:\n :return:\n ... |
def _fetch_repos_file(url, filename, job):
'Use curl to fetch a repos file and display the contents.'
job.run(['curl', '-skL', url, '-o', filename])
log(('@{bf}==>@| Contents of `%s`:' % filename))
with open(filename, 'r') as f:
print(f.read()) | -366,778,116,241,786,200 | Use curl to fetch a repos file and display the contents. | ros2_batch_job/__main__.py | _fetch_repos_file | jlblancoc/ci | python | def _fetch_repos_file(url, filename, job):
job.run(['curl', '-skL', url, '-o', filename])
log(('@{bf}==>@| Contents of `%s`:' % filename))
with open(filename, 'r') as f:
print(f.read()) |
@contextmanager
def context_session(self) -> Iterator[SqlSession]:
'Override base method to include exception handling.'
try:
(yield from self.get_db())
except sa.exc.StatementError as e:
if isinstance(e.orig, psycopg2.errors.UniqueViolation):
raise errors.ConflictError('resource... | -4,033,125,691,219,364,000 | Override base method to include exception handling. | stac_fastapi/sqlalchemy/stac_fastapi/sqlalchemy/session.py | context_session | AsgerPetersen/stac-fastapi | python | @contextmanager
def context_session(self) -> Iterator[SqlSession]:
try:
(yield from self.get_db())
except sa.exc.StatementError as e:
if isinstance(e.orig, psycopg2.errors.UniqueViolation):
raise errors.ConflictError('resource already exists') from e
elif isinstance(e.or... |
@classmethod
def create_from_env(cls):
'Create from environment.'
return cls(reader_conn_string=os.environ['READER_CONN_STRING'], writer_conn_string=os.environ['WRITER_CONN_STRING']) | 5,541,047,790,610,243,000 | Create from environment. | stac_fastapi/sqlalchemy/stac_fastapi/sqlalchemy/session.py | create_from_env | AsgerPetersen/stac-fastapi | python | @classmethod
def create_from_env(cls):
return cls(reader_conn_string=os.environ['READER_CONN_STRING'], writer_conn_string=os.environ['WRITER_CONN_STRING']) |
@classmethod
def create_from_settings(cls, settings: SqlalchemySettings) -> 'Session':
'Create a Session object from settings.'
return cls(reader_conn_string=settings.reader_connection_string, writer_conn_string=settings.writer_connection_string) | 591,955,616,614,499,500 | Create a Session object from settings. | stac_fastapi/sqlalchemy/stac_fastapi/sqlalchemy/session.py | create_from_settings | AsgerPetersen/stac-fastapi | python | @classmethod
def create_from_settings(cls, settings: SqlalchemySettings) -> 'Session':
return cls(reader_conn_string=settings.reader_connection_string, writer_conn_string=settings.writer_connection_string) |
def __attrs_post_init__(self):
'Post init handler.'
self.reader: FastAPISessionMaker = FastAPISessionMaker(self.reader_conn_string)
self.writer: FastAPISessionMaker = FastAPISessionMaker(self.writer_conn_string) | 9,184,957,250,236,342,000 | Post init handler. | stac_fastapi/sqlalchemy/stac_fastapi/sqlalchemy/session.py | __attrs_post_init__ | AsgerPetersen/stac-fastapi | python | def __attrs_post_init__(self):
self.reader: FastAPISessionMaker = FastAPISessionMaker(self.reader_conn_string)
self.writer: FastAPISessionMaker = FastAPISessionMaker(self.writer_conn_string) |
def MycobacteriumSp15544247(directed: bool=False, preprocess: bool=True, load_nodes: bool=True, verbose: int=2, cache: bool=True, cache_path: str='graphs/string', version: str='links.v11.5', **additional_graph_kwargs: Dict) -> Graph:
'Return new instance of the Mycobacterium sp. 1554424.7 graph.\n\n The graph is... | 7,044,234,832,566,808,000 | Return new instance of the Mycobacterium sp. 1554424.7 graph.
The graph is automatically retrieved from the STRING repository.
Parameters
-------------------
directed: bool = False
Wether to load the graph as directed or undirected.
By default false.
preprocess: bool = True
Whether to preprocess the g... | bindings/python/ensmallen/datasets/string/mycobacteriumsp15544247.py | MycobacteriumSp15544247 | AnacletoLAB/ensmallen | python | def MycobacteriumSp15544247(directed: bool=False, preprocess: bool=True, load_nodes: bool=True, verbose: int=2, cache: bool=True, cache_path: str='graphs/string', version: str='links.v11.5', **additional_graph_kwargs: Dict) -> Graph:
'Return new instance of the Mycobacterium sp. 1554424.7 graph.\n\n The graph is... |
@format_response
@handle_exceptions
async def get_tasks(self, request):
'\n ---\n description: get all tasks associated with the specified step.\n tags:\n - Tasks\n parameters:\n - name: "flow_id"\n in: "path"\n description: "flow_id"\n required: ... | 8,151,153,275,299,854,000 | ---
description: get all tasks associated with the specified step.
tags:
- Tasks
parameters:
- name: "flow_id"
in: "path"
description: "flow_id"
required: true
type: "string"
- name: "run_number"
in: "path"
description: "run_number"
required: true
type: "integer"
- name: "step_name"
in: "path"
descr... | metadata_service/api/task.py | get_tasks | ferras/metaflow-service-clone | python | @format_response
@handle_exceptions
async def get_tasks(self, request):
'\n ---\n description: get all tasks associated with the specified step.\n tags:\n - Tasks\n parameters:\n - name: "flow_id"\n in: "path"\n description: "flow_id"\n required: ... |
@format_response
@handle_exceptions
async def get_task(self, request):
'\n ---\n description: get all artifacts associated with the specified task.\n tags:\n - Tasks\n parameters:\n - name: "flow_id"\n in: "path"\n description: "flow_id"\n require... | -9,094,517,948,369,713,000 | ---
description: get all artifacts associated with the specified task.
tags:
- Tasks
parameters:
- name: "flow_id"
in: "path"
description: "flow_id"
required: true
type: "string"
- name: "run_number"
in: "path"
description: "run_number"
required: true
type: "integer"
- name: "step_name"
in: "path"
d... | metadata_service/api/task.py | get_task | ferras/metaflow-service-clone | python | @format_response
@handle_exceptions
async def get_task(self, request):
'\n ---\n description: get all artifacts associated with the specified task.\n tags:\n - Tasks\n parameters:\n - name: "flow_id"\n in: "path"\n description: "flow_id"\n require... |
@format_response
@handle_exceptions
async def create_task(self, request):
'\n ---\n description: This end-point allow to test that service is up.\n tags:\n - Tasks\n parameters:\n - name: "flow_id"\n in: "path"\n description: "flow_id"\n required:... | -7,596,690,592,353,255,000 | ---
description: This end-point allow to test that service is up.
tags:
- Tasks
parameters:
- name: "flow_id"
in: "path"
description: "flow_id"
required: true
type: "string"
- name: "run_number"
in: "path"
description: "run_number"
required: true
type: "integer"
- name: "step_name"
in: "path"
descri... | metadata_service/api/task.py | create_task | ferras/metaflow-service-clone | python | @format_response
@handle_exceptions
async def create_task(self, request):
'\n ---\n description: This end-point allow to test that service is up.\n tags:\n - Tasks\n parameters:\n - name: "flow_id"\n in: "path"\n description: "flow_id"\n required:... |
def csv_to_generator(csv_file_path):
'\n Parse your CSV file into generator\n '
for row in DictReader(open(csv_file_path, 'r')):
point = Point('financial-analysis').tag('type', 'vix-daily').field('open', float(row['VIX Open'])).field('high', float(row['VIX High'])).field('low', float(row['VIX Low'... | 8,230,420,822,704,317,000 | Parse your CSV file into generator | examples/asynchronous_batching.py | csv_to_generator | bonitoo-io/influxdb-client-python | python | def csv_to_generator(csv_file_path):
'\n \n '
for row in DictReader(open(csv_file_path, 'r')):
point = Point('financial-analysis').tag('type', 'vix-daily').field('open', float(row['VIX Open'])).field('high', float(row['VIX High'])).field('low', float(row['VIX Low'])).field('close', float(row['VIX ... |
async def async_write(batch):
'\n Prepare async task\n '
(await write_api.write(bucket='my-bucket', record=batch))
return batch | 3,711,358,592,541,441,000 | Prepare async task | examples/asynchronous_batching.py | async_write | bonitoo-io/influxdb-client-python | python | async def async_write(batch):
'\n \n '
(await write_api.write(bucket='my-bucket', record=batch))
return batch |
def __get_language_extensions(self):
'\n :returns: A directory of the considered language extensions\n '
return {'C++': self.cpp_extensions, 'C': self.c_extensions, 'Rust': self.rust_extensions, 'Ruby': self.ruby_extensions, 'Java': self.java_extensions, 'Go': self.go_extensions, 'PHP': self.php_e... | -3,165,527,756,211,458,000 | :returns: A directory of the considered language extensions | gitScrabber/scrabTasks/file/languageDetector.py | __get_language_extensions | Eyenseo/gitScrabber | python | def __get_language_extensions(self):
'\n \n '
return {'C++': self.cpp_extensions, 'C': self.c_extensions, 'Rust': self.rust_extensions, 'Ruby': self.ruby_extensions, 'Java': self.java_extensions, 'Go': self.go_extensions, 'PHP': self.php_extensions, 'JavaScript': self.js_extensions, 'Objective-C':... |
def __get_files_per_language(self):
'\n :returns: A default directory of the considered languages, their\n extensions and the amount of files that have that extension\n (default=0)\n '
return {'C++': {extension: 0 for extension in self.cpp_extensions}, 'C': {exten... | -689,377,611,099,756,500 | :returns: A default directory of the considered languages, their
extensions and the amount of files that have that extension
(default=0) | gitScrabber/scrabTasks/file/languageDetector.py | __get_files_per_language | Eyenseo/gitScrabber | python | def __get_files_per_language(self):
'\n :returns: A default directory of the considered languages, their\n extensions and the amount of files that have that extension\n (default=0)\n '
return {'C++': {extension: 0 for extension in self.cpp_extensions}, 'C': {exten... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.