repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
maartenbreddels/ipyvolume
ipyvolume/pylab.py
screenshot
def screenshot( width=None, height=None, format="png", fig=None, timeout_seconds=10, output_widget=None, headless=False, devmode=False, ): """Save the figure to a PIL.Image object. :param int width: the width of the image in pixels :param int height: the height of the image in pixels :param format: format of output data (png, jpeg or svg) :type fig: ipyvolume.widgets.Figure or None :param fig: if None use the current figure :type timeout_seconds: int :param timeout_seconds: maximum time to wait for image data to return :type output_widget: ipywidgets.Output :param output_widget: a widget to use as a context manager for capturing the data :param bool headless: if True, use headless chrome to take screenshot :param bool devmode: if True, attempt to get index.js from local js/dist folder :return: PIL.Image """ assert format in ['png', 'jpeg', 'svg'], "image format must be png, jpeg or svg" data = _screenshot_data( timeout_seconds=timeout_seconds, output_widget=output_widget, format=format, width=width, height=height, fig=fig, headless=headless, devmode=devmode, ) f = StringIO(data) return PIL.Image.open(f)
python
def screenshot( width=None, height=None, format="png", fig=None, timeout_seconds=10, output_widget=None, headless=False, devmode=False, ): """Save the figure to a PIL.Image object. :param int width: the width of the image in pixels :param int height: the height of the image in pixels :param format: format of output data (png, jpeg or svg) :type fig: ipyvolume.widgets.Figure or None :param fig: if None use the current figure :type timeout_seconds: int :param timeout_seconds: maximum time to wait for image data to return :type output_widget: ipywidgets.Output :param output_widget: a widget to use as a context manager for capturing the data :param bool headless: if True, use headless chrome to take screenshot :param bool devmode: if True, attempt to get index.js from local js/dist folder :return: PIL.Image """ assert format in ['png', 'jpeg', 'svg'], "image format must be png, jpeg or svg" data = _screenshot_data( timeout_seconds=timeout_seconds, output_widget=output_widget, format=format, width=width, height=height, fig=fig, headless=headless, devmode=devmode, ) f = StringIO(data) return PIL.Image.open(f)
[ "def", "screenshot", "(", "width", "=", "None", ",", "height", "=", "None", ",", "format", "=", "\"png\"", ",", "fig", "=", "None", ",", "timeout_seconds", "=", "10", ",", "output_widget", "=", "None", ",", "headless", "=", "False", ",", "devmode", "="...
Save the figure to a PIL.Image object. :param int width: the width of the image in pixels :param int height: the height of the image in pixels :param format: format of output data (png, jpeg or svg) :type fig: ipyvolume.widgets.Figure or None :param fig: if None use the current figure :type timeout_seconds: int :param timeout_seconds: maximum time to wait for image data to return :type output_widget: ipywidgets.Output :param output_widget: a widget to use as a context manager for capturing the data :param bool headless: if True, use headless chrome to take screenshot :param bool devmode: if True, attempt to get index.js from local js/dist folder :return: PIL.Image
[ "Save", "the", "figure", "to", "a", "PIL", ".", "Image", "object", "." ]
e68b72852b61276f8e6793bc8811f5b2432a155f
https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L1059-L1097
train
220,700
maartenbreddels/ipyvolume
ipyvolume/pylab.py
savefig
def savefig( filename, width=None, height=None, fig=None, timeout_seconds=10, output_widget=None, headless=False, devmode=False ): """Save the figure to an image file. :param str filename: must have extension .png, .jpeg or .svg :param int width: the width of the image in pixels :param int height: the height of the image in pixels :type fig: ipyvolume.widgets.Figure or None :param fig: if None use the current figure :param float timeout_seconds: maximum time to wait for image data to return :param ipywidgets.Output output_widget: a widget to use as a context manager for capturing the data :param bool headless: if True, use headless chrome to save figure :param bool devmode: if True, attempt to get index.js from local js/dist folder """ __, ext = os.path.splitext(filename) format = ext[1:] assert format in ['png', 'jpeg', 'svg'], "image format must be png, jpeg or svg" with open(filename, "wb") as f: f.write( _screenshot_data( timeout_seconds=timeout_seconds, output_widget=output_widget, format=format, width=width, height=height, fig=fig, headless=headless, devmode=devmode, ) )
python
def savefig( filename, width=None, height=None, fig=None, timeout_seconds=10, output_widget=None, headless=False, devmode=False ): """Save the figure to an image file. :param str filename: must have extension .png, .jpeg or .svg :param int width: the width of the image in pixels :param int height: the height of the image in pixels :type fig: ipyvolume.widgets.Figure or None :param fig: if None use the current figure :param float timeout_seconds: maximum time to wait for image data to return :param ipywidgets.Output output_widget: a widget to use as a context manager for capturing the data :param bool headless: if True, use headless chrome to save figure :param bool devmode: if True, attempt to get index.js from local js/dist folder """ __, ext = os.path.splitext(filename) format = ext[1:] assert format in ['png', 'jpeg', 'svg'], "image format must be png, jpeg or svg" with open(filename, "wb") as f: f.write( _screenshot_data( timeout_seconds=timeout_seconds, output_widget=output_widget, format=format, width=width, height=height, fig=fig, headless=headless, devmode=devmode, ) )
[ "def", "savefig", "(", "filename", ",", "width", "=", "None", ",", "height", "=", "None", ",", "fig", "=", "None", ",", "timeout_seconds", "=", "10", ",", "output_widget", "=", "None", ",", "headless", "=", "False", ",", "devmode", "=", "False", ")", ...
Save the figure to an image file. :param str filename: must have extension .png, .jpeg or .svg :param int width: the width of the image in pixels :param int height: the height of the image in pixels :type fig: ipyvolume.widgets.Figure or None :param fig: if None use the current figure :param float timeout_seconds: maximum time to wait for image data to return :param ipywidgets.Output output_widget: a widget to use as a context manager for capturing the data :param bool headless: if True, use headless chrome to save figure :param bool devmode: if True, attempt to get index.js from local js/dist folder
[ "Save", "the", "figure", "to", "an", "image", "file", "." ]
e68b72852b61276f8e6793bc8811f5b2432a155f
https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L1100-L1130
train
220,701
maartenbreddels/ipyvolume
ipyvolume/pylab.py
xyzlabel
def xyzlabel(labelx, labely, labelz): """Set all labels at once.""" xlabel(labelx) ylabel(labely) zlabel(labelz)
python
def xyzlabel(labelx, labely, labelz): """Set all labels at once.""" xlabel(labelx) ylabel(labely) zlabel(labelz)
[ "def", "xyzlabel", "(", "labelx", ",", "labely", ",", "labelz", ")", ":", "xlabel", "(", "labelx", ")", "ylabel", "(", "labely", ")", "zlabel", "(", "labelz", ")" ]
Set all labels at once.
[ "Set", "all", "labels", "at", "once", "." ]
e68b72852b61276f8e6793bc8811f5b2432a155f
https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L1151-L1155
train
220,702
maartenbreddels/ipyvolume
ipyvolume/pylab.py
view
def view(azimuth=None, elevation=None, distance=None): """Set camera angles and distance and return the current. :param float azimuth: rotation around the axis pointing up in degrees :param float elevation: rotation where +90 means 'up', -90 means 'down', in degrees :param float distance: radial distance from the center to the camera. """ fig = gcf() # first calculate the current values x, y, z = fig.camera.position r = np.sqrt(x ** 2 + y ** 2 + z ** 2) az = np.degrees(np.arctan2(x, z)) el = np.degrees(np.arcsin(y / r)) if azimuth is None: azimuth = az if elevation is None: elevation = el if distance is None: distance = r cosaz = np.cos(np.radians(azimuth)) sinaz = np.sin(np.radians(azimuth)) sine = np.sin(np.radians(elevation)) cose = np.cos(np.radians(elevation)) fig.camera.position = (distance * sinaz * cose, distance * sine, distance * cosaz * cose) return azimuth, elevation, distance
python
def view(azimuth=None, elevation=None, distance=None): """Set camera angles and distance and return the current. :param float azimuth: rotation around the axis pointing up in degrees :param float elevation: rotation where +90 means 'up', -90 means 'down', in degrees :param float distance: radial distance from the center to the camera. """ fig = gcf() # first calculate the current values x, y, z = fig.camera.position r = np.sqrt(x ** 2 + y ** 2 + z ** 2) az = np.degrees(np.arctan2(x, z)) el = np.degrees(np.arcsin(y / r)) if azimuth is None: azimuth = az if elevation is None: elevation = el if distance is None: distance = r cosaz = np.cos(np.radians(azimuth)) sinaz = np.sin(np.radians(azimuth)) sine = np.sin(np.radians(elevation)) cose = np.cos(np.radians(elevation)) fig.camera.position = (distance * sinaz * cose, distance * sine, distance * cosaz * cose) return azimuth, elevation, distance
[ "def", "view", "(", "azimuth", "=", "None", ",", "elevation", "=", "None", ",", "distance", "=", "None", ")", ":", "fig", "=", "gcf", "(", ")", "# first calculate the current values", "x", ",", "y", ",", "z", "=", "fig", ".", "camera", ".", "position",...
Set camera angles and distance and return the current. :param float azimuth: rotation around the axis pointing up in degrees :param float elevation: rotation where +90 means 'up', -90 means 'down', in degrees :param float distance: radial distance from the center to the camera.
[ "Set", "camera", "angles", "and", "distance", "and", "return", "the", "current", "." ]
e68b72852b61276f8e6793bc8811f5b2432a155f
https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L1158-L1182
train
220,703
maartenbreddels/ipyvolume
ipyvolume/pylab.py
plot_plane
def plot_plane(where="back", texture=None): """Plot a plane at a particular location in the viewbox. :param str where: 'back', 'front', 'left', 'right', 'top', 'bottom' :param texture: {texture} :return: :any:`Mesh` """ fig = gcf() xmin, xmax = fig.xlim ymin, ymax = fig.ylim zmin, zmax = fig.zlim if where == "back": x = [xmin, xmax, xmax, xmin] y = [ymin, ymin, ymax, ymax] z = [zmin, zmin, zmin, zmin] if where == "front": x = [xmin, xmax, xmax, xmin][::-1] y = [ymin, ymin, ymax, ymax] z = [zmax, zmax, zmax, zmax] if where == "left": x = [xmin, xmin, xmin, xmin] y = [ymin, ymin, ymax, ymax] z = [zmin, zmax, zmax, zmin] if where == "right": x = [xmax, xmax, xmax, xmax] y = [ymin, ymin, ymax, ymax] z = [zmin, zmax, zmax, zmin][::-1] if where == "top": x = [xmin, xmax, xmax, xmin] y = [ymax, ymax, ymax, ymax] z = [zmax, zmax, zmin, zmin] if where == "bottom": x = [xmax, xmin, xmin, xmax] y = [ymin, ymin, ymin, ymin] z = [zmin, zmin, zmax, zmax] triangles = [(0, 1, 2), (0, 2, 3)] u = v = None if texture is not None: u = [0.0, 1.0, 1.0, 0.0] v = [0.0, 0.0, 1.0, 1.0] mesh = plot_trisurf(x, y, z, triangles, texture=texture, u=u, v=v) return mesh
python
def plot_plane(where="back", texture=None): """Plot a plane at a particular location in the viewbox. :param str where: 'back', 'front', 'left', 'right', 'top', 'bottom' :param texture: {texture} :return: :any:`Mesh` """ fig = gcf() xmin, xmax = fig.xlim ymin, ymax = fig.ylim zmin, zmax = fig.zlim if where == "back": x = [xmin, xmax, xmax, xmin] y = [ymin, ymin, ymax, ymax] z = [zmin, zmin, zmin, zmin] if where == "front": x = [xmin, xmax, xmax, xmin][::-1] y = [ymin, ymin, ymax, ymax] z = [zmax, zmax, zmax, zmax] if where == "left": x = [xmin, xmin, xmin, xmin] y = [ymin, ymin, ymax, ymax] z = [zmin, zmax, zmax, zmin] if where == "right": x = [xmax, xmax, xmax, xmax] y = [ymin, ymin, ymax, ymax] z = [zmin, zmax, zmax, zmin][::-1] if where == "top": x = [xmin, xmax, xmax, xmin] y = [ymax, ymax, ymax, ymax] z = [zmax, zmax, zmin, zmin] if where == "bottom": x = [xmax, xmin, xmin, xmax] y = [ymin, ymin, ymin, ymin] z = [zmin, zmin, zmax, zmax] triangles = [(0, 1, 2), (0, 2, 3)] u = v = None if texture is not None: u = [0.0, 1.0, 1.0, 0.0] v = [0.0, 0.0, 1.0, 1.0] mesh = plot_trisurf(x, y, z, triangles, texture=texture, u=u, v=v) return mesh
[ "def", "plot_plane", "(", "where", "=", "\"back\"", ",", "texture", "=", "None", ")", ":", "fig", "=", "gcf", "(", ")", "xmin", ",", "xmax", "=", "fig", ".", "xlim", "ymin", ",", "ymax", "=", "fig", ".", "ylim", "zmin", ",", "zmax", "=", "fig", ...
Plot a plane at a particular location in the viewbox. :param str where: 'back', 'front', 'left', 'right', 'top', 'bottom' :param texture: {texture} :return: :any:`Mesh`
[ "Plot", "a", "plane", "at", "a", "particular", "location", "in", "the", "viewbox", "." ]
e68b72852b61276f8e6793bc8811f5b2432a155f
https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L1306-L1347
train
220,704
maartenbreddels/ipyvolume
ipyvolume/pylab.py
_make_triangles_lines
def _make_triangles_lines(shape, wrapx=False, wrapy=False): """Transform rectangular regular grid into triangles. :param x: {x2d} :param y: {y2d} :param z: {z2d} :param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the end end begin points :param bool wrapy: simular for the y coordinate :return: triangles and lines used to plot Mesh """ nx, ny = shape mx = nx if wrapx else nx - 1 my = ny if wrapy else ny - 1 """ create all pair of indices (i,j) of the rectangular grid minus last row if wrapx = False => mx minus last column if wrapy = False => my | (0,0) ... (0,j) ... (0,my-1) | | . . . . . | | (i,0) ... (i,j) ... (i,my-1) | | . . . . . | |(mx-1,0) ... (mx-1,j) ... (mx-1,my-1) | """ i, j = np.mgrid[0:mx, 0:my] """ collapsed i and j in one dimensional array, row-major order ex : array([[0, 1, 2], => array([0, 1, 2, 3, *4*, 5]) [3, *4*, 5]]) if we want vertex 4 at (i=1,j=1) we must transform it in i*ny+j = 4 """ i, j = np.ravel(i), np.ravel(j) """ Let's go for the triangles : (i,j) - (i,j+1) -> y dir (i+1,j) - (i+1,j+1) | v x dir in flatten coordinates: i*ny+j - i*ny+j+1 (i+1)*ny+j - (i+1)*ny+j+1 """ t1 = (i * ny + j, (i + 1) % nx * ny + j, (i + 1) % nx * ny + (j + 1) % ny) t2 = (i * ny + j, (i + 1) % nx * ny + (j + 1) % ny, i * ny + (j + 1) % ny) """ %nx and %ny are used for wrapx and wrapy : if (i+1)=nx => (i+1)%nx=0 => close mesh in x direction if (j+1)=ny => (j+1)%ny=0 => close mesh in y direction """ nt = len(t1[0]) triangles = np.zeros((nt * 2, 3), dtype=np.uint32) triangles[0::2, 0], triangles[0::2, 1], triangles[0::2, 2] = t1 triangles[1::2, 0], triangles[1::2, 1], triangles[1::2, 2] = t2 lines = np.zeros((nt * 4, 2), dtype=np.uint32) lines[::4, 0], lines[::4, 1] = t1[:2] lines[1::4, 0], lines[1::4, 1] = t1[0], t2[2] lines[2::4, 0], lines[2::4, 1] = t2[2:0:-1] lines[3::4, 0], lines[3::4, 1] = t1[1], t2[1] return triangles, lines
python
def _make_triangles_lines(shape, wrapx=False, wrapy=False): """Transform rectangular regular grid into triangles. :param x: {x2d} :param y: {y2d} :param z: {z2d} :param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the end end begin points :param bool wrapy: simular for the y coordinate :return: triangles and lines used to plot Mesh """ nx, ny = shape mx = nx if wrapx else nx - 1 my = ny if wrapy else ny - 1 """ create all pair of indices (i,j) of the rectangular grid minus last row if wrapx = False => mx minus last column if wrapy = False => my | (0,0) ... (0,j) ... (0,my-1) | | . . . . . | | (i,0) ... (i,j) ... (i,my-1) | | . . . . . | |(mx-1,0) ... (mx-1,j) ... (mx-1,my-1) | """ i, j = np.mgrid[0:mx, 0:my] """ collapsed i and j in one dimensional array, row-major order ex : array([[0, 1, 2], => array([0, 1, 2, 3, *4*, 5]) [3, *4*, 5]]) if we want vertex 4 at (i=1,j=1) we must transform it in i*ny+j = 4 """ i, j = np.ravel(i), np.ravel(j) """ Let's go for the triangles : (i,j) - (i,j+1) -> y dir (i+1,j) - (i+1,j+1) | v x dir in flatten coordinates: i*ny+j - i*ny+j+1 (i+1)*ny+j - (i+1)*ny+j+1 """ t1 = (i * ny + j, (i + 1) % nx * ny + j, (i + 1) % nx * ny + (j + 1) % ny) t2 = (i * ny + j, (i + 1) % nx * ny + (j + 1) % ny, i * ny + (j + 1) % ny) """ %nx and %ny are used for wrapx and wrapy : if (i+1)=nx => (i+1)%nx=0 => close mesh in x direction if (j+1)=ny => (j+1)%ny=0 => close mesh in y direction """ nt = len(t1[0]) triangles = np.zeros((nt * 2, 3), dtype=np.uint32) triangles[0::2, 0], triangles[0::2, 1], triangles[0::2, 2] = t1 triangles[1::2, 0], triangles[1::2, 1], triangles[1::2, 2] = t2 lines = np.zeros((nt * 4, 2), dtype=np.uint32) lines[::4, 0], lines[::4, 1] = t1[:2] lines[1::4, 0], lines[1::4, 1] = t1[0], t2[2] lines[2::4, 0], lines[2::4, 1] = t2[2:0:-1] lines[3::4, 0], lines[3::4, 1] = t1[1], t2[1] return triangles, lines
[ "def", "_make_triangles_lines", "(", "shape", ",", "wrapx", "=", "False", ",", "wrapy", "=", "False", ")", ":", "nx", ",", "ny", "=", "shape", "mx", "=", "nx", "if", "wrapx", "else", "nx", "-", "1", "my", "=", "ny", "if", "wrapy", "else", "ny", "...
Transform rectangular regular grid into triangles. :param x: {x2d} :param y: {y2d} :param z: {z2d} :param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the end end begin points :param bool wrapy: simular for the y coordinate :return: triangles and lines used to plot Mesh
[ "Transform", "rectangular", "regular", "grid", "into", "triangles", "." ]
e68b72852b61276f8e6793bc8811f5b2432a155f
https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/pylab.py#L1443-L1513
train
220,705
maartenbreddels/ipyvolume
ipyvolume/embed.py
save_ipyvolumejs
def save_ipyvolumejs( target="", devmode=False, version=ipyvolume._version.__version_js__, version3js=__version_threejs__ ): """Output the ipyvolume javascript to a local file. :type target: str :param bool devmode: if True get index.js from js/dist directory :param str version: version number of ipyvolume :param str version3js: version number of threejs """ url = "https://unpkg.com/ipyvolume@{version}/dist/index.js".format(version=version) pyv_filename = 'ipyvolume_v{version}.js'.format(version=version) pyv_filepath = os.path.join(target, pyv_filename) devfile = os.path.join(os.path.abspath(ipyvolume.__path__[0]), "..", "js", "dist", "index.js") if devmode: if not os.path.exists(devfile): raise IOError('devmode=True but cannot find : {}'.format(devfile)) if target and not os.path.exists(target): os.makedirs(target) shutil.copy(devfile, pyv_filepath) else: download_to_file(url, pyv_filepath) # TODO: currently not in use, think about this if we want to have this external for embedding, # see also https://github.com/jovyan/pythreejs/issues/109 # three_filename = 'three_v{version}.js'.format(version=__version_threejs__) # three_filepath = os.path.join(target, three_filename) # threejs = os.path.join(os.path.abspath(ipyvolume.__path__[0]), "static", "three.js") # shutil.copy(threejs, three_filepath) return pyv_filename
python
def save_ipyvolumejs( target="", devmode=False, version=ipyvolume._version.__version_js__, version3js=__version_threejs__ ): """Output the ipyvolume javascript to a local file. :type target: str :param bool devmode: if True get index.js from js/dist directory :param str version: version number of ipyvolume :param str version3js: version number of threejs """ url = "https://unpkg.com/ipyvolume@{version}/dist/index.js".format(version=version) pyv_filename = 'ipyvolume_v{version}.js'.format(version=version) pyv_filepath = os.path.join(target, pyv_filename) devfile = os.path.join(os.path.abspath(ipyvolume.__path__[0]), "..", "js", "dist", "index.js") if devmode: if not os.path.exists(devfile): raise IOError('devmode=True but cannot find : {}'.format(devfile)) if target and not os.path.exists(target): os.makedirs(target) shutil.copy(devfile, pyv_filepath) else: download_to_file(url, pyv_filepath) # TODO: currently not in use, think about this if we want to have this external for embedding, # see also https://github.com/jovyan/pythreejs/issues/109 # three_filename = 'three_v{version}.js'.format(version=__version_threejs__) # three_filepath = os.path.join(target, three_filename) # threejs = os.path.join(os.path.abspath(ipyvolume.__path__[0]), "static", "three.js") # shutil.copy(threejs, three_filepath) return pyv_filename
[ "def", "save_ipyvolumejs", "(", "target", "=", "\"\"", ",", "devmode", "=", "False", ",", "version", "=", "ipyvolume", ".", "_version", ".", "__version_js__", ",", "version3js", "=", "__version_threejs__", ")", ":", "url", "=", "\"https://unpkg.com/ipyvolume@{vers...
Output the ipyvolume javascript to a local file. :type target: str :param bool devmode: if True get index.js from js/dist directory :param str version: version number of ipyvolume :param str version3js: version number of threejs
[ "Output", "the", "ipyvolume", "javascript", "to", "a", "local", "file", "." ]
e68b72852b61276f8e6793bc8811f5b2432a155f
https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/embed.py#L28-L60
train
220,706
maartenbreddels/ipyvolume
ipyvolume/embed.py
save_requirejs
def save_requirejs(target="", version="2.3.4"): """Download and save the require javascript to a local file. :type target: str :type version: str """ url = "https://cdnjs.cloudflare.com/ajax/libs/require.js/{version}/require.min.js".format(version=version) filename = "require.min.v{0}.js".format(version) filepath = os.path.join(target, filename) download_to_file(url, filepath) return filename
python
def save_requirejs(target="", version="2.3.4"): """Download and save the require javascript to a local file. :type target: str :type version: str """ url = "https://cdnjs.cloudflare.com/ajax/libs/require.js/{version}/require.min.js".format(version=version) filename = "require.min.v{0}.js".format(version) filepath = os.path.join(target, filename) download_to_file(url, filepath) return filename
[ "def", "save_requirejs", "(", "target", "=", "\"\"", ",", "version", "=", "\"2.3.4\"", ")", ":", "url", "=", "\"https://cdnjs.cloudflare.com/ajax/libs/require.js/{version}/require.min.js\"", ".", "format", "(", "version", "=", "version", ")", "filename", "=", "\"requi...
Download and save the require javascript to a local file. :type target: str :type version: str
[ "Download", "and", "save", "the", "require", "javascript", "to", "a", "local", "file", "." ]
e68b72852b61276f8e6793bc8811f5b2432a155f
https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/embed.py#L63-L73
train
220,707
maartenbreddels/ipyvolume
ipyvolume/embed.py
save_embed_js
def save_embed_js(target="", version=wembed.__html_manager_version__): """Download and save the ipywidgets embedding javascript to a local file. :type target: str :type version: str """ url = u'https://unpkg.com/@jupyter-widgets/html-manager@{0:s}/dist/embed-amd.js'.format(version) if version.startswith('^'): version = version[1:] filename = "embed-amd_v{0:s}.js".format(version) filepath = os.path.join(target, filename) download_to_file(url, filepath) return filename
python
def save_embed_js(target="", version=wembed.__html_manager_version__): """Download and save the ipywidgets embedding javascript to a local file. :type target: str :type version: str """ url = u'https://unpkg.com/@jupyter-widgets/html-manager@{0:s}/dist/embed-amd.js'.format(version) if version.startswith('^'): version = version[1:] filename = "embed-amd_v{0:s}.js".format(version) filepath = os.path.join(target, filename) download_to_file(url, filepath) return filename
[ "def", "save_embed_js", "(", "target", "=", "\"\"", ",", "version", "=", "wembed", ".", "__html_manager_version__", ")", ":", "url", "=", "u'https://unpkg.com/@jupyter-widgets/html-manager@{0:s}/dist/embed-amd.js'", ".", "format", "(", "version", ")", "if", "version", ...
Download and save the ipywidgets embedding javascript to a local file. :type target: str :type version: str
[ "Download", "and", "save", "the", "ipywidgets", "embedding", "javascript", "to", "a", "local", "file", "." ]
e68b72852b61276f8e6793bc8811f5b2432a155f
https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/embed.py#L76-L90
train
220,708
maartenbreddels/ipyvolume
ipyvolume/embed.py
save_font_awesome
def save_font_awesome(dirpath='', version="4.7.0"): """Download and save the font-awesome package to a local directory. :type dirpath: str :type url: str """ directory_name = "font-awesome-{0:s}".format(version) directory_path = os.path.join(dirpath, directory_name) if os.path.exists(directory_path): return directory_name url = "https://fontawesome.com/v{0:s}/assets/font-awesome-{0:s}.zip".format(version) content, _encoding = download_to_bytes(url) try: zip_directory = io.BytesIO(content) unzip = zipfile.ZipFile(zip_directory) top_level_name = unzip.namelist()[0] unzip.extractall(dirpath) except Exception as err: raise IOError('Could not unzip content from: {0}\n{1}'.format(url, err)) os.rename(os.path.join(dirpath, top_level_name), directory_path) return directory_name
python
def save_font_awesome(dirpath='', version="4.7.0"): """Download and save the font-awesome package to a local directory. :type dirpath: str :type url: str """ directory_name = "font-awesome-{0:s}".format(version) directory_path = os.path.join(dirpath, directory_name) if os.path.exists(directory_path): return directory_name url = "https://fontawesome.com/v{0:s}/assets/font-awesome-{0:s}.zip".format(version) content, _encoding = download_to_bytes(url) try: zip_directory = io.BytesIO(content) unzip = zipfile.ZipFile(zip_directory) top_level_name = unzip.namelist()[0] unzip.extractall(dirpath) except Exception as err: raise IOError('Could not unzip content from: {0}\n{1}'.format(url, err)) os.rename(os.path.join(dirpath, top_level_name), directory_path) return directory_name
[ "def", "save_font_awesome", "(", "dirpath", "=", "''", ",", "version", "=", "\"4.7.0\"", ")", ":", "directory_name", "=", "\"font-awesome-{0:s}\"", ".", "format", "(", "version", ")", "directory_path", "=", "os", ".", "path", ".", "join", "(", "dirpath", ","...
Download and save the font-awesome package to a local directory. :type dirpath: str :type url: str
[ "Download", "and", "save", "the", "font", "-", "awesome", "package", "to", "a", "local", "directory", "." ]
e68b72852b61276f8e6793bc8811f5b2432a155f
https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/embed.py#L94-L118
train
220,709
maartenbreddels/ipyvolume
ipyvolume/utils.py
download_to_bytes
def download_to_bytes(url, chunk_size=1024 * 1024 * 10, loadbar_length=10): """Download a url to bytes. if chunk_size is not None, prints a simple loading bar [=*loadbar_length] to show progress (in console and notebook) :param url: str or url :param chunk_size: None or int in bytes :param loadbar_length: int length of load bar :return: (bytes, encoding) """ stream = False if chunk_size is None else True print("Downloading {0:s}: ".format(url), end="") response = requests.get(url, stream=stream) # raise error if download was unsuccessful response.raise_for_status() encoding = response.encoding total_length = response.headers.get('content-length') if total_length is not None: total_length = float(total_length) if stream: print("{0:.2f}Mb/{1:} ".format(total_length / (1024 * 1024), loadbar_length), end="") else: print("{0:.2f}Mb ".format(total_length / (1024 * 1024)), end="") if stream: print("[", end="") chunks = [] loaded = 0 loaded_size = 0 for chunk in response.iter_content(chunk_size=chunk_size): if chunk: # filter out keep-alive new chunks # print our progress bar if total_length is not None: while loaded < loadbar_length * loaded_size / total_length: print("=", end='') loaded += 1 loaded_size += chunk_size chunks.append(chunk) if total_length is None: print("=" * loadbar_length, end='') else: while loaded < loadbar_length: print("=", end='') loaded += 1 content = b"".join(chunks) print("] ", end="") else: content = response.content print("Finished") response.close() return content, encoding
python
def download_to_bytes(url, chunk_size=1024 * 1024 * 10, loadbar_length=10): """Download a url to bytes. if chunk_size is not None, prints a simple loading bar [=*loadbar_length] to show progress (in console and notebook) :param url: str or url :param chunk_size: None or int in bytes :param loadbar_length: int length of load bar :return: (bytes, encoding) """ stream = False if chunk_size is None else True print("Downloading {0:s}: ".format(url), end="") response = requests.get(url, stream=stream) # raise error if download was unsuccessful response.raise_for_status() encoding = response.encoding total_length = response.headers.get('content-length') if total_length is not None: total_length = float(total_length) if stream: print("{0:.2f}Mb/{1:} ".format(total_length / (1024 * 1024), loadbar_length), end="") else: print("{0:.2f}Mb ".format(total_length / (1024 * 1024)), end="") if stream: print("[", end="") chunks = [] loaded = 0 loaded_size = 0 for chunk in response.iter_content(chunk_size=chunk_size): if chunk: # filter out keep-alive new chunks # print our progress bar if total_length is not None: while loaded < loadbar_length * loaded_size / total_length: print("=", end='') loaded += 1 loaded_size += chunk_size chunks.append(chunk) if total_length is None: print("=" * loadbar_length, end='') else: while loaded < loadbar_length: print("=", end='') loaded += 1 content = b"".join(chunks) print("] ", end="") else: content = response.content print("Finished") response.close() return content, encoding
[ "def", "download_to_bytes", "(", "url", ",", "chunk_size", "=", "1024", "*", "1024", "*", "10", ",", "loadbar_length", "=", "10", ")", ":", "stream", "=", "False", "if", "chunk_size", "is", "None", "else", "True", "print", "(", "\"Downloading {0:s}: \"", "...
Download a url to bytes. if chunk_size is not None, prints a simple loading bar [=*loadbar_length] to show progress (in console and notebook) :param url: str or url :param chunk_size: None or int in bytes :param loadbar_length: int length of load bar :return: (bytes, encoding)
[ "Download", "a", "url", "to", "bytes", "." ]
e68b72852b61276f8e6793bc8811f5b2432a155f
https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/utils.py#L40-L95
train
220,710
maartenbreddels/ipyvolume
ipyvolume/utils.py
download_yield_bytes
def download_yield_bytes(url, chunk_size=1024 * 1024 * 10): """Yield a downloaded url as byte chunks. :param url: str or url :param chunk_size: None or int in bytes :yield: byte chunks """ response = requests.get(url, stream=True) # raise error if download was unsuccessful response.raise_for_status() total_length = response.headers.get('content-length') if total_length is not None: total_length = float(total_length) length_str = "{0:.2f}Mb ".format(total_length / (1024 * 1024)) else: length_str = "" print("Yielding {0:s} {1:s}".format(url, length_str)) for chunk in response.iter_content(chunk_size=chunk_size): yield chunk response.close()
python
def download_yield_bytes(url, chunk_size=1024 * 1024 * 10): """Yield a downloaded url as byte chunks. :param url: str or url :param chunk_size: None or int in bytes :yield: byte chunks """ response = requests.get(url, stream=True) # raise error if download was unsuccessful response.raise_for_status() total_length = response.headers.get('content-length') if total_length is not None: total_length = float(total_length) length_str = "{0:.2f}Mb ".format(total_length / (1024 * 1024)) else: length_str = "" print("Yielding {0:s} {1:s}".format(url, length_str)) for chunk in response.iter_content(chunk_size=chunk_size): yield chunk response.close()
[ "def", "download_yield_bytes", "(", "url", ",", "chunk_size", "=", "1024", "*", "1024", "*", "10", ")", ":", "response", "=", "requests", ".", "get", "(", "url", ",", "stream", "=", "True", ")", "# raise error if download was unsuccessful", "response", ".", ...
Yield a downloaded url as byte chunks. :param url: str or url :param chunk_size: None or int in bytes :yield: byte chunks
[ "Yield", "a", "downloaded", "url", "as", "byte", "chunks", "." ]
e68b72852b61276f8e6793bc8811f5b2432a155f
https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/utils.py#L98-L119
train
220,711
maartenbreddels/ipyvolume
ipyvolume/utils.py
download_to_file
def download_to_file(url, filepath, resume=False, overwrite=False, chunk_size=1024 * 1024 * 10, loadbar_length=10): """Download a url. prints a simple loading bar [=*loadbar_length] to show progress (in console and notebook) :type url: str :type filepath: str :param filepath: path to download to :param resume: if True resume download from existing file chunk :param overwrite: if True remove any existing filepath :param chunk_size: None or int in bytes :param loadbar_length: int length of load bar :return: """ resume_header = None loaded_size = 0 write_mode = 'wb' if os.path.exists(filepath): if overwrite: os.remove(filepath) elif resume: # if we want to resume, first try and see if the file is already complete loaded_size = os.path.getsize(filepath) clength = requests.head(url).headers.get('content-length') if clength is not None: if int(clength) == loaded_size: return None # give the point to resume at resume_header = {'Range': 'bytes=%s-' % loaded_size} write_mode = 'ab' else: return None stream = False if chunk_size is None else True # start printing with no return character, so that we can have everything on one line print("Downloading {0:s}: ".format(url), end="") response = requests.get(url, stream=stream, headers=resume_header) # raise error if download was unsuccessful response.raise_for_status() # get the size of the file if available total_length = response.headers.get('content-length') if total_length is not None: total_length = float(total_length) + loaded_size print("{0:.2f}Mb/{1:} ".format(total_length / (1024 * 1024), loadbar_length), end="") print("[", end="") parent = os.path.dirname(filepath) if not os.path.exists(parent) and parent: os.makedirs(parent) with io.open(filepath, write_mode) as f: loaded = 0 for chunk in response.iter_content(chunk_size=chunk_size): if chunk: # filter out keep-alive new chunks # print our progress bar if total_length is not None and chunk_size is not None: while loaded < loadbar_length * loaded_size / total_length: print("=", end='') loaded += 1 loaded_size += chunk_size f.write(chunk) if total_length is None: print("=" * loadbar_length, end='') else: while loaded < loadbar_length: print("=", end='') loaded += 1 print("] Finished")
python
def download_to_file(url, filepath, resume=False, overwrite=False, chunk_size=1024 * 1024 * 10, loadbar_length=10): """Download a url. prints a simple loading bar [=*loadbar_length] to show progress (in console and notebook) :type url: str :type filepath: str :param filepath: path to download to :param resume: if True resume download from existing file chunk :param overwrite: if True remove any existing filepath :param chunk_size: None or int in bytes :param loadbar_length: int length of load bar :return: """ resume_header = None loaded_size = 0 write_mode = 'wb' if os.path.exists(filepath): if overwrite: os.remove(filepath) elif resume: # if we want to resume, first try and see if the file is already complete loaded_size = os.path.getsize(filepath) clength = requests.head(url).headers.get('content-length') if clength is not None: if int(clength) == loaded_size: return None # give the point to resume at resume_header = {'Range': 'bytes=%s-' % loaded_size} write_mode = 'ab' else: return None stream = False if chunk_size is None else True # start printing with no return character, so that we can have everything on one line print("Downloading {0:s}: ".format(url), end="") response = requests.get(url, stream=stream, headers=resume_header) # raise error if download was unsuccessful response.raise_for_status() # get the size of the file if available total_length = response.headers.get('content-length') if total_length is not None: total_length = float(total_length) + loaded_size print("{0:.2f}Mb/{1:} ".format(total_length / (1024 * 1024), loadbar_length), end="") print("[", end="") parent = os.path.dirname(filepath) if not os.path.exists(parent) and parent: os.makedirs(parent) with io.open(filepath, write_mode) as f: loaded = 0 for chunk in response.iter_content(chunk_size=chunk_size): if chunk: # filter out keep-alive new chunks # print our progress bar if total_length is not None and chunk_size is not None: while loaded < loadbar_length * loaded_size / total_length: print("=", end='') loaded += 1 loaded_size += chunk_size f.write(chunk) if total_length is None: print("=" * loadbar_length, end='') else: while loaded < loadbar_length: print("=", end='') loaded += 1 print("] Finished")
[ "def", "download_to_file", "(", "url", ",", "filepath", ",", "resume", "=", "False", ",", "overwrite", "=", "False", ",", "chunk_size", "=", "1024", "*", "1024", "*", "10", ",", "loadbar_length", "=", "10", ")", ":", "resume_header", "=", "None", "loaded...
Download a url. prints a simple loading bar [=*loadbar_length] to show progress (in console and notebook) :type url: str :type filepath: str :param filepath: path to download to :param resume: if True resume download from existing file chunk :param overwrite: if True remove any existing filepath :param chunk_size: None or int in bytes :param loadbar_length: int length of load bar :return:
[ "Download", "a", "url", "." ]
e68b72852b61276f8e6793bc8811f5b2432a155f
https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/utils.py#L122-L193
train
220,712
maartenbreddels/ipyvolume
ipyvolume/astro.py
_randomSO3
def _randomSO3(): """Return random rotatation matrix, algo by James Arvo.""" u1 = np.random.random() u2 = np.random.random() u3 = np.random.random() R = np.array( [ [np.cos(2 * np.pi * u1), np.sin(2 * np.pi * u1), 0], [-np.sin(2 * np.pi * u1), np.cos(2 * np.pi * u1), 0], [0, 0, 1], ] ) v = np.array([np.cos(2 * np.pi * u2) * np.sqrt(u3), np.sin(2 * np.pi * u2) * np.sqrt(u3), np.sqrt(1 - u3)]) H = np.identity(3) - 2 * v * np.transpose([v]) return -np.dot(H, R)
python
def _randomSO3(): """Return random rotatation matrix, algo by James Arvo.""" u1 = np.random.random() u2 = np.random.random() u3 = np.random.random() R = np.array( [ [np.cos(2 * np.pi * u1), np.sin(2 * np.pi * u1), 0], [-np.sin(2 * np.pi * u1), np.cos(2 * np.pi * u1), 0], [0, 0, 1], ] ) v = np.array([np.cos(2 * np.pi * u2) * np.sqrt(u3), np.sin(2 * np.pi * u2) * np.sqrt(u3), np.sqrt(1 - u3)]) H = np.identity(3) - 2 * v * np.transpose([v]) return -np.dot(H, R)
[ "def", "_randomSO3", "(", ")", ":", "u1", "=", "np", ".", "random", ".", "random", "(", ")", "u2", "=", "np", ".", "random", ".", "random", "(", ")", "u3", "=", "np", ".", "random", ".", "random", "(", ")", "R", "=", "np", ".", "array", "(", ...
Return random rotatation matrix, algo by James Arvo.
[ "Return", "random", "rotatation", "matrix", "algo", "by", "James", "Arvo", "." ]
e68b72852b61276f8e6793bc8811f5b2432a155f
https://github.com/maartenbreddels/ipyvolume/blob/e68b72852b61276f8e6793bc8811f5b2432a155f/ipyvolume/astro.py#L11-L25
train
220,713
jaegertracing/jaeger-client-python
jaeger_client/throttler.py
RemoteThrottler._set_client_id
def _set_client_id(self, client_id): """ Method for tracer to set client ID of throttler. """ with self.lock: if self.client_id is None: self.client_id = client_id
python
def _set_client_id(self, client_id): """ Method for tracer to set client ID of throttler. """ with self.lock: if self.client_id is None: self.client_id = client_id
[ "def", "_set_client_id", "(", "self", ",", "client_id", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "client_id", "is", "None", ":", "self", ".", "client_id", "=", "client_id" ]
Method for tracer to set client ID of throttler.
[ "Method", "for", "tracer", "to", "set", "client", "ID", "of", "throttler", "." ]
06face094757c645a6d81f0e073c001931a22a05
https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/throttler.py#L81-L87
train
220,714
jaegertracing/jaeger-client-python
jaeger_client/throttler.py
RemoteThrottler._init_polling
def _init_polling(self): """ Bootstrap polling for throttler. To avoid spiky traffic from throttler clients, we use a random delay before the first poll. """ with self.lock: if not self.running: return r = random.Random() delay = r.random() * self.refresh_interval self.channel.io_loop.call_later( delay=delay, callback=self._delayed_polling) self.logger.info( 'Delaying throttling credit polling by %d sec', delay)
python
def _init_polling(self): """ Bootstrap polling for throttler. To avoid spiky traffic from throttler clients, we use a random delay before the first poll. """ with self.lock: if not self.running: return r = random.Random() delay = r.random() * self.refresh_interval self.channel.io_loop.call_later( delay=delay, callback=self._delayed_polling) self.logger.info( 'Delaying throttling credit polling by %d sec', delay)
[ "def", "_init_polling", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "not", "self", ".", "running", ":", "return", "r", "=", "random", ".", "Random", "(", ")", "delay", "=", "r", ".", "random", "(", ")", "*", "self", ".", "refre...
Bootstrap polling for throttler. To avoid spiky traffic from throttler clients, we use a random delay before the first poll.
[ "Bootstrap", "polling", "for", "throttler", "." ]
06face094757c645a6d81f0e073c001931a22a05
https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/throttler.py#L89-L105
train
220,715
jaegertracing/jaeger-client-python
jaeger_client/reporter.py
Reporter.close
def close(self): """ Ensure that all spans from the queue are submitted. Returns Future that will be completed once the queue is empty. """ with self.stop_lock: self.stopped = True return ioloop_util.submit(self._flush, io_loop=self.io_loop)
python
def close(self): """ Ensure that all spans from the queue are submitted. Returns Future that will be completed once the queue is empty. """ with self.stop_lock: self.stopped = True return ioloop_util.submit(self._flush, io_loop=self.io_loop)
[ "def", "close", "(", "self", ")", ":", "with", "self", ".", "stop_lock", ":", "self", ".", "stopped", "=", "True", "return", "ioloop_util", ".", "submit", "(", "self", ".", "_flush", ",", "io_loop", "=", "self", ".", "io_loop", ")" ]
Ensure that all spans from the queue are submitted. Returns Future that will be completed once the queue is empty.
[ "Ensure", "that", "all", "spans", "from", "the", "queue", "are", "submitted", ".", "Returns", "Future", "that", "will", "be", "completed", "once", "the", "queue", "is", "empty", "." ]
06face094757c645a6d81f0e073c001931a22a05
https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/reporter.py#L218-L226
train
220,716
jaegertracing/jaeger-client-python
jaeger_client/span.py
Span.finish
def finish(self, finish_time=None): """Indicate that the work represented by this span has been completed or terminated, and is ready to be sent to the Reporter. If any tags / logs need to be added to the span, it should be done before calling finish(), otherwise they may be ignored. :param finish_time: an explicit Span finish timestamp as a unix timestamp per time.time() """ if not self.is_sampled(): return self.end_time = finish_time or time.time() # no locking self.tracer.report_span(self)
python
def finish(self, finish_time=None): """Indicate that the work represented by this span has been completed or terminated, and is ready to be sent to the Reporter. If any tags / logs need to be added to the span, it should be done before calling finish(), otherwise they may be ignored. :param finish_time: an explicit Span finish timestamp as a unix timestamp per time.time() """ if not self.is_sampled(): return self.end_time = finish_time or time.time() # no locking self.tracer.report_span(self)
[ "def", "finish", "(", "self", ",", "finish_time", "=", "None", ")", ":", "if", "not", "self", ".", "is_sampled", "(", ")", ":", "return", "self", ".", "end_time", "=", "finish_time", "or", "time", ".", "time", "(", ")", "# no locking", "self", ".", "...
Indicate that the work represented by this span has been completed or terminated, and is ready to be sent to the Reporter. If any tags / logs need to be added to the span, it should be done before calling finish(), otherwise they may be ignored. :param finish_time: an explicit Span finish timestamp as a unix timestamp per time.time()
[ "Indicate", "that", "the", "work", "represented", "by", "this", "span", "has", "been", "completed", "or", "terminated", "and", "is", "ready", "to", "be", "sent", "to", "the", "Reporter", "." ]
06face094757c645a6d81f0e073c001931a22a05
https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/span.py#L60-L74
train
220,717
jaegertracing/jaeger-client-python
jaeger_client/span.py
Span._set_sampling_priority
def _set_sampling_priority(self, value): """ N.B. Caller must be holding update_lock. """ # Ignore debug spans trying to re-enable debug. if self.is_debug() and value: return False try: value_num = int(value) except ValueError: return False if value_num == 0: self.context.flags &= ~(SAMPLED_FLAG | DEBUG_FLAG) return False if self.tracer.is_debug_allowed(self.operation_name): self.context.flags |= SAMPLED_FLAG | DEBUG_FLAG return True return False
python
def _set_sampling_priority(self, value): """ N.B. Caller must be holding update_lock. """ # Ignore debug spans trying to re-enable debug. if self.is_debug() and value: return False try: value_num = int(value) except ValueError: return False if value_num == 0: self.context.flags &= ~(SAMPLED_FLAG | DEBUG_FLAG) return False if self.tracer.is_debug_allowed(self.operation_name): self.context.flags |= SAMPLED_FLAG | DEBUG_FLAG return True return False
[ "def", "_set_sampling_priority", "(", "self", ",", "value", ")", ":", "# Ignore debug spans trying to re-enable debug.", "if", "self", ".", "is_debug", "(", ")", "and", "value", ":", "return", "False", "try", ":", "value_num", "=", "int", "(", "value", ")", "e...
N.B. Caller must be holding update_lock.
[ "N", ".", "B", ".", "Caller", "must", "be", "holding", "update_lock", "." ]
06face094757c645a6d81f0e073c001931a22a05
https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/span.py#L92-L111
train
220,718
jaegertracing/jaeger-client-python
jaeger_client/TUDPTransport.py
TUDPTransport.write
def write(self, buf): """Raw write to the UDP socket.""" return self.transport_sock.sendto( buf, (self.transport_host, self.transport_port) )
python
def write(self, buf): """Raw write to the UDP socket.""" return self.transport_sock.sendto( buf, (self.transport_host, self.transport_port) )
[ "def", "write", "(", "self", ",", "buf", ")", ":", "return", "self", ".", "transport_sock", ".", "sendto", "(", "buf", ",", "(", "self", ".", "transport_host", ",", "self", ".", "transport_port", ")", ")" ]
Raw write to the UDP socket.
[ "Raw", "write", "to", "the", "UDP", "socket", "." ]
06face094757c645a6d81f0e073c001931a22a05
https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/TUDPTransport.py#L39-L44
train
220,719
jaegertracing/jaeger-client-python
jaeger_client/config.py
Config.initialize_tracer
def initialize_tracer(self, io_loop=None): """ Initialize Jaeger Tracer based on the passed `jaeger_client.Config`. Save it to `opentracing.tracer` global variable. Only the first call to this method has any effect. """ with Config._initialized_lock: if Config._initialized: logger.warn('Jaeger tracer already initialized, skipping') return Config._initialized = True tracer = self.new_tracer(io_loop) self._initialize_global_tracer(tracer=tracer) return tracer
python
def initialize_tracer(self, io_loop=None): """ Initialize Jaeger Tracer based on the passed `jaeger_client.Config`. Save it to `opentracing.tracer` global variable. Only the first call to this method has any effect. """ with Config._initialized_lock: if Config._initialized: logger.warn('Jaeger tracer already initialized, skipping') return Config._initialized = True tracer = self.new_tracer(io_loop) self._initialize_global_tracer(tracer=tracer) return tracer
[ "def", "initialize_tracer", "(", "self", ",", "io_loop", "=", "None", ")", ":", "with", "Config", ".", "_initialized_lock", ":", "if", "Config", ".", "_initialized", ":", "logger", ".", "warn", "(", "'Jaeger tracer already initialized, skipping'", ")", "return", ...
Initialize Jaeger Tracer based on the passed `jaeger_client.Config`. Save it to `opentracing.tracer` global variable. Only the first call to this method has any effect.
[ "Initialize", "Jaeger", "Tracer", "based", "on", "the", "passed", "jaeger_client", ".", "Config", ".", "Save", "it", "to", "opentracing", ".", "tracer", "global", "variable", ".", "Only", "the", "first", "call", "to", "this", "method", "has", "any", "effect"...
06face094757c645a6d81f0e073c001931a22a05
https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/config.py#L340-L356
train
220,720
jaegertracing/jaeger-client-python
jaeger_client/config.py
Config.new_tracer
def new_tracer(self, io_loop=None): """ Create a new Jaeger Tracer based on the passed `jaeger_client.Config`. Does not set `opentracing.tracer` global variable. """ channel = self._create_local_agent_channel(io_loop=io_loop) sampler = self.sampler if not sampler: sampler = RemoteControlledSampler( channel=channel, service_name=self.service_name, logger=logger, metrics_factory=self._metrics_factory, error_reporter=self.error_reporter, sampling_refresh_interval=self.sampling_refresh_interval, max_operations=self.max_operations) logger.info('Using sampler %s', sampler) reporter = Reporter( channel=channel, queue_capacity=self.reporter_queue_size, batch_size=self.reporter_batch_size, flush_interval=self.reporter_flush_interval, logger=logger, metrics_factory=self._metrics_factory, error_reporter=self.error_reporter) if self.logging: reporter = CompositeReporter(reporter, LoggingReporter(logger)) if not self.throttler_group() is None: throttler = RemoteThrottler( channel, self.service_name, refresh_interval=self.throttler_refresh_interval, logger=logger, metrics_factory=self._metrics_factory, error_reporter=self.error_reporter) else: throttler = None return self.create_tracer( reporter=reporter, sampler=sampler, throttler=throttler, )
python
def new_tracer(self, io_loop=None): """ Create a new Jaeger Tracer based on the passed `jaeger_client.Config`. Does not set `opentracing.tracer` global variable. """ channel = self._create_local_agent_channel(io_loop=io_loop) sampler = self.sampler if not sampler: sampler = RemoteControlledSampler( channel=channel, service_name=self.service_name, logger=logger, metrics_factory=self._metrics_factory, error_reporter=self.error_reporter, sampling_refresh_interval=self.sampling_refresh_interval, max_operations=self.max_operations) logger.info('Using sampler %s', sampler) reporter = Reporter( channel=channel, queue_capacity=self.reporter_queue_size, batch_size=self.reporter_batch_size, flush_interval=self.reporter_flush_interval, logger=logger, metrics_factory=self._metrics_factory, error_reporter=self.error_reporter) if self.logging: reporter = CompositeReporter(reporter, LoggingReporter(logger)) if not self.throttler_group() is None: throttler = RemoteThrottler( channel, self.service_name, refresh_interval=self.throttler_refresh_interval, logger=logger, metrics_factory=self._metrics_factory, error_reporter=self.error_reporter) else: throttler = None return self.create_tracer( reporter=reporter, sampler=sampler, throttler=throttler, )
[ "def", "new_tracer", "(", "self", ",", "io_loop", "=", "None", ")", ":", "channel", "=", "self", ".", "_create_local_agent_channel", "(", "io_loop", "=", "io_loop", ")", "sampler", "=", "self", ".", "sampler", "if", "not", "sampler", ":", "sampler", "=", ...
Create a new Jaeger Tracer based on the passed `jaeger_client.Config`. Does not set `opentracing.tracer` global variable.
[ "Create", "a", "new", "Jaeger", "Tracer", "based", "on", "the", "passed", "jaeger_client", ".", "Config", ".", "Does", "not", "set", "opentracing", ".", "tracer", "global", "variable", "." ]
06face094757c645a6d81f0e073c001931a22a05
https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/config.py#L358-L403
train
220,721
jaegertracing/jaeger-client-python
jaeger_client/config.py
Config._create_local_agent_channel
def _create_local_agent_channel(self, io_loop): """ Create an out-of-process channel communicating to local jaeger-agent. Spans are submitted as SOCK_DGRAM Thrift, sampling strategy is polled via JSON HTTP. :param self: instance of Config """ logger.info('Initializing Jaeger Tracer with UDP reporter') return LocalAgentSender( host=self.local_agent_reporting_host, sampling_port=self.local_agent_sampling_port, reporting_port=self.local_agent_reporting_port, throttling_port=self.throttler_port, io_loop=io_loop )
python
def _create_local_agent_channel(self, io_loop): """ Create an out-of-process channel communicating to local jaeger-agent. Spans are submitted as SOCK_DGRAM Thrift, sampling strategy is polled via JSON HTTP. :param self: instance of Config """ logger.info('Initializing Jaeger Tracer with UDP reporter') return LocalAgentSender( host=self.local_agent_reporting_host, sampling_port=self.local_agent_sampling_port, reporting_port=self.local_agent_reporting_port, throttling_port=self.throttler_port, io_loop=io_loop )
[ "def", "_create_local_agent_channel", "(", "self", ",", "io_loop", ")", ":", "logger", ".", "info", "(", "'Initializing Jaeger Tracer with UDP reporter'", ")", "return", "LocalAgentSender", "(", "host", "=", "self", ".", "local_agent_reporting_host", ",", "sampling_port...
Create an out-of-process channel communicating to local jaeger-agent. Spans are submitted as SOCK_DGRAM Thrift, sampling strategy is polled via JSON HTTP. :param self: instance of Config
[ "Create", "an", "out", "-", "of", "-", "process", "channel", "communicating", "to", "local", "jaeger", "-", "agent", ".", "Spans", "are", "submitted", "as", "SOCK_DGRAM", "Thrift", "sampling", "strategy", "is", "polled", "via", "JSON", "HTTP", "." ]
06face094757c645a6d81f0e073c001931a22a05
https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/config.py#L427-L442
train
220,722
jaegertracing/jaeger-client-python
jaeger_client/codecs.py
span_context_from_string
def span_context_from_string(value): """ Decode span ID from a string into a TraceContext. Returns None if the string value is malformed. :param value: formatted {trace_id}:{span_id}:{parent_id}:{flags} """ if type(value) is list and len(value) > 0: # sometimes headers are presented as arrays of values if len(value) > 1: raise SpanContextCorruptedException( 'trace context must be a string or array of 1: "%s"' % value) value = value[0] if not isinstance(value, six.string_types): raise SpanContextCorruptedException( 'trace context not a string "%s"' % value) parts = value.split(':') if len(parts) != 4: raise SpanContextCorruptedException( 'malformed trace context "%s"' % value) try: trace_id = int(parts[0], 16) span_id = int(parts[1], 16) parent_id = int(parts[2], 16) flags = int(parts[3], 16) if trace_id < 1 or span_id < 1 or parent_id < 0 or flags < 0: raise SpanContextCorruptedException( 'malformed trace context "%s"' % value) if parent_id == 0: parent_id = None return trace_id, span_id, parent_id, flags except ValueError as e: raise SpanContextCorruptedException( 'malformed trace context "%s": %s' % (value, e))
python
def span_context_from_string(value): """ Decode span ID from a string into a TraceContext. Returns None if the string value is malformed. :param value: formatted {trace_id}:{span_id}:{parent_id}:{flags} """ if type(value) is list and len(value) > 0: # sometimes headers are presented as arrays of values if len(value) > 1: raise SpanContextCorruptedException( 'trace context must be a string or array of 1: "%s"' % value) value = value[0] if not isinstance(value, six.string_types): raise SpanContextCorruptedException( 'trace context not a string "%s"' % value) parts = value.split(':') if len(parts) != 4: raise SpanContextCorruptedException( 'malformed trace context "%s"' % value) try: trace_id = int(parts[0], 16) span_id = int(parts[1], 16) parent_id = int(parts[2], 16) flags = int(parts[3], 16) if trace_id < 1 or span_id < 1 or parent_id < 0 or flags < 0: raise SpanContextCorruptedException( 'malformed trace context "%s"' % value) if parent_id == 0: parent_id = None return trace_id, span_id, parent_id, flags except ValueError as e: raise SpanContextCorruptedException( 'malformed trace context "%s": %s' % (value, e))
[ "def", "span_context_from_string", "(", "value", ")", ":", "if", "type", "(", "value", ")", "is", "list", "and", "len", "(", "value", ")", ">", "0", ":", "# sometimes headers are presented as arrays of values", "if", "len", "(", "value", ")", ">", "1", ":", ...
Decode span ID from a string into a TraceContext. Returns None if the string value is malformed. :param value: formatted {trace_id}:{span_id}:{parent_id}:{flags}
[ "Decode", "span", "ID", "from", "a", "string", "into", "a", "TraceContext", ".", "Returns", "None", "if", "the", "string", "value", "is", "malformed", "." ]
06face094757c645a6d81f0e073c001931a22a05
https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/codecs.py#L173-L206
train
220,723
jaegertracing/jaeger-client-python
jaeger_client/thrift.py
parse_sampling_strategy
def parse_sampling_strategy(response): """ Parse SamplingStrategyResponse and converts to a Sampler. :param response: :return: Returns Go-style (value, error) pair """ s_type = response.strategyType if s_type == sampling_manager.SamplingStrategyType.PROBABILISTIC: if response.probabilisticSampling is None: return None, 'probabilisticSampling field is None' sampling_rate = response.probabilisticSampling.samplingRate if 0 <= sampling_rate <= 1.0: from jaeger_client.sampler import ProbabilisticSampler return ProbabilisticSampler(rate=sampling_rate), None return None, ( 'Probabilistic sampling rate not in [0, 1] range: %s' % sampling_rate ) elif s_type == sampling_manager.SamplingStrategyType.RATE_LIMITING: if response.rateLimitingSampling is None: return None, 'rateLimitingSampling field is None' mtps = response.rateLimitingSampling.maxTracesPerSecond if 0 <= mtps < 500: from jaeger_client.sampler import RateLimitingSampler return RateLimitingSampler(max_traces_per_second=mtps), None return None, ( 'Rate limiting parameter not in [0, 500] range: %s' % mtps ) return None, ( 'Unsupported sampling strategy type: %s' % s_type )
python
def parse_sampling_strategy(response): """ Parse SamplingStrategyResponse and converts to a Sampler. :param response: :return: Returns Go-style (value, error) pair """ s_type = response.strategyType if s_type == sampling_manager.SamplingStrategyType.PROBABILISTIC: if response.probabilisticSampling is None: return None, 'probabilisticSampling field is None' sampling_rate = response.probabilisticSampling.samplingRate if 0 <= sampling_rate <= 1.0: from jaeger_client.sampler import ProbabilisticSampler return ProbabilisticSampler(rate=sampling_rate), None return None, ( 'Probabilistic sampling rate not in [0, 1] range: %s' % sampling_rate ) elif s_type == sampling_manager.SamplingStrategyType.RATE_LIMITING: if response.rateLimitingSampling is None: return None, 'rateLimitingSampling field is None' mtps = response.rateLimitingSampling.maxTracesPerSecond if 0 <= mtps < 500: from jaeger_client.sampler import RateLimitingSampler return RateLimitingSampler(max_traces_per_second=mtps), None return None, ( 'Rate limiting parameter not in [0, 500] range: %s' % mtps ) return None, ( 'Unsupported sampling strategy type: %s' % s_type )
[ "def", "parse_sampling_strategy", "(", "response", ")", ":", "s_type", "=", "response", ".", "strategyType", "if", "s_type", "==", "sampling_manager", ".", "SamplingStrategyType", ".", "PROBABILISTIC", ":", "if", "response", ".", "probabilisticSampling", "is", "None...
Parse SamplingStrategyResponse and converts to a Sampler. :param response: :return: Returns Go-style (value, error) pair
[ "Parse", "SamplingStrategyResponse", "and", "converts", "to", "a", "Sampler", "." ]
06face094757c645a6d81f0e073c001931a22a05
https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/thrift.py#L208-L239
train
220,724
jaegertracing/jaeger-client-python
jaeger_client/span_context.py
SpanContext.with_debug_id
def with_debug_id(debug_id): """Deprecated, not used by Jaeger.""" ctx = SpanContext( trace_id=None, span_id=None, parent_id=None, flags=None ) ctx._debug_id = debug_id return ctx
python
def with_debug_id(debug_id): """Deprecated, not used by Jaeger.""" ctx = SpanContext( trace_id=None, span_id=None, parent_id=None, flags=None ) ctx._debug_id = debug_id return ctx
[ "def", "with_debug_id", "(", "debug_id", ")", ":", "ctx", "=", "SpanContext", "(", "trace_id", "=", "None", ",", "span_id", "=", "None", ",", "parent_id", "=", "None", ",", "flags", "=", "None", ")", "ctx", ".", "_debug_id", "=", "debug_id", "return", ...
Deprecated, not used by Jaeger.
[ "Deprecated", "not", "used", "by", "Jaeger", "." ]
06face094757c645a6d81f0e073c001931a22a05
https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/span_context.py#L65-L71
train
220,725
jaegertracing/jaeger-client-python
jaeger_client/tracer.py
Tracer.start_span
def start_span(self, operation_name=None, child_of=None, references=None, tags=None, start_time=None, ignore_active_span=False, ): """ Start and return a new Span representing a unit of work. :param operation_name: name of the operation represented by the new span from the perspective of the current service. :param child_of: shortcut for 'child_of' reference :param references: (optional) either a single Reference object or a list of Reference objects that identify one or more parent SpanContexts. (See the opentracing.Reference documentation for detail) :param tags: optional dictionary of Span Tags. The caller gives up ownership of that dictionary, because the Tracer may use it as-is to avoid extra data copying. :param start_time: an explicit Span start time as a unix timestamp per time.time() :param ignore_active_span: an explicit flag that ignores the current active :class:`Scope` and creates a root :class:`Span` :return: Returns an already-started Span instance. """ parent = child_of if self.active_span is not None \ and not ignore_active_span \ and not parent: parent = self.active_span # allow Span to be passed as reference, not just SpanContext if isinstance(parent, Span): parent = parent.context valid_references = None if references: valid_references = list() if not isinstance(references, list): references = [references] for reference in references: if reference.referenced_context is not None: valid_references.append(reference) # setting first reference as parent if valid_references and (parent is None or not parent.has_trace): parent = valid_references[0].referenced_context rpc_server = tags and \ tags.get(ext_tags.SPAN_KIND) == ext_tags.SPAN_KIND_RPC_SERVER if parent is None or not parent.has_trace: trace_id = self._random_id(self.max_trace_id_bits) span_id = self._random_id(constants._max_id_bits) parent_id = None flags = 0 baggage = None if parent is None: sampled, sampler_tags = \ self.sampler.is_sampled(trace_id, operation_name) if sampled: flags = SAMPLED_FLAG tags = tags or {} for k, v in six.iteritems(sampler_tags): tags[k] = v elif parent.debug_id and self.is_debug_allowed(operation_name): flags = SAMPLED_FLAG | DEBUG_FLAG tags = tags or {} tags[self.debug_id_header] = parent.debug_id if parent and parent.baggage: baggage = dict(parent.baggage) # TODO do we need to clone? else: trace_id = parent.trace_id if rpc_server and self.one_span_per_rpc: # Zipkin-style one-span-per-RPC span_id = parent.span_id parent_id = parent.parent_id else: span_id = self._random_id(constants._max_id_bits) parent_id = parent.span_id flags = parent.flags baggage = dict(parent.baggage) # TODO do we need to clone? span_ctx = SpanContext(trace_id=trace_id, span_id=span_id, parent_id=parent_id, flags=flags, baggage=baggage) span = Span(context=span_ctx, tracer=self, operation_name=operation_name, tags=tags, start_time=start_time, references=valid_references) self._emit_span_metrics(span=span, join=rpc_server) return span
python
def start_span(self, operation_name=None, child_of=None, references=None, tags=None, start_time=None, ignore_active_span=False, ): """ Start and return a new Span representing a unit of work. :param operation_name: name of the operation represented by the new span from the perspective of the current service. :param child_of: shortcut for 'child_of' reference :param references: (optional) either a single Reference object or a list of Reference objects that identify one or more parent SpanContexts. (See the opentracing.Reference documentation for detail) :param tags: optional dictionary of Span Tags. The caller gives up ownership of that dictionary, because the Tracer may use it as-is to avoid extra data copying. :param start_time: an explicit Span start time as a unix timestamp per time.time() :param ignore_active_span: an explicit flag that ignores the current active :class:`Scope` and creates a root :class:`Span` :return: Returns an already-started Span instance. """ parent = child_of if self.active_span is not None \ and not ignore_active_span \ and not parent: parent = self.active_span # allow Span to be passed as reference, not just SpanContext if isinstance(parent, Span): parent = parent.context valid_references = None if references: valid_references = list() if not isinstance(references, list): references = [references] for reference in references: if reference.referenced_context is not None: valid_references.append(reference) # setting first reference as parent if valid_references and (parent is None or not parent.has_trace): parent = valid_references[0].referenced_context rpc_server = tags and \ tags.get(ext_tags.SPAN_KIND) == ext_tags.SPAN_KIND_RPC_SERVER if parent is None or not parent.has_trace: trace_id = self._random_id(self.max_trace_id_bits) span_id = self._random_id(constants._max_id_bits) parent_id = None flags = 0 baggage = None if parent is None: sampled, sampler_tags = \ self.sampler.is_sampled(trace_id, operation_name) if sampled: flags = SAMPLED_FLAG tags = tags or {} for k, v in six.iteritems(sampler_tags): tags[k] = v elif parent.debug_id and self.is_debug_allowed(operation_name): flags = SAMPLED_FLAG | DEBUG_FLAG tags = tags or {} tags[self.debug_id_header] = parent.debug_id if parent and parent.baggage: baggage = dict(parent.baggage) # TODO do we need to clone? else: trace_id = parent.trace_id if rpc_server and self.one_span_per_rpc: # Zipkin-style one-span-per-RPC span_id = parent.span_id parent_id = parent.parent_id else: span_id = self._random_id(constants._max_id_bits) parent_id = parent.span_id flags = parent.flags baggage = dict(parent.baggage) # TODO do we need to clone? span_ctx = SpanContext(trace_id=trace_id, span_id=span_id, parent_id=parent_id, flags=flags, baggage=baggage) span = Span(context=span_ctx, tracer=self, operation_name=operation_name, tags=tags, start_time=start_time, references=valid_references) self._emit_span_metrics(span=span, join=rpc_server) return span
[ "def", "start_span", "(", "self", ",", "operation_name", "=", "None", ",", "child_of", "=", "None", ",", "references", "=", "None", ",", "tags", "=", "None", ",", "start_time", "=", "None", ",", "ignore_active_span", "=", "False", ",", ")", ":", "parent"...
Start and return a new Span representing a unit of work. :param operation_name: name of the operation represented by the new span from the perspective of the current service. :param child_of: shortcut for 'child_of' reference :param references: (optional) either a single Reference object or a list of Reference objects that identify one or more parent SpanContexts. (See the opentracing.Reference documentation for detail) :param tags: optional dictionary of Span Tags. The caller gives up ownership of that dictionary, because the Tracer may use it as-is to avoid extra data copying. :param start_time: an explicit Span start time as a unix timestamp per time.time() :param ignore_active_span: an explicit flag that ignores the current active :class:`Scope` and creates a root :class:`Span` :return: Returns an already-started Span instance.
[ "Start", "and", "return", "a", "new", "Span", "representing", "a", "unit", "of", "work", "." ]
06face094757c645a6d81f0e073c001931a22a05
https://github.com/jaegertracing/jaeger-client-python/blob/06face094757c645a6d81f0e073c001931a22a05/jaeger_client/tracer.py#L118-L213
train
220,726
RedHatInsights/insights-core
insights/combiners/lvm.py
merge_lvm_data
def merge_lvm_data(primary, secondary, name_key): """ Returns a dictionary containing the set of data from primary and secondary where values in primary will always be returned if present, and values in secondary will only be returned if not present in primary, or if the value in primary is `None`. Sample input Data:: primary = [ {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'name_key': 'xyz'}, {'a': None, 'b': 12, 'c': 13, 'd': 14, 'name_key': 'qrs'}, {'a': None, 'b': 12, 'c': 13, 'd': 14, 'name_key': 'def'}, ] secondary = [ {'a': 31, 'e': 33, 'name_key': 'xyz'}, {'a': 11, 'e': 23, 'name_key': 'qrs'}, {'a': 1, 'e': 3, 'name_key': 'ghi'}, ] Returns: dict: Dictionary of key value pairs from obj1 and obj2:: { 'xyz': {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 33, 'name_key': 'xyz'}, 'qrs': {'a': 11, 'b': 12, 'c': 13, d: 14, e: 23, 'name_key': 'qrs'}, 'def': {'a': None, 'b': 12, 'c': 13, 'd': 14, 'name_key': 'def'}, 'ghi': {'a': 1, 'e': 3, 'name_key': 'ghi'} } """ pri_data = to_name_key_dict(primary, name_key) # Prime results with secondary data, to be updated with primary data combined_data = to_name_key_dict(secondary, name_key) for name in pri_data: if name not in combined_data: # Data only in primary combined_data[name] = pri_data[name] else: # Data in both primary and secondary, pick primary if better or no secondary combined_data[name].update(dict( (k, v) for k, v in pri_data[name].items() if v is not None or k not in combined_data[name] )) return set_defaults(combined_data)
python
def merge_lvm_data(primary, secondary, name_key): """ Returns a dictionary containing the set of data from primary and secondary where values in primary will always be returned if present, and values in secondary will only be returned if not present in primary, or if the value in primary is `None`. Sample input Data:: primary = [ {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'name_key': 'xyz'}, {'a': None, 'b': 12, 'c': 13, 'd': 14, 'name_key': 'qrs'}, {'a': None, 'b': 12, 'c': 13, 'd': 14, 'name_key': 'def'}, ] secondary = [ {'a': 31, 'e': 33, 'name_key': 'xyz'}, {'a': 11, 'e': 23, 'name_key': 'qrs'}, {'a': 1, 'e': 3, 'name_key': 'ghi'}, ] Returns: dict: Dictionary of key value pairs from obj1 and obj2:: { 'xyz': {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 33, 'name_key': 'xyz'}, 'qrs': {'a': 11, 'b': 12, 'c': 13, d: 14, e: 23, 'name_key': 'qrs'}, 'def': {'a': None, 'b': 12, 'c': 13, 'd': 14, 'name_key': 'def'}, 'ghi': {'a': 1, 'e': 3, 'name_key': 'ghi'} } """ pri_data = to_name_key_dict(primary, name_key) # Prime results with secondary data, to be updated with primary data combined_data = to_name_key_dict(secondary, name_key) for name in pri_data: if name not in combined_data: # Data only in primary combined_data[name] = pri_data[name] else: # Data in both primary and secondary, pick primary if better or no secondary combined_data[name].update(dict( (k, v) for k, v in pri_data[name].items() if v is not None or k not in combined_data[name] )) return set_defaults(combined_data)
[ "def", "merge_lvm_data", "(", "primary", ",", "secondary", ",", "name_key", ")", ":", "pri_data", "=", "to_name_key_dict", "(", "primary", ",", "name_key", ")", "# Prime results with secondary data, to be updated with primary data", "combined_data", "=", "to_name_key_dict",...
Returns a dictionary containing the set of data from primary and secondary where values in primary will always be returned if present, and values in secondary will only be returned if not present in primary, or if the value in primary is `None`. Sample input Data:: primary = [ {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'name_key': 'xyz'}, {'a': None, 'b': 12, 'c': 13, 'd': 14, 'name_key': 'qrs'}, {'a': None, 'b': 12, 'c': 13, 'd': 14, 'name_key': 'def'}, ] secondary = [ {'a': 31, 'e': 33, 'name_key': 'xyz'}, {'a': 11, 'e': 23, 'name_key': 'qrs'}, {'a': 1, 'e': 3, 'name_key': 'ghi'}, ] Returns: dict: Dictionary of key value pairs from obj1 and obj2:: { 'xyz': {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 33, 'name_key': 'xyz'}, 'qrs': {'a': 11, 'b': 12, 'c': 13, d: 14, e: 23, 'name_key': 'qrs'}, 'def': {'a': None, 'b': 12, 'c': 13, 'd': 14, 'name_key': 'def'}, 'ghi': {'a': 1, 'e': 3, 'name_key': 'ghi'} }
[ "Returns", "a", "dictionary", "containing", "the", "set", "of", "data", "from", "primary", "and", "secondary", "where", "values", "in", "primary", "will", "always", "be", "returned", "if", "present", "and", "values", "in", "secondary", "will", "only", "be", ...
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/combiners/lvm.py#L112-L157
train
220,727
RedHatInsights/insights-core
insights/client/insights_spec.py
InsightsFile.get_output
def get_output(self): ''' Get file content, selecting only lines we are interested in ''' if not os.path.isfile(self.real_path): logger.debug('File %s does not exist', self.real_path) return cmd = [] cmd.append('sed') cmd.append('-rf') cmd.append(constants.default_sed_file) cmd.append(self.real_path) sedcmd = Popen(cmd, stdout=PIPE) if self.exclude is not None: exclude_file = NamedTemporaryFile() exclude_file.write("\n".join(self.exclude).encode('utf-8')) exclude_file.flush() cmd = "grep -v -F -f %s" % exclude_file.name args = shlex.split(cmd) proc = Popen(args, stdin=sedcmd.stdout, stdout=PIPE) sedcmd.stdout.close() stdin = proc.stdout if self.pattern is None: output = proc.communicate()[0] else: sedcmd = proc if self.pattern is not None: pattern_file = NamedTemporaryFile() pattern_file.write("\n".join(self.pattern).encode('utf-8')) pattern_file.flush() cmd = "grep -F -f %s" % pattern_file.name args = shlex.split(cmd) proc1 = Popen(args, stdin=sedcmd.stdout, stdout=PIPE) sedcmd.stdout.close() if self.exclude is not None: stdin.close() output = proc1.communicate()[0] if self.pattern is None and self.exclude is None: output = sedcmd.communicate()[0] return output.decode('utf-8', 'ignore').strip()
python
def get_output(self): ''' Get file content, selecting only lines we are interested in ''' if not os.path.isfile(self.real_path): logger.debug('File %s does not exist', self.real_path) return cmd = [] cmd.append('sed') cmd.append('-rf') cmd.append(constants.default_sed_file) cmd.append(self.real_path) sedcmd = Popen(cmd, stdout=PIPE) if self.exclude is not None: exclude_file = NamedTemporaryFile() exclude_file.write("\n".join(self.exclude).encode('utf-8')) exclude_file.flush() cmd = "grep -v -F -f %s" % exclude_file.name args = shlex.split(cmd) proc = Popen(args, stdin=sedcmd.stdout, stdout=PIPE) sedcmd.stdout.close() stdin = proc.stdout if self.pattern is None: output = proc.communicate()[0] else: sedcmd = proc if self.pattern is not None: pattern_file = NamedTemporaryFile() pattern_file.write("\n".join(self.pattern).encode('utf-8')) pattern_file.flush() cmd = "grep -F -f %s" % pattern_file.name args = shlex.split(cmd) proc1 = Popen(args, stdin=sedcmd.stdout, stdout=PIPE) sedcmd.stdout.close() if self.exclude is not None: stdin.close() output = proc1.communicate()[0] if self.pattern is None and self.exclude is None: output = sedcmd.communicate()[0] return output.decode('utf-8', 'ignore').strip()
[ "def", "get_output", "(", "self", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "self", ".", "real_path", ")", ":", "logger", ".", "debug", "(", "'File %s does not exist'", ",", "self", ".", "real_path", ")", "return", "cmd", "=", "[", ...
Get file content, selecting only lines we are interested in
[ "Get", "file", "content", "selecting", "only", "lines", "we", "are", "interested", "in" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/insights_spec.py#L147-L196
train
220,728
RedHatInsights/insights-core
insights/parsers/openvswitch_logs.py
OpenVSwitchLog._parse_line
def _parse_line(self, line): """ Parse line into fields. """ fields = line.split('|', 4) # stop splitting after fourth | found line_info = {'raw_message': line} if len(fields) == 5: line_info.update(dict(zip(self._fieldnames, fields))) return line_info
python
def _parse_line(self, line): """ Parse line into fields. """ fields = line.split('|', 4) # stop splitting after fourth | found line_info = {'raw_message': line} if len(fields) == 5: line_info.update(dict(zip(self._fieldnames, fields))) return line_info
[ "def", "_parse_line", "(", "self", ",", "line", ")", ":", "fields", "=", "line", ".", "split", "(", "'|'", ",", "4", ")", "# stop splitting after fourth | found", "line_info", "=", "{", "'raw_message'", ":", "line", "}", "if", "len", "(", "fields", ")", ...
Parse line into fields.
[ "Parse", "line", "into", "fields", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/openvswitch_logs.py#L52-L60
train
220,729
RedHatInsights/insights-core
insights/core/dr.py
_import_component
def _import_component(name): """ Returns a class, function, or class method specified by the fully qualified name. """ for f in (_get_from_module, _get_from_class): try: return f(name) except: pass log.debug("Couldn't load %s" % name)
python
def _import_component(name): """ Returns a class, function, or class method specified by the fully qualified name. """ for f in (_get_from_module, _get_from_class): try: return f(name) except: pass log.debug("Couldn't load %s" % name)
[ "def", "_import_component", "(", "name", ")", ":", "for", "f", "in", "(", "_get_from_module", ",", "_get_from_class", ")", ":", "try", ":", "return", "f", "(", "name", ")", "except", ":", "pass", "log", ".", "debug", "(", "\"Couldn't load %s\"", "%", "na...
Returns a class, function, or class method specified by the fully qualified name.
[ "Returns", "a", "class", "function", "or", "class", "method", "specified", "by", "the", "fully", "qualified", "name", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L151-L161
train
220,730
RedHatInsights/insights-core
insights/core/dr.py
get_name
def get_name(component): """ Attempt to get the string name of component, including module and class if applicable. """ if six.callable(component): name = getattr(component, "__qualname__", component.__name__) return '.'.join([component.__module__, name]) return str(component)
python
def get_name(component): """ Attempt to get the string name of component, including module and class if applicable. """ if six.callable(component): name = getattr(component, "__qualname__", component.__name__) return '.'.join([component.__module__, name]) return str(component)
[ "def", "get_name", "(", "component", ")", ":", "if", "six", ".", "callable", "(", "component", ")", ":", "name", "=", "getattr", "(", "component", ",", "\"__qualname__\"", ",", "component", ".", "__name__", ")", "return", "'.'", ".", "join", "(", "[", ...
Attempt to get the string name of component, including module and class if applicable.
[ "Attempt", "to", "get", "the", "string", "name", "of", "component", "including", "module", "and", "class", "if", "applicable", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L237-L245
train
220,731
RedHatInsights/insights-core
insights/core/dr.py
walk_dependencies
def walk_dependencies(root, visitor): """ Call visitor on root and all dependencies reachable from it in breadth first order. Args: root (component): component function or class visitor (function): signature is `func(component, parent)`. The call on root is `visitor(root, None)`. """ def visit(parent, visitor): for d in get_dependencies(parent): visitor(d, parent) visit(d, visitor) visitor(root, None) visit(root, visitor)
python
def walk_dependencies(root, visitor): """ Call visitor on root and all dependencies reachable from it in breadth first order. Args: root (component): component function or class visitor (function): signature is `func(component, parent)`. The call on root is `visitor(root, None)`. """ def visit(parent, visitor): for d in get_dependencies(parent): visitor(d, parent) visit(d, visitor) visitor(root, None) visit(root, visitor)
[ "def", "walk_dependencies", "(", "root", ",", "visitor", ")", ":", "def", "visit", "(", "parent", ",", "visitor", ")", ":", "for", "d", "in", "get_dependencies", "(", "parent", ")", ":", "visitor", "(", "d", ",", "parent", ")", "visit", "(", "d", ","...
Call visitor on root and all dependencies reachable from it in breadth first order. Args: root (component): component function or class visitor (function): signature is `func(component, parent)`. The call on root is `visitor(root, None)`.
[ "Call", "visitor", "on", "root", "and", "all", "dependencies", "reachable", "from", "it", "in", "breadth", "first", "order", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L303-L319
train
220,732
RedHatInsights/insights-core
insights/core/dr.py
get_subgraphs
def get_subgraphs(graph=None): """ Given a graph of possibly disconnected components, generate all graphs of connected components. graph is a dictionary of dependencies. Keys are components, and values are sets of components on which they depend. """ graph = graph or DEPENDENCIES keys = set(graph) frontier = set() seen = set() while keys: frontier.add(keys.pop()) while frontier: component = frontier.pop() seen.add(component) frontier |= set([d for d in get_dependencies(component) if d in graph]) frontier |= set([d for d in get_dependents(component) if d in graph]) frontier -= seen yield dict((s, get_dependencies(s)) for s in seen) keys -= seen seen.clear()
python
def get_subgraphs(graph=None): """ Given a graph of possibly disconnected components, generate all graphs of connected components. graph is a dictionary of dependencies. Keys are components, and values are sets of components on which they depend. """ graph = graph or DEPENDENCIES keys = set(graph) frontier = set() seen = set() while keys: frontier.add(keys.pop()) while frontier: component = frontier.pop() seen.add(component) frontier |= set([d for d in get_dependencies(component) if d in graph]) frontier |= set([d for d in get_dependents(component) if d in graph]) frontier -= seen yield dict((s, get_dependencies(s)) for s in seen) keys -= seen seen.clear()
[ "def", "get_subgraphs", "(", "graph", "=", "None", ")", ":", "graph", "=", "graph", "or", "DEPENDENCIES", "keys", "=", "set", "(", "graph", ")", "frontier", "=", "set", "(", ")", "seen", "=", "set", "(", ")", "while", "keys", ":", "frontier", ".", ...
Given a graph of possibly disconnected components, generate all graphs of connected components. graph is a dictionary of dependencies. Keys are components, and values are sets of components on which they depend.
[ "Given", "a", "graph", "of", "possibly", "disconnected", "components", "generate", "all", "graphs", "of", "connected", "components", ".", "graph", "is", "a", "dictionary", "of", "dependencies", ".", "Keys", "are", "components", "and", "values", "are", "sets", ...
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L352-L372
train
220,733
RedHatInsights/insights-core
insights/core/dr.py
load_components
def load_components(*paths, **kwargs): """ Loads all components on the paths. Each path should be a package or module. All components beneath a path are loaded. Args: paths (str): A package or module to load Keyword Args: include (str): A regular expression of packages and modules to include. Defaults to '.*' exclude (str): A regular expression of packges and modules to exclude. Defaults to 'test' continue_on_error (bool): If True, continue importing even if something raises an ImportError. If False, raise the first ImportError. Returns: int: The total number of modules loaded. Raises: ImportError """ num_loaded = 0 for path in paths: num_loaded += _load_components(path, **kwargs) return num_loaded
python
def load_components(*paths, **kwargs): """ Loads all components on the paths. Each path should be a package or module. All components beneath a path are loaded. Args: paths (str): A package or module to load Keyword Args: include (str): A regular expression of packages and modules to include. Defaults to '.*' exclude (str): A regular expression of packges and modules to exclude. Defaults to 'test' continue_on_error (bool): If True, continue importing even if something raises an ImportError. If False, raise the first ImportError. Returns: int: The total number of modules loaded. Raises: ImportError """ num_loaded = 0 for path in paths: num_loaded += _load_components(path, **kwargs) return num_loaded
[ "def", "load_components", "(", "*", "paths", ",", "*", "*", "kwargs", ")", ":", "num_loaded", "=", "0", "for", "path", "in", "paths", ":", "num_loaded", "+=", "_load_components", "(", "path", ",", "*", "*", "kwargs", ")", "return", "num_loaded" ]
Loads all components on the paths. Each path should be a package or module. All components beneath a path are loaded. Args: paths (str): A package or module to load Keyword Args: include (str): A regular expression of packages and modules to include. Defaults to '.*' exclude (str): A regular expression of packges and modules to exclude. Defaults to 'test' continue_on_error (bool): If True, continue importing even if something raises an ImportError. If False, raise the first ImportError. Returns: int: The total number of modules loaded. Raises: ImportError
[ "Loads", "all", "components", "on", "the", "paths", ".", "Each", "path", "should", "be", "a", "package", "or", "module", ".", "All", "components", "beneath", "a", "path", "are", "loaded", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L418-L443
train
220,734
RedHatInsights/insights-core
insights/core/dr.py
run
def run(components=None, broker=None): """ Executes components in an order that satisfies their dependency relationships. Keyword Args: components: Can be one of a dependency graph, a single component, a component group, or a component type. If it's anything other than a dependency graph, the appropriate graph is built for you and before evaluation. broker (Broker): Optionally pass a broker to use for evaluation. One is created by default, but it's often useful to seed a broker with an initial dependency. Returns: Broker: The broker after evaluation. """ components = components or COMPONENTS[GROUPS.single] components = _determine_components(components) broker = broker or Broker() for component in run_order(components): start = time.time() try: if component not in broker and component in DELEGATES and is_enabled(component): log.info("Trying %s" % get_name(component)) result = DELEGATES[component].process(broker) broker[component] = result except MissingRequirements as mr: if log.isEnabledFor(logging.DEBUG): name = get_name(component) reqs = stringify_requirements(mr.requirements) log.debug("%s missing requirements %s" % (name, reqs)) broker.add_exception(component, mr) except SkipComponent: pass except Exception as ex: tb = traceback.format_exc() log.warn(tb) broker.add_exception(component, ex, tb) finally: broker.exec_times[component] = time.time() - start broker.fire_observers(component) return broker
python
def run(components=None, broker=None): """ Executes components in an order that satisfies their dependency relationships. Keyword Args: components: Can be one of a dependency graph, a single component, a component group, or a component type. If it's anything other than a dependency graph, the appropriate graph is built for you and before evaluation. broker (Broker): Optionally pass a broker to use for evaluation. One is created by default, but it's often useful to seed a broker with an initial dependency. Returns: Broker: The broker after evaluation. """ components = components or COMPONENTS[GROUPS.single] components = _determine_components(components) broker = broker or Broker() for component in run_order(components): start = time.time() try: if component not in broker and component in DELEGATES and is_enabled(component): log.info("Trying %s" % get_name(component)) result = DELEGATES[component].process(broker) broker[component] = result except MissingRequirements as mr: if log.isEnabledFor(logging.DEBUG): name = get_name(component) reqs = stringify_requirements(mr.requirements) log.debug("%s missing requirements %s" % (name, reqs)) broker.add_exception(component, mr) except SkipComponent: pass except Exception as ex: tb = traceback.format_exc() log.warn(tb) broker.add_exception(component, ex, tb) finally: broker.exec_times[component] = time.time() - start broker.fire_observers(component) return broker
[ "def", "run", "(", "components", "=", "None", ",", "broker", "=", "None", ")", ":", "components", "=", "components", "or", "COMPONENTS", "[", "GROUPS", ".", "single", "]", "components", "=", "_determine_components", "(", "components", ")", "broker", "=", "...
Executes components in an order that satisfies their dependency relationships. Keyword Args: components: Can be one of a dependency graph, a single component, a component group, or a component type. If it's anything other than a dependency graph, the appropriate graph is built for you and before evaluation. broker (Broker): Optionally pass a broker to use for evaluation. One is created by default, but it's often useful to seed a broker with an initial dependency. Returns: Broker: The broker after evaluation.
[ "Executes", "components", "in", "an", "order", "that", "satisfies", "their", "dependency", "relationships", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L927-L970
train
220,735
RedHatInsights/insights-core
insights/core/dr.py
run_incremental
def run_incremental(components=None, broker=None): """ Executes components in an order that satisfies their dependency relationships. Disjoint subgraphs are executed one at a time and a broker containing the results for each is yielded. If a broker is passed here, its instances are used to seed the broker used to hold state for each sub graph. Keyword Args: components: Can be one of a dependency graph, a single component, a component group, or a component type. If it's anything other than a dependency graph, the appropriate graph is built for you and before evaluation. broker (Broker): Optionally pass a broker to use for evaluation. One is created by default, but it's often useful to seed a broker with an initial dependency. Yields: Broker: the broker used to evaluate each subgraph. """ for graph, _broker in generate_incremental(components, broker): yield run(graph, broker=_broker)
python
def run_incremental(components=None, broker=None): """ Executes components in an order that satisfies their dependency relationships. Disjoint subgraphs are executed one at a time and a broker containing the results for each is yielded. If a broker is passed here, its instances are used to seed the broker used to hold state for each sub graph. Keyword Args: components: Can be one of a dependency graph, a single component, a component group, or a component type. If it's anything other than a dependency graph, the appropriate graph is built for you and before evaluation. broker (Broker): Optionally pass a broker to use for evaluation. One is created by default, but it's often useful to seed a broker with an initial dependency. Yields: Broker: the broker used to evaluate each subgraph. """ for graph, _broker in generate_incremental(components, broker): yield run(graph, broker=_broker)
[ "def", "run_incremental", "(", "components", "=", "None", ",", "broker", "=", "None", ")", ":", "for", "graph", ",", "_broker", "in", "generate_incremental", "(", "components", ",", "broker", ")", ":", "yield", "run", "(", "graph", ",", "broker", "=", "_...
Executes components in an order that satisfies their dependency relationships. Disjoint subgraphs are executed one at a time and a broker containing the results for each is yielded. If a broker is passed here, its instances are used to seed the broker used to hold state for each sub graph. Keyword Args: components: Can be one of a dependency graph, a single component, a component group, or a component type. If it's anything other than a dependency graph, the appropriate graph is built for you and before evaluation. broker (Broker): Optionally pass a broker to use for evaluation. One is created by default, but it's often useful to seed a broker with an initial dependency. Yields: Broker: the broker used to evaluate each subgraph.
[ "Executes", "components", "in", "an", "order", "that", "satisfies", "their", "dependency", "relationships", ".", "Disjoint", "subgraphs", "are", "executed", "one", "at", "a", "time", "and", "a", "broker", "containing", "the", "results", "for", "each", "is", "y...
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L982-L1002
train
220,736
RedHatInsights/insights-core
insights/core/dr.py
ComponentType.invoke
def invoke(self, results): """ Handles invocation of the component. The default implementation invokes it with positional arguments based on order of dependency declaration. """ args = [results.get(d) for d in self.deps] return self.component(*args)
python
def invoke(self, results): """ Handles invocation of the component. The default implementation invokes it with positional arguments based on order of dependency declaration. """ args = [results.get(d) for d in self.deps] return self.component(*args)
[ "def", "invoke", "(", "self", ",", "results", ")", ":", "args", "=", "[", "results", ".", "get", "(", "d", ")", "for", "d", "in", "self", ".", "deps", "]", "return", "self", ".", "component", "(", "*", "args", ")" ]
Handles invocation of the component. The default implementation invokes it with positional arguments based on order of dependency declaration.
[ "Handles", "invocation", "of", "the", "component", ".", "The", "default", "implementation", "invokes", "it", "with", "positional", "arguments", "based", "on", "order", "of", "dependency", "declaration", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L647-L653
train
220,737
RedHatInsights/insights-core
insights/core/dr.py
ComponentType.get_missing_dependencies
def get_missing_dependencies(self, broker): """ Gets required and at-least-one dependencies not provided by the broker. """ missing_required = [r for r in self.requires if r not in broker] missing_at_least_one = [d for d in self.at_least_one if not set(d).intersection(broker)] if missing_required or missing_at_least_one: return (missing_required, missing_at_least_one)
python
def get_missing_dependencies(self, broker): """ Gets required and at-least-one dependencies not provided by the broker. """ missing_required = [r for r in self.requires if r not in broker] missing_at_least_one = [d for d in self.at_least_one if not set(d).intersection(broker)] if missing_required or missing_at_least_one: return (missing_required, missing_at_least_one)
[ "def", "get_missing_dependencies", "(", "self", ",", "broker", ")", ":", "missing_required", "=", "[", "r", "for", "r", "in", "self", ".", "requires", "if", "r", "not", "in", "broker", "]", "missing_at_least_one", "=", "[", "d", "for", "d", "in", "self",...
Gets required and at-least-one dependencies not provided by the broker.
[ "Gets", "required", "and", "at", "-", "least", "-", "one", "dependencies", "not", "provided", "by", "the", "broker", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L655-L662
train
220,738
RedHatInsights/insights-core
insights/core/dr.py
Broker.observer
def observer(self, component_type=ComponentType): """ You can use ``@broker.observer()`` as a decorator to your callback instead of :func:`Broker.add_observer`. """ def inner(func): self.add_observer(func, component_type) return func return inner
python
def observer(self, component_type=ComponentType): """ You can use ``@broker.observer()`` as a decorator to your callback instead of :func:`Broker.add_observer`. """ def inner(func): self.add_observer(func, component_type) return func return inner
[ "def", "observer", "(", "self", ",", "component_type", "=", "ComponentType", ")", ":", "def", "inner", "(", "func", ")", ":", "self", ".", "add_observer", "(", "func", ",", "component_type", ")", "return", "func", "return", "inner" ]
You can use ``@broker.observer()`` as a decorator to your callback instead of :func:`Broker.add_observer`.
[ "You", "can", "use" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L735-L743
train
220,739
RedHatInsights/insights-core
insights/core/dr.py
Broker.add_observer
def add_observer(self, o, component_type=ComponentType): """ Add a callback that will get invoked after each component is called. Args: o (func): the callback function Keyword Args: component_type (ComponentType): the :class:`ComponentType` to observe. The callback will fire any time an instance of the class or its subclasses is invoked. The callback should look like this: .. code-block:: python def callback(comp, broker): value = broker.get(comp) # do something with value pass """ self.observers[component_type].add(o)
python
def add_observer(self, o, component_type=ComponentType): """ Add a callback that will get invoked after each component is called. Args: o (func): the callback function Keyword Args: component_type (ComponentType): the :class:`ComponentType` to observe. The callback will fire any time an instance of the class or its subclasses is invoked. The callback should look like this: .. code-block:: python def callback(comp, broker): value = broker.get(comp) # do something with value pass """ self.observers[component_type].add(o)
[ "def", "add_observer", "(", "self", ",", "o", ",", "component_type", "=", "ComponentType", ")", ":", "self", ".", "observers", "[", "component_type", "]", ".", "add", "(", "o", ")" ]
Add a callback that will get invoked after each component is called. Args: o (func): the callback function Keyword Args: component_type (ComponentType): the :class:`ComponentType` to observe. The callback will fire any time an instance of the class or its subclasses is invoked. The callback should look like this: .. code-block:: python def callback(comp, broker): value = broker.get(comp) # do something with value pass
[ "Add", "a", "callback", "that", "will", "get", "invoked", "after", "each", "component", "is", "called", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/dr.py#L745-L767
train
220,740
RedHatInsights/insights-core
insights/combiners/logrotate_conf.py
get_tree
def get_tree(root=None): """ This is a helper function to get a logrotate configuration component for your local machine or an archive. It's for use in interactive sessions. """ from insights import run return run(LogRotateConfTree, root=root).get(LogRotateConfTree)
python
def get_tree(root=None): """ This is a helper function to get a logrotate configuration component for your local machine or an archive. It's for use in interactive sessions. """ from insights import run return run(LogRotateConfTree, root=root).get(LogRotateConfTree)
[ "def", "get_tree", "(", "root", "=", "None", ")", ":", "from", "insights", "import", "run", "return", "run", "(", "LogRotateConfTree", ",", "root", "=", "root", ")", ".", "get", "(", "LogRotateConfTree", ")" ]
This is a helper function to get a logrotate configuration component for your local machine or an archive. It's for use in interactive sessions.
[ "This", "is", "a", "helper", "function", "to", "get", "a", "logrotate", "configuration", "component", "for", "your", "local", "machine", "or", "an", "archive", ".", "It", "s", "for", "use", "in", "interactive", "sessions", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/combiners/logrotate_conf.py#L231-L237
train
220,741
RedHatInsights/insights-core
insights/formats/_syslog.py
SysLogFormat.logit
def logit(self, msg, pid, user, cname, priority=None): """Function for formatting content and logging to syslog""" if self.stream: print(msg, file=self.stream) elif priority == logging.WARNING: self.logger.warning("{0}[pid:{1}] user:{2}: WARNING - {3}".format(cname, pid, user, msg)) elif priority == logging.ERROR: self.logger.error("{0}[pid:{1}] user:{2}: ERROR - {3}".format(cname, pid, user, msg)) else: self.logger.info("{0}[pid:{1}] user:{2}: INFO - {3}".format(cname, pid, user, msg))
python
def logit(self, msg, pid, user, cname, priority=None): """Function for formatting content and logging to syslog""" if self.stream: print(msg, file=self.stream) elif priority == logging.WARNING: self.logger.warning("{0}[pid:{1}] user:{2}: WARNING - {3}".format(cname, pid, user, msg)) elif priority == logging.ERROR: self.logger.error("{0}[pid:{1}] user:{2}: ERROR - {3}".format(cname, pid, user, msg)) else: self.logger.info("{0}[pid:{1}] user:{2}: INFO - {3}".format(cname, pid, user, msg))
[ "def", "logit", "(", "self", ",", "msg", ",", "pid", ",", "user", ",", "cname", ",", "priority", "=", "None", ")", ":", "if", "self", ".", "stream", ":", "print", "(", "msg", ",", "file", "=", "self", ".", "stream", ")", "elif", "priority", "==",...
Function for formatting content and logging to syslog
[ "Function", "for", "formatting", "content", "and", "logging", "to", "syslog" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/formats/_syslog.py#L45-L55
train
220,742
RedHatInsights/insights-core
insights/formats/_syslog.py
SysLogFormat.log_exceptions
def log_exceptions(self, c, broker): """Gets exceptions to be logged and sends to logit function to be logged to syslog""" if c in broker.exceptions: ex = broker.exceptions.get(c) ex = "Exception in {0} - {1}".format(dr.get_name(c), str(ex)) self.logit(ex, self.pid, self.user, "insights-run", logging.ERROR)
python
def log_exceptions(self, c, broker): """Gets exceptions to be logged and sends to logit function to be logged to syslog""" if c in broker.exceptions: ex = broker.exceptions.get(c) ex = "Exception in {0} - {1}".format(dr.get_name(c), str(ex)) self.logit(ex, self.pid, self.user, "insights-run", logging.ERROR)
[ "def", "log_exceptions", "(", "self", ",", "c", ",", "broker", ")", ":", "if", "c", "in", "broker", ".", "exceptions", ":", "ex", "=", "broker", ".", "exceptions", ".", "get", "(", "c", ")", "ex", "=", "\"Exception in {0} - {1}\"", ".", "format", "(", ...
Gets exceptions to be logged and sends to logit function to be logged to syslog
[ "Gets", "exceptions", "to", "be", "logged", "and", "sends", "to", "logit", "function", "to", "be", "logged", "to", "syslog" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/formats/_syslog.py#L57-L63
train
220,743
RedHatInsights/insights-core
insights/formats/_syslog.py
SysLogFormat.log_rule_info
def log_rule_info(self): """Collects rule information and send to logit function to log to syslog""" for c in sorted(self.broker.get_by_type(rule), key=dr.get_name): v = self.broker[c] _type = v.get("type") if _type: if _type != "skip": msg = "Running {0} ".format(dr.get_name(c)) self.logit(msg, self.pid, self.user, "insights-run", logging.INFO) else: msg = "Rule skipped {0} ".format(dr.get_name(c)) self.logit(msg, self.pid, self.user, "insights-run", logging.WARNING)
python
def log_rule_info(self): """Collects rule information and send to logit function to log to syslog""" for c in sorted(self.broker.get_by_type(rule), key=dr.get_name): v = self.broker[c] _type = v.get("type") if _type: if _type != "skip": msg = "Running {0} ".format(dr.get_name(c)) self.logit(msg, self.pid, self.user, "insights-run", logging.INFO) else: msg = "Rule skipped {0} ".format(dr.get_name(c)) self.logit(msg, self.pid, self.user, "insights-run", logging.WARNING)
[ "def", "log_rule_info", "(", "self", ")", ":", "for", "c", "in", "sorted", "(", "self", ".", "broker", ".", "get_by_type", "(", "rule", ")", ",", "key", "=", "dr", ".", "get_name", ")", ":", "v", "=", "self", ".", "broker", "[", "c", "]", "_type"...
Collects rule information and send to logit function to log to syslog
[ "Collects", "rule", "information", "and", "send", "to", "logit", "function", "to", "log", "to", "syslog" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/formats/_syslog.py#L72-L84
train
220,744
RedHatInsights/insights-core
insights/client/data_collector.py
DataCollector._run_pre_command
def _run_pre_command(self, pre_cmd): ''' Run a pre command to get external args for a command ''' logger.debug('Executing pre-command: %s', pre_cmd) try: pre_proc = Popen(pre_cmd, stdout=PIPE, stderr=STDOUT, shell=True) except OSError as err: if err.errno == errno.ENOENT: logger.debug('Command %s not found', pre_cmd) return stdout, stderr = pre_proc.communicate() the_return_code = pre_proc.poll() logger.debug("Pre-command results:") logger.debug("STDOUT: %s", stdout) logger.debug("STDERR: %s", stderr) logger.debug("Return Code: %s", the_return_code) if the_return_code != 0: return [] if six.PY3: stdout = stdout.decode('utf-8') return stdout.splitlines()
python
def _run_pre_command(self, pre_cmd): ''' Run a pre command to get external args for a command ''' logger.debug('Executing pre-command: %s', pre_cmd) try: pre_proc = Popen(pre_cmd, stdout=PIPE, stderr=STDOUT, shell=True) except OSError as err: if err.errno == errno.ENOENT: logger.debug('Command %s not found', pre_cmd) return stdout, stderr = pre_proc.communicate() the_return_code = pre_proc.poll() logger.debug("Pre-command results:") logger.debug("STDOUT: %s", stdout) logger.debug("STDERR: %s", stderr) logger.debug("Return Code: %s", the_return_code) if the_return_code != 0: return [] if six.PY3: stdout = stdout.decode('utf-8') return stdout.splitlines()
[ "def", "_run_pre_command", "(", "self", ",", "pre_cmd", ")", ":", "logger", ".", "debug", "(", "'Executing pre-command: %s'", ",", "pre_cmd", ")", "try", ":", "pre_proc", "=", "Popen", "(", "pre_cmd", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "STDOUT...
Run a pre command to get external args for a command
[ "Run", "a", "pre", "command", "to", "get", "external", "args", "for", "a", "command" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/data_collector.py#L51-L72
train
220,745
RedHatInsights/insights-core
insights/client/data_collector.py
DataCollector._parse_file_spec
def _parse_file_spec(self, spec): ''' Separate wildcard specs into more specs ''' # separate wildcard specs into more specs if '*' in spec['file']: expanded_paths = _expand_paths(spec['file']) if not expanded_paths: return [] expanded_specs = [] for p in expanded_paths: _spec = copy.copy(spec) _spec['file'] = p expanded_specs.append(_spec) return expanded_specs else: return [spec]
python
def _parse_file_spec(self, spec): ''' Separate wildcard specs into more specs ''' # separate wildcard specs into more specs if '*' in spec['file']: expanded_paths = _expand_paths(spec['file']) if not expanded_paths: return [] expanded_specs = [] for p in expanded_paths: _spec = copy.copy(spec) _spec['file'] = p expanded_specs.append(_spec) return expanded_specs else: return [spec]
[ "def", "_parse_file_spec", "(", "self", ",", "spec", ")", ":", "# separate wildcard specs into more specs", "if", "'*'", "in", "spec", "[", "'file'", "]", ":", "expanded_paths", "=", "_expand_paths", "(", "spec", "[", "'file'", "]", ")", "if", "not", "expanded...
Separate wildcard specs into more specs
[ "Separate", "wildcard", "specs", "into", "more", "specs" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/data_collector.py#L74-L91
train
220,746
RedHatInsights/insights-core
insights/client/data_collector.py
DataCollector._parse_glob_spec
def _parse_glob_spec(self, spec): ''' Grab globs of things ''' some_globs = glob.glob(spec['glob']) if not some_globs: return [] el_globs = [] for g in some_globs: _spec = copy.copy(spec) _spec['file'] = g el_globs.append(_spec) return el_globs
python
def _parse_glob_spec(self, spec): ''' Grab globs of things ''' some_globs = glob.glob(spec['glob']) if not some_globs: return [] el_globs = [] for g in some_globs: _spec = copy.copy(spec) _spec['file'] = g el_globs.append(_spec) return el_globs
[ "def", "_parse_glob_spec", "(", "self", ",", "spec", ")", ":", "some_globs", "=", "glob", ".", "glob", "(", "spec", "[", "'glob'", "]", ")", "if", "not", "some_globs", ":", "return", "[", "]", "el_globs", "=", "[", "]", "for", "g", "in", "some_globs"...
Grab globs of things
[ "Grab", "globs", "of", "things" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/data_collector.py#L93-L105
train
220,747
RedHatInsights/insights-core
insights/client/data_collector.py
DataCollector.run_collection
def run_collection(self, conf, rm_conf, branch_info): ''' Run specs and collect all the data ''' if rm_conf is None: rm_conf = {} logger.debug('Beginning to run collection spec...') exclude = None if rm_conf: try: exclude = rm_conf['patterns'] logger.warn("WARNING: Skipping patterns found in remove.conf") except LookupError: logger.debug('Patterns section of remove.conf is empty.') for c in conf['commands']: # remember hostname archive path if c.get('symbolic_name') == 'hostname': self.hostname_path = os.path.join( 'insights_commands', mangle.mangle_command(c['command'])) rm_commands = rm_conf.get('commands', []) if c['command'] in rm_commands or c.get('symbolic_name') in rm_commands: logger.warn("WARNING: Skipping command %s", c['command']) elif self.mountpoint == "/" or c.get("image"): cmd_specs = self._parse_command_spec(c, conf['pre_commands']) for s in cmd_specs: cmd_spec = InsightsCommand(self.config, s, exclude, self.mountpoint) self.archive.add_to_archive(cmd_spec) for f in conf['files']: rm_files = rm_conf.get('files', []) if f['file'] in rm_files or f.get('symbolic_name') in rm_files: logger.warn("WARNING: Skipping file %s", f['file']) else: file_specs = self._parse_file_spec(f) for s in file_specs: # filter files post-wildcard parsing if s['file'] in rm_conf.get('files', []): logger.warn("WARNING: Skipping file %s", s['file']) else: file_spec = InsightsFile(s, exclude, self.mountpoint) self.archive.add_to_archive(file_spec) if 'globs' in conf: for g in conf['globs']: glob_specs = self._parse_glob_spec(g) for g in glob_specs: if g['file'] in rm_conf.get('files', []): logger.warn("WARNING: Skipping file %s", g) else: glob_spec = InsightsFile(g, exclude, self.mountpoint) self.archive.add_to_archive(glob_spec) logger.debug('Spec collection finished.') # collect metadata logger.debug('Collecting metadata...') self._write_branch_info(branch_info) logger.debug('Metadata collection finished.')
python
def run_collection(self, conf, rm_conf, branch_info): ''' Run specs and collect all the data ''' if rm_conf is None: rm_conf = {} logger.debug('Beginning to run collection spec...') exclude = None if rm_conf: try: exclude = rm_conf['patterns'] logger.warn("WARNING: Skipping patterns found in remove.conf") except LookupError: logger.debug('Patterns section of remove.conf is empty.') for c in conf['commands']: # remember hostname archive path if c.get('symbolic_name') == 'hostname': self.hostname_path = os.path.join( 'insights_commands', mangle.mangle_command(c['command'])) rm_commands = rm_conf.get('commands', []) if c['command'] in rm_commands or c.get('symbolic_name') in rm_commands: logger.warn("WARNING: Skipping command %s", c['command']) elif self.mountpoint == "/" or c.get("image"): cmd_specs = self._parse_command_spec(c, conf['pre_commands']) for s in cmd_specs: cmd_spec = InsightsCommand(self.config, s, exclude, self.mountpoint) self.archive.add_to_archive(cmd_spec) for f in conf['files']: rm_files = rm_conf.get('files', []) if f['file'] in rm_files or f.get('symbolic_name') in rm_files: logger.warn("WARNING: Skipping file %s", f['file']) else: file_specs = self._parse_file_spec(f) for s in file_specs: # filter files post-wildcard parsing if s['file'] in rm_conf.get('files', []): logger.warn("WARNING: Skipping file %s", s['file']) else: file_spec = InsightsFile(s, exclude, self.mountpoint) self.archive.add_to_archive(file_spec) if 'globs' in conf: for g in conf['globs']: glob_specs = self._parse_glob_spec(g) for g in glob_specs: if g['file'] in rm_conf.get('files', []): logger.warn("WARNING: Skipping file %s", g) else: glob_spec = InsightsFile(g, exclude, self.mountpoint) self.archive.add_to_archive(glob_spec) logger.debug('Spec collection finished.') # collect metadata logger.debug('Collecting metadata...') self._write_branch_info(branch_info) logger.debug('Metadata collection finished.')
[ "def", "run_collection", "(", "self", ",", "conf", ",", "rm_conf", ",", "branch_info", ")", ":", "if", "rm_conf", "is", "None", ":", "rm_conf", "=", "{", "}", "logger", ".", "debug", "(", "'Beginning to run collection spec...'", ")", "exclude", "=", "None", ...
Run specs and collect all the data
[ "Run", "specs", "and", "collect", "all", "the", "data" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/data_collector.py#L148-L203
train
220,748
RedHatInsights/insights-core
insights/client/data_collector.py
DataCollector.done
def done(self, conf, rm_conf): """ Do finalization stuff """ if self.config.obfuscate: cleaner = SOSCleaner(quiet=True) clean_opts = CleanOptions( self.config, self.archive.tmp_dir, rm_conf, self.hostname_path) fresh = cleaner.clean_report(clean_opts, self.archive.archive_dir) if clean_opts.keyword_file is not None: os.remove(clean_opts.keyword_file.name) logger.warn("WARNING: Skipping keywords found in remove.conf") return fresh[0] return self.archive.create_tar_file()
python
def done(self, conf, rm_conf): """ Do finalization stuff """ if self.config.obfuscate: cleaner = SOSCleaner(quiet=True) clean_opts = CleanOptions( self.config, self.archive.tmp_dir, rm_conf, self.hostname_path) fresh = cleaner.clean_report(clean_opts, self.archive.archive_dir) if clean_opts.keyword_file is not None: os.remove(clean_opts.keyword_file.name) logger.warn("WARNING: Skipping keywords found in remove.conf") return fresh[0] return self.archive.create_tar_file()
[ "def", "done", "(", "self", ",", "conf", ",", "rm_conf", ")", ":", "if", "self", ".", "config", ".", "obfuscate", ":", "cleaner", "=", "SOSCleaner", "(", "quiet", "=", "True", ")", "clean_opts", "=", "CleanOptions", "(", "self", ".", "config", ",", "...
Do finalization stuff
[ "Do", "finalization", "stuff" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/data_collector.py#L205-L218
train
220,749
RedHatInsights/insights-core
insights/specs/default.py
DefaultSpecs.sap_sid_nr
def sap_sid_nr(broker): """ Get the SID and Instance Number Typical output of saphostctrl_listinstances:: # /usr/sap/hostctrl/exe/saphostctrl -function ListInstances Inst Info : SR1 - 01 - liuxc-rhel7-hana-ent - 749, patch 418, changelist 1816226 Returns: (list): List of tuple of SID and Instance Number. """ insts = broker[DefaultSpecs.saphostctrl_listinstances].content hn = broker[DefaultSpecs.hostname].content[0].split('.')[0].strip() results = set() for ins in insts: ins_splits = ins.split(' - ') # Local Instance if ins_splits[2].strip() == hn: # (sid, nr) results.add((ins_splits[0].split()[-1].lower(), ins_splits[1].strip())) return list(results)
python
def sap_sid_nr(broker): """ Get the SID and Instance Number Typical output of saphostctrl_listinstances:: # /usr/sap/hostctrl/exe/saphostctrl -function ListInstances Inst Info : SR1 - 01 - liuxc-rhel7-hana-ent - 749, patch 418, changelist 1816226 Returns: (list): List of tuple of SID and Instance Number. """ insts = broker[DefaultSpecs.saphostctrl_listinstances].content hn = broker[DefaultSpecs.hostname].content[0].split('.')[0].strip() results = set() for ins in insts: ins_splits = ins.split(' - ') # Local Instance if ins_splits[2].strip() == hn: # (sid, nr) results.add((ins_splits[0].split()[-1].lower(), ins_splits[1].strip())) return list(results)
[ "def", "sap_sid_nr", "(", "broker", ")", ":", "insts", "=", "broker", "[", "DefaultSpecs", ".", "saphostctrl_listinstances", "]", ".", "content", "hn", "=", "broker", "[", "DefaultSpecs", ".", "hostname", "]", ".", "content", "[", "0", "]", ".", "split", ...
Get the SID and Instance Number Typical output of saphostctrl_listinstances:: # /usr/sap/hostctrl/exe/saphostctrl -function ListInstances Inst Info : SR1 - 01 - liuxc-rhel7-hana-ent - 749, patch 418, changelist 1816226 Returns: (list): List of tuple of SID and Instance Number.
[ "Get", "the", "SID", "and", "Instance", "Number" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/specs/default.py#L724-L745
train
220,750
RedHatInsights/insights-core
insights/util/file_permissions.py
FilePermissions.from_dict
def from_dict(self, dirent): """ Create a new FilePermissions object from the given dictionary. This works with the FileListing parser class, which has already done the hard work of pulling many of these fields out. We create an object with all the dictionary keys available as properties, and also split the ``perms`` string up into owner, group """ # Check that we have at least as much data as the __init__ requires for k in ['perms', 'owner', 'group', 'name', 'dir']: if k not in dirent: raise ValueError("Need required key '{k}'".format(k=k)) # Copy all values across for k in dirent: setattr(self, k, dirent[k]) # Create perms parts self.perms_owner = self.perms[0:3] self.perms_group = self.perms[3:6] self.perms_other = self.perms[6:9] return self
python
def from_dict(self, dirent): """ Create a new FilePermissions object from the given dictionary. This works with the FileListing parser class, which has already done the hard work of pulling many of these fields out. We create an object with all the dictionary keys available as properties, and also split the ``perms`` string up into owner, group """ # Check that we have at least as much data as the __init__ requires for k in ['perms', 'owner', 'group', 'name', 'dir']: if k not in dirent: raise ValueError("Need required key '{k}'".format(k=k)) # Copy all values across for k in dirent: setattr(self, k, dirent[k]) # Create perms parts self.perms_owner = self.perms[0:3] self.perms_group = self.perms[3:6] self.perms_other = self.perms[6:9] return self
[ "def", "from_dict", "(", "self", ",", "dirent", ")", ":", "# Check that we have at least as much data as the __init__ requires", "for", "k", "in", "[", "'perms'", ",", "'owner'", ",", "'group'", ",", "'name'", ",", "'dir'", "]", ":", "if", "k", "not", "in", "d...
Create a new FilePermissions object from the given dictionary. This works with the FileListing parser class, which has already done the hard work of pulling many of these fields out. We create an object with all the dictionary keys available as properties, and also split the ``perms`` string up into owner, group
[ "Create", "a", "new", "FilePermissions", "object", "from", "the", "given", "dictionary", ".", "This", "works", "with", "the", "FileListing", "parser", "class", "which", "has", "already", "done", "the", "hard", "work", "of", "pulling", "many", "of", "these", ...
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/util/file_permissions.py#L88-L107
train
220,751
RedHatInsights/insights-core
insights/util/file_permissions.py
FilePermissions.owned_by
def owned_by(self, owner, also_check_group=False): """ Checks if the specified user or user and group own the file. Args: owner (str): the user (or group) name for which we ask about ownership also_check_group (bool): if set to True, both user owner and group owner checked if set to False, only user owner checked Returns: bool: True if owner of the file is the specified owner """ if also_check_group: return self.owner == owner and self.group == owner else: return self.owner == owner
python
def owned_by(self, owner, also_check_group=False): """ Checks if the specified user or user and group own the file. Args: owner (str): the user (or group) name for which we ask about ownership also_check_group (bool): if set to True, both user owner and group owner checked if set to False, only user owner checked Returns: bool: True if owner of the file is the specified owner """ if also_check_group: return self.owner == owner and self.group == owner else: return self.owner == owner
[ "def", "owned_by", "(", "self", ",", "owner", ",", "also_check_group", "=", "False", ")", ":", "if", "also_check_group", ":", "return", "self", ".", "owner", "==", "owner", "and", "self", ".", "group", "==", "owner", "else", ":", "return", "self", ".", ...
Checks if the specified user or user and group own the file. Args: owner (str): the user (or group) name for which we ask about ownership also_check_group (bool): if set to True, both user owner and group owner checked if set to False, only user owner checked Returns: bool: True if owner of the file is the specified owner
[ "Checks", "if", "the", "specified", "user", "or", "user", "and", "group", "own", "the", "file", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/util/file_permissions.py#L109-L124
train
220,752
RedHatInsights/insights-core
insights/parsers/multipath_conf.py
get_tree
def get_tree(root=None): """ This is a helper function to get a multipath configuration component for your local machine or an archive. It's for use in interactive sessions. """ from insights import run return run(MultipathConfTree, root=root).get(MultipathConfTree)
python
def get_tree(root=None): """ This is a helper function to get a multipath configuration component for your local machine or an archive. It's for use in interactive sessions. """ from insights import run return run(MultipathConfTree, root=root).get(MultipathConfTree)
[ "def", "get_tree", "(", "root", "=", "None", ")", ":", "from", "insights", "import", "run", "return", "run", "(", "MultipathConfTree", ",", "root", "=", "root", ")", ".", "get", "(", "MultipathConfTree", ")" ]
This is a helper function to get a multipath configuration component for your local machine or an archive. It's for use in interactive sessions.
[ "This", "is", "a", "helper", "function", "to", "get", "a", "multipath", "configuration", "component", "for", "your", "local", "machine", "or", "an", "archive", ".", "It", "s", "for", "use", "in", "interactive", "sessions", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/multipath_conf.py#L188-L194
train
220,753
RedHatInsights/insights-core
insights/client/support.py
InsightsSupport._support_diag_dump
def _support_diag_dump(self): ''' Collect log info for debug ''' # check insights config cfg_block = [] pconn = InsightsConnection(self.config) logger.info('Insights version: %s', get_nvr()) reg_check = registration_check(pconn) cfg_block.append('Registration check:') for key in reg_check: cfg_block.append(key + ': ' + str(reg_check[key])) lastupload = 'never' if os.path.isfile(constants.lastupload_file): with open(constants.lastupload_file) as upl_file: lastupload = upl_file.readline().strip() cfg_block.append('\nLast successful upload was ' + lastupload) cfg_block.append('auto_config: ' + str(self.config.auto_config)) if self.config.proxy: obfuscated_proxy = re.sub(r'(.*)(:)(.*)(@.*)', r'\1\2********\4', self.config.proxy) else: obfuscated_proxy = 'None' cfg_block.append('proxy: ' + obfuscated_proxy) logger.info('\n'.join(cfg_block)) logger.info('python-requests: %s', requests.__version__) succ = pconn.test_connection() if succ == 0: logger.info('Connection test: PASS\n') else: logger.info('Connection test: FAIL\n') # run commands commands = ['uname -a', 'cat /etc/redhat-release', 'env', 'sestatus', 'subscription-manager identity', 'systemctl cat insights-client.timer', 'systemctl cat insights-client.service', 'systemctl status insights-client.timer', 'systemctl status insights-client.service'] for cmd in commands: logger.info("Running command: %s", cmd) try: proc = Popen( shlex.split(cmd), shell=False, stdout=PIPE, stderr=STDOUT, close_fds=True) stdout, stderr = proc.communicate() except OSError as o: if 'systemctl' not in cmd: # suppress output for systemctl cmd failures logger.info('Error running command "%s": %s', cmd, o) except Exception as e: # unknown error logger.info("Process failed: %s", e) logger.info("Process output: \n%s", stdout) # check available disk space for /var/tmp tmp_dir = '/var/tmp' dest_dir_stat = os.statvfs(tmp_dir) dest_dir_size = (dest_dir_stat.f_bavail * dest_dir_stat.f_frsize) logger.info('Available space in %s:\t%s bytes\t%.1f 1K-blocks\t%.1f MB', tmp_dir, dest_dir_size, dest_dir_size / 1024.0, (dest_dir_size / 1024.0) / 1024.0)
python
def _support_diag_dump(self): ''' Collect log info for debug ''' # check insights config cfg_block = [] pconn = InsightsConnection(self.config) logger.info('Insights version: %s', get_nvr()) reg_check = registration_check(pconn) cfg_block.append('Registration check:') for key in reg_check: cfg_block.append(key + ': ' + str(reg_check[key])) lastupload = 'never' if os.path.isfile(constants.lastupload_file): with open(constants.lastupload_file) as upl_file: lastupload = upl_file.readline().strip() cfg_block.append('\nLast successful upload was ' + lastupload) cfg_block.append('auto_config: ' + str(self.config.auto_config)) if self.config.proxy: obfuscated_proxy = re.sub(r'(.*)(:)(.*)(@.*)', r'\1\2********\4', self.config.proxy) else: obfuscated_proxy = 'None' cfg_block.append('proxy: ' + obfuscated_proxy) logger.info('\n'.join(cfg_block)) logger.info('python-requests: %s', requests.__version__) succ = pconn.test_connection() if succ == 0: logger.info('Connection test: PASS\n') else: logger.info('Connection test: FAIL\n') # run commands commands = ['uname -a', 'cat /etc/redhat-release', 'env', 'sestatus', 'subscription-manager identity', 'systemctl cat insights-client.timer', 'systemctl cat insights-client.service', 'systemctl status insights-client.timer', 'systemctl status insights-client.service'] for cmd in commands: logger.info("Running command: %s", cmd) try: proc = Popen( shlex.split(cmd), shell=False, stdout=PIPE, stderr=STDOUT, close_fds=True) stdout, stderr = proc.communicate() except OSError as o: if 'systemctl' not in cmd: # suppress output for systemctl cmd failures logger.info('Error running command "%s": %s', cmd, o) except Exception as e: # unknown error logger.info("Process failed: %s", e) logger.info("Process output: \n%s", stdout) # check available disk space for /var/tmp tmp_dir = '/var/tmp' dest_dir_stat = os.statvfs(tmp_dir) dest_dir_size = (dest_dir_stat.f_bavail * dest_dir_stat.f_frsize) logger.info('Available space in %s:\t%s bytes\t%.1f 1K-blocks\t%.1f MB', tmp_dir, dest_dir_size, dest_dir_size / 1024.0, (dest_dir_size / 1024.0) / 1024.0)
[ "def", "_support_diag_dump", "(", "self", ")", ":", "# check insights config", "cfg_block", "=", "[", "]", "pconn", "=", "InsightsConnection", "(", "self", ".", "config", ")", "logger", ".", "info", "(", "'Insights version: %s'", ",", "get_nvr", "(", ")", ")",...
Collect log info for debug
[ "Collect", "log", "info", "for", "debug" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/support.py#L94-L165
train
220,754
RedHatInsights/insights-core
insights/core/filters.py
add_filter
def add_filter(ds, patterns): """ Add a filter or list of filters to a datasource. A filter is a simple string, and it matches if it is contained anywhere within a line. Args: ds (@datasource component): The datasource to filter patterns (str, [str]): A string, list of strings, or set of strings to add to the datasource's filters. """ if not plugins.is_datasource(ds): raise Exception("Filters are applicable only to datasources.") delegate = dr.get_delegate(ds) if delegate.raw: raise Exception("Filters aren't applicable to raw datasources.") if not delegate.filterable: raise Exception("Filters aren't applicable to %s." % dr.get_name(ds)) if ds in _CACHE: del _CACHE[ds] if isinstance(patterns, six.string_types): FILTERS[ds].add(patterns) elif isinstance(patterns, list): FILTERS[ds] |= set(patterns) elif isinstance(patterns, set): FILTERS[ds] |= patterns else: raise TypeError("patterns must be string, list, or set.")
python
def add_filter(ds, patterns): """ Add a filter or list of filters to a datasource. A filter is a simple string, and it matches if it is contained anywhere within a line. Args: ds (@datasource component): The datasource to filter patterns (str, [str]): A string, list of strings, or set of strings to add to the datasource's filters. """ if not plugins.is_datasource(ds): raise Exception("Filters are applicable only to datasources.") delegate = dr.get_delegate(ds) if delegate.raw: raise Exception("Filters aren't applicable to raw datasources.") if not delegate.filterable: raise Exception("Filters aren't applicable to %s." % dr.get_name(ds)) if ds in _CACHE: del _CACHE[ds] if isinstance(patterns, six.string_types): FILTERS[ds].add(patterns) elif isinstance(patterns, list): FILTERS[ds] |= set(patterns) elif isinstance(patterns, set): FILTERS[ds] |= patterns else: raise TypeError("patterns must be string, list, or set.")
[ "def", "add_filter", "(", "ds", ",", "patterns", ")", ":", "if", "not", "plugins", ".", "is_datasource", "(", "ds", ")", ":", "raise", "Exception", "(", "\"Filters are applicable only to datasources.\"", ")", "delegate", "=", "dr", ".", "get_delegate", "(", "d...
Add a filter or list of filters to a datasource. A filter is a simple string, and it matches if it is contained anywhere within a line. Args: ds (@datasource component): The datasource to filter patterns (str, [str]): A string, list of strings, or set of strings to add to the datasource's filters.
[ "Add", "a", "filter", "or", "list", "of", "filters", "to", "a", "datasource", ".", "A", "filter", "is", "a", "simple", "string", "and", "it", "matches", "if", "it", "is", "contained", "anywhere", "within", "a", "line", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/filters.py#L49-L79
train
220,755
RedHatInsights/insights-core
insights/core/filters.py
get_filters
def get_filters(component): """ Get the set of filters for the given datasource. Filters added to a ``RegistryPoint`` will be applied to all datasources that implement it. Filters added to a datasource implementation apply only to that implementation. For example, a filter added to ``Specs.ps_auxww`` will apply to ``DefaultSpecs.ps_auxww``, ``InsightsArchiveSpecs.ps_auxww``, ``SosSpecs.ps_auxww``, etc. But a filter added to ``DefaultSpecs.ps_auxww`` will only apply to ``DefaultSpecs.ps_auxww``. See the modules in ``insights.specs`` for those classes. Args: component (a datasource): The target datasource Returns: set: The set of filters defined for the datasource """ def inner(c, filters=None): filters = filters or set() if not ENABLED: return filters if not plugins.is_datasource(c): return filters if c in FILTERS: filters |= FILTERS[c] for d in dr.get_dependents(c): filters |= inner(d, filters) return filters if component not in _CACHE: _CACHE[component] = inner(component) return _CACHE[component]
python
def get_filters(component): """ Get the set of filters for the given datasource. Filters added to a ``RegistryPoint`` will be applied to all datasources that implement it. Filters added to a datasource implementation apply only to that implementation. For example, a filter added to ``Specs.ps_auxww`` will apply to ``DefaultSpecs.ps_auxww``, ``InsightsArchiveSpecs.ps_auxww``, ``SosSpecs.ps_auxww``, etc. But a filter added to ``DefaultSpecs.ps_auxww`` will only apply to ``DefaultSpecs.ps_auxww``. See the modules in ``insights.specs`` for those classes. Args: component (a datasource): The target datasource Returns: set: The set of filters defined for the datasource """ def inner(c, filters=None): filters = filters or set() if not ENABLED: return filters if not plugins.is_datasource(c): return filters if c in FILTERS: filters |= FILTERS[c] for d in dr.get_dependents(c): filters |= inner(d, filters) return filters if component not in _CACHE: _CACHE[component] = inner(component) return _CACHE[component]
[ "def", "get_filters", "(", "component", ")", ":", "def", "inner", "(", "c", ",", "filters", "=", "None", ")", ":", "filters", "=", "filters", "or", "set", "(", ")", "if", "not", "ENABLED", ":", "return", "filters", "if", "not", "plugins", ".", "is_da...
Get the set of filters for the given datasource. Filters added to a ``RegistryPoint`` will be applied to all datasources that implement it. Filters added to a datasource implementation apply only to that implementation. For example, a filter added to ``Specs.ps_auxww`` will apply to ``DefaultSpecs.ps_auxww``, ``InsightsArchiveSpecs.ps_auxww``, ``SosSpecs.ps_auxww``, etc. But a filter added to ``DefaultSpecs.ps_auxww`` will only apply to ``DefaultSpecs.ps_auxww``. See the modules in ``insights.specs`` for those classes. Args: component (a datasource): The target datasource Returns: set: The set of filters defined for the datasource
[ "Get", "the", "set", "of", "filters", "for", "the", "given", "datasource", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/filters.py#L82-L119
train
220,756
RedHatInsights/insights-core
insights/core/filters.py
apply_filters
def apply_filters(target, lines): """ Applys filters to the lines of a datasource. This function is used only in integration tests. Filters are applied in an equivalent but more performant way at run time. """ filters = get_filters(target) if filters: for l in lines: if any(f in l for f in filters): yield l else: for l in lines: yield l
python
def apply_filters(target, lines): """ Applys filters to the lines of a datasource. This function is used only in integration tests. Filters are applied in an equivalent but more performant way at run time. """ filters = get_filters(target) if filters: for l in lines: if any(f in l for f in filters): yield l else: for l in lines: yield l
[ "def", "apply_filters", "(", "target", ",", "lines", ")", ":", "filters", "=", "get_filters", "(", "target", ")", "if", "filters", ":", "for", "l", "in", "lines", ":", "if", "any", "(", "f", "in", "l", "for", "f", "in", "filters", ")", ":", "yield"...
Applys filters to the lines of a datasource. This function is used only in integration tests. Filters are applied in an equivalent but more performant way at run time.
[ "Applys", "filters", "to", "the", "lines", "of", "a", "datasource", ".", "This", "function", "is", "used", "only", "in", "integration", "tests", ".", "Filters", "are", "applied", "in", "an", "equivalent", "but", "more", "performant", "way", "at", "run", "t...
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/filters.py#L122-L135
train
220,757
RedHatInsights/insights-core
insights/core/filters.py
loads
def loads(string): """Loads the filters dictionary given a string.""" d = _loads(string) for k, v in d.items(): FILTERS[dr.get_component(k) or k] = set(v)
python
def loads(string): """Loads the filters dictionary given a string.""" d = _loads(string) for k, v in d.items(): FILTERS[dr.get_component(k) or k] = set(v)
[ "def", "loads", "(", "string", ")", ":", "d", "=", "_loads", "(", "string", ")", "for", "k", ",", "v", "in", "d", ".", "items", "(", ")", ":", "FILTERS", "[", "dr", ".", "get_component", "(", "k", ")", "or", "k", "]", "=", "set", "(", "v", ...
Loads the filters dictionary given a string.
[ "Loads", "the", "filters", "dictionary", "given", "a", "string", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/filters.py#L143-L147
train
220,758
RedHatInsights/insights-core
insights/core/filters.py
load
def load(stream=None): """ Loads filters from a stream, normally an open file. If one is not passed, filters are loaded from a default location within the project. """ if stream: loads(stream.read()) else: data = pkgutil.get_data(insights.__name__, _filename) return loads(data) if data else None
python
def load(stream=None): """ Loads filters from a stream, normally an open file. If one is not passed, filters are loaded from a default location within the project. """ if stream: loads(stream.read()) else: data = pkgutil.get_data(insights.__name__, _filename) return loads(data) if data else None
[ "def", "load", "(", "stream", "=", "None", ")", ":", "if", "stream", ":", "loads", "(", "stream", ".", "read", "(", ")", ")", "else", ":", "data", "=", "pkgutil", ".", "get_data", "(", "insights", ".", "__name__", ",", "_filename", ")", "return", "...
Loads filters from a stream, normally an open file. If one is not passed, filters are loaded from a default location within the project.
[ "Loads", "filters", "from", "a", "stream", "normally", "an", "open", "file", ".", "If", "one", "is", "not", "passed", "filters", "are", "loaded", "from", "a", "default", "location", "within", "the", "project", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/filters.py#L150-L160
train
220,759
RedHatInsights/insights-core
insights/core/filters.py
dumps
def dumps(): """Returns a string representation of the FILTERS dictionary.""" d = {} for k, v in FILTERS.items(): d[dr.get_name(k)] = list(v) return _dumps(d)
python
def dumps(): """Returns a string representation of the FILTERS dictionary.""" d = {} for k, v in FILTERS.items(): d[dr.get_name(k)] = list(v) return _dumps(d)
[ "def", "dumps", "(", ")", ":", "d", "=", "{", "}", "for", "k", ",", "v", "in", "FILTERS", ".", "items", "(", ")", ":", "d", "[", "dr", ".", "get_name", "(", "k", ")", "]", "=", "list", "(", "v", ")", "return", "_dumps", "(", "d", ")" ]
Returns a string representation of the FILTERS dictionary.
[ "Returns", "a", "string", "representation", "of", "the", "FILTERS", "dictionary", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/filters.py#L163-L168
train
220,760
RedHatInsights/insights-core
insights/core/filters.py
dump
def dump(stream=None): """ Dumps a string representation of `FILTERS` to a stream, normally an open file. If none is passed, `FILTERS` is dumped to a default location within the project. """ if stream: stream.write(dumps()) else: path = os.path.join(os.path.dirname(insights.__file__), _filename) with open(path, "wu") as f: f.write(dumps())
python
def dump(stream=None): """ Dumps a string representation of `FILTERS` to a stream, normally an open file. If none is passed, `FILTERS` is dumped to a default location within the project. """ if stream: stream.write(dumps()) else: path = os.path.join(os.path.dirname(insights.__file__), _filename) with open(path, "wu") as f: f.write(dumps())
[ "def", "dump", "(", "stream", "=", "None", ")", ":", "if", "stream", ":", "stream", ".", "write", "(", "dumps", "(", ")", ")", "else", ":", "path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "insights", "....
Dumps a string representation of `FILTERS` to a stream, normally an open file. If none is passed, `FILTERS` is dumped to a default location within the project.
[ "Dumps", "a", "string", "representation", "of", "FILTERS", "to", "a", "stream", "normally", "an", "open", "file", ".", "If", "none", "is", "passed", "FILTERS", "is", "dumped", "to", "a", "default", "location", "within", "the", "project", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/filters.py#L171-L182
train
220,761
RedHatInsights/insights-core
insights/parsers/grub_conf.py
_parse_script
def _parse_script(list, line, line_iter): """ Eliminate any bash script contained in the grub v2 configuration """ ifIdx = 0 while (True): line = next(line_iter) if line.startswith("fi"): if ifIdx == 0: return ifIdx -= 1 elif line.startswith("if"): ifIdx += 1
python
def _parse_script(list, line, line_iter): """ Eliminate any bash script contained in the grub v2 configuration """ ifIdx = 0 while (True): line = next(line_iter) if line.startswith("fi"): if ifIdx == 0: return ifIdx -= 1 elif line.startswith("if"): ifIdx += 1
[ "def", "_parse_script", "(", "list", ",", "line", ",", "line_iter", ")", ":", "ifIdx", "=", "0", "while", "(", "True", ")", ":", "line", "=", "next", "(", "line_iter", ")", "if", "line", ".", "startswith", "(", "\"fi\"", ")", ":", "if", "ifIdx", "=...
Eliminate any bash script contained in the grub v2 configuration
[ "Eliminate", "any", "bash", "script", "contained", "in", "the", "grub", "v2", "configuration" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/grub_conf.py#L397-L409
train
220,762
RedHatInsights/insights-core
insights/parsers/grub_conf.py
_parse_title
def _parse_title(line_iter, cur_line, conf): """ Parse "title" in grub v1 config """ title = [] conf['title'].append(title) title.append(('title_name', cur_line.split('title', 1)[1].strip())) while (True): line = next(line_iter) if line.startswith("title "): return line cmd, opt = _parse_cmd(line) title.append((cmd, opt))
python
def _parse_title(line_iter, cur_line, conf): """ Parse "title" in grub v1 config """ title = [] conf['title'].append(title) title.append(('title_name', cur_line.split('title', 1)[1].strip())) while (True): line = next(line_iter) if line.startswith("title "): return line cmd, opt = _parse_cmd(line) title.append((cmd, opt))
[ "def", "_parse_title", "(", "line_iter", ",", "cur_line", ",", "conf", ")", ":", "title", "=", "[", "]", "conf", "[", "'title'", "]", ".", "append", "(", "title", ")", "title", ".", "append", "(", "(", "'title_name'", ",", "cur_line", ".", "split", "...
Parse "title" in grub v1 config
[ "Parse", "title", "in", "grub", "v1", "config" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/grub_conf.py#L447-L460
train
220,763
RedHatInsights/insights-core
insights/parsers/grub_conf.py
GrubConfig.is_kdump_iommu_enabled
def is_kdump_iommu_enabled(self): """ Does any kernel have 'intel_iommu=on' set? Returns: (bool): ``True`` when 'intel_iommu=on' is set, otherwise returns ``False`` """ for line in self._boot_entries: if line.cmdline and IOMMU in line.cmdline: return True return False
python
def is_kdump_iommu_enabled(self): """ Does any kernel have 'intel_iommu=on' set? Returns: (bool): ``True`` when 'intel_iommu=on' is set, otherwise returns ``False`` """ for line in self._boot_entries: if line.cmdline and IOMMU in line.cmdline: return True return False
[ "def", "is_kdump_iommu_enabled", "(", "self", ")", ":", "for", "line", "in", "self", ".", "_boot_entries", ":", "if", "line", ".", "cmdline", "and", "IOMMU", "in", "line", ".", "cmdline", ":", "return", "True", "return", "False" ]
Does any kernel have 'intel_iommu=on' set? Returns: (bool): ``True`` when 'intel_iommu=on' is set, otherwise returns ``False``
[ "Does", "any", "kernel", "have", "intel_iommu", "=", "on", "set?" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/grub_conf.py#L177-L188
train
220,764
RedHatInsights/insights-core
insights/parsers/grub_conf.py
GrubConfig.kernel_initrds
def kernel_initrds(self): """ Get the `kernel` and `initrd` files referenced in GRUB configuration files Returns: (dict): Returns a dict of the `kernel` and `initrd` files referenced in GRUB configuration files """ kernels = [] initrds = [] name_values = [(k, v) for k, v in self.data.get('configs', [])] for value in self.data.get('title', []) + self.data.get('menuentry', []): name_values.extend(value) for name, value in name_values: if name.startswith('module'): if 'vmlinuz' in value: kernels.append(_parse_kernel_initrds_value(value)) elif 'initrd' in value or 'initramfs' in value: initrds.append(_parse_kernel_initrds_value(value)) elif (name.startswith(('kernel', 'linux'))): if 'ipxe.lkrn' in value: # Machine PXE boots the kernel, assume all is ok return {} elif 'xen.gz' not in value: kernels.append(_parse_kernel_initrds_value(value)) elif name.startswith('initrd') or name.startswith('initrd16'): initrds.append(_parse_kernel_initrds_value(value)) return {GRUB_KERNELS: kernels, GRUB_INITRDS: initrds}
python
def kernel_initrds(self): """ Get the `kernel` and `initrd` files referenced in GRUB configuration files Returns: (dict): Returns a dict of the `kernel` and `initrd` files referenced in GRUB configuration files """ kernels = [] initrds = [] name_values = [(k, v) for k, v in self.data.get('configs', [])] for value in self.data.get('title', []) + self.data.get('menuentry', []): name_values.extend(value) for name, value in name_values: if name.startswith('module'): if 'vmlinuz' in value: kernels.append(_parse_kernel_initrds_value(value)) elif 'initrd' in value or 'initramfs' in value: initrds.append(_parse_kernel_initrds_value(value)) elif (name.startswith(('kernel', 'linux'))): if 'ipxe.lkrn' in value: # Machine PXE boots the kernel, assume all is ok return {} elif 'xen.gz' not in value: kernels.append(_parse_kernel_initrds_value(value)) elif name.startswith('initrd') or name.startswith('initrd16'): initrds.append(_parse_kernel_initrds_value(value)) return {GRUB_KERNELS: kernels, GRUB_INITRDS: initrds}
[ "def", "kernel_initrds", "(", "self", ")", ":", "kernels", "=", "[", "]", "initrds", "=", "[", "]", "name_values", "=", "[", "(", "k", ",", "v", ")", "for", "k", ",", "v", "in", "self", ".", "data", ".", "get", "(", "'configs'", ",", "[", "]", ...
Get the `kernel` and `initrd` files referenced in GRUB configuration files Returns: (dict): Returns a dict of the `kernel` and `initrd` files referenced in GRUB configuration files
[ "Get", "the", "kernel", "and", "initrd", "files", "referenced", "in", "GRUB", "configuration", "files" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/grub_conf.py#L192-L222
train
220,765
RedHatInsights/insights-core
insights/core/serde.py
serializer
def serializer(_type): """ Decorator for serializers. A serializer should accept two parameters: An object and a path which is a directory on the filesystem where supplementary data can be stored. This is most often useful for datasources. It should return a dictionary version of the original object that contains only elements that can be serialized to json. """ def inner(func): name = dr.get_name(_type) if name in SERIALIZERS: msg = "%s already has a serializer registered: %s" raise Exception(msg % (name, dr.get_name(SERIALIZERS[name]))) SERIALIZERS[name] = func return func return inner
python
def serializer(_type): """ Decorator for serializers. A serializer should accept two parameters: An object and a path which is a directory on the filesystem where supplementary data can be stored. This is most often useful for datasources. It should return a dictionary version of the original object that contains only elements that can be serialized to json. """ def inner(func): name = dr.get_name(_type) if name in SERIALIZERS: msg = "%s already has a serializer registered: %s" raise Exception(msg % (name, dr.get_name(SERIALIZERS[name]))) SERIALIZERS[name] = func return func return inner
[ "def", "serializer", "(", "_type", ")", ":", "def", "inner", "(", "func", ")", ":", "name", "=", "dr", ".", "get_name", "(", "_type", ")", "if", "name", "in", "SERIALIZERS", ":", "msg", "=", "\"%s already has a serializer registered: %s\"", "raise", "Excepti...
Decorator for serializers. A serializer should accept two parameters: An object and a path which is a directory on the filesystem where supplementary data can be stored. This is most often useful for datasources. It should return a dictionary version of the original object that contains only elements that can be serialized to json.
[ "Decorator", "for", "serializers", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/serde.py#L26-L44
train
220,766
RedHatInsights/insights-core
insights/core/serde.py
deserializer
def deserializer(_type): """ Decorator for deserializers. A deserializer should accept three parameters: A type, a dictionary, and a path that may contain supplementary data stored by its paired serializer. If the serializer stores supplementary data, the relative path to it should be somewhere in the dict of the second parameter. """ def inner(func): name = dr.get_name(_type) if name in DESERIALIZERS: msg = "%s already has a deserializer registered: %s" raise Exception(msg % (dr.get_name(name), dr.get_name(DESERIALIZERS[name]))) DESERIALIZERS[name] = (_type, func) return func return inner
python
def deserializer(_type): """ Decorator for deserializers. A deserializer should accept three parameters: A type, a dictionary, and a path that may contain supplementary data stored by its paired serializer. If the serializer stores supplementary data, the relative path to it should be somewhere in the dict of the second parameter. """ def inner(func): name = dr.get_name(_type) if name in DESERIALIZERS: msg = "%s already has a deserializer registered: %s" raise Exception(msg % (dr.get_name(name), dr.get_name(DESERIALIZERS[name]))) DESERIALIZERS[name] = (_type, func) return func return inner
[ "def", "deserializer", "(", "_type", ")", ":", "def", "inner", "(", "func", ")", ":", "name", "=", "dr", ".", "get_name", "(", "_type", ")", "if", "name", "in", "DESERIALIZERS", ":", "msg", "=", "\"%s already has a deserializer registered: %s\"", "raise", "E...
Decorator for deserializers. A deserializer should accept three parameters: A type, a dictionary, and a path that may contain supplementary data stored by its paired serializer. If the serializer stores supplementary data, the relative path to it should be somewhere in the dict of the second parameter.
[ "Decorator", "for", "deserializers", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/serde.py#L47-L64
train
220,767
RedHatInsights/insights-core
insights/core/serde.py
Hydration.hydrate
def hydrate(self, broker=None): """ Loads a Broker from a previously saved one. A Broker is created if one isn't provided. """ broker = broker or dr.Broker() for path in glob(os.path.join(self.meta_data, "*")): try: with open(path) as f: doc = ser.load(f) res = self._hydrate_one(doc) comp, results, exec_time, ser_time = res if results: broker[comp] = results broker.exec_times[comp] = exec_time + ser_time except Exception as ex: log.warning(ex) return broker
python
def hydrate(self, broker=None): """ Loads a Broker from a previously saved one. A Broker is created if one isn't provided. """ broker = broker or dr.Broker() for path in glob(os.path.join(self.meta_data, "*")): try: with open(path) as f: doc = ser.load(f) res = self._hydrate_one(doc) comp, results, exec_time, ser_time = res if results: broker[comp] = results broker.exec_times[comp] = exec_time + ser_time except Exception as ex: log.warning(ex) return broker
[ "def", "hydrate", "(", "self", ",", "broker", "=", "None", ")", ":", "broker", "=", "broker", "or", "dr", ".", "Broker", "(", ")", "for", "path", "in", "glob", "(", "os", ".", "path", ".", "join", "(", "self", ".", "meta_data", ",", "\"*\"", ")",...
Loads a Broker from a previously saved one. A Broker is created if one isn't provided.
[ "Loads", "a", "Broker", "from", "a", "previously", "saved", "one", ".", "A", "Broker", "is", "created", "if", "one", "isn", "t", "provided", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/serde.py#L144-L161
train
220,768
RedHatInsights/insights-core
insights/core/serde.py
Hydration.dehydrate
def dehydrate(self, comp, broker): """ Saves a component in the given broker to the file system. """ if not self.meta_data: raise Exception("Hydration meta_path not set. Can't dehydrate.") if not self.created: fs.ensure_path(self.meta_data, mode=0o770) if self.data: fs.ensure_path(self.data, mode=0o770) self.created = True c = comp doc = None try: name = dr.get_name(c) value = broker.get(c) errors = [t for e in broker.exceptions.get(c, []) for t in broker.tracebacks[e]] doc = { "name": name, "exec_time": broker.exec_times.get(c), "errors": errors } try: start = time.time() doc["results"] = marshal(value, root=self.data, pool=self.pool) except Exception: errors.append(traceback.format_exc()) log.debug(traceback.format_exc()) doc["results"] = None finally: doc["ser_time"] = time.time() - start except Exception as ex: log.exception(ex) else: if doc is not None and (doc["results"] or doc["errors"]): try: path = os.path.join(self.meta_data, name + "." + self.ser_name) with open(path, "w") as f: ser.dump(doc, f) except Exception as boom: log.error("Could not serialize %s to %s: %r" % (name, self.ser_name, boom)) if path: fs.remove(path)
python
def dehydrate(self, comp, broker): """ Saves a component in the given broker to the file system. """ if not self.meta_data: raise Exception("Hydration meta_path not set. Can't dehydrate.") if not self.created: fs.ensure_path(self.meta_data, mode=0o770) if self.data: fs.ensure_path(self.data, mode=0o770) self.created = True c = comp doc = None try: name = dr.get_name(c) value = broker.get(c) errors = [t for e in broker.exceptions.get(c, []) for t in broker.tracebacks[e]] doc = { "name": name, "exec_time": broker.exec_times.get(c), "errors": errors } try: start = time.time() doc["results"] = marshal(value, root=self.data, pool=self.pool) except Exception: errors.append(traceback.format_exc()) log.debug(traceback.format_exc()) doc["results"] = None finally: doc["ser_time"] = time.time() - start except Exception as ex: log.exception(ex) else: if doc is not None and (doc["results"] or doc["errors"]): try: path = os.path.join(self.meta_data, name + "." + self.ser_name) with open(path, "w") as f: ser.dump(doc, f) except Exception as boom: log.error("Could not serialize %s to %s: %r" % (name, self.ser_name, boom)) if path: fs.remove(path)
[ "def", "dehydrate", "(", "self", ",", "comp", ",", "broker", ")", ":", "if", "not", "self", ".", "meta_data", ":", "raise", "Exception", "(", "\"Hydration meta_path not set. Can't dehydrate.\"", ")", "if", "not", "self", ".", "created", ":", "fs", ".", "ensu...
Saves a component in the given broker to the file system.
[ "Saves", "a", "component", "in", "the", "given", "broker", "to", "the", "file", "system", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/serde.py#L163-L209
train
220,769
RedHatInsights/insights-core
insights/core/serde.py
Hydration.make_persister
def make_persister(self, to_persist): """ Returns a function that hydrates components as they are evaluated. The function should be registered as an observer on a Broker just before execution. Args: to_persist (set): Set of components to persist. Skip everything else. """ if not self.meta_data: raise Exception("Root not set. Can't create persister.") def persister(c, broker): if c in to_persist: self.dehydrate(c, broker) return persister
python
def make_persister(self, to_persist): """ Returns a function that hydrates components as they are evaluated. The function should be registered as an observer on a Broker just before execution. Args: to_persist (set): Set of components to persist. Skip everything else. """ if not self.meta_data: raise Exception("Root not set. Can't create persister.") def persister(c, broker): if c in to_persist: self.dehydrate(c, broker) return persister
[ "def", "make_persister", "(", "self", ",", "to_persist", ")", ":", "if", "not", "self", ".", "meta_data", ":", "raise", "Exception", "(", "\"Root not set. Can't create persister.\"", ")", "def", "persister", "(", "c", ",", "broker", ")", ":", "if", "c", "in"...
Returns a function that hydrates components as they are evaluated. The function should be registered as an observer on a Broker just before execution. Args: to_persist (set): Set of components to persist. Skip everything else.
[ "Returns", "a", "function", "that", "hydrates", "components", "as", "they", "are", "evaluated", ".", "The", "function", "should", "be", "registered", "as", "an", "observer", "on", "a", "Broker", "just", "before", "execution", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/core/serde.py#L211-L228
train
220,770
RedHatInsights/insights-core
insights/parsers/lvm.py
map_keys
def map_keys(pvs, keys): """ Add human readable key names to dictionary while leaving any existing key names. """ rs = [] for pv in pvs: r = dict((v, None) for k, v in keys.items()) for k, v in pv.items(): if k in keys: r[keys[k]] = v r[k] = v rs.append(r) return rs
python
def map_keys(pvs, keys): """ Add human readable key names to dictionary while leaving any existing key names. """ rs = [] for pv in pvs: r = dict((v, None) for k, v in keys.items()) for k, v in pv.items(): if k in keys: r[keys[k]] = v r[k] = v rs.append(r) return rs
[ "def", "map_keys", "(", "pvs", ",", "keys", ")", ":", "rs", "=", "[", "]", "for", "pv", "in", "pvs", ":", "r", "=", "dict", "(", "(", "v", ",", "None", ")", "for", "k", ",", "v", "in", "keys", ".", "items", "(", ")", ")", "for", "k", ",",...
Add human readable key names to dictionary while leaving any existing key names.
[ "Add", "human", "readable", "key", "names", "to", "dictionary", "while", "leaving", "any", "existing", "key", "names", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/lvm.py#L43-L55
train
220,771
RedHatInsights/insights-core
insights/configtree/__init__.py
from_dict
def from_dict(dct): """ Convert a dictionary into a configtree. """ def inner(d): results = [] for name, v in d.items(): if isinstance(v, dict): results.append(Section(name=name, children=from_dict(v))) elif isinstance(v, list): if not any(isinstance(i, dict) for i in v): results.append(Directive(name=name, attrs=v)) else: for i in v: if isinstance(i, dict): results.append(Section(name=name, children=from_dict(i))) elif isinstance(i, list): results.append(Directive(name=name, attrs=i)) else: results.append(Directive(name=name, attrs=[i])) else: results.append(Directive(name, attrs=[v])) return results return Root(children=inner(dct))
python
def from_dict(dct): """ Convert a dictionary into a configtree. """ def inner(d): results = [] for name, v in d.items(): if isinstance(v, dict): results.append(Section(name=name, children=from_dict(v))) elif isinstance(v, list): if not any(isinstance(i, dict) for i in v): results.append(Directive(name=name, attrs=v)) else: for i in v: if isinstance(i, dict): results.append(Section(name=name, children=from_dict(i))) elif isinstance(i, list): results.append(Directive(name=name, attrs=i)) else: results.append(Directive(name=name, attrs=[i])) else: results.append(Directive(name, attrs=[v])) return results return Root(children=inner(dct))
[ "def", "from_dict", "(", "dct", ")", ":", "def", "inner", "(", "d", ")", ":", "results", "=", "[", "]", "for", "name", ",", "v", "in", "d", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "dict", ")", ":", "results", ".", "app...
Convert a dictionary into a configtree.
[ "Convert", "a", "dictionary", "into", "a", "configtree", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/configtree/__init__.py#L348-L369
train
220,772
RedHatInsights/insights-core
insights/configtree/__init__.py
__or
def __or(funcs, args): """ Support list sugar for "or" of two predicates. Used inside `select`. """ results = [] for f in funcs: result = f(args) if result: results.extend(result) return results
python
def __or(funcs, args): """ Support list sugar for "or" of two predicates. Used inside `select`. """ results = [] for f in funcs: result = f(args) if result: results.extend(result) return results
[ "def", "__or", "(", "funcs", ",", "args", ")", ":", "results", "=", "[", "]", "for", "f", "in", "funcs", ":", "result", "=", "f", "(", "args", ")", "if", "result", ":", "results", ".", "extend", "(", "result", ")", "return", "results" ]
Support list sugar for "or" of two predicates. Used inside `select`.
[ "Support", "list", "sugar", "for", "or", "of", "two", "predicates", ".", "Used", "inside", "select", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/configtree/__init__.py#L582-L589
train
220,773
RedHatInsights/insights-core
insights/configtree/__init__.py
BinaryBool
def BinaryBool(pred): """ Lifts predicates that take an argument into the DSL. """ class Predicate(Bool): def __init__(self, value, ignore_case=False): self.value = caseless(value) if ignore_case else value self.ignore_case = ignore_case def __call__(self, data): if not isinstance(data, list): data = [data] for d in data: try: if pred(caseless(d) if self.ignore_case else d, self.value): return True except: pass return False return Predicate
python
def BinaryBool(pred): """ Lifts predicates that take an argument into the DSL. """ class Predicate(Bool): def __init__(self, value, ignore_case=False): self.value = caseless(value) if ignore_case else value self.ignore_case = ignore_case def __call__(self, data): if not isinstance(data, list): data = [data] for d in data: try: if pred(caseless(d) if self.ignore_case else d, self.value): return True except: pass return False return Predicate
[ "def", "BinaryBool", "(", "pred", ")", ":", "class", "Predicate", "(", "Bool", ")", ":", "def", "__init__", "(", "self", ",", "value", ",", "ignore_case", "=", "False", ")", ":", "self", ".", "value", "=", "caseless", "(", "value", ")", "if", "ignore...
Lifts predicates that take an argument into the DSL.
[ "Lifts", "predicates", "that", "take", "an", "argument", "into", "the", "DSL", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/configtree/__init__.py#L652-L669
train
220,774
RedHatInsights/insights-core
insights/configtree/__init__.py
select
def select(*queries, **kwargs): """ Builds a function that will execute the specified queries against a list of Nodes. """ def make_query(*args): def simple_query(nodes): if len(args) == 0: return nodes pred = args[0] results = [] if isinstance(pred, list): funcs = [make_query(q) for q in pred] return __or(funcs, nodes) elif isinstance(pred, tuple): name, attrs = pred[0], pred[1:] name_pred = __make_name_pred(name) attrs_pred = __make_attrs_pred(attrs) for n in nodes: if name_pred(n.name) and attrs_pred(n.attrs): results.append(n) else: name_pred = __make_name_pred(pred) for n in nodes: if name_pred(n.name): results.append(n) return results if len(args) > 1: return __compose(make_query(*args[1:]), simple_query) return simple_query def deep_query(query, nodes): """ Slide the query down the branches. """ def inner(children): results = [] for c in children: if query([c]): results.append(c) results.extend(inner(c.children)) return results return inner(nodes) def unique(roots): seen = set() results = [] for r in roots: if r not in seen: seen.add(r) results.append(r) return results def compiled_query(nodes): """ This is the compiled query that can be run against a configuration. """ query = make_query(*queries) roots = kwargs.get("roots", True) if kwargs.get("deep", False): results = deep_query(query, nodes) if roots: results = unique([r.root for r in results]) elif roots: results = unique([n.root for n in query(nodes)]) else: results = query(nodes) one = kwargs.get("one") if one is None: return SearchResult(children=results) return results[one] if results else None return compiled_query
python
def select(*queries, **kwargs): """ Builds a function that will execute the specified queries against a list of Nodes. """ def make_query(*args): def simple_query(nodes): if len(args) == 0: return nodes pred = args[0] results = [] if isinstance(pred, list): funcs = [make_query(q) for q in pred] return __or(funcs, nodes) elif isinstance(pred, tuple): name, attrs = pred[0], pred[1:] name_pred = __make_name_pred(name) attrs_pred = __make_attrs_pred(attrs) for n in nodes: if name_pred(n.name) and attrs_pred(n.attrs): results.append(n) else: name_pred = __make_name_pred(pred) for n in nodes: if name_pred(n.name): results.append(n) return results if len(args) > 1: return __compose(make_query(*args[1:]), simple_query) return simple_query def deep_query(query, nodes): """ Slide the query down the branches. """ def inner(children): results = [] for c in children: if query([c]): results.append(c) results.extend(inner(c.children)) return results return inner(nodes) def unique(roots): seen = set() results = [] for r in roots: if r not in seen: seen.add(r) results.append(r) return results def compiled_query(nodes): """ This is the compiled query that can be run against a configuration. """ query = make_query(*queries) roots = kwargs.get("roots", True) if kwargs.get("deep", False): results = deep_query(query, nodes) if roots: results = unique([r.root for r in results]) elif roots: results = unique([n.root for n in query(nodes)]) else: results = query(nodes) one = kwargs.get("one") if one is None: return SearchResult(children=results) return results[one] if results else None return compiled_query
[ "def", "select", "(", "*", "queries", ",", "*", "*", "kwargs", ")", ":", "def", "make_query", "(", "*", "args", ")", ":", "def", "simple_query", "(", "nodes", ")", ":", "if", "len", "(", "args", ")", "==", "0", ":", "return", "nodes", "pred", "="...
Builds a function that will execute the specified queries against a list of Nodes.
[ "Builds", "a", "function", "that", "will", "execute", "the", "specified", "queries", "against", "a", "list", "of", "Nodes", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/configtree/__init__.py#L722-L793
train
220,775
RedHatInsights/insights-core
insights/configtree/__init__.py
Node.find
def find(self, *queries, **kwargs): """ Finds the first result found anywhere in the configuration. Pass `one=last` for the last result. Returns `None` if no results are found. """ kwargs["deep"] = True kwargs["roots"] = False if "one" not in kwargs: kwargs["one"] = first return self.select(*queries, **kwargs)
python
def find(self, *queries, **kwargs): """ Finds the first result found anywhere in the configuration. Pass `one=last` for the last result. Returns `None` if no results are found. """ kwargs["deep"] = True kwargs["roots"] = False if "one" not in kwargs: kwargs["one"] = first return self.select(*queries, **kwargs)
[ "def", "find", "(", "self", ",", "*", "queries", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"deep\"", "]", "=", "True", "kwargs", "[", "\"roots\"", "]", "=", "False", "if", "\"one\"", "not", "in", "kwargs", ":", "kwargs", "[", "\"one\"", "...
Finds the first result found anywhere in the configuration. Pass `one=last` for the last result. Returns `None` if no results are found.
[ "Finds", "the", "first", "result", "found", "anywhere", "in", "the", "configuration", ".", "Pass", "one", "=", "last", "for", "the", "last", "result", ".", "Returns", "None", "if", "no", "results", "are", "found", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/configtree/__init__.py#L165-L174
train
220,776
RedHatInsights/insights-core
insights/configtree/__init__.py
Node.find_all
def find_all(self, *queries): """ Find all results matching the query anywhere in the configuration. Returns an empty `SearchResult` if no results are found. """ return self.select(*queries, deep=True, roots=False)
python
def find_all(self, *queries): """ Find all results matching the query anywhere in the configuration. Returns an empty `SearchResult` if no results are found. """ return self.select(*queries, deep=True, roots=False)
[ "def", "find_all", "(", "self", ",", "*", "queries", ")", ":", "return", "self", ".", "select", "(", "*", "queries", ",", "deep", "=", "True", ",", "roots", "=", "False", ")" ]
Find all results matching the query anywhere in the configuration. Returns an empty `SearchResult` if no results are found.
[ "Find", "all", "results", "matching", "the", "query", "anywhere", "in", "the", "configuration", ".", "Returns", "an", "empty", "SearchResult", "if", "no", "results", "are", "found", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/configtree/__init__.py#L176-L181
train
220,777
RedHatInsights/insights-core
insights/parsers/installed_rpms.py
pad_version
def pad_version(left, right): """Returns two sequences of the same length so that they can be compared. The shorter of the two arguments is lengthened by inserting extra zeros before non-integer components. The algorithm attempts to align character components.""" pair = vcmp(left), vcmp(right) mn, mx = min(pair, key=len), max(pair, key=len) for idx, c in enumerate(mx): try: a = mx[idx] b = mn[idx] if type(a) != type(b): mn.insert(idx, 0) except IndexError: if type(c) is int: mn.append(0) elif isinstance(c, six.string_types): mn.append('') else: raise Exception("pad_version failed (%s) (%s)" % (left, right)) return pair
python
def pad_version(left, right): """Returns two sequences of the same length so that they can be compared. The shorter of the two arguments is lengthened by inserting extra zeros before non-integer components. The algorithm attempts to align character components.""" pair = vcmp(left), vcmp(right) mn, mx = min(pair, key=len), max(pair, key=len) for idx, c in enumerate(mx): try: a = mx[idx] b = mn[idx] if type(a) != type(b): mn.insert(idx, 0) except IndexError: if type(c) is int: mn.append(0) elif isinstance(c, six.string_types): mn.append('') else: raise Exception("pad_version failed (%s) (%s)" % (left, right)) return pair
[ "def", "pad_version", "(", "left", ",", "right", ")", ":", "pair", "=", "vcmp", "(", "left", ")", ",", "vcmp", "(", "right", ")", "mn", ",", "mx", "=", "min", "(", "pair", ",", "key", "=", "len", ")", ",", "max", "(", "pair", ",", "key", "=",...
Returns two sequences of the same length so that they can be compared. The shorter of the two arguments is lengthened by inserting extra zeros before non-integer components. The algorithm attempts to align character components.
[ "Returns", "two", "sequences", "of", "the", "same", "length", "so", "that", "they", "can", "be", "compared", ".", "The", "shorter", "of", "the", "two", "arguments", "is", "lengthened", "by", "inserting", "extra", "zeros", "before", "non", "-", "integer", "...
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/installed_rpms.py#L254-L278
train
220,778
RedHatInsights/insights-core
insights/parsers/installed_rpms.py
InstalledRpm._parse_package
def _parse_package(cls, package_string): """ Helper method for parsing package string. Args: package_string (str): dash separated package string such as 'bash-4.2.39-3.el7' Returns: dict: dictionary containing 'name', 'version', 'release' and 'arch' keys """ pkg, arch = rsplit(package_string, cls._arch_sep(package_string)) if arch not in KNOWN_ARCHITECTURES: pkg, arch = (package_string, None) pkg, release = rsplit(pkg, '-') name, version = rsplit(pkg, '-') epoch, version = version.split(':', 1) if ":" in version else ['0', version] # oracleasm packages have a dash in their version string, fix that if name.startswith('oracleasm') and name.endswith('.el5'): name, version2 = name.split('-', 1) version = version2 + '-' + version return { 'name': name, 'version': version, 'release': release, 'arch': arch, 'epoch': epoch }
python
def _parse_package(cls, package_string): """ Helper method for parsing package string. Args: package_string (str): dash separated package string such as 'bash-4.2.39-3.el7' Returns: dict: dictionary containing 'name', 'version', 'release' and 'arch' keys """ pkg, arch = rsplit(package_string, cls._arch_sep(package_string)) if arch not in KNOWN_ARCHITECTURES: pkg, arch = (package_string, None) pkg, release = rsplit(pkg, '-') name, version = rsplit(pkg, '-') epoch, version = version.split(':', 1) if ":" in version else ['0', version] # oracleasm packages have a dash in their version string, fix that if name.startswith('oracleasm') and name.endswith('.el5'): name, version2 = name.split('-', 1) version = version2 + '-' + version return { 'name': name, 'version': version, 'release': release, 'arch': arch, 'epoch': epoch }
[ "def", "_parse_package", "(", "cls", ",", "package_string", ")", ":", "pkg", ",", "arch", "=", "rsplit", "(", "package_string", ",", "cls", ".", "_arch_sep", "(", "package_string", ")", ")", "if", "arch", "not", "in", "KNOWN_ARCHITECTURES", ":", "pkg", ","...
Helper method for parsing package string. Args: package_string (str): dash separated package string such as 'bash-4.2.39-3.el7' Returns: dict: dictionary containing 'name', 'version', 'release' and 'arch' keys
[ "Helper", "method", "for", "parsing", "package", "string", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/installed_rpms.py#L431-L457
train
220,779
RedHatInsights/insights-core
insights/parsers/installed_rpms.py
InstalledRpm._parse_line
def _parse_line(cls, line): """ Helper method for parsing package line with or without SOS report information. Args: line (str): package line with or without SOS report information Returns: dict: dictionary containing 'name', 'version', 'release' and 'arch' keys plus additionally 'installtime', 'buildtime', 'vendor', 'buildserver', 'pgpsig', 'pgpsig_short' if these are present. """ try: pkg, rest = line.split(None, 1) except ValueError: rpm = cls._parse_package(line.strip()) return rpm rpm = cls._parse_package(pkg) rest = rest.split('\t') for i, value in enumerate(rest): rpm[cls.SOSREPORT_KEYS[i]] = value return rpm
python
def _parse_line(cls, line): """ Helper method for parsing package line with or without SOS report information. Args: line (str): package line with or without SOS report information Returns: dict: dictionary containing 'name', 'version', 'release' and 'arch' keys plus additionally 'installtime', 'buildtime', 'vendor', 'buildserver', 'pgpsig', 'pgpsig_short' if these are present. """ try: pkg, rest = line.split(None, 1) except ValueError: rpm = cls._parse_package(line.strip()) return rpm rpm = cls._parse_package(pkg) rest = rest.split('\t') for i, value in enumerate(rest): rpm[cls.SOSREPORT_KEYS[i]] = value return rpm
[ "def", "_parse_line", "(", "cls", ",", "line", ")", ":", "try", ":", "pkg", ",", "rest", "=", "line", ".", "split", "(", "None", ",", "1", ")", "except", "ValueError", ":", "rpm", "=", "cls", ".", "_parse_package", "(", "line", ".", "strip", "(", ...
Helper method for parsing package line with or without SOS report information. Args: line (str): package line with or without SOS report information Returns: dict: dictionary containing 'name', 'version', 'release' and 'arch' keys plus additionally 'installtime', 'buildtime', 'vendor', 'buildserver', 'pgpsig', 'pgpsig_short' if these are present.
[ "Helper", "method", "for", "parsing", "package", "line", "with", "or", "without", "SOS", "report", "information", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/installed_rpms.py#L460-L481
train
220,780
RedHatInsights/insights-core
insights/contrib/importlib.py
_resolve_name
def _resolve_name(name, package, level): """Return the absolute name of the module to be imported.""" if not hasattr(package, 'rindex'): raise ValueError("'package' not set to a string") dot = len(package) for x in xrange(level, 1, -1): try: dot = package.rindex('.', 0, dot) except ValueError: raise ValueError("attempted relative import beyond top-level " "package") return "%s.%s" % (package[:dot], name)
python
def _resolve_name(name, package, level): """Return the absolute name of the module to be imported.""" if not hasattr(package, 'rindex'): raise ValueError("'package' not set to a string") dot = len(package) for x in xrange(level, 1, -1): try: dot = package.rindex('.', 0, dot) except ValueError: raise ValueError("attempted relative import beyond top-level " "package") return "%s.%s" % (package[:dot], name)
[ "def", "_resolve_name", "(", "name", ",", "package", ",", "level", ")", ":", "if", "not", "hasattr", "(", "package", ",", "'rindex'", ")", ":", "raise", "ValueError", "(", "\"'package' not set to a string\"", ")", "dot", "=", "len", "(", "package", ")", "f...
Return the absolute name of the module to be imported.
[ "Return", "the", "absolute", "name", "of", "the", "module", "to", "be", "imported", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/contrib/importlib.py#L6-L17
train
220,781
RedHatInsights/insights-core
insights/parsers/krb5.py
_handle_key_value
def _handle_key_value(t_dict, key, value): """ Function to handle key has multi value, and return the values as list. """ if key in t_dict: val = t_dict[key] if isinstance(val, str): val = [val] val.append(value) return val return value
python
def _handle_key_value(t_dict, key, value): """ Function to handle key has multi value, and return the values as list. """ if key in t_dict: val = t_dict[key] if isinstance(val, str): val = [val] val.append(value) return val return value
[ "def", "_handle_key_value", "(", "t_dict", ",", "key", ",", "value", ")", ":", "if", "key", "in", "t_dict", ":", "val", "=", "t_dict", "[", "key", "]", "if", "isinstance", "(", "val", ",", "str", ")", ":", "val", "=", "[", "val", "]", "val", ".",...
Function to handle key has multi value, and return the values as list.
[ "Function", "to", "handle", "key", "has", "multi", "value", "and", "return", "the", "values", "as", "list", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/krb5.py#L63-L73
train
220,782
RedHatInsights/insights-core
insights/formats/__init__.py
get_formatter
def get_formatter(name): """ Looks up a formatter class given a prefix to it. The names are sorted, and the first matching class is returned. """ for k in sorted(_FORMATTERS): if k.startswith(name): return _FORMATTERS[k]
python
def get_formatter(name): """ Looks up a formatter class given a prefix to it. The names are sorted, and the first matching class is returned. """ for k in sorted(_FORMATTERS): if k.startswith(name): return _FORMATTERS[k]
[ "def", "get_formatter", "(", "name", ")", ":", "for", "k", "in", "sorted", "(", "_FORMATTERS", ")", ":", "if", "k", ".", "startswith", "(", "name", ")", ":", "return", "_FORMATTERS", "[", "k", "]" ]
Looks up a formatter class given a prefix to it. The names are sorted, and the first matching class is returned.
[ "Looks", "up", "a", "formatter", "class", "given", "a", "prefix", "to", "it", ".", "The", "names", "are", "sorted", "and", "the", "first", "matching", "class", "is", "returned", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/formats/__init__.py#L10-L17
train
220,783
RedHatInsights/insights-core
insights/parsers/nfs_exports.py
NFSExportsBase.all_options
def all_options(self): """Returns the set of all options used in all export entries""" items = chain.from_iterable(hosts.values() for hosts in self.data.values()) return set(chain.from_iterable(items))
python
def all_options(self): """Returns the set of all options used in all export entries""" items = chain.from_iterable(hosts.values() for hosts in self.data.values()) return set(chain.from_iterable(items))
[ "def", "all_options", "(", "self", ")", ":", "items", "=", "chain", ".", "from_iterable", "(", "hosts", ".", "values", "(", ")", "for", "hosts", "in", "self", ".", "data", ".", "values", "(", ")", ")", "return", "set", "(", "chain", ".", "from_iterab...
Returns the set of all options used in all export entries
[ "Returns", "the", "set", "of", "all", "options", "used", "in", "all", "export", "entries" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/parsers/nfs_exports.py#L133-L136
train
220,784
RedHatInsights/insights-core
insights/client/connection.py
InsightsConnection._init_session
def _init_session(self): """ Set up the session, auth is handled here """ session = requests.Session() session.headers = {'User-Agent': self.user_agent, 'Accept': 'application/json'} if self.systemid is not None: session.headers.update({'systemid': self.systemid}) if self.authmethod == "BASIC": session.auth = (self.username, self.password) elif self.authmethod == "CERT": cert = rhsmCertificate.certpath() key = rhsmCertificate.keypath() if rhsmCertificate.exists(): session.cert = (cert, key) else: logger.error('ERROR: Certificates not found.') session.verify = self.cert_verify session.proxies = self.proxies session.trust_env = False if self.proxy_auth: # HACKY try: # Need to make a request that will fail to get proxies set up net_logger.info("GET %s", self.base_url) session.request( "GET", self.base_url, timeout=self.config.http_timeout) except requests.ConnectionError: pass # Major hack, requests/urllib3 does not make access to # proxy_headers easy proxy_mgr = session.adapters['https://'].proxy_manager[self.proxies['https']] auth_map = {'Proxy-Authorization': self.proxy_auth} proxy_mgr.proxy_headers = auth_map proxy_mgr.connection_pool_kw['_proxy_headers'] = auth_map conns = proxy_mgr.pools._container for conn in conns: connection = conns[conn] connection.proxy_headers = auth_map return session
python
def _init_session(self): """ Set up the session, auth is handled here """ session = requests.Session() session.headers = {'User-Agent': self.user_agent, 'Accept': 'application/json'} if self.systemid is not None: session.headers.update({'systemid': self.systemid}) if self.authmethod == "BASIC": session.auth = (self.username, self.password) elif self.authmethod == "CERT": cert = rhsmCertificate.certpath() key = rhsmCertificate.keypath() if rhsmCertificate.exists(): session.cert = (cert, key) else: logger.error('ERROR: Certificates not found.') session.verify = self.cert_verify session.proxies = self.proxies session.trust_env = False if self.proxy_auth: # HACKY try: # Need to make a request that will fail to get proxies set up net_logger.info("GET %s", self.base_url) session.request( "GET", self.base_url, timeout=self.config.http_timeout) except requests.ConnectionError: pass # Major hack, requests/urllib3 does not make access to # proxy_headers easy proxy_mgr = session.adapters['https://'].proxy_manager[self.proxies['https']] auth_map = {'Proxy-Authorization': self.proxy_auth} proxy_mgr.proxy_headers = auth_map proxy_mgr.connection_pool_kw['_proxy_headers'] = auth_map conns = proxy_mgr.pools._container for conn in conns: connection = conns[conn] connection.proxy_headers = auth_map return session
[ "def", "_init_session", "(", "self", ")", ":", "session", "=", "requests", ".", "Session", "(", ")", "session", ".", "headers", "=", "{", "'User-Agent'", ":", "self", ".", "user_agent", ",", "'Accept'", ":", "'application/json'", "}", "if", "self", ".", ...
Set up the session, auth is handled here
[ "Set", "up", "the", "session", "auth", "is", "handled", "here" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/connection.py#L129-L169
train
220,785
RedHatInsights/insights-core
insights/client/connection.py
InsightsConnection.handle_fail_rcs
def handle_fail_rcs(self, req): """ Bail out if we get a 401 and leave a message """ try: logger.debug("HTTP Status Code: %s", req.status_code) logger.debug("HTTP Response Text: %s", req.text) logger.debug("HTTP Response Reason: %s", req.reason) logger.debug("HTTP Response Content: %s", req.content) except: logger.error("Malformed HTTP Request.") # attempt to read the HTTP response JSON message try: logger.debug("HTTP Response Message: %s", req.json()["message"]) except: logger.debug("No HTTP Response message present.") # handle specific status codes if req.status_code >= 400: logger.info("Debug Information:\nHTTP Status Code: %s", req.status_code) logger.info("HTTP Status Text: %s", req.reason) if req.status_code == 401: logger.error("Authorization Required.") logger.error("Please ensure correct credentials " "in " + constants.default_conf_file) logger.debug("HTTP Response Text: %s", req.text) if req.status_code == 402: # failed registration because of entitlement limit hit logger.debug('Registration failed by 402 error.') try: logger.error(req.json()["message"]) except LookupError: logger.error("Got 402 but no message") logger.debug("HTTP Response Text: %s", req.text) except: logger.error("Got 402 but no message") logger.debug("HTTP Response Text: %s", req.text) if req.status_code == 403 and self.auto_config: # Insights disabled in satellite rhsm_hostname = urlparse(self.base_url).hostname if (rhsm_hostname != 'subscription.rhn.redhat.com' and rhsm_hostname != 'subscription.rhsm.redhat.com'): logger.error('Please enable Insights on Satellite server ' '%s to continue.', rhsm_hostname) if req.status_code == 412: try: unreg_date = req.json()["unregistered_at"] logger.error(req.json()["message"]) write_unregistered_file(unreg_date) except LookupError: unreg_date = "412, but no unreg_date or message" logger.debug("HTTP Response Text: %s", req.text) except: unreg_date = "412, but no unreg_date or message" logger.debug("HTTP Response Text: %s", req.text) return True return False
python
def handle_fail_rcs(self, req): """ Bail out if we get a 401 and leave a message """ try: logger.debug("HTTP Status Code: %s", req.status_code) logger.debug("HTTP Response Text: %s", req.text) logger.debug("HTTP Response Reason: %s", req.reason) logger.debug("HTTP Response Content: %s", req.content) except: logger.error("Malformed HTTP Request.") # attempt to read the HTTP response JSON message try: logger.debug("HTTP Response Message: %s", req.json()["message"]) except: logger.debug("No HTTP Response message present.") # handle specific status codes if req.status_code >= 400: logger.info("Debug Information:\nHTTP Status Code: %s", req.status_code) logger.info("HTTP Status Text: %s", req.reason) if req.status_code == 401: logger.error("Authorization Required.") logger.error("Please ensure correct credentials " "in " + constants.default_conf_file) logger.debug("HTTP Response Text: %s", req.text) if req.status_code == 402: # failed registration because of entitlement limit hit logger.debug('Registration failed by 402 error.') try: logger.error(req.json()["message"]) except LookupError: logger.error("Got 402 but no message") logger.debug("HTTP Response Text: %s", req.text) except: logger.error("Got 402 but no message") logger.debug("HTTP Response Text: %s", req.text) if req.status_code == 403 and self.auto_config: # Insights disabled in satellite rhsm_hostname = urlparse(self.base_url).hostname if (rhsm_hostname != 'subscription.rhn.redhat.com' and rhsm_hostname != 'subscription.rhsm.redhat.com'): logger.error('Please enable Insights on Satellite server ' '%s to continue.', rhsm_hostname) if req.status_code == 412: try: unreg_date = req.json()["unregistered_at"] logger.error(req.json()["message"]) write_unregistered_file(unreg_date) except LookupError: unreg_date = "412, but no unreg_date or message" logger.debug("HTTP Response Text: %s", req.text) except: unreg_date = "412, but no unreg_date or message" logger.debug("HTTP Response Text: %s", req.text) return True return False
[ "def", "handle_fail_rcs", "(", "self", ",", "req", ")", ":", "try", ":", "logger", ".", "debug", "(", "\"HTTP Status Code: %s\"", ",", "req", ".", "status_code", ")", "logger", ".", "debug", "(", "\"HTTP Response Text: %s\"", ",", "req", ".", "text", ")", ...
Bail out if we get a 401 and leave a message
[ "Bail", "out", "if", "we", "get", "a", "401", "and", "leave", "a", "message" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/connection.py#L352-L411
train
220,786
RedHatInsights/insights-core
insights/client/connection.py
InsightsConnection.get_satellite5_info
def get_satellite5_info(self, branch_info): """ Get remote_leaf for Satellite 5 Managed box """ logger.debug( "Remote branch not -1 but remote leaf is -1, must be Satellite 5") if os.path.isfile('/etc/sysconfig/rhn/systemid'): logger.debug("Found systemid file") sat5_conf = ET.parse('/etc/sysconfig/rhn/systemid').getroot() leaf_id = None for member in sat5_conf.getiterator('member'): if member.find('name').text == 'system_id': logger.debug("Found member 'system_id'") leaf_id = member.find('value').find( 'string').text.split('ID-')[1] logger.debug("Found leaf id: %s", leaf_id) branch_info['remote_leaf'] = leaf_id if leaf_id is None: logger.error("Could not determine leaf_id! Exiting!") return False
python
def get_satellite5_info(self, branch_info): """ Get remote_leaf for Satellite 5 Managed box """ logger.debug( "Remote branch not -1 but remote leaf is -1, must be Satellite 5") if os.path.isfile('/etc/sysconfig/rhn/systemid'): logger.debug("Found systemid file") sat5_conf = ET.parse('/etc/sysconfig/rhn/systemid').getroot() leaf_id = None for member in sat5_conf.getiterator('member'): if member.find('name').text == 'system_id': logger.debug("Found member 'system_id'") leaf_id = member.find('value').find( 'string').text.split('ID-')[1] logger.debug("Found leaf id: %s", leaf_id) branch_info['remote_leaf'] = leaf_id if leaf_id is None: logger.error("Could not determine leaf_id! Exiting!") return False
[ "def", "get_satellite5_info", "(", "self", ",", "branch_info", ")", ":", "logger", ".", "debug", "(", "\"Remote branch not -1 but remote leaf is -1, must be Satellite 5\"", ")", "if", "os", ".", "path", ".", "isfile", "(", "'/etc/sysconfig/rhn/systemid'", ")", ":", "l...
Get remote_leaf for Satellite 5 Managed box
[ "Get", "remote_leaf", "for", "Satellite", "5", "Managed", "box" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/connection.py#L413-L432
train
220,787
RedHatInsights/insights-core
insights/client/connection.py
InsightsConnection.get_branch_info
def get_branch_info(self): """ Retrieve branch_info from Satellite Server """ branch_info = None if os.path.exists(constants.cached_branch_info): # use cached branch info file if less than 10 minutes old # (failsafe, should be deleted at end of client run normally) logger.debug(u'Reading branch info from cached file.') ctime = datetime.utcfromtimestamp( os.path.getctime(constants.cached_branch_info)) if datetime.utcnow() < (ctime + timedelta(minutes=5)): with io.open(constants.cached_branch_info, encoding='utf8', mode='r') as f: branch_info = json.load(f) return branch_info else: logger.debug(u'Cached branch info is older than 5 minutes.') logger.debug(u'Obtaining branch information from %s', self.branch_info_url) net_logger.info(u'GET %s', self.branch_info_url) response = self.session.get(self.branch_info_url, timeout=self.config.http_timeout) logger.debug(u'GET branch_info status: %s', response.status_code) if response.status_code != 200: logger.debug("There was an error obtaining branch information.") logger.debug(u'Bad status from server: %s', response.status_code) logger.debug("Assuming default branch information %s" % self.branch_info) return False branch_info = response.json() logger.debug(u'Branch information: %s', json.dumps(branch_info)) # Determine if we are connected to Satellite 5 if ((branch_info[u'remote_branch'] is not -1 and branch_info[u'remote_leaf'] is -1)): self.get_satellite5_info(branch_info) logger.debug(u'Saving branch info to file.') with io.open(constants.cached_branch_info, encoding='utf8', mode='w') as f: # json.dump is broke in py2 so use dumps bi_str = json.dumps(branch_info, ensure_ascii=False) f.write(bi_str) self.branch_info = branch_info return branch_info
python
def get_branch_info(self): """ Retrieve branch_info from Satellite Server """ branch_info = None if os.path.exists(constants.cached_branch_info): # use cached branch info file if less than 10 minutes old # (failsafe, should be deleted at end of client run normally) logger.debug(u'Reading branch info from cached file.') ctime = datetime.utcfromtimestamp( os.path.getctime(constants.cached_branch_info)) if datetime.utcnow() < (ctime + timedelta(minutes=5)): with io.open(constants.cached_branch_info, encoding='utf8', mode='r') as f: branch_info = json.load(f) return branch_info else: logger.debug(u'Cached branch info is older than 5 minutes.') logger.debug(u'Obtaining branch information from %s', self.branch_info_url) net_logger.info(u'GET %s', self.branch_info_url) response = self.session.get(self.branch_info_url, timeout=self.config.http_timeout) logger.debug(u'GET branch_info status: %s', response.status_code) if response.status_code != 200: logger.debug("There was an error obtaining branch information.") logger.debug(u'Bad status from server: %s', response.status_code) logger.debug("Assuming default branch information %s" % self.branch_info) return False branch_info = response.json() logger.debug(u'Branch information: %s', json.dumps(branch_info)) # Determine if we are connected to Satellite 5 if ((branch_info[u'remote_branch'] is not -1 and branch_info[u'remote_leaf'] is -1)): self.get_satellite5_info(branch_info) logger.debug(u'Saving branch info to file.') with io.open(constants.cached_branch_info, encoding='utf8', mode='w') as f: # json.dump is broke in py2 so use dumps bi_str = json.dumps(branch_info, ensure_ascii=False) f.write(bi_str) self.branch_info = branch_info return branch_info
[ "def", "get_branch_info", "(", "self", ")", ":", "branch_info", "=", "None", "if", "os", ".", "path", ".", "exists", "(", "constants", ".", "cached_branch_info", ")", ":", "# use cached branch info file if less than 10 minutes old", "# (failsafe, should be deleted at end...
Retrieve branch_info from Satellite Server
[ "Retrieve", "branch_info", "from", "Satellite", "Server" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/connection.py#L434-L478
train
220,788
RedHatInsights/insights-core
insights/client/connection.py
InsightsConnection.create_system
def create_system(self, new_machine_id=False): """ Create the machine via the API """ client_hostname = determine_hostname() machine_id = generate_machine_id(new_machine_id) branch_info = self.branch_info if not branch_info: return False remote_branch = branch_info['remote_branch'] remote_leaf = branch_info['remote_leaf'] data = {'machine_id': machine_id, 'remote_branch': remote_branch, 'remote_leaf': remote_leaf, 'hostname': client_hostname} if self.config.display_name is not None: data['display_name'] = self.config.display_name data = json.dumps(data) post_system_url = self.api_url + '/v1/systems' logger.debug("POST System: %s", post_system_url) logger.debug(data) net_logger.info("POST %s", post_system_url) return self.session.post(post_system_url, headers={'Content-Type': 'application/json'}, data=data)
python
def create_system(self, new_machine_id=False): """ Create the machine via the API """ client_hostname = determine_hostname() machine_id = generate_machine_id(new_machine_id) branch_info = self.branch_info if not branch_info: return False remote_branch = branch_info['remote_branch'] remote_leaf = branch_info['remote_leaf'] data = {'machine_id': machine_id, 'remote_branch': remote_branch, 'remote_leaf': remote_leaf, 'hostname': client_hostname} if self.config.display_name is not None: data['display_name'] = self.config.display_name data = json.dumps(data) post_system_url = self.api_url + '/v1/systems' logger.debug("POST System: %s", post_system_url) logger.debug(data) net_logger.info("POST %s", post_system_url) return self.session.post(post_system_url, headers={'Content-Type': 'application/json'}, data=data)
[ "def", "create_system", "(", "self", ",", "new_machine_id", "=", "False", ")", ":", "client_hostname", "=", "determine_hostname", "(", ")", "machine_id", "=", "generate_machine_id", "(", "new_machine_id", ")", "branch_info", "=", "self", ".", "branch_info", "if", ...
Create the machine via the API
[ "Create", "the", "machine", "via", "the", "API" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/connection.py#L481-L508
train
220,789
RedHatInsights/insights-core
insights/client/connection.py
InsightsConnection.group_systems
def group_systems(self, group_name, systems): """ Adds an array of systems to specified group Args: group_name: Display name of group systems: Array of {'machine_id': machine_id} """ api_group_id = None headers = {'Content-Type': 'application/json'} group_path = self.api_url + '/v1/groups' group_get_path = group_path + ('?display_name=%s' % quote(group_name)) logger.debug("GET group: %s", group_get_path) net_logger.info("GET %s", group_get_path) get_group = self.session.get(group_get_path) logger.debug("GET group status: %s", get_group.status_code) if get_group.status_code == 200: api_group_id = get_group.json()['id'] if get_group.status_code == 404: # Group does not exist, POST to create logger.debug("POST group") data = json.dumps({'display_name': group_name}) net_logger.info("POST", group_path) post_group = self.session.post(group_path, headers=headers, data=data) logger.debug("POST group status: %s", post_group.status_code) logger.debug("POST Group: %s", post_group.json()) self.handle_fail_rcs(post_group) api_group_id = post_group.json()['id'] logger.debug("PUT group") data = json.dumps(systems) net_logger.info("PUT %s", group_path + ('/%s/systems' % api_group_id)) put_group = self.session.put(group_path + ('/%s/systems' % api_group_id), headers=headers, data=data) logger.debug("PUT group status: %d", put_group.status_code) logger.debug("PUT Group: %s", put_group.json())
python
def group_systems(self, group_name, systems): """ Adds an array of systems to specified group Args: group_name: Display name of group systems: Array of {'machine_id': machine_id} """ api_group_id = None headers = {'Content-Type': 'application/json'} group_path = self.api_url + '/v1/groups' group_get_path = group_path + ('?display_name=%s' % quote(group_name)) logger.debug("GET group: %s", group_get_path) net_logger.info("GET %s", group_get_path) get_group = self.session.get(group_get_path) logger.debug("GET group status: %s", get_group.status_code) if get_group.status_code == 200: api_group_id = get_group.json()['id'] if get_group.status_code == 404: # Group does not exist, POST to create logger.debug("POST group") data = json.dumps({'display_name': group_name}) net_logger.info("POST", group_path) post_group = self.session.post(group_path, headers=headers, data=data) logger.debug("POST group status: %s", post_group.status_code) logger.debug("POST Group: %s", post_group.json()) self.handle_fail_rcs(post_group) api_group_id = post_group.json()['id'] logger.debug("PUT group") data = json.dumps(systems) net_logger.info("PUT %s", group_path + ('/%s/systems' % api_group_id)) put_group = self.session.put(group_path + ('/%s/systems' % api_group_id), headers=headers, data=data) logger.debug("PUT group status: %d", put_group.status_code) logger.debug("PUT Group: %s", put_group.json())
[ "def", "group_systems", "(", "self", ",", "group_name", ",", "systems", ")", ":", "api_group_id", "=", "None", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", "}", "group_path", "=", "self", ".", "api_url", "+", "'/v1/groups'", "group_get_path"...
Adds an array of systems to specified group Args: group_name: Display name of group systems: Array of {'machine_id': machine_id}
[ "Adds", "an", "array", "of", "systems", "to", "specified", "group" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/connection.py#L511-L552
train
220,790
RedHatInsights/insights-core
insights/client/connection.py
InsightsConnection.do_group
def do_group(self): """ Do grouping on register """ group_id = self.config.group systems = {'machine_id': generate_machine_id()} self.group_systems(group_id, systems)
python
def do_group(self): """ Do grouping on register """ group_id = self.config.group systems = {'machine_id': generate_machine_id()} self.group_systems(group_id, systems)
[ "def", "do_group", "(", "self", ")", ":", "group_id", "=", "self", ".", "config", ".", "group", "systems", "=", "{", "'machine_id'", ":", "generate_machine_id", "(", ")", "}", "self", ".", "group_systems", "(", "group_id", ",", "systems", ")" ]
Do grouping on register
[ "Do", "grouping", "on", "register" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/connection.py#L556-L562
train
220,791
RedHatInsights/insights-core
insights/client/connection.py
InsightsConnection._legacy_api_registration_check
def _legacy_api_registration_check(self): ''' Check registration status through API ''' logger.debug('Checking registration status...') machine_id = generate_machine_id() try: url = self.api_url + '/v1/systems/' + machine_id net_logger.info("GET %s", url) res = self.session.get(url, timeout=self.config.http_timeout) except requests.ConnectionError: # can't connect, run connection test logger.error('Connection timed out. Running connection test...') self.test_connection() return False # had to do a quick bugfix changing this around, # which makes the None-False-True dichotomy seem weird # TODO: reconsider what gets returned, probably this: # True for registered # False for unregistered # None for system 404 try: # check the 'unregistered_at' key of the response unreg_status = json.loads(res.content).get('unregistered_at', 'undefined') # set the global account number self.config.account_number = json.loads(res.content).get('account_number', 'undefined') except ValueError: # bad response, no json object return False if unreg_status == 'undefined': # key not found, machine not yet registered return None elif unreg_status is None: # unregistered_at = null, means this machine IS registered return True else: # machine has been unregistered, this is a timestamp return unreg_status
python
def _legacy_api_registration_check(self): ''' Check registration status through API ''' logger.debug('Checking registration status...') machine_id = generate_machine_id() try: url = self.api_url + '/v1/systems/' + machine_id net_logger.info("GET %s", url) res = self.session.get(url, timeout=self.config.http_timeout) except requests.ConnectionError: # can't connect, run connection test logger.error('Connection timed out. Running connection test...') self.test_connection() return False # had to do a quick bugfix changing this around, # which makes the None-False-True dichotomy seem weird # TODO: reconsider what gets returned, probably this: # True for registered # False for unregistered # None for system 404 try: # check the 'unregistered_at' key of the response unreg_status = json.loads(res.content).get('unregistered_at', 'undefined') # set the global account number self.config.account_number = json.loads(res.content).get('account_number', 'undefined') except ValueError: # bad response, no json object return False if unreg_status == 'undefined': # key not found, machine not yet registered return None elif unreg_status is None: # unregistered_at = null, means this machine IS registered return True else: # machine has been unregistered, this is a timestamp return unreg_status
[ "def", "_legacy_api_registration_check", "(", "self", ")", ":", "logger", ".", "debug", "(", "'Checking registration status...'", ")", "machine_id", "=", "generate_machine_id", "(", ")", "try", ":", "url", "=", "self", ".", "api_url", "+", "'/v1/systems/'", "+", ...
Check registration status through API
[ "Check", "registration", "status", "through", "API" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/connection.py#L565-L602
train
220,792
RedHatInsights/insights-core
insights/client/connection.py
InsightsConnection._fetch_system_by_machine_id
def _fetch_system_by_machine_id(self): ''' Get a system by machine ID Returns dict system exists in inventory False system does not exist in inventory None error connection or parsing response ''' machine_id = generate_machine_id() try: url = self.api_url + '/inventory/v1/hosts?insights_id=' + machine_id net_logger.info("GET %s", url) res = self.session.get(url, timeout=self.config.http_timeout) except (requests.ConnectionError, requests.Timeout) as e: logger.error(e) logger.error('The Insights API could not be reached.') return None try: if (self.handle_fail_rcs(res)): return None res_json = json.loads(res.content) except ValueError as e: logger.error(e) logger.error('Could not parse response body.') return None if res_json['total'] == 0: logger.debug('No hosts found with machine ID: %s', machine_id) return False return res_json['results']
python
def _fetch_system_by_machine_id(self): ''' Get a system by machine ID Returns dict system exists in inventory False system does not exist in inventory None error connection or parsing response ''' machine_id = generate_machine_id() try: url = self.api_url + '/inventory/v1/hosts?insights_id=' + machine_id net_logger.info("GET %s", url) res = self.session.get(url, timeout=self.config.http_timeout) except (requests.ConnectionError, requests.Timeout) as e: logger.error(e) logger.error('The Insights API could not be reached.') return None try: if (self.handle_fail_rcs(res)): return None res_json = json.loads(res.content) except ValueError as e: logger.error(e) logger.error('Could not parse response body.') return None if res_json['total'] == 0: logger.debug('No hosts found with machine ID: %s', machine_id) return False return res_json['results']
[ "def", "_fetch_system_by_machine_id", "(", "self", ")", ":", "machine_id", "=", "generate_machine_id", "(", ")", "try", ":", "url", "=", "self", ".", "api_url", "+", "'/inventory/v1/hosts?insights_id='", "+", "machine_id", "net_logger", ".", "info", "(", "\"GET %s...
Get a system by machine ID Returns dict system exists in inventory False system does not exist in inventory None error connection or parsing response
[ "Get", "a", "system", "by", "machine", "ID", "Returns", "dict", "system", "exists", "in", "inventory", "False", "system", "does", "not", "exist", "in", "inventory", "None", "error", "connection", "or", "parsing", "response" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/connection.py#L604-L632
train
220,793
RedHatInsights/insights-core
insights/client/connection.py
InsightsConnection.api_registration_check
def api_registration_check(self): ''' Reach out to the inventory API to check whether a machine exists. Returns True system exists in inventory False system does not exist in inventory None error connection or parsing response ''' if self.config.legacy_upload: return self._legacy_api_registration_check() logger.debug('Checking registration status...') results = self._fetch_system_by_machine_id() if not results: return results logger.debug('System found.') logger.debug('Machine ID: %s', results[0]['insights_id']) logger.debug('Inventory ID: %s', results[0]['id']) return True
python
def api_registration_check(self): ''' Reach out to the inventory API to check whether a machine exists. Returns True system exists in inventory False system does not exist in inventory None error connection or parsing response ''' if self.config.legacy_upload: return self._legacy_api_registration_check() logger.debug('Checking registration status...') results = self._fetch_system_by_machine_id() if not results: return results logger.debug('System found.') logger.debug('Machine ID: %s', results[0]['insights_id']) logger.debug('Inventory ID: %s', results[0]['id']) return True
[ "def", "api_registration_check", "(", "self", ")", ":", "if", "self", ".", "config", ".", "legacy_upload", ":", "return", "self", ".", "_legacy_api_registration_check", "(", ")", "logger", ".", "debug", "(", "'Checking registration status...'", ")", "results", "="...
Reach out to the inventory API to check whether a machine exists. Returns True system exists in inventory False system does not exist in inventory None error connection or parsing response
[ "Reach", "out", "to", "the", "inventory", "API", "to", "check", "whether", "a", "machine", "exists", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/connection.py#L634-L655
train
220,794
RedHatInsights/insights-core
insights/client/connection.py
InsightsConnection.unregister
def unregister(self): """ Unregister this system from the insights service """ machine_id = generate_machine_id() try: logger.debug("Unregistering %s", machine_id) url = self.api_url + "/v1/systems/" + machine_id net_logger.info("DELETE %s", url) self.session.delete(url) logger.info( "Successfully unregistered from the Red Hat Insights Service") return True except requests.ConnectionError as e: logger.debug(e) logger.error("Could not unregister this system") return False
python
def unregister(self): """ Unregister this system from the insights service """ machine_id = generate_machine_id() try: logger.debug("Unregistering %s", machine_id) url = self.api_url + "/v1/systems/" + machine_id net_logger.info("DELETE %s", url) self.session.delete(url) logger.info( "Successfully unregistered from the Red Hat Insights Service") return True except requests.ConnectionError as e: logger.debug(e) logger.error("Could not unregister this system") return False
[ "def", "unregister", "(", "self", ")", ":", "machine_id", "=", "generate_machine_id", "(", ")", "try", ":", "logger", ".", "debug", "(", "\"Unregistering %s\"", ",", "machine_id", ")", "url", "=", "self", ".", "api_url", "+", "\"/v1/systems/\"", "+", "machin...
Unregister this system from the insights service
[ "Unregister", "this", "system", "from", "the", "insights", "service" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/connection.py#L658-L674
train
220,795
RedHatInsights/insights-core
insights/client/connection.py
InsightsConnection.register
def register(self): """ Register this machine """ client_hostname = determine_hostname() # This will undo a blacklist logger.debug("API: Create system") system = self.create_system(new_machine_id=False) if system is False: return ('Could not reach the Insights service to register.', '', '', '') # If we get a 409, we know we need to generate a new machine-id if system.status_code == 409: system = self.create_system(new_machine_id=True) self.handle_fail_rcs(system) logger.debug("System: %s", system.json()) message = system.headers.get("x-rh-message", "") # Do grouping if self.config.group is not None: self.do_group() # Display registration success messasge to STDOUT and logs if system.status_code == 201: try: system_json = system.json() machine_id = system_json["machine_id"] account_number = system_json["account_number"] logger.info("You successfully registered %s to account %s." % (machine_id, account_number)) except: logger.debug('Received invalid JSON on system registration.') logger.debug('API still indicates valid registration with 201 status code.') logger.debug(system) logger.debug(system.json()) if self.config.group is not None: return (message, client_hostname, self.config.group, self.config.display_name) elif self.config.display_name is not None: return (message, client_hostname, "None", self.config.display_name) else: return (message, client_hostname, "None", "")
python
def register(self): """ Register this machine """ client_hostname = determine_hostname() # This will undo a blacklist logger.debug("API: Create system") system = self.create_system(new_machine_id=False) if system is False: return ('Could not reach the Insights service to register.', '', '', '') # If we get a 409, we know we need to generate a new machine-id if system.status_code == 409: system = self.create_system(new_machine_id=True) self.handle_fail_rcs(system) logger.debug("System: %s", system.json()) message = system.headers.get("x-rh-message", "") # Do grouping if self.config.group is not None: self.do_group() # Display registration success messasge to STDOUT and logs if system.status_code == 201: try: system_json = system.json() machine_id = system_json["machine_id"] account_number = system_json["account_number"] logger.info("You successfully registered %s to account %s." % (machine_id, account_number)) except: logger.debug('Received invalid JSON on system registration.') logger.debug('API still indicates valid registration with 201 status code.') logger.debug(system) logger.debug(system.json()) if self.config.group is not None: return (message, client_hostname, self.config.group, self.config.display_name) elif self.config.display_name is not None: return (message, client_hostname, "None", self.config.display_name) else: return (message, client_hostname, "None", "")
[ "def", "register", "(", "self", ")", ":", "client_hostname", "=", "determine_hostname", "(", ")", "# This will undo a blacklist", "logger", ".", "debug", "(", "\"API: Create system\"", ")", "system", "=", "self", ".", "create_system", "(", "new_machine_id", "=", "...
Register this machine
[ "Register", "this", "machine" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/connection.py#L677-L719
train
220,796
RedHatInsights/insights-core
insights/client/connection.py
InsightsConnection._legacy_upload_archive
def _legacy_upload_archive(self, data_collected, duration): ''' Do an HTTPS upload of the archive ''' file_name = os.path.basename(data_collected) try: from insights.contrib import magic m = magic.open(magic.MAGIC_MIME) m.load() mime_type = m.file(data_collected) except ImportError: magic = None logger.debug('python-magic not installed, using backup function...') from .utilities import magic_plan_b mime_type = magic_plan_b(data_collected) files = { 'file': (file_name, open(data_collected, 'rb'), mime_type)} if self.config.analyze_container: logger.debug('Uploading container, image, mountpoint or tarfile.') upload_url = self.upload_url else: logger.debug('Uploading a host.') upload_url = self.upload_url + '/' + generate_machine_id() logger.debug("Uploading %s to %s", data_collected, upload_url) headers = {'x-rh-collection-time': str(duration)} net_logger.info("POST %s", upload_url) upload = self.session.post(upload_url, files=files, headers=headers) logger.debug("Upload status: %s %s %s", upload.status_code, upload.reason, upload.text) if upload.status_code in (200, 201): the_json = json.loads(upload.text) else: logger.error("Upload archive failed with status code %s", upload.status_code) return upload try: self.config.account_number = the_json["upload"]["account_number"] except: self.config.account_number = None logger.debug("Upload duration: %s", upload.elapsed) return upload
python
def _legacy_upload_archive(self, data_collected, duration): ''' Do an HTTPS upload of the archive ''' file_name = os.path.basename(data_collected) try: from insights.contrib import magic m = magic.open(magic.MAGIC_MIME) m.load() mime_type = m.file(data_collected) except ImportError: magic = None logger.debug('python-magic not installed, using backup function...') from .utilities import magic_plan_b mime_type = magic_plan_b(data_collected) files = { 'file': (file_name, open(data_collected, 'rb'), mime_type)} if self.config.analyze_container: logger.debug('Uploading container, image, mountpoint or tarfile.') upload_url = self.upload_url else: logger.debug('Uploading a host.') upload_url = self.upload_url + '/' + generate_machine_id() logger.debug("Uploading %s to %s", data_collected, upload_url) headers = {'x-rh-collection-time': str(duration)} net_logger.info("POST %s", upload_url) upload = self.session.post(upload_url, files=files, headers=headers) logger.debug("Upload status: %s %s %s", upload.status_code, upload.reason, upload.text) if upload.status_code in (200, 201): the_json = json.loads(upload.text) else: logger.error("Upload archive failed with status code %s", upload.status_code) return upload try: self.config.account_number = the_json["upload"]["account_number"] except: self.config.account_number = None logger.debug("Upload duration: %s", upload.elapsed) return upload
[ "def", "_legacy_upload_archive", "(", "self", ",", "data_collected", ",", "duration", ")", ":", "file_name", "=", "os", ".", "path", ".", "basename", "(", "data_collected", ")", "try", ":", "from", "insights", ".", "contrib", "import", "magic", "m", "=", "...
Do an HTTPS upload of the archive
[ "Do", "an", "HTTPS", "upload", "of", "the", "archive" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/connection.py#L722-L766
train
220,797
RedHatInsights/insights-core
insights/client/connection.py
InsightsConnection.upload_archive
def upload_archive(self, data_collected, content_type, duration): """ Do an HTTPS Upload of the archive """ if self.config.legacy_upload: return self._legacy_upload_archive(data_collected, duration) file_name = os.path.basename(data_collected) upload_url = self.upload_url c_facts = {} try: c_facts = get_canonical_facts() except Exception as e: logger.debug('Error getting canonical facts: %s', e) if self.config.display_name: # add display_name to canonical facts c_facts['display_name'] = self.config.display_name c_facts = json.dumps(c_facts) logger.debug('Canonical facts collected:\n%s', c_facts) files = { 'file': (file_name, open(data_collected, 'rb'), content_type), 'metadata': c_facts } logger.debug("Uploading %s to %s", data_collected, upload_url) net_logger.info("POST %s", upload_url) upload = self.session.post(upload_url, files=files, headers={}) logger.debug("Upload status: %s %s %s", upload.status_code, upload.reason, upload.text) logger.debug('Request ID: %s', upload.headers.get('x-rh-insights-request-id', None)) if upload.status_code == 202: # 202 from platform, no json response logger.debug(upload.text) # upload = registration on platform write_registered_file() else: logger.error( "Upload archive failed with status code %s", upload.status_code) return upload logger.debug("Upload duration: %s", upload.elapsed) return upload
python
def upload_archive(self, data_collected, content_type, duration): """ Do an HTTPS Upload of the archive """ if self.config.legacy_upload: return self._legacy_upload_archive(data_collected, duration) file_name = os.path.basename(data_collected) upload_url = self.upload_url c_facts = {} try: c_facts = get_canonical_facts() except Exception as e: logger.debug('Error getting canonical facts: %s', e) if self.config.display_name: # add display_name to canonical facts c_facts['display_name'] = self.config.display_name c_facts = json.dumps(c_facts) logger.debug('Canonical facts collected:\n%s', c_facts) files = { 'file': (file_name, open(data_collected, 'rb'), content_type), 'metadata': c_facts } logger.debug("Uploading %s to %s", data_collected, upload_url) net_logger.info("POST %s", upload_url) upload = self.session.post(upload_url, files=files, headers={}) logger.debug("Upload status: %s %s %s", upload.status_code, upload.reason, upload.text) logger.debug('Request ID: %s', upload.headers.get('x-rh-insights-request-id', None)) if upload.status_code == 202: # 202 from platform, no json response logger.debug(upload.text) # upload = registration on platform write_registered_file() else: logger.error( "Upload archive failed with status code %s", upload.status_code) return upload logger.debug("Upload duration: %s", upload.elapsed) return upload
[ "def", "upload_archive", "(", "self", ",", "data_collected", ",", "content_type", ",", "duration", ")", ":", "if", "self", ".", "config", ".", "legacy_upload", ":", "return", "self", ".", "_legacy_upload_archive", "(", "data_collected", ",", "duration", ")", "...
Do an HTTPS Upload of the archive
[ "Do", "an", "HTTPS", "Upload", "of", "the", "archive" ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/connection.py#L768-L811
train
220,798
RedHatInsights/insights-core
insights/client/connection.py
InsightsConnection.set_display_name
def set_display_name(self, display_name): ''' Set display name of a system independently of upload. ''' if self.config.legacy_upload: return self._legacy_set_display_name(display_name) system = self._fetch_system_by_machine_id() if not system: return system inventory_id = system[0]['id'] req_url = self.base_url + '/inventory/v1/hosts/' + inventory_id try: net_logger.info("PATCH %s", req_url) res = self.session.patch(req_url, json={'display_name': display_name}) except (requests.ConnectionError, requests.Timeout) as e: logger.error(e) logger.error('The Insights API could not be reached.') return False if (self.handle_fail_rcs(res)): logger.error('Could not update display name.') return False logger.info('Display name updated to ' + display_name + '.') return True
python
def set_display_name(self, display_name): ''' Set display name of a system independently of upload. ''' if self.config.legacy_upload: return self._legacy_set_display_name(display_name) system = self._fetch_system_by_machine_id() if not system: return system inventory_id = system[0]['id'] req_url = self.base_url + '/inventory/v1/hosts/' + inventory_id try: net_logger.info("PATCH %s", req_url) res = self.session.patch(req_url, json={'display_name': display_name}) except (requests.ConnectionError, requests.Timeout) as e: logger.error(e) logger.error('The Insights API could not be reached.') return False if (self.handle_fail_rcs(res)): logger.error('Could not update display name.') return False logger.info('Display name updated to ' + display_name + '.') return True
[ "def", "set_display_name", "(", "self", ",", "display_name", ")", ":", "if", "self", ".", "config", ".", "legacy_upload", ":", "return", "self", ".", "_legacy_set_display_name", "(", "display_name", ")", "system", "=", "self", ".", "_fetch_system_by_machine_id", ...
Set display name of a system independently of upload.
[ "Set", "display", "name", "of", "a", "system", "independently", "of", "upload", "." ]
b57cbf8ed7c089672426ede0441e0a4f789ef4a1
https://github.com/RedHatInsights/insights-core/blob/b57cbf8ed7c089672426ede0441e0a4f789ef4a1/insights/client/connection.py#L851-L874
train
220,799