repo stringlengths 7 55 | path stringlengths 4 223 | func_name stringlengths 1 134 | original_string stringlengths 75 104k | language stringclasses 1
value | code stringlengths 75 104k | code_tokens listlengths 19 28.4k | docstring stringlengths 1 46.9k | docstring_tokens listlengths 1 1.97k | sha stringlengths 40 40 | url stringlengths 87 315 | partition stringclasses 3
values | summary stringlengths 4 350 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
aht/stream.py | example/pi.py | Gregory | def Gregory(type=float):
"""Return partial sums of the Gregory series converging to atan(1) == pi/4.
Yield 1 - 1/3 + 1/5 - 1/7 + ... computed with the given type.
"""
return seq(type(1), step=2) >> map(lambda x: 1/x) >> alt_sign >> fold(operator.add) | python | def Gregory(type=float):
"""Return partial sums of the Gregory series converging to atan(1) == pi/4.
Yield 1 - 1/3 + 1/5 - 1/7 + ... computed with the given type.
"""
return seq(type(1), step=2) >> map(lambda x: 1/x) >> alt_sign >> fold(operator.add) | [
"def",
"Gregory",
"(",
"type",
"=",
"float",
")",
":",
"return",
"seq",
"(",
"type",
"(",
"1",
")",
",",
"step",
"=",
"2",
")",
">>",
"map",
"(",
"lambda",
"x",
":",
"1",
"/",
"x",
")",
">>",
"alt_sign",
">>",
"fold",
"(",
"operator",
".",
"a... | Return partial sums of the Gregory series converging to atan(1) == pi/4.
Yield 1 - 1/3 + 1/5 - 1/7 + ... computed with the given type. | [
"Return",
"partial",
"sums",
"of",
"the",
"Gregory",
"series",
"converging",
"to",
"atan",
"(",
"1",
")",
"==",
"pi",
"/",
"4",
"."
] | 6a4945cbddaf74138eee5ba33eee3988cfceb84d | https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/example/pi.py#L23-L28 | train | Return partial sums of the Gregory series converging to atan ( 1 ) == pi |
aht/stream.py | example/pi.py | Aitken | def Aitken(s):
"""Accelerate the convergence of the a series
using Aitken's delta-squared process (SCIP calls it Euler).
"""
def accel():
s0, s1, s2 = s >> item[:3]
while 1:
yield s2 - (s2 - s1)**2 / (s0 - 2*s1 + s2)
s0, s1, s2 = s1, s2, next(s)
return accel() | python | def Aitken(s):
"""Accelerate the convergence of the a series
using Aitken's delta-squared process (SCIP calls it Euler).
"""
def accel():
s0, s1, s2 = s >> item[:3]
while 1:
yield s2 - (s2 - s1)**2 / (s0 - 2*s1 + s2)
s0, s1, s2 = s1, s2, next(s)
return accel() | [
"def",
"Aitken",
"(",
"s",
")",
":",
"def",
"accel",
"(",
")",
":",
"s0",
",",
"s1",
",",
"s2",
"=",
"s",
">>",
"item",
"[",
":",
"3",
"]",
"while",
"1",
":",
"yield",
"s2",
"-",
"(",
"s2",
"-",
"s1",
")",
"**",
"2",
"/",
"(",
"s0",
"-"... | Accelerate the convergence of the a series
using Aitken's delta-squared process (SCIP calls it Euler). | [
"Accelerate",
"the",
"convergence",
"of",
"the",
"a",
"series",
"using",
"Aitken",
"s",
"delta",
"-",
"squared",
"process",
"(",
"SCIP",
"calls",
"it",
"Euler",
")",
"."
] | 6a4945cbddaf74138eee5ba33eee3988cfceb84d | https://github.com/aht/stream.py/blob/6a4945cbddaf74138eee5ba33eee3988cfceb84d/example/pi.py#L35-L44 | train | Accelerate convergence of the a series
using Aitken s delta - squared process. |
DarkEnergySurvey/ugali | ugali/preprocess/database.py | SDSSDatabase.upload | def upload(self, array, fields=None, table="MyDB", configfile=None):
"""
Upload an array to a personal database using SOAP POST protocol.
http://skyserver.sdss3.org/casjobs/services/jobs.asmx?op=UploadData
"""
wsid=''
password=''
if configfile is None:
... | python | def upload(self, array, fields=None, table="MyDB", configfile=None):
"""
Upload an array to a personal database using SOAP POST protocol.
http://skyserver.sdss3.org/casjobs/services/jobs.asmx?op=UploadData
"""
wsid=''
password=''
if configfile is None:
... | [
"def",
"upload",
"(",
"self",
",",
"array",
",",
"fields",
"=",
"None",
",",
"table",
"=",
"\"MyDB\"",
",",
"configfile",
"=",
"None",
")",
":",
"wsid",
"=",
"''",
"password",
"=",
"''",
"if",
"configfile",
"is",
"None",
":",
"configfile",
"=",
"\"Ca... | Upload an array to a personal database using SOAP POST protocol.
http://skyserver.sdss3.org/casjobs/services/jobs.asmx?op=UploadData | [
"Upload",
"an",
"array",
"to",
"a",
"personal",
"database",
"using",
"SOAP",
"POST",
"protocol",
".",
"http",
":",
"//",
"skyserver",
".",
"sdss3",
".",
"org",
"/",
"casjobs",
"/",
"services",
"/",
"jobs",
".",
"asmx?op",
"=",
"UploadData"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/preprocess/database.py#L201-L262 | train | Uploads an array to a personal database using the SOAP POST protocol. |
DarkEnergySurvey/ugali | ugali/preprocess/database.py | SDSSDatabase.footprint | def footprint(self,nside):
"""
Download the survey footprint for HEALpix pixels.
"""
import healpy
import ugali.utils.projector
if nside > 2**9: raise Exception("Overflow error: nside must be <=2**9")
pix = np.arange(healpy.nside2npix(nside),dtype='int')
f... | python | def footprint(self,nside):
"""
Download the survey footprint for HEALpix pixels.
"""
import healpy
import ugali.utils.projector
if nside > 2**9: raise Exception("Overflow error: nside must be <=2**9")
pix = np.arange(healpy.nside2npix(nside),dtype='int')
f... | [
"def",
"footprint",
"(",
"self",
",",
"nside",
")",
":",
"import",
"healpy",
"import",
"ugali",
".",
"utils",
".",
"projector",
"if",
"nside",
">",
"2",
"**",
"9",
":",
"raise",
"Exception",
"(",
"\"Overflow error: nside must be <=2**9\"",
")",
"pix",
"=",
... | Download the survey footprint for HEALpix pixels. | [
"Download",
"the",
"survey",
"footprint",
"for",
"HEALpix",
"pixels",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/preprocess/database.py#L298-L315 | train | Download the survey footprint for HEALpix pixels. |
DarkEnergySurvey/ugali | ugali/utils/plotting.py | histogram | def histogram(title, title_x, title_y,
x, bins_x):
"""
Plot a basic histogram.
"""
plt.figure()
plt.hist(x, bins_x)
plt.xlabel(title_x)
plt.ylabel(title_y)
plt.title(title) | python | def histogram(title, title_x, title_y,
x, bins_x):
"""
Plot a basic histogram.
"""
plt.figure()
plt.hist(x, bins_x)
plt.xlabel(title_x)
plt.ylabel(title_y)
plt.title(title) | [
"def",
"histogram",
"(",
"title",
",",
"title_x",
",",
"title_y",
",",
"x",
",",
"bins_x",
")",
":",
"plt",
".",
"figure",
"(",
")",
"plt",
".",
"hist",
"(",
"x",
",",
"bins_x",
")",
"plt",
".",
"xlabel",
"(",
"title_x",
")",
"plt",
".",
"ylabel"... | Plot a basic histogram. | [
"Plot",
"a",
"basic",
"histogram",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L61-L70 | train | Plots a histogram plot. |
DarkEnergySurvey/ugali | ugali/utils/plotting.py | twoDimensionalHistogram | def twoDimensionalHistogram(title, title_x, title_y,
z, bins_x, bins_y,
lim_x=None, lim_y=None,
vmin=None, vmax=None):
"""
Create a two-dimension histogram plot or binned map.
If using the outputs of np.histogram2d, remembe... | python | def twoDimensionalHistogram(title, title_x, title_y,
z, bins_x, bins_y,
lim_x=None, lim_y=None,
vmin=None, vmax=None):
"""
Create a two-dimension histogram plot or binned map.
If using the outputs of np.histogram2d, remembe... | [
"def",
"twoDimensionalHistogram",
"(",
"title",
",",
"title_x",
",",
"title_y",
",",
"z",
",",
"bins_x",
",",
"bins_y",
",",
"lim_x",
"=",
"None",
",",
"lim_y",
"=",
"None",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
")",
":",
"plt",
".",
... | Create a two-dimension histogram plot or binned map.
If using the outputs of np.histogram2d, remember to transpose the histogram.
INPUTS | [
"Create",
"a",
"two",
"-",
"dimension",
"histogram",
"plot",
"or",
"binned",
"map",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L74-L101 | train | Create a two - dimension histogram plot. |
DarkEnergySurvey/ugali | ugali/utils/plotting.py | twoDimensionalScatter | def twoDimensionalScatter(title, title_x, title_y,
x, y,
lim_x = None, lim_y = None,
color = 'b', size = 20, alpha=None):
"""
Create a two-dimensional scatter plot.
INPUTS
"""
plt.figure()
plt.scatter(x, y, c=color, ... | python | def twoDimensionalScatter(title, title_x, title_y,
x, y,
lim_x = None, lim_y = None,
color = 'b', size = 20, alpha=None):
"""
Create a two-dimensional scatter plot.
INPUTS
"""
plt.figure()
plt.scatter(x, y, c=color, ... | [
"def",
"twoDimensionalScatter",
"(",
"title",
",",
"title_x",
",",
"title_y",
",",
"x",
",",
"y",
",",
"lim_x",
"=",
"None",
",",
"lim_y",
"=",
"None",
",",
"color",
"=",
"'b'",
",",
"size",
"=",
"20",
",",
"alpha",
"=",
"None",
")",
":",
"plt",
... | Create a two-dimensional scatter plot.
INPUTS | [
"Create",
"a",
"two",
"-",
"dimensional",
"scatter",
"plot",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L105-L127 | train | Create a two - dimensional scatter plot. |
DarkEnergySurvey/ugali | ugali/utils/plotting.py | zoomedHealpixMap | def zoomedHealpixMap(title, map, lon, lat, radius,
xsize=1000, **kwargs):
"""
Inputs: lon (deg), lat (deg), radius (deg)
"""
reso = 60. * 2. * radius / xsize # Deg to arcmin
hp.gnomview(map=map, rot=[lon, lat, 0], title=title, xsize=xsize, reso=reso, degree=False, **kwargs) | python | def zoomedHealpixMap(title, map, lon, lat, radius,
xsize=1000, **kwargs):
"""
Inputs: lon (deg), lat (deg), radius (deg)
"""
reso = 60. * 2. * radius / xsize # Deg to arcmin
hp.gnomview(map=map, rot=[lon, lat, 0], title=title, xsize=xsize, reso=reso, degree=False, **kwargs) | [
"def",
"zoomedHealpixMap",
"(",
"title",
",",
"map",
",",
"lon",
",",
"lat",
",",
"radius",
",",
"xsize",
"=",
"1000",
",",
"*",
"*",
"kwargs",
")",
":",
"reso",
"=",
"60.",
"*",
"2.",
"*",
"radius",
"/",
"xsize",
"# Deg to arcmin",
"hp",
".",
"gno... | Inputs: lon (deg), lat (deg), radius (deg) | [
"Inputs",
":",
"lon",
"(",
"deg",
")",
"lat",
"(",
"deg",
")",
"radius",
"(",
"deg",
")"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L131-L137 | train | Zooms a HEALPix map in a Zoomed HealPix map. |
DarkEnergySurvey/ugali | ugali/utils/plotting.py | projScatter | def projScatter(lon, lat, **kwargs):
"""
Create a scatter plot on HEALPix projected axes.
Inputs: lon (deg), lat (deg)
"""
hp.projscatter(lon, lat, lonlat=True, **kwargs) | python | def projScatter(lon, lat, **kwargs):
"""
Create a scatter plot on HEALPix projected axes.
Inputs: lon (deg), lat (deg)
"""
hp.projscatter(lon, lat, lonlat=True, **kwargs) | [
"def",
"projScatter",
"(",
"lon",
",",
"lat",
",",
"*",
"*",
"kwargs",
")",
":",
"hp",
".",
"projscatter",
"(",
"lon",
",",
"lat",
",",
"lonlat",
"=",
"True",
",",
"*",
"*",
"kwargs",
")"
] | Create a scatter plot on HEALPix projected axes.
Inputs: lon (deg), lat (deg) | [
"Create",
"a",
"scatter",
"plot",
"on",
"HEALPix",
"projected",
"axes",
".",
"Inputs",
":",
"lon",
"(",
"deg",
")",
"lat",
"(",
"deg",
")"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L141-L146 | train | projScatter is a wrapper around hp. projscatter |
DarkEnergySurvey/ugali | ugali/utils/plotting.py | sparseHealpixFiles | def sparseHealpixFiles(title, infiles, field='MAGLIM',**kwargs):
"""
Inputs: field
"""
#map = ugali.utils.skymap.readSparseHealpixMaps(infiles,field)
map = ugali.utils.skymap.read_partial_map(infiles,field)
ax = hp.mollview(map=map, title=title, **kwargs)
return ax, m... | python | def sparseHealpixFiles(title, infiles, field='MAGLIM',**kwargs):
"""
Inputs: field
"""
#map = ugali.utils.skymap.readSparseHealpixMaps(infiles,field)
map = ugali.utils.skymap.read_partial_map(infiles,field)
ax = hp.mollview(map=map, title=title, **kwargs)
return ax, m... | [
"def",
"sparseHealpixFiles",
"(",
"title",
",",
"infiles",
",",
"field",
"=",
"'MAGLIM'",
",",
"*",
"*",
"kwargs",
")",
":",
"#map = ugali.utils.skymap.readSparseHealpixMaps(infiles,field)",
"map",
"=",
"ugali",
".",
"utils",
".",
"skymap",
".",
"read_partial_map",
... | Inputs: field | [
"Inputs",
":",
"field"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L150-L158 | train | Returns a plot of a sparse HEALPix map. |
DarkEnergySurvey/ugali | ugali/utils/plotting.py | drawHealpixMap | def drawHealpixMap(hpxmap, lon, lat, size=1.0, xsize=501, coord='GC', **kwargs):
"""
Draw local projection of healpix map.
"""
ax = plt.gca()
x = np.linspace(-size,size,xsize)
y = np.linspace(-size,size,xsize)
xx, yy = np.meshgrid(x,y)
coord = coord.upper()
if coord == ... | python | def drawHealpixMap(hpxmap, lon, lat, size=1.0, xsize=501, coord='GC', **kwargs):
"""
Draw local projection of healpix map.
"""
ax = plt.gca()
x = np.linspace(-size,size,xsize)
y = np.linspace(-size,size,xsize)
xx, yy = np.meshgrid(x,y)
coord = coord.upper()
if coord == ... | [
"def",
"drawHealpixMap",
"(",
"hpxmap",
",",
"lon",
",",
"lat",
",",
"size",
"=",
"1.0",
",",
"xsize",
"=",
"501",
",",
"coord",
"=",
"'GC'",
",",
"*",
"*",
"kwargs",
")",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"x",
"=",
"np",
".",
"lin... | Draw local projection of healpix map. | [
"Draw",
"local",
"projection",
"of",
"healpix",
"map",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L162-L189 | train | Draw a healpix map. |
DarkEnergySurvey/ugali | ugali/utils/plotting.py | getSDSSImage | def getSDSSImage(ra,dec,radius=1.0,xsize=800,opt='GML',**kwargs):
"""
Download Sloan Digital Sky Survey images
http://skyserver.sdss3.org/dr9/en/tools/chart/chart.asp
radius (degrees)
opts: (G) Grid, (L) Label, P (PhotoObj), S (SpecObj), O (Outline), (B) Bounding Box,
(F) Fields, (M) Mas... | python | def getSDSSImage(ra,dec,radius=1.0,xsize=800,opt='GML',**kwargs):
"""
Download Sloan Digital Sky Survey images
http://skyserver.sdss3.org/dr9/en/tools/chart/chart.asp
radius (degrees)
opts: (G) Grid, (L) Label, P (PhotoObj), S (SpecObj), O (Outline), (B) Bounding Box,
(F) Fields, (M) Mas... | [
"def",
"getSDSSImage",
"(",
"ra",
",",
"dec",
",",
"radius",
"=",
"1.0",
",",
"xsize",
"=",
"800",
",",
"opt",
"=",
"'GML'",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"subprocess",
"import",
"tempfile",
"url",
"=",
"\"http://skyservice.pha.jhu.edu/DR10/... | Download Sloan Digital Sky Survey images
http://skyserver.sdss3.org/dr9/en/tools/chart/chart.asp
radius (degrees)
opts: (G) Grid, (L) Label, P (PhotoObj), S (SpecObj), O (Outline), (B) Bounding Box,
(F) Fields, (M) Mask, (Q) Plates, (I) Invert | [
"Download",
"Sloan",
"Digital",
"Sky",
"Survey",
"images",
"http",
":",
"//",
"skyserver",
".",
"sdss3",
".",
"org",
"/",
"dr9",
"/",
"en",
"/",
"tools",
"/",
"chart",
"/",
"chart",
".",
"asp"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L214-L238 | train | Download and return the Sloan Digital Sky Survey images from the DSS server. |
DarkEnergySurvey/ugali | ugali/utils/plotting.py | getDSSImage | def getDSSImage(ra,dec,radius=1.0,xsize=800,**kwargs):
"""
Download Digitized Sky Survey images
https://archive.stsci.edu/cgi-bin/dss_form
https://archive.stsci.edu/cgi-bin/dss_search
Image is in celestial orientation (RA increases to the right)
https://archive.stsci.edu/dss/script_usage.h... | python | def getDSSImage(ra,dec,radius=1.0,xsize=800,**kwargs):
"""
Download Digitized Sky Survey images
https://archive.stsci.edu/cgi-bin/dss_form
https://archive.stsci.edu/cgi-bin/dss_search
Image is in celestial orientation (RA increases to the right)
https://archive.stsci.edu/dss/script_usage.h... | [
"def",
"getDSSImage",
"(",
"ra",
",",
"dec",
",",
"radius",
"=",
"1.0",
",",
"xsize",
"=",
"800",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"subprocess",
"import",
"tempfile",
"service",
"=",
"'skyview'",
"if",
"service",
"==",
"'stsci'",
":",
"url"... | Download Digitized Sky Survey images
https://archive.stsci.edu/cgi-bin/dss_form
https://archive.stsci.edu/cgi-bin/dss_search
Image is in celestial orientation (RA increases to the right)
https://archive.stsci.edu/dss/script_usage.html
ra (r) - right ascension
dec (d) - declination
equ... | [
"Download",
"Digitized",
"Sky",
"Survey",
"images"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L241-L298 | train | Download Digitized Sky Survey images and display them in a temporary file. |
DarkEnergySurvey/ugali | ugali/utils/plotting.py | draw_slices | def draw_slices(hist, func=np.sum, **kwargs):
""" Draw horizontal and vertical slices through histogram """
from mpl_toolkits.axes_grid1 import make_axes_locatable
kwargs.setdefault('ls','-')
ax = plt.gca()
data = hist
# Slices
vslice = func(data,axis=0)
hslice = func(data,axis=1)
... | python | def draw_slices(hist, func=np.sum, **kwargs):
""" Draw horizontal and vertical slices through histogram """
from mpl_toolkits.axes_grid1 import make_axes_locatable
kwargs.setdefault('ls','-')
ax = plt.gca()
data = hist
# Slices
vslice = func(data,axis=0)
hslice = func(data,axis=1)
... | [
"def",
"draw_slices",
"(",
"hist",
",",
"func",
"=",
"np",
".",
"sum",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"mpl_toolkits",
".",
"axes_grid1",
"import",
"make_axes_locatable",
"kwargs",
".",
"setdefault",
"(",
"'ls'",
",",
"'-'",
")",
"ax",
"=",
... | Draw horizontal and vertical slices through histogram | [
"Draw",
"horizontal",
"and",
"vertical",
"slices",
"through",
"histogram"
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L1035-L1077 | train | Draw horizontal and vertical slices through histogram |
DarkEnergySurvey/ugali | ugali/utils/plotting.py | plotSkymapCatalog | def plotSkymapCatalog(lon,lat,**kwargs):
"""
Plot a catalog of coordinates on a full-sky map.
"""
fig = plt.figure()
ax = plt.subplot(111,projection=projection)
drawSkymapCatalog(ax,lon,lat,**kwargs) | python | def plotSkymapCatalog(lon,lat,**kwargs):
"""
Plot a catalog of coordinates on a full-sky map.
"""
fig = plt.figure()
ax = plt.subplot(111,projection=projection)
drawSkymapCatalog(ax,lon,lat,**kwargs) | [
"def",
"plotSkymapCatalog",
"(",
"lon",
",",
"lat",
",",
"*",
"*",
"kwargs",
")",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
")",
"ax",
"=",
"plt",
".",
"subplot",
"(",
"111",
",",
"projection",
"=",
"projection",
")",
"drawSkymapCatalog",
"(",
"ax"... | Plot a catalog of coordinates on a full-sky map. | [
"Plot",
"a",
"catalog",
"of",
"coordinates",
"on",
"a",
"full",
"-",
"sky",
"map",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L1409-L1415 | train | Plot a catalog of coordinates on a full - sky map. |
DarkEnergySurvey/ugali | ugali/utils/plotting.py | makePath | def makePath(x_path, y_path, epsilon=1.e-10):
"""
Create closed path.
"""
x_path_closed = np.concatenate([x_path, x_path[::-1]])
y_path_closed = np.concatenate([y_path, epsilon + y_path[::-1]])
path = matplotlib.path.Path(list(zip(x_path_closed, y_path_closed)))
return path | python | def makePath(x_path, y_path, epsilon=1.e-10):
"""
Create closed path.
"""
x_path_closed = np.concatenate([x_path, x_path[::-1]])
y_path_closed = np.concatenate([y_path, epsilon + y_path[::-1]])
path = matplotlib.path.Path(list(zip(x_path_closed, y_path_closed)))
return path | [
"def",
"makePath",
"(",
"x_path",
",",
"y_path",
",",
"epsilon",
"=",
"1.e-10",
")",
":",
"x_path_closed",
"=",
"np",
".",
"concatenate",
"(",
"[",
"x_path",
",",
"x_path",
"[",
":",
":",
"-",
"1",
"]",
"]",
")",
"y_path_closed",
"=",
"np",
".",
"c... | Create closed path. | [
"Create",
"closed",
"path",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L1499-L1506 | train | Create a path from two arrays of x and y. |
DarkEnergySurvey/ugali | ugali/utils/plotting.py | cutIsochronePath | def cutIsochronePath(g, r, g_err, r_err, isochrone, radius=0.1, return_all=False):
"""
Cut to identify objects within isochrone cookie-cutter.
ADW: This should be moved into the isochrone class.
"""
import scipy.interpolate
from ugali.isochrone import CompositeIsochrone
if isinstance(isoch... | python | def cutIsochronePath(g, r, g_err, r_err, isochrone, radius=0.1, return_all=False):
"""
Cut to identify objects within isochrone cookie-cutter.
ADW: This should be moved into the isochrone class.
"""
import scipy.interpolate
from ugali.isochrone import CompositeIsochrone
if isinstance(isoch... | [
"def",
"cutIsochronePath",
"(",
"g",
",",
"r",
",",
"g_err",
",",
"r_err",
",",
"isochrone",
",",
"radius",
"=",
"0.1",
",",
"return_all",
"=",
"False",
")",
":",
"import",
"scipy",
".",
"interpolate",
"from",
"ugali",
".",
"isochrone",
"import",
"Compos... | Cut to identify objects within isochrone cookie-cutter.
ADW: This should be moved into the isochrone class. | [
"Cut",
"to",
"identify",
"objects",
"within",
"isochrone",
"cookie",
"-",
"cutter",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L1510-L1574 | train | Cut the path from g to r_err and r_err to the isochrone. |
DarkEnergySurvey/ugali | ugali/utils/plotting.py | BasePlotter.drawMask | def drawMask(self,ax=None, mask=None, mtype='maglim'):
""" Draw the maglim from the mask. """
if not ax: ax = plt.gca()
if mask is None:
mask = ugali.analysis.loglike.createMask(self.config,roi=self.roi)
mask_map = hp.UNSEEN*np.ones(hp.nside2npix(self.nside))
if mtyp... | python | def drawMask(self,ax=None, mask=None, mtype='maglim'):
""" Draw the maglim from the mask. """
if not ax: ax = plt.gca()
if mask is None:
mask = ugali.analysis.loglike.createMask(self.config,roi=self.roi)
mask_map = hp.UNSEEN*np.ones(hp.nside2npix(self.nside))
if mtyp... | [
"def",
"drawMask",
"(",
"self",
",",
"ax",
"=",
"None",
",",
"mask",
"=",
"None",
",",
"mtype",
"=",
"'maglim'",
")",
":",
"if",
"not",
"ax",
":",
"ax",
"=",
"plt",
".",
"gca",
"(",
")",
"if",
"mask",
"is",
"None",
":",
"mask",
"=",
"ugali",
... | Draw the maglim from the mask. | [
"Draw",
"the",
"maglim",
"from",
"the",
"mask",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/plotting.py#L458-L480 | train | Draw the maglim from the mask. |
warrenspe/hconf | hconf/subparsers/ini.py | INI.parse | def parse(self, configManager, config):
"""
Parse configuration options out of an .ini configuration file.
Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object.
config - The _Config object containing configuration options popul... | python | def parse(self, configManager, config):
"""
Parse configuration options out of an .ini configuration file.
Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object.
config - The _Config object containing configuration options popul... | [
"def",
"parse",
"(",
"self",
",",
"configManager",
",",
"config",
")",
":",
"parser",
"=",
"ConfigParser",
".",
"RawConfigParser",
"(",
")",
"configOptions",
"=",
"dict",
"(",
")",
"configFile",
"=",
"self",
".",
"_getConfigFile",
"(",
"config",
")",
"if",... | Parse configuration options out of an .ini configuration file.
Inputs: configManager - Our parent ConfigManager instance which is constructing the Config object.
config - The _Config object containing configuration options populated thus far.
Outputs: A dictionary of new configu... | [
"Parse",
"configuration",
"options",
"out",
"of",
"an",
".",
"ini",
"configuration",
"file",
"."
] | 12074d15dc3641d3903488c95d89a507386a32d5 | https://github.com/warrenspe/hconf/blob/12074d15dc3641d3903488c95d89a507386a32d5/hconf/subparsers/ini.py#L46-L67 | train | Parse configuration options out of an. ini file. |
kallimachos/sphinxmark | sphinxmark/__init__.py | buildcss | def buildcss(app, buildpath, imagefile):
"""Create CSS file."""
# set default values
div = 'body'
repeat = 'repeat-y'
position = 'center'
attachment = 'scroll'
if app.config.sphinxmark_div != 'default':
div = app.config.sphinxmark_div
if app.config.sphinxmark_repeat is False:
... | python | def buildcss(app, buildpath, imagefile):
"""Create CSS file."""
# set default values
div = 'body'
repeat = 'repeat-y'
position = 'center'
attachment = 'scroll'
if app.config.sphinxmark_div != 'default':
div = app.config.sphinxmark_div
if app.config.sphinxmark_repeat is False:
... | [
"def",
"buildcss",
"(",
"app",
",",
"buildpath",
",",
"imagefile",
")",
":",
"# set default values",
"div",
"=",
"'body'",
"repeat",
"=",
"'repeat-y'",
"position",
"=",
"'center'",
"attachment",
"=",
"'scroll'",
"if",
"app",
".",
"config",
".",
"sphinxmark_div... | Create CSS file. | [
"Create",
"CSS",
"file",
"."
] | f7b17d9dabf1fff448bb38d90474498f0d203990 | https://github.com/kallimachos/sphinxmark/blob/f7b17d9dabf1fff448bb38d90474498f0d203990/sphinxmark/__init__.py#L34-L64 | train | Create CSS file. |
kallimachos/sphinxmark | sphinxmark/__init__.py | createimage | def createimage(app, srcdir, buildpath):
"""Create PNG image from string."""
text = app.config.sphinxmark_text
# draw transparent background
width = app.config.sphinxmark_text_width
height = app.config.sphinxmark_text_spacing
img = Image.new('RGBA', (width, height), (255, 255, 255, 0))
d = ... | python | def createimage(app, srcdir, buildpath):
"""Create PNG image from string."""
text = app.config.sphinxmark_text
# draw transparent background
width = app.config.sphinxmark_text_width
height = app.config.sphinxmark_text_spacing
img = Image.new('RGBA', (width, height), (255, 255, 255, 0))
d = ... | [
"def",
"createimage",
"(",
"app",
",",
"srcdir",
",",
"buildpath",
")",
":",
"text",
"=",
"app",
".",
"config",
".",
"sphinxmark_text",
"# draw transparent background",
"width",
"=",
"app",
".",
"config",
".",
"sphinxmark_text_width",
"height",
"=",
"app",
"."... | Create PNG image from string. | [
"Create",
"PNG",
"image",
"from",
"string",
"."
] | f7b17d9dabf1fff448bb38d90474498f0d203990 | https://github.com/kallimachos/sphinxmark/blob/f7b17d9dabf1fff448bb38d90474498f0d203990/sphinxmark/__init__.py#L67-L103 | train | Create PNG image from string. |
kallimachos/sphinxmark | sphinxmark/__init__.py | getimage | def getimage(app):
"""Get image file."""
# append source directory to TEMPLATE_PATH so template is found
srcdir = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_PATH.append(srcdir)
staticbase = '_static'
buildpath = os.path.join(app.outdir, staticbase)
try:
os.makedirs(buildpath... | python | def getimage(app):
"""Get image file."""
# append source directory to TEMPLATE_PATH so template is found
srcdir = os.path.abspath(os.path.dirname(__file__))
TEMPLATE_PATH.append(srcdir)
staticbase = '_static'
buildpath = os.path.join(app.outdir, staticbase)
try:
os.makedirs(buildpath... | [
"def",
"getimage",
"(",
"app",
")",
":",
"# append source directory to TEMPLATE_PATH so template is found",
"srcdir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
"TEMPLATE_PATH",
".",
"append",
"(",
... | Get image file. | [
"Get",
"image",
"file",
"."
] | f7b17d9dabf1fff448bb38d90474498f0d203990 | https://github.com/kallimachos/sphinxmark/blob/f7b17d9dabf1fff448bb38d90474498f0d203990/sphinxmark/__init__.py#L106-L149 | train | Get image file. |
kallimachos/sphinxmark | sphinxmark/__init__.py | watermark | def watermark(app, env):
"""Add watermark."""
if app.config.sphinxmark_enable is True:
LOG.info('adding watermark...', nonl=True)
buildpath, imagefile = getimage(app)
cssname = buildcss(app, buildpath, imagefile)
app.add_css_file(cssname)
LOG.info(' done') | python | def watermark(app, env):
"""Add watermark."""
if app.config.sphinxmark_enable is True:
LOG.info('adding watermark...', nonl=True)
buildpath, imagefile = getimage(app)
cssname = buildcss(app, buildpath, imagefile)
app.add_css_file(cssname)
LOG.info(' done') | [
"def",
"watermark",
"(",
"app",
",",
"env",
")",
":",
"if",
"app",
".",
"config",
".",
"sphinxmark_enable",
"is",
"True",
":",
"LOG",
".",
"info",
"(",
"'adding watermark...'",
",",
"nonl",
"=",
"True",
")",
"buildpath",
",",
"imagefile",
"=",
"getimage"... | Add watermark. | [
"Add",
"watermark",
"."
] | f7b17d9dabf1fff448bb38d90474498f0d203990 | https://github.com/kallimachos/sphinxmark/blob/f7b17d9dabf1fff448bb38d90474498f0d203990/sphinxmark/__init__.py#L152-L159 | train | Add watermark to the Sphinx application. |
kallimachos/sphinxmark | sphinxmark/__init__.py | setup | def setup(app):
"""
Configure setup for Sphinx extension.
:param app: Sphinx application context.
"""
app.add_config_value('sphinxmark_enable', False, 'html')
app.add_config_value('sphinxmark_div', 'default', 'html')
app.add_config_value('sphinxmark_border', None, 'html')
app.add_config... | python | def setup(app):
"""
Configure setup for Sphinx extension.
:param app: Sphinx application context.
"""
app.add_config_value('sphinxmark_enable', False, 'html')
app.add_config_value('sphinxmark_div', 'default', 'html')
app.add_config_value('sphinxmark_border', None, 'html')
app.add_config... | [
"def",
"setup",
"(",
"app",
")",
":",
"app",
".",
"add_config_value",
"(",
"'sphinxmark_enable'",
",",
"False",
",",
"'html'",
")",
"app",
".",
"add_config_value",
"(",
"'sphinxmark_div'",
",",
"'default'",
",",
"'html'",
")",
"app",
".",
"add_config_value",
... | Configure setup for Sphinx extension.
:param app: Sphinx application context. | [
"Configure",
"setup",
"for",
"Sphinx",
"extension",
"."
] | f7b17d9dabf1fff448bb38d90474498f0d203990 | https://github.com/kallimachos/sphinxmark/blob/f7b17d9dabf1fff448bb38d90474498f0d203990/sphinxmark/__init__.py#L162-L187 | train | Configure Sphinx extension. |
akx/lepo | lepo/handlers.py | BaseHandler.get_view | def get_view(cls, method_name):
"""
Get a Django function view calling the given method (and pre/post-processors)
:param method_name: The method on the class
:return: View function
"""
method = getattr(cls, method_name)
@wraps(method)
def view(request, *... | python | def get_view(cls, method_name):
"""
Get a Django function view calling the given method (and pre/post-processors)
:param method_name: The method on the class
:return: View function
"""
method = getattr(cls, method_name)
@wraps(method)
def view(request, *... | [
"def",
"get_view",
"(",
"cls",
",",
"method_name",
")",
":",
"method",
"=",
"getattr",
"(",
"cls",
",",
"method_name",
")",
"@",
"wraps",
"(",
"method",
")",
"def",
"view",
"(",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"handler",
"=",
"cls",
"... | Get a Django function view calling the given method (and pre/post-processors)
:param method_name: The method on the class
:return: View function | [
"Get",
"a",
"Django",
"function",
"view",
"calling",
"the",
"given",
"method",
"(",
"and",
"pre",
"/",
"post",
"-",
"processors",
")"
] | 34cfb24a40f18ea40f672c1ea9a0734ee1816b7d | https://github.com/akx/lepo/blob/34cfb24a40f18ea40f672c1ea9a0734ee1816b7d/lepo/handlers.py#L13-L33 | train | Get a Django function view calling the given method on the class
. |
DarkEnergySurvey/ugali | ugali/utils/bayesian_efficiency.py | gammalnStirling | def gammalnStirling(z):
"""
Uses Stirling's approximation for the log-gamma function suitable for large arguments.
"""
return (0.5 * (np.log(2. * np.pi) - np.log(z))) \
+ (z * (np.log(z + (1. / ((12. * z) - (1. / (10. * z))))) - 1.)) | python | def gammalnStirling(z):
"""
Uses Stirling's approximation for the log-gamma function suitable for large arguments.
"""
return (0.5 * (np.log(2. * np.pi) - np.log(z))) \
+ (z * (np.log(z + (1. / ((12. * z) - (1. / (10. * z))))) - 1.)) | [
"def",
"gammalnStirling",
"(",
"z",
")",
":",
"return",
"(",
"0.5",
"*",
"(",
"np",
".",
"log",
"(",
"2.",
"*",
"np",
".",
"pi",
")",
"-",
"np",
".",
"log",
"(",
"z",
")",
")",
")",
"+",
"(",
"z",
"*",
"(",
"np",
".",
"log",
"(",
"z",
"... | Uses Stirling's approximation for the log-gamma function suitable for large arguments. | [
"Uses",
"Stirling",
"s",
"approximation",
"for",
"the",
"log",
"-",
"gamma",
"function",
"suitable",
"for",
"large",
"arguments",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/bayesian_efficiency.py#L15-L20 | train | Returns the log - gamma function for a given number of times z. |
DarkEnergySurvey/ugali | ugali/utils/bayesian_efficiency.py | confidenceInterval | def confidenceInterval(n, k, alpha = 0.68, errorbar=False):
"""
Given n tests and k successes, return efficiency and confidence interval.
"""
try:
e = float(k) / float(n)
except ZeroDivisionError:
return np.nan, [np.nan, np.nan]
bins = 1000001
dx = 1. / bins
efficiency ... | python | def confidenceInterval(n, k, alpha = 0.68, errorbar=False):
"""
Given n tests and k successes, return efficiency and confidence interval.
"""
try:
e = float(k) / float(n)
except ZeroDivisionError:
return np.nan, [np.nan, np.nan]
bins = 1000001
dx = 1. / bins
efficiency ... | [
"def",
"confidenceInterval",
"(",
"n",
",",
"k",
",",
"alpha",
"=",
"0.68",
",",
"errorbar",
"=",
"False",
")",
":",
"try",
":",
"e",
"=",
"float",
"(",
"k",
")",
"/",
"float",
"(",
"n",
")",
"except",
"ZeroDivisionError",
":",
"return",
"np",
".",... | Given n tests and k successes, return efficiency and confidence interval. | [
"Given",
"n",
"tests",
"and",
"k",
"successes",
"return",
"efficiency",
"and",
"confidence",
"interval",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/bayesian_efficiency.py#L24-L76 | train | Given n tests and k successes return efficiency and confidence interval. |
DarkEnergySurvey/ugali | ugali/utils/bayesian_efficiency.py | binomialInterval | def binomialInterval(n, k, alpha = 0.68):
"""
Given n tests and k successes, return efficiency and confidence interval.
"""
e = float(k)/n
delta_e = 1/float(n) * np.sqrt(e * (1 - e) * float(n)) * alpha/0.68
return e, [e - delta_e, e + delta_e] | python | def binomialInterval(n, k, alpha = 0.68):
"""
Given n tests and k successes, return efficiency and confidence interval.
"""
e = float(k)/n
delta_e = 1/float(n) * np.sqrt(e * (1 - e) * float(n)) * alpha/0.68
return e, [e - delta_e, e + delta_e] | [
"def",
"binomialInterval",
"(",
"n",
",",
"k",
",",
"alpha",
"=",
"0.68",
")",
":",
"e",
"=",
"float",
"(",
"k",
")",
"/",
"n",
"delta_e",
"=",
"1",
"/",
"float",
"(",
"n",
")",
"*",
"np",
".",
"sqrt",
"(",
"e",
"*",
"(",
"1",
"-",
"e",
"... | Given n tests and k successes, return efficiency and confidence interval. | [
"Given",
"n",
"tests",
"and",
"k",
"successes",
"return",
"efficiency",
"and",
"confidence",
"interval",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/utils/bayesian_efficiency.py#L84-L90 | train | Given n tests and k successes return efficiency and confidence interval. |
DarkEnergySurvey/ugali | ugali/simulation/simulator.py | satellite | def satellite(isochrone, kernel, stellar_mass, distance_modulus,**kwargs):
"""
Wrapping the isochrone and kernel simulate functions.
"""
mag_1, mag_2 = isochrone.simulate(stellar_mass, distance_modulus)
lon, lat = kernel.simulate(len(mag_1))
return mag_1, mag_2, lon, lat | python | def satellite(isochrone, kernel, stellar_mass, distance_modulus,**kwargs):
"""
Wrapping the isochrone and kernel simulate functions.
"""
mag_1, mag_2 = isochrone.simulate(stellar_mass, distance_modulus)
lon, lat = kernel.simulate(len(mag_1))
return mag_1, mag_2, lon, lat | [
"def",
"satellite",
"(",
"isochrone",
",",
"kernel",
",",
"stellar_mass",
",",
"distance_modulus",
",",
"*",
"*",
"kwargs",
")",
":",
"mag_1",
",",
"mag_2",
"=",
"isochrone",
".",
"simulate",
"(",
"stellar_mass",
",",
"distance_modulus",
")",
"lon",
",",
"... | Wrapping the isochrone and kernel simulate functions. | [
"Wrapping",
"the",
"isochrone",
"and",
"kernel",
"simulate",
"functions",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/simulator.py#L811-L818 | train | Wrap the isochrone and kernel simulate functions. |
DarkEnergySurvey/ugali | ugali/simulation/simulator.py | Generator.detectability | def detectability(self,**kwargs):
"""
An a priori detectability proxy.
"""
distance_modulus = kwargs.get('distance_modulus')
distance = mod2dist(distance_modulus)
stellar_mass = kwargs.get('stellar_mass')
extension = kwargs.get('extension')
# Normalized t... | python | def detectability(self,**kwargs):
"""
An a priori detectability proxy.
"""
distance_modulus = kwargs.get('distance_modulus')
distance = mod2dist(distance_modulus)
stellar_mass = kwargs.get('stellar_mass')
extension = kwargs.get('extension')
# Normalized t... | [
"def",
"detectability",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"distance_modulus",
"=",
"kwargs",
".",
"get",
"(",
"'distance_modulus'",
")",
"distance",
"=",
"mod2dist",
"(",
"distance_modulus",
")",
"stellar_mass",
"=",
"kwargs",
".",
"get",
"(",
... | An a priori detectability proxy. | [
"An",
"a",
"priori",
"detectability",
"proxy",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/simulator.py#L76-L88 | train | Returns the detectability of a priori detectability proxy. |
DarkEnergySurvey/ugali | ugali/simulation/simulator.py | Simulator._create_catalog | def _create_catalog(self,catalog=None):
"""
Bundle it.
"""
if catalog is None:
catalog = ugali.analysis.loglike.createCatalog(self.config,self.roi)
cut = self.mask.restrictCatalogToObservableSpace(catalog)
self.catalog = catalog.applyCut(cut) | python | def _create_catalog(self,catalog=None):
"""
Bundle it.
"""
if catalog is None:
catalog = ugali.analysis.loglike.createCatalog(self.config,self.roi)
cut = self.mask.restrictCatalogToObservableSpace(catalog)
self.catalog = catalog.applyCut(cut) | [
"def",
"_create_catalog",
"(",
"self",
",",
"catalog",
"=",
"None",
")",
":",
"if",
"catalog",
"is",
"None",
":",
"catalog",
"=",
"ugali",
".",
"analysis",
".",
"loglike",
".",
"createCatalog",
"(",
"self",
".",
"config",
",",
"self",
".",
"roi",
")",
... | Bundle it. | [
"Bundle",
"it",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/simulator.py#L228-L235 | train | Create a new catalog. |
DarkEnergySurvey/ugali | ugali/simulation/simulator.py | Simulator._photometricErrors | def _photometricErrors(self, n_per_bin=100, plot=False):
"""
Realistic photometric errors estimated from catalog objects and mask.
Extend below the magnitude threshold with a flat extrapolation.
"""
self.catalog.spatialBin(self.roi)
if len(self.catalog.mag_1) < n_per_bi... | python | def _photometricErrors(self, n_per_bin=100, plot=False):
"""
Realistic photometric errors estimated from catalog objects and mask.
Extend below the magnitude threshold with a flat extrapolation.
"""
self.catalog.spatialBin(self.roi)
if len(self.catalog.mag_1) < n_per_bi... | [
"def",
"_photometricErrors",
"(",
"self",
",",
"n_per_bin",
"=",
"100",
",",
"plot",
"=",
"False",
")",
":",
"self",
".",
"catalog",
".",
"spatialBin",
"(",
"self",
".",
"roi",
")",
"if",
"len",
"(",
"self",
".",
"catalog",
".",
"mag_1",
")",
"<",
... | Realistic photometric errors estimated from catalog objects and mask.
Extend below the magnitude threshold with a flat extrapolation. | [
"Realistic",
"photometric",
"errors",
"estimated",
"from",
"catalog",
"objects",
"and",
"mask",
".",
"Extend",
"below",
"the",
"magnitude",
"threshold",
"with",
"a",
"flat",
"extrapolation",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/simulator.py#L237-L286 | train | Calculates the realistic photometric errors estimated from catalog objects and mask objects and mask. |
DarkEnergySurvey/ugali | ugali/simulation/simulator.py | Simulator._setup_subpix | def _setup_subpix(self,nside=2**16):
"""
Subpixels for random position generation.
"""
# Only setup once...
if hasattr(self,'subpix'): return
# Simulate over full ROI
self.roi_radius = self.config['coords']['roi_radius']
# Setup background spatial stuff... | python | def _setup_subpix(self,nside=2**16):
"""
Subpixels for random position generation.
"""
# Only setup once...
if hasattr(self,'subpix'): return
# Simulate over full ROI
self.roi_radius = self.config['coords']['roi_radius']
# Setup background spatial stuff... | [
"def",
"_setup_subpix",
"(",
"self",
",",
"nside",
"=",
"2",
"**",
"16",
")",
":",
"# Only setup once...",
"if",
"hasattr",
"(",
"self",
",",
"'subpix'",
")",
":",
"return",
"# Simulate over full ROI",
"self",
".",
"roi_radius",
"=",
"self",
".",
"config",
... | Subpixels for random position generation. | [
"Subpixels",
"for",
"random",
"position",
"generation",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/simulator.py#L289-L306 | train | Setup subpixels for random position generation. |
DarkEnergySurvey/ugali | ugali/simulation/simulator.py | Simulator._setup_cmd | def _setup_cmd(self,mode='cloud-in-cells'):
"""
The purpose here is to create a more finely binned
background CMD to sample from.
"""
# Only setup once...
if hasattr(self,'bkg_lambda'): return
logger.info("Setup color...")
# In the limit theta->0: 2*pi*(1... | python | def _setup_cmd(self,mode='cloud-in-cells'):
"""
The purpose here is to create a more finely binned
background CMD to sample from.
"""
# Only setup once...
if hasattr(self,'bkg_lambda'): return
logger.info("Setup color...")
# In the limit theta->0: 2*pi*(1... | [
"def",
"_setup_cmd",
"(",
"self",
",",
"mode",
"=",
"'cloud-in-cells'",
")",
":",
"# Only setup once...",
"if",
"hasattr",
"(",
"self",
",",
"'bkg_lambda'",
")",
":",
"return",
"logger",
".",
"info",
"(",
"\"Setup color...\"",
")",
"# In the limit theta->0: 2*pi*(... | The purpose here is to create a more finely binned
background CMD to sample from. | [
"The",
"purpose",
"here",
"is",
"to",
"create",
"a",
"more",
"finely",
"binned",
"background",
"CMD",
"to",
"sample",
"from",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/simulator.py#L308-L340 | train | Create background CMD to sample from. |
DarkEnergySurvey/ugali | ugali/simulation/simulator.py | Simulator.toy_background | def toy_background(self,mc_source_id=2,seed=None):
"""
Quick uniform background generation.
"""
logger.info("Running toy background simulation...")
size = 20000
nstar = np.random.poisson(size)
#np.random.seed(0)
logger.info("Simulating %i background stars... | python | def toy_background(self,mc_source_id=2,seed=None):
"""
Quick uniform background generation.
"""
logger.info("Running toy background simulation...")
size = 20000
nstar = np.random.poisson(size)
#np.random.seed(0)
logger.info("Simulating %i background stars... | [
"def",
"toy_background",
"(",
"self",
",",
"mc_source_id",
"=",
"2",
",",
"seed",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"\"Running toy background simulation...\"",
")",
"size",
"=",
"20000",
"nstar",
"=",
"np",
".",
"random",
".",
"poisson",
"... | Quick uniform background generation. | [
"Quick",
"uniform",
"background",
"generation",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/simulator.py#L343-L397 | train | Generate a random HEALPix map from the main HEALPix pixels. |
DarkEnergySurvey/ugali | ugali/simulation/simulator.py | Simulator.background | def background(self,mc_source_id=2,seed=None):
"""
Create a simulation of the background stellar population.
Because some stars have been clipped to generate the CMD,
this function tends to slightly underestimate (~1%) the
background as compared to the true catalog.
The... | python | def background(self,mc_source_id=2,seed=None):
"""
Create a simulation of the background stellar population.
Because some stars have been clipped to generate the CMD,
this function tends to slightly underestimate (~1%) the
background as compared to the true catalog.
The... | [
"def",
"background",
"(",
"self",
",",
"mc_source_id",
"=",
"2",
",",
"seed",
"=",
"None",
")",
":",
"if",
"seed",
"is",
"not",
"None",
":",
"np",
".",
"random",
".",
"seed",
"(",
"seed",
")",
"self",
".",
"_setup_cmd",
"(",
")",
"# Randomize the num... | Create a simulation of the background stellar population.
Because some stars have been clipped to generate the CMD,
this function tends to slightly underestimate (~1%) the
background as compared to the true catalog.
The simulation of background object colors relies on the
data-... | [
"Create",
"a",
"simulation",
"of",
"the",
"background",
"stellar",
"population",
".",
"Because",
"some",
"stars",
"have",
"been",
"clipped",
"to",
"generate",
"the",
"CMD",
"this",
"function",
"tends",
"to",
"slightly",
"underestimate",
"(",
"~1%",
")",
"the",... | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/simulator.py#L400-L493 | train | Create a simulation of the background object colors for each CMD in the main command set. |
DarkEnergySurvey/ugali | ugali/simulation/simulator.py | Simulator.satellite | def satellite(self,stellar_mass,distance_modulus,mc_source_id=1,seed=None,**kwargs):
"""
Create a simulated satellite. Returns a catalog object.
"""
if seed is not None: np.random.seed(seed)
isochrone = kwargs.pop('isochrone',self.isochrone)
kernel = kwargs.pop('kerne... | python | def satellite(self,stellar_mass,distance_modulus,mc_source_id=1,seed=None,**kwargs):
"""
Create a simulated satellite. Returns a catalog object.
"""
if seed is not None: np.random.seed(seed)
isochrone = kwargs.pop('isochrone',self.isochrone)
kernel = kwargs.pop('kerne... | [
"def",
"satellite",
"(",
"self",
",",
"stellar_mass",
",",
"distance_modulus",
",",
"mc_source_id",
"=",
"1",
",",
"seed",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"seed",
"is",
"not",
"None",
":",
"np",
".",
"random",
".",
"seed",
"(",
... | Create a simulated satellite. Returns a catalog object. | [
"Create",
"a",
"simulated",
"satellite",
".",
"Returns",
"a",
"catalog",
"object",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/simulator.py#L495-L544 | train | Create a simulated satellite. |
DarkEnergySurvey/ugali | ugali/simulation/simulator.py | Simulator.makeHDU | def makeHDU(self, mag_1, mag_err_1, mag_2, mag_err_2, lon, lat, mc_source_id):
"""
Create a catalog fits file object based on input data.
ADW: This should be combined with the write_membership
function of loglike.
"""
if self.config['catalog']['coordsys'].lower() == 'cel... | python | def makeHDU(self, mag_1, mag_err_1, mag_2, mag_err_2, lon, lat, mc_source_id):
"""
Create a catalog fits file object based on input data.
ADW: This should be combined with the write_membership
function of loglike.
"""
if self.config['catalog']['coordsys'].lower() == 'cel... | [
"def",
"makeHDU",
"(",
"self",
",",
"mag_1",
",",
"mag_err_1",
",",
"mag_2",
",",
"mag_err_2",
",",
"lon",
",",
"lat",
",",
"mc_source_id",
")",
":",
"if",
"self",
".",
"config",
"[",
"'catalog'",
"]",
"[",
"'coordsys'",
"]",
".",
"lower",
"(",
")",
... | Create a catalog fits file object based on input data.
ADW: This should be combined with the write_membership
function of loglike. | [
"Create",
"a",
"catalog",
"fits",
"file",
"object",
"based",
"on",
"input",
"data",
"."
] | 21e890b4117fc810afb6fb058e8055d564f03382 | https://github.com/DarkEnergySurvey/ugali/blob/21e890b4117fc810afb6fb058e8055d564f03382/ugali/simulation/simulator.py#L628-L662 | train | Create a catalog FITS file object based on input data. |
totalgood/pugnlp | src/pugnlp/util.py | clean_columns | def clean_columns(columns, valid_regex=r'\w', lower=True, max_len=32):
""" Ensure all column name strings are valid python variable/attribute names
>>> df = pd.DataFrame(np.zeros((2, 3)), columns=['WAT??', "Don't do th!s, way too long. ya-think????", 'ok-this123.456'])
>>> df.columns = clean_columns(df.co... | python | def clean_columns(columns, valid_regex=r'\w', lower=True, max_len=32):
""" Ensure all column name strings are valid python variable/attribute names
>>> df = pd.DataFrame(np.zeros((2, 3)), columns=['WAT??', "Don't do th!s, way too long. ya-think????", 'ok-this123.456'])
>>> df.columns = clean_columns(df.co... | [
"def",
"clean_columns",
"(",
"columns",
",",
"valid_regex",
"=",
"r'\\w'",
",",
"lower",
"=",
"True",
",",
"max_len",
"=",
"32",
")",
":",
"rettype",
"=",
"None",
"if",
"isinstance",
"(",
"columns",
",",
"str",
")",
":",
"rettype",
"=",
"type",
"(",
... | Ensure all column name strings are valid python variable/attribute names
>>> df = pd.DataFrame(np.zeros((2, 3)), columns=['WAT??', "Don't do th!s, way too long. ya-think????", 'ok-this123.456'])
>>> df.columns = clean_columns(df.columns, max_len=12)
>>> df.head()
wat dont_do_ths_ okthis123456
... | [
"Ensure",
"all",
"column",
"name",
"strings",
"are",
"valid",
"python",
"variable",
"/",
"attribute",
"names"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L103-L126 | train | Ensure all column names in a list are valid python variable names and attribute names. |
totalgood/pugnlp | src/pugnlp/util.py | force_hashable | def force_hashable(obj, recursive=True):
"""Force frozenset() command to freeze the order and contents of mutables and iterables like lists, dicts, generators
Useful for memoization and constructing dicts or hashtables where keys must be immutable.
FIXME: Rename function because "hashable" is misleading.
... | python | def force_hashable(obj, recursive=True):
"""Force frozenset() command to freeze the order and contents of mutables and iterables like lists, dicts, generators
Useful for memoization and constructing dicts or hashtables where keys must be immutable.
FIXME: Rename function because "hashable" is misleading.
... | [
"def",
"force_hashable",
"(",
"obj",
",",
"recursive",
"=",
"True",
")",
":",
"# if it's already hashable, and isn't a generator (which are also hashable, but also mutable?)",
"if",
"hasattr",
"(",
"obj",
",",
"'__hash__'",
")",
"and",
"not",
"hasattr",
"(",
"obj",
",",... | Force frozenset() command to freeze the order and contents of mutables and iterables like lists, dicts, generators
Useful for memoization and constructing dicts or hashtables where keys must be immutable.
FIXME: Rename function because "hashable" is misleading.
A better name might be `force_immutab... | [
"Force",
"frozenset",
"()",
"command",
"to",
"freeze",
"the",
"order",
"and",
"contents",
"of",
"mutables",
"and",
"iterables",
"like",
"lists",
"dicts",
"generators"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L129-L164 | train | Force a frozen set of mutables and iterables like lists dicts and generators to freeze the order and contents of mutables and iterables like lists dicts and generators. |
totalgood/pugnlp | src/pugnlp/util.py | inverted_dict | def inverted_dict(d):
"""Return a dict with swapped keys and values
>>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}
True
"""
return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d))) | python | def inverted_dict(d):
"""Return a dict with swapped keys and values
>>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}
True
"""
return dict((force_hashable(v), k) for (k, v) in viewitems(dict(d))) | [
"def",
"inverted_dict",
"(",
"d",
")",
":",
"return",
"dict",
"(",
"(",
"force_hashable",
"(",
"v",
")",
",",
"k",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"viewitems",
"(",
"dict",
"(",
"d",
")",
")",
")"
] | Return a dict with swapped keys and values
>>> inverted_dict({0: ('a', 'b'), 1: 'cd'}) == {'cd': 1, ('a', 'b'): 0}
True | [
"Return",
"a",
"dict",
"with",
"swapped",
"keys",
"and",
"values"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L167-L173 | train | Return a dict with swapped keys and values |
totalgood/pugnlp | src/pugnlp/util.py | inverted_dict_of_lists | def inverted_dict_of_lists(d):
"""Return a dict where the keys are all the values listed in the values of the original dict
>>> inverted_dict_of_lists({0: ['a', 'b'], 1: 'cd'}) == {'a': 0, 'b': 0, 'cd': 1}
True
"""
new_dict = {}
for (old_key, old_value_list) in viewitems(dict(d)):
for n... | python | def inverted_dict_of_lists(d):
"""Return a dict where the keys are all the values listed in the values of the original dict
>>> inverted_dict_of_lists({0: ['a', 'b'], 1: 'cd'}) == {'a': 0, 'b': 0, 'cd': 1}
True
"""
new_dict = {}
for (old_key, old_value_list) in viewitems(dict(d)):
for n... | [
"def",
"inverted_dict_of_lists",
"(",
"d",
")",
":",
"new_dict",
"=",
"{",
"}",
"for",
"(",
"old_key",
",",
"old_value_list",
")",
"in",
"viewitems",
"(",
"dict",
"(",
"d",
")",
")",
":",
"for",
"new_key",
"in",
"listify",
"(",
"old_value_list",
")",
"... | Return a dict where the keys are all the values listed in the values of the original dict
>>> inverted_dict_of_lists({0: ['a', 'b'], 1: 'cd'}) == {'a': 0, 'b': 0, 'cd': 1}
True | [
"Return",
"a",
"dict",
"where",
"the",
"keys",
"are",
"all",
"the",
"values",
"listed",
"in",
"the",
"values",
"of",
"the",
"original",
"dict"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L176-L186 | train | Return a dict where the keys are all the values listed in the values of the original dict
|
totalgood/pugnlp | src/pugnlp/util.py | sort_strings | def sort_strings(strings, sort_order=None, reverse=False, case_sensitive=False, sort_order_first=True):
"""Sort a list of strings according to the provided sorted list of string prefixes
TODO:
- Provide an option to use `.startswith()` rather than a fixed prefix length (will be much slower)
Argume... | python | def sort_strings(strings, sort_order=None, reverse=False, case_sensitive=False, sort_order_first=True):
"""Sort a list of strings according to the provided sorted list of string prefixes
TODO:
- Provide an option to use `.startswith()` rather than a fixed prefix length (will be much slower)
Argume... | [
"def",
"sort_strings",
"(",
"strings",
",",
"sort_order",
"=",
"None",
",",
"reverse",
"=",
"False",
",",
"case_sensitive",
"=",
"False",
",",
"sort_order_first",
"=",
"True",
")",
":",
"if",
"not",
"case_sensitive",
":",
"sort_order",
"=",
"tuple",
"(",
"... | Sort a list of strings according to the provided sorted list of string prefixes
TODO:
- Provide an option to use `.startswith()` rather than a fixed prefix length (will be much slower)
Arguments:
sort_order_first (bool): Whether strings in sort_order should always preceed "unknown" strings
... | [
"Sort",
"a",
"list",
"of",
"strings",
"according",
"to",
"the",
"provided",
"sorted",
"list",
"of",
"string",
"prefixes"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L189-L238 | train | Sort a list of strings according to the provided sorted list of string prefixes. |
totalgood/pugnlp | src/pugnlp/util.py | clean_field_dict | def clean_field_dict(field_dict, cleaner=str.strip, time_zone=None):
r"""Normalize field values by stripping whitespace from strings, localizing datetimes to a timezone, etc
>>> (sorted(clean_field_dict({'_state': object(), 'x': 1, 'y': "\t Wash Me! \n" }).items()) ==
... [('x', 1), ('y', 'Wash Me!')])
... | python | def clean_field_dict(field_dict, cleaner=str.strip, time_zone=None):
r"""Normalize field values by stripping whitespace from strings, localizing datetimes to a timezone, etc
>>> (sorted(clean_field_dict({'_state': object(), 'x': 1, 'y': "\t Wash Me! \n" }).items()) ==
... [('x', 1), ('y', 'Wash Me!')])
... | [
"def",
"clean_field_dict",
"(",
"field_dict",
",",
"cleaner",
"=",
"str",
".",
"strip",
",",
"time_zone",
"=",
"None",
")",
":",
"d",
"=",
"{",
"}",
"if",
"time_zone",
"is",
"None",
":",
"tz",
"=",
"DEFAULT_TZ",
"for",
"k",
",",
"v",
"in",
"viewitems... | r"""Normalize field values by stripping whitespace from strings, localizing datetimes to a timezone, etc
>>> (sorted(clean_field_dict({'_state': object(), 'x': 1, 'y': "\t Wash Me! \n" }).items()) ==
... [('x', 1), ('y', 'Wash Me!')])
True | [
"r",
"Normalize",
"field",
"values",
"by",
"stripping",
"whitespace",
"from",
"strings",
"localizing",
"datetimes",
"to",
"a",
"timezone",
"etc"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L241-L260 | train | Normalize field values by stripping whitespace from strings localizing datetimes to a timezone etc. |
totalgood/pugnlp | src/pugnlp/util.py | reduce_vocab | def reduce_vocab(tokens, similarity=.85, limit=20, sort_order=-1):
"""Find spelling variations of similar words within a list of tokens to reduce token set size
Lexically sorted in reverse order (unless `reverse=False`), before running through fuzzy-wuzzy
which results in the longer of identical spellings ... | python | def reduce_vocab(tokens, similarity=.85, limit=20, sort_order=-1):
"""Find spelling variations of similar words within a list of tokens to reduce token set size
Lexically sorted in reverse order (unless `reverse=False`), before running through fuzzy-wuzzy
which results in the longer of identical spellings ... | [
"def",
"reduce_vocab",
"(",
"tokens",
",",
"similarity",
"=",
".85",
",",
"limit",
"=",
"20",
",",
"sort_order",
"=",
"-",
"1",
")",
":",
"if",
"0",
"<=",
"similarity",
"<=",
"1",
":",
"similarity",
"*=",
"100",
"if",
"sort_order",
":",
"tokens",
"="... | Find spelling variations of similar words within a list of tokens to reduce token set size
Lexically sorted in reverse order (unless `reverse=False`), before running through fuzzy-wuzzy
which results in the longer of identical spellings to be prefered (e.g. "ones" prefered to "one")
as the key token. Usual... | [
"Find",
"spelling",
"variations",
"of",
"similar",
"words",
"within",
"a",
"list",
"of",
"tokens",
"to",
"reduce",
"token",
"set",
"size"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L327-L391 | train | This function is used to reduce the vocabulary of similar words within a list of tokens. |
totalgood/pugnlp | src/pugnlp/util.py | reduce_vocab_by_len | def reduce_vocab_by_len(tokens, similarity=.87, limit=20, reverse=True):
"""Find spelling variations of similar words within a list of tokens to reduce token set size
Sorted by length (longest first unless reverse=False) before running through fuzzy-wuzzy
which results in longer key tokens.
Arguments:... | python | def reduce_vocab_by_len(tokens, similarity=.87, limit=20, reverse=True):
"""Find spelling variations of similar words within a list of tokens to reduce token set size
Sorted by length (longest first unless reverse=False) before running through fuzzy-wuzzy
which results in longer key tokens.
Arguments:... | [
"def",
"reduce_vocab_by_len",
"(",
"tokens",
",",
"similarity",
"=",
".87",
",",
"limit",
"=",
"20",
",",
"reverse",
"=",
"True",
")",
":",
"tokens",
"=",
"set",
"(",
"tokens",
")",
"tokens_sorted",
"=",
"list",
"(",
"zip",
"(",
"*",
"sorted",
"(",
"... | Find spelling variations of similar words within a list of tokens to reduce token set size
Sorted by length (longest first unless reverse=False) before running through fuzzy-wuzzy
which results in longer key tokens.
Arguments:
tokens (list or set or tuple of str): token strings from which to elimina... | [
"Find",
"spelling",
"variations",
"of",
"similar",
"words",
"within",
"a",
"list",
"of",
"tokens",
"to",
"reduce",
"token",
"set",
"size"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L394-L413 | train | Reduce the vocabulary of similar words within a list of tokens. |
totalgood/pugnlp | src/pugnlp/util.py | quantify_field_dict | def quantify_field_dict(field_dict, precision=None, date_precision=None, cleaner=str.strip):
r"""Convert strings and datetime objects in the values of a dict into float/int/long, if possible
Arguments:
field_dict (dict): The dict to have any values (not keys) that are strings "quantified"
precision... | python | def quantify_field_dict(field_dict, precision=None, date_precision=None, cleaner=str.strip):
r"""Convert strings and datetime objects in the values of a dict into float/int/long, if possible
Arguments:
field_dict (dict): The dict to have any values (not keys) that are strings "quantified"
precision... | [
"def",
"quantify_field_dict",
"(",
"field_dict",
",",
"precision",
"=",
"None",
",",
"date_precision",
"=",
"None",
",",
"cleaner",
"=",
"str",
".",
"strip",
")",
":",
"if",
"cleaner",
":",
"d",
"=",
"clean_field_dict",
"(",
"field_dict",
",",
"cleaner",
"... | r"""Convert strings and datetime objects in the values of a dict into float/int/long, if possible
Arguments:
field_dict (dict): The dict to have any values (not keys) that are strings "quantified"
precision (int): Number of digits of precision to enforce
cleaner: A string cleaner to apply to all ... | [
"r",
"Convert",
"strings",
"and",
"datetime",
"objects",
"in",
"the",
"values",
"of",
"a",
"dict",
"into",
"float",
"/",
"int",
"/",
"long",
"if",
"possible"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L416-L457 | train | r Quantify the values of a dict into float int or long. |
totalgood/pugnlp | src/pugnlp/util.py | generate_batches | def generate_batches(sequence, batch_len=1, allow_partial=True, ignore_errors=True, verbosity=1):
"""Iterate through a sequence (or generator) in batches of length `batch_len`
http://stackoverflow.com/a/761125/623735
>>> [batch for batch in generate_batches(range(7), 3)]
[[0, 1, 2], [3, 4, 5], [6]]
... | python | def generate_batches(sequence, batch_len=1, allow_partial=True, ignore_errors=True, verbosity=1):
"""Iterate through a sequence (or generator) in batches of length `batch_len`
http://stackoverflow.com/a/761125/623735
>>> [batch for batch in generate_batches(range(7), 3)]
[[0, 1, 2], [3, 4, 5], [6]]
... | [
"def",
"generate_batches",
"(",
"sequence",
",",
"batch_len",
"=",
"1",
",",
"allow_partial",
"=",
"True",
",",
"ignore_errors",
"=",
"True",
",",
"verbosity",
"=",
"1",
")",
":",
"it",
"=",
"iter",
"(",
"sequence",
")",
"last_value",
"=",
"False",
"# An... | Iterate through a sequence (or generator) in batches of length `batch_len`
http://stackoverflow.com/a/761125/623735
>>> [batch for batch in generate_batches(range(7), 3)]
[[0, 1, 2], [3, 4, 5], [6]] | [
"Iterate",
"through",
"a",
"sequence",
"(",
"or",
"generator",
")",
"in",
"batches",
"of",
"length",
"batch_len"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L460-L488 | train | Iterate through a sequence or generator in batches of length batch_len |
totalgood/pugnlp | src/pugnlp/util.py | generate_tuple_batches | def generate_tuple_batches(qs, batch_len=1):
"""Iterate through a queryset in batches of length `batch_len`
>>> [batch for batch in generate_tuple_batches(range(7), 3)]
[(0, 1, 2), (3, 4, 5), (6,)]
"""
num_items, batch = 0, []
for item in qs:
if num_items >= batch_len:
yield... | python | def generate_tuple_batches(qs, batch_len=1):
"""Iterate through a queryset in batches of length `batch_len`
>>> [batch for batch in generate_tuple_batches(range(7), 3)]
[(0, 1, 2), (3, 4, 5), (6,)]
"""
num_items, batch = 0, []
for item in qs:
if num_items >= batch_len:
yield... | [
"def",
"generate_tuple_batches",
"(",
"qs",
",",
"batch_len",
"=",
"1",
")",
":",
"num_items",
",",
"batch",
"=",
"0",
",",
"[",
"]",
"for",
"item",
"in",
"qs",
":",
"if",
"num_items",
">=",
"batch_len",
":",
"yield",
"tuple",
"(",
"batch",
")",
"num... | Iterate through a queryset in batches of length `batch_len`
>>> [batch for batch in generate_tuple_batches(range(7), 3)]
[(0, 1, 2), (3, 4, 5), (6,)] | [
"Iterate",
"through",
"a",
"queryset",
"in",
"batches",
"of",
"length",
"batch_len"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L491-L506 | train | Iterate through a queryset in batches of length batch_len |
totalgood/pugnlp | src/pugnlp/util.py | generate_slices | def generate_slices(sliceable_set, batch_len=1, length=None, start_batch=0):
"""Iterate through a sequence (or generator) in batches of length `batch_len`
See Also:
pug.dj.db.generate_queryset_batches
References:
http://stackoverflow.com/a/761125/623735
Examples:
>> [batch for batc... | python | def generate_slices(sliceable_set, batch_len=1, length=None, start_batch=0):
"""Iterate through a sequence (or generator) in batches of length `batch_len`
See Also:
pug.dj.db.generate_queryset_batches
References:
http://stackoverflow.com/a/761125/623735
Examples:
>> [batch for batc... | [
"def",
"generate_slices",
"(",
"sliceable_set",
",",
"batch_len",
"=",
"1",
",",
"length",
"=",
"None",
",",
"start_batch",
"=",
"0",
")",
":",
"if",
"length",
"is",
"None",
":",
"try",
":",
"length",
"=",
"sliceable_set",
".",
"count",
"(",
")",
"exce... | Iterate through a sequence (or generator) in batches of length `batch_len`
See Also:
pug.dj.db.generate_queryset_batches
References:
http://stackoverflow.com/a/761125/623735
Examples:
>> [batch for batch in generate_slices(range(7), 3)]
[(0, 1, 2), (3, 4, 5), (6,)]
>> from... | [
"Iterate",
"through",
"a",
"sequence",
"(",
"or",
"generator",
")",
"in",
"batches",
"of",
"length",
"batch_len"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L534-L566 | train | Iterate through a sequence of objects or generator in batches of length batch_len. |
totalgood/pugnlp | src/pugnlp/util.py | find_count_label | def find_count_label(d):
"""Find the member of a set that means "count" or "frequency" or "probability" or "number of occurrences".
"""
for name in COUNT_NAMES:
if name in d:
return name
for name in COUNT_NAMES:
if str(name).lower() in d:
return name | python | def find_count_label(d):
"""Find the member of a set that means "count" or "frequency" or "probability" or "number of occurrences".
"""
for name in COUNT_NAMES:
if name in d:
return name
for name in COUNT_NAMES:
if str(name).lower() in d:
return name | [
"def",
"find_count_label",
"(",
"d",
")",
":",
"for",
"name",
"in",
"COUNT_NAMES",
":",
"if",
"name",
"in",
"d",
":",
"return",
"name",
"for",
"name",
"in",
"COUNT_NAMES",
":",
"if",
"str",
"(",
"name",
")",
".",
"lower",
"(",
")",
"in",
"d",
":",
... | Find the member of a set that means "count" or "frequency" or "probability" or "number of occurrences". | [
"Find",
"the",
"member",
"of",
"a",
"set",
"that",
"means",
"count",
"or",
"frequency",
"or",
"probability",
"or",
"number",
"of",
"occurrences",
"."
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L569-L578 | train | Find the label of the count. |
totalgood/pugnlp | src/pugnlp/util.py | get_key_for_value | def get_key_for_value(dict_obj, value, default=None):
"""
>>> get_key_for_value({0: 'what', 'k': 'ever', 'you': 'want', 'to find': None}, 'you')
>>> get_key_for_value({0: 'what', 'k': 'ever', 'you': 'want', 'to find': None}, 'you', default='Not Found')
'Not Found'
>>> get_key_for_value({0: 'what', '... | python | def get_key_for_value(dict_obj, value, default=None):
"""
>>> get_key_for_value({0: 'what', 'k': 'ever', 'you': 'want', 'to find': None}, 'you')
>>> get_key_for_value({0: 'what', 'k': 'ever', 'you': 'want', 'to find': None}, 'you', default='Not Found')
'Not Found'
>>> get_key_for_value({0: 'what', '... | [
"def",
"get_key_for_value",
"(",
"dict_obj",
",",
"value",
",",
"default",
"=",
"None",
")",
":",
"for",
"k",
",",
"v",
"in",
"viewitems",
"(",
"dict_obj",
")",
":",
"if",
"v",
"==",
"value",
":",
"return",
"k",
"return",
"default"
] | >>> get_key_for_value({0: 'what', 'k': 'ever', 'you': 'want', 'to find': None}, 'you')
>>> get_key_for_value({0: 'what', 'k': 'ever', 'you': 'want', 'to find': None}, 'you', default='Not Found')
'Not Found'
>>> get_key_for_value({0: 'what', 'k': 'ever', 'you': 'want', 'to find': None}, 'other', default='Not... | [
">>>",
"get_key_for_value",
"(",
"{",
"0",
":",
"what",
"k",
":",
"ever",
"you",
":",
"want",
"to",
"find",
":",
"None",
"}",
"you",
")",
">>>",
"get_key_for_value",
"(",
"{",
"0",
":",
"what",
"k",
":",
"ever",
"you",
":",
"want",
"to",
"find",
... | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L586-L603 | train | Get the key for a given value in a dictionary. |
totalgood/pugnlp | src/pugnlp/util.py | list_set | def list_set(seq):
"""Similar to `list(set(seq))`, but maintains the order of `seq` while eliminating duplicates
In general list(set(L)) will not have the same order as the original list.
This is a list(set(L)) function that will preserve the order of L.
Arguments:
seq (iterable): list, tuple, o... | python | def list_set(seq):
"""Similar to `list(set(seq))`, but maintains the order of `seq` while eliminating duplicates
In general list(set(L)) will not have the same order as the original list.
This is a list(set(L)) function that will preserve the order of L.
Arguments:
seq (iterable): list, tuple, o... | [
"def",
"list_set",
"(",
"seq",
")",
":",
"new_list",
"=",
"[",
"]",
"for",
"i",
"in",
"seq",
":",
"if",
"i",
"not",
"in",
"new_list",
":",
"new_list",
"+=",
"[",
"i",
"]",
"return",
"type",
"(",
"seq",
")",
"(",
"new_list",
")"
] | Similar to `list(set(seq))`, but maintains the order of `seq` while eliminating duplicates
In general list(set(L)) will not have the same order as the original list.
This is a list(set(L)) function that will preserve the order of L.
Arguments:
seq (iterable): list, tuple, or other iterable to be use... | [
"Similar",
"to",
"list",
"(",
"set",
"(",
"seq",
"))",
"but",
"maintains",
"the",
"order",
"of",
"seq",
"while",
"eliminating",
"duplicates"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L606-L628 | train | Similar to list ( set ( seq ) but maintains the order of the original list while eliminating duplicates
MimeType |
totalgood/pugnlp | src/pugnlp/util.py | fuzzy_get | def fuzzy_get(possible_keys, approximate_key, default=None, similarity=0.6, tuple_joiner='|',
key_and_value=False, dict_keys=None):
r"""Find the closest matching key in a dictionary (or element in a list)
For a dict, optionally retrieve the associated value associated with the closest key
No... | python | def fuzzy_get(possible_keys, approximate_key, default=None, similarity=0.6, tuple_joiner='|',
key_and_value=False, dict_keys=None):
r"""Find the closest matching key in a dictionary (or element in a list)
For a dict, optionally retrieve the associated value associated with the closest key
No... | [
"def",
"fuzzy_get",
"(",
"possible_keys",
",",
"approximate_key",
",",
"default",
"=",
"None",
",",
"similarity",
"=",
"0.6",
",",
"tuple_joiner",
"=",
"'|'",
",",
"key_and_value",
"=",
"False",
",",
"dict_keys",
"=",
"None",
")",
":",
"dict_obj",
"=",
"co... | r"""Find the closest matching key in a dictionary (or element in a list)
For a dict, optionally retrieve the associated value associated with the closest key
Notes:
`possible_keys` must have all string elements or keys!
Argument order is in reverse order relative to `fuzzywuzzy.process.extractOne(... | [
"r",
"Find",
"the",
"closest",
"matching",
"key",
"in",
"a",
"dictionary",
"(",
"or",
"element",
"in",
"a",
"list",
")"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L631-L729 | train | r Returns the closest matching key in a dictionary or element in a list. |
totalgood/pugnlp | src/pugnlp/util.py | fuzzy_get_value | def fuzzy_get_value(obj, approximate_key, default=None, **kwargs):
""" Like fuzzy_get, but assume the obj is dict-like and return the value without the key
Notes:
Argument order is in reverse order relative to `fuzzywuzzy.process.extractOne()`
but in the same order as get(self, key) method on dic... | python | def fuzzy_get_value(obj, approximate_key, default=None, **kwargs):
""" Like fuzzy_get, but assume the obj is dict-like and return the value without the key
Notes:
Argument order is in reverse order relative to `fuzzywuzzy.process.extractOne()`
but in the same order as get(self, key) method on dic... | [
"def",
"fuzzy_get_value",
"(",
"obj",
",",
"approximate_key",
",",
"default",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"dict_obj",
"=",
"OrderedDict",
"(",
"obj",
")",
"try",
":",
"return",
"dict_obj",
"[",
"list",
"(",
"dict_obj",
".",
"keys",
... | Like fuzzy_get, but assume the obj is dict-like and return the value without the key
Notes:
Argument order is in reverse order relative to `fuzzywuzzy.process.extractOne()`
but in the same order as get(self, key) method on dicts
Arguments:
obj (dict-like): object to run the get method on u... | [
"Like",
"fuzzy_get",
"but",
"assume",
"the",
"obj",
"is",
"dict",
"-",
"like",
"and",
"return",
"the",
"value",
"without",
"the",
"key"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L732-L770 | train | This is a convenience method that uses fuzzywuzzy to get the value of a key in a dict - like object. |
totalgood/pugnlp | src/pugnlp/util.py | fuzzy_get_tuple | def fuzzy_get_tuple(dict_obj, approximate_key, dict_keys=None, key_and_value=False, similarity=0.6, default=None):
"""Find the closest matching key and/or value in a dictionary (must have all string keys!)"""
return fuzzy_get(dict(('|'.join(str(k2) for k2 in k), v) for (k, v) in viewitems(dict_obj)),
... | python | def fuzzy_get_tuple(dict_obj, approximate_key, dict_keys=None, key_and_value=False, similarity=0.6, default=None):
"""Find the closest matching key and/or value in a dictionary (must have all string keys!)"""
return fuzzy_get(dict(('|'.join(str(k2) for k2 in k), v) for (k, v) in viewitems(dict_obj)),
... | [
"def",
"fuzzy_get_tuple",
"(",
"dict_obj",
",",
"approximate_key",
",",
"dict_keys",
"=",
"None",
",",
"key_and_value",
"=",
"False",
",",
"similarity",
"=",
"0.6",
",",
"default",
"=",
"None",
")",
":",
"return",
"fuzzy_get",
"(",
"dict",
"(",
"(",
"'|'",... | Find the closest matching key and/or value in a dictionary (must have all string keys!) | [
"Find",
"the",
"closest",
"matching",
"key",
"and",
"/",
"or",
"value",
"in",
"a",
"dictionary",
"(",
"must",
"have",
"all",
"string",
"keys!",
")"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L773-L777 | train | Find the closest matching key and value in a dictionary. |
totalgood/pugnlp | src/pugnlp/util.py | sod_transposed | def sod_transposed(seq_of_dicts, align=True, pad=True, filler=None):
"""Return sequence (list) of dictionaries, transposed into a dictionary of sequences (lists)
>>> sorted(sod_transposed([{'c': 1, 'cm': 'P'}, {'c': 1, 'ct': 2, 'cm': 6, 'cn': 'MUS'},
... {'c': 1, 'cm': 'Q', 'cn': 'RO... | python | def sod_transposed(seq_of_dicts, align=True, pad=True, filler=None):
"""Return sequence (list) of dictionaries, transposed into a dictionary of sequences (lists)
>>> sorted(sod_transposed([{'c': 1, 'cm': 'P'}, {'c': 1, 'ct': 2, 'cm': 6, 'cn': 'MUS'},
... {'c': 1, 'cm': 'Q', 'cn': 'RO... | [
"def",
"sod_transposed",
"(",
"seq_of_dicts",
",",
"align",
"=",
"True",
",",
"pad",
"=",
"True",
",",
"filler",
"=",
"None",
")",
":",
"result",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"seq_of_dicts",
",",
"Mapping",
")",
":",
"seq_of_dicts",
"=",
"["... | Return sequence (list) of dictionaries, transposed into a dictionary of sequences (lists)
>>> sorted(sod_transposed([{'c': 1, 'cm': 'P'}, {'c': 1, 'ct': 2, 'cm': 6, 'cn': 'MUS'},
... {'c': 1, 'cm': 'Q', 'cn': 'ROM'}], filler=0).items())
[('c', [1, 1, 1]), ('cm', ['P', 6, 'Q']), ('cn'... | [
"Return",
"sequence",
"(",
"list",
")",
"of",
"dictionaries",
"transposed",
"into",
"a",
"dictionary",
"of",
"sequences",
"(",
"lists",
")"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L780-L808 | train | Return sequence of dictionaries transposed into a dictionary of lists |
totalgood/pugnlp | src/pugnlp/util.py | joined_seq | def joined_seq(seq, sep=None):
r"""Join a sequence into a tuple or a concatenated string
>>> joined_seq(range(3), ', ')
'0, 1, 2'
>>> joined_seq([1, 2, 3])
(1, 2, 3)
"""
joined_seq = tuple(seq)
if isinstance(sep, basestring):
joined_seq = sep.join(str(item) for item in joined_se... | python | def joined_seq(seq, sep=None):
r"""Join a sequence into a tuple or a concatenated string
>>> joined_seq(range(3), ', ')
'0, 1, 2'
>>> joined_seq([1, 2, 3])
(1, 2, 3)
"""
joined_seq = tuple(seq)
if isinstance(sep, basestring):
joined_seq = sep.join(str(item) for item in joined_se... | [
"def",
"joined_seq",
"(",
"seq",
",",
"sep",
"=",
"None",
")",
":",
"joined_seq",
"=",
"tuple",
"(",
"seq",
")",
"if",
"isinstance",
"(",
"sep",
",",
"basestring",
")",
":",
"joined_seq",
"=",
"sep",
".",
"join",
"(",
"str",
"(",
"item",
")",
"for"... | r"""Join a sequence into a tuple or a concatenated string
>>> joined_seq(range(3), ', ')
'0, 1, 2'
>>> joined_seq([1, 2, 3])
(1, 2, 3) | [
"r",
"Join",
"a",
"sequence",
"into",
"a",
"tuple",
"or",
"a",
"concatenated",
"string"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L811-L822 | train | r Join a sequence into a tuple or a concatenated string |
totalgood/pugnlp | src/pugnlp/util.py | consolidate_stats | def consolidate_stats(dict_of_seqs, stats_key=None, sep=','):
"""Join (stringify and concatenate) keys (table fields) in a dict (table) of sequences (columns)
>>> consolidate_stats(dict([('c', [1, 1, 1]), ('cm', ['P', 6, 'Q']), ('cn', [0, 'MUS', 'ROM']),
... ('ct', [0, 2, 0])]), stat... | python | def consolidate_stats(dict_of_seqs, stats_key=None, sep=','):
"""Join (stringify and concatenate) keys (table fields) in a dict (table) of sequences (columns)
>>> consolidate_stats(dict([('c', [1, 1, 1]), ('cm', ['P', 6, 'Q']), ('cn', [0, 'MUS', 'ROM']),
... ('ct', [0, 2, 0])]), stat... | [
"def",
"consolidate_stats",
"(",
"dict_of_seqs",
",",
"stats_key",
"=",
"None",
",",
"sep",
"=",
"','",
")",
":",
"if",
"isinstance",
"(",
"dict_of_seqs",
",",
"dict",
")",
":",
"stats",
"=",
"dict_of_seqs",
"[",
"stats_key",
"]",
"keys",
"=",
"joined_seq"... | Join (stringify and concatenate) keys (table fields) in a dict (table) of sequences (columns)
>>> consolidate_stats(dict([('c', [1, 1, 1]), ('cm', ['P', 6, 'Q']), ('cn', [0, 'MUS', 'ROM']),
... ('ct', [0, 2, 0])]), stats_key='c')
[{'P,0,0': 1}, {'6,MUS,2': 1}, {'Q,ROM,0': 1}]
>>>... | [
"Join",
"(",
"stringify",
"and",
"concatenate",
")",
"keys",
"(",
"table",
"fields",
")",
"in",
"a",
"dict",
"(",
"table",
")",
"of",
"sequences",
"(",
"columns",
")"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L825-L844 | train | Consolidate stats from a dict of sequences into a single tree of new tree items. |
totalgood/pugnlp | src/pugnlp/util.py | dos_from_table | def dos_from_table(table, header=None):
"""Produce dictionary of sequences from sequence of sequences, optionally with a header "row".
>>> dos_from_table([['hello', 'world'], [1, 2], [3,4]]) == {'hello': [1, 3], 'world': [2, 4]}
True
"""
start_row = 0
if not table:
return table
if n... | python | def dos_from_table(table, header=None):
"""Produce dictionary of sequences from sequence of sequences, optionally with a header "row".
>>> dos_from_table([['hello', 'world'], [1, 2], [3,4]]) == {'hello': [1, 3], 'world': [2, 4]}
True
"""
start_row = 0
if not table:
return table
if n... | [
"def",
"dos_from_table",
"(",
"table",
",",
"header",
"=",
"None",
")",
":",
"start_row",
"=",
"0",
"if",
"not",
"table",
":",
"return",
"table",
"if",
"not",
"header",
":",
"header",
"=",
"table",
"[",
"0",
"]",
"start_row",
"=",
"1",
"header_list",
... | Produce dictionary of sequences from sequence of sequences, optionally with a header "row".
>>> dos_from_table([['hello', 'world'], [1, 2], [3,4]]) == {'hello': [1, 3], 'world': [2, 4]}
True | [
"Produce",
"dictionary",
"of",
"sequences",
"from",
"sequence",
"of",
"sequences",
"optionally",
"with",
"a",
"header",
"row",
"."
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L847-L869 | train | Produce dictionary of sequences from sequence of sequences optionally with a header row. |
totalgood/pugnlp | src/pugnlp/util.py | transposed_lists | def transposed_lists(list_of_lists, default=None):
"""Like `numpy.transposed`, but allows uneven row lengths
Uneven lengths will affect the order of the elements in the rows of the transposed lists
>>> transposed_lists([[1, 2], [3, 4, 5], [6]])
[[1, 3, 6], [2, 4], [5]]
>>> transposed_lists(transpo... | python | def transposed_lists(list_of_lists, default=None):
"""Like `numpy.transposed`, but allows uneven row lengths
Uneven lengths will affect the order of the elements in the rows of the transposed lists
>>> transposed_lists([[1, 2], [3, 4, 5], [6]])
[[1, 3, 6], [2, 4], [5]]
>>> transposed_lists(transpo... | [
"def",
"transposed_lists",
"(",
"list_of_lists",
",",
"default",
"=",
"None",
")",
":",
"if",
"default",
"is",
"None",
"or",
"default",
"is",
"[",
"]",
"or",
"default",
"is",
"tuple",
"(",
")",
":",
"default",
"=",
"[",
"]",
"elif",
"default",
"is",
... | Like `numpy.transposed`, but allows uneven row lengths
Uneven lengths will affect the order of the elements in the rows of the transposed lists
>>> transposed_lists([[1, 2], [3, 4, 5], [6]])
[[1, 3, 6], [2, 4], [5]]
>>> transposed_lists(transposed_lists([[], [1, 2, 3], [4]]))
[[1, 2, 3], [4]]
... | [
"Like",
"numpy",
".",
"transposed",
"but",
"allows",
"uneven",
"row",
"lengths"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L872-L905 | train | Like numpy. transposed but allows uneven row lengths
|
totalgood/pugnlp | src/pugnlp/util.py | transposed_matrix | def transposed_matrix(matrix, filler=None, row_type=list, matrix_type=list, value_type=None):
"""Like numpy.transposed, evens up row (list) lengths that aren't uniform, filling with None.
Also, makes all elements a uniform type (default=type(matrix[0][0])),
except for filler elements.
TODO: add featur... | python | def transposed_matrix(matrix, filler=None, row_type=list, matrix_type=list, value_type=None):
"""Like numpy.transposed, evens up row (list) lengths that aren't uniform, filling with None.
Also, makes all elements a uniform type (default=type(matrix[0][0])),
except for filler elements.
TODO: add featur... | [
"def",
"transposed_matrix",
"(",
"matrix",
",",
"filler",
"=",
"None",
",",
"row_type",
"=",
"list",
",",
"matrix_type",
"=",
"list",
",",
"value_type",
"=",
"None",
")",
":",
"matrix_type",
"=",
"matrix_type",
"or",
"type",
"(",
"matrix",
")",
"try",
":... | Like numpy.transposed, evens up row (list) lengths that aren't uniform, filling with None.
Also, makes all elements a uniform type (default=type(matrix[0][0])),
except for filler elements.
TODO: add feature to delete None's at the end of rows so that transpose(transpose(LOL)) = LOL
>>> transposed_mat... | [
"Like",
"numpy",
".",
"transposed",
"evens",
"up",
"row",
"(",
"list",
")",
"lengths",
"that",
"aren",
"t",
"uniform",
"filling",
"with",
"None",
"."
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L908-L969 | train | Like numpy. transposed but evens up row lengths that aren t uniform filling with None. |
totalgood/pugnlp | src/pugnlp/util.py | hist_from_counts | def hist_from_counts(counts, normalize=False, cumulative=False, to_str=False, sep=',', min_bin=None, max_bin=None):
"""Compute an emprical histogram, PMF or CDF in a list of lists
TESTME: compare results to hist_from_values_list and hist_from_float_values_list
"""
counters = [dict((i, c)for i, c in enu... | python | def hist_from_counts(counts, normalize=False, cumulative=False, to_str=False, sep=',', min_bin=None, max_bin=None):
"""Compute an emprical histogram, PMF or CDF in a list of lists
TESTME: compare results to hist_from_values_list and hist_from_float_values_list
"""
counters = [dict((i, c)for i, c in enu... | [
"def",
"hist_from_counts",
"(",
"counts",
",",
"normalize",
"=",
"False",
",",
"cumulative",
"=",
"False",
",",
"to_str",
"=",
"False",
",",
"sep",
"=",
"','",
",",
"min_bin",
"=",
"None",
",",
"max_bin",
"=",
"None",
")",
":",
"counters",
"=",
"[",
... | Compute an emprical histogram, PMF or CDF in a list of lists
TESTME: compare results to hist_from_values_list and hist_from_float_values_list | [
"Compute",
"an",
"emprical",
"histogram",
"PMF",
"or",
"CDF",
"in",
"a",
"list",
"of",
"lists"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L972-L1011 | train | Compute an emprical histogram PMF or CDF in a list of lists
|
totalgood/pugnlp | src/pugnlp/util.py | hist_from_values_list | def hist_from_values_list(values_list, fillers=(None,), normalize=False,
cumulative=False, to_str=False, sep=',', min_bin=None, max_bin=None):
"""Compute an emprical histogram, PMF or CDF in a list of lists or a csv string
Only works for discrete (integer) values (doesn't bin real val... | python | def hist_from_values_list(values_list, fillers=(None,), normalize=False,
cumulative=False, to_str=False, sep=',', min_bin=None, max_bin=None):
"""Compute an emprical histogram, PMF or CDF in a list of lists or a csv string
Only works for discrete (integer) values (doesn't bin real val... | [
"def",
"hist_from_values_list",
"(",
"values_list",
",",
"fillers",
"=",
"(",
"None",
",",
")",
",",
"normalize",
"=",
"False",
",",
"cumulative",
"=",
"False",
",",
"to_str",
"=",
"False",
",",
"sep",
"=",
"','",
",",
"min_bin",
"=",
"None",
",",
"max... | Compute an emprical histogram, PMF or CDF in a list of lists or a csv string
Only works for discrete (integer) values (doesn't bin real values).
`fillers`: list or tuple of values to ignore in computing the histogram
>>> hist_from_values_list([1,1,2,1,1,1,2,3,2,4,4,5,7,7,9]) # doctest: +NORMALIZE_WHITESP... | [
"Compute",
"an",
"emprical",
"histogram",
"PMF",
"or",
"CDF",
"in",
"a",
"list",
"of",
"lists",
"or",
"a",
"csv",
"string"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1014-L1091 | train | Compute an emprical histogram PMF or CDF in a list of lists or csv string. |
totalgood/pugnlp | src/pugnlp/util.py | get_similar | def get_similar(obj, labels, default=None, min_similarity=0.5):
"""Similar to fuzzy_get, but allows non-string keys and a list of possible keys
Searches attributes in addition to keys and indexes to find the closest match.
See Also:
`fuzzy_get`
"""
raise NotImplementedError(
"Unfi... | python | def get_similar(obj, labels, default=None, min_similarity=0.5):
"""Similar to fuzzy_get, but allows non-string keys and a list of possible keys
Searches attributes in addition to keys and indexes to find the closest match.
See Also:
`fuzzy_get`
"""
raise NotImplementedError(
"Unfi... | [
"def",
"get_similar",
"(",
"obj",
",",
"labels",
",",
"default",
"=",
"None",
",",
"min_similarity",
"=",
"0.5",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Unfinished implementation, needs to be in fuzzy_get where list of scores & keywords is sorted.\"",
")",
"labels... | Similar to fuzzy_get, but allows non-string keys and a list of possible keys
Searches attributes in addition to keys and indexes to find the closest match.
See Also:
`fuzzy_get` | [
"Similar",
"to",
"fuzzy_get",
"but",
"allows",
"non",
"-",
"string",
"keys",
"and",
"a",
"list",
"of",
"possible",
"keys"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1094-L1126 | train | Similar to fuzzy_get but allows non - string keys and a list of possible keys
vms. |
totalgood/pugnlp | src/pugnlp/util.py | update_dict | def update_dict(d, u=None, depth=-1, take_new=True, default_mapping_type=dict, prefer_update_type=False, copy=False):
"""
Recursively merge (union or update) dict-like objects (Mapping) to the specified depth.
>>> update_dict({'k1': {'k2': 2}}, {'k1': {'k2': {'k3': 3}}, 'k4': 4}) == {'k1': {'k2': {'k3': 3}... | python | def update_dict(d, u=None, depth=-1, take_new=True, default_mapping_type=dict, prefer_update_type=False, copy=False):
"""
Recursively merge (union or update) dict-like objects (Mapping) to the specified depth.
>>> update_dict({'k1': {'k2': 2}}, {'k1': {'k2': {'k3': 3}}, 'k4': 4}) == {'k1': {'k2': {'k3': 3}... | [
"def",
"update_dict",
"(",
"d",
",",
"u",
"=",
"None",
",",
"depth",
"=",
"-",
"1",
",",
"take_new",
"=",
"True",
",",
"default_mapping_type",
"=",
"dict",
",",
"prefer_update_type",
"=",
"False",
",",
"copy",
"=",
"False",
")",
":",
"u",
"=",
"u",
... | Recursively merge (union or update) dict-like objects (Mapping) to the specified depth.
>>> update_dict({'k1': {'k2': 2}}, {'k1': {'k2': {'k3': 3}}, 'k4': 4}) == {'k1': {'k2': {'k3': 3}}, 'k4': 4}
True
>>> update_dict(OrderedDict([('k1', OrderedDict([('k2', 2)]))]), {'k1': {'k2': {'k3': 3}}, 'k4': 4})
... | [
"Recursively",
"merge",
"(",
"union",
"or",
"update",
")",
"dict",
"-",
"like",
"objects",
"(",
"Mapping",
")",
"to",
"the",
"specified",
"depth",
"."
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1136-L1184 | train | Recursively updates a dict - like object. |
totalgood/pugnlp | src/pugnlp/util.py | make_name | def make_name(s, camel=None, lower=None, space='_', remove_prefix=None, language='python', string_type=str):
"""Process a string to produce a valid python variable/class/type name
Arguments:
space (str): string to substitute for spaces ('' to delete all whitespace)
camel (bool): whether to camel-ca... | python | def make_name(s, camel=None, lower=None, space='_', remove_prefix=None, language='python', string_type=str):
"""Process a string to produce a valid python variable/class/type name
Arguments:
space (str): string to substitute for spaces ('' to delete all whitespace)
camel (bool): whether to camel-ca... | [
"def",
"make_name",
"(",
"s",
",",
"camel",
"=",
"None",
",",
"lower",
"=",
"None",
",",
"space",
"=",
"'_'",
",",
"remove_prefix",
"=",
"None",
",",
"language",
"=",
"'python'",
",",
"string_type",
"=",
"str",
")",
":",
"if",
"camel",
"is",
"None",
... | Process a string to produce a valid python variable/class/type name
Arguments:
space (str): string to substitute for spaces ('' to delete all whitespace)
camel (bool): whether to camel-case names, Django Model Name style (first letter capitalized)
lower (bool): whether to lowercase all strings
... | [
"Process",
"a",
"string",
"to",
"produce",
"a",
"valid",
"python",
"variable",
"/",
"class",
"/",
"type",
"name"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1209-L1272 | train | Generates a valid python variable name from a string. |
totalgood/pugnlp | src/pugnlp/util.py | make_filename | def make_filename(s, space=None, language='msdos', strict=False, max_len=None, repeats=1024):
r"""Process string to remove any characters not allowed by the language specified (default: MSDOS)
In addition, optionally replace spaces with the indicated "space" character
(to make the path useful in a copy-pas... | python | def make_filename(s, space=None, language='msdos', strict=False, max_len=None, repeats=1024):
r"""Process string to remove any characters not allowed by the language specified (default: MSDOS)
In addition, optionally replace spaces with the indicated "space" character
(to make the path useful in a copy-pas... | [
"def",
"make_filename",
"(",
"s",
",",
"space",
"=",
"None",
",",
"language",
"=",
"'msdos'",
",",
"strict",
"=",
"False",
",",
"max_len",
"=",
"None",
",",
"repeats",
"=",
"1024",
")",
":",
"filename",
"=",
"None",
"if",
"strict",
"or",
"language",
... | r"""Process string to remove any characters not allowed by the language specified (default: MSDOS)
In addition, optionally replace spaces with the indicated "space" character
(to make the path useful in a copy-paste without quoting).
Uses the following regular expression to substitute spaces for invalid c... | [
"r",
"Process",
"string",
"to",
"remove",
"any",
"characters",
"not",
"allowed",
"by",
"the",
"language",
"specified",
"(",
"default",
":",
"MSDOS",
")"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1279-L1325 | train | Make a filename from a string. |
totalgood/pugnlp | src/pugnlp/util.py | update_file_ext | def update_file_ext(filename, ext='txt', sep='.'):
r"""Force the file or path str to end with the indicated extension
Note: a dot (".") is assumed to delimit the extension
>>> from __future__ import unicode_literals
>>> update_file_ext('/home/hobs/extremofile', 'bac')
'/home/hobs/extremofile.bac'
... | python | def update_file_ext(filename, ext='txt', sep='.'):
r"""Force the file or path str to end with the indicated extension
Note: a dot (".") is assumed to delimit the extension
>>> from __future__ import unicode_literals
>>> update_file_ext('/home/hobs/extremofile', 'bac')
'/home/hobs/extremofile.bac'
... | [
"def",
"update_file_ext",
"(",
"filename",
",",
"ext",
"=",
"'txt'",
",",
"sep",
"=",
"'.'",
")",
":",
"path",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"filename",
")",
"if",
"ext",
"and",
"ext",
"[",
"0",
"]",
"==",
"sep",
":"... | r"""Force the file or path str to end with the indicated extension
Note: a dot (".") is assumed to delimit the extension
>>> from __future__ import unicode_literals
>>> update_file_ext('/home/hobs/extremofile', 'bac')
'/home/hobs/extremofile.bac'
>>> update_file_ext('/home/hobs/piano.file/', 'musi... | [
"r",
"Force",
"the",
"file",
"or",
"path",
"str",
"to",
"end",
"with",
"the",
"indicated",
"extension"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1328-L1347 | train | r Force the file or path str to end with the indicated extension
|
totalgood/pugnlp | src/pugnlp/util.py | tryconvert | def tryconvert(value, desired_types=SCALAR_TYPES, default=None, empty='', strip=True):
"""
Convert value to one of the desired_types specified (in order of preference) without raising an exception.
If value is empty is a string and Falsey, then return the `empty` value specified.
If value can't be conv... | python | def tryconvert(value, desired_types=SCALAR_TYPES, default=None, empty='', strip=True):
"""
Convert value to one of the desired_types specified (in order of preference) without raising an exception.
If value is empty is a string and Falsey, then return the `empty` value specified.
If value can't be conv... | [
"def",
"tryconvert",
"(",
"value",
",",
"desired_types",
"=",
"SCALAR_TYPES",
",",
"default",
"=",
"None",
",",
"empty",
"=",
"''",
",",
"strip",
"=",
"True",
")",
":",
"if",
"value",
"in",
"tryconvert",
".",
"EMPTY",
":",
"if",
"isinstance",
"(",
"val... | Convert value to one of the desired_types specified (in order of preference) without raising an exception.
If value is empty is a string and Falsey, then return the `empty` value specified.
If value can't be converted to any of the desired_types requested, then return the `default` value specified.
>>> tr... | [
"Convert",
"value",
"to",
"one",
"of",
"the",
"desired_types",
"specified",
"(",
"in",
"order",
"of",
"preference",
")",
"without",
"raising",
"an",
"exception",
"."
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1350-L1397 | train | Try to convert value to one of the desired_types. |
totalgood/pugnlp | src/pugnlp/util.py | transcode | def transcode(infile, outfile=None, incoding="shift-jis", outcoding="utf-8"):
"""Change encoding of text file"""
if not outfile:
outfile = os.path.basename(infile) + '.utf8'
with codecs.open(infile, "rb", incoding) as fpin:
with codecs.open(outfile, "wb", outcoding) as fpout:
fpo... | python | def transcode(infile, outfile=None, incoding="shift-jis", outcoding="utf-8"):
"""Change encoding of text file"""
if not outfile:
outfile = os.path.basename(infile) + '.utf8'
with codecs.open(infile, "rb", incoding) as fpin:
with codecs.open(outfile, "wb", outcoding) as fpout:
fpo... | [
"def",
"transcode",
"(",
"infile",
",",
"outfile",
"=",
"None",
",",
"incoding",
"=",
"\"shift-jis\"",
",",
"outcoding",
"=",
"\"utf-8\"",
")",
":",
"if",
"not",
"outfile",
":",
"outfile",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"infile",
")",
"+... | Change encoding of text file | [
"Change",
"encoding",
"of",
"text",
"file"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1404-L1410 | train | Change encoding of text file |
totalgood/pugnlp | src/pugnlp/util.py | strip_br | def strip_br(s):
r""" Strip the trailing html linebreak character (<BR />) from a string or sequence of strings
A sequence of strings is assumed to be a row in a CSV/TSV file or words from a line of text
so only the last element in a sequence is "stripped"
>>> strip_br(' Title <BR> ')
' Title'
... | python | def strip_br(s):
r""" Strip the trailing html linebreak character (<BR />) from a string or sequence of strings
A sequence of strings is assumed to be a row in a CSV/TSV file or words from a line of text
so only the last element in a sequence is "stripped"
>>> strip_br(' Title <BR> ')
' Title'
... | [
"def",
"strip_br",
"(",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"basestring",
")",
":",
"return",
"re",
".",
"sub",
"(",
"r'\\s*<\\s*[Bb][Rr]\\s*[/]?\\s*>\\s*$'",
",",
"''",
",",
"s",
")",
"elif",
"isinstance",
"(",
"s",
",",
"(",
"tuple",
",... | r""" Strip the trailing html linebreak character (<BR />) from a string or sequence of strings
A sequence of strings is assumed to be a row in a CSV/TSV file or words from a line of text
so only the last element in a sequence is "stripped"
>>> strip_br(' Title <BR> ')
' Title'
>>> strip_br(list(ra... | [
"r",
"Strip",
"the",
"trailing",
"html",
"linebreak",
"character",
"(",
"<BR",
"/",
">",
")",
"from",
"a",
"string",
"or",
"sequence",
"of",
"strings"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1413-L1448 | train | r Strip the trailing html linebreak character from a string or sequence of strings. |
totalgood/pugnlp | src/pugnlp/util.py | read_csv | def read_csv(csv_file, ext='.csv', format=None, delete_empty_keys=False,
fieldnames=[], rowlimit=100000000, numbers=False, normalize_names=True, unique_names=True,
verbosity=0):
r"""
Read a csv file from a path or file pointer, returning a dict of lists, or list of lists (according to ... | python | def read_csv(csv_file, ext='.csv', format=None, delete_empty_keys=False,
fieldnames=[], rowlimit=100000000, numbers=False, normalize_names=True, unique_names=True,
verbosity=0):
r"""
Read a csv file from a path or file pointer, returning a dict of lists, or list of lists (according to ... | [
"def",
"read_csv",
"(",
"csv_file",
",",
"ext",
"=",
"'.csv'",
",",
"format",
"=",
"None",
",",
"delete_empty_keys",
"=",
"False",
",",
"fieldnames",
"=",
"[",
"]",
",",
"rowlimit",
"=",
"100000000",
",",
"numbers",
"=",
"False",
",",
"normalize_names",
... | r"""
Read a csv file from a path or file pointer, returning a dict of lists, or list of lists (according to `format`)
filename: a directory or list of file paths
numbers: whether to attempt to convert strings in csv to numbers
TODO:
merge with `nlp.util.make_dataframe` function
Handles un... | [
"r",
"Read",
"a",
"csv",
"file",
"from",
"a",
"path",
"or",
"file",
"pointer",
"returning",
"a",
"dict",
"of",
"lists",
"or",
"list",
"of",
"lists",
"(",
"according",
"to",
"format",
")"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1451-L1583 | train | r Reads a CSV file into a dict of lists or lists. |
totalgood/pugnlp | src/pugnlp/util.py | dict2obj | def dict2obj(d):
"""Convert a dict to an object or namespace
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
>>> obj = dict2obj(d)
>>> obj.b.c
2
>>> obj.d
['hi', {'foo': 'bar'}]
>>> d = {'a': 1, 'b': {'c': 2}, 'd': [("hi", {'foo': "bar"})]}
>>> obj = dict2obj(d)
>>... | python | def dict2obj(d):
"""Convert a dict to an object or namespace
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
>>> obj = dict2obj(d)
>>> obj.b.c
2
>>> obj.d
['hi', {'foo': 'bar'}]
>>> d = {'a': 1, 'b': {'c': 2}, 'd': [("hi", {'foo': "bar"})]}
>>> obj = dict2obj(d)
>>... | [
"def",
"dict2obj",
"(",
"d",
")",
":",
"if",
"isinstance",
"(",
"d",
",",
"(",
"Mapping",
",",
"list",
",",
"tuple",
")",
")",
":",
"try",
":",
"d",
"=",
"dict",
"(",
"d",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"return",
... | Convert a dict to an object or namespace
>>> d = {'a': 1, 'b': {'c': 2}, 'd': ["hi", {'foo': "bar"}]}
>>> obj = dict2obj(d)
>>> obj.b.c
2
>>> obj.d
['hi', {'foo': 'bar'}]
>>> d = {'a': 1, 'b': {'c': 2}, 'd': [("hi", {'foo': "bar"})]}
>>> obj = dict2obj(d)
>>> obj.d.hi.foo
'bar' | [
"Convert",
"a",
"dict",
"to",
"an",
"object",
"or",
"namespace"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1602-L1627 | train | Convert a dict to an object or namespace
|
totalgood/pugnlp | src/pugnlp/util.py | make_series | def make_series(x, *args, **kwargs):
"""Coerce a provided array/sequence/generator into a pandas.Series object
FIXME: Deal with CSR, COO, DOK and other sparse matrices like this:
pd.Series(csr.toarray()[:,0])
or, if csr.shape[1] == 2
pd.Series(csr.toarray()[:,1], index=csr.toarray()[:,0])... | python | def make_series(x, *args, **kwargs):
"""Coerce a provided array/sequence/generator into a pandas.Series object
FIXME: Deal with CSR, COO, DOK and other sparse matrices like this:
pd.Series(csr.toarray()[:,0])
or, if csr.shape[1] == 2
pd.Series(csr.toarray()[:,1], index=csr.toarray()[:,0])... | [
"def",
"make_series",
"(",
"x",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"pd",
".",
"Series",
")",
":",
"return",
"x",
"try",
":",
"if",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"'pk'",
"not",
... | Coerce a provided array/sequence/generator into a pandas.Series object
FIXME: Deal with CSR, COO, DOK and other sparse matrices like this:
pd.Series(csr.toarray()[:,0])
or, if csr.shape[1] == 2
pd.Series(csr.toarray()[:,1], index=csr.toarray()[:,0])
>>> make_series(range(1, 4))
0 1... | [
"Coerce",
"a",
"provided",
"array",
"/",
"sequence",
"/",
"generator",
"into",
"a",
"pandas",
".",
"Series",
"object",
"FIXME",
":",
"Deal",
"with",
"CSR",
"COO",
"DOK",
"and",
"other",
"sparse",
"matrices",
"like",
"this",
":",
"pd",
".",
"Series",
"(",... | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1645-L1696 | train | Coerce a provided array or sequence generator into a pandas. Series |
totalgood/pugnlp | src/pugnlp/util.py | encode | def encode(obj):
r"""Encode all unicode/str objects in a dataframe in the encoding indicated (as a fun attribute)
similar to to_ascii, but doesn't return a None, even when it fails.
>>> encode(u'Is 2013 a year or a code point for "\u2013"?')
b'Is 2013 a year or a code point for "\xe2\x80\x93"?'
>>>... | python | def encode(obj):
r"""Encode all unicode/str objects in a dataframe in the encoding indicated (as a fun attribute)
similar to to_ascii, but doesn't return a None, even when it fails.
>>> encode(u'Is 2013 a year or a code point for "\u2013"?')
b'Is 2013 a year or a code point for "\xe2\x80\x93"?'
>>>... | [
"def",
"encode",
"(",
"obj",
")",
":",
"try",
":",
"return",
"obj",
".",
"encode",
"(",
"encode",
".",
"encoding",
")",
"except",
"AttributeError",
":",
"pass",
"except",
"UnicodeDecodeError",
":",
"logger",
".",
"warning",
"(",
"'Problem with byte sequence of... | r"""Encode all unicode/str objects in a dataframe in the encoding indicated (as a fun attribute)
similar to to_ascii, but doesn't return a None, even when it fails.
>>> encode(u'Is 2013 a year or a code point for "\u2013"?')
b'Is 2013 a year or a code point for "\xe2\x80\x93"?'
>>> print(u'Is 2013 a ye... | [
"r",
"Encode",
"all",
"unicode",
"/",
"str",
"objects",
"in",
"a",
"dataframe",
"in",
"the",
"encoding",
"indicated",
"(",
"as",
"a",
"fun",
"attribute",
")"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1699-L1717 | train | r Encode all unicode strings in a dataframe in the encoding indicated as a fun attribute and return a unicode string. |
totalgood/pugnlp | src/pugnlp/util.py | clean_series | def clean_series(series, *args, **kwargs):
"""Ensure all datetimes are valid Timestamp objects and dtype is np.datetime64[ns]
>>> from datetime import timedelta
>>> clean_series(pd.Series([datetime.datetime(1, 1, 1), 9, '1942', datetime.datetime(1970, 10, 23)]))
0 1677-09-22 00:12:44+00:00
1 ... | python | def clean_series(series, *args, **kwargs):
"""Ensure all datetimes are valid Timestamp objects and dtype is np.datetime64[ns]
>>> from datetime import timedelta
>>> clean_series(pd.Series([datetime.datetime(1, 1, 1), 9, '1942', datetime.datetime(1970, 10, 23)]))
0 1677-09-22 00:12:44+00:00
1 ... | [
"def",
"clean_series",
"(",
"series",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"series",
".",
"dtype",
"==",
"np",
".",
"dtype",
"(",
"'O'",
")",
":",
"return",
"series",
"if",
"any_generated",
"(",
"(",
"isinstance",
"(",
... | Ensure all datetimes are valid Timestamp objects and dtype is np.datetime64[ns]
>>> from datetime import timedelta
>>> clean_series(pd.Series([datetime.datetime(1, 1, 1), 9, '1942', datetime.datetime(1970, 10, 23)]))
0 1677-09-22 00:12:44+00:00
1 9
2 ... | [
"Ensure",
"all",
"datetimes",
"are",
"valid",
"Timestamp",
"objects",
"and",
"dtype",
"is",
"np",
".",
"datetime64",
"[",
"ns",
"]",
">>>",
"from",
"datetime",
"import",
"timedelta",
">>>",
"clean_series",
"(",
"pd",
".",
"Series",
"(",
"[",
"datetime",
".... | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1740-L1761 | train | Ensure all datetimes are valid Timestamp objects and dtype is np. datetime64 [ ns ] |
totalgood/pugnlp | src/pugnlp/util.py | make_dataframe | def make_dataframe(table, clean=True, verbose=False, **kwargs):
"""Coerce a provided table (QuerySet, list of lists, list of Series)
>>> dt = datetime.datetime
>>> make_dataframe([[1,2,3],[4,5,6]])
0 1 2
0 1 2 3
1 4 5 6
>>> make_dataframe([])
Empty DataFrame
Columns: []
... | python | def make_dataframe(table, clean=True, verbose=False, **kwargs):
"""Coerce a provided table (QuerySet, list of lists, list of Series)
>>> dt = datetime.datetime
>>> make_dataframe([[1,2,3],[4,5,6]])
0 1 2
0 1 2 3
1 4 5 6
>>> make_dataframe([])
Empty DataFrame
Columns: []
... | [
"def",
"make_dataframe",
"(",
"table",
",",
"clean",
"=",
"True",
",",
"verbose",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"hasattr",
"(",
"table",
",",
"'objects'",
")",
"and",
"not",
"callable",
"(",
"table",
".",
"objects",
")",
":",... | Coerce a provided table (QuerySet, list of lists, list of Series)
>>> dt = datetime.datetime
>>> make_dataframe([[1,2,3],[4,5,6]])
0 1 2
0 1 2 3
1 4 5 6
>>> make_dataframe([])
Empty DataFrame
Columns: []
Index: []
>>> make_dataframe([OrderedDict([('a', 2), ('b', 3)]), ... | [
"Coerce",
"a",
"provided",
"table",
"(",
"QuerySet",
"list",
"of",
"lists",
"list",
"of",
"Series",
")",
">>>",
"dt",
"=",
"datetime",
".",
"datetime",
">>>",
"make_dataframe",
"(",
"[[",
"1",
"2",
"3",
"]",
"[",
"4",
"5",
"6",
"]]",
")",
"0",
"1",... | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1764-L1804 | train | Coerce a provided table to a Pandas DataFrame. |
totalgood/pugnlp | src/pugnlp/util.py | column_name_to_date | def column_name_to_date(name):
"""
TODO: should probably assume a 2000 epoch for 2-digit dates
>>> column_name_to_date('10-Apr')
datetime.date(10, 4, 1)
>>> column_name_to_date('10_2011')
datetime.date(2011, 10, 1)
>>> column_name_to_date('apr_10')
datetime.date(10, 4, 1)
"""
mo... | python | def column_name_to_date(name):
"""
TODO: should probably assume a 2000 epoch for 2-digit dates
>>> column_name_to_date('10-Apr')
datetime.date(10, 4, 1)
>>> column_name_to_date('10_2011')
datetime.date(2011, 10, 1)
>>> column_name_to_date('apr_10')
datetime.date(10, 4, 1)
"""
mo... | [
"def",
"column_name_to_date",
"(",
"name",
")",
":",
"month_nums",
"=",
"{",
"'Jan'",
":",
"1",
",",
"'Feb'",
":",
"2",
",",
"'Mar'",
":",
"3",
",",
"'Apr'",
":",
"4",
",",
"'May'",
":",
"5",
",",
"'Jun'",
":",
"6",
",",
"'Jul'",
":",
"7",
",",... | TODO: should probably assume a 2000 epoch for 2-digit dates
>>> column_name_to_date('10-Apr')
datetime.date(10, 4, 1)
>>> column_name_to_date('10_2011')
datetime.date(2011, 10, 1)
>>> column_name_to_date('apr_10')
datetime.date(10, 4, 1) | [
"TODO",
":",
"should",
"probably",
"assume",
"a",
"2000",
"epoch",
"for",
"2",
"-",
"digit",
"dates"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1809-L1845 | train | Convert a column name to a date. |
totalgood/pugnlp | src/pugnlp/util.py | first_digits | def first_digits(s, default=0):
"""Return the fist (left-hand) digits in a string as a single integer, ignoring sign (+/-).
>>> first_digits('+123.456')
123
"""
s = re.split(r'[^0-9]+', str(s).strip().lstrip('+-' + charlist.whitespace))
if len(s) and len(s[0]):
return int(s[0])
retur... | python | def first_digits(s, default=0):
"""Return the fist (left-hand) digits in a string as a single integer, ignoring sign (+/-).
>>> first_digits('+123.456')
123
"""
s = re.split(r'[^0-9]+', str(s).strip().lstrip('+-' + charlist.whitespace))
if len(s) and len(s[0]):
return int(s[0])
retur... | [
"def",
"first_digits",
"(",
"s",
",",
"default",
"=",
"0",
")",
":",
"s",
"=",
"re",
".",
"split",
"(",
"r'[^0-9]+'",
",",
"str",
"(",
"s",
")",
".",
"strip",
"(",
")",
".",
"lstrip",
"(",
"'+-'",
"+",
"charlist",
".",
"whitespace",
")",
")",
"... | Return the fist (left-hand) digits in a string as a single integer, ignoring sign (+/-).
>>> first_digits('+123.456')
123 | [
"Return",
"the",
"fist",
"(",
"left",
"-",
"hand",
")",
"digits",
"in",
"a",
"string",
"as",
"a",
"single",
"integer",
"ignoring",
"sign",
"(",
"+",
"/",
"-",
")",
".",
">>>",
"first_digits",
"(",
"+",
"123",
".",
"456",
")",
"123"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1848-L1856 | train | Return the first digits in a string ignoring sign ( + - ). |
totalgood/pugnlp | src/pugnlp/util.py | int_pair | def int_pair(s, default=(0, None)):
"""Return the digits to either side of a single non-digit character as a 2-tuple of integers
>>> int_pair('90210-007')
(90210, 7)
>>> int_pair('04321.0123')
(4321, 123)
"""
s = re.split(r'[^0-9]+', str(s).strip())
if len(s) and len(s[0]):
if l... | python | def int_pair(s, default=(0, None)):
"""Return the digits to either side of a single non-digit character as a 2-tuple of integers
>>> int_pair('90210-007')
(90210, 7)
>>> int_pair('04321.0123')
(4321, 123)
"""
s = re.split(r'[^0-9]+', str(s).strip())
if len(s) and len(s[0]):
if l... | [
"def",
"int_pair",
"(",
"s",
",",
"default",
"=",
"(",
"0",
",",
"None",
")",
")",
":",
"s",
"=",
"re",
".",
"split",
"(",
"r'[^0-9]+'",
",",
"str",
"(",
"s",
")",
".",
"strip",
"(",
")",
")",
"if",
"len",
"(",
"s",
")",
"and",
"len",
"(",
... | Return the digits to either side of a single non-digit character as a 2-tuple of integers
>>> int_pair('90210-007')
(90210, 7)
>>> int_pair('04321.0123')
(4321, 123) | [
"Return",
"the",
"digits",
"to",
"either",
"side",
"of",
"a",
"single",
"non",
"-",
"digit",
"character",
"as",
"a",
"2",
"-",
"tuple",
"of",
"integers"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1859-L1872 | train | Return the digits to either side of a single non - digit character as a 2 - tuple of integers |
totalgood/pugnlp | src/pugnlp/util.py | make_us_postal_code | def make_us_postal_code(s, allowed_lengths=(), allowed_digits=()):
"""
>>> make_us_postal_code(1234)
'01234'
>>> make_us_postal_code(507.6009)
'507'
>>> make_us_postal_code(90210.0)
'90210'
>>> make_us_postal_code(39567.7226)
'39567-7226'
>>> make_us_postal_code(39567.7226)
'... | python | def make_us_postal_code(s, allowed_lengths=(), allowed_digits=()):
"""
>>> make_us_postal_code(1234)
'01234'
>>> make_us_postal_code(507.6009)
'507'
>>> make_us_postal_code(90210.0)
'90210'
>>> make_us_postal_code(39567.7226)
'39567-7226'
>>> make_us_postal_code(39567.7226)
'... | [
"def",
"make_us_postal_code",
"(",
"s",
",",
"allowed_lengths",
"=",
"(",
")",
",",
"allowed_digits",
"=",
"(",
")",
")",
":",
"allowed_lengths",
"=",
"allowed_lengths",
"or",
"tuple",
"(",
"N",
"if",
"N",
"<",
"6",
"else",
"N",
"+",
"1",
"for",
"N",
... | >>> make_us_postal_code(1234)
'01234'
>>> make_us_postal_code(507.6009)
'507'
>>> make_us_postal_code(90210.0)
'90210'
>>> make_us_postal_code(39567.7226)
'39567-7226'
>>> make_us_postal_code(39567.7226)
'39567-7226' | [
">>>",
"make_us_postal_code",
"(",
"1234",
")",
"01234",
">>>",
"make_us_postal_code",
"(",
"507",
".",
"6009",
")",
"507",
">>>",
"make_us_postal_code",
"(",
"90210",
".",
"0",
")",
"90210",
">>>",
"make_us_postal_code",
"(",
"39567",
".",
"7226",
")",
"395... | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1875-L1899 | train | Make a US - postal code from a string. |
totalgood/pugnlp | src/pugnlp/util.py | make_float | def make_float(s, default='', ignore_commas=True):
r"""Coerce a string into a float
>>> make_float('12,345')
12345.0
>>> make_float('12.345')
12.345
>>> make_float('1+2')
3.0
>>> make_float('+42.0')
42.0
>>> make_float('\r\n-42?\r\n')
-42.0
>>> make_float('$42.42')
4... | python | def make_float(s, default='', ignore_commas=True):
r"""Coerce a string into a float
>>> make_float('12,345')
12345.0
>>> make_float('12.345')
12.345
>>> make_float('1+2')
3.0
>>> make_float('+42.0')
42.0
>>> make_float('\r\n-42?\r\n')
-42.0
>>> make_float('$42.42')
4... | [
"def",
"make_float",
"(",
"s",
",",
"default",
"=",
"''",
",",
"ignore_commas",
"=",
"True",
")",
":",
"if",
"ignore_commas",
"and",
"isinstance",
"(",
"s",
",",
"basestring",
")",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"','",
",",
"''",
")",
"tr... | r"""Coerce a string into a float
>>> make_float('12,345')
12345.0
>>> make_float('12.345')
12.345
>>> make_float('1+2')
3.0
>>> make_float('+42.0')
42.0
>>> make_float('\r\n-42?\r\n')
-42.0
>>> make_float('$42.42')
42.42
>>> make_float('B-52')
-52.0
>>> make_... | [
"r",
"Coerce",
"a",
"string",
"into",
"a",
"float"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1903-L1941 | train | Coerce a string into a float |
totalgood/pugnlp | src/pugnlp/util.py | make_int | def make_int(s, default='', ignore_commas=True):
r"""Coerce a string into an integer (long ints will fail)
TODO:
- Ignore dashes and other punctuation within a long string of digits,
like a telephone number, partnumber, datecode or serial number.
- Use the Decimal type to allow infinite precisio... | python | def make_int(s, default='', ignore_commas=True):
r"""Coerce a string into an integer (long ints will fail)
TODO:
- Ignore dashes and other punctuation within a long string of digits,
like a telephone number, partnumber, datecode or serial number.
- Use the Decimal type to allow infinite precisio... | [
"def",
"make_int",
"(",
"s",
",",
"default",
"=",
"''",
",",
"ignore_commas",
"=",
"True",
")",
":",
"if",
"ignore_commas",
"and",
"isinstance",
"(",
"s",
",",
"basestring",
")",
":",
"s",
"=",
"s",
".",
"replace",
"(",
"','",
",",
"''",
")",
"try"... | r"""Coerce a string into an integer (long ints will fail)
TODO:
- Ignore dashes and other punctuation within a long string of digits,
like a telephone number, partnumber, datecode or serial number.
- Use the Decimal type to allow infinite precision
- Use regexes to be more robust
>>> make_i... | [
"r",
"Coerce",
"a",
"string",
"into",
"an",
"integer",
"(",
"long",
"ints",
"will",
"fail",
")"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1945-L1976 | train | Coerce a string into an integer. |
totalgood/pugnlp | src/pugnlp/util.py | normalize_scientific_notation | def normalize_scientific_notation(s, ignore_commas=True, verbosity=1):
"""Produce a string convertable with float(s), if possible, fixing some common scientific notations
Deletes commas and allows addition.
>>> normalize_scientific_notation(' -123 x 10^-45 ')
'-123e-45'
>>> normalize_scientific_not... | python | def normalize_scientific_notation(s, ignore_commas=True, verbosity=1):
"""Produce a string convertable with float(s), if possible, fixing some common scientific notations
Deletes commas and allows addition.
>>> normalize_scientific_notation(' -123 x 10^-45 ')
'-123e-45'
>>> normalize_scientific_not... | [
"def",
"normalize_scientific_notation",
"(",
"s",
",",
"ignore_commas",
"=",
"True",
",",
"verbosity",
"=",
"1",
")",
":",
"s",
"=",
"s",
".",
"lstrip",
"(",
"charlist",
".",
"not_digits_nor_sign",
")",
"s",
"=",
"s",
".",
"rstrip",
"(",
"charlist",
".",... | Produce a string convertable with float(s), if possible, fixing some common scientific notations
Deletes commas and allows addition.
>>> normalize_scientific_notation(' -123 x 10^-45 ')
'-123e-45'
>>> normalize_scientific_notation(' -1+1,234 x 10^-5,678 ')
'1233e-5678'
>>> normalize_scientific_... | [
"Produce",
"a",
"string",
"convertable",
"with",
"float",
"(",
"s",
")",
"if",
"possible",
"fixing",
"some",
"common",
"scientific",
"notations"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L1980-L2020 | train | Produce a string convertable with float s if possible fixing some common scientific notations and allows addition. |
totalgood/pugnlp | src/pugnlp/util.py | normalize_names | def normalize_names(names):
"""Coerce a string or nested list of strings into a flat list of strings."""
if isinstance(names, basestring):
names = names.split(',')
names = listify(names)
return [str(name).strip() for name in names] | python | def normalize_names(names):
"""Coerce a string or nested list of strings into a flat list of strings."""
if isinstance(names, basestring):
names = names.split(',')
names = listify(names)
return [str(name).strip() for name in names] | [
"def",
"normalize_names",
"(",
"names",
")",
":",
"if",
"isinstance",
"(",
"names",
",",
"basestring",
")",
":",
"names",
"=",
"names",
".",
"split",
"(",
"','",
")",
"names",
"=",
"listify",
"(",
"names",
")",
"return",
"[",
"str",
"(",
"name",
")",... | Coerce a string or nested list of strings into a flat list of strings. | [
"Coerce",
"a",
"string",
"or",
"nested",
"list",
"of",
"strings",
"into",
"a",
"flat",
"list",
"of",
"strings",
"."
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2023-L2028 | train | Coerce a string or nested list of strings into a flat list of strings. |
totalgood/pugnlp | src/pugnlp/util.py | string_stats | def string_stats(strs, valid_chars='012346789', left_pad='0', right_pad='', strip=True):
""" Count the occurrence of a category of valid characters within an iterable of serial/model no, etc """
if left_pad is None:
left_pad = ''.join(c for c in rex.ASCII_CHARACTERS if c not in valid_chars)
if right... | python | def string_stats(strs, valid_chars='012346789', left_pad='0', right_pad='', strip=True):
""" Count the occurrence of a category of valid characters within an iterable of serial/model no, etc """
if left_pad is None:
left_pad = ''.join(c for c in rex.ASCII_CHARACTERS if c not in valid_chars)
if right... | [
"def",
"string_stats",
"(",
"strs",
",",
"valid_chars",
"=",
"'012346789'",
",",
"left_pad",
"=",
"'0'",
",",
"right_pad",
"=",
"''",
",",
"strip",
"=",
"True",
")",
":",
"if",
"left_pad",
"is",
"None",
":",
"left_pad",
"=",
"''",
".",
"join",
"(",
"... | Count the occurrence of a category of valid characters within an iterable of serial/model no, etc | [
"Count",
"the",
"occurrence",
"of",
"a",
"category",
"of",
"valid",
"characters",
"within",
"an",
"iterable",
"of",
"serial",
"/",
"model",
"no",
"etc"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2031-L2061 | train | Count the occurrence of a category of valid characters within an iterable of serial numbers. |
totalgood/pugnlp | src/pugnlp/util.py | normalize_serial_number | def normalize_serial_number(sn,
max_length=None, left_fill='0', right_fill=str(), blank=str(),
valid_chars=' -0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
invalid_chars=None,
strip_whitesp... | python | def normalize_serial_number(sn,
max_length=None, left_fill='0', right_fill=str(), blank=str(),
valid_chars=' -0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
invalid_chars=None,
strip_whitesp... | [
"def",
"normalize_serial_number",
"(",
"sn",
",",
"max_length",
"=",
"None",
",",
"left_fill",
"=",
"'0'",
",",
"right_fill",
"=",
"str",
"(",
")",
",",
"blank",
"=",
"str",
"(",
")",
",",
"valid_chars",
"=",
"' -0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM... | r"""Make a string compatible with typical serial number requirements
# Default configuration strips internal and external whitespaces and retains only the last 10 characters
>>> normalize_serial_number('1C 234567890 ')
'0234567890'
>>> normalize_serial_number('1C 234567890 ', ... | [
"r",
"Make",
"a",
"string",
"compatible",
"with",
"typical",
"serial",
"number",
"requirements"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2064-L2173 | train | r Converts a serial number into a string compatible with typical serial number requirements. |
totalgood/pugnlp | src/pugnlp/util.py | multisplit | def multisplit(s, seps=list(string.punctuation) + list(string.whitespace), blank=True):
r"""Just like str.split(), except that a variety (list) of seperators is allowed.
>>> multisplit(r'1-2?3,;.4+-', string.punctuation)
['1', '2', '3', '', '', '4', '', '']
>>> multisplit(r'1-2?3,;.4+-', string.punctua... | python | def multisplit(s, seps=list(string.punctuation) + list(string.whitespace), blank=True):
r"""Just like str.split(), except that a variety (list) of seperators is allowed.
>>> multisplit(r'1-2?3,;.4+-', string.punctuation)
['1', '2', '3', '', '', '4', '', '']
>>> multisplit(r'1-2?3,;.4+-', string.punctua... | [
"def",
"multisplit",
"(",
"s",
",",
"seps",
"=",
"list",
"(",
"string",
".",
"punctuation",
")",
"+",
"list",
"(",
"string",
".",
"whitespace",
")",
",",
"blank",
"=",
"True",
")",
":",
"seps",
"=",
"str",
"(",
")",
".",
"join",
"(",
"seps",
")",... | r"""Just like str.split(), except that a variety (list) of seperators is allowed.
>>> multisplit(r'1-2?3,;.4+-', string.punctuation)
['1', '2', '3', '', '', '4', '', '']
>>> multisplit(r'1-2?3,;.4+-', string.punctuation, blank=False)
['1', '2', '3', '4']
>>> multisplit(r'1C 234567890', '\x00\x01\x0... | [
"r",
"Just",
"like",
"str",
".",
"split",
"()",
"except",
"that",
"a",
"variety",
"(",
"list",
")",
"of",
"seperators",
"is",
"allowed",
"."
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2188-L2200 | train | A simple split function that returns a list of strings. |
totalgood/pugnlp | src/pugnlp/util.py | strip_HTML | def strip_HTML(s):
"""Simple, clumsy, slow HTML tag stripper"""
result = ''
total = 0
for c in s:
if c == '<':
total = 1
elif c == '>':
total = 0
result += ' '
elif total == 0:
result += c
return result | python | def strip_HTML(s):
"""Simple, clumsy, slow HTML tag stripper"""
result = ''
total = 0
for c in s:
if c == '<':
total = 1
elif c == '>':
total = 0
result += ' '
elif total == 0:
result += c
return result | [
"def",
"strip_HTML",
"(",
"s",
")",
":",
"result",
"=",
"''",
"total",
"=",
"0",
"for",
"c",
"in",
"s",
":",
"if",
"c",
"==",
"'<'",
":",
"total",
"=",
"1",
"elif",
"c",
"==",
"'>'",
":",
"total",
"=",
"0",
"result",
"+=",
"' '",
"elif",
"tot... | Simple, clumsy, slow HTML tag stripper | [
"Simple",
"clumsy",
"slow",
"HTML",
"tag",
"stripper"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2256-L2268 | train | Simple clumsy slow HTML tag stripper |
totalgood/pugnlp | src/pugnlp/util.py | get_words | def get_words(s, splitter_regex=rex.word_sep_except_external_appostrophe,
preprocessor=strip_HTML, postprocessor=strip_edge_punc, min_len=None,
max_len=None, blacklist=None, whitelist=None, lower=False,
filter_fun=None, str_type=str):
r"""Segment words (tokens), returning a... | python | def get_words(s, splitter_regex=rex.word_sep_except_external_appostrophe,
preprocessor=strip_HTML, postprocessor=strip_edge_punc, min_len=None,
max_len=None, blacklist=None, whitelist=None, lower=False,
filter_fun=None, str_type=str):
r"""Segment words (tokens), returning a... | [
"def",
"get_words",
"(",
"s",
",",
"splitter_regex",
"=",
"rex",
".",
"word_sep_except_external_appostrophe",
",",
"preprocessor",
"=",
"strip_HTML",
",",
"postprocessor",
"=",
"strip_edge_punc",
",",
"min_len",
"=",
"None",
",",
"max_len",
"=",
"None",
",",
"bl... | r"""Segment words (tokens), returning a list of all tokens
Does not return any separating whitespace or punctuation marks.
Attempts to return external apostrophes at the end of words.
Comparable to `nltk.word_toeknize`.
Arguments:
splitter_regex (str or re): compiled or uncompiled regular expres... | [
"r",
"Segment",
"words",
"(",
"tokens",
")",
"returning",
"a",
"list",
"of",
"all",
"tokens"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2295-L2364 | train | r Returns a list of words in a string. |
totalgood/pugnlp | src/pugnlp/util.py | tabulate | def tabulate(lol, headers, eol='\n'):
"""Use the pypi tabulate package instead!"""
yield '| %s |' % ' | '.join(headers) + eol
yield '| %s:|' % ':| '.join(['-' * len(w) for w in headers]) + eol
for row in lol:
yield '| %s |' % ' | '.join(str(c) for c in row) + eol | python | def tabulate(lol, headers, eol='\n'):
"""Use the pypi tabulate package instead!"""
yield '| %s |' % ' | '.join(headers) + eol
yield '| %s:|' % ':| '.join(['-' * len(w) for w in headers]) + eol
for row in lol:
yield '| %s |' % ' | '.join(str(c) for c in row) + eol | [
"def",
"tabulate",
"(",
"lol",
",",
"headers",
",",
"eol",
"=",
"'\\n'",
")",
":",
"yield",
"'| %s |'",
"%",
"' | '",
".",
"join",
"(",
"headers",
")",
"+",
"eol",
"yield",
"'| %s:|'",
"%",
"':| '",
".",
"join",
"(",
"[",
"'-'",
"*",
"len",
"(",
... | Use the pypi tabulate package instead! | [
"Use",
"the",
"pypi",
"tabulate",
"package",
"instead!"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2396-L2401 | train | Yields a list of strings in a tabulate format. |
totalgood/pugnlp | src/pugnlp/util.py | intify | def intify(obj, str_fun=str, use_ord=True, use_hash=True, use_len=True):
"""FIXME: this is unpythonic and does things you don't expect!
FIXME: rename to "integer_from_category"
Returns an integer representative of a categorical object (string, dict, etc)
>>> intify('1.2345e10')
12345000000
>>... | python | def intify(obj, str_fun=str, use_ord=True, use_hash=True, use_len=True):
"""FIXME: this is unpythonic and does things you don't expect!
FIXME: rename to "integer_from_category"
Returns an integer representative of a categorical object (string, dict, etc)
>>> intify('1.2345e10')
12345000000
>>... | [
"def",
"intify",
"(",
"obj",
",",
"str_fun",
"=",
"str",
",",
"use_ord",
"=",
"True",
",",
"use_hash",
"=",
"True",
",",
"use_len",
"=",
"True",
")",
":",
"try",
":",
"return",
"int",
"(",
"obj",
")",
"except",
"(",
"IndexError",
",",
"ValueError",
... | FIXME: this is unpythonic and does things you don't expect!
FIXME: rename to "integer_from_category"
Returns an integer representative of a categorical object (string, dict, etc)
>>> intify('1.2345e10')
12345000000
>>> intify([12]), intify('[99]'), intify('(12,)')
(91, 91, 40)
>>> intify(... | [
"FIXME",
":",
"this",
"is",
"unpythonic",
"and",
"does",
"things",
"you",
"don",
"t",
"expect!"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2404-L2461 | train | Convert an object into an integer. |
totalgood/pugnlp | src/pugnlp/util.py | listify | def listify(values, N=1, delim=None):
"""Return an N-length list, with elements values, extrapolating as necessary.
>>> listify("don't split into characters")
["don't split into characters"]
>>> listify("len = 3", 3)
['len = 3', 'len = 3', 'len = 3']
>>> listify("But split on a delimeter, if re... | python | def listify(values, N=1, delim=None):
"""Return an N-length list, with elements values, extrapolating as necessary.
>>> listify("don't split into characters")
["don't split into characters"]
>>> listify("len = 3", 3)
['len = 3', 'len = 3', 'len = 3']
>>> listify("But split on a delimeter, if re... | [
"def",
"listify",
"(",
"values",
",",
"N",
"=",
"1",
",",
"delim",
"=",
"None",
")",
":",
"ans",
"=",
"[",
"]",
"if",
"values",
"is",
"None",
"else",
"values",
"# convert non-string non-list iterables into a list",
"if",
"hasattr",
"(",
"ans",
",",
"'__ite... | Return an N-length list, with elements values, extrapolating as necessary.
>>> listify("don't split into characters")
["don't split into characters"]
>>> listify("len = 3", 3)
['len = 3', 'len = 3', 'len = 3']
>>> listify("But split on a delimeter, if requested.", delim=',')
['But split on a de... | [
"Return",
"an",
"N",
"-",
"length",
"list",
"with",
"elements",
"values",
"extrapolating",
"as",
"necessary",
"."
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2464-L2515 | train | Return an N - length list with elements values extrapolating as necessary. |
totalgood/pugnlp | src/pugnlp/util.py | unlistify | def unlistify(n, depth=1, typ=list, get=None):
"""Return the desired element in a list ignoring the rest.
>>> unlistify([1,2,3])
1
>>> unlistify([1,[4, 5, 6],3], get=1)
[4, 5, 6]
>>> unlistify([1,[4, 5, 6],3], depth=2, get=1)
5
>>> unlistify([1,(4, 5, 6),3], depth=2, get=1)
(4, 5, 6... | python | def unlistify(n, depth=1, typ=list, get=None):
"""Return the desired element in a list ignoring the rest.
>>> unlistify([1,2,3])
1
>>> unlistify([1,[4, 5, 6],3], get=1)
[4, 5, 6]
>>> unlistify([1,[4, 5, 6],3], depth=2, get=1)
5
>>> unlistify([1,(4, 5, 6),3], depth=2, get=1)
(4, 5, 6... | [
"def",
"unlistify",
"(",
"n",
",",
"depth",
"=",
"1",
",",
"typ",
"=",
"list",
",",
"get",
"=",
"None",
")",
":",
"i",
"=",
"0",
"if",
"depth",
"is",
"None",
":",
"depth",
"=",
"1",
"index_desired",
"=",
"get",
"or",
"0",
"while",
"i",
"<",
"... | Return the desired element in a list ignoring the rest.
>>> unlistify([1,2,3])
1
>>> unlistify([1,[4, 5, 6],3], get=1)
[4, 5, 6]
>>> unlistify([1,[4, 5, 6],3], depth=2, get=1)
5
>>> unlistify([1,(4, 5, 6),3], depth=2, get=1)
(4, 5, 6)
>>> unlistify([1,2,(4, 5, 6)], depth=2, get=2)
... | [
"Return",
"the",
"desired",
"element",
"in",
"a",
"list",
"ignoring",
"the",
"rest",
"."
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2522-L2549 | train | Return the desired element in a list ignoring the rest. |
totalgood/pugnlp | src/pugnlp/util.py | strip_keys | def strip_keys(d, nones=False, depth=0):
r"""Strip whitespace from all dictionary keys, to the depth indicated
>>> strip_keys({' a': ' a', ' b\t c ': {'d e ': 'd e '}}) == {'a': ' a', 'b\t c': {'d e ': 'd e '}}
True
>>> strip_keys({' a': ' a', ' b\t c ': {'d e ': 'd e '}}, depth=100) == {'a': ' a... | python | def strip_keys(d, nones=False, depth=0):
r"""Strip whitespace from all dictionary keys, to the depth indicated
>>> strip_keys({' a': ' a', ' b\t c ': {'d e ': 'd e '}}) == {'a': ' a', 'b\t c': {'d e ': 'd e '}}
True
>>> strip_keys({' a': ' a', ' b\t c ': {'d e ': 'd e '}}, depth=100) == {'a': ' a... | [
"def",
"strip_keys",
"(",
"d",
",",
"nones",
"=",
"False",
",",
"depth",
"=",
"0",
")",
":",
"ans",
"=",
"type",
"(",
"d",
")",
"(",
"(",
"str",
"(",
"k",
")",
".",
"strip",
"(",
")",
",",
"v",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
... | r"""Strip whitespace from all dictionary keys, to the depth indicated
>>> strip_keys({' a': ' a', ' b\t c ': {'d e ': 'd e '}}) == {'a': ' a', 'b\t c': {'d e ': 'd e '}}
True
>>> strip_keys({' a': ' a', ' b\t c ': {'d e ': 'd e '}}, depth=100) == {'a': ' a', 'b\t c': {'d e': 'd e '}}
True | [
"r",
"Strip",
"whitespace",
"from",
"all",
"dictionary",
"keys",
"to",
"the",
"depth",
"indicated"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2568-L2585 | train | r Strip whitespace from all dictionary keys to the depth indicated
|
totalgood/pugnlp | src/pugnlp/util.py | get_table_from_csv | def get_table_from_csv(filename='ssg_report_aarons_returns.csv', delimiter=',', dos=False):
"""Dictionary of sequences from CSV file"""
table = []
with open(filename, 'rb') as f:
reader = csv.reader(f, dialect='excel', delimiter=delimiter)
for row in reader:
table += [row]
if... | python | def get_table_from_csv(filename='ssg_report_aarons_returns.csv', delimiter=',', dos=False):
"""Dictionary of sequences from CSV file"""
table = []
with open(filename, 'rb') as f:
reader = csv.reader(f, dialect='excel', delimiter=delimiter)
for row in reader:
table += [row]
if... | [
"def",
"get_table_from_csv",
"(",
"filename",
"=",
"'ssg_report_aarons_returns.csv'",
",",
"delimiter",
"=",
"','",
",",
"dos",
"=",
"False",
")",
":",
"table",
"=",
"[",
"]",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"reader",
"... | Dictionary of sequences from CSV file | [
"Dictionary",
"of",
"sequences",
"from",
"CSV",
"file"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2596-L2605 | train | Returns a dictionary of sequences from a CSV file |
totalgood/pugnlp | src/pugnlp/util.py | shorten | def shorten(s, max_len=16):
"""Attempt to shorten a phrase by deleting words at the end of the phrase
>>> shorten('Hello World!')
'Hello World'
>>> shorten("Hello World! I'll talk your ear off!", 15)
'Hello World'
"""
short = s
words = [abbreviate(word) for word in get_words(s)]
for... | python | def shorten(s, max_len=16):
"""Attempt to shorten a phrase by deleting words at the end of the phrase
>>> shorten('Hello World!')
'Hello World'
>>> shorten("Hello World! I'll talk your ear off!", 15)
'Hello World'
"""
short = s
words = [abbreviate(word) for word in get_words(s)]
for... | [
"def",
"shorten",
"(",
"s",
",",
"max_len",
"=",
"16",
")",
":",
"short",
"=",
"s",
"words",
"=",
"[",
"abbreviate",
"(",
"word",
")",
"for",
"word",
"in",
"get_words",
"(",
"s",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"words",
")... | Attempt to shorten a phrase by deleting words at the end of the phrase
>>> shorten('Hello World!')
'Hello World'
>>> shorten("Hello World! I'll talk your ear off!", 15)
'Hello World' | [
"Attempt",
"to",
"shorten",
"a",
"phrase",
"by",
"deleting",
"words",
"at",
"the",
"end",
"of",
"the",
"phrase"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2627-L2641 | train | Shorten a phrase by deleting words at the end of the phrase. |
totalgood/pugnlp | src/pugnlp/util.py | truncate | def truncate(s, max_len=20, ellipsis='...'):
r"""Return string at most `max_len` characters or sequence elments appended with the `ellipsis` characters
>>> truncate(OrderedDict(zip(list('ABCDEFGH'), range(8))), 1)
"{'A': 0..."
>>> truncate(list(range(5)), 3)
'[0, 1, 2...'
>>> truncate(np.arange... | python | def truncate(s, max_len=20, ellipsis='...'):
r"""Return string at most `max_len` characters or sequence elments appended with the `ellipsis` characters
>>> truncate(OrderedDict(zip(list('ABCDEFGH'), range(8))), 1)
"{'A': 0..."
>>> truncate(list(range(5)), 3)
'[0, 1, 2...'
>>> truncate(np.arange... | [
"def",
"truncate",
"(",
"s",
",",
"max_len",
"=",
"20",
",",
"ellipsis",
"=",
"'...'",
")",
":",
"if",
"s",
"is",
"None",
":",
"return",
"None",
"elif",
"isinstance",
"(",
"s",
",",
"basestring",
")",
":",
"return",
"s",
"[",
":",
"min",
"(",
"le... | r"""Return string at most `max_len` characters or sequence elments appended with the `ellipsis` characters
>>> truncate(OrderedDict(zip(list('ABCDEFGH'), range(8))), 1)
"{'A': 0..."
>>> truncate(list(range(5)), 3)
'[0, 1, 2...'
>>> truncate(np.arange(5), 3)
'[0, 1, 2...'
>>> truncate('Too v... | [
"r",
"Return",
"string",
"at",
"most",
"max_len",
"characters",
"or",
"sequence",
"elments",
"appended",
"with",
"the",
"ellipsis",
"characters"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2656-L2676 | train | r Returns a string at most max_len characters or sequence elments appended with the ellipsis characters. |
totalgood/pugnlp | src/pugnlp/util.py | generate_kmers | def generate_kmers(seq, k=4):
"""Return a generator of all the unique substrings (k-mer or q-gram strings) within a sequence/string
Not effiicent for large k and long strings.
Doesn't form substrings that are shorter than k, only exactly k-mers
Used for algorithms like UniqTag for genome unique identi... | python | def generate_kmers(seq, k=4):
"""Return a generator of all the unique substrings (k-mer or q-gram strings) within a sequence/string
Not effiicent for large k and long strings.
Doesn't form substrings that are shorter than k, only exactly k-mers
Used for algorithms like UniqTag for genome unique identi... | [
"def",
"generate_kmers",
"(",
"seq",
",",
"k",
"=",
"4",
")",
":",
"if",
"isinstance",
"(",
"seq",
",",
"basestring",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"seq",
")",
"-",
"k",
"+",
"1",
")",
":",
"yield",
"seq",
"[",
"i",
":... | Return a generator of all the unique substrings (k-mer or q-gram strings) within a sequence/string
Not effiicent for large k and long strings.
Doesn't form substrings that are shorter than k, only exactly k-mers
Used for algorithms like UniqTag for genome unique identifier locality sensitive hashing.
... | [
"Return",
"a",
"generator",
"of",
"all",
"the",
"unique",
"substrings",
"(",
"k",
"-",
"mer",
"or",
"q",
"-",
"gram",
"strings",
")",
"within",
"a",
"sequence",
"/",
"string"
] | c43445b14afddfdeadc5f3076675c9e8fc1ee67c | https://github.com/totalgood/pugnlp/blob/c43445b14afddfdeadc5f3076675c9e8fc1ee67c/src/pugnlp/util.py#L2705-L2732 | train | Return a generator of all the k - mers within a sequence. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.