repository_name stringclasses 316
values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1
value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1
value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
dshean/demcoreg | demcoreg/dem_mask.py | get_bareground_mask | python | def get_bareground_mask(bareground_ds, bareground_thresh=60, out_fn=None):
print("Loading bareground")
b = bareground_ds.GetRasterBand(1)
l = b.ReadAsArray()
print("Masking pixels with <%0.1f%% bare ground" % bareground_thresh)
if bareground_thresh < 0.0 or bareground_thresh > 100.0:
sys.exi... | Generate raster mask for exposed bare ground from global bareground data | train | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/dem_mask.py#L143-L158 | null | #! /usr/bin/env python
"""
Utility to automate reference surface identification for raster co-registration
Note: Initial run may take a long time to download and process required data (NLCD, global bareground, glacier polygons)
Can control location of these data files with DATADIR environmental variable
export DATAD... |
dshean/demcoreg | demcoreg/dem_mask.py | get_snodas_ds | python | def get_snodas_ds(dem_dt, code=1036):
import tarfile
import gzip
snodas_ds = None
snodas_url_str = None
outdir = os.path.join(datadir, 'snodas')
if not os.path.exists(outdir):
os.makedirs(outdir)
#Note: unmasked products (beyond CONUS) are only available from 2010-present
if de... | Function to fetch and process SNODAS snow depth products for input datetime
http://nsidc.org/data/docs/noaa/g02158_snodas_snow_cover_model/index.html
Product codes:
1036 is snow depth
1034 is SWE
filename format: us_ssmv11036tS__T0001TTNATS2015042205HP001.Hdr | train | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/dem_mask.py#L160-L228 | null | #! /usr/bin/env python
"""
Utility to automate reference surface identification for raster co-registration
Note: Initial run may take a long time to download and process required data (NLCD, global bareground, glacier polygons)
Can control location of these data files with DATADIR environmental variable
export DATAD... |
dshean/demcoreg | demcoreg/dem_mask.py | get_modis_tile_list | python | def get_modis_tile_list(ds):
from demcoreg import modis_grid
modis_dict = {}
for key in modis_grid.modis_dict:
modis_dict[key] = ogr.CreateGeometryFromWkt(modis_grid.modis_dict[key])
geom = geolib.ds_geom(ds)
geom_dup = geolib.geom_dup(geom)
ct = osr.CoordinateTransformation(geom_dup.Get... | Helper function to identify MODIS tiles that intersect input geometry
modis_gird.py contains dictionary of tile boundaries (tile name and WKT polygon ring from bbox)
See: https://modis-land.gsfc.nasa.gov/MODLAND_grid.html | train | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/dem_mask.py#L230-L249 | null | #! /usr/bin/env python
"""
Utility to automate reference surface identification for raster co-registration
Note: Initial run may take a long time to download and process required data (NLCD, global bareground, glacier polygons)
Can control location of these data files with DATADIR environmental variable
export DATAD... |
dshean/demcoreg | demcoreg/dem_mask.py | get_modscag_fn_list | python | def get_modscag_fn_list(dem_dt, tile_list=('h08v04', 'h09v04', 'h10v04', 'h08v05', 'h09v05'), pad_days=7):
#Could also use global MODIS 500 m snowcover grids, 8 day
#http://nsidc.org/data/docs/daac/modis_v5/mod10a2_modis_terra_snow_8-day_global_500m_grid.gd.html
#These are HDF4, sinusoidal
#Should be a... | Function to fetch and process MODSCAG fractional snow cover products for input datetime
Products are tiled in MODIS sinusoidal projection
example url: https://snow-data.jpl.nasa.gov/modscag-historic/2015/001/MOD09GA.A2015001.h07v03.005.2015006001833.snow_fraction.tif | train | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/dem_mask.py#L251-L331 | null | #! /usr/bin/env python
"""
Utility to automate reference surface identification for raster co-registration
Note: Initial run may take a long time to download and process required data (NLCD, global bareground, glacier polygons)
Can control location of these data files with DATADIR environmental variable
export DATAD... |
dshean/demcoreg | demcoreg/dem_mask.py | proc_modscag | python | def proc_modscag(fn_list, extent=None, t_srs=None):
#Use cubic spline here for improve upsampling
ds_list = warplib.memwarp_multi_fn(fn_list, res='min', extent=extent, t_srs=t_srs, r='cubicspline')
stack_fn = os.path.splitext(fn_list[0])[0] + '_' + os.path.splitext(os.path.split(fn_list[-1])[1])[0] + '_sta... | Process the MODSCAG products for full date range, create composites and reproject | train | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/dem_mask.py#L333-L362 | null | #! /usr/bin/env python
"""
Utility to automate reference surface identification for raster co-registration
Note: Initial run may take a long time to download and process required data (NLCD, global bareground, glacier polygons)
Can control location of these data files with DATADIR environmental variable
export DATAD... |
dshean/demcoreg | demcoreg/coreglib.py | apply_xy_shift | python | def apply_xy_shift(ds, dx, dy, createcopy=True):
print("X shift: ", dx)
print("Y shift: ", dy)
#Update geotransform
gt_orig = ds.GetGeoTransform()
gt_shift = np.copy(gt_orig)
gt_shift[0] += dx
gt_shift[3] += dy
print("Original geotransform:", gt_orig)
print("Updated geotransfor... | Apply horizontal shift to GDAL dataset GeoTransform
Returns:
GDAL Dataset copy with updated GeoTransform | train | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/coreglib.py#L14-L40 | null | #! /usr/bin/env python
"""
Library of functions that can be used for co-registration of raster data
For many situations, ASP pc_align ICP co-registration is superior to these approaches. See pc_align_wrapper.sh
"""
import sys
import numpy as np
import matplotlib.pyplot as plt
from pygeotools.lib import malib, iolib
... |
dshean/demcoreg | demcoreg/coreglib.py | compute_offset_sad | python | def compute_offset_sad(dem1, dem2, pad=(9,9), plot=False):
#This defines the search window size
#Use half-pixel stride?
#Note: stride is not properly implemented
#stride = 1
#ref = dem1[::stride,::stride]
#kernel = dem2[pad[0]:-pad[0]:stride, pad[1]:-pad[1]:stride]
kernel = dem2[pad[0]:-pad... | Compute subpixel horizontal offset between input rasters using sum of absolute differences (SAD) method | train | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/coreglib.py#L65-L115 | [
"def find_subpixel_peak_position(corr, subpixel_method='gaussian'):\n \"\"\"\n Find subpixel approximation of the correlation peak.\n\n This function returns a subpixels approximation of the correlation\n peak by using one of the several methods available. If requested, \n the function also returns t... | #! /usr/bin/env python
"""
Library of functions that can be used for co-registration of raster data
For many situations, ASP pc_align ICP co-registration is superior to these approaches. See pc_align_wrapper.sh
"""
import sys
import numpy as np
import matplotlib.pyplot as plt
from pygeotools.lib import malib, iolib
... |
dshean/demcoreg | demcoreg/coreglib.py | compute_offset_ncc | python | def compute_offset_ncc(dem1, dem2, pad=(9,9), prefilter=False, plot=False):
#Apply edge detection filter up front - improves results when input DEMs are same resolution
if prefilter:
print("Applying LoG edge-detection filter to DEMs")
sigma = 1
import scipy.ndimage
#Note, ndimag... | Compute horizontal offset between input rasters using normalized cross-correlation (NCC) method | train | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/coreglib.py#L118-L198 | [
"def find_subpixel_peak_position(corr, subpixel_method='gaussian'):\n \"\"\"\n Find subpixel approximation of the correlation peak.\n\n This function returns a subpixels approximation of the correlation\n peak by using one of the several methods available. If requested, \n the function also returns t... | #! /usr/bin/env python
"""
Library of functions that can be used for co-registration of raster data
For many situations, ASP pc_align ICP co-registration is superior to these approaches. See pc_align_wrapper.sh
"""
import sys
import numpy as np
import matplotlib.pyplot as plt
from pygeotools.lib import malib, iolib
... |
dshean/demcoreg | demcoreg/coreglib.py | compute_offset_nuth | python | def compute_offset_nuth(dh, slope, aspect, min_count=100, remove_outliers=True, plot=True):
import scipy.optimize as optimization
if dh.count() < min_count:
sys.exit("Not enough dh samples")
if slope.count() < min_count:
sys.exit("Not enough slope/aspect samples")
#mean_dh = dh.mean()
... | Compute horizontal offset between input rasters using Nuth and Kaab [2011] (nuth) method | train | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/coreglib.py#L201-L373 | [
"def nuth_func(x, a, b, c):\n y = a * np.cos(np.deg2rad(b-x)) + c\n #Can use Phasor addition, but need to change conversion to offset dx and dy\n #https://stackoverflow.com/questions/12397412/i-know-scipy-curve-fit-can-do-better?rq=1\n #y = a * np.cos(np.deg2rad(x)) + b * np.sin(np.deg2rad(x)) + c\n ... | #! /usr/bin/env python
"""
Library of functions that can be used for co-registration of raster data
For many situations, ASP pc_align ICP co-registration is superior to these approaches. See pc_align_wrapper.sh
"""
import sys
import numpy as np
import matplotlib.pyplot as plt
from pygeotools.lib import malib, iolib
... |
dshean/demcoreg | demcoreg/coreglib.py | find_first_peak | python | def find_first_peak(corr):
"""
Find row and column indices of the first correlation peak.
Parameters
----------
corr : np.ndarray
the correlation map
Returns
-------
i : int
the row index of the correlation peak
j : int
the column index ... | Find row and column indices of the first correlation peak.
Parameters
----------
corr : np.ndarray
the correlation map
Returns
-------
i : int
the row index of the correlation peak
j : int
the column index of the correlation peak
co... | train | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/coreglib.py#L387-L416 | null | #! /usr/bin/env python
"""
Library of functions that can be used for co-registration of raster data
For many situations, ASP pc_align ICP co-registration is superior to these approaches. See pc_align_wrapper.sh
"""
import sys
import numpy as np
import matplotlib.pyplot as plt
from pygeotools.lib import malib, iolib
... |
dshean/demcoreg | demcoreg/coreglib.py | find_subpixel_peak_position | python | def find_subpixel_peak_position(corr, subpixel_method='gaussian'):
# initialization
default_peak_position = (corr.shape[0]/2,corr.shape[1]/2)
# the peak locations
peak1_i, peak1_j, dummy = find_first_peak(corr)
try:
# the peak and its neighbours: left, right, down, up
c = corr[... | Find subpixel approximation of the correlation peak.
This function returns a subpixels approximation of the correlation
peak by using one of the several methods available. If requested,
the function also returns the signal to noise ratio level evaluated
from the correlation map.
Paramete... | train | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/coreglib.py#L419-L485 | [
"def find_first_peak(corr):\n \"\"\"\n Find row and column indices of the first correlation peak.\n\n Parameters\n ----------\n corr : np.ndarray\n the correlation map\n\n Returns\n -------\n i : int\n the row index of the correlation peak\n\n j : int\n the column ind... | #! /usr/bin/env python
"""
Library of functions that can be used for co-registration of raster data
For many situations, ASP pc_align ICP co-registration is superior to these approaches. See pc_align_wrapper.sh
"""
import sys
import numpy as np
import matplotlib.pyplot as plt
from pygeotools.lib import malib, iolib
... |
dshean/demcoreg | demcoreg/pc_align_error_analysis.py | main | python | def main():
#filenames = !ls *align/*reference-DEM.tif
#run ~/src/demtools/error_analysis.py $filenames.s
if len(sys.argv) < 1:
sys.exit('No input files provided')
fn_list = sys.argv[1:]
n_samp = len(fn_list)
error_dict_list = []
for fn in fn_list:
ed = parse_pc_align_log(... | #ECEF translations
#key = 'Translation vector (ECEF meters)'
key = 'Translation vector (Cartesian, meters)'
#key = 'Translation vector (meters)'
val = np.array([e[key] for e in error_dict_list])
#make_plot3d(val[:,0], val[:,1], val[:,2], title=key)
ce90 = geolib.CE90(val[:,0], val[:,1])
le90... | train | https://github.com/dshean/demcoreg/blob/abd6be75d326b35f52826ee30dff01f9e86b4b52/demcoreg/pc_align_error_analysis.py#L315-L611 | [
"def make_plot3d(x, y, z, title=None, orthogonal_fig=True):\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n ax.set_aspect('equal')\n ax.set_xlabel('X offset (m)')\n ax.set_ylabel('Y offset (m)')\n ax.set_zlabel('Z offset (m)')\n if title is not None:\n plt.suptitle(ti... | #! /usr/bin/env python
#David Shean
#dshean@gmail.com
#Perform error analysis for DEM output from pc_align
import sys
import os
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from pygeotools.lib import timelib, geolib, malib
#shell
#filenames=$(ls WV*/dem*/*align/*-DEM.t... |
peterwittek/somoclu | src/Python/somoclu/train.py | _check_cooling_parameters | python | def _check_cooling_parameters(radiuscooling, scalecooling):
if radiuscooling != "linear" and radiuscooling != "exponential":
raise Exception("Invalid parameter for radiuscooling: " +
radiuscooling)
if scalecooling != "linear" and scalecooling != "exponential":
raise Excep... | Helper function to verify the cooling parameters of the training. | train | https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L663-L671 | null | # -*- coding: utf-8 -*-
"""
The module contains the Somoclu class that trains and visualizes
self-organizing maps and emergent self-organizing maps.
Created on Sun July 26 15:07:47 2015
@author: Peter Wittek
"""
from __future__ import division, print_function
import sys
import matplotlib.cm as cm
import matplotlib.py... |
peterwittek/somoclu | src/Python/somoclu/train.py | _hexplot | python | def _hexplot(matrix, fig, colormap):
umatrix_min = matrix.min()
umatrix_max = matrix.max()
n_rows, n_columns = matrix.shape
cmap = plt.get_cmap(colormap)
offsets = np.zeros((n_columns * n_rows, 2))
facecolors = []
for row in range(n_rows):
for col in range(n_columns):
if ... | Internal function to plot a hexagonal map. | train | https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L674-L713 | null | # -*- coding: utf-8 -*-
"""
The module contains the Somoclu class that trains and visualizes
self-organizing maps and emergent self-organizing maps.
Created on Sun July 26 15:07:47 2015
@author: Peter Wittek
"""
from __future__ import division, print_function
import sys
import matplotlib.cm as cm
import matplotlib.py... |
peterwittek/somoclu | src/Python/somoclu/train.py | Somoclu.load_bmus | python | def load_bmus(self, filename):
self.bmus = np.loadtxt(filename, comments='%', usecols=(1, 2))
if self.n_vectors != 0 and len(self.bmus) != self.n_vectors:
raise Exception("The number of best matching units does not match "
"the number of data instances")
e... | Load the best matching units from a file to the Somoclu object.
:param filename: The name of the file.
:type filename: str. | train | https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L136-L154 | null | class Somoclu(object):
"""Class for training and visualizing a self-organizing map.
Attributes:
codebook The codebook of the self-organizing map.
bmus The BMUs corresponding to the data points.
:param n_columns: The number of columns in the map.
:type n_columns: int.
... |
peterwittek/somoclu | src/Python/somoclu/train.py | Somoclu.load_umatrix | python | def load_umatrix(self, filename):
self.umatrix = np.loadtxt(filename, comments='%')
if self.umatrix.shape != (self._n_rows, self._n_columns):
raise Exception("The dimensions of the U-matrix do not "
"match that of the map") | Load the umatrix from a file to the Somoclu object.
:param filename: The name of the file.
:type filename: str. | train | https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L156-L166 | null | class Somoclu(object):
"""Class for training and visualizing a self-organizing map.
Attributes:
codebook The codebook of the self-organizing map.
bmus The BMUs corresponding to the data points.
:param n_columns: The number of columns in the map.
:type n_columns: int.
... |
peterwittek/somoclu | src/Python/somoclu/train.py | Somoclu.load_codebook | python | def load_codebook(self, filename):
self.codebook = np.loadtxt(filename, comments='%')
if self.n_dim == 0:
self.n_dim = self.codebook.shape[1]
if self.codebook.shape != (self._n_rows * self._n_columns,
self.n_dim):
raise Exception("The di... | Load the codebook from a file to the Somoclu object.
:param filename: The name of the file.
:type filename: str. | train | https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L168-L181 | null | class Somoclu(object):
"""Class for training and visualizing a self-organizing map.
Attributes:
codebook The codebook of the self-organizing map.
bmus The BMUs corresponding to the data points.
:param n_columns: The number of columns in the map.
:type n_columns: int.
... |
peterwittek/somoclu | src/Python/somoclu/train.py | Somoclu.train | python | def train(self, data=None, epochs=10, radius0=0, radiusN=1,
radiuscooling="linear",
scale0=0.1, scaleN=0.01, scalecooling="linear"):
_check_cooling_parameters(radiuscooling, scalecooling)
if self._data is None and data is None:
raise Exception("No data was provide... | Train the map on the current data in the Somoclu object.
:param data: Optional parameter to provide training data. It is not
necessary if the data was added via the method
`update_data`.
:type data: 2D numpy.array of float32.
:param epochs: The number of... | train | https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L183-L231 | [
"def _check_cooling_parameters(radiuscooling, scalecooling):\n \"\"\"Helper function to verify the cooling parameters of the training.\n \"\"\"\n if radiuscooling != \"linear\" and radiuscooling != \"exponential\":\n raise Exception(\"Invalid parameter for radiuscooling: \" +\n ... | class Somoclu(object):
"""Class for training and visualizing a self-organizing map.
Attributes:
codebook The codebook of the self-organizing map.
bmus The BMUs corresponding to the data points.
:param n_columns: The number of columns in the map.
:type n_columns: int.
... |
peterwittek/somoclu | src/Python/somoclu/train.py | Somoclu.update_data | python | def update_data(self, data):
oldn_dim = self.n_dim
if data.dtype != np.float32:
print("Warning: data was not float32. A 32-bit copy was made")
self._data = np.float32(data)
else:
self._data = data
self.n_vectors, self.n_dim = data.shape
if self... | Change the data set in the Somoclu object. It is useful when the
data is updated and the training should continue on the new data.
:param data: The training data.
:type data: 2D numpy.array of float32. | train | https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L233-L249 | null | class Somoclu(object):
"""Class for training and visualizing a self-organizing map.
Attributes:
codebook The codebook of the self-organizing map.
bmus The BMUs corresponding to the data points.
:param n_columns: The number of columns in the map.
:type n_columns: int.
... |
peterwittek/somoclu | src/Python/somoclu/train.py | Somoclu.view_component_planes | python | def view_component_planes(self, dimensions=None, figsize=None,
colormap=cm.Spectral_r, colorbar=False,
bestmatches=False, bestmatchcolors=None,
labels=None, zoom=None, filename=None):
if self.codebook is None:
... | Observe the component planes in the codebook of the SOM.
:param dimensions: Optional parameter to specify along which dimension
or dimensions should the plotting happen. By
default, each dimension is plotted in a sequence of
plots... | train | https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L251-L293 | [
"def _view_matrix(self, matrix, figsize, colormap, colorbar, bestmatches,\n bestmatchcolors, labels, zoom, filename):\n \"\"\"Internal function to plot a map with best matching units and labels.\n \"\"\"\n if zoom is None:\n zoom = ((0, self._n_rows), (0, self._n_columns))\n if fi... | class Somoclu(object):
"""Class for training and visualizing a self-organizing map.
Attributes:
codebook The codebook of the self-organizing map.
bmus The BMUs corresponding to the data points.
:param n_columns: The number of columns in the map.
:type n_columns: int.
... |
peterwittek/somoclu | src/Python/somoclu/train.py | Somoclu.view_umatrix | python | def view_umatrix(self, figsize=None, colormap=cm.Spectral_r,
colorbar=False, bestmatches=False, bestmatchcolors=None,
labels=None, zoom=None, filename=None):
if self.umatrix is None:
raise Exception("The U-matrix is not available. Either train a map"
... | Plot the U-matrix of the trained map.
:param figsize: Optional parameter to specify the size of the figure.
:type figsize: (int, int)
:param colormap: Optional parameter to specify the color map to be
used.
:type colormap: matplotlib.colors.Colormap
:par... | train | https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L295-L327 | [
"def _view_matrix(self, matrix, figsize, colormap, colorbar, bestmatches,\n bestmatchcolors, labels, zoom, filename):\n \"\"\"Internal function to plot a map with best matching units and labels.\n \"\"\"\n if zoom is None:\n zoom = ((0, self._n_rows), (0, self._n_columns))\n if fi... | class Somoclu(object):
"""Class for training and visualizing a self-organizing map.
Attributes:
codebook The codebook of the self-organizing map.
bmus The BMUs corresponding to the data points.
:param n_columns: The number of columns in the map.
:type n_columns: int.
... |
peterwittek/somoclu | src/Python/somoclu/train.py | Somoclu.view_activation_map | python | def view_activation_map(self, data_vector=None, data_index=None,
activation_map=None, figsize=None,
colormap=cm.Spectral_r, colorbar=False,
bestmatches=False, bestmatchcolors=None,
labels=None, zoom=None, fil... | Plot the activation map of a given data instance or a new data
vector
:param data_vector: Optional parameter for a new vector
:type data_vector: numpy.array
:param data_index: Optional parameter for the index of the data instance
:type data_index: int.
:param activation_... | train | https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L329-L397 | [
"def _view_matrix(self, matrix, figsize, colormap, colorbar, bestmatches,\n bestmatchcolors, labels, zoom, filename):\n \"\"\"Internal function to plot a map with best matching units and labels.\n \"\"\"\n if zoom is None:\n zoom = ((0, self._n_rows), (0, self._n_columns))\n if fi... | class Somoclu(object):
"""Class for training and visualizing a self-organizing map.
Attributes:
codebook The codebook of the self-organizing map.
bmus The BMUs corresponding to the data points.
:param n_columns: The number of columns in the map.
:type n_columns: int.
... |
peterwittek/somoclu | src/Python/somoclu/train.py | Somoclu._view_matrix | python | def _view_matrix(self, matrix, figsize, colormap, colorbar, bestmatches,
bestmatchcolors, labels, zoom, filename):
if zoom is None:
zoom = ((0, self._n_rows), (0, self._n_columns))
if figsize is None:
figsize = (8, 8 / float(zoom[1][1] / zoom[0][1]))
... | Internal function to plot a map with best matching units and labels. | train | https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L399-L456 | [
"def _hexplot(matrix, fig, colormap):\n \"\"\"Internal function to plot a hexagonal map.\n \"\"\"\n umatrix_min = matrix.min()\n umatrix_max = matrix.max()\n n_rows, n_columns = matrix.shape\n cmap = plt.get_cmap(colormap)\n offsets = np.zeros((n_columns * n_rows, 2))\n facecolors = []\n ... | class Somoclu(object):
"""Class for training and visualizing a self-organizing map.
Attributes:
codebook The codebook of the self-organizing map.
bmus The BMUs corresponding to the data points.
:param n_columns: The number of columns in the map.
:type n_columns: int.
... |
peterwittek/somoclu | src/Python/somoclu/train.py | Somoclu._check_parameters | python | def _check_parameters(self):
if self._map_type != "planar" and self._map_type != "toroid":
raise Exception("Invalid parameter for _map_type: " +
self._map_type)
if self._grid_type != "rectangular" and self._grid_type != "hexagonal":
raise Exception("In... | Internal function to verify the basic parameters of the SOM. | train | https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L466-L483 | null | class Somoclu(object):
"""Class for training and visualizing a self-organizing map.
Attributes:
codebook The codebook of the self-organizing map.
bmus The BMUs corresponding to the data points.
:param n_columns: The number of columns in the map.
:type n_columns: int.
... |
peterwittek/somoclu | src/Python/somoclu/train.py | Somoclu._init_codebook | python | def _init_codebook(self):
codebook_size = self._n_columns * self._n_rows * self.n_dim
if self.codebook is None:
if self._initialization == "random":
self.codebook = np.zeros(codebook_size, dtype=np.float32)
self.codebook[0:2] = [1000, 2000]
else:
... | Internal function to set the codebook or to indicate it to the C++
code that it should be randomly initialized. | train | https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L511-L529 | [
"def _pca_init(self):\n try:\n from sklearn.decomposition import PCA\n pca = PCA(n_components=2, svd_solver=\"randomized\")\n except:\n from sklearn.decomposition import RandomizedPCA\n pca = RandomizedPCA(n_components=2)\n coord = np.zeros((self._n_columns * self._n_rows, 2))\n... | class Somoclu(object):
"""Class for training and visualizing a self-organizing map.
Attributes:
codebook The codebook of the self-organizing map.
bmus The BMUs corresponding to the data points.
:param n_columns: The number of columns in the map.
:type n_columns: int.
... |
peterwittek/somoclu | src/Python/somoclu/train.py | Somoclu.cluster | python | def cluster(self, algorithm=None):
import sklearn.base
if algorithm is None:
import sklearn.cluster
algorithm = sklearn.cluster.KMeans()
elif not isinstance(algorithm, sklearn.base.ClusterMixin):
raise Exception("Cannot use algorithm of type " + type(algorith... | Cluster the codebook. The clusters of the data instances can be
assigned based on the BMUs. The method populates the class variable
Somoclu.clusters. If viewing methods are called after clustering, but
without colors for best matching units, colors will be automatically
assigned based on... | train | https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L531-L556 | null | class Somoclu(object):
"""Class for training and visualizing a self-organizing map.
Attributes:
codebook The codebook of the self-organizing map.
bmus The BMUs corresponding to the data points.
:param n_columns: The number of columns in the map.
:type n_columns: int.
... |
peterwittek/somoclu | src/Python/somoclu/train.py | Somoclu.get_surface_state | python | def get_surface_state(self, data=None):
if data is None:
d = self._data
else:
d = data
codebookReshaped = self.codebook.reshape(self.codebook.shape[0] * self.codebook.shape[1], self.codebook.shape[2])
parts = np.array_split(d, 200, axis=0)
am = np.empty(... | Return the Euclidean distance between codebook and data.
:param data: Optional parameter to specify data, otherwise the
data used previously to train the SOM is used.
:type data: 2D numpy.array of float32.
:returns: The the dot product of the codebook and the data.
... | train | https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L558-L582 | null | class Somoclu(object):
"""Class for training and visualizing a self-organizing map.
Attributes:
codebook The codebook of the self-organizing map.
bmus The BMUs corresponding to the data points.
:param n_columns: The number of columns in the map.
:type n_columns: int.
... |
peterwittek/somoclu | src/Python/somoclu/train.py | Somoclu.get_bmus | python | def get_bmus(self, activation_map):
Y, X = np.unravel_index(activation_map.argmin(axis=1),
(self._n_rows, self._n_columns))
return np.vstack((X, Y)).T | Returns Best Matching Units indexes of the activation map.
:param activation_map: Activation map computed with self.get_surface_state()
:type activation_map: 2D numpy.array
:returns: The bmus indexes corresponding to this activation map
(same as self.bmus for the training sam... | train | https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L584-L597 | null | class Somoclu(object):
"""Class for training and visualizing a self-organizing map.
Attributes:
codebook The codebook of the self-organizing map.
bmus The BMUs corresponding to the data points.
:param n_columns: The number of columns in the map.
:type n_columns: int.
... |
peterwittek/somoclu | src/Python/somoclu/train.py | Somoclu.view_similarity_matrix | python | def view_similarity_matrix(self, data=None, labels=None, figsize=None,
filename=None):
if not have_heatmap:
raise Exception("Import dependencies missing for viewing "
"similarity matrix. You must have seaborn and "
... | Plot the similarity map according to the activation map
:param data: Optional parameter for data points to calculate the
similarity with
:type data: numpy.array
:param figsize: Optional parameter to specify the size of the figure.
:type figsize: (int, int)
:... | train | https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/somoclu/train.py#L599-L660 | [
"def get_surface_state(self, data=None):\n \"\"\"Return the Euclidean distance between codebook and data.\n\n :param data: Optional parameter to specify data, otherwise the\n data used previously to train the SOM is used.\n :type data: 2D numpy.array of float32.\n\n :returns: The the dot... | class Somoclu(object):
"""Class for training and visualizing a self-organizing map.
Attributes:
codebook The codebook of the self-organizing map.
bmus The BMUs corresponding to the data points.
:param n_columns: The number of columns in the map.
:type n_columns: int.
... |
peterwittek/somoclu | src/Python/setup.py | customize_compiler_for_nvcc | python | def customize_compiler_for_nvcc(self):
'''This is a verbatim copy of the NVCC compiler extension from
https://github.com/rmcgibbo/npcuda-example
'''
self.src_extensions.append('.cu')
default_compiler_so = self.compiler_so
super = self._compile
def _compile(obj, src, ext, cc_args, extra_post... | This is a verbatim copy of the NVCC compiler extension from
https://github.com/rmcgibbo/npcuda-example | train | https://github.com/peterwittek/somoclu/blob/b31dfbeba6765e64aedddcf8259626d6684f5349/src/Python/setup.py#L56-L73 | null | #!/usr/bin/env python
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
import numpy
import os
import sys
import platform
import traceback
win_cuda_dir = None
def find_cuda():
if 'CUDAHOME' in os.environ:
home = os.environ['CUDAHOME']
nvcc = os.path.join(ho... |
rodricios/eatiht | eatiht/v2.py | get_html_tree | python | def get_html_tree(filename_url_or_filelike):
"""From some file path, input stream, or URL, construct and return
an HTML tree.
"""
try:
handler = (
HTTPSHandler
if filename_url_or_filelike.lower().startswith('https')
else HTTPHandler
)
... | From some file path, input stream, or URL, construct and return
an HTML tree. | train | https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/v2.py#L113-L158 | null | """eatiht - Extract Article Text In HyperText documents
This version of eatiht v2 is the "script" implementation, where
the result is simply the extracted text; there's also extract_more where
the output is the extracted text plus some of the structures that were
built along the way. Please refer to etv2.py for an alm... |
rodricios/eatiht | eatiht/v2.py | get_xpath_frequencydistribution | python | def get_xpath_frequencydistribution(paths):
""" Build and return a frequency distribution over xpath occurrences."""
# "html/body/div/div/text" -> [ "html", "body", "div", "div", "text" ]
splitpaths = [p.split('/') for p in paths]
# get list of "parentpaths" by right-stripping off the last xpath-n... | Build and return a frequency distribution over xpath occurrences. | train | https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/v2.py#L162-L173 | null | """eatiht - Extract Article Text In HyperText documents
This version of eatiht v2 is the "script" implementation, where
the result is simply the extracted text; there's also extract_more where
the output is the extracted text plus some of the structures that were
built along the way. Please refer to etv2.py for an alm... |
rodricios/eatiht | eatiht/v2.py | calc_avgstrlen_pathstextnodes | python | def calc_avgstrlen_pathstextnodes(pars_tnodes, dbg=False):
"""In the effort of not using external libraries (like scipy, numpy, etc),
I've written some harmless code for basic statistical calculations
"""
ttl = 0
for _, tnodes in pars_tnodes:
ttl += tnodes[3] # index #3 holds th... | In the effort of not using external libraries (like scipy, numpy, etc),
I've written some harmless code for basic statistical calculations | train | https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/v2.py#L177-L190 | null | """eatiht - Extract Article Text In HyperText documents
This version of eatiht v2 is the "script" implementation, where
the result is simply the extracted text; there's also extract_more where
the output is the extracted text plus some of the structures that were
built along the way. Please refer to etv2.py for an alm... |
rodricios/eatiht | eatiht/v2.py | calc_across_paths_textnodes | python | def calc_across_paths_textnodes(paths_nodes, dbg=False):
"""Given a list of parent paths tupled with children textnodes, plus
initialized feature values, we calculate the total and average string
length of the parent's children textnodes.
"""
# for (path, [textnodes],
# num. of... | Given a list of parent paths tupled with children textnodes, plus
initialized feature values, we calculate the total and average string
length of the parent's children textnodes. | train | https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/v2.py#L194-L211 | null | """eatiht - Extract Article Text In HyperText documents
This version of eatiht v2 is the "script" implementation, where
the result is simply the extracted text; there's also extract_more where
the output is the extracted text plus some of the structures that were
built along the way. Please refer to etv2.py for an alm... |
rodricios/eatiht | eatiht/v2.py | get_parent_xpaths_and_textnodes | python | def get_parent_xpaths_and_textnodes(filename_url_or_filelike,
xpath_to_text=TEXT_FINDER_XPATH):
"""Provided a url, path or filelike obj., we construct an html tree,
and build a list of parent paths and children textnodes & "feature"
tuples.
The features - descrip... | Provided a url, path or filelike obj., we construct an html tree,
and build a list of parent paths and children textnodes & "feature"
tuples.
The features - descriptive values used for gathering statistics that
attempts to describe this artificial environment I've created (parent
paths and chil... | train | https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/v2.py#L215-L250 | [
"def get_html_tree(filename_url_or_filelike):\n \"\"\"From some file path, input stream, or URL, construct and return\n an HTML tree.\n \"\"\"\n try:\n handler = (\n HTTPSHandler\n if filename_url_or_filelike.lower().startswith('https')\n else HTTPHandler\... | """eatiht - Extract Article Text In HyperText documents
This version of eatiht v2 is the "script" implementation, where
the result is simply the extracted text; there's also extract_more where
the output is the extracted text plus some of the structures that were
built along the way. Please refer to etv2.py for an alm... |
rodricios/eatiht | eatiht/v2.py | extract | python | def extract(filename_url_or_filelike):
"""A more precise algorithm over the original eatiht algorithm
"""
pars_tnodes = get_parent_xpaths_and_textnodes(filename_url_or_filelike)
#[iterable, cardinality, ttl across iterable, avg across iterable.])
calc_across_paths_textnodes(pars_tnodes)
... | A more precise algorithm over the original eatiht algorithm | train | https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/v2.py#L253-L275 | [
"def get_xpath_frequencydistribution(paths):\n \"\"\" Build and return a frequency distribution over xpath occurrences.\"\"\"\n # \"html/body/div/div/text\" -> [ \"html\", \"body\", \"div\", \"div\", \"text\" ]\n splitpaths = [p.split('/') for p in paths]\n\n # get list of \"parentpaths\" by right-strip... | """eatiht - Extract Article Text In HyperText documents
This version of eatiht v2 is the "script" implementation, where
the result is simply the extracted text; there's also extract_more where
the output is the extracted text plus some of the structures that were
built along the way. Please refer to etv2.py for an alm... |
rodricios/eatiht | eatiht/etv2.py | get_xpath_frequencydistribution | python | def get_xpath_frequencydistribution(paths):
""" Build and return a frequency distribution over xpath occurrences."""
# "html/body/div/div/text" -> [ "html", "body", "div", "div", "text" ]
splitpaths = [p.rsplit('/', 1) for p in paths]
# get list of "parentpaths" by right-stripping off the last xpa... | Build and return a frequency distribution over xpath occurrences. | train | https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/etv2.py#L178-L190 | null | """eatiht v2 - Rodrigo Palacios - Copyright 2014
This version of eatiht v2 is the "script" implementation, where
the result is simply the extracted text; there's also extract_more where
the output is the extracted text plus some of the structures that were
built along the way. Please refer to etv2.py for an almost ide... |
rodricios/eatiht | eatiht/etv2.py | calcavg_avgstrlen_subtrees | python | def calcavg_avgstrlen_subtrees(subtrees, dbg=False):
"""In the effort of not using external libraries (like scipy, numpy, etc),
I've written some harmless code for basic statistical calculations
"""
ttl = 0
for subtree in subtrees:
ttl += subtree.avg_strlen
crd = len(subtrees)
... | In the effort of not using external libraries (like scipy, numpy, etc),
I've written some harmless code for basic statistical calculations | train | https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/etv2.py#L193-L206 | null | """eatiht v2 - Rodrigo Palacios - Copyright 2014
This version of eatiht v2 is the "script" implementation, where
the result is simply the extracted text; there's also extract_more where
the output is the extracted text plus some of the structures that were
built along the way. Please refer to etv2.py for an almost ide... |
rodricios/eatiht | eatiht/etv2.py | get_textnode_subtrees | python | def get_textnode_subtrees(html_tree,
xpath_to_text=TEXT_FINDER_XPATH):
"""A modification of get_sentence_xpath_tuples: some code was
refactored-out, variable names are slightly different. This function
does wrap the ltml.tree construction, so a file path, file-like
structu... | A modification of get_sentence_xpath_tuples: some code was
refactored-out, variable names are slightly different. This function
does wrap the ltml.tree construction, so a file path, file-like
structure, or URL is required. | train | https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/etv2.py#L209-L235 | null | """eatiht v2 - Rodrigo Palacios - Copyright 2014
This version of eatiht v2 is the "script" implementation, where
the result is simply the extracted text; there's also extract_more where
the output is the extracted text plus some of the structures that were
built along the way. Please refer to etv2.py for an almost ide... |
rodricios/eatiht | eatiht/etv2.py | extract | python | def extract(filename_url_filelike_or_htmlstring):
"""An "improved" algorithm over the original eatiht algorithm
"""
html_tree = get_html_tree(filename_url_filelike_or_htmlstring)
subtrees = get_textnode_subtrees(html_tree)
#[iterable, cardinality, ttl across iterable, avg across iterable.])
... | An "improved" algorithm over the original eatiht algorithm | train | https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/etv2.py#L238-L262 | [
"def get_xpath_frequencydistribution(paths):\n \"\"\" Build and return a frequency distribution over xpath occurrences.\"\"\"\n # \"html/body/div/div/text\" -> [ \"html\", \"body\", \"div\", \"div\", \"text\" ]\n splitpaths = [p.rsplit('/', 1) for p in paths]\n\n # get list of \"parentpaths\" by right-s... | """eatiht v2 - Rodrigo Palacios - Copyright 2014
This version of eatiht v2 is the "script" implementation, where
the result is simply the extracted text; there's also extract_more where
the output is the extracted text plus some of the structures that were
built along the way. Please refer to etv2.py for an almost ide... |
rodricios/eatiht | eatiht/eatiht_trees.py | TextNodeSubTree.__learn_oneself | python | def __learn_oneself(self):
"""calculate cardinality, total and average string length"""
if not self.__parent_path or not self.__text_nodes:
raise Exception("This error occurred because the step constructor\
had insufficient textnodes or it had empty string\
... | calculate cardinality, total and average string length | train | https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/eatiht_trees.py#L161-L174 | null | class TextNodeSubTree(object):
""" This class can be described in a few different ways. A proper
explanation requires a brief definition of terms.
There's two W3C-spec'd conceptual pieces that I make use of:
TEXT_NODE - #text - NodeType 3
------------------
A text node is a W3C node type. Its ... |
rodricios/eatiht | eatiht/eatiht_trees.py | TextNodeTree.__make_tree | python | def __make_tree(self):
"""Build a tree using lxml.html.builder and our subtrees"""
# create div with "container" class
div = E.DIV(E.CLASS("container"))
# append header with title
div.append(E.H2(self.__title))
# next, iterate through subtrees appending each t... | Build a tree using lxml.html.builder and our subtrees | train | https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/eatiht_trees.py#L228-L250 | null | class TextNodeTree(object):
"""collection of textnode subtrees"""
def __init__(self, title, subtrees, hist):
"""This is a structure that is explained above."""
super(TextNodeTree, self).__init__()
self.__title = title
self.__subtrees = subtrees
self.__histogram = hist
... |
rodricios/eatiht | eatiht/eatiht_trees.py | TextNodeTree.get_html | python | def get_html(self):
"""Generates if need be and returns a simpler html document with text"""
if self.__htmltree is not None:
return self.__htmltree
else:
self.__make_tree()
return self.__htmltree | Generates if need be and returns a simpler html document with text | train | https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/eatiht_trees.py#L252-L258 | [
"def __make_tree(self):\n \"\"\"Build a tree using lxml.html.builder and our subtrees\"\"\"\n\n # create div with \"container\" class\n div = E.DIV(E.CLASS(\"container\"))\n\n # append header with title\n div.append(E.H2(self.__title))\n\n # next, iterate through subtrees appending each tree to di... | class TextNodeTree(object):
"""collection of textnode subtrees"""
def __init__(self, title, subtrees, hist):
"""This is a structure that is explained above."""
super(TextNodeTree, self).__init__()
self.__title = title
self.__subtrees = subtrees
self.__histogram = hist
... |
rodricios/eatiht | eatiht/eatiht_trees.py | TextNodeTree.get_html_string | python | def get_html_string(self):
"""Generates if need be and returns a simpler html string with
extracted text"""
if self.__htmltree is not None:
return htmltostring(self.__htmltree)
else:
self.__make_tree()
return htmltostring(self.__htmltree) | Generates if need be and returns a simpler html string with
extracted text | train | https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/eatiht_trees.py#L260-L267 | [
"def __make_tree(self):\n \"\"\"Build a tree using lxml.html.builder and our subtrees\"\"\"\n\n # create div with \"container\" class\n div = E.DIV(E.CLASS(\"container\"))\n\n # append header with title\n div.append(E.H2(self.__title))\n\n # next, iterate through subtrees appending each tree to di... | class TextNodeTree(object):
"""collection of textnode subtrees"""
def __init__(self, title, subtrees, hist):
"""This is a structure that is explained above."""
super(TextNodeTree, self).__init__()
self.__title = title
self.__subtrees = subtrees
self.__histogram = hist
... |
rodricios/eatiht | eatiht/eatiht_trees.py | TextNodeTree.get_text | python | def get_text(self):
"""Return all joined text from each subtree"""
if self.__fulltext:
return self.__fulltext
else:
self.__fulltext = "\n\n".join(text.get_text()
for text in self.__subtrees)
return self.__fullte... | Return all joined text from each subtree | train | https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/eatiht_trees.py#L269-L276 | null | class TextNodeTree(object):
"""collection of textnode subtrees"""
def __init__(self, title, subtrees, hist):
"""This is a structure that is explained above."""
super(TextNodeTree, self).__init__()
self.__title = title
self.__subtrees = subtrees
self.__histogram = hist
... |
rodricios/eatiht | eatiht/eatiht_trees.py | TextNodeTree.bootstrapify | python | def bootstrapify(self):
"""Add bootstrap cdn to headers of html"""
if self.__htmltree is None:
#raise Exception("HtmlTree has not been made yet")
self.__make_tree()
# add bootstrap cdn to head
self.__htmltree.find('head').append(
E.LINK(rel="s... | Add bootstrap cdn to headers of html | train | https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/eatiht_trees.py#L280-L300 | [
"def __make_tree(self):\n \"\"\"Build a tree using lxml.html.builder and our subtrees\"\"\"\n\n # create div with \"container\" class\n div = E.DIV(E.CLASS(\"container\"))\n\n # append header with title\n div.append(E.H2(self.__title))\n\n # next, iterate through subtrees appending each tree to di... | class TextNodeTree(object):
"""collection of textnode subtrees"""
def __init__(self, title, subtrees, hist):
"""This is a structure that is explained above."""
super(TextNodeTree, self).__init__()
self.__title = title
self.__subtrees = subtrees
self.__histogram = hist
... |
rodricios/eatiht | eatiht/eatiht.py | get_sentence_xpath_tuples | python | def get_sentence_xpath_tuples(filename_url_or_filelike,
xpath_to_text=TEXT_FINDER_XPATH):
"""
Given a url and xpath, this function will download, parse, then
iterate though queried text-nodes. From the resulting text-nodes,
extract a list of (text, exact-xpath) tuples.... | Given a url and xpath, this function will download, parse, then
iterate though queried text-nodes. From the resulting text-nodes,
extract a list of (text, exact-xpath) tuples. | train | https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/eatiht.py#L189-L216 | [
"def get_html_tree(filename_url_or_filelike):\n \"\"\"From some file path, input stream, or URL, construct and return\n an HTML tree.\n \"\"\"\n try:\n handler = (\n HTTPSHandler\n if filename_url_or_filelike.lower().startswith('https')\n else HTTPHandler\... | """
eatiht
Extract Article Text In HyperText documents
written by Rodrigo Palacios
**tl;dr**
(revised on 12/20/2014)
Note: for those unfamiliar with xpaths, think of them as file/folder
paths, where each "file/folder" is really just some HTML element.
Algorithm, dammit!:
Using a clever xpath expression that targets... |
rodricios/eatiht | eatiht/eatiht.py | extract | python | def extract(url_or_htmlstring, xpath_to_text=TEXT_FINDER_XPATH):
"""
Wrapper function for extracting the main article from html document.
A crappy flowchart/state-diagram:
start: url[,xpath] -> xpaths of text-nodes -> frequency distribution
-> argmax( freq. dist. ) = likely xpath leading to a... | Wrapper function for extracting the main article from html document.
A crappy flowchart/state-diagram:
start: url[,xpath] -> xpaths of text-nodes -> frequency distribution
-> argmax( freq. dist. ) = likely xpath leading to article's content | train | https://github.com/rodricios/eatiht/blob/7341c46327cfe7e0c9f226ef5e9808975c4d43da/eatiht/eatiht.py#L219-L238 | [
"def get_sentence_xpath_tuples(filename_url_or_filelike,\n xpath_to_text=TEXT_FINDER_XPATH):\n \"\"\"\n Given a url and xpath, this function will download, parse, then\n iterate though queried text-nodes. From the resulting text-nodes,\n extract a list of (text, exact-xpath)... | """
eatiht
Extract Article Text In HyperText documents
written by Rodrigo Palacios
**tl;dr**
(revised on 12/20/2014)
Note: for those unfamiliar with xpaths, think of them as file/folder
paths, where each "file/folder" is really just some HTML element.
Algorithm, dammit!:
Using a clever xpath expression that targets... |
etobella/python-xmlsig | src/xmlsig/signature_context.py | SignatureContext.sign | python | def sign(self, node):
signed_info = node.find('ds:SignedInfo', namespaces=constants.NS_MAP)
signature_method = signed_info.find('ds:SignatureMethod',
namespaces=constants.NS_MAP).get(
'Algorithm')
key_info = node.find('ds:KeyInfo', namespac... | Signs a Signature node
:param node: Signature node
:type node: lxml.etree.Element
:return: None | train | https://github.com/etobella/python-xmlsig/blob/120a50935a4d4c2c972cfa3f8519bbce7e30d67b/src/xmlsig/signature_context.py#L29-L44 | [
"def fill_key_info(self, key_info, signature_method):\n \"\"\"\n Fills the KeyInfo node\n :param key_info: KeyInfo node \n :type key_info: lxml.etree.Element\n :param signature_method: Signature node to use\n :type signature_method: str\n :return: None\n \"\"\"\n x509_data = key_info.find... | class SignatureContext(object):
"""
Signature context is used to sign and verify Signature nodes with keys
"""
def __init__(self):
self.x509 = None
self.crl = None
self.private_key = None
self.public_key = None
self.key_name = None
def fill_key_info(self, k... |
etobella/python-xmlsig | src/xmlsig/signature_context.py | SignatureContext.fill_key_info | python | def fill_key_info(self, key_info, signature_method):
x509_data = key_info.find('ds:X509Data', namespaces=constants.NS_MAP)
if x509_data is not None:
self.fill_x509_data(x509_data)
key_name = key_info.find('ds:KeyName', namespaces=constants.NS_MAP)
if key_name is not None and ... | Fills the KeyInfo node
:param key_info: KeyInfo node
:type key_info: lxml.etree.Element
:param signature_method: Signature node to use
:type signature_method: str
:return: None | train | https://github.com/etobella/python-xmlsig/blob/120a50935a4d4c2c972cfa3f8519bbce7e30d67b/src/xmlsig/signature_context.py#L46-L74 | [
"def fill_x509_data(self, x509_data):\n \"\"\"\n Fills the X509Data Node\n :param x509_data: X509Data Node\n :type x509_data: lxml.etree.Element\n :return: None\n \"\"\"\n x509_issuer_serial = x509_data.find(\n 'ds:X509IssuerSerial', namespaces=constants.NS_MAP\n )\n if x509_issuer... | class SignatureContext(object):
"""
Signature context is used to sign and verify Signature nodes with keys
"""
def __init__(self):
self.x509 = None
self.crl = None
self.private_key = None
self.public_key = None
self.key_name = None
def sign(self, node):
... |
etobella/python-xmlsig | src/xmlsig/signature_context.py | SignatureContext.fill_x509_data | python | def fill_x509_data(self, x509_data):
x509_issuer_serial = x509_data.find(
'ds:X509IssuerSerial', namespaces=constants.NS_MAP
)
if x509_issuer_serial is not None:
self.fill_x509_issuer_name(x509_issuer_serial)
x509_crl = x509_data.find('ds:X509CRL', namespaces=con... | Fills the X509Data Node
:param x509_data: X509Data Node
:type x509_data: lxml.etree.Element
:return: None | train | https://github.com/etobella/python-xmlsig/blob/120a50935a4d4c2c972cfa3f8519bbce7e30d67b/src/xmlsig/signature_context.py#L76-L112 | [
"def b64_print(s):\n \"\"\"\n Prints a string with spaces at every b64_intro characters\n :param s: String to print\n :return: String\n \"\"\"\n if USING_PYTHON2:\n string = str(s)\n else:\n string = str(s, 'utf8')\n return '\\n'.join(\n string[pos:pos + b64_intro] for p... | class SignatureContext(object):
"""
Signature context is used to sign and verify Signature nodes with keys
"""
def __init__(self):
self.x509 = None
self.crl = None
self.private_key = None
self.public_key = None
self.key_name = None
def sign(self, node):
... |
etobella/python-xmlsig | src/xmlsig/signature_context.py | SignatureContext.fill_x509_issuer_name | python | def fill_x509_issuer_name(self, x509_issuer_serial):
x509_issuer_name = x509_issuer_serial.find(
'ds:X509IssuerName', namespaces=constants.NS_MAP
)
if x509_issuer_name is not None:
x509_issuer_name.text = get_rdns_name(self.x509.issuer.rdns)
x509_issuer_number = x... | Fills the X509IssuerSerial node
:param x509_issuer_serial: X509IssuerSerial node
:type x509_issuer_serial: lxml.etree.Element
:return: None | train | https://github.com/etobella/python-xmlsig/blob/120a50935a4d4c2c972cfa3f8519bbce7e30d67b/src/xmlsig/signature_context.py#L114-L130 | [
"def get_rdns_name(rdns):\n \"\"\"\n Gets the rdns String name\n :param rdns: RDNS object\n :type rdns: cryptography.x509.RelativeDistinguishedName\n :return: RDNS name\n \"\"\"\n name = ''\n for rdn in rdns:\n for attr in rdn._attributes:\n if len(name) > 0:\n ... | class SignatureContext(object):
"""
Signature context is used to sign and verify Signature nodes with keys
"""
def __init__(self):
self.x509 = None
self.crl = None
self.private_key = None
self.public_key = None
self.key_name = None
def sign(self, node):
... |
etobella/python-xmlsig | src/xmlsig/signature_context.py | SignatureContext.fill_signed_info | python | def fill_signed_info(self, signed_info):
for reference in signed_info.findall(
'ds:Reference', namespaces=constants.NS_MAP
):
self.calculate_reference(reference, True) | Fills the SignedInfo node
:param signed_info: SignedInfo node
:type signed_info: lxml.etree.Element
:return: None | train | https://github.com/etobella/python-xmlsig/blob/120a50935a4d4c2c972cfa3f8519bbce7e30d67b/src/xmlsig/signature_context.py#L132-L142 | [
"def calculate_reference(self, reference, sign=True):\n \"\"\"\n Calculates or verifies the digest of the reference\n :param reference: Reference node\n :type reference: lxml.etree.Element\n :param sign: It marks if we must sign or check a signature\n :type sign: bool\n :return: None\n \"\"\... | class SignatureContext(object):
"""
Signature context is used to sign and verify Signature nodes with keys
"""
def __init__(self):
self.x509 = None
self.crl = None
self.private_key = None
self.public_key = None
self.key_name = None
def sign(self, node):
... |
etobella/python-xmlsig | src/xmlsig/signature_context.py | SignatureContext.verify | python | def verify(self, node):
# Added XSD Validation
with open(path.join(
path.dirname(__file__), "data/xmldsig-core-schema.xsd"
), "rb") as file:
schema = etree.XMLSchema(etree.fromstring(file.read()))
schema.assertValid(node)
# Validates reference value
... | Verifies a signature
:param node: Signature node
:type node: lxml.etree.Element
:return: None | train | https://github.com/etobella/python-xmlsig/blob/120a50935a4d4c2c972cfa3f8519bbce7e30d67b/src/xmlsig/signature_context.py#L144-L169 | [
"def calculate_reference(self, reference, sign=True):\n \"\"\"\n Calculates or verifies the digest of the reference\n :param reference: Reference node\n :type reference: lxml.etree.Element\n :param sign: It marks if we must sign or check a signature\n :type sign: bool\n :return: None\n \"\"\... | class SignatureContext(object):
"""
Signature context is used to sign and verify Signature nodes with keys
"""
def __init__(self):
self.x509 = None
self.crl = None
self.private_key = None
self.public_key = None
self.key_name = None
def sign(self, node):
... |
etobella/python-xmlsig | src/xmlsig/signature_context.py | SignatureContext.transform | python | def transform(self, transform, node):
method = transform.get('Algorithm')
if method not in constants.TransformUsageDSigTransform:
raise Exception('Method not allowed')
# C14N methods are allowed
if method in constants.TransformUsageC14NMethod:
return self.canonica... | Transforms a node following the transform especification
:param transform: Transform node
:type transform: lxml.etree.Element
:param node: Element to transform
:type node: str
:return: Transformed node in a String | train | https://github.com/etobella/python-xmlsig/blob/120a50935a4d4c2c972cfa3f8519bbce7e30d67b/src/xmlsig/signature_context.py#L171-L205 | [
"def canonicalization(self, method, node):\n \"\"\"\n Canonicalizes a node following the method\n :param method: Method identification\n :type method: str\n :param node: object to canonicalize\n :type node: str\n :return: Canonicalized node in a String\n \"\"\"\n if method not in constant... | class SignatureContext(object):
"""
Signature context is used to sign and verify Signature nodes with keys
"""
def __init__(self):
self.x509 = None
self.crl = None
self.private_key = None
self.public_key = None
self.key_name = None
def sign(self, node):
... |
etobella/python-xmlsig | src/xmlsig/signature_context.py | SignatureContext.canonicalization | python | def canonicalization(self, method, node):
if method not in constants.TransformUsageC14NMethod:
raise Exception('Method not allowed: ' + method)
c14n_method = constants.TransformUsageC14NMethod[method]
return etree.tostring(
node,
method=c14n_method['method'],
... | Canonicalizes a node following the method
:param method: Method identification
:type method: str
:param node: object to canonicalize
:type node: str
:return: Canonicalized node in a String | train | https://github.com/etobella/python-xmlsig/blob/120a50935a4d4c2c972cfa3f8519bbce7e30d67b/src/xmlsig/signature_context.py#L207-L224 | null | class SignatureContext(object):
"""
Signature context is used to sign and verify Signature nodes with keys
"""
def __init__(self):
self.x509 = None
self.crl = None
self.private_key = None
self.public_key = None
self.key_name = None
def sign(self, node):
... |
etobella/python-xmlsig | src/xmlsig/signature_context.py | SignatureContext.digest | python | def digest(self, method, node):
if method not in constants.TransformUsageDigestMethod:
raise Exception('Method not allowed')
lib = hashlib.new(constants.TransformUsageDigestMethod[method])
lib.update(node)
return base64.b64encode(lib.digest()) | Returns the digest of an object from a method name
:param method: hash method
:type method: str
:param node: Object to hash
:type node: str
:return: hash result | train | https://github.com/etobella/python-xmlsig/blob/120a50935a4d4c2c972cfa3f8519bbce7e30d67b/src/xmlsig/signature_context.py#L226-L239 | null | class SignatureContext(object):
"""
Signature context is used to sign and verify Signature nodes with keys
"""
def __init__(self):
self.x509 = None
self.crl = None
self.private_key = None
self.public_key = None
self.key_name = None
def sign(self, node):
... |
etobella/python-xmlsig | src/xmlsig/signature_context.py | SignatureContext.get_uri | python | def get_uri(self, uri, reference):
if uri == "":
return self.canonicalization(
constants.TransformInclC14N, reference.getroottree()
)
if uri.startswith("#"):
query = "//*[@*[local-name() = '{}' ]=$uri]"
node = reference.getroottree()
... | It returns the node of the specified URI
:param uri: uri of the
:type uri: str
:param reference: Reference node
:type reference: etree.lxml.Element
:return: Element of the URI in a String | train | https://github.com/etobella/python-xmlsig/blob/120a50935a4d4c2c972cfa3f8519bbce7e30d67b/src/xmlsig/signature_context.py#L241-L272 | [
"def canonicalization(self, method, node):\n \"\"\"\n Canonicalizes a node following the method\n :param method: Method identification\n :type method: str\n :param node: object to canonicalize\n :type node: str\n :return: Canonicalized node in a String\n \"\"\"\n if method not in constant... | class SignatureContext(object):
"""
Signature context is used to sign and verify Signature nodes with keys
"""
def __init__(self):
self.x509 = None
self.crl = None
self.private_key = None
self.public_key = None
self.key_name = None
def sign(self, node):
... |
etobella/python-xmlsig | src/xmlsig/signature_context.py | SignatureContext.calculate_reference | python | def calculate_reference(self, reference, sign=True):
node = self.get_uri(reference.get('URI', ''), reference)
transforms = reference.find(
'ds:Transforms', namespaces=constants.NS_MAP
)
if transforms is not None:
for transform in transforms.findall(
... | Calculates or verifies the digest of the reference
:param reference: Reference node
:type reference: lxml.etree.Element
:param sign: It marks if we must sign or check a signature
:type sign: bool
:return: None | train | https://github.com/etobella/python-xmlsig/blob/120a50935a4d4c2c972cfa3f8519bbce7e30d67b/src/xmlsig/signature_context.py#L277-L308 | [
"def transform(self, transform, node):\n \"\"\"\n Transforms a node following the transform especification\n :param transform: Transform node\n :type transform: lxml.etree.Element\n :param node: Element to transform\n :type node: str\n :return: Transformed node in a String\n \"\"\"\n meth... | class SignatureContext(object):
"""
Signature context is used to sign and verify Signature nodes with keys
"""
def __init__(self):
self.x509 = None
self.crl = None
self.private_key = None
self.public_key = None
self.key_name = None
def sign(self, node):
... |
etobella/python-xmlsig | src/xmlsig/signature_context.py | SignatureContext.calculate_signature | python | def calculate_signature(self, node, sign=True):
signed_info_xml = node.find('ds:SignedInfo',
namespaces=constants.NS_MAP)
canonicalization_method = signed_info_xml.find(
'ds:CanonicalizationMethod', namespaces=constants.NS_MAP
).get('Algorithm')
... | Calculate or verifies the signature
:param node: Signature node
:type node: lxml.etree.Element
:param sign: It checks if it must calculate or verify
:type sign: bool
:return: None | train | https://github.com/etobella/python-xmlsig/blob/120a50935a4d4c2c972cfa3f8519bbce7e30d67b/src/xmlsig/signature_context.py#L310-L352 | [
"def b64_print(s):\n \"\"\"\n Prints a string with spaces at every b64_intro characters\n :param s: String to print\n :return: String\n \"\"\"\n if USING_PYTHON2:\n string = str(s)\n else:\n string = str(s, 'utf8')\n return '\\n'.join(\n string[pos:pos + b64_intro] for p... | class SignatureContext(object):
"""
Signature context is used to sign and verify Signature nodes with keys
"""
def __init__(self):
self.x509 = None
self.crl = None
self.private_key = None
self.public_key = None
self.key_name = None
def sign(self, node):
... |
etobella/python-xmlsig | src/xmlsig/signature_context.py | SignatureContext.load_pkcs12 | python | def load_pkcs12(self, key):
self.x509 = key.get_certificate().to_cryptography()
self.public_key = key.get_certificate().to_cryptography().public_key()
self.private_key = key.get_privatekey().to_cryptography_key() | This function fills the context public_key, private_key and x509 from
PKCS12 Object
:param key: the PKCS12 Object
:type key: OpenSSL.crypto.PKCS12
:return: None | train | https://github.com/etobella/python-xmlsig/blob/120a50935a4d4c2c972cfa3f8519bbce7e30d67b/src/xmlsig/signature_context.py#L354-L364 | null | class SignatureContext(object):
"""
Signature context is used to sign and verify Signature nodes with keys
"""
def __init__(self):
self.x509 = None
self.crl = None
self.private_key = None
self.public_key = None
self.key_name = None
def sign(self, node):
... |
etobella/python-xmlsig | src/xmlsig/algorithms/base.py | Algorithm.get_public_key | python | def get_public_key(key_info, ctx):
x509_certificate = key_info.find(
'ds:KeyInfo/ds:X509Data/ds:X509Certificate',
namespaces={'ds': ns.DSigNs}
)
if x509_certificate is not None:
return load_der_x509_certificate(
base64.b64decode(x509_certificat... | Get the public key if its defined in X509Certificate node. Otherwise,
take self.public_key element
:param sign: Signature node
:type sign: lxml.etree.Element
:return: Public key to use | train | https://github.com/etobella/python-xmlsig/blob/120a50935a4d4c2c972cfa3f8519bbce7e30d67b/src/xmlsig/algorithms/base.py#L31-L52 | null | class Algorithm(object):
private_key_class = None
public_key_class = None
@staticmethod
def sign(data, private_key, digest):
raise Exception("Sign function must be redefined")
@staticmethod
def verify(signature_value, data, public_key, digest):
raise Exception("Verify function ... |
etobella/python-xmlsig | src/xmlsig/utils.py | b64_print | python | def b64_print(s):
if USING_PYTHON2:
string = str(s)
else:
string = str(s, 'utf8')
return '\n'.join(
string[pos:pos + b64_intro] for pos in range(0, len(string), b64_intro)
) | Prints a string with spaces at every b64_intro characters
:param s: String to print
:return: String | train | https://github.com/etobella/python-xmlsig/blob/120a50935a4d4c2c972cfa3f8519bbce7e30d67b/src/xmlsig/utils.py#L27-L39 | null | # -*- coding: utf-8 -*-
# © 2017 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import struct
import sys
from cryptography.x509 import oid
from lxml import etree
OID_NAMES = {
oid.NameOID.COMMON_NAME: 'CN',
oid.NameOID.COUNTRY_NAME: 'C',
oid.NameOID.DOMAIN_COMPONENT: 'DC... |
etobella/python-xmlsig | src/xmlsig/utils.py | create_node | python | def create_node(name, parent=None, ns='', tail=False, text=False):
node = etree.Element(etree.QName(ns, name))
if parent is not None:
parent.append(node)
if tail:
node.tail = tail
if text:
node.text = text
return node | Creates a new node
:param name: Node name
:param parent: Node parent
:param ns: Namespace to use
:param tail: Tail to add
:param text: Text of the node
:return: New node | train | https://github.com/etobella/python-xmlsig/blob/120a50935a4d4c2c972cfa3f8519bbce7e30d67b/src/xmlsig/utils.py#L85-L102 | null | # -*- coding: utf-8 -*-
# © 2017 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import struct
import sys
from cryptography.x509 import oid
from lxml import etree
OID_NAMES = {
oid.NameOID.COMMON_NAME: 'CN',
oid.NameOID.COUNTRY_NAME: 'C',
oid.NameOID.DOMAIN_COMPONENT: 'DC... |
etobella/python-xmlsig | src/xmlsig/utils.py | get_rdns_name | python | def get_rdns_name(rdns):
name = ''
for rdn in rdns:
for attr in rdn._attributes:
if len(name) > 0:
name = name + ','
if attr.oid in OID_NAMES:
name = name + OID_NAMES[attr.oid]
else:
name = name + attr.oid._name
... | Gets the rdns String name
:param rdns: RDNS object
:type rdns: cryptography.x509.RelativeDistinguishedName
:return: RDNS name | train | https://github.com/etobella/python-xmlsig/blob/120a50935a4d4c2c972cfa3f8519bbce7e30d67b/src/xmlsig/utils.py#L105-L122 | null | # -*- coding: utf-8 -*-
# © 2017 Creu Blanca
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
import struct
import sys
from cryptography.x509 import oid
from lxml import etree
OID_NAMES = {
oid.NameOID.COMMON_NAME: 'CN',
oid.NameOID.COUNTRY_NAME: 'C',
oid.NameOID.DOMAIN_COMPONENT: 'DC... |
etobella/python-xmlsig | src/xmlsig/algorithms/rsa.py | RSAAlgorithm.get_public_key | python | def get_public_key(key_info, ctx):
key = key_info.find(
'ds:KeyInfo/ds:KeyValue/ds:RSAKeyValue', namespaces=NS_MAP
)
if key is not None:
n = os2ip(b64decode(key.find(
'ds:Modulus', namespaces=NS_MAP).text))
e = os2ip(b64decode(key.find(
... | Get the public key if its defined in X509Certificate node. Otherwise,
take self.public_key element
:param sign: Signature node
:type sign: lxml.etree.Element
:return: Public key to use | train | https://github.com/etobella/python-xmlsig/blob/120a50935a4d4c2c972cfa3f8519bbce7e30d67b/src/xmlsig/algorithms/rsa.py#L60-L77 | null | class RSAAlgorithm(Algorithm):
private_key_class = rsa.RSAPrivateKey
public_key_class = rsa.RSAPublicKey
@staticmethod
def sign(data, private_key, digest):
return private_key.sign(
data,
padding.PKCS1v15(),
digest()
)
@staticmethod
def verify... |
Aula13/poloniex | poloniex/concurrency.py | Semaphore.clear | python | def clear(self):
with self._cond:
to_notify = self._initial - self._value
self._value = self._initial
self._cond.notify(to_notify) | Release the semaphore of all of its bounds, setting the internal
counter back to its original bind limit. Notify an equivalent amount
of threads that they can run. | train | https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/concurrency.py#L96-L103 | null | class Semaphore(object):
"""This class implements semaphore objects.
Semaphores manage a counter representing the number of release() calls minus
the number of acquire() calls, plus an initial value. The acquire() method
blocks if necessary until it can return without making the counter
negative. If... |
Aula13/poloniex | poloniex/poloniex.py | _api_wrapper | python | def _api_wrapper(fn):
def _convert(value):
if isinstance(value, _datetime.date):
return value.strftime('%s')
return value
@_six.wraps(fn)
def _fn(self, command, **params):
# sanitize the params by removing the None values
with self.startup_lock:
if s... | API function decorator that performs rate limiting and error checking. | train | https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L20-L55 | null | import six as _six
import hmac as _hmac
import time as _time
import atexit as _atexit
import hashlib as _hashlib
import datetime as _datetime
import requests as _requests
import itertools as _itertools
import threading as _threading
from .concurrency import RecurrentTimer, Semaphore
from .utils import AutoCastDict as ... |
Aula13/poloniex | poloniex/poloniex.py | PoloniexPublic._public | python | def _public(self, command, **params):
params['command'] = command
response = self.session.get(self._public_url, params=params)
return response | Invoke the 'command' public API with optional params. | train | https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L80-L84 | null | class PoloniexPublic(object):
"""Client to connect to Poloniex public APIs"""
def __init__(self, public_url=_PUBLIC_URL, limit=6,
session_class=_requests.Session,
session=None, startup_lock=None,
semaphore=None, timer=None):
"""Initialize Poloniex cli... |
Aula13/poloniex | poloniex/poloniex.py | PoloniexPublic.returnOrderBook | python | def returnOrderBook(self, currencyPair='all', depth='50'):
return self._public('returnOrderBook', currencyPair=currencyPair,
depth=depth) | Returns the order book for a given market, as well as a sequence
number for use with the Push API and an indicator specifying whether
the market is frozen. You may set currencyPair to "all" to get the
order books of all markets. | train | https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L95-L101 | null | class PoloniexPublic(object):
"""Client to connect to Poloniex public APIs"""
def __init__(self, public_url=_PUBLIC_URL, limit=6,
session_class=_requests.Session,
session=None, startup_lock=None,
semaphore=None, timer=None):
"""Initialize Poloniex cli... |
Aula13/poloniex | poloniex/poloniex.py | PoloniexPublic.returnTradeHistory | python | def returnTradeHistory(self, currencyPair, start=None, end=None):
return self._public('returnTradeHistory', currencyPair=currencyPair,
start=start, end=end) | Returns the past 200 trades for a given market, or up to 50,000
trades between a range specified in UNIX timestamps by the "start"
and "end" GET parameters. | train | https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L103-L108 | null | class PoloniexPublic(object):
"""Client to connect to Poloniex public APIs"""
def __init__(self, public_url=_PUBLIC_URL, limit=6,
session_class=_requests.Session,
session=None, startup_lock=None,
semaphore=None, timer=None):
"""Initialize Poloniex cli... |
Aula13/poloniex | poloniex/poloniex.py | PoloniexPublic.returnChartData | python | def returnChartData(self, currencyPair, period, start=0, end=2**32-1):
return self._public('returnChartData', currencyPair=currencyPair,
period=period, start=start, end=end) | Returns candlestick chart data. Required GET parameters are
"currencyPair", "period" (candlestick period in seconds; valid values
are 300, 900, 1800, 7200, 14400, and 86400), "start", and "end".
"Start" and "end" are given in UNIX timestamp format and used to
specify the date range for t... | train | https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L110-L117 | null | class PoloniexPublic(object):
"""Client to connect to Poloniex public APIs"""
def __init__(self, public_url=_PUBLIC_URL, limit=6,
session_class=_requests.Session,
session=None, startup_lock=None,
semaphore=None, timer=None):
"""Initialize Poloniex cli... |
Aula13/poloniex | poloniex/poloniex.py | Poloniex._private | python | def _private(self, command, **params):
if not self._apikey or not self._secret:
raise PoloniexCredentialsException('missing apikey/secret')
with self.nonce_lock:
params.update({'command': command, 'nonce': next(self.nonce_iter)})
response = self.session.post(
... | Invoke the 'command' public API with optional params. | train | https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L169-L179 | null | class Poloniex(PoloniexPublic):
"""Client to connect to Poloniex private APIs."""
class _PoloniexAuth(_requests.auth.AuthBase):
"""Poloniex Request Authentication."""
def __init__(self, apikey, secret):
self._apikey, self._secret = apikey, secret
def __call__(self, reque... |
Aula13/poloniex | poloniex/poloniex.py | Poloniex.returnDepositsWithdrawals | python | def returnDepositsWithdrawals(self, start=0, end=2**32-1):
return self._private('returnDepositsWithdrawals', start=start, end=end) | Returns your deposit and withdrawal history within a range,
specified by the "start" and "end" POST parameters, both of which
should be given as UNIX timestamps. | train | https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L203-L207 | null | class Poloniex(PoloniexPublic):
"""Client to connect to Poloniex private APIs."""
class _PoloniexAuth(_requests.auth.AuthBase):
"""Poloniex Request Authentication."""
def __init__(self, apikey, secret):
self._apikey, self._secret = apikey, secret
def __call__(self, reque... |
Aula13/poloniex | poloniex/poloniex.py | Poloniex.returnTradeHistory | python | def returnTradeHistory(self, currencyPair='all', start=None, end=None, limit=500):
return self._private('returnTradeHistory', currencyPair=currencyPair,
start=start, end=end, limit=limit) | Returns your trade history for a given market, specified by the
"currencyPair" POST parameter. You may specify "all" as the
currencyPair to receive your trade history for all markets. You may
optionally specify a range via "start" and/or "end" POST parameters,
given in UNIX timestamp for... | train | https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L227-L235 | null | class Poloniex(PoloniexPublic):
"""Client to connect to Poloniex private APIs."""
class _PoloniexAuth(_requests.auth.AuthBase):
"""Poloniex Request Authentication."""
def __init__(self, apikey, secret):
self._apikey, self._secret = apikey, secret
def __call__(self, reque... |
Aula13/poloniex | poloniex/poloniex.py | Poloniex.returnTradeHistoryPublic | python | def returnTradeHistoryPublic(self, currencyPair, start=None, end=None):
return super(Poloniex, self).returnTradeHistory(currencyPair, start, end) | Returns the past 200 trades for a given market, or up to 50,000
trades between a range specified in UNIX timestamps by the "start"
and "end" GET parameters. | train | https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L237-L241 | [
"def returnTradeHistory(self, currencyPair, start=None, end=None):\n \"\"\"Returns the past 200 trades for a given market, or up to 50,000\n trades between a range specified in UNIX timestamps by the \"start\"\n and \"end\" GET parameters.\"\"\"\n return self._public('returnTradeHistory', currencyPair=c... | class Poloniex(PoloniexPublic):
"""Client to connect to Poloniex private APIs."""
class _PoloniexAuth(_requests.auth.AuthBase):
"""Poloniex Request Authentication."""
def __init__(self, apikey, secret):
self._apikey, self._secret = apikey, secret
def __call__(self, reque... |
Aula13/poloniex | poloniex/poloniex.py | Poloniex.buy | python | def buy(self, currencyPair, rate, amount, fillOrKill=None,
immediateOrCancel=None, postOnly=None):
return self._private('buy', currencyPair=currencyPair, rate=rate,
amount=amount, fillOrKill=fillOrKill,
immediateOrCancel=immediateOrCancel,
... | Places a limit buy order in a given market. Required POST parameters
are "currencyPair", "rate", and "amount". If successful, the method
will return the order number.
You may optionally set "fillOrKill", "immediateOrCancel", "postOnly"
to 1. A fill-or-kill order will either fill in its e... | train | https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L250-L266 | null | class Poloniex(PoloniexPublic):
"""Client to connect to Poloniex private APIs."""
class _PoloniexAuth(_requests.auth.AuthBase):
"""Poloniex Request Authentication."""
def __init__(self, apikey, secret):
self._apikey, self._secret = apikey, secret
def __call__(self, reque... |
Aula13/poloniex | poloniex/poloniex.py | Poloniex.moveOrder | python | def moveOrder(self, orderNumber, rate, amount=None, postOnly=None,
immediateOrCancel=None):
return self._private('moveOrder', orderNumber=orderNumber, rate=rate,
amount=amount, postOnly=postOnly,
immediateOrCancel=immediateOrCancel) | Cancels an order and places a new one of the same type in a single
atomic transaction, meaning either both operations will succeed or both
will fail. Required POST parameters are "orderNumber" and "rate"; you
may optionally specify "amount" if you wish to change the amount of
the new ... | train | https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L282-L292 | null | class Poloniex(PoloniexPublic):
"""Client to connect to Poloniex private APIs."""
class _PoloniexAuth(_requests.auth.AuthBase):
"""Poloniex Request Authentication."""
def __init__(self, apikey, secret):
self._apikey, self._secret = apikey, secret
def __call__(self, reque... |
Aula13/poloniex | poloniex/poloniex.py | Poloniex.withdraw | python | def withdraw(self, currency, amount, address, paymentId=None):
return self._private('withdraw', currency=currency, amount=amount,
address=address, paymentId=paymentId) | Immediately places a withdrawal for a given currency, with no email
confirmation. In order to use this method, the withdrawal privilege
must be enabled for your API key. Required POST parameters are
"currency", "amount", and "address". For XMR withdrawals, you may
optionally specify "pay... | train | https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L294-L301 | null | class Poloniex(PoloniexPublic):
"""Client to connect to Poloniex private APIs."""
class _PoloniexAuth(_requests.auth.AuthBase):
"""Poloniex Request Authentication."""
def __init__(self, apikey, secret):
self._apikey, self._secret = apikey, secret
def __call__(self, reque... |
Aula13/poloniex | poloniex/poloniex.py | Poloniex.transferBalance | python | def transferBalance(self, currency, amount, fromAccount, toAccount):
return self._private('transferBalance', currency=currency,
amount=amount, fromAccount=fromAccount,
toAccount=toAccount) | Transfers funds from one account to another (e.g. from your exchange
account to your margin account). Required POST parameters are
"currency", "amount", "fromAccount", and "toAccount". | train | https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L322-L328 | null | class Poloniex(PoloniexPublic):
"""Client to connect to Poloniex private APIs."""
class _PoloniexAuth(_requests.auth.AuthBase):
"""Poloniex Request Authentication."""
def __init__(self, apikey, secret):
self._apikey, self._secret = apikey, secret
def __call__(self, reque... |
Aula13/poloniex | poloniex/poloniex.py | Poloniex.marginBuy | python | def marginBuy(self, currencyPair, rate, amount, lendingRate=None):
return self._private('marginBuy', currencyPair=currencyPair, rate=rate,
amount=amount, lendingRate=lendingRate) | Places a margin buy order in a given market. Required POST
parameters are "currencyPair", "rate", and "amount". You may optionally
specify a maximum lending rate using the "lendingRate" parameter.
If successful, the method will return the order number and any trades
immediately result... | train | https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L336-L343 | null | class Poloniex(PoloniexPublic):
"""Client to connect to Poloniex private APIs."""
class _PoloniexAuth(_requests.auth.AuthBase):
"""Poloniex Request Authentication."""
def __init__(self, apikey, secret):
self._apikey, self._secret = apikey, secret
def __call__(self, reque... |
Aula13/poloniex | poloniex/poloniex.py | Poloniex.marginSell | python | def marginSell(self, currencyPair, rate, amount, lendingRate=None):
return self._private('marginSell', currencyPair=currencyPair, rate=rate,
amount=amount, lendingRate=lendingRate) | Places a margin sell order in a given market. Parameters and output
are the same as for the marginBuy method. | train | https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L345-L349 | null | class Poloniex(PoloniexPublic):
"""Client to connect to Poloniex private APIs."""
class _PoloniexAuth(_requests.auth.AuthBase):
"""Poloniex Request Authentication."""
def __init__(self, apikey, secret):
self._apikey, self._secret = apikey, secret
def __call__(self, reque... |
Aula13/poloniex | poloniex/poloniex.py | Poloniex.createLoanOffer | python | def createLoanOffer(self, currency, amount, duration, autoRenew,
lendingRate):
return self._private('createLoanOffer', currency=currency,
amount=amount, duration=duration,
autoRenew=autoRenew, lendingRate=lendingRate) | Creates a loan offer for a given currency. Required POST parameters
are "currency", "amount", "duration", "autoRenew" (0 or 1), and
"lendingRate". | train | https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L369-L376 | null | class Poloniex(PoloniexPublic):
"""Client to connect to Poloniex private APIs."""
class _PoloniexAuth(_requests.auth.AuthBase):
"""Poloniex Request Authentication."""
def __init__(self, apikey, secret):
self._apikey, self._secret = apikey, secret
def __call__(self, reque... |
Aula13/poloniex | poloniex/poloniex.py | Poloniex.returnLendingHistory | python | def returnLendingHistory(self, start=0, end=2**32-1, limit=None):
return self._private('returnLendingHistory', start=start, end=end,
limit=limit) | Returns your lending history within a time range specified by the
"start" and "end" POST parameters as UNIX timestamps. "limit" may also
be specified to limit the number of rows returned. | train | https://github.com/Aula13/poloniex/blob/a5bfc91e766e220bf77f5e3a1b131f095913e714/poloniex/poloniex.py#L391-L396 | null | class Poloniex(PoloniexPublic):
"""Client to connect to Poloniex private APIs."""
class _PoloniexAuth(_requests.auth.AuthBase):
"""Poloniex Request Authentication."""
def __init__(self, apikey, secret):
self._apikey, self._secret = apikey, secret
def __call__(self, reque... |
jvarho/pylibscrypt | pylibscrypt/pypyscrypt_inline.py | salsa20_8 | python | def salsa20_8(B, x, src, s_start, dest, d_start):
# Merged blockxor for speed
for i in xrange(16):
x[i] = B[i] = B[i] ^ src[s_start + i]
# This is the actual Salsa 20/8: four identical double rounds
for i in xrange(4):
a = (x[0]+x[12]) & 0xffffffff
b = (x[5]+x[1]) & 0xffffffff
... | Salsa20/8 http://en.wikipedia.org/wiki/Salsa20 | train | https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/pypyscrypt_inline.py#L58-L135 | null | # Automatically generated file, see inline.py
# Copyright (c) 2014 Richard Moore
# Copyright (c) 2014-2019 Jan Varho
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, in... |
jvarho/pylibscrypt | pylibscrypt/pypyscrypt_inline.py | blockmix_salsa8 | python | def blockmix_salsa8(BY, Yi, r):
start = (2 * r - 1) * 16
X = BY[start:start+16] # BlockMix - 1
tmp = [0]*16
for i in xrange(2 * r): # BlockMix - 2
#blockxor(BY, i * 16, X, 0, 16) # BlockMix - 3(inner)
salsa20_8(X, tm... | Blockmix; Used by SMix | train | https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/pypyscrypt_inline.py#L138-L152 | [
"def salsa20_8(B, x, src, s_start, dest, d_start):\n \"\"\"Salsa20/8 http://en.wikipedia.org/wiki/Salsa20\"\"\"\n\n # Merged blockxor for speed\n for i in xrange(16):\n x[i] = B[i] = B[i] ^ src[s_start + i]\n\n # This is the actual Salsa 20/8: four identical double rounds\n for i in xrange(4):... | # Automatically generated file, see inline.py
# Copyright (c) 2014 Richard Moore
# Copyright (c) 2014-2019 Jan Varho
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, in... |
jvarho/pylibscrypt | pylibscrypt/pypyscrypt_inline.py | smix | python | def smix(B, Bi, r, N, V, X):
X[0:(0)+(32 * r)] = B[Bi:(Bi)+(32 * r)]
for i in xrange(N): # ROMix - 2
V[i * (32 * r):(i * (32 * r))+(32 * r)] = X[0:(0)+(32 * r)]
blockmix_salsa8(X, 32 * r, r) # ROMix - 4
for i in xrange(N): ... | SMix; a specific case of ROMix based on Salsa20/8 | train | https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/pypyscrypt_inline.py#L155-L169 | [
"def blockxor(source, s_start, dest, d_start, length):\n for i in xrange(length):\n dest[d_start + i] ^= source[s_start + i]\n",
"def integerify(B, r):\n \"\"\"A bijection from ({0, 1} ** k) to {0, ..., (2 ** k) - 1\"\"\"\n\n Bi = (2 * r - 1) * 16\n return B[Bi]\n",
"def blockmix_salsa8(BY, Y... | # Automatically generated file, see inline.py
# Copyright (c) 2014 Richard Moore
# Copyright (c) 2014-2019 Jan Varho
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, in... |
jvarho/pylibscrypt | pylibscrypt/pypyscrypt_inline.py | scrypt | python | def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64):
check_args(password, salt, N, r, p, olen)
# Everything is lists of 32-bit uints for all but pbkdf2
try:
B = _pbkdf2('sha256', password, salt, 1, p * 128 * r)
B = list(struct.unpack('<%dI' % (len(B) // 4), B))
... | Returns a key derived using the scrypt key-derivarion function
N must be a power of two larger than 1 but no larger than 2 ** 63 (insane)
r and p must be positive numbers such that r * p < 2 ** 30
The default values are:
N -- 2**14 (~16k)
r -- 8
p -- 1
Memory usage is proportional to N*r.... | train | https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/pypyscrypt_inline.py#L172-L207 | [
"def check_args(password, salt, N, r, p, olen=64):\n if not isinstance(password, bytes):\n raise TypeError('password must be a byte string')\n if not isinstance(salt, bytes):\n raise TypeError('salt must be a byte string')\n if not isinstance(N, numbers.Integral):\n raise TypeError('N ... | # Automatically generated file, see inline.py
# Copyright (c) 2014 Richard Moore
# Copyright (c) 2014-2019 Jan Varho
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, in... |
jvarho/pylibscrypt | pylibscrypt/pypyscrypt_inline.py | scrypt_mcf | python | def scrypt_mcf(password, salt=None, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p,
prefix=SCRYPT_MCF_PREFIX_DEFAULT):
return mcf_mod.scrypt_mcf(scrypt, password, salt, N, r, p, prefix) | Derives a Modular Crypt Format hash using the scrypt KDF
Parameter space is smaller than for scrypt():
N must be a power of two larger than 1 but no larger than 2 ** 31
r and p must be positive numbers between 1 and 255
Salt must be a byte string 1-16 bytes long.
If no salt is given, a random salt... | train | https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/pypyscrypt_inline.py#L210-L221 | [
"def scrypt_mcf(scrypt, password, salt=None, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p,\n prefix=SCRYPT_MCF_PREFIX_DEFAULT):\n \"\"\"Derives a Modular Crypt Format hash using the scrypt KDF given\n\n Expects the signature:\n scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64)\n\n ... | # Automatically generated file, see inline.py
# Copyright (c) 2014 Richard Moore
# Copyright (c) 2014-2019 Jan Varho
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, in... |
jvarho/pylibscrypt | pylibscrypt/libsodium_load.py | get_libsodium | python | def get_libsodium():
'''Locate the libsodium C library'''
__SONAMES = (13, 10, 5, 4)
# Import libsodium from system
sys_sodium = ctypes.util.find_library('sodium')
if sys_sodium is None:
sys_sodium = ctypes.util.find_library('libsodium')
if sys_sodium:
try:
return c... | Locate the libsodium C library | train | https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/libsodium_load.py#L19-L71 | null | # Copyright (c) 2015, Jan Varho
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARR... |
jvarho/pylibscrypt | pylibscrypt/pylibsodium.py | scrypt | python | def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64):
check_args(password, salt, N, r, p, olen)
if _scrypt_ll:
out = ctypes.create_string_buffer(olen)
if _scrypt_ll(password, len(password), salt, len(salt),
N, r, p, out, olen):
raise ValueErr... | Returns a key derived using the scrypt key-derivarion function
N must be a power of two larger than 1 but no larger than 2 ** 63 (insane)
r and p must be positive numbers such that r * p < 2 ** 30
The default values are:
N -- 2**14 (~16k)
r -- 8
p -- 1
Memory usage is proportional to N*r.... | train | https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/pylibsodium.py#L98-L138 | [
"def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64):\n \"\"\"Returns a key derived using the scrypt key-derivarion function\n\n N must be a power of two larger than 1 but no larger than 2 ** 63 (insane)\n r and p must be positive numbers such that r * p < 2 ** 30\n\n The default val... | # Copyright (c) 2014-2018, Jan Varho
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL... |
jvarho/pylibscrypt | pylibscrypt/pylibsodium.py | scrypt_mcf | python | def scrypt_mcf(password, salt=None, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p,
prefix=SCRYPT_MCF_PREFIX_DEFAULT):
if isinstance(password, unicode):
password = password.encode('utf8')
elif not isinstance(password, bytes):
raise TypeError('password must be a unicode or byte string')
if... | Derives a Modular Crypt Format hash using the scrypt KDF
Parameter space is smaller than for scrypt():
N must be a power of two larger than 1 but no larger than 2 ** 31
r and p must be positive numbers between 1 and 255
Salt must be a byte string 1-16 bytes long.
If no salt is given, a random salt... | train | https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/pylibsodium.py#L141-L182 | [
"def scrypt_mcf(scrypt, password, salt=None, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p,\n prefix=SCRYPT_MCF_PREFIX_DEFAULT):\n \"\"\"Derives a Modular Crypt Format hash using the scrypt KDF given\n\n Expects the signature:\n scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64)\n\n ... | # Copyright (c) 2014-2018, Jan Varho
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL... |
jvarho/pylibscrypt | pylibscrypt/pylibsodium.py | scrypt_mcf_check | python | def scrypt_mcf_check(mcf, password):
if isinstance(password, unicode):
password = password.encode('utf8')
elif not isinstance(password, bytes):
raise TypeError('password must be a unicode or byte string')
if not isinstance(mcf, bytes):
raise TypeError('MCF must be a byte string')
... | Returns True if the password matches the given MCF hash | train | https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/pylibsodium.py#L185-L195 | [
"def scrypt_mcf_check(scrypt, mcf, password):\n \"\"\"Returns True if the password matches the given MCF hash\n\n Supports both the libscrypt $s1$ format and the $7$ format.\n \"\"\"\n if not isinstance(mcf, bytes):\n raise TypeError('MCF must be a byte string')\n if isinstance(password, unico... | # Copyright (c) 2014-2018, Jan Varho
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL... |
jvarho/pylibscrypt | pylibscrypt/mcf.py | scrypt_mcf | python | def scrypt_mcf(scrypt, password, salt=None, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p,
prefix=SCRYPT_MCF_PREFIX_DEFAULT):
if isinstance(password, unicode):
password = password.encode('utf8')
elif not isinstance(password, bytes):
raise TypeError('password must be a unicode or byte string'... | Derives a Modular Crypt Format hash using the scrypt KDF given
Expects the signature:
scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64)
If no salt is given, a random salt of 128+ bits is used. (Recommended.) | train | https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/mcf.py#L199-L237 | [
"def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64):\n \"\"\"Returns a key derived using the scrypt key-derivarion function\n\n N must be a power of two larger than 1 but no larger than 2 ** 63 (insane)\n r and p must be positive numbers such that r * p < 2 ** 30\n\n The default val... | # Copyright (c) 2014-2018, Jan Varho
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL... |
jvarho/pylibscrypt | pylibscrypt/mcf.py | scrypt_mcf_check | python | def scrypt_mcf_check(scrypt, mcf, password):
if not isinstance(mcf, bytes):
raise TypeError('MCF must be a byte string')
if isinstance(password, unicode):
password = password.encode('utf8')
elif not isinstance(password, bytes):
raise TypeError('password must be a unicode or byte stri... | Returns True if the password matches the given MCF hash
Supports both the libscrypt $s1$ format and the $7$ format. | train | https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/mcf.py#L240-L257 | [
"def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64):\n \"\"\"Returns a key derived using the scrypt key-derivarion function\n\n N must be a power of two larger than 1 but no larger than 2 ** 63 (insane)\n r and p must be positive numbers such that r * p < 2 ** 30\n\n The default val... | # Copyright (c) 2014-2018, Jan Varho
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL... |
jvarho/pylibscrypt | pylibscrypt/pyscrypt.py | scrypt | python | def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64):
check_args(password, salt, N, r, p, olen)
try:
return _scrypt(password=password, salt=salt, N=N, r=r, p=p, buflen=olen)
except:
raise ValueError | Returns a key derived using the scrypt key-derivarion function
N must be a power of two larger than 1 but no larger than 2 ** 63 (insane)
r and p must be positive numbers such that r * p < 2 ** 30
The default values are:
N -- 2**14 (~16k)
r -- 8
p -- 1
Memory usage is proportional to N*r.... | train | https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/pyscrypt.py#L37-L61 | [
"def check_args(password, salt, N, r, p, olen=64):\n if not isinstance(password, bytes):\n raise TypeError('password must be a byte string')\n if not isinstance(salt, bytes):\n raise TypeError('salt must be a byte string')\n if not isinstance(N, numbers.Integral):\n raise TypeError('N ... | # Copyright (c) 2014-2016, Jan Varho
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL... |
jvarho/pylibscrypt | pylibscrypt/hashlibscrypt.py | scrypt | python | def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64):
check_args(password, salt, N, r, p, olen)
# Set the memory required based on parameter values
m = 128 * r * (N + p + 2)
try:
return _scrypt(
password=password, salt=salt, n=N, r=r, p=p, maxmem=m, dklen=olen)
... | Returns a key derived using the scrypt key-derivarion function
N must be a power of two larger than 1 but no larger than 2 ** 63 (insane)
r and p must be positive numbers such that r * p < 2 ** 30
The default values are:
N -- 2**14 (~16k)
r -- 8
p -- 1
Memory usage is proportional to N*r.... | train | https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/hashlibscrypt.py#L30-L58 | [
"def check_args(password, salt, N, r, p, olen=64):\n if not isinstance(password, bytes):\n raise TypeError('password must be a byte string')\n if not isinstance(salt, bytes):\n raise TypeError('salt must be a byte string')\n if not isinstance(N, numbers.Integral):\n raise TypeError('N ... | # Copyright (c) 2016-2017, Jan Varho
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL... |
jvarho/pylibscrypt | pylibscrypt/pypyscrypt.py | R | python | def R(X, destination, a1, a2, b):
a = (X[a1] + X[a2]) & 0xffffffff
X[destination] ^= ((a << b) | (a >> (32 - b))) | A single Salsa20 row operation | train | https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/pypyscrypt.py#L60-L64 | null | # Copyright (c) 2014 Richard Moore
# Copyright (c) 2014-2019 Jan Varho
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use,... |
jvarho/pylibscrypt | pylibscrypt/pypyscrypt.py | salsa20_8 | python | def salsa20_8(B, x, src, s_start, dest, d_start):
# Merged blockxor for speed
for i in xrange(16):
x[i] = B[i] = B[i] ^ src[s_start + i]
# This is the actual Salsa 20/8: four identical double rounds
for i in xrange(4):
R(x, 4, 0,12, 7);R(x, 8, 4, 0, 9);R(x,12, 8, 4,13);R(x, 0,12, 8,18)... | Salsa20/8 http://en.wikipedia.org/wiki/Salsa20 | train | https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/pypyscrypt.py#L67-L88 | [
"def R(X, destination, a1, a2, b):\n \"\"\"A single Salsa20 row operation\"\"\"\n\n a = (X[a1] + X[a2]) & 0xffffffff\n X[destination] ^= ((a << b) | (a >> (32 - b)))\n"
] | # Copyright (c) 2014 Richard Moore
# Copyright (c) 2014-2019 Jan Varho
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use,... |
jvarho/pylibscrypt | pylibscrypt/pylibscrypt.py | scrypt | python | def scrypt(password, salt, N=SCRYPT_N, r=SCRYPT_r, p=SCRYPT_p, olen=64):
check_args(password, salt, N, r, p, olen)
out = ctypes.create_string_buffer(olen)
ret = _libscrypt_scrypt(password, len(password), salt, len(salt),
N, r, p, out, len(out))
if ret:
raise ValueError... | Returns a key derived using the scrypt key-derivarion function
N must be a power of two larger than 1 but no larger than 2 ** 63 (insane)
r and p must be positive numbers such that r * p < 2 ** 30
The default values are:
N -- 2**14 (~16k)
r -- 8
p -- 1
Memory usage is proportional to N*r.... | train | https://github.com/jvarho/pylibscrypt/blob/f2ff02e49f44aa620e308a4a64dd8376b9510f99/pylibscrypt/pylibscrypt.py#L71-L98 | [
"def check_args(password, salt, N, r, p, olen=64):\n if not isinstance(password, bytes):\n raise TypeError('password must be a byte string')\n if not isinstance(salt, bytes):\n raise TypeError('salt must be a byte string')\n if not isinstance(N, numbers.Integral):\n raise TypeError('N ... | # Copyright (c) 2014-2018, Jan Varho
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.