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
ee.carousel.component.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { FormsModule } from '@angular/forms'; import { IconLoaderService } from '../../../index'; import { AmexioImageComponent } from '../../media/image/image.component'; import { MultiMediaCarouselComponent } from './ee.carousel.component'; import { AmexioRatingComponent } from './../../forms/rating/rating.component'; import { ContentComponent } from '../ee-content/ee.content'; describe('amexio-ee-content', () => { let comp: MultiMediaCarouselComponent; let fixture: ComponentFixture<MultiMediaCarouselComponent>;
declarations: [MultiMediaCarouselComponent, ContentComponent, AmexioRatingComponent, AmexioImageComponent], providers: [IconLoaderService], }); fixture = TestBed.createComponent(MultiMediaCarouselComponent); comp = fixture.componentInstance; }); it('playVideo method check ', () => { let video: any; comp.playVideo(video); comp.onVideoLoad.subscribe((g: any) => { expect(video).toEqual(g); }); }); it('ngOnInit method check ',() => { comp.carouselStyle = 'horizontal'; comp.ngOnInit(); expect(comp.carouselStyle).toBe('horizontal'); }); });
beforeEach(() => { TestBed.configureTestingModule({ imports: [FormsModule],
random_line_split
CreateHeightMap.ts
import { Laya } from "Laya"; import { Camera } from "laya/d3/core/Camera"; import { HeightMap } from "laya/d3/core/HeightMap"; import { MeshSprite3D } from "laya/d3/core/MeshSprite3D"; import { Scene } from "laya/d3/core/scene/Scene"; import { Sprite3D } from "laya/d3/core/Sprite3D"; import { Vector2 } from "laya/d3/math/Vector2"; import { Mesh } from "laya/d3/resource/models/Mesh"; import { Stage } from "laya/display/Stage"; import { Event } from "laya/events/Event"; import { Browser } from "laya/utils/Browser"; import { Laya3D } from "Laya3D"; /** * ... * @author asanwu */ export class CreateHeightMap { //生成高度图的宽度 width: number = 64; //生成高度图的高度 height: number = 64; constructor() { Laya3D.init(0, 0); Laya.st
mber, tGreed: number, tBlue: number, tAlpha: number; tRed = tGreed = tBlue = tAlpha = 0xFF; var tStr: string = ""; var ncanvas: any = Browser.createElement('canvas'); ncanvas.setAttribute('width', tWidth.toString()); ncanvas.setAttribute('height', tHeight.toString()); var ctx: any = ncanvas.getContext("2d"); var tI: number = 0; for (var i: number = 0; i < tHeight; i++) { for (var j: number = 0; j < tWidth; j++) { var oriHeight: number = th.getHeight(i, j); if (isNaN(oriHeight)) { tRed = 255; tGreed = 255; tBlue = 255; } else { var height: number = Math.round((oriHeight - min) / cr); tRed = height; tGreed = height; tBlue = height; } tAlpha = 1; tStr = "rgba(" + tRed.toString() + "," + tGreed.toString() + "," + tBlue.toString() + "," + tAlpha.toString() + ")"; ctx.fillStyle = tStr; ctx.fillRect(j, i, 1, 1); } } var image = ncanvas.toDataURL("image/png").replace("image/png", "image/octet-stream;Content-Disposition: attachment;filename=foobar.png"); window.location.href = image; } }
age.scaleMode = Stage.SCALE_FULL; Laya.stage.screenMode = Stage.SCREEN_HORIZONTAL; var scene: Scene = (<Scene>Laya.stage.addChild(new Scene())); scene.currentCamera = (<Camera>(scene.addChild(new Camera(0, 0.1, 2000)))); //3d场景 var sceneSprite3d: Sprite3D = (<Sprite3D>scene.addChild(Sprite3D.load("maze/maze.lh"))); sceneSprite3d.once(Event.HIERARCHY_LOADED, this, function (): void { var v2: Vector2 = new Vector2(); //获取3d场景中需要采集高度数据的网格精灵,这里需要美术根据场景中可行走区域建模型 var meshSprite3D: MeshSprite3D = (<MeshSprite3D>sceneSprite3d.getChildAt(0)); var heightMap: HeightMap = HeightMap.creatFromMesh((<Mesh>meshSprite3D.meshFilter.sharedMesh), this.width, this.height, v2); var maxHeight: number = heightMap.maxHeight; var minHeight: number = heightMap.minHeight; //获取最大高度和最小高度,使用高度图时需要此数据 console.log("-----------------------------"); console.log(maxHeight, minHeight); console.log("-----------------------------"); var compressionRatio: number = (maxHeight - minHeight) / 254; //把高度数据画到canvas画布上,并保存为png图片 this.pringScreen(this.width, this.height, compressionRatio, minHeight, heightMap); }); } private pringScreen(tWidth: number, tHeight: number, cr: number, min: number, th: HeightMap): void { var pixel: any = Laya.stage.drawToCanvas(tWidth, tHeight, 0, 0); var tRed: nu
identifier_body
CreateHeightMap.ts
import { Laya } from "Laya"; import { Camera } from "laya/d3/core/Camera"; import { HeightMap } from "laya/d3/core/HeightMap"; import { MeshSprite3D } from "laya/d3/core/MeshSprite3D"; import { Scene } from "laya/d3/core/scene/Scene"; import { Sprite3D } from "laya/d3/core/Sprite3D"; import { Vector2 } from "laya/d3/math/Vector2"; import { Mesh } from "laya/d3/resource/models/Mesh"; import { Stage } from "laya/display/Stage"; import { Event } from "laya/events/Event"; import { Browser } from "laya/utils/Browser"; import { Laya3D } from "Laya3D"; /** * ... * @author asanwu */ export class
{ //生成高度图的宽度 width: number = 64; //生成高度图的高度 height: number = 64; constructor() { Laya3D.init(0, 0); Laya.stage.scaleMode = Stage.SCALE_FULL; Laya.stage.screenMode = Stage.SCREEN_HORIZONTAL; var scene: Scene = (<Scene>Laya.stage.addChild(new Scene())); scene.currentCamera = (<Camera>(scene.addChild(new Camera(0, 0.1, 2000)))); //3d场景 var sceneSprite3d: Sprite3D = (<Sprite3D>scene.addChild(Sprite3D.load("maze/maze.lh"))); sceneSprite3d.once(Event.HIERARCHY_LOADED, this, function (): void { var v2: Vector2 = new Vector2(); //获取3d场景中需要采集高度数据的网格精灵,这里需要美术根据场景中可行走区域建模型 var meshSprite3D: MeshSprite3D = (<MeshSprite3D>sceneSprite3d.getChildAt(0)); var heightMap: HeightMap = HeightMap.creatFromMesh((<Mesh>meshSprite3D.meshFilter.sharedMesh), this.width, this.height, v2); var maxHeight: number = heightMap.maxHeight; var minHeight: number = heightMap.minHeight; //获取最大高度和最小高度,使用高度图时需要此数据 console.log("-----------------------------"); console.log(maxHeight, minHeight); console.log("-----------------------------"); var compressionRatio: number = (maxHeight - minHeight) / 254; //把高度数据画到canvas画布上,并保存为png图片 this.pringScreen(this.width, this.height, compressionRatio, minHeight, heightMap); }); } private pringScreen(tWidth: number, tHeight: number, cr: number, min: number, th: HeightMap): void { var pixel: any = Laya.stage.drawToCanvas(tWidth, tHeight, 0, 0); var tRed: number, tGreed: number, tBlue: number, tAlpha: number; tRed = tGreed = tBlue = tAlpha = 0xFF; var tStr: string = ""; var ncanvas: any = Browser.createElement('canvas'); ncanvas.setAttribute('width', tWidth.toString()); ncanvas.setAttribute('height', tHeight.toString()); var ctx: any = ncanvas.getContext("2d"); var tI: number = 0; for (var i: number = 0; i < tHeight; i++) { for (var j: number = 0; j < tWidth; j++) { var oriHeight: number = th.getHeight(i, j); if (isNaN(oriHeight)) { tRed = 255; tGreed = 255; tBlue = 255; } else { var height: number = Math.round((oriHeight - min) / cr); tRed = height; tGreed = height; tBlue = height; } tAlpha = 1; tStr = "rgba(" + tRed.toString() + "," + tGreed.toString() + "," + tBlue.toString() + "," + tAlpha.toString() + ")"; ctx.fillStyle = tStr; ctx.fillRect(j, i, 1, 1); } } var image = ncanvas.toDataURL("image/png").replace("image/png", "image/octet-stream;Content-Disposition: attachment;filename=foobar.png"); window.location.href = image; } }
CreateHeightMap
identifier_name
CreateHeightMap.ts
import { Laya } from "Laya"; import { Camera } from "laya/d3/core/Camera"; import { HeightMap } from "laya/d3/core/HeightMap"; import { MeshSprite3D } from "laya/d3/core/MeshSprite3D"; import { Scene } from "laya/d3/core/scene/Scene"; import { Sprite3D } from "laya/d3/core/Sprite3D"; import { Vector2 } from "laya/d3/math/Vector2"; import { Mesh } from "laya/d3/resource/models/Mesh"; import { Stage } from "laya/display/Stage"; import { Event } from "laya/events/Event"; import { Browser } from "laya/utils/Browser"; import { Laya3D } from "Laya3D"; /** * ... * @author asanwu */ export class CreateHeightMap { //生成高度图的宽度
constructor() { Laya3D.init(0, 0); Laya.stage.scaleMode = Stage.SCALE_FULL; Laya.stage.screenMode = Stage.SCREEN_HORIZONTAL; var scene: Scene = (<Scene>Laya.stage.addChild(new Scene())); scene.currentCamera = (<Camera>(scene.addChild(new Camera(0, 0.1, 2000)))); //3d场景 var sceneSprite3d: Sprite3D = (<Sprite3D>scene.addChild(Sprite3D.load("maze/maze.lh"))); sceneSprite3d.once(Event.HIERARCHY_LOADED, this, function (): void { var v2: Vector2 = new Vector2(); //获取3d场景中需要采集高度数据的网格精灵,这里需要美术根据场景中可行走区域建模型 var meshSprite3D: MeshSprite3D = (<MeshSprite3D>sceneSprite3d.getChildAt(0)); var heightMap: HeightMap = HeightMap.creatFromMesh((<Mesh>meshSprite3D.meshFilter.sharedMesh), this.width, this.height, v2); var maxHeight: number = heightMap.maxHeight; var minHeight: number = heightMap.minHeight; //获取最大高度和最小高度,使用高度图时需要此数据 console.log("-----------------------------"); console.log(maxHeight, minHeight); console.log("-----------------------------"); var compressionRatio: number = (maxHeight - minHeight) / 254; //把高度数据画到canvas画布上,并保存为png图片 this.pringScreen(this.width, this.height, compressionRatio, minHeight, heightMap); }); } private pringScreen(tWidth: number, tHeight: number, cr: number, min: number, th: HeightMap): void { var pixel: any = Laya.stage.drawToCanvas(tWidth, tHeight, 0, 0); var tRed: number, tGreed: number, tBlue: number, tAlpha: number; tRed = tGreed = tBlue = tAlpha = 0xFF; var tStr: string = ""; var ncanvas: any = Browser.createElement('canvas'); ncanvas.setAttribute('width', tWidth.toString()); ncanvas.setAttribute('height', tHeight.toString()); var ctx: any = ncanvas.getContext("2d"); var tI: number = 0; for (var i: number = 0; i < tHeight; i++) { for (var j: number = 0; j < tWidth; j++) { var oriHeight: number = th.getHeight(i, j); if (isNaN(oriHeight)) { tRed = 255; tGreed = 255; tBlue = 255; } else { var height: number = Math.round((oriHeight - min) / cr); tRed = height; tGreed = height; tBlue = height; } tAlpha = 1; tStr = "rgba(" + tRed.toString() + "," + tGreed.toString() + "," + tBlue.toString() + "," + tAlpha.toString() + ")"; ctx.fillStyle = tStr; ctx.fillRect(j, i, 1, 1); } } var image = ncanvas.toDataURL("image/png").replace("image/png", "image/octet-stream;Content-Disposition: attachment;filename=foobar.png"); window.location.href = image; } }
width: number = 64; //生成高度图的高度 height: number = 64;
random_line_split
CreateHeightMap.ts
import { Laya } from "Laya"; import { Camera } from "laya/d3/core/Camera"; import { HeightMap } from "laya/d3/core/HeightMap"; import { MeshSprite3D } from "laya/d3/core/MeshSprite3D"; import { Scene } from "laya/d3/core/scene/Scene"; import { Sprite3D } from "laya/d3/core/Sprite3D"; import { Vector2 } from "laya/d3/math/Vector2"; import { Mesh } from "laya/d3/resource/models/Mesh"; import { Stage } from "laya/display/Stage"; import { Event } from "laya/events/Event"; import { Browser } from "laya/utils/Browser"; import { Laya3D } from "Laya3D"; /** * ... * @author asanwu */ export class CreateHeightMap { //生成高度图的宽度 width: number = 64; //生成高度图的高度 height: number = 64; constructor() { Laya3D.init(0, 0); Laya.stage.scaleMode = Stage.SCALE_FULL; Laya.stage.screenMode = Stage.SCREEN_HORIZONTAL; var scene: Scene = (<Scene>Laya.stage.addChild(new Scene())); scene.currentCamera = (<Camera>(scene.addChild(new Camera(0, 0.1, 2000)))); //3d场景 var sceneSprite3d: Sprite3D = (<Sprite3D>scene.addChild(Sprite3D.load("maze/maze.lh"))); sceneSprite3d.once(Event.HIERARCHY_LOADED, this, function (): void { var v2: Vector2 = new Vector2(); //获取3d场景中需要采集高度数据的网格精灵,这里需要美术根据场景中可行走区域建模型 var meshSprite3D: MeshSprite3D = (<MeshSprite3D>sceneSprite3d.getChildAt(0)); var heightMap: HeightMap = HeightMap.creatFromMesh((<Mesh>meshSprite3D.meshFilter.sharedMesh), this.width, this.height, v2); var maxHeight: number = heightMap.maxHeight; var minHeight: number = heightMap.minHeight; //获取最大高度和最小高度,使用高度图时需要此数据 console.log("-----------------------------"); console.log(maxHeight, minHeight); console.log("-----------------------------"); var compressionRatio: number = (maxHeight - minHeight) / 254; //把高度数据画到canvas画布上,并保存为png图片 this.pringScreen(this.width, this.height, compressionRatio, minHeight, heightMap); }); } private pringScreen(tWidth: number, tHeight: number, cr: number, min: number, th: HeightMap): void { var pixel: any = Laya.stage.drawToCanvas(tWidth, tHeight, 0, 0); var tRed: number, tGreed: number, tBlue: number, tAlpha: number; tRed = tGreed = tBlue = tAlpha = 0xFF; var tStr: string = ""; var ncanvas: any = Browser.createElement('canvas'); ncanvas.setAttribute('width', tWidth.toString()); ncanvas.setAttribute('height', tHeight.toString()); var ctx: any = ncanvas.getContext("2d"); var tI: number = 0; for (var i: number = 0; i < tHeight; i++) { for (var j: number = 0; j < tWidth; j++) { var oriHeight: number = th.getHeight(i, j); if (isNaN(oriHeight)) { tRed = 255; tGreed = 255; tBlue = 255; } else { var height: number = Math.round(
(oriHeight - min) / cr); tRed = height; tGreed = height; tBlue = height; } tAlpha = 1; tStr = "rgba(" + tRed.toString() + "," + tGreed.toString() + "," + tBlue.toString() + "," + tAlpha.toString() + ")"; ctx.fillStyle = tStr; ctx.fillRect(j, i, 1, 1); } } var image = ncanvas.toDataURL("image/png").replace("image/png", "image/octet-stream;Content-Disposition: attachment;filename=foobar.png"); window.location.href = image; } }
conditional_block
robotics.py
""" Classes for using robotic or other hardware using Topographica. This module contains several classes for constructing robotics interfaces to Topographica simulations. It includes modules that read input from or send output to robot devices, and a (quasi) real-time simulation object that attempts to maintain a correspondence between simulation time and real time. This module requires the PlayerStage robot interface system (from playerstage.sourceforge.net), and the playerrobot module for high-level communications with Player robots. """ import Image import ImageOps from math import pi,cos,sin import param from topo.base.simulation import EventProcessor from imagen.image import GenericImage from playerrobot import CameraDevice, PTZDevice class CameraImage(GenericImage): """ An image pattern generator that gets its image from a Player camera device. """ camera = param.ClassSelector(CameraDevice,default=None,doc=""" An instance of playerrobot.CameraDevice to be used to generate images.""") def __init__(self,**params): super(CameraImage,self).__init__(**params) self._image = None def _get_image(self,params): self._decode_image(*self.camera.image) return True def _decode_image(self,fmt,w,h,bpp,fdiv,data): if fmt==1: self._image = Image.new('L',(w,h)) self._image.fromstring(data,'raw') else: # JPALERT: if not grayscale, then assume color. This # should be expanded for other modes. rgb_im = Image.new('RGB',(w,h)) rgb_im.fromstring(data,'raw') self._image = ImageOps.grayscale(rgb_im) class CameraImageQueued(CameraImage): """ A version of CameraImage that gets the image from the camera's image queue, rather than directly from the camera object. Using queues is necessary when running the playerrobot in a separate process without shared memory. When getting an image, this pattern generator will fetch every image in the image queue and use the most recent as the current pattern. """ def _get_image(self,params): im_spec = None if self._image is None: # if we don't have an image then block until we get one im_spec = self.camera.image_queue.get() self.camera.image_queue.task_done() # Make sure we clear the image queue and get the most recent image. while not self.camera.image_queue.empty(): im_spec = self.camera.image_queue.get_nowait() self.camera.image_queue.task_done() if im_spec: # If we got a new image from the queue, then # construct a PIL image from it. self._decode_image(*im_spec) return True else: return False class PTZ(EventProcessor): """ Pan/Tilt/Zoom control. This event processor takes input events on its 'Saccade' input port in the form of (amplitude,direction) saccade commands (as produced by the topo.sheet.saccade.SaccadeController class) and appropriately servoes the attached PTZ object. There is not currently any dynamic zoom control, though the static zoom level can be set as a parameter. """ ptz = param.ClassSelector(PTZDevice,default=None,doc=""" An instance of playerrobot.PTZDevice to be controlled.""") zoom = param.Number(default=120,bounds=(0,None),doc=""" Desired FOV width in degrees.""") speed = param.Number(default=200,bounds=(0,None),doc=""" Desired max pan/tilt speed in deg/sec.""") invert_amplitude = param.Boolean(default=False,doc=""" Invert the sense of the amplitude signal, in order to get the appropriate ipsi-/contralateral sense of saccades.""") dest_ports = ["Saccade"] src_ports = ["State"] def start(self): pass def input_event(self,conn,data): if conn.dest_port == "Saccade": # the data should be (amplitude,direction) amplitude,direction = data self.shift(amplitude,direction) def shift(self,amplitude,direction):
self.debug("Executing shift, amplitude=%.2f, direction=%.2f"%(amplitude,direction)) if self.invert_amplitude: amplitude *= -1 # if the amplitude is negative, invert the direction, so up is still up. if amplitude < 0: direction *= -1 angle = direction * pi/180 pan,tilt,zoom = self.ptz.state_deg pan += amplitude * cos(angle) tilt += amplitude * sin(angle) self.ptz.set_ws_deg(pan,tilt,self.zoom,self.speed,self.speed) ## self.ptz.cmd_queue.put_nowait(('set_ws_deg', ## (pan,tilt,self.zoom,self.speed,self.speed)))
identifier_body
robotics.py
""" Classes for using robotic or other hardware using Topographica. This module contains several classes for constructing robotics interfaces to Topographica simulations. It includes modules that read input from or send output to robot devices, and a (quasi) real-time simulation object that attempts to maintain a correspondence between simulation time and real time. This module requires the PlayerStage robot interface system (from playerstage.sourceforge.net), and the playerrobot module for high-level communications with Player robots. """ import Image import ImageOps from math import pi,cos,sin import param from topo.base.simulation import EventProcessor from imagen.image import GenericImage from playerrobot import CameraDevice, PTZDevice class CameraImage(GenericImage): """ An image pattern generator that gets its image from a Player camera device. """ camera = param.ClassSelector(CameraDevice,default=None,doc=""" An instance of playerrobot.CameraDevice to be used to generate images.""") def __init__(self,**params): super(CameraImage,self).__init__(**params) self._image = None def _get_image(self,params): self._decode_image(*self.camera.image) return True def _decode_image(self,fmt,w,h,bpp,fdiv,data): if fmt==1: self._image = Image.new('L',(w,h)) self._image.fromstring(data,'raw') else: # JPALERT: if not grayscale, then assume color. This # should be expanded for other modes. rgb_im = Image.new('RGB',(w,h)) rgb_im.fromstring(data,'raw') self._image = ImageOps.grayscale(rgb_im) class CameraImageQueued(CameraImage): """ A version of CameraImage that gets the image from the camera's image queue, rather than directly from the camera object. Using queues is necessary when running the playerrobot in a separate process without shared memory. When getting an image, this pattern generator will fetch every image in the image queue and use the most recent as the current pattern. """ def _get_image(self,params): im_spec = None if self._image is None: # if we don't have an image then block until we get one im_spec = self.camera.image_queue.get() self.camera.image_queue.task_done() # Make sure we clear the image queue and get the most recent image. while not self.camera.image_queue.empty(): im_spec = self.camera.image_queue.get_nowait() self.camera.image_queue.task_done() if im_spec: # If we got a new image from the queue, then # construct a PIL image from it. self._decode_image(*im_spec) return True else: return False class PTZ(EventProcessor): """ Pan/Tilt/Zoom control. This event processor takes input events on its 'Saccade' input port in the form of (amplitude,direction) saccade commands (as produced by the topo.sheet.saccade.SaccadeController class) and appropriately servoes the attached PTZ object. There is not currently any dynamic zoom control, though the static zoom level can be set as a parameter. """ ptz = param.ClassSelector(PTZDevice,default=None,doc=""" An instance of playerrobot.PTZDevice to be controlled.""") zoom = param.Number(default=120,bounds=(0,None),doc=""" Desired FOV width in degrees.""") speed = param.Number(default=200,bounds=(0,None),doc=""" Desired max pan/tilt speed in deg/sec.""") invert_amplitude = param.Boolean(default=False,doc=""" Invert the sense of the amplitude signal, in order to get the appropriate ipsi-/contralateral sense of saccades.""") dest_ports = ["Saccade"] src_ports = ["State"] def start(self): pass def input_event(self,conn,data): if conn.dest_port == "Saccade": # the data should be (amplitude,direction)
def shift(self,amplitude,direction): self.debug("Executing shift, amplitude=%.2f, direction=%.2f"%(amplitude,direction)) if self.invert_amplitude: amplitude *= -1 # if the amplitude is negative, invert the direction, so up is still up. if amplitude < 0: direction *= -1 angle = direction * pi/180 pan,tilt,zoom = self.ptz.state_deg pan += amplitude * cos(angle) tilt += amplitude * sin(angle) self.ptz.set_ws_deg(pan,tilt,self.zoom,self.speed,self.speed) ## self.ptz.cmd_queue.put_nowait(('set_ws_deg', ## (pan,tilt,self.zoom,self.speed,self.speed)))
amplitude,direction = data self.shift(amplitude,direction)
conditional_block
robotics.py
""" Classes for using robotic or other hardware using Topographica. This module contains several classes for constructing robotics interfaces to Topographica simulations. It includes modules that read input from or send output to robot devices, and a (quasi) real-time simulation object that attempts to maintain a correspondence between simulation time and real time. This module requires the PlayerStage robot interface system (from playerstage.sourceforge.net), and the playerrobot module for high-level communications with Player robots. """ import Image import ImageOps from math import pi,cos,sin import param from topo.base.simulation import EventProcessor from imagen.image import GenericImage from playerrobot import CameraDevice, PTZDevice class CameraImage(GenericImage): """ An image pattern generator that gets its image from a Player camera device. """ camera = param.ClassSelector(CameraDevice,default=None,doc=""" An instance of playerrobot.CameraDevice to be used to generate images.""") def __init__(self,**params): super(CameraImage,self).__init__(**params) self._image = None def _get_image(self,params): self._decode_image(*self.camera.image) return True def _decode_image(self,fmt,w,h,bpp,fdiv,data): if fmt==1: self._image = Image.new('L',(w,h)) self._image.fromstring(data,'raw') else: # JPALERT: if not grayscale, then assume color. This # should be expanded for other modes. rgb_im = Image.new('RGB',(w,h)) rgb_im.fromstring(data,'raw') self._image = ImageOps.grayscale(rgb_im) class CameraImageQueued(CameraImage): """ A version of CameraImage that gets the image from the camera's image queue, rather than directly from the camera object. Using queues is necessary when running the playerrobot in a separate process without shared memory. When getting an image, this pattern generator will fetch every image in the image queue and use the most recent as the current pattern. """ def _get_image(self,params): im_spec = None if self._image is None: # if we don't have an image then block until we get one im_spec = self.camera.image_queue.get() self.camera.image_queue.task_done() # Make sure we clear the image queue and get the most recent image. while not self.camera.image_queue.empty(): im_spec = self.camera.image_queue.get_nowait() self.camera.image_queue.task_done() if im_spec: # If we got a new image from the queue, then # construct a PIL image from it. self._decode_image(*im_spec) return True else: return False class PTZ(EventProcessor): """ Pan/Tilt/Zoom control. This event processor takes input events on its 'Saccade' input port in the form of (amplitude,direction) saccade commands (as produced by the topo.sheet.saccade.SaccadeController class) and appropriately servoes the attached PTZ object. There is not currently any dynamic zoom control, though the static zoom level can be set as a parameter. """ ptz = param.ClassSelector(PTZDevice,default=None,doc=""" An instance of playerrobot.PTZDevice to be controlled.""") zoom = param.Number(default=120,bounds=(0,None),doc=""" Desired FOV width in degrees.""") speed = param.Number(default=200,bounds=(0,None),doc=""" Desired max pan/tilt speed in deg/sec.""") invert_amplitude = param.Boolean(default=False,doc=""" Invert the sense of the amplitude signal, in order to get the appropriate ipsi-/contralateral sense of saccades.""") dest_ports = ["Saccade"] src_ports = ["State"] def start(self): pass def input_event(self,conn,data): if conn.dest_port == "Saccade": # the data should be (amplitude,direction) amplitude,direction = data self.shift(amplitude,direction) def shift(self,amplitude,direction): self.debug("Executing shift, amplitude=%.2f, direction=%.2f"%(amplitude,direction)) if self.invert_amplitude: amplitude *= -1
pan,tilt,zoom = self.ptz.state_deg pan += amplitude * cos(angle) tilt += amplitude * sin(angle) self.ptz.set_ws_deg(pan,tilt,self.zoom,self.speed,self.speed) ## self.ptz.cmd_queue.put_nowait(('set_ws_deg', ## (pan,tilt,self.zoom,self.speed,self.speed)))
# if the amplitude is negative, invert the direction, so up is still up. if amplitude < 0: direction *= -1 angle = direction * pi/180
random_line_split
robotics.py
""" Classes for using robotic or other hardware using Topographica. This module contains several classes for constructing robotics interfaces to Topographica simulations. It includes modules that read input from or send output to robot devices, and a (quasi) real-time simulation object that attempts to maintain a correspondence between simulation time and real time. This module requires the PlayerStage robot interface system (from playerstage.sourceforge.net), and the playerrobot module for high-level communications with Player robots. """ import Image import ImageOps from math import pi,cos,sin import param from topo.base.simulation import EventProcessor from imagen.image import GenericImage from playerrobot import CameraDevice, PTZDevice class CameraImage(GenericImage): """ An image pattern generator that gets its image from a Player camera device. """ camera = param.ClassSelector(CameraDevice,default=None,doc=""" An instance of playerrobot.CameraDevice to be used to generate images.""") def __init__(self,**params): super(CameraImage,self).__init__(**params) self._image = None def _get_image(self,params): self._decode_image(*self.camera.image) return True def _decode_image(self,fmt,w,h,bpp,fdiv,data): if fmt==1: self._image = Image.new('L',(w,h)) self._image.fromstring(data,'raw') else: # JPALERT: if not grayscale, then assume color. This # should be expanded for other modes. rgb_im = Image.new('RGB',(w,h)) rgb_im.fromstring(data,'raw') self._image = ImageOps.grayscale(rgb_im) class
(CameraImage): """ A version of CameraImage that gets the image from the camera's image queue, rather than directly from the camera object. Using queues is necessary when running the playerrobot in a separate process without shared memory. When getting an image, this pattern generator will fetch every image in the image queue and use the most recent as the current pattern. """ def _get_image(self,params): im_spec = None if self._image is None: # if we don't have an image then block until we get one im_spec = self.camera.image_queue.get() self.camera.image_queue.task_done() # Make sure we clear the image queue and get the most recent image. while not self.camera.image_queue.empty(): im_spec = self.camera.image_queue.get_nowait() self.camera.image_queue.task_done() if im_spec: # If we got a new image from the queue, then # construct a PIL image from it. self._decode_image(*im_spec) return True else: return False class PTZ(EventProcessor): """ Pan/Tilt/Zoom control. This event processor takes input events on its 'Saccade' input port in the form of (amplitude,direction) saccade commands (as produced by the topo.sheet.saccade.SaccadeController class) and appropriately servoes the attached PTZ object. There is not currently any dynamic zoom control, though the static zoom level can be set as a parameter. """ ptz = param.ClassSelector(PTZDevice,default=None,doc=""" An instance of playerrobot.PTZDevice to be controlled.""") zoom = param.Number(default=120,bounds=(0,None),doc=""" Desired FOV width in degrees.""") speed = param.Number(default=200,bounds=(0,None),doc=""" Desired max pan/tilt speed in deg/sec.""") invert_amplitude = param.Boolean(default=False,doc=""" Invert the sense of the amplitude signal, in order to get the appropriate ipsi-/contralateral sense of saccades.""") dest_ports = ["Saccade"] src_ports = ["State"] def start(self): pass def input_event(self,conn,data): if conn.dest_port == "Saccade": # the data should be (amplitude,direction) amplitude,direction = data self.shift(amplitude,direction) def shift(self,amplitude,direction): self.debug("Executing shift, amplitude=%.2f, direction=%.2f"%(amplitude,direction)) if self.invert_amplitude: amplitude *= -1 # if the amplitude is negative, invert the direction, so up is still up. if amplitude < 0: direction *= -1 angle = direction * pi/180 pan,tilt,zoom = self.ptz.state_deg pan += amplitude * cos(angle) tilt += amplitude * sin(angle) self.ptz.set_ws_deg(pan,tilt,self.zoom,self.speed,self.speed) ## self.ptz.cmd_queue.put_nowait(('set_ws_deg', ## (pan,tilt,self.zoom,self.speed,self.speed)))
CameraImageQueued
identifier_name
gash.rs
// // gash.rs // // Reference solution for PS2 // Running on Rust 0.8 // // Special thanks to Kiet Tran for porting code from Rust 0.7 to Rust 0.8. // // University of Virginia - cs4414 Fall 2013 // Weilin Xu, Purnam Jantrania, David Evans // Version 0.2 // // Modified use std::{run, os, libc}; use std::task; fn get_fd(fpath: &str, mode: &str) -> libc::c_int { #[fixed_stack_segment]; #[inline(never)]; unsafe { let fpathbuf = fpath.to_c_str().unwrap(); let modebuf = mode.to_c_str().unwrap(); return libc::fileno(libc::fopen(fpathbuf, modebuf)); } } fn exit(status: libc::c_int) { #[fixed_stack_segment]; #[inline(never)]; unsafe { libc::exit(status); } } fn _handle_cmd(cmd_line: &str, pipe_in: libc::c_int, pipe_out: libc::c_int, pipe_err: libc::c_int, output: bool) -> Option<run::ProcessOutput> { let out_fd = pipe_out; let in_fd = pipe_in; let err_fd = pipe_err; let mut argv: ~[~str] = cmd_line.split_iter(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec(); if argv.len() > 0 { let program = argv.remove(0); let (out_opt, err_opt) = if output { (None, None) } else { (Some(out_fd), Some(err_fd))}; let mut prog = run::Process::new(program, argv, run::ProcessOptions { env: None, dir: None, in_fd: Some(in_fd), out_fd: out_opt, err_fd: err_opt }); let output_opt = if output { Some(prog.finish_with_output()) } else { prog.finish(); None }; // close the pipes after process terminates. if in_fd != 0 {os::close(in_fd);} if out_fd != 1 {os::close(out_fd);} if err_fd != 2 {os::close(err_fd);} return output_opt; } return None; } fn handle_cmd(cmd_line: &str, pipe_in: libc::c_int, pipe_out: libc::c_int, pipe_err: libc::c_int) { _handle_cmd(cmd_line, pipe_in, pipe_out, pipe_err, false); } fn handle_cmd_with_output(cmd_line: &str, pipe_in: libc::c_int) -> Option<run::ProcessOutput> { return _handle_cmd(cmd_line, pipe_in, -1, -1, true); } pub fn handle_cmdline(cmd_line: &str) -> Option<run::ProcessOutput> { // handle pipes let progs: ~[~str] = cmd_line.split_iter('|').map(|x| x.trim().to_owned()).collect(); let mut pipes = ~[]; for _ in range(0, progs.len()-1) { pipes.push(os::pipe()); } if progs.len() == 1 { return handle_cmd_with_output(progs[0], 0); } else
}
{ let mut output_opt = None; for i in range(0, progs.len()) { let prog = progs[i].to_owned(); if i == 0 { let pipe_i = pipes[i]; task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, 0, pipe_i.out, 2)}); } else if i == progs.len() - 1 { let pipe_i_1 = pipes[i-1]; output_opt = handle_cmd_with_output(prog, pipe_i_1.input); } else { let pipe_i = pipes[i]; let pipe_i_1 = pipes[i-1]; task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, pipe_i_1.input, pipe_i.out, 2)}); } } return output_opt; }
conditional_block
gash.rs
// // gash.rs // // Reference solution for PS2 // Running on Rust 0.8 // // Special thanks to Kiet Tran for porting code from Rust 0.7 to Rust 0.8. // // University of Virginia - cs4414 Fall 2013 // Weilin Xu, Purnam Jantrania, David Evans // Version 0.2 // // Modified use std::{run, os, libc}; use std::task; fn get_fd(fpath: &str, mode: &str) -> libc::c_int { #[fixed_stack_segment]; #[inline(never)]; unsafe { let fpathbuf = fpath.to_c_str().unwrap(); let modebuf = mode.to_c_str().unwrap(); return libc::fileno(libc::fopen(fpathbuf, modebuf)); } } fn exit(status: libc::c_int)
fn _handle_cmd(cmd_line: &str, pipe_in: libc::c_int, pipe_out: libc::c_int, pipe_err: libc::c_int, output: bool) -> Option<run::ProcessOutput> { let out_fd = pipe_out; let in_fd = pipe_in; let err_fd = pipe_err; let mut argv: ~[~str] = cmd_line.split_iter(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec(); if argv.len() > 0 { let program = argv.remove(0); let (out_opt, err_opt) = if output { (None, None) } else { (Some(out_fd), Some(err_fd))}; let mut prog = run::Process::new(program, argv, run::ProcessOptions { env: None, dir: None, in_fd: Some(in_fd), out_fd: out_opt, err_fd: err_opt }); let output_opt = if output { Some(prog.finish_with_output()) } else { prog.finish(); None }; // close the pipes after process terminates. if in_fd != 0 {os::close(in_fd);} if out_fd != 1 {os::close(out_fd);} if err_fd != 2 {os::close(err_fd);} return output_opt; } return None; } fn handle_cmd(cmd_line: &str, pipe_in: libc::c_int, pipe_out: libc::c_int, pipe_err: libc::c_int) { _handle_cmd(cmd_line, pipe_in, pipe_out, pipe_err, false); } fn handle_cmd_with_output(cmd_line: &str, pipe_in: libc::c_int) -> Option<run::ProcessOutput> { return _handle_cmd(cmd_line, pipe_in, -1, -1, true); } pub fn handle_cmdline(cmd_line: &str) -> Option<run::ProcessOutput> { // handle pipes let progs: ~[~str] = cmd_line.split_iter('|').map(|x| x.trim().to_owned()).collect(); let mut pipes = ~[]; for _ in range(0, progs.len()-1) { pipes.push(os::pipe()); } if progs.len() == 1 { return handle_cmd_with_output(progs[0], 0); } else { let mut output_opt = None; for i in range(0, progs.len()) { let prog = progs[i].to_owned(); if i == 0 { let pipe_i = pipes[i]; task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, 0, pipe_i.out, 2)}); } else if i == progs.len() - 1 { let pipe_i_1 = pipes[i-1]; output_opt = handle_cmd_with_output(prog, pipe_i_1.input); } else { let pipe_i = pipes[i]; let pipe_i_1 = pipes[i-1]; task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, pipe_i_1.input, pipe_i.out, 2)}); } } return output_opt; } }
{ #[fixed_stack_segment]; #[inline(never)]; unsafe { libc::exit(status); } }
identifier_body
gash.rs
// // gash.rs // // Reference solution for PS2 // Running on Rust 0.8 // // Special thanks to Kiet Tran for porting code from Rust 0.7 to Rust 0.8. // // University of Virginia - cs4414 Fall 2013 // Weilin Xu, Purnam Jantrania, David Evans // Version 0.2 // // Modified use std::{run, os, libc}; use std::task; fn get_fd(fpath: &str, mode: &str) -> libc::c_int { #[fixed_stack_segment]; #[inline(never)]; unsafe { let fpathbuf = fpath.to_c_str().unwrap(); let modebuf = mode.to_c_str().unwrap(); return libc::fileno(libc::fopen(fpathbuf, modebuf)); } } fn exit(status: libc::c_int) { #[fixed_stack_segment]; #[inline(never)]; unsafe { libc::exit(status); } } fn _handle_cmd(cmd_line: &str, pipe_in: libc::c_int, pipe_out: libc::c_int, pipe_err: libc::c_int, output: bool) -> Option<run::ProcessOutput> { let out_fd = pipe_out; let in_fd = pipe_in; let err_fd = pipe_err; let mut argv: ~[~str] = cmd_line.split_iter(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec(); if argv.len() > 0 { let program = argv.remove(0); let (out_opt, err_opt) = if output { (None, None) } else { (Some(out_fd), Some(err_fd))}; let mut prog = run::Process::new(program, argv, run::ProcessOptions { env: None, dir: None, in_fd: Some(in_fd), out_fd: out_opt, err_fd: err_opt }); let output_opt = if output { Some(prog.finish_with_output()) } else { prog.finish(); None }; // close the pipes after process terminates. if in_fd != 0 {os::close(in_fd);} if out_fd != 1 {os::close(out_fd);} if err_fd != 2 {os::close(err_fd);} return output_opt; } return None; } fn handle_cmd(cmd_line: &str, pipe_in: libc::c_int, pipe_out: libc::c_int, pipe_err: libc::c_int) { _handle_cmd(cmd_line, pipe_in, pipe_out, pipe_err, false); } fn handle_cmd_with_output(cmd_line: &str, pipe_in: libc::c_int) -> Option<run::ProcessOutput> { return _handle_cmd(cmd_line, pipe_in, -1, -1, true); } pub fn
(cmd_line: &str) -> Option<run::ProcessOutput> { // handle pipes let progs: ~[~str] = cmd_line.split_iter('|').map(|x| x.trim().to_owned()).collect(); let mut pipes = ~[]; for _ in range(0, progs.len()-1) { pipes.push(os::pipe()); } if progs.len() == 1 { return handle_cmd_with_output(progs[0], 0); } else { let mut output_opt = None; for i in range(0, progs.len()) { let prog = progs[i].to_owned(); if i == 0 { let pipe_i = pipes[i]; task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, 0, pipe_i.out, 2)}); } else if i == progs.len() - 1 { let pipe_i_1 = pipes[i-1]; output_opt = handle_cmd_with_output(prog, pipe_i_1.input); } else { let pipe_i = pipes[i]; let pipe_i_1 = pipes[i-1]; task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, pipe_i_1.input, pipe_i.out, 2)}); } } return output_opt; } }
handle_cmdline
identifier_name
gash.rs
// // gash.rs // // Reference solution for PS2 // Running on Rust 0.8 // // Special thanks to Kiet Tran for porting code from Rust 0.7 to Rust 0.8. // // University of Virginia - cs4414 Fall 2013 // Weilin Xu, Purnam Jantrania, David Evans // Version 0.2 // // Modified use std::{run, os, libc}; use std::task; fn get_fd(fpath: &str, mode: &str) -> libc::c_int { #[fixed_stack_segment]; #[inline(never)]; unsafe { let fpathbuf = fpath.to_c_str().unwrap();
} fn exit(status: libc::c_int) { #[fixed_stack_segment]; #[inline(never)]; unsafe { libc::exit(status); } } fn _handle_cmd(cmd_line: &str, pipe_in: libc::c_int, pipe_out: libc::c_int, pipe_err: libc::c_int, output: bool) -> Option<run::ProcessOutput> { let out_fd = pipe_out; let in_fd = pipe_in; let err_fd = pipe_err; let mut argv: ~[~str] = cmd_line.split_iter(' ').filter_map(|x| if x != "" { Some(x.to_owned()) } else { None }).to_owned_vec(); if argv.len() > 0 { let program = argv.remove(0); let (out_opt, err_opt) = if output { (None, None) } else { (Some(out_fd), Some(err_fd))}; let mut prog = run::Process::new(program, argv, run::ProcessOptions { env: None, dir: None, in_fd: Some(in_fd), out_fd: out_opt, err_fd: err_opt }); let output_opt = if output { Some(prog.finish_with_output()) } else { prog.finish(); None }; // close the pipes after process terminates. if in_fd != 0 {os::close(in_fd);} if out_fd != 1 {os::close(out_fd);} if err_fd != 2 {os::close(err_fd);} return output_opt; } return None; } fn handle_cmd(cmd_line: &str, pipe_in: libc::c_int, pipe_out: libc::c_int, pipe_err: libc::c_int) { _handle_cmd(cmd_line, pipe_in, pipe_out, pipe_err, false); } fn handle_cmd_with_output(cmd_line: &str, pipe_in: libc::c_int) -> Option<run::ProcessOutput> { return _handle_cmd(cmd_line, pipe_in, -1, -1, true); } pub fn handle_cmdline(cmd_line: &str) -> Option<run::ProcessOutput> { // handle pipes let progs: ~[~str] = cmd_line.split_iter('|').map(|x| x.trim().to_owned()).collect(); let mut pipes = ~[]; for _ in range(0, progs.len()-1) { pipes.push(os::pipe()); } if progs.len() == 1 { return handle_cmd_with_output(progs[0], 0); } else { let mut output_opt = None; for i in range(0, progs.len()) { let prog = progs[i].to_owned(); if i == 0 { let pipe_i = pipes[i]; task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, 0, pipe_i.out, 2)}); } else if i == progs.len() - 1 { let pipe_i_1 = pipes[i-1]; output_opt = handle_cmd_with_output(prog, pipe_i_1.input); } else { let pipe_i = pipes[i]; let pipe_i_1 = pipes[i-1]; task::spawn_sched(task::SingleThreaded, ||{handle_cmd(prog, pipe_i_1.input, pipe_i.out, 2)}); } } return output_opt; } }
let modebuf = mode.to_c_str().unwrap(); return libc::fileno(libc::fopen(fpathbuf, modebuf)); }
random_line_split
test_dominating_set.py
#!/usr/bin/env python from nose.tools import ok_ from nose.tools import eq_ import networkx as nx from networkx.algorithms.approximation import min_weighted_dominating_set from networkx.algorithms.approximation import min_edge_dominating_set class TestMinWeightDominatingSet: def test_min_weighted_dominating_set(self): graph = nx.Graph() graph.add_edge(1, 2) graph.add_edge(1, 5) graph.add_edge(2, 3) graph.add_edge(2, 5) graph.add_edge(3, 4) graph.add_edge(3, 6) graph.add_edge(5, 6) vertices = set([1, 2, 3, 4, 5, 6]) # due to ties, this might be hard to test tight bounds dom_set = min_weighted_dominating_set(graph) for vertex in vertices - dom_set: neighbors = set(graph.neighbors(vertex)) ok_(len(neighbors & dom_set) > 0, "Non dominating set found!") def
(self): """Tests that an approximate dominating set for the star graph, even when the center node does not have the smallest integer label, gives just the center node. For more information, see #1527. """ # Create a star graph in which the center node has the highest # label instead of the lowest. G = nx.star_graph(10) G = nx.relabel_nodes(G, {0: 9, 9: 0}) eq_(min_weighted_dominating_set(G), {9}) def test_min_edge_dominating_set(self): graph = nx.path_graph(5) dom_set = min_edge_dominating_set(graph) # this is a crappy way to test, but good enough for now. for edge in graph.edges_iter(): if edge in dom_set: continue else: u, v = edge found = False for dom_edge in dom_set: found |= u == dom_edge[0] or u == dom_edge[1] ok_(found, "Non adjacent edge found!") graph = nx.complete_graph(10) dom_set = min_edge_dominating_set(graph) # this is a crappy way to test, but good enough for now. for edge in graph.edges_iter(): if edge in dom_set: continue else: u, v = edge found = False for dom_edge in dom_set: found |= u == dom_edge[0] or u == dom_edge[1] ok_(found, "Non adjacent edge found!")
test_star_graph
identifier_name
test_dominating_set.py
#!/usr/bin/env python from nose.tools import ok_ from nose.tools import eq_ import networkx as nx from networkx.algorithms.approximation import min_weighted_dominating_set from networkx.algorithms.approximation import min_edge_dominating_set class TestMinWeightDominatingSet: def test_min_weighted_dominating_set(self): graph = nx.Graph() graph.add_edge(1, 2) graph.add_edge(1, 5) graph.add_edge(2, 3) graph.add_edge(2, 5) graph.add_edge(3, 4) graph.add_edge(3, 6) graph.add_edge(5, 6) vertices = set([1, 2, 3, 4, 5, 6]) # due to ties, this might be hard to test tight bounds dom_set = min_weighted_dominating_set(graph) for vertex in vertices - dom_set: neighbors = set(graph.neighbors(vertex)) ok_(len(neighbors & dom_set) > 0, "Non dominating set found!") def test_star_graph(self): """Tests that an approximate dominating set for the star graph, even when the center node does not have the smallest integer label, gives just the center node. For more information, see #1527. """ # Create a star graph in which the center node has the highest # label instead of the lowest. G = nx.star_graph(10) G = nx.relabel_nodes(G, {0: 9, 9: 0}) eq_(min_weighted_dominating_set(G), {9}) def test_min_edge_dominating_set(self): graph = nx.path_graph(5) dom_set = min_edge_dominating_set(graph) # this is a crappy way to test, but good enough for now. for edge in graph.edges_iter():
graph = nx.complete_graph(10) dom_set = min_edge_dominating_set(graph) # this is a crappy way to test, but good enough for now. for edge in graph.edges_iter(): if edge in dom_set: continue else: u, v = edge found = False for dom_edge in dom_set: found |= u == dom_edge[0] or u == dom_edge[1] ok_(found, "Non adjacent edge found!")
if edge in dom_set: continue else: u, v = edge found = False for dom_edge in dom_set: found |= u == dom_edge[0] or u == dom_edge[1] ok_(found, "Non adjacent edge found!")
conditional_block
test_dominating_set.py
#!/usr/bin/env python from nose.tools import ok_ from nose.tools import eq_ import networkx as nx from networkx.algorithms.approximation import min_weighted_dominating_set from networkx.algorithms.approximation import min_edge_dominating_set class TestMinWeightDominatingSet: def test_min_weighted_dominating_set(self): graph = nx.Graph() graph.add_edge(1, 2) graph.add_edge(1, 5) graph.add_edge(2, 3) graph.add_edge(2, 5) graph.add_edge(3, 4) graph.add_edge(3, 6) graph.add_edge(5, 6) vertices = set([1, 2, 3, 4, 5, 6]) # due to ties, this might be hard to test tight bounds dom_set = min_weighted_dominating_set(graph) for vertex in vertices - dom_set: neighbors = set(graph.neighbors(vertex)) ok_(len(neighbors & dom_set) > 0, "Non dominating set found!") def test_star_graph(self): """Tests that an approximate dominating set for the star graph, even when the center node does not have the smallest integer label, gives just the center node. For more information, see #1527. """
G = nx.star_graph(10) G = nx.relabel_nodes(G, {0: 9, 9: 0}) eq_(min_weighted_dominating_set(G), {9}) def test_min_edge_dominating_set(self): graph = nx.path_graph(5) dom_set = min_edge_dominating_set(graph) # this is a crappy way to test, but good enough for now. for edge in graph.edges_iter(): if edge in dom_set: continue else: u, v = edge found = False for dom_edge in dom_set: found |= u == dom_edge[0] or u == dom_edge[1] ok_(found, "Non adjacent edge found!") graph = nx.complete_graph(10) dom_set = min_edge_dominating_set(graph) # this is a crappy way to test, but good enough for now. for edge in graph.edges_iter(): if edge in dom_set: continue else: u, v = edge found = False for dom_edge in dom_set: found |= u == dom_edge[0] or u == dom_edge[1] ok_(found, "Non adjacent edge found!")
# Create a star graph in which the center node has the highest # label instead of the lowest.
random_line_split
test_dominating_set.py
#!/usr/bin/env python from nose.tools import ok_ from nose.tools import eq_ import networkx as nx from networkx.algorithms.approximation import min_weighted_dominating_set from networkx.algorithms.approximation import min_edge_dominating_set class TestMinWeightDominatingSet: def test_min_weighted_dominating_set(self):
def test_star_graph(self): """Tests that an approximate dominating set for the star graph, even when the center node does not have the smallest integer label, gives just the center node. For more information, see #1527. """ # Create a star graph in which the center node has the highest # label instead of the lowest. G = nx.star_graph(10) G = nx.relabel_nodes(G, {0: 9, 9: 0}) eq_(min_weighted_dominating_set(G), {9}) def test_min_edge_dominating_set(self): graph = nx.path_graph(5) dom_set = min_edge_dominating_set(graph) # this is a crappy way to test, but good enough for now. for edge in graph.edges_iter(): if edge in dom_set: continue else: u, v = edge found = False for dom_edge in dom_set: found |= u == dom_edge[0] or u == dom_edge[1] ok_(found, "Non adjacent edge found!") graph = nx.complete_graph(10) dom_set = min_edge_dominating_set(graph) # this is a crappy way to test, but good enough for now. for edge in graph.edges_iter(): if edge in dom_set: continue else: u, v = edge found = False for dom_edge in dom_set: found |= u == dom_edge[0] or u == dom_edge[1] ok_(found, "Non adjacent edge found!")
graph = nx.Graph() graph.add_edge(1, 2) graph.add_edge(1, 5) graph.add_edge(2, 3) graph.add_edge(2, 5) graph.add_edge(3, 4) graph.add_edge(3, 6) graph.add_edge(5, 6) vertices = set([1, 2, 3, 4, 5, 6]) # due to ties, this might be hard to test tight bounds dom_set = min_weighted_dominating_set(graph) for vertex in vertices - dom_set: neighbors = set(graph.neighbors(vertex)) ok_(len(neighbors & dom_set) > 0, "Non dominating set found!")
identifier_body
debug.py
# Based on Rapptz's RoboDanny's repl cog import contextlib import inspect import logging import re import sys import textwrap import traceback from io import StringIO from typing import * from typing import Pattern import discord from discord.ext import commands # i took this from somewhere and i cant remember where md: Pattern = re.compile(r"^(([ \t]*`{3,4})([^\n]*)(?P<code>[\s\S]+?)(^[ \t]*\2))", re.MULTILINE) logger = logging.getLogger(__name__) class BotDebug(object): def __init__(self, client: commands.Bot): self.client = client self.last_eval = None @commands.command(hidden=True) async def exec(self, ctx: commands.Context, *, cmd: str): result, stdout, stderr = await self.run(ctx, cmd, use_exec=True) await self.send_output(ctx, result, stdout, stderr) @commands.command(hidden=True) async def eval(self, ctx: commands.Context, *, cmd: str): scope = {"_": self.last_eval, "last": self.last_eval} result, stdout, stderr = await self.run(ctx, cmd, use_exec=False, extra_scope=scope) self.last_eval = result await self.send_output(ctx, result, stdout, stderr) async def send_output(self, ctx: commands.Context, result: str, stdout: str, stderr: str): print(result, stdout, stderr) if result is not None: await ctx.send(f"Result: `{result}`") if stdout: logger.info(f"exec stdout: \n{stdout}") await ctx.send("stdout:") await self.send_split(ctx, stdout) if stderr: logger.error(f"exec stderr: \n{stderr}") await ctx.send("stderr:") await self.send_split(ctx, stderr) async def run(self, ctx: commands.Context, cmd: str, use_exec: bool, extra_scope: dict=None) -> Tuple[Any, str, str]: if not self.client.is_owner(ctx.author): return None, "", "" # note: exec/eval inserts __builtins__ if a custom version is not defined (or set to {} or whatever) scope: Dict[str, Any] = {'bot': self.client, 'ctx': ctx, 'discord': discord} if extra_scope: scope.update(extra_scope) match: Match = md.match(cmd) code: str = match.group("code").strip() if match else cmd.strip('` \n') logger.info(f"Executing code '{code}'") result = None with std_redirect() as (stdout, stderr): try: if use_exec: # wrap in async function to run in loop and allow await calls func = f"async def run():\n{textwrap.indent(code, ' ')}" exec(func, scope) result = await scope['run']() else:
except (SystemExit, KeyboardInterrupt): raise except Exception: await self.on_error(ctx) else: await ctx.message.add_reaction('✅') return result, stdout.getvalue(), stderr.getvalue() async def on_error(self, ctx: commands.Context): # prepend a "- " to each line and use ```diff``` syntax highlighting to color the error message red. # also strip lines 2 and 3 of the traceback which includes full path to the file, irrelevant for repl code. # yes i know error[:1] is basically error[0] but i want it to stay as a list logger.exception("Error in exec code") error = traceback.format_exc().splitlines() error = textwrap.indent('\n'.join(error[:1] + error[3:]), '- ', lambda x: True) await ctx.send("Traceback:") await self.send_split(ctx, error, prefix="```diff\n") async def send_split(self, ctx: commands.Context, text: str, *, prefix="```\n", postfix="\n```"): max_len = 2000 - (len(prefix) + len(postfix)) text: List[str] = [text[x:x + max_len] for x in range(0, len(text), max_len)] print(text) for message in text: await ctx.send(f"{prefix}{message}{postfix}") @contextlib.contextmanager def std_redirect(): stdout = sys.stdout stderr = sys.stderr sys.stdout = StringIO() sys.stderr = StringIO() yield sys.stdout, sys.stderr sys.stdout = stdout sys.stderr = stderr def init(bot: commands.Bot, cfg: dict): bot.add_cog(BotDebug(bot))
result = eval(code, scope) # eval doesn't allow `await` if inspect.isawaitable(result): result = await result
conditional_block
debug.py
# Based on Rapptz's RoboDanny's repl cog import contextlib import inspect import logging import re import sys import textwrap import traceback from io import StringIO from typing import * from typing import Pattern import discord from discord.ext import commands # i took this from somewhere and i cant remember where md: Pattern = re.compile(r"^(([ \t]*`{3,4})([^\n]*)(?P<code>[\s\S]+?)(^[ \t]*\2))", re.MULTILINE) logger = logging.getLogger(__name__) class BotDebug(object): def __init__(self, client: commands.Bot): self.client = client self.last_eval = None @commands.command(hidden=True) async def exec(self, ctx: commands.Context, *, cmd: str): result, stdout, stderr = await self.run(ctx, cmd, use_exec=True) await self.send_output(ctx, result, stdout, stderr) @commands.command(hidden=True) async def eval(self, ctx: commands.Context, *, cmd: str): scope = {"_": self.last_eval, "last": self.last_eval} result, stdout, stderr = await self.run(ctx, cmd, use_exec=False, extra_scope=scope) self.last_eval = result await self.send_output(ctx, result, stdout, stderr) async def send_output(self, ctx: commands.Context, result: str, stdout: str, stderr: str): print(result, stdout, stderr) if result is not None: await ctx.send(f"Result: `{result}`") if stdout: logger.info(f"exec stdout: \n{stdout}") await ctx.send("stdout:") await self.send_split(ctx, stdout) if stderr: logger.error(f"exec stderr: \n{stderr}") await ctx.send("stderr:") await self.send_split(ctx, stderr) async def run(self, ctx: commands.Context, cmd: str, use_exec: bool, extra_scope: dict=None) -> Tuple[Any, str, str]: if not self.client.is_owner(ctx.author): return None, "", "" # note: exec/eval inserts __builtins__ if a custom version is not defined (or set to {} or whatever) scope: Dict[str, Any] = {'bot': self.client, 'ctx': ctx, 'discord': discord} if extra_scope: scope.update(extra_scope) match: Match = md.match(cmd) code: str = match.group("code").strip() if match else cmd.strip('` \n') logger.info(f"Executing code '{code}'") result = None with std_redirect() as (stdout, stderr): try: if use_exec: # wrap in async function to run in loop and allow await calls func = f"async def run():\n{textwrap.indent(code, ' ')}" exec(func, scope) result = await scope['run']() else: result = eval(code, scope) # eval doesn't allow `await` if inspect.isawaitable(result): result = await result except (SystemExit, KeyboardInterrupt): raise except Exception: await self.on_error(ctx) else: await ctx.message.add_reaction('✅') return result, stdout.getvalue(), stderr.getvalue() async def on_error(self, ctx: commands.Context): # prepend a "- " to each line and use ```diff``` syntax highlighting to color the error message red. # also strip lines 2 and 3 of the traceback which includes full path to the file, irrelevant for repl code. # yes i know error[:1] is basically error[0] but i want it to stay as a list logger.exception("Error in exec code") error = traceback.format_exc().splitlines() error = textwrap.indent('\n'.join(error[:1] + error[3:]), '- ', lambda x: True) await ctx.send("Traceback:") await self.send_split(ctx, error, prefix="```diff\n") async def send_split(self, ctx: commands.Context, text: str, *, prefix="```\n", postfix="\n```"): max_len = 2000 - (len(prefix) + len(postfix)) text: List[str] = [text[x:x + max_len] for x in range(0, len(text), max_len)] print(text) for message in text: await ctx.send(f"{prefix}{message}{postfix}") @contextlib.contextmanager def std_redirect(): stdout = sys.stdout stderr = sys.stderr sys.stdout = StringIO() sys.stderr = StringIO() yield sys.stdout, sys.stderr sys.stdout = stdout sys.stderr = stderr def init(bot: commands.Bot, cfg: dict): bo
t.add_cog(BotDebug(bot))
identifier_body
debug.py
# Based on Rapptz's RoboDanny's repl cog import contextlib import inspect import logging import re import sys import textwrap import traceback from io import StringIO from typing import * from typing import Pattern import discord from discord.ext import commands # i took this from somewhere and i cant remember where md: Pattern = re.compile(r"^(([ \t]*`{3,4})([^\n]*)(?P<code>[\s\S]+?)(^[ \t]*\2))", re.MULTILINE) logger = logging.getLogger(__name__) class BotDebug(object): def __init__(self, client: commands.Bot): self.client = client self.last_eval = None @commands.command(hidden=True) async def exec(self, ctx: commands.Context, *, cmd: str): result, stdout, stderr = await self.run(ctx, cmd, use_exec=True) await self.send_output(ctx, result, stdout, stderr) @commands.command(hidden=True) async def eval(self, ctx: commands.Context, *, cmd: str): scope = {"_": self.last_eval, "last": self.last_eval} result, stdout, stderr = await self.run(ctx, cmd, use_exec=False, extra_scope=scope) self.last_eval = result await self.send_output(ctx, result, stdout, stderr) async def send_output(self, ctx: commands.Context, result: str, stdout: str, stderr: str): print(result, stdout, stderr) if result is not None: await ctx.send(f"Result: `{result}`") if stdout: logger.info(f"exec stdout: \n{stdout}") await ctx.send("stdout:") await self.send_split(ctx, stdout) if stderr: logger.error(f"exec stderr: \n{stderr}") await ctx.send("stderr:") await self.send_split(ctx, stderr) async def run(self, ctx: commands.Context, cmd: str, use_exec: bool, extra_scope: dict=None) -> Tuple[Any, str, str]: if not self.client.is_owner(ctx.author): return None, "", "" # note: exec/eval inserts __builtins__ if a custom version is not defined (or set to {} or whatever) scope: Dict[str, Any] = {'bot': self.client, 'ctx': ctx, 'discord': discord} if extra_scope: scope.update(extra_scope) match: Match = md.match(cmd) code: str = match.group("code").strip() if match else cmd.strip('` \n') logger.info(f"Executing code '{code}'") result = None with std_redirect() as (stdout, stderr): try: if use_exec: # wrap in async function to run in loop and allow await calls func = f"async def run():\n{textwrap.indent(code, ' ')}" exec(func, scope) result = await scope['run']() else: result = eval(code, scope) # eval doesn't allow `await` if inspect.isawaitable(result): result = await result except (SystemExit, KeyboardInterrupt): raise except Exception: await self.on_error(ctx) else: await ctx.message.add_reaction('✅') return result, stdout.getvalue(), stderr.getvalue() async def on_error(self, ctx: commands.Context): # prepend a "- " to each line and use ```diff``` syntax highlighting to color the error message red. # also strip lines 2 and 3 of the traceback which includes full path to the file, irrelevant for repl code. # yes i know error[:1] is basically error[0] but i want it to stay as a list logger.exception("Error in exec code") error = traceback.format_exc().splitlines() error = textwrap.indent('\n'.join(error[:1] + error[3:]), '- ', lambda x: True) await ctx.send("Traceback:") await self.send_split(ctx, error, prefix="```diff\n") async def send_split(self, ctx: commands.Context, text: str, *, prefix="```\n", postfix="\n```"): max_len = 2000 - (len(prefix) + len(postfix)) text: List[str] = [text[x:x + max_len] for x in range(0, len(text), max_len)] print(text) for message in text: await ctx.send(f"{prefix}{message}{postfix}") @contextlib.contextmanager def std_redirect(): stdout = sys.stdout stderr = sys.stderr sys.stdout = StringIO() sys.stderr = StringIO() yield sys.stdout, sys.stderr sys.stdout = stdout sys.stderr = stderr def in
ot: commands.Bot, cfg: dict): bot.add_cog(BotDebug(bot))
it(b
identifier_name
debug.py
# Based on Rapptz's RoboDanny's repl cog import contextlib import inspect import logging import re import sys import textwrap import traceback from io import StringIO
from discord.ext import commands # i took this from somewhere and i cant remember where md: Pattern = re.compile(r"^(([ \t]*`{3,4})([^\n]*)(?P<code>[\s\S]+?)(^[ \t]*\2))", re.MULTILINE) logger = logging.getLogger(__name__) class BotDebug(object): def __init__(self, client: commands.Bot): self.client = client self.last_eval = None @commands.command(hidden=True) async def exec(self, ctx: commands.Context, *, cmd: str): result, stdout, stderr = await self.run(ctx, cmd, use_exec=True) await self.send_output(ctx, result, stdout, stderr) @commands.command(hidden=True) async def eval(self, ctx: commands.Context, *, cmd: str): scope = {"_": self.last_eval, "last": self.last_eval} result, stdout, stderr = await self.run(ctx, cmd, use_exec=False, extra_scope=scope) self.last_eval = result await self.send_output(ctx, result, stdout, stderr) async def send_output(self, ctx: commands.Context, result: str, stdout: str, stderr: str): print(result, stdout, stderr) if result is not None: await ctx.send(f"Result: `{result}`") if stdout: logger.info(f"exec stdout: \n{stdout}") await ctx.send("stdout:") await self.send_split(ctx, stdout) if stderr: logger.error(f"exec stderr: \n{stderr}") await ctx.send("stderr:") await self.send_split(ctx, stderr) async def run(self, ctx: commands.Context, cmd: str, use_exec: bool, extra_scope: dict=None) -> Tuple[Any, str, str]: if not self.client.is_owner(ctx.author): return None, "", "" # note: exec/eval inserts __builtins__ if a custom version is not defined (or set to {} or whatever) scope: Dict[str, Any] = {'bot': self.client, 'ctx': ctx, 'discord': discord} if extra_scope: scope.update(extra_scope) match: Match = md.match(cmd) code: str = match.group("code").strip() if match else cmd.strip('` \n') logger.info(f"Executing code '{code}'") result = None with std_redirect() as (stdout, stderr): try: if use_exec: # wrap in async function to run in loop and allow await calls func = f"async def run():\n{textwrap.indent(code, ' ')}" exec(func, scope) result = await scope['run']() else: result = eval(code, scope) # eval doesn't allow `await` if inspect.isawaitable(result): result = await result except (SystemExit, KeyboardInterrupt): raise except Exception: await self.on_error(ctx) else: await ctx.message.add_reaction('✅') return result, stdout.getvalue(), stderr.getvalue() async def on_error(self, ctx: commands.Context): # prepend a "- " to each line and use ```diff``` syntax highlighting to color the error message red. # also strip lines 2 and 3 of the traceback which includes full path to the file, irrelevant for repl code. # yes i know error[:1] is basically error[0] but i want it to stay as a list logger.exception("Error in exec code") error = traceback.format_exc().splitlines() error = textwrap.indent('\n'.join(error[:1] + error[3:]), '- ', lambda x: True) await ctx.send("Traceback:") await self.send_split(ctx, error, prefix="```diff\n") async def send_split(self, ctx: commands.Context, text: str, *, prefix="```\n", postfix="\n```"): max_len = 2000 - (len(prefix) + len(postfix)) text: List[str] = [text[x:x + max_len] for x in range(0, len(text), max_len)] print(text) for message in text: await ctx.send(f"{prefix}{message}{postfix}") @contextlib.contextmanager def std_redirect(): stdout = sys.stdout stderr = sys.stderr sys.stdout = StringIO() sys.stderr = StringIO() yield sys.stdout, sys.stderr sys.stdout = stdout sys.stderr = stderr def init(bot: commands.Bot, cfg: dict): bot.add_cog(BotDebug(bot))
from typing import * from typing import Pattern import discord
random_line_split
bypass-security.component.ts
// #docplaster
import { Component } from '@angular/core'; import { DomSanitizer, SafeResourceUrl, SafeUrl } from '@angular/platform-browser'; @Component({ selector: 'app-bypass-security', templateUrl: './bypass-security.component.html', }) export class BypassSecurityComponent { dangerousUrl: string; trustedUrl: SafeUrl; dangerousVideoUrl!: string; videoUrl!: SafeResourceUrl; // #docregion trust-url constructor(private sanitizer: DomSanitizer) { // javascript: URLs are dangerous if attacker controlled. // Angular sanitizes them in data binding, but you can // explicitly tell Angular to trust this value: this.dangerousUrl = 'javascript:alert("Hi there")'; this.trustedUrl = sanitizer.bypassSecurityTrustUrl(this.dangerousUrl); // #enddocregion trust-url this.updateVideoUrl('PUBnlbjZFAI'); } // #docregion trust-video-url updateVideoUrl(id: string) { // Appending an ID to a YouTube URL is safe. // Always make sure to construct SafeValue objects as // close as possible to the input data so // that it's easier to check if the value is safe. this.dangerousVideoUrl = 'https://www.youtube.com/embed/' + id; this.videoUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.dangerousVideoUrl); } // #enddocregion trust-video-url }
// #docregion
random_line_split
bypass-security.component.ts
// #docplaster // #docregion import { Component } from '@angular/core'; import { DomSanitizer, SafeResourceUrl, SafeUrl } from '@angular/platform-browser'; @Component({ selector: 'app-bypass-security', templateUrl: './bypass-security.component.html', }) export class BypassSecurityComponent { dangerousUrl: string; trustedUrl: SafeUrl; dangerousVideoUrl!: string; videoUrl!: SafeResourceUrl; // #docregion trust-url
(private sanitizer: DomSanitizer) { // javascript: URLs are dangerous if attacker controlled. // Angular sanitizes them in data binding, but you can // explicitly tell Angular to trust this value: this.dangerousUrl = 'javascript:alert("Hi there")'; this.trustedUrl = sanitizer.bypassSecurityTrustUrl(this.dangerousUrl); // #enddocregion trust-url this.updateVideoUrl('PUBnlbjZFAI'); } // #docregion trust-video-url updateVideoUrl(id: string) { // Appending an ID to a YouTube URL is safe. // Always make sure to construct SafeValue objects as // close as possible to the input data so // that it's easier to check if the value is safe. this.dangerousVideoUrl = 'https://www.youtube.com/embed/' + id; this.videoUrl = this.sanitizer.bypassSecurityTrustResourceUrl(this.dangerousVideoUrl); } // #enddocregion trust-video-url }
constructor
identifier_name
mpd_mediaplayer_it.ts
<?xml version="1.0" ?><!DOCTYPE TS><TS language="it" version="2.1"> <context> <name>@default</name> <message> <source>MediaPlayer</source> <translation>MediaPlayer</translation> </message>
<source>General</source> <translation>Generale</translation> </message> <message> <source>Media Player Daemon Settings</source> <translation>Impostazioni Demone Media Player</translation> </message> <message> <source>Host</source> <translation>Host</translation> </message> <message> <source>Media Player Daemon server address</source> <translation>Indirizzo del server del Demone Media Player</translation> </message> <message> <source>Port</source> <translation>Porta</translation> </message> <message> <source>Port number MPD is listening on</source> <translation>Il numero della porta MPD è in ascolto</translation> </message> <message> <source>Connection timeout (seconds)</source> <translation>Scadenza connessione (secondi)</translation> </message> <message> <source>Number of seconds before the connection is terminated</source> <translation>Numero di secondi prima del termine della connessione</translation> </message> </context> <context> <name>MPDMediaPlayer</name> <message> <source>Unknown</source> <translation>Sconosciuto</translation> </message> </context> </TS>
<message>
random_line_split
move-nodetest.js
'use strict'; var expect = require('chai').expect; var ember = require('ember-cli/tests/helpers/ember'); var MockUI = require('ember-cli/tests/helpers/mock-ui'); var MockAnalytics = require('ember-cli/tests/helpers/mock-analytics'); var Command = require('ember-cli/lib/models/command'); var Task = require('ember-cli/lib/models/task'); var Promise = require('ember-cli/lib/ext/promise'); var RSVP = require('rsvp'); var fs = require('fs-extra'); var path = require('path'); var exec = Promise.denodeify(require('child_process').exec); var remove = Promise.denodeify(fs.remove); var ensureFile = Promise.denodeify(fs.ensureFile); var root = process.cwd(); var tmp = require('tmp-sync'); var tmproot = path.join(root, 'tmp'); var MoveCommandBase = require('../../../lib/commands/move'); describe('move command', function() { var ui; var tasks; var analytics; var project; var fakeSpawn; var CommandUnderTest; var buildTaskCalled; var buildTaskReceivedProject; var tmpdir; before(function() { CommandUnderTest = Command.extend(MoveCommandBase); }); beforeEach(function() { buildTaskCalled = false; ui = new MockUI(); analytics = new MockAnalytics(); tasks = { Build: Task.extend({ run: function() { buildTaskCalled = true; buildTaskReceivedProject = !!this.project; return RSVP.resolve(); } }) }; project = { isEmberCLIProject: function() { return true; } }; }); function setupGit()
function generateFile(path) { return ensureFile(path); } function addFileToGit(path) { return ensureFile(path) .then(function() { return exec('git add .'); }); } function addFilesToGit(files) { var filesToAdd = files.map(addFileToGit); return RSVP.all(filesToAdd); } function setupForMove() { return setupTmpDir() // .then(setupGit) .then(addFilesToGit.bind(null,['foo.js','bar.js'])); } function setupTmpDir() { return Promise.resolve() .then(function(){ tmpdir = tmp.in(tmproot); process.chdir(tmpdir); return tmpdir; }); } function cleanupTmpDir() { return Promise.resolve() .then(function(){ process.chdir(root); return remove(tmproot); }); } /* afterEach(function() { process.chdir(root); return remove(tmproot); }); */ /* //TODO: fix so this isn't moving the fixtures it('smoke test', function() { return new CommandUnderTest({ ui: ui, analytics: analytics, project: project, environment: { }, tasks: tasks, settings: {}, runCommand: function(command, args) { expect.deepEqual(args, ['./tests/fixtures/smoke-test/foo.js', './tests/fixtures/smoke-test/bar.js']); } }).validateAndRun(['./tests/fixtures/smoke-test/foo.js', './tests/fixtures/smoke-test/bar.js']); }); */ it('exits for unversioned file', function() { return setupTmpDir() .then(function(){ fs.writeFileSync('foo.js','foo'); return new CommandUnderTest({ ui: ui, analytics: analytics, project: project, environment: { }, tasks: tasks, settings: {}, runCommand: function(command, args) { expect.deepEqual(args, ['nope.js']); } }).validateAndRun(['nope.js']).then(function() { expect(ui.output).to.include('nope.js'); expect(ui.output).to.include('The source path: nope.js does not exist.'); }); }) .then(cleanupTmpDir); }); it('can move a file', function() { return setupForMove(). then(function(result) { console.log('result',result); return new CommandUnderTest({ ui: ui, analytics: analytics, project: project, environment: { }, tasks: tasks, settings: {}, runCommand: function(command, args) { expect.deepEqual(args, ['foo.js', 'foo-bar.js']); } }).validateAndRun(['foo.js', 'foo-bar.js']).then(function() { expect(ui.output).to.include('foo.js'); // expect(ui.output).to.include('The source path: nope.js does not exist.'); }); }) .then(cleanupTmpDir); }); });
{ return exec('git --version') .then(function(){ return exec('git rev-parse --is-inside-work-tree', { encoding: 'utf8' }) .then(function(result) { console.log('result',result) return; // return exec('git init'); }) .catch(function(e){ return exec('git init'); }); }); }
identifier_body
move-nodetest.js
'use strict'; var expect = require('chai').expect; var ember = require('ember-cli/tests/helpers/ember'); var MockUI = require('ember-cli/tests/helpers/mock-ui'); var MockAnalytics = require('ember-cli/tests/helpers/mock-analytics'); var Command = require('ember-cli/lib/models/command'); var Task = require('ember-cli/lib/models/task'); var Promise = require('ember-cli/lib/ext/promise'); var RSVP = require('rsvp'); var fs = require('fs-extra'); var path = require('path'); var exec = Promise.denodeify(require('child_process').exec); var remove = Promise.denodeify(fs.remove); var ensureFile = Promise.denodeify(fs.ensureFile); var root = process.cwd(); var tmp = require('tmp-sync'); var tmproot = path.join(root, 'tmp'); var MoveCommandBase = require('../../../lib/commands/move'); describe('move command', function() { var ui; var tasks; var analytics; var project; var fakeSpawn; var CommandUnderTest; var buildTaskCalled; var buildTaskReceivedProject; var tmpdir; before(function() { CommandUnderTest = Command.extend(MoveCommandBase); }); beforeEach(function() { buildTaskCalled = false; ui = new MockUI(); analytics = new MockAnalytics(); tasks = { Build: Task.extend({ run: function() { buildTaskCalled = true; buildTaskReceivedProject = !!this.project; return RSVP.resolve(); } }) }; project = { isEmberCLIProject: function() { return true; } }; }); function setupGit() { return exec('git --version') .then(function(){ return exec('git rev-parse --is-inside-work-tree', { encoding: 'utf8' }) .then(function(result) { console.log('result',result) return; // return exec('git init'); }) .catch(function(e){ return exec('git init'); }); }); } function generateFile(path) { return ensureFile(path); } function addFileToGit(path) { return ensureFile(path) .then(function() { return exec('git add .'); }); } function addFilesToGit(files) { var filesToAdd = files.map(addFileToGit); return RSVP.all(filesToAdd); } function setupForMove() { return setupTmpDir() // .then(setupGit) .then(addFilesToGit.bind(null,['foo.js','bar.js'])); } function setupTmpDir() { return Promise.resolve() .then(function(){ tmpdir = tmp.in(tmproot); process.chdir(tmpdir); return tmpdir; }); } function cleanupTmpDir() { return Promise.resolve() .then(function(){ process.chdir(root); return remove(tmproot); }); } /* afterEach(function() { process.chdir(root); return remove(tmproot);
}); */ /* //TODO: fix so this isn't moving the fixtures it('smoke test', function() { return new CommandUnderTest({ ui: ui, analytics: analytics, project: project, environment: { }, tasks: tasks, settings: {}, runCommand: function(command, args) { expect.deepEqual(args, ['./tests/fixtures/smoke-test/foo.js', './tests/fixtures/smoke-test/bar.js']); } }).validateAndRun(['./tests/fixtures/smoke-test/foo.js', './tests/fixtures/smoke-test/bar.js']); }); */ it('exits for unversioned file', function() { return setupTmpDir() .then(function(){ fs.writeFileSync('foo.js','foo'); return new CommandUnderTest({ ui: ui, analytics: analytics, project: project, environment: { }, tasks: tasks, settings: {}, runCommand: function(command, args) { expect.deepEqual(args, ['nope.js']); } }).validateAndRun(['nope.js']).then(function() { expect(ui.output).to.include('nope.js'); expect(ui.output).to.include('The source path: nope.js does not exist.'); }); }) .then(cleanupTmpDir); }); it('can move a file', function() { return setupForMove(). then(function(result) { console.log('result',result); return new CommandUnderTest({ ui: ui, analytics: analytics, project: project, environment: { }, tasks: tasks, settings: {}, runCommand: function(command, args) { expect.deepEqual(args, ['foo.js', 'foo-bar.js']); } }).validateAndRun(['foo.js', 'foo-bar.js']).then(function() { expect(ui.output).to.include('foo.js'); // expect(ui.output).to.include('The source path: nope.js does not exist.'); }); }) .then(cleanupTmpDir); }); });
random_line_split
move-nodetest.js
'use strict'; var expect = require('chai').expect; var ember = require('ember-cli/tests/helpers/ember'); var MockUI = require('ember-cli/tests/helpers/mock-ui'); var MockAnalytics = require('ember-cli/tests/helpers/mock-analytics'); var Command = require('ember-cli/lib/models/command'); var Task = require('ember-cli/lib/models/task'); var Promise = require('ember-cli/lib/ext/promise'); var RSVP = require('rsvp'); var fs = require('fs-extra'); var path = require('path'); var exec = Promise.denodeify(require('child_process').exec); var remove = Promise.denodeify(fs.remove); var ensureFile = Promise.denodeify(fs.ensureFile); var root = process.cwd(); var tmp = require('tmp-sync'); var tmproot = path.join(root, 'tmp'); var MoveCommandBase = require('../../../lib/commands/move'); describe('move command', function() { var ui; var tasks; var analytics; var project; var fakeSpawn; var CommandUnderTest; var buildTaskCalled; var buildTaskReceivedProject; var tmpdir; before(function() { CommandUnderTest = Command.extend(MoveCommandBase); }); beforeEach(function() { buildTaskCalled = false; ui = new MockUI(); analytics = new MockAnalytics(); tasks = { Build: Task.extend({ run: function() { buildTaskCalled = true; buildTaskReceivedProject = !!this.project; return RSVP.resolve(); } }) }; project = { isEmberCLIProject: function() { return true; } }; }); function setupGit() { return exec('git --version') .then(function(){ return exec('git rev-parse --is-inside-work-tree', { encoding: 'utf8' }) .then(function(result) { console.log('result',result) return; // return exec('git init'); }) .catch(function(e){ return exec('git init'); }); }); } function generateFile(path) { return ensureFile(path); } function
(path) { return ensureFile(path) .then(function() { return exec('git add .'); }); } function addFilesToGit(files) { var filesToAdd = files.map(addFileToGit); return RSVP.all(filesToAdd); } function setupForMove() { return setupTmpDir() // .then(setupGit) .then(addFilesToGit.bind(null,['foo.js','bar.js'])); } function setupTmpDir() { return Promise.resolve() .then(function(){ tmpdir = tmp.in(tmproot); process.chdir(tmpdir); return tmpdir; }); } function cleanupTmpDir() { return Promise.resolve() .then(function(){ process.chdir(root); return remove(tmproot); }); } /* afterEach(function() { process.chdir(root); return remove(tmproot); }); */ /* //TODO: fix so this isn't moving the fixtures it('smoke test', function() { return new CommandUnderTest({ ui: ui, analytics: analytics, project: project, environment: { }, tasks: tasks, settings: {}, runCommand: function(command, args) { expect.deepEqual(args, ['./tests/fixtures/smoke-test/foo.js', './tests/fixtures/smoke-test/bar.js']); } }).validateAndRun(['./tests/fixtures/smoke-test/foo.js', './tests/fixtures/smoke-test/bar.js']); }); */ it('exits for unversioned file', function() { return setupTmpDir() .then(function(){ fs.writeFileSync('foo.js','foo'); return new CommandUnderTest({ ui: ui, analytics: analytics, project: project, environment: { }, tasks: tasks, settings: {}, runCommand: function(command, args) { expect.deepEqual(args, ['nope.js']); } }).validateAndRun(['nope.js']).then(function() { expect(ui.output).to.include('nope.js'); expect(ui.output).to.include('The source path: nope.js does not exist.'); }); }) .then(cleanupTmpDir); }); it('can move a file', function() { return setupForMove(). then(function(result) { console.log('result',result); return new CommandUnderTest({ ui: ui, analytics: analytics, project: project, environment: { }, tasks: tasks, settings: {}, runCommand: function(command, args) { expect.deepEqual(args, ['foo.js', 'foo-bar.js']); } }).validateAndRun(['foo.js', 'foo-bar.js']).then(function() { expect(ui.output).to.include('foo.js'); // expect(ui.output).to.include('The source path: nope.js does not exist.'); }); }) .then(cleanupTmpDir); }); });
addFileToGit
identifier_name
dependency_loader.ts
import {ScriptReceivers, ScriptReceiverFactory} from './script_receiver_factory';
import ScriptRequest from './script_request'; /** Handles loading dependency files. * * Dependency loaders don't remember whether a resource has been loaded or * not. It is caller's responsibility to make sure the resource is not loaded * twice. This is because it's impossible to detect resource loading status * without knowing its content. * * Options: * - cdn_http - url to HTTP CND * - cdn_https - url to HTTPS CDN * - version - version of pusher-js * - suffix - suffix appended to all names of dependency files * * @param {Object} options */ export default class DependencyLoader { options: any; receivers: ScriptReceiverFactory; loading: any; constructor(options : any) { this.options = options; this.receivers = options.receivers || ScriptReceivers; this.loading = {}; } /** Loads the dependency from CDN. * * @param {String} name * @param {Function} callback */ load(name : string, options: any, callback : Function) { var self = this; if (self.loading[name] && self.loading[name].length > 0) { self.loading[name].push(callback); } else { self.loading[name] = [callback]; var request = Runtime.createScriptRequest(self.getPath(name, options)); var receiver = self.receivers.create(function(error) { self.receivers.remove(receiver); if (self.loading[name]) { var callbacks = self.loading[name]; delete self.loading[name]; var successCallback = function(wasSuccessful) { if (!wasSuccessful) { request.cleanup(); } }; for (var i = 0; i < callbacks.length; i++) { callbacks[i](error, successCallback); } } }); request.send(receiver); } } /** Returns a root URL for pusher-js CDN. * * @returns {String} */ getRoot(options : any) : string { var cdn; var protocol = Runtime.getDocument().location.protocol; if ((options && options.encrypted) || protocol === "https:") { cdn = this.options.cdn_https; } else { cdn = this.options.cdn_http; } // make sure there are no double slashes return cdn.replace(/\/*$/, "") + "/" + this.options.version; } /** Returns a full path to a dependency file. * * @param {String} name * @returns {String} */ getPath(name : string, options : any) : string { return this.getRoot(options) + '/' + name + this.options.suffix + '.js'; }; }
import Runtime from 'runtime';
random_line_split
dependency_loader.ts
import {ScriptReceivers, ScriptReceiverFactory} from './script_receiver_factory'; import Runtime from 'runtime'; import ScriptRequest from './script_request'; /** Handles loading dependency files. * * Dependency loaders don't remember whether a resource has been loaded or * not. It is caller's responsibility to make sure the resource is not loaded * twice. This is because it's impossible to detect resource loading status * without knowing its content. * * Options: * - cdn_http - url to HTTP CND * - cdn_https - url to HTTPS CDN * - version - version of pusher-js * - suffix - suffix appended to all names of dependency files * * @param {Object} options */ export default class DependencyLoader { options: any; receivers: ScriptReceiverFactory; loading: any; constructor(options : any) { this.options = options; this.receivers = options.receivers || ScriptReceivers; this.loading = {}; } /** Loads the dependency from CDN. * * @param {String} name * @param {Function} callback */ load(name : string, options: any, callback : Function) { var self = this; if (self.loading[name] && self.loading[name].length > 0) { self.loading[name].push(callback); } else
} /** Returns a root URL for pusher-js CDN. * * @returns {String} */ getRoot(options : any) : string { var cdn; var protocol = Runtime.getDocument().location.protocol; if ((options && options.encrypted) || protocol === "https:") { cdn = this.options.cdn_https; } else { cdn = this.options.cdn_http; } // make sure there are no double slashes return cdn.replace(/\/*$/, "") + "/" + this.options.version; } /** Returns a full path to a dependency file. * * @param {String} name * @returns {String} */ getPath(name : string, options : any) : string { return this.getRoot(options) + '/' + name + this.options.suffix + '.js'; }; }
{ self.loading[name] = [callback]; var request = Runtime.createScriptRequest(self.getPath(name, options)); var receiver = self.receivers.create(function(error) { self.receivers.remove(receiver); if (self.loading[name]) { var callbacks = self.loading[name]; delete self.loading[name]; var successCallback = function(wasSuccessful) { if (!wasSuccessful) { request.cleanup(); } }; for (var i = 0; i < callbacks.length; i++) { callbacks[i](error, successCallback); } } }); request.send(receiver); }
conditional_block
dependency_loader.ts
import {ScriptReceivers, ScriptReceiverFactory} from './script_receiver_factory'; import Runtime from 'runtime'; import ScriptRequest from './script_request'; /** Handles loading dependency files. * * Dependency loaders don't remember whether a resource has been loaded or * not. It is caller's responsibility to make sure the resource is not loaded * twice. This is because it's impossible to detect resource loading status * without knowing its content. * * Options: * - cdn_http - url to HTTP CND * - cdn_https - url to HTTPS CDN * - version - version of pusher-js * - suffix - suffix appended to all names of dependency files * * @param {Object} options */ export default class
{ options: any; receivers: ScriptReceiverFactory; loading: any; constructor(options : any) { this.options = options; this.receivers = options.receivers || ScriptReceivers; this.loading = {}; } /** Loads the dependency from CDN. * * @param {String} name * @param {Function} callback */ load(name : string, options: any, callback : Function) { var self = this; if (self.loading[name] && self.loading[name].length > 0) { self.loading[name].push(callback); } else { self.loading[name] = [callback]; var request = Runtime.createScriptRequest(self.getPath(name, options)); var receiver = self.receivers.create(function(error) { self.receivers.remove(receiver); if (self.loading[name]) { var callbacks = self.loading[name]; delete self.loading[name]; var successCallback = function(wasSuccessful) { if (!wasSuccessful) { request.cleanup(); } }; for (var i = 0; i < callbacks.length; i++) { callbacks[i](error, successCallback); } } }); request.send(receiver); } } /** Returns a root URL for pusher-js CDN. * * @returns {String} */ getRoot(options : any) : string { var cdn; var protocol = Runtime.getDocument().location.protocol; if ((options && options.encrypted) || protocol === "https:") { cdn = this.options.cdn_https; } else { cdn = this.options.cdn_http; } // make sure there are no double slashes return cdn.replace(/\/*$/, "") + "/" + this.options.version; } /** Returns a full path to a dependency file. * * @param {String} name * @returns {String} */ getPath(name : string, options : any) : string { return this.getRoot(options) + '/' + name + this.options.suffix + '.js'; }; }
DependencyLoader
identifier_name
tkinter_gui.py
from Tkinter import * root = Tk() root.title('first test window') #root.geometry('300x200') frm = Frame(root) frm_l = Frame(frm) Label(frm_l, text='left_top').pack(side=TOP) Label(frm_l, text='left_bottom').pack(side=BOTTOM) frm_l.pack(side=LEFT) frm_r = Frame(frm) Label(frm_r, text='right_top').pack(side=TOP) Label(frm_r, text='right_bottom').pack(side=BOTTOM) frm_r.pack(side=RIGHT) frm.pack(side=TOP) ########################################################## frm1 = Frame(root) var = StringVar() Entry(frm1, textvariable=var).pack(side=TOP) var.set('entry text') t = Text(frm1) t.pack(side=TOP) def
(): t.insert(END, var.get()) Button(frm1, text='copy', command=print_entry).pack(side=TOP) frm1.pack(side=TOP) ########################################################## frm2 = Frame(root) redbutton = Button(frm2, text="Red", fg="red") redbutton.pack( side = LEFT) greenbutton = Button(frm2, text="Brown", fg="brown") greenbutton.pack( side = LEFT ) bluebutton = Button(frm2, text="Blue", fg="blue") bluebutton.pack( side = LEFT ) blackbutton = Button(frm2, text="Black", fg="black") blackbutton.pack( side = BOTTOM) frm2.pack(side=TOP) ###################################################### frm3 = Frame(root) b = Button(frm3, text='move') b.place(bordermode=OUTSIDE, height=100, width=100, x=50, y=50) b.pack() frm3.pack(side=TOP) root.mainloop()
print_entry
identifier_name
tkinter_gui.py
from Tkinter import * root = Tk() root.title('first test window') #root.geometry('300x200') frm = Frame(root) frm_l = Frame(frm) Label(frm_l, text='left_top').pack(side=TOP) Label(frm_l, text='left_bottom').pack(side=BOTTOM) frm_l.pack(side=LEFT) frm_r = Frame(frm) Label(frm_r, text='right_top').pack(side=TOP) Label(frm_r, text='right_bottom').pack(side=BOTTOM) frm_r.pack(side=RIGHT) frm.pack(side=TOP) ########################################################## frm1 = Frame(root) var = StringVar() Entry(frm1, textvariable=var).pack(side=TOP) var.set('entry text')
t.insert(END, var.get()) Button(frm1, text='copy', command=print_entry).pack(side=TOP) frm1.pack(side=TOP) ########################################################## frm2 = Frame(root) redbutton = Button(frm2, text="Red", fg="red") redbutton.pack( side = LEFT) greenbutton = Button(frm2, text="Brown", fg="brown") greenbutton.pack( side = LEFT ) bluebutton = Button(frm2, text="Blue", fg="blue") bluebutton.pack( side = LEFT ) blackbutton = Button(frm2, text="Black", fg="black") blackbutton.pack( side = BOTTOM) frm2.pack(side=TOP) ###################################################### frm3 = Frame(root) b = Button(frm3, text='move') b.place(bordermode=OUTSIDE, height=100, width=100, x=50, y=50) b.pack() frm3.pack(side=TOP) root.mainloop()
t = Text(frm1) t.pack(side=TOP) def print_entry():
random_line_split
tkinter_gui.py
from Tkinter import * root = Tk() root.title('first test window') #root.geometry('300x200') frm = Frame(root) frm_l = Frame(frm) Label(frm_l, text='left_top').pack(side=TOP) Label(frm_l, text='left_bottom').pack(side=BOTTOM) frm_l.pack(side=LEFT) frm_r = Frame(frm) Label(frm_r, text='right_top').pack(side=TOP) Label(frm_r, text='right_bottom').pack(side=BOTTOM) frm_r.pack(side=RIGHT) frm.pack(side=TOP) ########################################################## frm1 = Frame(root) var = StringVar() Entry(frm1, textvariable=var).pack(side=TOP) var.set('entry text') t = Text(frm1) t.pack(side=TOP) def print_entry():
Button(frm1, text='copy', command=print_entry).pack(side=TOP) frm1.pack(side=TOP) ########################################################## frm2 = Frame(root) redbutton = Button(frm2, text="Red", fg="red") redbutton.pack( side = LEFT) greenbutton = Button(frm2, text="Brown", fg="brown") greenbutton.pack( side = LEFT ) bluebutton = Button(frm2, text="Blue", fg="blue") bluebutton.pack( side = LEFT ) blackbutton = Button(frm2, text="Black", fg="black") blackbutton.pack( side = BOTTOM) frm2.pack(side=TOP) ###################################################### frm3 = Frame(root) b = Button(frm3, text='move') b.place(bordermode=OUTSIDE, height=100, width=100, x=50, y=50) b.pack() frm3.pack(side=TOP) root.mainloop()
t.insert(END, var.get())
identifier_body
squeeze-more.js
define(function(require, exports, module) { var jsp = require("./parse-js"), pro = require("./process"), slice = jsp.slice, member = jsp.member, curry = jsp.curry, MAP = pro.MAP, PRECEDENCE = jsp.PRECEDENCE, OPERATORS = jsp.OPERATORS; function ast_squeeze_more(ast) { var w = pro.ast_walker(), walk = w.walk, scope; function with_scope(s, cont)
; function _lambda(name, args, body) { return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ]; }; return w.with_walkers({ "toplevel": function(body) { return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ]; }, "function": _lambda, "defun": _lambda, "new": function(ctor, args) { if (ctor[0] == "name" && ctor[1] == "Array" && !scope.has("Array")) { if (args.length != 1) { return [ "array", args ]; } else { return walk([ "call", [ "name", "Array" ], args ]); } } }, "call": function(expr, args) { if (expr[0] == "dot" && expr[2] == "toString" && args.length == 0) { // foo.toString() ==> foo+"" return [ "binary", "+", expr[1], [ "string", "" ]]; } if (expr[0] == "name" && expr[1] == "Array" && args.length != 1 && !scope.has("Array")) { return [ "array", args ]; } } }, function() { return walk(pro.ast_add_scope(ast)); }); }; exports.ast_squeeze_more = ast_squeeze_more; });
{ var save = scope, ret; scope = s; ret = cont(); scope = save; return ret; }
identifier_body
squeeze-more.js
define(function(require, exports, module) { var jsp = require("./parse-js"), pro = require("./process"), slice = jsp.slice, member = jsp.member, curry = jsp.curry, MAP = pro.MAP, PRECEDENCE = jsp.PRECEDENCE, OPERATORS = jsp.OPERATORS; function ast_squeeze_more(ast) { var w = pro.ast_walker(), walk = w.walk, scope; function
(s, cont) { var save = scope, ret; scope = s; ret = cont(); scope = save; return ret; }; function _lambda(name, args, body) { return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ]; }; return w.with_walkers({ "toplevel": function(body) { return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ]; }, "function": _lambda, "defun": _lambda, "new": function(ctor, args) { if (ctor[0] == "name" && ctor[1] == "Array" && !scope.has("Array")) { if (args.length != 1) { return [ "array", args ]; } else { return walk([ "call", [ "name", "Array" ], args ]); } } }, "call": function(expr, args) { if (expr[0] == "dot" && expr[2] == "toString" && args.length == 0) { // foo.toString() ==> foo+"" return [ "binary", "+", expr[1], [ "string", "" ]]; } if (expr[0] == "name" && expr[1] == "Array" && args.length != 1 && !scope.has("Array")) { return [ "array", args ]; } } }, function() { return walk(pro.ast_add_scope(ast)); }); }; exports.ast_squeeze_more = ast_squeeze_more; });
with_scope
identifier_name
squeeze-more.js
define(function(require, exports, module) { var jsp = require("./parse-js"), pro = require("./process"), slice = jsp.slice, member = jsp.member, curry = jsp.curry, MAP = pro.MAP, PRECEDENCE = jsp.PRECEDENCE, OPERATORS = jsp.OPERATORS; function ast_squeeze_more(ast) { var w = pro.ast_walker(), walk = w.walk, scope; function with_scope(s, cont) { var save = scope, ret; scope = s; ret = cont(); scope = save; return ret; }; function _lambda(name, args, body) { return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ]; }; return w.with_walkers({ "toplevel": function(body) { return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ]; }, "function": _lambda, "defun": _lambda, "new": function(ctor, args) { if (ctor[0] == "name" && ctor[1] == "Array" && !scope.has("Array")) { if (args.length != 1) { return [ "array", args ]; } else { return walk([ "call", [ "name", "Array" ], args ]); } } },
if (expr[0] == "name" && expr[1] == "Array" && args.length != 1 && !scope.has("Array")) { return [ "array", args ]; } } }, function() { return walk(pro.ast_add_scope(ast)); }); }; exports.ast_squeeze_more = ast_squeeze_more; });
"call": function(expr, args) { if (expr[0] == "dot" && expr[2] == "toString" && args.length == 0) { // foo.toString() ==> foo+"" return [ "binary", "+", expr[1], [ "string", "" ]]; }
random_line_split
squeeze-more.js
define(function(require, exports, module) { var jsp = require("./parse-js"), pro = require("./process"), slice = jsp.slice, member = jsp.member, curry = jsp.curry, MAP = pro.MAP, PRECEDENCE = jsp.PRECEDENCE, OPERATORS = jsp.OPERATORS; function ast_squeeze_more(ast) { var w = pro.ast_walker(), walk = w.walk, scope; function with_scope(s, cont) { var save = scope, ret; scope = s; ret = cont(); scope = save; return ret; }; function _lambda(name, args, body) { return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ]; }; return w.with_walkers({ "toplevel": function(body) { return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ]; }, "function": _lambda, "defun": _lambda, "new": function(ctor, args) { if (ctor[0] == "name" && ctor[1] == "Array" && !scope.has("Array")) { if (args.length != 1) { return [ "array", args ]; } else { return walk([ "call", [ "name", "Array" ], args ]); } } }, "call": function(expr, args) { if (expr[0] == "dot" && expr[2] == "toString" && args.length == 0)
if (expr[0] == "name" && expr[1] == "Array" && args.length != 1 && !scope.has("Array")) { return [ "array", args ]; } } }, function() { return walk(pro.ast_add_scope(ast)); }); }; exports.ast_squeeze_more = ast_squeeze_more; });
{ // foo.toString() ==> foo+"" return [ "binary", "+", expr[1], [ "string", "" ]]; }
conditional_block
lib.rs
// Copyright 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. // // ignore-lexer-test FIXME #15679 //! This crate provides a native implementation of regular expressions that is //! heavily based on RE2 both in syntax and in implementation. Notably, //! backreferences and arbitrary lookahead/lookbehind assertions are not //! provided. In return, regular expression searching provided by this package //! has excellent worst case performance. The specific syntax supported is //! documented further down. //! //! This crate's documentation provides some simple examples, describes Unicode //! support and exhaustively lists the supported syntax. For more specific //! details on the API, please see the documentation for the `Regex` type. //! //! # First example: find a date //! //! General use of regular expressions in this package involves compiling an //! expression and then using it to search, split or replace text. For example, //! to confirm that some text resembles a date: //! //! ```rust //! use regex::Regex; //! let re = match Regex::new(r"^\d{4}-\d{2}-\d{2}$") { //! Ok(re) => re, //! Err(err) => fail!("{}", err), //! }; //! assert_eq!(re.is_match("2014-01-01"), true); //! ``` //! //! Notice the use of the `^` and `$` anchors. In this crate, every expression //! is executed with an implicit `.*?` at the beginning and end, which allows //! it to match anywhere in the text. Anchors can be used to ensure that the //! full text matches an expression. //! //! This example also demonstrates the utility of raw strings in Rust, which //! are just like regular strings except they are prefixed with an `r` and do //! not process any escape sequences. For example, `"\\d"` is the same //! expression as `r"\d"`. //! //! # The `regex!` macro //! //! Rust's compile time meta-programming facilities provide a way to write a //! `regex!` macro which compiles regular expressions *when your program //! compiles*. Said differently, if you only use `regex!` to build regular //! expressions in your program, then your program cannot compile with an //! invalid regular expression. Moreover, the `regex!` macro compiles the //! given expression to native Rust code, which makes it much faster for //! searching text. //! //! Since `regex!` provides compiled regular expressions that are both safer //! and faster to use, you should use them whenever possible. The only //! requirement for using them is that you have a string literal corresponding //! to your expression. Otherwise, it is indistinguishable from an expression //! compiled at runtime with `Regex::new`. //! //! To use the `regex!` macro, you must enable the `phase` feature and import //! the `regex_macros` crate as a syntax extension: //! //! ```rust //! #![feature(phase)] //! #[phase(plugin)] //! extern crate regex_macros; //! extern crate regex; //! //! fn main() { //! let re = regex!(r"^\d{4}-\d{2}-\d{2}$"); //! assert_eq!(re.is_match("2014-01-01"), true); //! } //! ``` //! //! There are a few things worth mentioning about using the `regex!` macro. //! Firstly, the `regex!` macro *only* accepts string *literals*. //! Secondly, the `regex` crate *must* be linked with the name `regex` since //! the generated code depends on finding symbols in the `regex` crate. //! //! The only downside of using the `regex!` macro is that it can increase the //! size of your program's binary since it generates specialized Rust code. //! The extra size probably won't be significant for a small number of //! expressions, but 100+ calls to `regex!` will probably result in a //! noticeably bigger binary. //! //! # Example: iterating over capture groups //! //! This crate provides convenient iterators for matching an expression //! repeatedly against a search string to find successive non-overlapping //! matches. For example, to find all dates in a string and be able to access //! them by their component pieces: //! //! ```rust //! # #![feature(phase)] //! # extern crate regex; #[phase(plugin)] extern crate regex_macros; //! # fn main() { //! let re = regex!(r"(\d{4})-(\d{2})-(\d{2})"); //! let text = "2012-03-14, 2013-01-01 and 2014-07-05"; //! for cap in re.captures_iter(text) { //! println!("Month: {} Day: {} Year: {}", cap.at(2), cap.at(3), cap.at(1)); //! } //! // Output: //! // Month: 03 Day: 14 Year: 2012 //! // Month: 01 Day: 01 Year: 2013 //! // Month: 07 Day: 05 Year: 2014 //! # } //! ``` //! //! Notice that the year is in the capture group indexed at `1`. This is //! because the *entire match* is stored in the capture group at index `0`. //! //! # Example: replacement with named capture groups //! //! Building on the previous example, perhaps we'd like to rearrange the date //! formats. This can be done with text replacement. But to make the code //! clearer, we can *name* our capture groups and use those names as variables //! in our replacement text: //! //! ```rust //! # #![feature(phase)] //! # extern crate regex; #[phase(plugin)] extern crate regex_macros; //! # fn main() { //! let re = regex!(r"(?P<y>\d{4})-(?P<m>\d{2})-(?P<d>\d{2})"); //! let before = "2012-03-14, 2013-01-01 and 2014-07-05"; //! let after = re.replace_all(before, "$m/$d/$y"); //! assert_eq!(after.as_slice(), "03/14/2012, 01/01/2013 and 07/05/2014"); //! # } //! ``` //! //! The `replace` methods are actually polymorphic in the replacement, which //! provides more flexibility than is seen here. (See the documentation for //! `Regex::replace` for more details.) //! //! # Pay for what you use //! //! With respect to searching text with a regular expression, there are three //! questions that can be asked: //! //! 1. Does the text match this expression? //! 2. If so, where does it match? //! 3. Where are the submatches? //! //! Generally speaking, this crate could provide a function to answer only #3, //! which would subsume #1 and #2 automatically. However, it can be //! significantly more expensive to compute the location of submatches, so it's //! best not to do it if you don't need to. //! //! Therefore, only use what you need. For example, don't use `find` if you //! only need to test if an expression matches a string. (Use `is_match` //! instead.) //! //! # Unicode
//! This implementation executes regular expressions **only** on sequences of //! Unicode code points while exposing match locations as byte indices into the //! search string. //! //! Currently, only naive case folding is supported. Namely, when matching //! case insensitively, the characters are first converted to their uppercase //! forms and then compared. //! //! Regular expressions themselves are also **only** interpreted as a sequence //! of Unicode code points. This means you can use Unicode characters //! directly in your expression: //! //! ```rust //! # #![feature(phase)] //! # extern crate regex; #[phase(plugin)] extern crate regex_macros; //! # fn main() { //! let re = regex!(r"(?i)Δ+"); //! assert_eq!(re.find("ΔδΔ"), Some((0, 6))); //! # } //! ``` //! //! Finally, Unicode general categories and scripts are available as character //! classes. For example, you can match a sequence of numerals, Greek or //! Cherokee letters: //! //! ```rust //! # #![feature(phase)] //! # extern crate regex; #[phase(plugin)] extern crate regex_macros; //! # fn main() { //! let re = regex!(r"[\pN\p{Greek}\p{Cherokee}]+"); //! assert_eq!(re.find("abcΔᎠβⅠᏴγδⅡxyz"), Some((3, 23))); //! # } //! ``` //! //! # Syntax //! //! The syntax supported in this crate is almost in an exact correspondence //! with the syntax supported by RE2. //! //! ## Matching one character //! //! <pre class="rust"> //! . any character except new line (includes new line with s flag) //! [xyz] A character class matching either x, y or z. //! [^xyz] A character class matching any character except x, y and z. //! [a-z] A character class matching any character in range a-z. //! \d Perl character class ([0-9]) //! \D Negated Perl character class ([^0-9]) //! [:alpha:] ASCII character class ([A-Za-z]) //! [:^alpha:] Negated ASCII character class ([^A-Za-z]) //! \pN One letter name Unicode character class //! \p{Greek} Unicode character class (general category or script) //! \PN Negated one letter name Unicode character class //! \P{Greek} negated Unicode character class (general category or script) //! </pre> //! //! Any named character class may appear inside a bracketed `[...]` character //! class. For example, `[\p{Greek}\pN]` matches any Greek or numeral //! character. //! //! ## Composites //! //! <pre class="rust"> //! xy concatenation (x followed by y) //! x|y alternation (x or y, prefer x) //! </pre> //! //! ## Repetitions //! //! <pre class="rust"> //! x* zero or more of x (greedy) //! x+ one or more of x (greedy) //! x? zero or one of x (greedy) //! x*? zero or more of x (ungreedy) //! x+? one or more of x (ungreedy) //! x?? zero or one of x (ungreedy) //! x{n,m} at least n x and at most m x (greedy) //! x{n,} at least n x (greedy) //! x{n} exactly n x //! x{n,m}? at least n x and at most m x (ungreedy) //! x{n,}? at least n x (ungreedy) //! x{n}? exactly n x //! </pre> //! //! ## Empty matches //! //! <pre class="rust"> //! ^ the beginning of text (or start-of-line with multi-line mode) //! $ the end of text (or end-of-line with multi-line mode) //! \A only the beginning of text (even with multi-line mode enabled) //! \z only the end of text (even with multi-line mode enabled) //! \b a Unicode word boundary (\w on one side and \W, \A, or \z on other) //! \B not a Unicode word boundary //! </pre> //! //! ## Grouping and flags //! //! <pre class="rust"> //! (exp) numbered capture group (indexed by opening parenthesis) //! (?P&lt;name&gt;exp) named (also numbered) capture group (allowed chars: [_0-9a-zA-Z]) //! (?:exp) non-capturing group //! (?flags) set flags within current group //! (?flags:exp) set flags for exp (non-capturing) //! </pre> //! //! Flags are each a single character. For example, `(?x)` sets the flag `x` //! and `(?-x)` clears the flag `x`. Multiple flags can be set or cleared at //! the same time: `(?xy)` sets both the `x` and `y` flags and `(?x-y)` sets //! the `x` flag and clears the `y` flag. //! //! All flags are by default disabled. They are: //! //! <pre class="rust"> //! i case insensitive //! m multi-line mode: ^ and $ match begin/end of line //! s allow . to match \n //! U swap the meaning of x* and x*? //! </pre> //! //! Here's an example that matches case insensitively for only part of the //! expression: //! //! ```rust //! # #![feature(phase)] //! # extern crate regex; #[phase(plugin)] extern crate regex_macros; //! # fn main() { //! let re = regex!(r"(?i)a+(?-i)b+"); //! let cap = re.captures("AaAaAbbBBBb").unwrap(); //! assert_eq!(cap.at(0), "AaAaAbb"); //! # } //! ``` //! //! Notice that the `a+` matches either `a` or `A`, but the `b+` only matches //! `b`. //! //! ## Escape sequences //! //! <pre class="rust"> //! \* literal *, works for any punctuation character: \.+*?()|[]{}^$ //! \a bell (\x07) //! \f form feed (\x0C) //! \t horizontal tab //! \n new line //! \r carriage return //! \v vertical tab (\x0B) //! \123 octal character code (up to three digits) //! \x7F hex character code (exactly two digits) //! \x{10FFFF} any hex character code corresponding to a Unicode code point //! </pre> //! //! ## Perl character classes (Unicode friendly) //! //! These classes are based on the definitions provided in //! [UTS#18](http://www.unicode.org/reports/tr18/#Compatibility_Properties): //! //! <pre class="rust"> //! \d digit (\p{Nd}) //! \D not digit //! \s whitespace (\p{White_Space}) //! \S not whitespace //! \w word character (\p{Alphabetic} + \p{M} + \d + \p{Pc} + \p{Join_Control}) //! \W not word character //! </pre> //! //! ## ASCII character classes //! //! <pre class="rust"> //! [:alnum:] alphanumeric ([0-9A-Za-z]) //! [:alpha:] alphabetic ([A-Za-z]) //! [:ascii:] ASCII ([\x00-\x7F]) //! [:blank:] blank ([\t ]) //! [:cntrl:] control ([\x00-\x1F\x7F]) //! [:digit:] digits ([0-9]) //! [:graph:] graphical ([!-~]) //! [:lower:] lower case ([a-z]) //! [:print:] printable ([ -~]) //! [:punct:] punctuation ([!-/:-@[-`{-~]) //! [:space:] whitespace ([\t\n\v\f\r ]) //! [:upper:] upper case ([A-Z]) //! [:word:] word characters ([0-9A-Za-z_]) //! [:xdigit:] hex digit ([0-9A-Fa-f]) //! </pre> //! //! # Untrusted input //! //! There are two factors to consider here: untrusted regular expressions and //! untrusted search text. //! //! Currently, there are no counter-measures in place to prevent a malicious //! user from writing an expression that may use a lot of resources. One such //! example is to repeat counted repetitions: `((a{100}){100}){100}` will try //! to repeat the `a` instruction `100^3` times. Essentially, this means it's //! very easy for an attacker to exhaust your system's memory if they are //! allowed to execute arbitrary regular expressions. A possible solution to //! this is to impose a hard limit on the size of a compiled expression, but it //! does not yet exist. //! //! The story is a bit better with untrusted search text, since this crate's //! implementation provides `O(nm)` search where `n` is the number of //! characters in the search text and `m` is the number of instructions in a //! compiled expression. #![crate_name = "regex"] #![crate_type = "rlib"] #![crate_type = "dylib"] #![experimental] #![license = "MIT/ASL2"] #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png", html_favicon_url = "http://www.rust-lang.org/favicon.ico", html_root_url = "http://doc.rust-lang.org/master/", html_playground_url = "http://play.rust-lang.org/")] #![feature(macro_rules, phase)] #![deny(missing_doc)] #[cfg(test)] extern crate stdtest = "test"; #[cfg(test)] extern crate rand; // During tests, this links with the `regex` crate so that the `regex!` macro // can be tested. #[cfg(test)] extern crate regex; // unicode tables for character classes are defined in libunicode extern crate unicode; pub use parse::Error; pub use re::{Regex, Captures, SubCaptures, SubCapturesPos}; pub use re::{FindCaptures, FindMatches}; pub use re::{Replacer, NoExpand, RegexSplits, RegexSplitsN}; pub use re::{quote, is_match}; mod compile; mod parse; mod re; mod vm; #[cfg(test)] mod test; /// The `native` module exists to support the `regex!` macro. Do not use. #[doc(hidden)] pub mod native { // Exporting this stuff is bad form, but it's necessary for two reasons. // Firstly, the `regex!` syntax extension is in a different crate and // requires access to the representation of a regex (particularly the // instruction set) in order to compile to native Rust. This could be // mitigated if `regex!` was defined in the same crate, but this has // undesirable consequences (such as requiring a dependency on // `libsyntax`). // // Secondly, the code generated by `regex!` must *also* be able // to access various functions in this crate to reduce code duplication // and to provide a value with precisely the same `Regex` type in this // crate. This, AFAIK, is impossible to mitigate. // // On the bright side, `rustdoc` lets us hide this from the public API // documentation. pub use compile::{ Program, OneChar, CharClass, Any, Save, Jump, Split, Match, EmptyBegin, EmptyEnd, EmptyWordBoundary, }; pub use parse::{ FLAG_EMPTY, FLAG_NOCASE, FLAG_MULTI, FLAG_DOTNL, FLAG_SWAP_GREED, FLAG_NEGATED, }; pub use re::{Dynamic, Native}; pub use vm::{ MatchKind, Exists, Location, Submatches, StepState, StepMatchEarlyReturn, StepMatch, StepContinue, CharReader, find_prefix, }; }
//!
random_line_split
package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class BashCompletion(AutotoolsPackage): """Programmable completion functions for bash.""" homepage = "https://github.com/scop/bash-completion" url = "https://github.com/scop/bash-completion/archive/2.3.tar.gz" git = "https://github.com/scop/bash-completion.git" version('develop', branch='master') version('2.7', sha256='dba2b88c363178622b61258f35d82df64dc8d279359f599e3b93eac0375a416c') version('2.3', sha256='d92fcef5f6e3bbc68a84f0a7b063a1cd07b4000cc6e275cd1ff83863ab3b322a') # Build dependencies depends_on('automake', type='build') depends_on('autoconf', type='build') depends_on('libtool', type='build')
def create_install_directory(self): mkdirp(join_path(self.prefix.share, 'bash-completion', 'completions')) @run_after('install') def show_message_to_user(self): prefix = self.prefix # Guidelines for individual user as provided by the author at # https://github.com/scop/bash-completion print('=====================================================') print('Bash completion has been installed. To use it, please') print('include the following lines in your ~/.bash_profile :') print('') print('# Use bash-completion, if available') print('[[ $PS1 && -f %s/share/bash-completion/bash_completion ]] && \ ' % prefix) # NOQA: ignore=E501 print(' . %s/share/bash-completion/bash_completion' % prefix) print('') print('=====================================================')
# Other dependencies depends_on('bash@4.1:', type='run') @run_before('install')
random_line_split
package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class BashCompletion(AutotoolsPackage):
"""Programmable completion functions for bash.""" homepage = "https://github.com/scop/bash-completion" url = "https://github.com/scop/bash-completion/archive/2.3.tar.gz" git = "https://github.com/scop/bash-completion.git" version('develop', branch='master') version('2.7', sha256='dba2b88c363178622b61258f35d82df64dc8d279359f599e3b93eac0375a416c') version('2.3', sha256='d92fcef5f6e3bbc68a84f0a7b063a1cd07b4000cc6e275cd1ff83863ab3b322a') # Build dependencies depends_on('automake', type='build') depends_on('autoconf', type='build') depends_on('libtool', type='build') # Other dependencies depends_on('bash@4.1:', type='run') @run_before('install') def create_install_directory(self): mkdirp(join_path(self.prefix.share, 'bash-completion', 'completions')) @run_after('install') def show_message_to_user(self): prefix = self.prefix # Guidelines for individual user as provided by the author at # https://github.com/scop/bash-completion print('=====================================================') print('Bash completion has been installed. To use it, please') print('include the following lines in your ~/.bash_profile :') print('') print('# Use bash-completion, if available') print('[[ $PS1 && -f %s/share/bash-completion/bash_completion ]] && \ ' % prefix) # NOQA: ignore=E501 print(' . %s/share/bash-completion/bash_completion' % prefix) print('') print('=====================================================')
identifier_body
package.py
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) from spack import * class BashCompletion(AutotoolsPackage): """Programmable completion functions for bash.""" homepage = "https://github.com/scop/bash-completion" url = "https://github.com/scop/bash-completion/archive/2.3.tar.gz" git = "https://github.com/scop/bash-completion.git" version('develop', branch='master') version('2.7', sha256='dba2b88c363178622b61258f35d82df64dc8d279359f599e3b93eac0375a416c') version('2.3', sha256='d92fcef5f6e3bbc68a84f0a7b063a1cd07b4000cc6e275cd1ff83863ab3b322a') # Build dependencies depends_on('automake', type='build') depends_on('autoconf', type='build') depends_on('libtool', type='build') # Other dependencies depends_on('bash@4.1:', type='run') @run_before('install') def create_install_directory(self): mkdirp(join_path(self.prefix.share, 'bash-completion', 'completions')) @run_after('install') def
(self): prefix = self.prefix # Guidelines for individual user as provided by the author at # https://github.com/scop/bash-completion print('=====================================================') print('Bash completion has been installed. To use it, please') print('include the following lines in your ~/.bash_profile :') print('') print('# Use bash-completion, if available') print('[[ $PS1 && -f %s/share/bash-completion/bash_completion ]] && \ ' % prefix) # NOQA: ignore=E501 print(' . %s/share/bash-completion/bash_completion' % prefix) print('') print('=====================================================')
show_message_to_user
identifier_name
runner.py
# docker-pipeline # # The MIT License (MIT) # # Copyright (c) 2015 Dan Leehr # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from docker.client import Client from docker.utils import kwargs_from_env class Runner(): def __init__(self, pipeline=None):
self.result = None @classmethod def get_client(cls): # Using boot2docker instructions for now # http://docker-py.readthedocs.org/en/latest/boot2docker/ # Workaround for requests.exceptions.SSLError: hostname '192.168.59.103' doesn't match 'boot2docker' client = Client(version='auto', **kwargs_from_env(assert_hostname=False)) return client def run(self): if self.pipeline.debug: print "Running pipeline: {}".format(self) for each_step in self.pipeline.steps: if self.pipeline.pull_images: self.pull_image(each_step) container = self.create_container(each_step) self.start_container(container, each_step) self.result = self.get_result(container, each_step) self.finish_container(container, each_step) if self.result['code'] != 0: # Container exited with nonzero status code print "Error: step exited with code {}".format(self.result['code']) # Pipeline breaks if nonzero result is encountered break if self.pipeline.debug: print 'Result: {}'.format(self.result) def pull_image(self, step): if self.pipeline.debug: print 'Pulling image for step: {}'.format(step) image_result = self.client.pull(step.image) if self.pipeline.debug: print image_result def create_container(self, step): if self.pipeline.debug: print 'Creating container for step: {}'.format(step) print 'Image: {}'.format(step.image) print 'Volumes: {}'.format(step.get_volumes()) print 'Environment: {}'.format(step.environment) container = self.client.create_container(step.image, command=step.command, environment=step.environment, volumes=step.get_volumes()) return container def start_container(self, container, step): if self.pipeline.debug: print 'Running container for step {}'.format(step) print 'Binds: {}'.format(step.binds) # client.start does not return anything self.client.start(container, binds=step.binds) def get_result(self, container, step): logs = self.client.attach(container, stream=True, logs=True) result = {'image': step.image} print 'step: {}\nimage: {}\n==============='.format(step.name, step.image) all_logs = str() for log in logs: all_logs = all_logs + log print log, # Store the return value code = self.client.wait(container) result['code'] = code return result def finish_container(self, container, step): if self.pipeline.debug: print 'Cleaning up container for step {}'.format(step) if self.remove_containers: self.client.remove_container(container)
self.pipeline = pipeline self.client = Runner.get_client() self.remove_containers = False
random_line_split
runner.py
# docker-pipeline # # The MIT License (MIT) # # Copyright (c) 2015 Dan Leehr # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from docker.client import Client from docker.utils import kwargs_from_env class Runner(): def __init__(self, pipeline=None): self.pipeline = pipeline self.client = Runner.get_client() self.remove_containers = False self.result = None @classmethod def get_client(cls): # Using boot2docker instructions for now # http://docker-py.readthedocs.org/en/latest/boot2docker/ # Workaround for requests.exceptions.SSLError: hostname '192.168.59.103' doesn't match 'boot2docker' client = Client(version='auto', **kwargs_from_env(assert_hostname=False)) return client def run(self): if self.pipeline.debug: print "Running pipeline: {}".format(self) for each_step in self.pipeline.steps: if self.pipeline.pull_images: self.pull_image(each_step) container = self.create_container(each_step) self.start_container(container, each_step) self.result = self.get_result(container, each_step) self.finish_container(container, each_step) if self.result['code'] != 0: # Container exited with nonzero status code print "Error: step exited with code {}".format(self.result['code']) # Pipeline breaks if nonzero result is encountered break if self.pipeline.debug: print 'Result: {}'.format(self.result) def pull_image(self, step): if self.pipeline.debug: print 'Pulling image for step: {}'.format(step) image_result = self.client.pull(step.image) if self.pipeline.debug: print image_result def create_container(self, step): if self.pipeline.debug: print 'Creating container for step: {}'.format(step) print 'Image: {}'.format(step.image) print 'Volumes: {}'.format(step.get_volumes()) print 'Environment: {}'.format(step.environment) container = self.client.create_container(step.image, command=step.command, environment=step.environment, volumes=step.get_volumes()) return container def start_container(self, container, step): if self.pipeline.debug: print 'Running container for step {}'.format(step) print 'Binds: {}'.format(step.binds) # client.start does not return anything self.client.start(container, binds=step.binds) def get_result(self, container, step):
def finish_container(self, container, step): if self.pipeline.debug: print 'Cleaning up container for step {}'.format(step) if self.remove_containers: self.client.remove_container(container)
logs = self.client.attach(container, stream=True, logs=True) result = {'image': step.image} print 'step: {}\nimage: {}\n==============='.format(step.name, step.image) all_logs = str() for log in logs: all_logs = all_logs + log print log, # Store the return value code = self.client.wait(container) result['code'] = code return result
identifier_body
runner.py
# docker-pipeline # # The MIT License (MIT) # # Copyright (c) 2015 Dan Leehr # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from docker.client import Client from docker.utils import kwargs_from_env class Runner(): def __init__(self, pipeline=None): self.pipeline = pipeline self.client = Runner.get_client() self.remove_containers = False self.result = None @classmethod def get_client(cls): # Using boot2docker instructions for now # http://docker-py.readthedocs.org/en/latest/boot2docker/ # Workaround for requests.exceptions.SSLError: hostname '192.168.59.103' doesn't match 'boot2docker' client = Client(version='auto', **kwargs_from_env(assert_hostname=False)) return client def run(self): if self.pipeline.debug: print "Running pipeline: {}".format(self) for each_step in self.pipeline.steps: if self.pipeline.pull_images: self.pull_image(each_step) container = self.create_container(each_step) self.start_container(container, each_step) self.result = self.get_result(container, each_step) self.finish_container(container, each_step) if self.result['code'] != 0: # Container exited with nonzero status code print "Error: step exited with code {}".format(self.result['code']) # Pipeline breaks if nonzero result is encountered break if self.pipeline.debug: print 'Result: {}'.format(self.result) def pull_image(self, step): if self.pipeline.debug: print 'Pulling image for step: {}'.format(step) image_result = self.client.pull(step.image) if self.pipeline.debug: print image_result def create_container(self, step): if self.pipeline.debug: print 'Creating container for step: {}'.format(step) print 'Image: {}'.format(step.image) print 'Volumes: {}'.format(step.get_volumes()) print 'Environment: {}'.format(step.environment) container = self.client.create_container(step.image, command=step.command, environment=step.environment, volumes=step.get_volumes()) return container def start_container(self, container, step): if self.pipeline.debug: print 'Running container for step {}'.format(step) print 'Binds: {}'.format(step.binds) # client.start does not return anything self.client.start(container, binds=step.binds) def get_result(self, container, step): logs = self.client.attach(container, stream=True, logs=True) result = {'image': step.image} print 'step: {}\nimage: {}\n==============='.format(step.name, step.image) all_logs = str() for log in logs: all_logs = all_logs + log print log, # Store the return value code = self.client.wait(container) result['code'] = code return result def finish_container(self, container, step): if self.pipeline.debug: print 'Cleaning up container for step {}'.format(step) if self.remove_containers:
self.client.remove_container(container)
conditional_block
runner.py
# docker-pipeline # # The MIT License (MIT) # # Copyright (c) 2015 Dan Leehr # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from docker.client import Client from docker.utils import kwargs_from_env class Runner(): def __init__(self, pipeline=None): self.pipeline = pipeline self.client = Runner.get_client() self.remove_containers = False self.result = None @classmethod def get_client(cls): # Using boot2docker instructions for now # http://docker-py.readthedocs.org/en/latest/boot2docker/ # Workaround for requests.exceptions.SSLError: hostname '192.168.59.103' doesn't match 'boot2docker' client = Client(version='auto', **kwargs_from_env(assert_hostname=False)) return client def run(self): if self.pipeline.debug: print "Running pipeline: {}".format(self) for each_step in self.pipeline.steps: if self.pipeline.pull_images: self.pull_image(each_step) container = self.create_container(each_step) self.start_container(container, each_step) self.result = self.get_result(container, each_step) self.finish_container(container, each_step) if self.result['code'] != 0: # Container exited with nonzero status code print "Error: step exited with code {}".format(self.result['code']) # Pipeline breaks if nonzero result is encountered break if self.pipeline.debug: print 'Result: {}'.format(self.result) def pull_image(self, step): if self.pipeline.debug: print 'Pulling image for step: {}'.format(step) image_result = self.client.pull(step.image) if self.pipeline.debug: print image_result def create_container(self, step): if self.pipeline.debug: print 'Creating container for step: {}'.format(step) print 'Image: {}'.format(step.image) print 'Volumes: {}'.format(step.get_volumes()) print 'Environment: {}'.format(step.environment) container = self.client.create_container(step.image, command=step.command, environment=step.environment, volumes=step.get_volumes()) return container def start_container(self, container, step): if self.pipeline.debug: print 'Running container for step {}'.format(step) print 'Binds: {}'.format(step.binds) # client.start does not return anything self.client.start(container, binds=step.binds) def get_result(self, container, step): logs = self.client.attach(container, stream=True, logs=True) result = {'image': step.image} print 'step: {}\nimage: {}\n==============='.format(step.name, step.image) all_logs = str() for log in logs: all_logs = all_logs + log print log, # Store the return value code = self.client.wait(container) result['code'] = code return result def
(self, container, step): if self.pipeline.debug: print 'Cleaning up container for step {}'.format(step) if self.remove_containers: self.client.remove_container(container)
finish_container
identifier_name
sort-table.js
'use strict'; import React from 'react'; import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table'; var products = []; function addProducts(quantity) { var startId = products.length; for (var i = 0; i < quantity; i++) { var id = startId + i; products.push({ id: id, name: "Item name " + id, price: 100 + i }); } } addProducts(5); var order = 'desc'; export default class SortTable extends React.Component{ handleBtnClick = e => { if(order === 'desc'){ this.refs.table.handleSort('asc', 'name'); order = 'asc'; } else { this.refs.table.handleSort('desc', 'name'); order = 'desc'; } } render()
};
{ return ( <div> <p style={{color:'red'}}>You cam click header to sort or click following button to perform a sorting by expose API</p> <button onClick={this.handleBtnClick}>Sort Product Name</button> <BootstrapTable ref="table" data={products}> <TableHeaderColumn dataField="id" isKey={true} dataSort={true}>Product ID</TableHeaderColumn> <TableHeaderColumn dataField="name" dataSort={true}>Product Name</TableHeaderColumn> <TableHeaderColumn dataField="price">Product Price</TableHeaderColumn> </BootstrapTable> </div> ); }
identifier_body
sort-table.js
'use strict'; import React from 'react'; import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table'; var products = []; function addProducts(quantity) { var startId = products.length; for (var i = 0; i < quantity; i++) { var id = startId + i; products.push({ id: id, name: "Item name " + id, price: 100 + i }); } }
export default class SortTable extends React.Component{ handleBtnClick = e => { if(order === 'desc'){ this.refs.table.handleSort('asc', 'name'); order = 'asc'; } else { this.refs.table.handleSort('desc', 'name'); order = 'desc'; } } render(){ return ( <div> <p style={{color:'red'}}>You cam click header to sort or click following button to perform a sorting by expose API</p> <button onClick={this.handleBtnClick}>Sort Product Name</button> <BootstrapTable ref="table" data={products}> <TableHeaderColumn dataField="id" isKey={true} dataSort={true}>Product ID</TableHeaderColumn> <TableHeaderColumn dataField="name" dataSort={true}>Product Name</TableHeaderColumn> <TableHeaderColumn dataField="price">Product Price</TableHeaderColumn> </BootstrapTable> </div> ); } };
addProducts(5); var order = 'desc';
random_line_split
sort-table.js
'use strict'; import React from 'react'; import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table'; var products = []; function addProducts(quantity) { var startId = products.length; for (var i = 0; i < quantity; i++) { var id = startId + i; products.push({ id: id, name: "Item name " + id, price: 100 + i }); } } addProducts(5); var order = 'desc'; export default class SortTable extends React.Component{ handleBtnClick = e => { if(order === 'desc'){ this.refs.table.handleSort('asc', 'name'); order = 'asc'; } else
} render(){ return ( <div> <p style={{color:'red'}}>You cam click header to sort or click following button to perform a sorting by expose API</p> <button onClick={this.handleBtnClick}>Sort Product Name</button> <BootstrapTable ref="table" data={products}> <TableHeaderColumn dataField="id" isKey={true} dataSort={true}>Product ID</TableHeaderColumn> <TableHeaderColumn dataField="name" dataSort={true}>Product Name</TableHeaderColumn> <TableHeaderColumn dataField="price">Product Price</TableHeaderColumn> </BootstrapTable> </div> ); } };
{ this.refs.table.handleSort('desc', 'name'); order = 'desc'; }
conditional_block
sort-table.js
'use strict'; import React from 'react'; import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table'; var products = []; function
(quantity) { var startId = products.length; for (var i = 0; i < quantity; i++) { var id = startId + i; products.push({ id: id, name: "Item name " + id, price: 100 + i }); } } addProducts(5); var order = 'desc'; export default class SortTable extends React.Component{ handleBtnClick = e => { if(order === 'desc'){ this.refs.table.handleSort('asc', 'name'); order = 'asc'; } else { this.refs.table.handleSort('desc', 'name'); order = 'desc'; } } render(){ return ( <div> <p style={{color:'red'}}>You cam click header to sort or click following button to perform a sorting by expose API</p> <button onClick={this.handleBtnClick}>Sort Product Name</button> <BootstrapTable ref="table" data={products}> <TableHeaderColumn dataField="id" isKey={true} dataSort={true}>Product ID</TableHeaderColumn> <TableHeaderColumn dataField="name" dataSort={true}>Product Name</TableHeaderColumn> <TableHeaderColumn dataField="price">Product Price</TableHeaderColumn> </BootstrapTable> </div> ); } };
addProducts
identifier_name
Range.ts
import Compiler from '../Compiler'; import Frame from '../Frame'; import { Token } from '../Lexer'; import Node from '../Node'; import Parser from '../Parser'; export default class RangeNode extends Node { public static parse(parser: Parser, next: () => Node) { let node = next(); if (parser.skipValue(Token.OPERATOR, '...'))
else if (parser.skipValue(Token.OPERATOR, '..')) { node = new RangeNode(node.line, node.col, { left: node, right: next(), exclusive: false }); } return node; } public exclusive: boolean; public left: any; public right: any; public compile(compiler: Compiler, frame: Frame) { const exclusive = this.exclusive ? 'true' : 'false'; compiler.emit(`lib.range(${ this.left.value }, ${ this.right.value }, 1, ${ exclusive })`, false); } }
{ node = new RangeNode(node.line, node.col, { left: node, right: next(), exclusive: true }); }
conditional_block
Range.ts
import Compiler from '../Compiler'; import Frame from '../Frame'; import { Token } from '../Lexer'; import Node from '../Node'; import Parser from '../Parser'; export default class RangeNode extends Node { public static parse(parser: Parser, next: () => Node) { let node = next(); if (parser.skipValue(Token.OPERATOR, '...')) { node = new RangeNode(node.line, node.col, { left: node, right: next(), exclusive: true }); } else if (parser.skipValue(Token.OPERATOR, '..')) { node = new RangeNode(node.line, node.col, { left: node, right: next(), exclusive: false });
public exclusive: boolean; public left: any; public right: any; public compile(compiler: Compiler, frame: Frame) { const exclusive = this.exclusive ? 'true' : 'false'; compiler.emit(`lib.range(${ this.left.value }, ${ this.right.value }, 1, ${ exclusive })`, false); } }
} return node; }
random_line_split
Range.ts
import Compiler from '../Compiler'; import Frame from '../Frame'; import { Token } from '../Lexer'; import Node from '../Node'; import Parser from '../Parser'; export default class RangeNode extends Node { public static parse(parser: Parser, next: () => Node)
public exclusive: boolean; public left: any; public right: any; public compile(compiler: Compiler, frame: Frame) { const exclusive = this.exclusive ? 'true' : 'false'; compiler.emit(`lib.range(${ this.left.value }, ${ this.right.value }, 1, ${ exclusive })`, false); } }
{ let node = next(); if (parser.skipValue(Token.OPERATOR, '...')) { node = new RangeNode(node.line, node.col, { left: node, right: next(), exclusive: true }); } else if (parser.skipValue(Token.OPERATOR, '..')) { node = new RangeNode(node.line, node.col, { left: node, right: next(), exclusive: false }); } return node; }
identifier_body
Range.ts
import Compiler from '../Compiler'; import Frame from '../Frame'; import { Token } from '../Lexer'; import Node from '../Node'; import Parser from '../Parser'; export default class RangeNode extends Node { public static parse(parser: Parser, next: () => Node) { let node = next(); if (parser.skipValue(Token.OPERATOR, '...')) { node = new RangeNode(node.line, node.col, { left: node, right: next(), exclusive: true }); } else if (parser.skipValue(Token.OPERATOR, '..')) { node = new RangeNode(node.line, node.col, { left: node, right: next(), exclusive: false }); } return node; } public exclusive: boolean; public left: any; public right: any; public
(compiler: Compiler, frame: Frame) { const exclusive = this.exclusive ? 'true' : 'false'; compiler.emit(`lib.range(${ this.left.value }, ${ this.right.value }, 1, ${ exclusive })`, false); } }
compile
identifier_name
gamepad.rs
//! Gamepad utility functions. //! //! This is going to be a bit of a work-in-progress as gamepad input //! gets fleshed out. The `gilrs` crate needs help to add better //! cross-platform support. Why not give it a hand? use gilrs::ConnectedGamepadsIterator; use std::fmt; pub use gilrs::{self, Event, Gamepad, Gilrs}; /// A unique identifier for a particular GamePad #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct GamepadId(pub(crate) gilrs::GamepadId); use crate::context::Context; use crate::error::GameResult; /// Trait object defining a gamepad/joystick context. pub trait GamepadContext { /// Returns a gamepad event. fn next_event(&mut self) -> Option<Event>; /// returns the `Gamepad` associated with an id. fn gamepad(&self, id: GamepadId) -> Gamepad; /// returns an iterator over the connected `Gamepad`s. fn gamepads(&self) -> GamepadsIterator; } /// A structure that contains gamepad state using `gilrs`. pub struct GilrsGamepadContext { pub(crate) gilrs: Gilrs, } impl fmt::Debug for GilrsGamepadContext { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<GilrsGamepadContext: {:p}>", self) } } impl GilrsGamepadContext { pub(crate) fn new() -> GameResult<Self> { let gilrs = Gilrs::new()?; Ok(GilrsGamepadContext { gilrs }) } } impl From<Gilrs> for GilrsGamepadContext { /// Converts from a `Gilrs` custom instance to a `GilrsGamepadContext` fn from(gilrs: Gilrs) -> Self { Self { gilrs } } } impl GamepadContext for GilrsGamepadContext { fn next_event(&mut self) -> Option<Event> { self.gilrs.next_event() } fn gamepad(&self, id: GamepadId) -> Gamepad { self.gilrs.gamepad(id.0) } fn gamepads(&self) -> GamepadsIterator { GamepadsIterator { wrapped: self.gilrs.gamepads(), } } } /// An iterator of the connected gamepads pub struct GamepadsIterator<'a> { wrapped: ConnectedGamepadsIterator<'a>, } impl<'a> fmt::Debug for GamepadsIterator<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<GamepadsIterator: {:p}>", self)
} } impl<'a> Iterator for GamepadsIterator<'a> { type Item = (GamepadId, Gamepad<'a>); fn next(&mut self) -> Option<(GamepadId, Gamepad<'a>)> { self.wrapped.next().map(|(id, gp)| (GamepadId(id), gp)) } } /// A structure that implements [`GamepadContext`](trait.GamepadContext.html) /// but does nothing; a stub for when you don't need it or are /// on a platform that `gilrs` doesn't support. #[derive(Debug, Clone, Copy, Default)] pub(crate) struct NullGamepadContext {} impl GamepadContext for NullGamepadContext { fn next_event(&mut self) -> Option<Event> { panic!("Gamepad module disabled") } fn gamepad(&self, _id: GamepadId) -> Gamepad { panic!("Gamepad module disabled") } fn gamepads(&self) -> GamepadsIterator { panic!("Gamepad module disabled") } } /// Returns the `Gamepad` associated with an `id`. pub fn gamepad(ctx: &Context, id: GamepadId) -> Gamepad { ctx.gamepad_context.gamepad(id) } /// Return an iterator of all the `Gamepads` that are connected. pub fn gamepads(ctx: &Context) -> GamepadsIterator { ctx.gamepad_context.gamepads() } // Properties gamepads might want: // Number of buttons // Number of axes // Name/ID // Is it connected? (For consoles?) // Whether or not they support vibration /* /// Lists all gamepads. With metainfo, maybe? pub fn list_gamepads() { unimplemented!() } /// Returns the state of the given axis on a gamepad. pub fn axis() { unimplemented!() } /// Returns the state of the given button on a gamepad. pub fn button_pressed() { unimplemented!() } */ #[cfg(test)] mod tests { use super::*; #[test] fn gilrs_init() { assert!(GilrsGamepadContext::new().is_ok()); } }
random_line_split
gamepad.rs
//! Gamepad utility functions. //! //! This is going to be a bit of a work-in-progress as gamepad input //! gets fleshed out. The `gilrs` crate needs help to add better //! cross-platform support. Why not give it a hand? use gilrs::ConnectedGamepadsIterator; use std::fmt; pub use gilrs::{self, Event, Gamepad, Gilrs}; /// A unique identifier for a particular GamePad #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct GamepadId(pub(crate) gilrs::GamepadId); use crate::context::Context; use crate::error::GameResult; /// Trait object defining a gamepad/joystick context. pub trait GamepadContext { /// Returns a gamepad event. fn next_event(&mut self) -> Option<Event>; /// returns the `Gamepad` associated with an id. fn gamepad(&self, id: GamepadId) -> Gamepad; /// returns an iterator over the connected `Gamepad`s. fn gamepads(&self) -> GamepadsIterator; } /// A structure that contains gamepad state using `gilrs`. pub struct GilrsGamepadContext { pub(crate) gilrs: Gilrs, } impl fmt::Debug for GilrsGamepadContext { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<GilrsGamepadContext: {:p}>", self) } } impl GilrsGamepadContext { pub(crate) fn new() -> GameResult<Self> { let gilrs = Gilrs::new()?; Ok(GilrsGamepadContext { gilrs }) } } impl From<Gilrs> for GilrsGamepadContext { /// Converts from a `Gilrs` custom instance to a `GilrsGamepadContext` fn from(gilrs: Gilrs) -> Self { Self { gilrs } } } impl GamepadContext for GilrsGamepadContext { fn next_event(&mut self) -> Option<Event> { self.gilrs.next_event() } fn gamepad(&self, id: GamepadId) -> Gamepad { self.gilrs.gamepad(id.0) } fn gamepads(&self) -> GamepadsIterator { GamepadsIterator { wrapped: self.gilrs.gamepads(), } } } /// An iterator of the connected gamepads pub struct GamepadsIterator<'a> { wrapped: ConnectedGamepadsIterator<'a>, } impl<'a> fmt::Debug for GamepadsIterator<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<GamepadsIterator: {:p}>", self) } } impl<'a> Iterator for GamepadsIterator<'a> { type Item = (GamepadId, Gamepad<'a>); fn
(&mut self) -> Option<(GamepadId, Gamepad<'a>)> { self.wrapped.next().map(|(id, gp)| (GamepadId(id), gp)) } } /// A structure that implements [`GamepadContext`](trait.GamepadContext.html) /// but does nothing; a stub for when you don't need it or are /// on a platform that `gilrs` doesn't support. #[derive(Debug, Clone, Copy, Default)] pub(crate) struct NullGamepadContext {} impl GamepadContext for NullGamepadContext { fn next_event(&mut self) -> Option<Event> { panic!("Gamepad module disabled") } fn gamepad(&self, _id: GamepadId) -> Gamepad { panic!("Gamepad module disabled") } fn gamepads(&self) -> GamepadsIterator { panic!("Gamepad module disabled") } } /// Returns the `Gamepad` associated with an `id`. pub fn gamepad(ctx: &Context, id: GamepadId) -> Gamepad { ctx.gamepad_context.gamepad(id) } /// Return an iterator of all the `Gamepads` that are connected. pub fn gamepads(ctx: &Context) -> GamepadsIterator { ctx.gamepad_context.gamepads() } // Properties gamepads might want: // Number of buttons // Number of axes // Name/ID // Is it connected? (For consoles?) // Whether or not they support vibration /* /// Lists all gamepads. With metainfo, maybe? pub fn list_gamepads() { unimplemented!() } /// Returns the state of the given axis on a gamepad. pub fn axis() { unimplemented!() } /// Returns the state of the given button on a gamepad. pub fn button_pressed() { unimplemented!() } */ #[cfg(test)] mod tests { use super::*; #[test] fn gilrs_init() { assert!(GilrsGamepadContext::new().is_ok()); } }
next
identifier_name
gamepad.rs
//! Gamepad utility functions. //! //! This is going to be a bit of a work-in-progress as gamepad input //! gets fleshed out. The `gilrs` crate needs help to add better //! cross-platform support. Why not give it a hand? use gilrs::ConnectedGamepadsIterator; use std::fmt; pub use gilrs::{self, Event, Gamepad, Gilrs}; /// A unique identifier for a particular GamePad #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct GamepadId(pub(crate) gilrs::GamepadId); use crate::context::Context; use crate::error::GameResult; /// Trait object defining a gamepad/joystick context. pub trait GamepadContext { /// Returns a gamepad event. fn next_event(&mut self) -> Option<Event>; /// returns the `Gamepad` associated with an id. fn gamepad(&self, id: GamepadId) -> Gamepad; /// returns an iterator over the connected `Gamepad`s. fn gamepads(&self) -> GamepadsIterator; } /// A structure that contains gamepad state using `gilrs`. pub struct GilrsGamepadContext { pub(crate) gilrs: Gilrs, } impl fmt::Debug for GilrsGamepadContext { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<GilrsGamepadContext: {:p}>", self) } } impl GilrsGamepadContext { pub(crate) fn new() -> GameResult<Self> { let gilrs = Gilrs::new()?; Ok(GilrsGamepadContext { gilrs }) } } impl From<Gilrs> for GilrsGamepadContext { /// Converts from a `Gilrs` custom instance to a `GilrsGamepadContext` fn from(gilrs: Gilrs) -> Self { Self { gilrs } } } impl GamepadContext for GilrsGamepadContext { fn next_event(&mut self) -> Option<Event> { self.gilrs.next_event() } fn gamepad(&self, id: GamepadId) -> Gamepad { self.gilrs.gamepad(id.0) } fn gamepads(&self) -> GamepadsIterator { GamepadsIterator { wrapped: self.gilrs.gamepads(), } } } /// An iterator of the connected gamepads pub struct GamepadsIterator<'a> { wrapped: ConnectedGamepadsIterator<'a>, } impl<'a> fmt::Debug for GamepadsIterator<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "<GamepadsIterator: {:p}>", self) } } impl<'a> Iterator for GamepadsIterator<'a> { type Item = (GamepadId, Gamepad<'a>); fn next(&mut self) -> Option<(GamepadId, Gamepad<'a>)> { self.wrapped.next().map(|(id, gp)| (GamepadId(id), gp)) } } /// A structure that implements [`GamepadContext`](trait.GamepadContext.html) /// but does nothing; a stub for when you don't need it or are /// on a platform that `gilrs` doesn't support. #[derive(Debug, Clone, Copy, Default)] pub(crate) struct NullGamepadContext {} impl GamepadContext for NullGamepadContext { fn next_event(&mut self) -> Option<Event>
fn gamepad(&self, _id: GamepadId) -> Gamepad { panic!("Gamepad module disabled") } fn gamepads(&self) -> GamepadsIterator { panic!("Gamepad module disabled") } } /// Returns the `Gamepad` associated with an `id`. pub fn gamepad(ctx: &Context, id: GamepadId) -> Gamepad { ctx.gamepad_context.gamepad(id) } /// Return an iterator of all the `Gamepads` that are connected. pub fn gamepads(ctx: &Context) -> GamepadsIterator { ctx.gamepad_context.gamepads() } // Properties gamepads might want: // Number of buttons // Number of axes // Name/ID // Is it connected? (For consoles?) // Whether or not they support vibration /* /// Lists all gamepads. With metainfo, maybe? pub fn list_gamepads() { unimplemented!() } /// Returns the state of the given axis on a gamepad. pub fn axis() { unimplemented!() } /// Returns the state of the given button on a gamepad. pub fn button_pressed() { unimplemented!() } */ #[cfg(test)] mod tests { use super::*; #[test] fn gilrs_init() { assert!(GilrsGamepadContext::new().is_ok()); } }
{ panic!("Gamepad module disabled") }
identifier_body
uniform-color-sk.ts
/** * @module modules/uniform-color-sk * @description <h2><code>uniform-color-sk</code></h2> * * A control for editing a float3 uniform which should be represented as a * color. * * The color uniform values are floats in [0, 1] and are in RGB order. */ import { $$ } from 'common-sk/modules/dom'; import { define } from 'elements-sk/define'; import { html } from 'lit-html'; import { ElementSk } from '../ElementSk'; import { Uniform, UniformControl } from '../uniform/uniform'; const defaultUniform: Uniform = { name: 'iColor', rows: 1, columns: 3, slot: 0, }; /** Converts the uniform value in the range [0, 1] into a two digit hex string. */ export const slotToHex = (uniforms: number[], slot: number): string => { const s = Math.floor(0.5 + uniforms[slot] * 255).toString(16); if (s.length === 1) { return `0${s}`; } return s; }; /** Converts the two digit hex into a uniform value in the range [0, 1] */ export const hexToSlot = (hexDigits: string, uniforms: number[], slot: number): void => { let colorAsFloat = parseInt(hexDigits, 16) / 255; // Truncate to 4 digits of precision. colorAsFloat = Math.floor(colorAsFloat * 10000) / 10000; uniforms[slot] = colorAsFloat; }; export class UniformColorSk extends ElementSk implements UniformControl { private _uniform: Uniform = defaultUniform; private colorInput: HTMLInputElement | null = null; private alphaInput: HTMLInputElement | null = null; constructor() { super(UniformColorSk.template); } private static template = (ele: UniformColorSk) => html` <label> <input id=colorInput value="#808080" type="color" /> ${ele.uniform.name} </label> <label class="${ele.hasAlphaChannel() ? '' : 'hidden'}"> <input id=alphaInput min="0" max="1" step="0.001" type="range" /> Alpha </label> `; connectedCallback(): void { super.connectedCallback(); this._render(); this.colorInput = $$<HTMLInputElement>('#colorInput', this); this.alphaInput = $$<HTMLInputElement>('#alphaInput', this); } /** The description of the uniform. */ get uniform(): Uniform { return this._uniform!; } set uniform(val: Uniform) { if ((val.columns !== 3 && val.columns !== 4) || val.rows !== 1) { throw new Error('uniform-color-sk can only work on a uniform of float3 or float4.'); } this._uniform = val; this._render();
const hex = this.colorInput!.value; hexToSlot(hex.slice(1, 3), uniforms, this.uniform.slot); hexToSlot(hex.slice(3, 5), uniforms, this.uniform.slot + 1); hexToSlot(hex.slice(5, 7), uniforms, this.uniform.slot + 2); // Set the alpha channel if present. if (this.hasAlphaChannel()) { uniforms[this.uniform.slot + 3] = this.alphaInput!.valueAsNumber; } } restoreUniformValues(uniforms: number[]): void { const r = slotToHex(uniforms, this.uniform.slot); const g = slotToHex(uniforms, this.uniform.slot + 1); const b = slotToHex(uniforms, this.uniform.slot + 2); this.colorInput!.value = `#${r}${g}${b}`; if (this.hasAlphaChannel()) { this.alphaInput!.valueAsNumber = uniforms[this.uniform.slot + 3]; } } onRAF(): void { // noop. } needsRAF(): boolean { return false; } private hasAlphaChannel(): boolean { return this._uniform.columns === 4; } } define('uniform-color-sk', UniformColorSk);
} /** Copies the values of the control into the uniforms array. */ applyUniformValues(uniforms: number[]): void { // Set all three floats from the color.
random_line_split
uniform-color-sk.ts
/** * @module modules/uniform-color-sk * @description <h2><code>uniform-color-sk</code></h2> * * A control for editing a float3 uniform which should be represented as a * color. * * The color uniform values are floats in [0, 1] and are in RGB order. */ import { $$ } from 'common-sk/modules/dom'; import { define } from 'elements-sk/define'; import { html } from 'lit-html'; import { ElementSk } from '../ElementSk'; import { Uniform, UniformControl } from '../uniform/uniform'; const defaultUniform: Uniform = { name: 'iColor', rows: 1, columns: 3, slot: 0, }; /** Converts the uniform value in the range [0, 1] into a two digit hex string. */ export const slotToHex = (uniforms: number[], slot: number): string => { const s = Math.floor(0.5 + uniforms[slot] * 255).toString(16); if (s.length === 1) { return `0${s}`; } return s; }; /** Converts the two digit hex into a uniform value in the range [0, 1] */ export const hexToSlot = (hexDigits: string, uniforms: number[], slot: number): void => { let colorAsFloat = parseInt(hexDigits, 16) / 255; // Truncate to 4 digits of precision. colorAsFloat = Math.floor(colorAsFloat * 10000) / 10000; uniforms[slot] = colorAsFloat; }; export class UniformColorSk extends ElementSk implements UniformControl { private _uniform: Uniform = defaultUniform; private colorInput: HTMLInputElement | null = null; private alphaInput: HTMLInputElement | null = null; constructor() { super(UniformColorSk.template); } private static template = (ele: UniformColorSk) => html` <label> <input id=colorInput value="#808080" type="color" /> ${ele.uniform.name} </label> <label class="${ele.hasAlphaChannel() ? '' : 'hidden'}"> <input id=alphaInput min="0" max="1" step="0.001" type="range" /> Alpha </label> `; connectedCallback(): void { super.connectedCallback(); this._render(); this.colorInput = $$<HTMLInputElement>('#colorInput', this); this.alphaInput = $$<HTMLInputElement>('#alphaInput', this); } /** The description of the uniform. */ get
(): Uniform { return this._uniform!; } set uniform(val: Uniform) { if ((val.columns !== 3 && val.columns !== 4) || val.rows !== 1) { throw new Error('uniform-color-sk can only work on a uniform of float3 or float4.'); } this._uniform = val; this._render(); } /** Copies the values of the control into the uniforms array. */ applyUniformValues(uniforms: number[]): void { // Set all three floats from the color. const hex = this.colorInput!.value; hexToSlot(hex.slice(1, 3), uniforms, this.uniform.slot); hexToSlot(hex.slice(3, 5), uniforms, this.uniform.slot + 1); hexToSlot(hex.slice(5, 7), uniforms, this.uniform.slot + 2); // Set the alpha channel if present. if (this.hasAlphaChannel()) { uniforms[this.uniform.slot + 3] = this.alphaInput!.valueAsNumber; } } restoreUniformValues(uniforms: number[]): void { const r = slotToHex(uniforms, this.uniform.slot); const g = slotToHex(uniforms, this.uniform.slot + 1); const b = slotToHex(uniforms, this.uniform.slot + 2); this.colorInput!.value = `#${r}${g}${b}`; if (this.hasAlphaChannel()) { this.alphaInput!.valueAsNumber = uniforms[this.uniform.slot + 3]; } } onRAF(): void { // noop. } needsRAF(): boolean { return false; } private hasAlphaChannel(): boolean { return this._uniform.columns === 4; } } define('uniform-color-sk', UniformColorSk);
uniform
identifier_name
uniform-color-sk.ts
/** * @module modules/uniform-color-sk * @description <h2><code>uniform-color-sk</code></h2> * * A control for editing a float3 uniform which should be represented as a * color. * * The color uniform values are floats in [0, 1] and are in RGB order. */ import { $$ } from 'common-sk/modules/dom'; import { define } from 'elements-sk/define'; import { html } from 'lit-html'; import { ElementSk } from '../ElementSk'; import { Uniform, UniformControl } from '../uniform/uniform'; const defaultUniform: Uniform = { name: 'iColor', rows: 1, columns: 3, slot: 0, }; /** Converts the uniform value in the range [0, 1] into a two digit hex string. */ export const slotToHex = (uniforms: number[], slot: number): string => { const s = Math.floor(0.5 + uniforms[slot] * 255).toString(16); if (s.length === 1) { return `0${s}`; } return s; }; /** Converts the two digit hex into a uniform value in the range [0, 1] */ export const hexToSlot = (hexDigits: string, uniforms: number[], slot: number): void => { let colorAsFloat = parseInt(hexDigits, 16) / 255; // Truncate to 4 digits of precision. colorAsFloat = Math.floor(colorAsFloat * 10000) / 10000; uniforms[slot] = colorAsFloat; }; export class UniformColorSk extends ElementSk implements UniformControl { private _uniform: Uniform = defaultUniform; private colorInput: HTMLInputElement | null = null; private alphaInput: HTMLInputElement | null = null; constructor() { super(UniformColorSk.template); } private static template = (ele: UniformColorSk) => html` <label> <input id=colorInput value="#808080" type="color" /> ${ele.uniform.name} </label> <label class="${ele.hasAlphaChannel() ? '' : 'hidden'}"> <input id=alphaInput min="0" max="1" step="0.001" type="range" /> Alpha </label> `; connectedCallback(): void { super.connectedCallback(); this._render(); this.colorInput = $$<HTMLInputElement>('#colorInput', this); this.alphaInput = $$<HTMLInputElement>('#alphaInput', this); } /** The description of the uniform. */ get uniform(): Uniform { return this._uniform!; } set uniform(val: Uniform) { if ((val.columns !== 3 && val.columns !== 4) || val.rows !== 1) { throw new Error('uniform-color-sk can only work on a uniform of float3 or float4.'); } this._uniform = val; this._render(); } /** Copies the values of the control into the uniforms array. */ applyUniformValues(uniforms: number[]): void { // Set all three floats from the color. const hex = this.colorInput!.value; hexToSlot(hex.slice(1, 3), uniforms, this.uniform.slot); hexToSlot(hex.slice(3, 5), uniforms, this.uniform.slot + 1); hexToSlot(hex.slice(5, 7), uniforms, this.uniform.slot + 2); // Set the alpha channel if present. if (this.hasAlphaChannel()) { uniforms[this.uniform.slot + 3] = this.alphaInput!.valueAsNumber; } } restoreUniformValues(uniforms: number[]): void { const r = slotToHex(uniforms, this.uniform.slot); const g = slotToHex(uniforms, this.uniform.slot + 1); const b = slotToHex(uniforms, this.uniform.slot + 2); this.colorInput!.value = `#${r}${g}${b}`; if (this.hasAlphaChannel())
} onRAF(): void { // noop. } needsRAF(): boolean { return false; } private hasAlphaChannel(): boolean { return this._uniform.columns === 4; } } define('uniform-color-sk', UniformColorSk);
{ this.alphaInput!.valueAsNumber = uniforms[this.uniform.slot + 3]; }
conditional_block
uniform-color-sk.ts
/** * @module modules/uniform-color-sk * @description <h2><code>uniform-color-sk</code></h2> * * A control for editing a float3 uniform which should be represented as a * color. * * The color uniform values are floats in [0, 1] and are in RGB order. */ import { $$ } from 'common-sk/modules/dom'; import { define } from 'elements-sk/define'; import { html } from 'lit-html'; import { ElementSk } from '../ElementSk'; import { Uniform, UniformControl } from '../uniform/uniform'; const defaultUniform: Uniform = { name: 'iColor', rows: 1, columns: 3, slot: 0, }; /** Converts the uniform value in the range [0, 1] into a two digit hex string. */ export const slotToHex = (uniforms: number[], slot: number): string => { const s = Math.floor(0.5 + uniforms[slot] * 255).toString(16); if (s.length === 1) { return `0${s}`; } return s; }; /** Converts the two digit hex into a uniform value in the range [0, 1] */ export const hexToSlot = (hexDigits: string, uniforms: number[], slot: number): void => { let colorAsFloat = parseInt(hexDigits, 16) / 255; // Truncate to 4 digits of precision. colorAsFloat = Math.floor(colorAsFloat * 10000) / 10000; uniforms[slot] = colorAsFloat; }; export class UniformColorSk extends ElementSk implements UniformControl { private _uniform: Uniform = defaultUniform; private colorInput: HTMLInputElement | null = null; private alphaInput: HTMLInputElement | null = null; constructor() { super(UniformColorSk.template); } private static template = (ele: UniformColorSk) => html` <label> <input id=colorInput value="#808080" type="color" /> ${ele.uniform.name} </label> <label class="${ele.hasAlphaChannel() ? '' : 'hidden'}"> <input id=alphaInput min="0" max="1" step="0.001" type="range" /> Alpha </label> `; connectedCallback(): void { super.connectedCallback(); this._render(); this.colorInput = $$<HTMLInputElement>('#colorInput', this); this.alphaInput = $$<HTMLInputElement>('#alphaInput', this); } /** The description of the uniform. */ get uniform(): Uniform
set uniform(val: Uniform) { if ((val.columns !== 3 && val.columns !== 4) || val.rows !== 1) { throw new Error('uniform-color-sk can only work on a uniform of float3 or float4.'); } this._uniform = val; this._render(); } /** Copies the values of the control into the uniforms array. */ applyUniformValues(uniforms: number[]): void { // Set all three floats from the color. const hex = this.colorInput!.value; hexToSlot(hex.slice(1, 3), uniforms, this.uniform.slot); hexToSlot(hex.slice(3, 5), uniforms, this.uniform.slot + 1); hexToSlot(hex.slice(5, 7), uniforms, this.uniform.slot + 2); // Set the alpha channel if present. if (this.hasAlphaChannel()) { uniforms[this.uniform.slot + 3] = this.alphaInput!.valueAsNumber; } } restoreUniformValues(uniforms: number[]): void { const r = slotToHex(uniforms, this.uniform.slot); const g = slotToHex(uniforms, this.uniform.slot + 1); const b = slotToHex(uniforms, this.uniform.slot + 2); this.colorInput!.value = `#${r}${g}${b}`; if (this.hasAlphaChannel()) { this.alphaInput!.valueAsNumber = uniforms[this.uniform.slot + 3]; } } onRAF(): void { // noop. } needsRAF(): boolean { return false; } private hasAlphaChannel(): boolean { return this._uniform.columns === 4; } } define('uniform-color-sk', UniformColorSk);
{ return this._uniform!; }
identifier_body
SrvShowHandsDataSerializer.ts
import { ArrayBufferBuilder } from "../../../../utils/ArrayBufferBuilder"; import { BitsReader } from "../../../../utils/BitsReader"; import { SerializerUtils } from "../../../../utils/SerializerUtils"; import { SrvShowHandsData } from "../data/SrvShowHandsData"; import { HandInfoData } from "../data/HandInfoData"; import { HandInfoDataSerializer } from "../serializers/HandInfoDataSerializer"; export class SrvShowHandsDataSerializer { public static serialize(buffer: ArrayBufferBuilder, data: SrvShowHandsData): void
public static deserialize(buffer: ArrayBufferBuilder, data: SrvShowHandsData): void { data.showHandListEvalLowHand = []; for (let i = 0, l = buffer.getUint8(); i < l; i++){ let temp = new HandInfoData(data); HandInfoDataSerializer.deserialize(buffer, temp); data.showHandListEvalLowHand.push( temp ); } } }
{ for (let i = 0, l = data.showHandListEvalLowHand.length , t = buffer.setUint8( l ); i < l; i++){ let temp = data.showHandListEvalLowHand[i]; HandInfoDataSerializer.serialize(buffer, temp); } }
identifier_body
SrvShowHandsDataSerializer.ts
import { ArrayBufferBuilder } from "../../../../utils/ArrayBufferBuilder"; import { BitsReader } from "../../../../utils/BitsReader"; import { SerializerUtils } from "../../../../utils/SerializerUtils"; import { SrvShowHandsData } from "../data/SrvShowHandsData"; import { HandInfoData } from "../data/HandInfoData"; import { HandInfoDataSerializer } from "../serializers/HandInfoDataSerializer"; export class SrvShowHandsDataSerializer { public static serialize(buffer: ArrayBufferBuilder, data: SrvShowHandsData): void { for (let i = 0, l = data.showHandListEvalLowHand.length , t = buffer.setUint8( l ); i < l; i++)
} public static deserialize(buffer: ArrayBufferBuilder, data: SrvShowHandsData): void { data.showHandListEvalLowHand = []; for (let i = 0, l = buffer.getUint8(); i < l; i++){ let temp = new HandInfoData(data); HandInfoDataSerializer.deserialize(buffer, temp); data.showHandListEvalLowHand.push( temp ); } } }
{ let temp = data.showHandListEvalLowHand[i]; HandInfoDataSerializer.serialize(buffer, temp); }
conditional_block
SrvShowHandsDataSerializer.ts
import { ArrayBufferBuilder } from "../../../../utils/ArrayBufferBuilder"; import { BitsReader } from "../../../../utils/BitsReader"; import { SerializerUtils } from "../../../../utils/SerializerUtils"; import { SrvShowHandsData } from "../data/SrvShowHandsData"; import { HandInfoData } from "../data/HandInfoData"; import { HandInfoDataSerializer } from "../serializers/HandInfoDataSerializer"; export class SrvShowHandsDataSerializer { public static serialize(buffer: ArrayBufferBuilder, data: SrvShowHandsData): void { for (let i = 0, l = data.showHandListEvalLowHand.length , t = buffer.setUint8( l ); i < l; i++){ let temp = data.showHandListEvalLowHand[i]; HandInfoDataSerializer.serialize(buffer, temp); } } public static
(buffer: ArrayBufferBuilder, data: SrvShowHandsData): void { data.showHandListEvalLowHand = []; for (let i = 0, l = buffer.getUint8(); i < l; i++){ let temp = new HandInfoData(data); HandInfoDataSerializer.deserialize(buffer, temp); data.showHandListEvalLowHand.push( temp ); } } }
deserialize
identifier_name
SrvShowHandsDataSerializer.ts
import { ArrayBufferBuilder } from "../../../../utils/ArrayBufferBuilder"; import { BitsReader } from "../../../../utils/BitsReader"; import { SerializerUtils } from "../../../../utils/SerializerUtils";
import { HandInfoDataSerializer } from "../serializers/HandInfoDataSerializer"; export class SrvShowHandsDataSerializer { public static serialize(buffer: ArrayBufferBuilder, data: SrvShowHandsData): void { for (let i = 0, l = data.showHandListEvalLowHand.length , t = buffer.setUint8( l ); i < l; i++){ let temp = data.showHandListEvalLowHand[i]; HandInfoDataSerializer.serialize(buffer, temp); } } public static deserialize(buffer: ArrayBufferBuilder, data: SrvShowHandsData): void { data.showHandListEvalLowHand = []; for (let i = 0, l = buffer.getUint8(); i < l; i++){ let temp = new HandInfoData(data); HandInfoDataSerializer.deserialize(buffer, temp); data.showHandListEvalLowHand.push( temp ); } } }
import { SrvShowHandsData } from "../data/SrvShowHandsData"; import { HandInfoData } from "../data/HandInfoData";
random_line_split
StopScreenShareSVGIcon.tsx
// This is a generated file from running the "createIcons" script. This file should not be updated manually. import { forwardRef } from "react"; import { SVGIcon, SVGIconProps } from "@react-md/icon";
<path d="M21.22 18.02l2 2H24v-2h-2.78zm.77-2l.01-10c0-1.11-.9-2-2-2H7.22l5.23 5.23c.18-.04.36-.07.55-.1V7.02l4 3.73-1.58 1.47 5.54 5.54c.61-.33 1.03-.99 1.03-1.74zM2.39 1.73L1.11 3l1.54 1.54c-.4.36-.65.89-.65 1.48v10c0 1.1.89 2 2 2H0v2h18.13l2.71 2.71 1.27-1.27L2.39 1.73zM7 15.02c.31-1.48.92-2.95 2.07-4.06l1.59 1.59c-1.54.38-2.7 1.18-3.66 2.47z" /> </SVGIcon> ); } );
export const StopScreenShareSVGIcon = forwardRef<SVGSVGElement, SVGIconProps>( function StopScreenShareSVGIcon(props, ref) { return ( <SVGIcon {...props} ref={ref}>
random_line_split
dir_mod.py
#! /usr/bin/env python import os import time import traceback import re import locale import subprocess import zlib import zipfile import private.metadata as metadata import private.messages as messages from glob import glob from private.exceptionclasses import CustomError, CritError, SyntaxError, LogicError from private.preliminaries import print_error #== Directory modification functions ================= def delete_files(pathname): """Delete files specified by a path This function deletes a possibly-empty list of files whose names match `pathname`, which must be a string containing a path specification. `pathname` can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools/*/*.gif). It can contain shell-style wildcards. """ print "\nDelete files", pathname for f in glob(pathname): os.remove(f) def remove_dir(pathname, options = '@DEFAULTVALUE@'): """Remove a directory This function completely removes the directory specified by `pathname` using the 'rmdir' command on Windows platforms and the 'rm' command on Unix platforms. This is useful for removing symlinks without deleting the source files or directory. """ if os.name == 'posix': os_command = 'rmdirunix' if pathname[-1] == '/': pathname = pathname[0:-1] else: os_command = 'rmdirwin' command = metadata.commands[os_command] if options == '@DEFAULTVALUE@': options = metadata.default_options[os_command] subprocess.check_call(command % (options, pathname), shell=True) def check_manifest(manifestlog = '@DEFAULTVALUE@', output_dir = '@DEFAULTVALUE@', makelog = '@DEFAULTVALUE@'): """ Produce an error if there are any .dta files in "output_dir" and all non-hidden sub-directories that are not in the manifest file "manifestlog", and produce a warning if there are .txt or .csv files not in the manifest along with a list of these files. All log is printed to "makelog" log file. """ # metadata.settings should not be part of argument defaults so that they can be # overwritten by make_log.set_option if manifestlog == '@DEFAULTVALUE@': manifestlog = metadata.settings['manifest_file'] if output_dir == '@DEFAULTVALUE@': output_dir = metadata.settings['output_dir'] if makelog == '@DEFAULTVALUE@': makelog = metadata.settings['makelog_file'] print "\nCheck manifest log file", manifestlog # Open main log file try: LOGFILE = open(makelog, 'ab') except Exception as errmsg: print errmsg raise CritError(messages.crit_error_log % makelog) try: # Open manifest log file try: MANIFESTFILE = open(manifestlog, 'rU') except Exception as errmsg: print errmsg raise CritError(messages.crit_error_log % manifestlog) manifest_lines = MANIFESTFILE.readlines() MANIFESTFILE.close() # Get file list try: file_list = [];
if ext == '': filepath = filepath + '.dta' file_list.append( filepath ) except Exception as errmsg: print errmsg raise SyntaxError(messages.syn_error_manifest % manifestlog) if not os.path.isdir(output_dir): raise CritError(messages.crit_error_no_directory % (output_dir)) # Loop over all levels of sub-directories of output_dir for root, dirs, files in os.walk(output_dir, topdown = True): # Ignore non-hidden sub-directories dirs_to_keep = [] for dirname in dirs: if not dirname.startswith('.'): dirs_to_keep.append(dirname) dirs[:] = dirs_to_keep # Check each file for filename in files: ext = os.path.splitext(filename)[1] fullpath = os.path.abspath( os.path.join(root, filename) ) # non-hidden .dta file: error if (not filename.startswith('.')) and (ext == '.dta'): print 'Checking: ', fullpath if not (fullpath in file_list): raise CritError(messages.crit_error_no_dta_file % (filename, manifestlog)) # non-hidden .csv file: warning if (not filename.startswith('.')) and (ext == '.csv'): print 'Checking: ', fullpath if not (fullpath in file_list): print messages.note_no_csv_file % (filename, manifestlog) print >> LOGFILE, messages.note_no_csv_file % (filename, manifestlog) # non-hidden .txt file: warning if (not filename.startswith('.')) and (ext == '.txt'): print 'Checking: ', fullpath if not (fullpath in file_list): print messages.note_no_txt_file % (filename, manifestlog) print >> LOGFILE, messages.note_no_txt_file % (filename, manifestlog) except: print_error(LOGFILE) LOGFILE.close() def list_directory(top, makelog = '@DEFAULTVALUE@'): """List directories This function lists all non-hidden sub-directories of the directory specified by `top`, a path, and their content from the top down. It writes their names, modified times, and sizes in bytes to the log file specified by the path `makelog`. """ # metadata.settings should not be part of argument defaults so that they can be # overwritten by make_log.set_option if makelog == '@DEFAULTVALUE@': makelog = metadata.settings['makelog_file'] print "\nList all files in directory", top # To print numbers (file sizes) with thousand separator locale.setlocale(locale.LC_ALL, '') makelog = re.sub('\\\\', '/', makelog) try: LOGFILE = open(makelog, 'ab') except Exception as errmsg: print errmsg raise CritError(messages.crit_error_log % makelog) print >> LOGFILE, '\n' print >> LOGFILE, 'List of all files in sub-directories in', top try: if os.path.isdir(top): for root, dirs, files in os.walk(top, topdown = True): # Ignore non-hidden sub-directories dirs_to_keep = [] for dirname in dirs: if not dirname.startswith('.'): dirs_to_keep.append(dirname) dirs[:] = dirs_to_keep # Print out the sub-directory and its time stamp created = os.stat(root).st_mtime asciiTime = time.asctime(time.localtime(created)) print >> LOGFILE, root print >> LOGFILE, 'created/modified', asciiTime # Print out all the files in the sub-directories for name in files: full_name = os.path.join(root, name) created = os.path.getmtime(full_name) size = os.path.getsize(full_name) asciiTime = time.asctime(time.localtime(created)) print >> LOGFILE, '%50s' % name, '--- created/modified', asciiTime, \ '(', locale.format('%d', size, 1), 'bytes )' except: print_error(LOGFILE) print >> LOGFILE, '\n' LOGFILE.close() def clear_dirs(*args): """Create fresh directories This function creates a directory for each path specified in *args if such a directory does not already exist. It deletes all files in each directory that already exists while keeping directory structure (i.e. sub-directories). This function is safe for symlinks. """ for dir in args: if os.path.isdir(dir): remove_dir(dir) os.makedirs(dir) print 'Cleared:', dir def unzip(file_name, output_dir): zip = zipfile.ZipFile(file_name, allowZip64=True) zip.extractall(output_dir) zip.close() def unzip_externals(external_dir='@DEFAULTVALUE@'): if external_dir == '@DEFAULTVALUE@': external_dir = metadata.settings['external_dir'] for dirname, subdirs, files in os.walk(external_dir): for filename in files: absname = os.path.abspath(os.path.join(dirname, filename)) if zipfile.is_zipfile(absname): unzip(absname, dirname) def zip_dir(source_dir, dest): zf = zipfile.ZipFile('%s.zip' % (dest), 'w', zipfile.ZIP_DEFLATED, allowZip64=True) abs_src = os.path.abspath(source_dir) for dirname, subdirs, files in os.walk(source_dir): for filename in files: absname = os.path.abspath(os.path.join(dirname, filename)) arcname = absname[len(abs_src) + 1:] print 'zipping %s as %s' % (os.path.join(dirname, filename), arcname) zf.write(absname, arcname) zf.close()
for i in range(len(manifest_lines)): if manifest_lines[i].startswith('File: '): filepath = os.path.abspath(manifest_lines[i][6:].rstrip()) ext = os.path.splitext(filepath)[1]
random_line_split
dir_mod.py
#! /usr/bin/env python import os import time import traceback import re import locale import subprocess import zlib import zipfile import private.metadata as metadata import private.messages as messages from glob import glob from private.exceptionclasses import CustomError, CritError, SyntaxError, LogicError from private.preliminaries import print_error #== Directory modification functions ================= def delete_files(pathname): """Delete files specified by a path This function deletes a possibly-empty list of files whose names match `pathname`, which must be a string containing a path specification. `pathname` can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools/*/*.gif). It can contain shell-style wildcards. """ print "\nDelete files", pathname for f in glob(pathname): os.remove(f) def remove_dir(pathname, options = '@DEFAULTVALUE@'): """Remove a directory This function completely removes the directory specified by `pathname` using the 'rmdir' command on Windows platforms and the 'rm' command on Unix platforms. This is useful for removing symlinks without deleting the source files or directory. """ if os.name == 'posix': os_command = 'rmdirunix' if pathname[-1] == '/': pathname = pathname[0:-1] else: os_command = 'rmdirwin' command = metadata.commands[os_command] if options == '@DEFAULTVALUE@': options = metadata.default_options[os_command] subprocess.check_call(command % (options, pathname), shell=True) def
(manifestlog = '@DEFAULTVALUE@', output_dir = '@DEFAULTVALUE@', makelog = '@DEFAULTVALUE@'): """ Produce an error if there are any .dta files in "output_dir" and all non-hidden sub-directories that are not in the manifest file "manifestlog", and produce a warning if there are .txt or .csv files not in the manifest along with a list of these files. All log is printed to "makelog" log file. """ # metadata.settings should not be part of argument defaults so that they can be # overwritten by make_log.set_option if manifestlog == '@DEFAULTVALUE@': manifestlog = metadata.settings['manifest_file'] if output_dir == '@DEFAULTVALUE@': output_dir = metadata.settings['output_dir'] if makelog == '@DEFAULTVALUE@': makelog = metadata.settings['makelog_file'] print "\nCheck manifest log file", manifestlog # Open main log file try: LOGFILE = open(makelog, 'ab') except Exception as errmsg: print errmsg raise CritError(messages.crit_error_log % makelog) try: # Open manifest log file try: MANIFESTFILE = open(manifestlog, 'rU') except Exception as errmsg: print errmsg raise CritError(messages.crit_error_log % manifestlog) manifest_lines = MANIFESTFILE.readlines() MANIFESTFILE.close() # Get file list try: file_list = []; for i in range(len(manifest_lines)): if manifest_lines[i].startswith('File: '): filepath = os.path.abspath(manifest_lines[i][6:].rstrip()) ext = os.path.splitext(filepath)[1] if ext == '': filepath = filepath + '.dta' file_list.append( filepath ) except Exception as errmsg: print errmsg raise SyntaxError(messages.syn_error_manifest % manifestlog) if not os.path.isdir(output_dir): raise CritError(messages.crit_error_no_directory % (output_dir)) # Loop over all levels of sub-directories of output_dir for root, dirs, files in os.walk(output_dir, topdown = True): # Ignore non-hidden sub-directories dirs_to_keep = [] for dirname in dirs: if not dirname.startswith('.'): dirs_to_keep.append(dirname) dirs[:] = dirs_to_keep # Check each file for filename in files: ext = os.path.splitext(filename)[1] fullpath = os.path.abspath( os.path.join(root, filename) ) # non-hidden .dta file: error if (not filename.startswith('.')) and (ext == '.dta'): print 'Checking: ', fullpath if not (fullpath in file_list): raise CritError(messages.crit_error_no_dta_file % (filename, manifestlog)) # non-hidden .csv file: warning if (not filename.startswith('.')) and (ext == '.csv'): print 'Checking: ', fullpath if not (fullpath in file_list): print messages.note_no_csv_file % (filename, manifestlog) print >> LOGFILE, messages.note_no_csv_file % (filename, manifestlog) # non-hidden .txt file: warning if (not filename.startswith('.')) and (ext == '.txt'): print 'Checking: ', fullpath if not (fullpath in file_list): print messages.note_no_txt_file % (filename, manifestlog) print >> LOGFILE, messages.note_no_txt_file % (filename, manifestlog) except: print_error(LOGFILE) LOGFILE.close() def list_directory(top, makelog = '@DEFAULTVALUE@'): """List directories This function lists all non-hidden sub-directories of the directory specified by `top`, a path, and their content from the top down. It writes their names, modified times, and sizes in bytes to the log file specified by the path `makelog`. """ # metadata.settings should not be part of argument defaults so that they can be # overwritten by make_log.set_option if makelog == '@DEFAULTVALUE@': makelog = metadata.settings['makelog_file'] print "\nList all files in directory", top # To print numbers (file sizes) with thousand separator locale.setlocale(locale.LC_ALL, '') makelog = re.sub('\\\\', '/', makelog) try: LOGFILE = open(makelog, 'ab') except Exception as errmsg: print errmsg raise CritError(messages.crit_error_log % makelog) print >> LOGFILE, '\n' print >> LOGFILE, 'List of all files in sub-directories in', top try: if os.path.isdir(top): for root, dirs, files in os.walk(top, topdown = True): # Ignore non-hidden sub-directories dirs_to_keep = [] for dirname in dirs: if not dirname.startswith('.'): dirs_to_keep.append(dirname) dirs[:] = dirs_to_keep # Print out the sub-directory and its time stamp created = os.stat(root).st_mtime asciiTime = time.asctime(time.localtime(created)) print >> LOGFILE, root print >> LOGFILE, 'created/modified', asciiTime # Print out all the files in the sub-directories for name in files: full_name = os.path.join(root, name) created = os.path.getmtime(full_name) size = os.path.getsize(full_name) asciiTime = time.asctime(time.localtime(created)) print >> LOGFILE, '%50s' % name, '--- created/modified', asciiTime, \ '(', locale.format('%d', size, 1), 'bytes )' except: print_error(LOGFILE) print >> LOGFILE, '\n' LOGFILE.close() def clear_dirs(*args): """Create fresh directories This function creates a directory for each path specified in *args if such a directory does not already exist. It deletes all files in each directory that already exists while keeping directory structure (i.e. sub-directories). This function is safe for symlinks. """ for dir in args: if os.path.isdir(dir): remove_dir(dir) os.makedirs(dir) print 'Cleared:', dir def unzip(file_name, output_dir): zip = zipfile.ZipFile(file_name, allowZip64=True) zip.extractall(output_dir) zip.close() def unzip_externals(external_dir='@DEFAULTVALUE@'): if external_dir == '@DEFAULTVALUE@': external_dir = metadata.settings['external_dir'] for dirname, subdirs, files in os.walk(external_dir): for filename in files: absname = os.path.abspath(os.path.join(dirname, filename)) if zipfile.is_zipfile(absname): unzip(absname, dirname) def zip_dir(source_dir, dest): zf = zipfile.ZipFile('%s.zip' % (dest), 'w', zipfile.ZIP_DEFLATED, allowZip64=True) abs_src = os.path.abspath(source_dir) for dirname, subdirs, files in os.walk(source_dir): for filename in files: absname = os.path.abspath(os.path.join(dirname, filename)) arcname = absname[len(abs_src) + 1:] print 'zipping %s as %s' % (os.path.join(dirname, filename), arcname) zf.write(absname, arcname) zf.close()
check_manifest
identifier_name
dir_mod.py
#! /usr/bin/env python import os import time import traceback import re import locale import subprocess import zlib import zipfile import private.metadata as metadata import private.messages as messages from glob import glob from private.exceptionclasses import CustomError, CritError, SyntaxError, LogicError from private.preliminaries import print_error #== Directory modification functions ================= def delete_files(pathname): """Delete files specified by a path This function deletes a possibly-empty list of files whose names match `pathname`, which must be a string containing a path specification. `pathname` can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools/*/*.gif). It can contain shell-style wildcards. """ print "\nDelete files", pathname for f in glob(pathname): os.remove(f) def remove_dir(pathname, options = '@DEFAULTVALUE@'): """Remove a directory This function completely removes the directory specified by `pathname` using the 'rmdir' command on Windows platforms and the 'rm' command on Unix platforms. This is useful for removing symlinks without deleting the source files or directory. """ if os.name == 'posix': os_command = 'rmdirunix' if pathname[-1] == '/': pathname = pathname[0:-1] else: os_command = 'rmdirwin' command = metadata.commands[os_command] if options == '@DEFAULTVALUE@': options = metadata.default_options[os_command] subprocess.check_call(command % (options, pathname), shell=True) def check_manifest(manifestlog = '@DEFAULTVALUE@', output_dir = '@DEFAULTVALUE@', makelog = '@DEFAULTVALUE@'): """ Produce an error if there are any .dta files in "output_dir" and all non-hidden sub-directories that are not in the manifest file "manifestlog", and produce a warning if there are .txt or .csv files not in the manifest along with a list of these files. All log is printed to "makelog" log file. """ # metadata.settings should not be part of argument defaults so that they can be # overwritten by make_log.set_option if manifestlog == '@DEFAULTVALUE@': manifestlog = metadata.settings['manifest_file'] if output_dir == '@DEFAULTVALUE@': output_dir = metadata.settings['output_dir'] if makelog == '@DEFAULTVALUE@': makelog = metadata.settings['makelog_file'] print "\nCheck manifest log file", manifestlog # Open main log file try: LOGFILE = open(makelog, 'ab') except Exception as errmsg: print errmsg raise CritError(messages.crit_error_log % makelog) try: # Open manifest log file try: MANIFESTFILE = open(manifestlog, 'rU') except Exception as errmsg: print errmsg raise CritError(messages.crit_error_log % manifestlog) manifest_lines = MANIFESTFILE.readlines() MANIFESTFILE.close() # Get file list try: file_list = []; for i in range(len(manifest_lines)): if manifest_lines[i].startswith('File: '): filepath = os.path.abspath(manifest_lines[i][6:].rstrip()) ext = os.path.splitext(filepath)[1] if ext == '': filepath = filepath + '.dta' file_list.append( filepath ) except Exception as errmsg: print errmsg raise SyntaxError(messages.syn_error_manifest % manifestlog) if not os.path.isdir(output_dir): raise CritError(messages.crit_error_no_directory % (output_dir)) # Loop over all levels of sub-directories of output_dir for root, dirs, files in os.walk(output_dir, topdown = True): # Ignore non-hidden sub-directories dirs_to_keep = [] for dirname in dirs: if not dirname.startswith('.'): dirs_to_keep.append(dirname) dirs[:] = dirs_to_keep # Check each file for filename in files: ext = os.path.splitext(filename)[1] fullpath = os.path.abspath( os.path.join(root, filename) ) # non-hidden .dta file: error if (not filename.startswith('.')) and (ext == '.dta'): print 'Checking: ', fullpath if not (fullpath in file_list): raise CritError(messages.crit_error_no_dta_file % (filename, manifestlog)) # non-hidden .csv file: warning if (not filename.startswith('.')) and (ext == '.csv'): print 'Checking: ', fullpath if not (fullpath in file_list): print messages.note_no_csv_file % (filename, manifestlog) print >> LOGFILE, messages.note_no_csv_file % (filename, manifestlog) # non-hidden .txt file: warning if (not filename.startswith('.')) and (ext == '.txt'): print 'Checking: ', fullpath if not (fullpath in file_list): print messages.note_no_txt_file % (filename, manifestlog) print >> LOGFILE, messages.note_no_txt_file % (filename, manifestlog) except: print_error(LOGFILE) LOGFILE.close() def list_directory(top, makelog = '@DEFAULTVALUE@'): """List directories This function lists all non-hidden sub-directories of the directory specified by `top`, a path, and their content from the top down. It writes their names, modified times, and sizes in bytes to the log file specified by the path `makelog`. """ # metadata.settings should not be part of argument defaults so that they can be # overwritten by make_log.set_option if makelog == '@DEFAULTVALUE@': makelog = metadata.settings['makelog_file'] print "\nList all files in directory", top # To print numbers (file sizes) with thousand separator locale.setlocale(locale.LC_ALL, '') makelog = re.sub('\\\\', '/', makelog) try: LOGFILE = open(makelog, 'ab') except Exception as errmsg: print errmsg raise CritError(messages.crit_error_log % makelog) print >> LOGFILE, '\n' print >> LOGFILE, 'List of all files in sub-directories in', top try: if os.path.isdir(top): for root, dirs, files in os.walk(top, topdown = True): # Ignore non-hidden sub-directories dirs_to_keep = [] for dirname in dirs: if not dirname.startswith('.'): dirs_to_keep.append(dirname) dirs[:] = dirs_to_keep # Print out the sub-directory and its time stamp created = os.stat(root).st_mtime asciiTime = time.asctime(time.localtime(created)) print >> LOGFILE, root print >> LOGFILE, 'created/modified', asciiTime # Print out all the files in the sub-directories for name in files: full_name = os.path.join(root, name) created = os.path.getmtime(full_name) size = os.path.getsize(full_name) asciiTime = time.asctime(time.localtime(created)) print >> LOGFILE, '%50s' % name, '--- created/modified', asciiTime, \ '(', locale.format('%d', size, 1), 'bytes )' except: print_error(LOGFILE) print >> LOGFILE, '\n' LOGFILE.close() def clear_dirs(*args): """Create fresh directories This function creates a directory for each path specified in *args if such a directory does not already exist. It deletes all files in each directory that already exists while keeping directory structure (i.e. sub-directories). This function is safe for symlinks. """ for dir in args: if os.path.isdir(dir): remove_dir(dir) os.makedirs(dir) print 'Cleared:', dir def unzip(file_name, output_dir):
def unzip_externals(external_dir='@DEFAULTVALUE@'): if external_dir == '@DEFAULTVALUE@': external_dir = metadata.settings['external_dir'] for dirname, subdirs, files in os.walk(external_dir): for filename in files: absname = os.path.abspath(os.path.join(dirname, filename)) if zipfile.is_zipfile(absname): unzip(absname, dirname) def zip_dir(source_dir, dest): zf = zipfile.ZipFile('%s.zip' % (dest), 'w', zipfile.ZIP_DEFLATED, allowZip64=True) abs_src = os.path.abspath(source_dir) for dirname, subdirs, files in os.walk(source_dir): for filename in files: absname = os.path.abspath(os.path.join(dirname, filename)) arcname = absname[len(abs_src) + 1:] print 'zipping %s as %s' % (os.path.join(dirname, filename), arcname) zf.write(absname, arcname) zf.close()
zip = zipfile.ZipFile(file_name, allowZip64=True) zip.extractall(output_dir) zip.close()
identifier_body
dir_mod.py
#! /usr/bin/env python import os import time import traceback import re import locale import subprocess import zlib import zipfile import private.metadata as metadata import private.messages as messages from glob import glob from private.exceptionclasses import CustomError, CritError, SyntaxError, LogicError from private.preliminaries import print_error #== Directory modification functions ================= def delete_files(pathname): """Delete files specified by a path This function deletes a possibly-empty list of files whose names match `pathname`, which must be a string containing a path specification. `pathname` can be either absolute (like /usr/src/Python-1.5/Makefile) or relative (like ../../Tools/*/*.gif). It can contain shell-style wildcards. """ print "\nDelete files", pathname for f in glob(pathname): os.remove(f) def remove_dir(pathname, options = '@DEFAULTVALUE@'): """Remove a directory This function completely removes the directory specified by `pathname` using the 'rmdir' command on Windows platforms and the 'rm' command on Unix platforms. This is useful for removing symlinks without deleting the source files or directory. """ if os.name == 'posix': os_command = 'rmdirunix' if pathname[-1] == '/': pathname = pathname[0:-1] else: os_command = 'rmdirwin' command = metadata.commands[os_command] if options == '@DEFAULTVALUE@': options = metadata.default_options[os_command] subprocess.check_call(command % (options, pathname), shell=True) def check_manifest(manifestlog = '@DEFAULTVALUE@', output_dir = '@DEFAULTVALUE@', makelog = '@DEFAULTVALUE@'): """ Produce an error if there are any .dta files in "output_dir" and all non-hidden sub-directories that are not in the manifest file "manifestlog", and produce a warning if there are .txt or .csv files not in the manifest along with a list of these files. All log is printed to "makelog" log file. """ # metadata.settings should not be part of argument defaults so that they can be # overwritten by make_log.set_option if manifestlog == '@DEFAULTVALUE@': manifestlog = metadata.settings['manifest_file'] if output_dir == '@DEFAULTVALUE@': output_dir = metadata.settings['output_dir'] if makelog == '@DEFAULTVALUE@': makelog = metadata.settings['makelog_file'] print "\nCheck manifest log file", manifestlog # Open main log file try: LOGFILE = open(makelog, 'ab') except Exception as errmsg: print errmsg raise CritError(messages.crit_error_log % makelog) try: # Open manifest log file try: MANIFESTFILE = open(manifestlog, 'rU') except Exception as errmsg: print errmsg raise CritError(messages.crit_error_log % manifestlog) manifest_lines = MANIFESTFILE.readlines() MANIFESTFILE.close() # Get file list try: file_list = []; for i in range(len(manifest_lines)): if manifest_lines[i].startswith('File: '): filepath = os.path.abspath(manifest_lines[i][6:].rstrip()) ext = os.path.splitext(filepath)[1] if ext == '': filepath = filepath + '.dta' file_list.append( filepath ) except Exception as errmsg: print errmsg raise SyntaxError(messages.syn_error_manifest % manifestlog) if not os.path.isdir(output_dir): raise CritError(messages.crit_error_no_directory % (output_dir)) # Loop over all levels of sub-directories of output_dir for root, dirs, files in os.walk(output_dir, topdown = True): # Ignore non-hidden sub-directories dirs_to_keep = [] for dirname in dirs: if not dirname.startswith('.'): dirs_to_keep.append(dirname) dirs[:] = dirs_to_keep # Check each file for filename in files: ext = os.path.splitext(filename)[1] fullpath = os.path.abspath( os.path.join(root, filename) ) # non-hidden .dta file: error if (not filename.startswith('.')) and (ext == '.dta'): print 'Checking: ', fullpath if not (fullpath in file_list): raise CritError(messages.crit_error_no_dta_file % (filename, manifestlog)) # non-hidden .csv file: warning if (not filename.startswith('.')) and (ext == '.csv'): print 'Checking: ', fullpath if not (fullpath in file_list): print messages.note_no_csv_file % (filename, manifestlog) print >> LOGFILE, messages.note_no_csv_file % (filename, manifestlog) # non-hidden .txt file: warning if (not filename.startswith('.')) and (ext == '.txt'): print 'Checking: ', fullpath if not (fullpath in file_list): print messages.note_no_txt_file % (filename, manifestlog) print >> LOGFILE, messages.note_no_txt_file % (filename, manifestlog) except: print_error(LOGFILE) LOGFILE.close() def list_directory(top, makelog = '@DEFAULTVALUE@'): """List directories This function lists all non-hidden sub-directories of the directory specified by `top`, a path, and their content from the top down. It writes their names, modified times, and sizes in bytes to the log file specified by the path `makelog`. """ # metadata.settings should not be part of argument defaults so that they can be # overwritten by make_log.set_option if makelog == '@DEFAULTVALUE@': makelog = metadata.settings['makelog_file'] print "\nList all files in directory", top # To print numbers (file sizes) with thousand separator locale.setlocale(locale.LC_ALL, '') makelog = re.sub('\\\\', '/', makelog) try: LOGFILE = open(makelog, 'ab') except Exception as errmsg: print errmsg raise CritError(messages.crit_error_log % makelog) print >> LOGFILE, '\n' print >> LOGFILE, 'List of all files in sub-directories in', top try: if os.path.isdir(top): for root, dirs, files in os.walk(top, topdown = True): # Ignore non-hidden sub-directories dirs_to_keep = [] for dirname in dirs:
dirs[:] = dirs_to_keep # Print out the sub-directory and its time stamp created = os.stat(root).st_mtime asciiTime = time.asctime(time.localtime(created)) print >> LOGFILE, root print >> LOGFILE, 'created/modified', asciiTime # Print out all the files in the sub-directories for name in files: full_name = os.path.join(root, name) created = os.path.getmtime(full_name) size = os.path.getsize(full_name) asciiTime = time.asctime(time.localtime(created)) print >> LOGFILE, '%50s' % name, '--- created/modified', asciiTime, \ '(', locale.format('%d', size, 1), 'bytes )' except: print_error(LOGFILE) print >> LOGFILE, '\n' LOGFILE.close() def clear_dirs(*args): """Create fresh directories This function creates a directory for each path specified in *args if such a directory does not already exist. It deletes all files in each directory that already exists while keeping directory structure (i.e. sub-directories). This function is safe for symlinks. """ for dir in args: if os.path.isdir(dir): remove_dir(dir) os.makedirs(dir) print 'Cleared:', dir def unzip(file_name, output_dir): zip = zipfile.ZipFile(file_name, allowZip64=True) zip.extractall(output_dir) zip.close() def unzip_externals(external_dir='@DEFAULTVALUE@'): if external_dir == '@DEFAULTVALUE@': external_dir = metadata.settings['external_dir'] for dirname, subdirs, files in os.walk(external_dir): for filename in files: absname = os.path.abspath(os.path.join(dirname, filename)) if zipfile.is_zipfile(absname): unzip(absname, dirname) def zip_dir(source_dir, dest): zf = zipfile.ZipFile('%s.zip' % (dest), 'w', zipfile.ZIP_DEFLATED, allowZip64=True) abs_src = os.path.abspath(source_dir) for dirname, subdirs, files in os.walk(source_dir): for filename in files: absname = os.path.abspath(os.path.join(dirname, filename)) arcname = absname[len(abs_src) + 1:] print 'zipping %s as %s' % (os.path.join(dirname, filename), arcname) zf.write(absname, arcname) zf.close()
if not dirname.startswith('.'): dirs_to_keep.append(dirname)
conditional_block
multiclass_classification.py
import os import numpy as np from sklearn.datasets import load_iris from sklearn.ensemble import RandomForestClassifier import shap import mlflow # prepare training data X, y = load_iris(return_X_y=True, as_frame=True) # train a model model = RandomForestClassifier() model.fit(X, y) # log an explanation with mlflow.start_run() as run: mlflow.shap.log_explanation(model.predict_proba, X) # list artifacts client = mlflow.tracking.MlflowClient() artifact_path = "model_explanations_shap" artifacts = [x.path for x in client.list_artifacts(run.info.run_id, artifact_path)] print("# artifacts:") print(artifacts) # load back the logged explanation dst_path = client.download_artifacts(run.info.run_id, artifact_path) base_values = np.load(os.path.join(dst_path, "base_values.npy")) shap_values = np.load(os.path.join(dst_path, "shap_values.npy"))
# show a force plot shap.force_plot(base_values[0], shap_values[0, 0, :], X.iloc[0, :], matplotlib=True)
random_line_split
alpr.py
#! /usr/bin/env python # -*- coding: utf-8 -*- import cv2 import numpy as np import pymeanshift as pms from blobs.BlobResult import CBlobResult from blobs.Blob import CBlob # Note: This must be imported in order to destroy blobs and use other methods ############################################################################# # so, here is the main part of the program if __name__ == '__main__': import sys import os blob_overlay = True file_name = "plates/license1.png" if len(sys.argv) != 1: file_name = sys.argv[1] base_name = os.path.basename(file_name) fname_prefix = ".".join(base_name.split(".")[:-1]) print fname_prefix # Image load & conversion to cvmat license_plate = cv2.imread(file_name, cv2.CV_LOAD_IMAGE_COLOR) # Segment segmented, labels, regions = pms.segment(license_plate, 3, 3, 50) print "Segmentation results" print "%s: %s" % ("labels", labels) print "%s: %s" % ("regions", regions) cv2.imwrite('%s_segmented.png' % fname_prefix, segmented) license_plate = cv2.imread('%s_segmented.png' % fname_prefix, cv2.CV_LOAD_IMAGE_COLOR) license_plate_size = (license_plate.shape[1], license_plate.shape[0]) license_plate_cvmat = cv2.cv.fromarray(license_plate) license_plate_ipl = cv2.cv.CreateImage(license_plate_size, cv2.cv.IPL_DEPTH_8U, 3) cv2.cv.SetData( license_plate_ipl, license_plate.tostring(), license_plate.dtype.itemsize * 3 * license_plate.shape[1]) license_plate_white_ipl = cv2.cv.CreateImage(license_plate_size, cv2.cv.IPL_DEPTH_8U, 1) cv2.cv.Set(license_plate_white_ipl, 255) # Grayscale conversion inverted_license_plate_grayscale_ipl = cv2.cv.CreateImage( license_plate_size, cv2.cv.IPL_DEPTH_8U, 1) license_plate_grayscale_ipl = cv2.cv.CreateImage( license_plate_size, cv2.cv.IPL_DEPTH_8U, 1) cv2.cv.CvtColor( license_plate_cvmat, license_plate_grayscale_ipl, cv2.COLOR_RGB2GRAY); license_plate_grayscale_np = np.asarray(license_plate_grayscale_ipl[:,:]) # We can also use cv.saveimage # cv2.cv.SaveImage('license1_grayscale.png', license_plate_grayscale_ipl) cv2.imwrite('%s_grayscale.png' % fname_prefix, license_plate_grayscale_np) # Thresholding or binarization of images (threshold_value, thresh_image) = cv2.threshold( license_plate_grayscale_np, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) print "Thresholding complete. Partition value is %d" % threshold_value cv2.imwrite('%s_threshold.png' % fname_prefix, thresh_image) # Create a mask that will cover the entire image mask = cv2.cv.CreateImage (license_plate_size, 8, 1) cv2.cv.Set(mask, 1) #if not blob_overlay: # # Convert black-and-white version back into three-color representation # cv2.cv.CvtColor(my_grayscale, frame_cvmat, cv2.COLOR_GRAY2RGB); # Blob detection thresh_image_ipl = cv2.cv.CreateImage(license_plate_size, cv2.cv.IPL_DEPTH_8U, 1) cv2.cv.SetData( thresh_image_ipl, thresh_image.tostring(), thresh_image.dtype.itemsize * 1 * thresh_image.shape[1]) cv2.cv.Not(thresh_image_ipl, inverted_license_plate_grayscale_ipl) # Min blob size and Max blob size min_blob_size = 100 # Blob must be 30 px by 30 px max_blob_size = 10000 threshold = 100 # Plate area as % of image area: max_plate_to_image_ratio = 0.3 min_plate_to_image_ratio = 0.01 image_area = license_plate_size[0] * license_plate_size[1] # Mask - Blob extracted where mask is set to 1 # Third parameter is threshold value to apply prior to blob detection # Boolean indicating whether we find moments myblobs = CBlobResult(thresh_image_ipl, mask, threshold, True) myblobs.filter_blobs(min_blob_size, max_blob_size) blob_count = myblobs.GetNumBlobs() print "Found %d blob[s] betweeen size %d and %d using threshold %d" % ( blob_count, min_blob_size, max_blob_size, threshold) for i in range(blob_count): my_enumerated_blob = myblobs.GetBlob(i) # print "%d: Area = %d" % (i, my_enumerated_blob.Area()) my_enumerated_blob.FillBlob( license_plate_grayscale_ipl, #license_plate_ipl, #cv2.cv.Scalar(255, 0, 0), cv2.cv.CV_RGB(255, 0, 0), 0, 0) my_enumerated_blob.FillBlob( license_plate_white_ipl, #license_plate_ipl, #cv2.cv.Scalar(255, 0, 0), cv2.cv.CV_RGB(255, 255, 255), 0, 0) # we can now save the image #annotated_image = np.asarray(license_plate_ipl[:,:]) blob_image = np.asarray(license_plate_grayscale_ipl[:,:]) cv2.imwrite("%s_blobs.png" % fname_prefix, blob_image) blob_white_image = np.asarray(license_plate_white_ipl[:,:]) cv2.imwrite("%s_white_blobs.png" % fname_prefix, blob_white_image) # Looking for a rectangle - Plates are rectangular # Thresholding image, the find contours then approxPolyDP (threshold_value, blob_threshold_image) = cv2.threshold( blob_white_image, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) print "Thresholding complete. Partition value is %d" % threshold_value cv2.imwrite('%s_blob_threshold.png' % fname_prefix, blob_threshold_image) # Blur to reduce noise? #blurred_plate = cv2.GaussianBlur(blob_threshold_image, (5,5), 0) #blob_threshold_image = blurred_plate # Erode then dilate to reduce noise blob_threshold_image_invert = cv2.bitwise_not(blob_threshold_image) cv2.imwrite("%s_pre_dilated_and_eroded.png" % fname_prefix, blob_threshold_image_invert) eroded_white_blobs = cv2.erode(blob_threshold_image_invert, None, iterations=4); cv2.imwrite("%s_eroded_image.png" % fname_prefix, eroded_white_blobs) dilated_white_blobs = cv2.dilate(eroded_white_blobs, None, iterations=4); cv2.imwrite("%s_dilated.png" % fname_prefix, dilated_white_blobs) blob_threshold_image = cv2.bitwise_not(blob_threshold_image_invert) cv2.imwrite("%s_dilated_and_eroded.png" % fname_prefix, blob_threshold_image) blob_threshold_image_invert = cv2.bitwise_not(blob_threshold_image) contours, hierarchy = cv2.findContours( blob_threshold_image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) #print "Contours: ", contours # We now have contours. Approximate the polygon shapes largest_rectangle_idx = 0 largest_rectangle_area = 0 rectangles = [] colours = ( (255,0,0), (0,255,0), (0,0,255), (255,255,0), (0,255,255)) for idx, contour in enumerate(contours): print "Contour: %d" % idx contour_area = cv2.contourArea(contour) if float(contour_area / image_area) < min_plate_to_image_ratio: print "Contour %d under threshold. Countour Area: %f" % (idx, contour_area) continue elif float(contour_area / image_area) > max_plate_to_image_ratio: print "Contour %d over threshold. Countour Area: %f" % (idx, contour_area) continue approx = cv2.approxPolyDP( contour, 0.02 * cv2.arcLength(contour, True), True) print "\n -" print "%d. Countour Area: %f, Arclength: %f, Polygon %d colour:%s" % (idx, contour_area, cv2.arcLength(contour, True), len(approx), colours[idx%len(colours)]) minarea_rectangle = cv2.minAreaRect(contour) minarea_box = cv2.cv.BoxPoints(minarea_rectangle) print "> ", minarea_rectangle print ">> ", minarea_box centre, width_and_height, theta = minarea_rectangle aspect_ratio = float(max(width_and_height) / min(width_and_height)) print " aspect ratio: %f for %s " % (aspect_ratio, width_and_height) minarea_box = np.int0(minarea_box) cv2.drawContours(license_plate, [minarea_box], 0, (255,0,255), 2) cv2.drawContours( license_plate, [contours[idx]], 0, colours[idx%len(colours)]) # Aspect ratio removal if aspect_ratio < 3 or aspect_ratio > 5: print " Aspect ratio bounds fails" continue # Rectangles have polygon shape 4 if len(approx) == 4: # Select the largest rect rectangles.append(contour) if contour_area > largest_rectangle_area : largest_rectangle_area = contour_area largest_rectangle_idx = idx print "Probable plate hit is %d" % largest_rectangle_idx cv2.drawContours( license_plate, [contours[largest_rectangle_idx]], 0, colours[0], idx + 1)
# Create a mask for the detected plate #hull = cv2.convexHull(contours[largest_rectangle_idx]) # This bounding rectangle does not consider rotation license_plate = cv2.imread(file_name, cv2.CV_LOAD_IMAGE_COLOR) bounding_rectangle = cv2.boundingRect(contours[largest_rectangle_idx]) b_rect_x, b_rect_y, b_rect_w, b_rect_h = bounding_rectangle plate_rectangle = (b_rect_x, b_rect_y, b_rect_w, b_rect_h) print "Plate rectangle is: ", plate_rectangle cv2.rectangle(license_plate, (b_rect_x, b_rect_y), (b_rect_x + b_rect_w, b_rect_y + b_rect_h), (0, 255, 0), 2) cv2.imwrite("%s_bounding_box.png" % fname_prefix, license_plate) license_plate = cv2.imread(file_name, cv2.CV_LOAD_IMAGE_COLOR) minarea_rectangle = cv2.minAreaRect(contours[largest_rectangle_idx]) minarea_box = cv2.cv.BoxPoints(minarea_rectangle) minarea_box = np.int0(minarea_box) cv2.drawContours(license_plate, [minarea_box], 0, (0,0,255), 2) cv2.imwrite("%s_bounding_box_minarea.png" % fname_prefix, license_plate)
cv2.imwrite("%s_contours_colored.png" % fname_prefix, license_plate)
random_line_split
alpr.py
#! /usr/bin/env python # -*- coding: utf-8 -*- import cv2 import numpy as np import pymeanshift as pms from blobs.BlobResult import CBlobResult from blobs.Blob import CBlob # Note: This must be imported in order to destroy blobs and use other methods ############################################################################# # so, here is the main part of the program if __name__ == '__main__': import sys import os blob_overlay = True file_name = "plates/license1.png" if len(sys.argv) != 1: file_name = sys.argv[1] base_name = os.path.basename(file_name) fname_prefix = ".".join(base_name.split(".")[:-1]) print fname_prefix # Image load & conversion to cvmat license_plate = cv2.imread(file_name, cv2.CV_LOAD_IMAGE_COLOR) # Segment segmented, labels, regions = pms.segment(license_plate, 3, 3, 50) print "Segmentation results" print "%s: %s" % ("labels", labels) print "%s: %s" % ("regions", regions) cv2.imwrite('%s_segmented.png' % fname_prefix, segmented) license_plate = cv2.imread('%s_segmented.png' % fname_prefix, cv2.CV_LOAD_IMAGE_COLOR) license_plate_size = (license_plate.shape[1], license_plate.shape[0]) license_plate_cvmat = cv2.cv.fromarray(license_plate) license_plate_ipl = cv2.cv.CreateImage(license_plate_size, cv2.cv.IPL_DEPTH_8U, 3) cv2.cv.SetData( license_plate_ipl, license_plate.tostring(), license_plate.dtype.itemsize * 3 * license_plate.shape[1]) license_plate_white_ipl = cv2.cv.CreateImage(license_plate_size, cv2.cv.IPL_DEPTH_8U, 1) cv2.cv.Set(license_plate_white_ipl, 255) # Grayscale conversion inverted_license_plate_grayscale_ipl = cv2.cv.CreateImage( license_plate_size, cv2.cv.IPL_DEPTH_8U, 1) license_plate_grayscale_ipl = cv2.cv.CreateImage( license_plate_size, cv2.cv.IPL_DEPTH_8U, 1) cv2.cv.CvtColor( license_plate_cvmat, license_plate_grayscale_ipl, cv2.COLOR_RGB2GRAY); license_plate_grayscale_np = np.asarray(license_plate_grayscale_ipl[:,:]) # We can also use cv.saveimage # cv2.cv.SaveImage('license1_grayscale.png', license_plate_grayscale_ipl) cv2.imwrite('%s_grayscale.png' % fname_prefix, license_plate_grayscale_np) # Thresholding or binarization of images (threshold_value, thresh_image) = cv2.threshold( license_plate_grayscale_np, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) print "Thresholding complete. Partition value is %d" % threshold_value cv2.imwrite('%s_threshold.png' % fname_prefix, thresh_image) # Create a mask that will cover the entire image mask = cv2.cv.CreateImage (license_plate_size, 8, 1) cv2.cv.Set(mask, 1) #if not blob_overlay: # # Convert black-and-white version back into three-color representation # cv2.cv.CvtColor(my_grayscale, frame_cvmat, cv2.COLOR_GRAY2RGB); # Blob detection thresh_image_ipl = cv2.cv.CreateImage(license_plate_size, cv2.cv.IPL_DEPTH_8U, 1) cv2.cv.SetData( thresh_image_ipl, thresh_image.tostring(), thresh_image.dtype.itemsize * 1 * thresh_image.shape[1]) cv2.cv.Not(thresh_image_ipl, inverted_license_plate_grayscale_ipl) # Min blob size and Max blob size min_blob_size = 100 # Blob must be 30 px by 30 px max_blob_size = 10000 threshold = 100 # Plate area as % of image area: max_plate_to_image_ratio = 0.3 min_plate_to_image_ratio = 0.01 image_area = license_plate_size[0] * license_plate_size[1] # Mask - Blob extracted where mask is set to 1 # Third parameter is threshold value to apply prior to blob detection # Boolean indicating whether we find moments myblobs = CBlobResult(thresh_image_ipl, mask, threshold, True) myblobs.filter_blobs(min_blob_size, max_blob_size) blob_count = myblobs.GetNumBlobs() print "Found %d blob[s] betweeen size %d and %d using threshold %d" % ( blob_count, min_blob_size, max_blob_size, threshold) for i in range(blob_count): my_enumerated_blob = myblobs.GetBlob(i) # print "%d: Area = %d" % (i, my_enumerated_blob.Area()) my_enumerated_blob.FillBlob( license_plate_grayscale_ipl, #license_plate_ipl, #cv2.cv.Scalar(255, 0, 0), cv2.cv.CV_RGB(255, 0, 0), 0, 0) my_enumerated_blob.FillBlob( license_plate_white_ipl, #license_plate_ipl, #cv2.cv.Scalar(255, 0, 0), cv2.cv.CV_RGB(255, 255, 255), 0, 0) # we can now save the image #annotated_image = np.asarray(license_plate_ipl[:,:]) blob_image = np.asarray(license_plate_grayscale_ipl[:,:]) cv2.imwrite("%s_blobs.png" % fname_prefix, blob_image) blob_white_image = np.asarray(license_plate_white_ipl[:,:]) cv2.imwrite("%s_white_blobs.png" % fname_prefix, blob_white_image) # Looking for a rectangle - Plates are rectangular # Thresholding image, the find contours then approxPolyDP (threshold_value, blob_threshold_image) = cv2.threshold( blob_white_image, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU) print "Thresholding complete. Partition value is %d" % threshold_value cv2.imwrite('%s_blob_threshold.png' % fname_prefix, blob_threshold_image) # Blur to reduce noise? #blurred_plate = cv2.GaussianBlur(blob_threshold_image, (5,5), 0) #blob_threshold_image = blurred_plate # Erode then dilate to reduce noise blob_threshold_image_invert = cv2.bitwise_not(blob_threshold_image) cv2.imwrite("%s_pre_dilated_and_eroded.png" % fname_prefix, blob_threshold_image_invert) eroded_white_blobs = cv2.erode(blob_threshold_image_invert, None, iterations=4); cv2.imwrite("%s_eroded_image.png" % fname_prefix, eroded_white_blobs) dilated_white_blobs = cv2.dilate(eroded_white_blobs, None, iterations=4); cv2.imwrite("%s_dilated.png" % fname_prefix, dilated_white_blobs) blob_threshold_image = cv2.bitwise_not(blob_threshold_image_invert) cv2.imwrite("%s_dilated_and_eroded.png" % fname_prefix, blob_threshold_image) blob_threshold_image_invert = cv2.bitwise_not(blob_threshold_image) contours, hierarchy = cv2.findContours( blob_threshold_image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) #print "Contours: ", contours # We now have contours. Approximate the polygon shapes largest_rectangle_idx = 0 largest_rectangle_area = 0 rectangles = [] colours = ( (255,0,0), (0,255,0), (0,0,255), (255,255,0), (0,255,255)) for idx, contour in enumerate(contours): print "Contour: %d" % idx contour_area = cv2.contourArea(contour) if float(contour_area / image_area) < min_plate_to_image_ratio:
elif float(contour_area / image_area) > max_plate_to_image_ratio: print "Contour %d over threshold. Countour Area: %f" % (idx, contour_area) continue approx = cv2.approxPolyDP( contour, 0.02 * cv2.arcLength(contour, True), True) print "\n -" print "%d. Countour Area: %f, Arclength: %f, Polygon %d colour:%s" % (idx, contour_area, cv2.arcLength(contour, True), len(approx), colours[idx%len(colours)]) minarea_rectangle = cv2.minAreaRect(contour) minarea_box = cv2.cv.BoxPoints(minarea_rectangle) print "> ", minarea_rectangle print ">> ", minarea_box centre, width_and_height, theta = minarea_rectangle aspect_ratio = float(max(width_and_height) / min(width_and_height)) print " aspect ratio: %f for %s " % (aspect_ratio, width_and_height) minarea_box = np.int0(minarea_box) cv2.drawContours(license_plate, [minarea_box], 0, (255,0,255), 2) cv2.drawContours( license_plate, [contours[idx]], 0, colours[idx%len(colours)]) # Aspect ratio removal if aspect_ratio < 3 or aspect_ratio > 5: print " Aspect ratio bounds fails" continue # Rectangles have polygon shape 4 if len(approx) == 4: # Select the largest rect rectangles.append(contour) if contour_area > largest_rectangle_area : largest_rectangle_area = contour_area largest_rectangle_idx = idx print "Probable plate hit is %d" % largest_rectangle_idx cv2.drawContours( license_plate, [contours[largest_rectangle_idx]], 0, colours[0], idx + 1) cv2.imwrite("%s_contours_colored.png" % fname_prefix, license_plate) # Create a mask for the detected plate #hull = cv2.convexHull(contours[largest_rectangle_idx]) # This bounding rectangle does not consider rotation license_plate = cv2.imread(file_name, cv2.CV_LOAD_IMAGE_COLOR) bounding_rectangle = cv2.boundingRect(contours[largest_rectangle_idx]) b_rect_x, b_rect_y, b_rect_w, b_rect_h = bounding_rectangle plate_rectangle = (b_rect_x, b_rect_y, b_rect_w, b_rect_h) print "Plate rectangle is: ", plate_rectangle cv2.rectangle(license_plate, (b_rect_x, b_rect_y), (b_rect_x + b_rect_w, b_rect_y + b_rect_h), (0, 255, 0), 2) cv2.imwrite("%s_bounding_box.png" % fname_prefix, license_plate) license_plate = cv2.imread(file_name, cv2.CV_LOAD_IMAGE_COLOR) minarea_rectangle = cv2.minAreaRect(contours[largest_rectangle_idx]) minarea_box = cv2.cv.BoxPoints(minarea_rectangle) minarea_box = np.int0(minarea_box) cv2.drawContours(license_plate, [minarea_box], 0, (0,0,255), 2) cv2.imwrite("%s_bounding_box_minarea.png" % fname_prefix, license_plate)
print "Contour %d under threshold. Countour Area: %f" % (idx, contour_area) continue
conditional_block
hash.js
/** * Module dependencies. */ var utils = require('../utils/utils'); /** * HLEN <key> */ exports.hlen = function(key){ var obj = this.lookup(key); if (!!obj && 'hash' == obj.type) { return Object.keys(obj.val).length; } else { return -1; } }; /** * HVALS <key> */ exports.hvals = function(key){ var obj = this.lookup(key); if (!!obj && 'hash' == obj.type) { return (obj.val); } else { return null; } }; /** * HKEYS <key> */ exports.hkeys = function(key){ var obj = this.lookup(key); if (!!obj && 'hash' == obj.type) { return Object.keys(obj.val); } else { return null; } }; /** * HSET <key> <field> <val> */ (exports.hset = function(key, field, val){ var obj = this.lookup(key); if (obj && 'hash' != obj.type) { return false;} obj = obj || (this.db.data[key] = { type: 'hash', val: {} }); obj.val[field] = val;
return true; }).mutates = true; /** * HMSET <key> (<field> <val>)+ */ (exports.hmset = function(data){ var len = data.length , key = data[0] , obj = this.lookup(key) , field , val; if (obj && 'hash' != obj.type) { return false;} obj = obj || (this.db.data[key] = { type: 'hash', val: {} }); var i = 1; for (i = 1; i < len; ++i) { field = data[i++]; val = data[i]; obj.val[field] = val; } return true; }).mutates = true; exports.hmset.multiple = 2; exports.hmset.skip = 1; /** * HGET <key> <field> */ exports.hget = function(key, field){ var obj = this.lookup(key) , val; if (!obj) { return null; } else if ('hash' == obj.type) { return obj.val[field] || null; } else { return null; } }; /** * HGETALL <key> */ exports.hgetall = function(key){ var obj = this.lookup(key); var list = []; var field; if (!!obj && 'hash' == obj.type) { for (field in obj.val) { list.push(field, obj.val[field]); } return list; } else { return null; } }; /** * HEXISTS <key> <field> */ exports.hexists = function(key, field){ var obj = this.lookup(key); if (!!obj && 'hash' == obj.type) { var result = (hfield in obj.val); return result; } else { return false; } };
random_line_split
hash.js
/** * Module dependencies. */ var utils = require('../utils/utils'); /** * HLEN <key> */ exports.hlen = function(key){ var obj = this.lookup(key); if (!!obj && 'hash' == obj.type) { return Object.keys(obj.val).length; } else { return -1; } }; /** * HVALS <key> */ exports.hvals = function(key){ var obj = this.lookup(key); if (!!obj && 'hash' == obj.type) { return (obj.val); } else { return null; } }; /** * HKEYS <key> */ exports.hkeys = function(key){ var obj = this.lookup(key); if (!!obj && 'hash' == obj.type) { return Object.keys(obj.val); } else { return null; } }; /** * HSET <key> <field> <val> */ (exports.hset = function(key, field, val){ var obj = this.lookup(key); if (obj && 'hash' != obj.type) { return false;} obj = obj || (this.db.data[key] = { type: 'hash', val: {} }); obj.val[field] = val; return true; }).mutates = true; /** * HMSET <key> (<field> <val>)+ */ (exports.hmset = function(data){ var len = data.length , key = data[0] , obj = this.lookup(key) , field , val; if (obj && 'hash' != obj.type) { return false;} obj = obj || (this.db.data[key] = { type: 'hash', val: {} }); var i = 1; for (i = 1; i < len; ++i) { field = data[i++]; val = data[i]; obj.val[field] = val; } return true; }).mutates = true; exports.hmset.multiple = 2; exports.hmset.skip = 1; /** * HGET <key> <field> */ exports.hget = function(key, field){ var obj = this.lookup(key) , val; if (!obj) { return null; } else if ('hash' == obj.type)
else { return null; } }; /** * HGETALL <key> */ exports.hgetall = function(key){ var obj = this.lookup(key); var list = []; var field; if (!!obj && 'hash' == obj.type) { for (field in obj.val) { list.push(field, obj.val[field]); } return list; } else { return null; } }; /** * HEXISTS <key> <field> */ exports.hexists = function(key, field){ var obj = this.lookup(key); if (!!obj && 'hash' == obj.type) { var result = (hfield in obj.val); return result; } else { return false; } };
{ return obj.val[field] || null; }
conditional_block
main.js
$(document).ready(function() { 'use strict'; if (applicationStatusCode == 1) $('.ui.basic.modal').modal('show'); $('.ui.dropdown').dropdown({ on: 'hover' }); $('.masthead .information').transition('scale in', 1000); var animateIcons = function() { $('.ui.feature .icon .icon').transition({ animation: 'horizontal flip', duration: 600, }) .transition({ animation: 'horizontal flip', duration: 600, }); }; setInterval(animateIcons, 3200); $('.menu .item').tab(); $('.ui.checkbox').checkbox(); $('.ui.form input[name="birth"]').datetimepicker({ timepicker: false, format: 'Y/m/d', lang: 'zh-TW' }); var printAmount = function() { var items = '', total; $('.ui.form input:checked').each(function() { items += $(this).val(); }); if (items.indexOf('學術課程')>=0 && items.indexOf('活動課程')==-1 && items.indexOf('加購紀念 T 恤')==-1) total = 500; else if (items.indexOf('學術課程')==-1 && items.indexOf('活動課程')>=0 && items.indexOf('加購紀念 T 恤')==-1) total = 2100; else if (items.indexOf('學術課程')==-1 && items.indexOf('活動課程')==-1 && items.indexOf('加購紀念 T 恤')>=0) total = 250; else if (items.indexOf('學術課程')>=0 && items.indexOf('活動課程')>=0 && items.indexOf('加購紀念 T 恤')==-1) total = 2500; else if (items.indexOf('學術課程')>=0 && items.indexOf('活動課程')==-1 && items.indexOf('加購紀念 T 恤')>=0) total = 650; else if (items.indexOf('學術課程')==-1 && items.indexOf('活動課程')>=0 && items.indexOf('加購紀念 T 恤')>=0) total = 2250; else if (items.indexOf('學術課程')>=0 && items.indexOf('活動課程')>=0 && items.indexOf('加購紀念 T 恤')>=0) total = 2650; else total = 0; $('.ui.form .green.label').text('費用總計:NT$ ' + total); }; $('.ui.form .ui.checkbox:not(.radio)').on('click', printAmount); var validationRules = { name: { identifier: 'name', rules: [ { type: 'empty', prompt: '請輸入姓名' } ] }, birth: { identifier: 'birth', rules: [ { type: 'empty', prompt: '請輸入生日' } ] }, phone: { identifier: 'phone', rules: [ { type: 'empty', prompt: '請輸入行動電話' }, { type: 'maxLength[10]', prompt: '行動電話的長度超過 10 個字元' }, { type: 'length[10]', prompt: '行動電話的長度小於 10 個字元' }, { type: 'integer', prompt: '行動電話無效' } ] }, idnum: { identifier: 'idnum', rules: [ { type: 'empty', prompt: '請輸入身份證字號' }, { type: 'maxLength[10]', prompt: '身份證字號的長度超過 10 個字元' }, { type: 'length[10]', prompt: '身份證字號的長度小於 10 個字元' } ] }, email: { identifier: 'email', rules: [ { type: 'empty', prompt: '請輸入電子郵件信箱' }, { type: 'email', prompt: '電子郵件信箱無效' } ] } }; $('.ui.form').form(validationRules, { on: 'blur' }); }); function goToApply() { 'use strict'; var destination = document.getElementsByTagName('section')[2]; $('html, body').animate({ scrollTop: $(destination).offset().top }, 800);
}
random_line_split
main.js
$(document).ready(function() { 'use strict'; if (applicationStatusCode == 1) $('.ui.basic.modal').modal('show'); $('.ui.dropdown').dropdown({ on: 'hover' }); $('.masthead .information').transition('scale in', 1000); var animateIcons = function() { $('.ui.feature .icon .icon').transition({ animation: 'horizontal flip', duration: 600, }) .transition({ animation: 'horizontal flip', duration: 600, }); }; setInterval(animateIcons, 3200); $('.menu .item').tab(); $('.ui.checkbox').checkbox(); $('.ui.form input[name="birth"]').datetimepicker({ timepicker: false, format: 'Y/m/d', lang: 'zh-TW' }); var printAmount = function() { var items = '', total; $('.ui.form input:checked').each(function() { items += $(this).val(); }); if (items.indexOf('學術課程')>=0 && items.indexOf('活動課程')==-1 && items.indexOf('加購紀念 T 恤')==-1) total = 500; else if (items.indexOf('學術課程')==-1 && items.indexOf('活動課程')>=0 && items.indexOf('加購紀念 T 恤')==-1) total = 2100; else if (items.indexOf('學術課程')==-1 && items.indexOf('活動課程')==-1 && items.indexOf('加購紀念 T 恤')>=0) total = 250; else if (items.indexOf('學術課程')>=0 && items.indexOf('活動課程')>=0 && items.indexOf('加購紀念 T 恤')==-1) total = 2500; else if (items.indexOf('學術課程')>=0 && items.indexOf('活動課程')==-1 && items.indexOf('加購紀念 T 恤')>=0) total = 650; else if (items.indexOf('學術課程')==-1 && items.indexOf('活動課程')>=0 && items.indexOf('加購紀念 T 恤')>=0) total = 2250; else if (items.indexOf('學術課程')>=0 && items.indexOf('活動課程')>=0 && items.indexOf('加購紀念 T 恤')>=0) total = 2650; else total = 0; $('.ui.form .green.label').text('費用總計:NT$ ' + total); }; $('.ui.form .ui.checkbox:not(.radio)').on('click', printAmount); var validationRules = { name: { identifier: 'name', rules: [ { type: 'empty', prompt: '請輸入姓名' } ] }, birth: { identifier: 'birth', rules: [ { type: 'empty', prompt: '請輸入生日' } ] }, phone: { identifier: 'phone', rules: [ { type: 'empty', prompt: '請輸入行動電話' }, { type: 'maxLength[10]', prompt: '行動電話的長度超過 10 個字元' }, { type: 'length[10]', prompt: '行動電話的長度小於 10 個字元' }, { type: 'integer', prompt: '行動電話無效' } ] }, idnum: { identifier: 'idnum', rules: [ { type: 'empty', prompt: '請輸入身份證字號' }, { type: 'maxLength[10]', prompt: '身份證字號的長度超過 10 個字元' }, { type: 'length[10]', prompt: '身份證字號的長度小於 10 個字元' } ] }, email: { identifier: 'email', rules: [ { type: 'empty', prompt: '請輸入電子郵件信箱' }, { type: 'email', prompt: '電子郵件信箱無效' } ] } }; $('.ui.form').form(validationRules, { on: 'blur' }); }); function goToApply() { 'use strict'; var destination = document.getElementsByTagName('section')[2]; $('html, body').animate({ scrollTop: $(destination).offset().top }, 800); }
identifier_body
main.js
$(document).ready(function() { 'use strict'; if (applicationStatusCode == 1) $('.ui.basic.modal').modal('show'); $('.ui.dropdown').dropdown({ on: 'hover' }); $('.masthead .information').transition('scale in', 1000); var animateIcons = function() { $('.ui.feature .icon .icon').transition({ animation: 'horizontal flip', duration: 600, }) .transition({ animation: 'horizontal flip', duration: 600, }); }; setInterval(animateIcons, 3200); $('.menu .item').tab(); $('.ui.checkbox').checkbox(); $('.ui.form input[name="birth"]').datetimepicker({ timepicker: false, format: 'Y/m/d', lang: 'zh-TW' }); var printAmount = function() { var items = '', total; $('.ui.form input:checked').each(function() { items += $(this).val(); }); if (items.indexOf('學術課程')>=0 && items.indexOf('活動課程')==-1 && items.indexOf('加購紀念 T 恤')==-1) total = 500; else if (items.indexOf('學術課程')==-1 && items.indexOf('活動課程')>=0 && items.indexOf('加購紀念 T 恤')==-1) total = 2100; else if (items.indexOf('學術課程')==-1 && items.indexOf('活動課程')==-1 && items.indexOf('加購紀念 T 恤')>=0) total = 250; else if (items.indexOf('學術課程')>=0 && items.indexOf('活動課程')>=0 && items.indexOf('加購紀念 T 恤')==-1) total = 2500; else if (items.indexOf('學術課程')>=0 && items.indexOf('活動課程')==-1 && items.indexOf('加購紀念 T 恤')>=0) total = 650; else if (items.indexOf('學術課程')==-1 && items.indexOf('活動課程')>=0 && items.indexOf('加購紀念 T 恤')>=0) total = 2250; else if (items.indexOf('學術課程')>=0 && items.indexOf('活動課程')>=0 && items.indexOf('加購紀念 T 恤')>=0) total = 2650; else total = 0; $('.ui.form .green.label').text('費用總計:NT$ ' + total); }; $('.ui.form .ui.checkbox:not(.radio)').on('click', printAmount); var validationRules = { name: { identifier: 'name', rules: [ { type: 'empty', prompt: '請輸入姓名' } ] }, birth: { identifier: 'birth', rules: [ { type: 'empty', prompt: '請輸入生日' } ] }, phone: { identifier: 'phone', rules: [ { type: 'empty', prompt: '請輸入行動電話' }, { type: 'maxLength[10]', prompt: '行動電話的長度超過 10 個字元' }, { type: 'length[10]', prompt: '行動電話的長度小於 10 個字元' }, { type: 'integer', prompt: '行動電話無效' } ] }, idnum: { identifier: 'idnum', rules: [ { type: 'empty', prompt: '請輸入身份證字號' }, { type: 'maxLength[10]', prompt: '身份證字號的長度超過 10 個字元' }, { type: 'length[10]', prompt: '身份證字號的長度小於 10 個字元' } ] }, email: { identifier: 'email', rules: [ { type: 'empty', prompt: '請輸入電子郵件信箱' }, { type: 'email', prompt: '電子郵件信箱無效' } ] } }; $('.ui.form').form(validationRules, { on: 'blur' }); }); function goToApply() { 'use strict'; var destination = document.getElementsByTagName('section')[2]; $('html, body').animate({ scrollTop: $(destination).offset().top }, 800); }
identifier_name
userpopups.js
Drupal.userpopups = {}; Drupal.behaviors.userpopups = {
jQuery('html').once('popups-initialized').each(function(){ Drupal.userpopups.init(); }); } }; Drupal.userpopups.init = function init(){ var login_box = jQuery('#block-userlogin'); var pass_box = jQuery('.user-pass'); login_box.append('<div class="close">Închide</div>'); pass_box.append('<div class="close">Închide</div>'); jQuery('.connect').click(function(e){ login_box.addClass('active'); e.preventDefault(); }); jQuery('.item-list li:nth-child(2)').find('a').click(function(e){ login_box.removeClass('active'); pass_box.addClass('active'); e.preventDefault(); }); jQuery('.close').click(function(e){ jQuery(this).parent().removeClass('active'); e.preventDefault(); }); };
attach: function(context, settings) {
random_line_split
exporter.py
# -*- coding: utf-8 -*- # Copyright 2015-2019 grafana-dashboard-builder contributors # # 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 # # http://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. from __future__ import unicode_literals import errno import json import logging import os __author__ = 'Jakub Plichta <jakub.plichta@gmail.com>' logger = logging.getLogger(__name__) class DashboardExporter(object): def process_dashboard(self, project_name, dashboard_name, dashboard_data): pass class ProjectProcessor(object): def __init__(self, dashboard_processors): """ :type dashboard_processors: list[grafana_dashboards.builder.DashboardExporter] """ super(ProjectProcessor, self).__init__() self._dashboard_processors = dashboard_processors def process_projects(self, projects, parent_context=None): """ :type projects: list[grafana_dashboards.components.projects.Project] :type parent_context: dict """ for project in projects: logger.info("Processing project '%s'", project.name) for context in project.get_contexts(parent_context): for dashboard in project.get_dashboards(): json_obj = dashboard.gen_json(context) dashboard_name = context.expand_placeholders(dashboard.name) for processor in self._dashboard_processors: processor.process_dashboard(project.name, dashboard_name, json_obj) class FileExporter(DashboardExporter):
def __init__(self, output_folder): super(FileExporter, self).__init__() self._output_folder = output_folder if not os.path.exists(self._output_folder): os.makedirs(self._output_folder) if not os.path.isdir(self._output_folder): raise Exception("'{0}' must be a directory".format(self._output_folder)) def process_dashboard(self, project_name, dashboard_name, dashboard_data): super(FileExporter, self).process_dashboard(project_name, dashboard_name, dashboard_data) dirname = os.path.join(self._output_folder, project_name) try: os.makedirs(dirname) except OSError as e: if e.errno != errno.EEXIST: raise dashboard_path = os.path.join(dirname, dashboard_name + '.json') logger.info("Saving dashboard '%s' to '%s'", dashboard_name, os.path.abspath(dashboard_path)) with open(dashboard_path, 'w') as f: json.dump(dashboard_data, f, sort_keys=True, indent=2, separators=(',', ': '))
identifier_body
exporter.py
# -*- coding: utf-8 -*- # Copyright 2015-2019 grafana-dashboard-builder contributors # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License.
# 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. from __future__ import unicode_literals import errno import json import logging import os __author__ = 'Jakub Plichta <jakub.plichta@gmail.com>' logger = logging.getLogger(__name__) class DashboardExporter(object): def process_dashboard(self, project_name, dashboard_name, dashboard_data): pass class ProjectProcessor(object): def __init__(self, dashboard_processors): """ :type dashboard_processors: list[grafana_dashboards.builder.DashboardExporter] """ super(ProjectProcessor, self).__init__() self._dashboard_processors = dashboard_processors def process_projects(self, projects, parent_context=None): """ :type projects: list[grafana_dashboards.components.projects.Project] :type parent_context: dict """ for project in projects: logger.info("Processing project '%s'", project.name) for context in project.get_contexts(parent_context): for dashboard in project.get_dashboards(): json_obj = dashboard.gen_json(context) dashboard_name = context.expand_placeholders(dashboard.name) for processor in self._dashboard_processors: processor.process_dashboard(project.name, dashboard_name, json_obj) class FileExporter(DashboardExporter): def __init__(self, output_folder): super(FileExporter, self).__init__() self._output_folder = output_folder if not os.path.exists(self._output_folder): os.makedirs(self._output_folder) if not os.path.isdir(self._output_folder): raise Exception("'{0}' must be a directory".format(self._output_folder)) def process_dashboard(self, project_name, dashboard_name, dashboard_data): super(FileExporter, self).process_dashboard(project_name, dashboard_name, dashboard_data) dirname = os.path.join(self._output_folder, project_name) try: os.makedirs(dirname) except OSError as e: if e.errno != errno.EEXIST: raise dashboard_path = os.path.join(dirname, dashboard_name + '.json') logger.info("Saving dashboard '%s' to '%s'", dashboard_name, os.path.abspath(dashboard_path)) with open(dashboard_path, 'w') as f: json.dump(dashboard_data, f, sort_keys=True, indent=2, separators=(',', ': '))
# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software
random_line_split
exporter.py
# -*- coding: utf-8 -*- # Copyright 2015-2019 grafana-dashboard-builder contributors # # 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 # # http://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. from __future__ import unicode_literals import errno import json import logging import os __author__ = 'Jakub Plichta <jakub.plichta@gmail.com>' logger = logging.getLogger(__name__) class DashboardExporter(object): def process_dashboard(self, project_name, dashboard_name, dashboard_data): pass class ProjectProcessor(object): def __init__(self, dashboard_processors): """ :type dashboard_processors: list[grafana_dashboards.builder.DashboardExporter] """ super(ProjectProcessor, self).__init__() self._dashboard_processors = dashboard_processors def process_projects(self, projects, parent_context=None): """ :type projects: list[grafana_dashboards.components.projects.Project] :type parent_context: dict """ for project in projects:
class FileExporter(DashboardExporter): def __init__(self, output_folder): super(FileExporter, self).__init__() self._output_folder = output_folder if not os.path.exists(self._output_folder): os.makedirs(self._output_folder) if not os.path.isdir(self._output_folder): raise Exception("'{0}' must be a directory".format(self._output_folder)) def process_dashboard(self, project_name, dashboard_name, dashboard_data): super(FileExporter, self).process_dashboard(project_name, dashboard_name, dashboard_data) dirname = os.path.join(self._output_folder, project_name) try: os.makedirs(dirname) except OSError as e: if e.errno != errno.EEXIST: raise dashboard_path = os.path.join(dirname, dashboard_name + '.json') logger.info("Saving dashboard '%s' to '%s'", dashboard_name, os.path.abspath(dashboard_path)) with open(dashboard_path, 'w') as f: json.dump(dashboard_data, f, sort_keys=True, indent=2, separators=(',', ': '))
logger.info("Processing project '%s'", project.name) for context in project.get_contexts(parent_context): for dashboard in project.get_dashboards(): json_obj = dashboard.gen_json(context) dashboard_name = context.expand_placeholders(dashboard.name) for processor in self._dashboard_processors: processor.process_dashboard(project.name, dashboard_name, json_obj)
conditional_block
exporter.py
# -*- coding: utf-8 -*- # Copyright 2015-2019 grafana-dashboard-builder contributors # # 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 # # http://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. from __future__ import unicode_literals import errno import json import logging import os __author__ = 'Jakub Plichta <jakub.plichta@gmail.com>' logger = logging.getLogger(__name__) class DashboardExporter(object): def process_dashboard(self, project_name, dashboard_name, dashboard_data): pass class
(object): def __init__(self, dashboard_processors): """ :type dashboard_processors: list[grafana_dashboards.builder.DashboardExporter] """ super(ProjectProcessor, self).__init__() self._dashboard_processors = dashboard_processors def process_projects(self, projects, parent_context=None): """ :type projects: list[grafana_dashboards.components.projects.Project] :type parent_context: dict """ for project in projects: logger.info("Processing project '%s'", project.name) for context in project.get_contexts(parent_context): for dashboard in project.get_dashboards(): json_obj = dashboard.gen_json(context) dashboard_name = context.expand_placeholders(dashboard.name) for processor in self._dashboard_processors: processor.process_dashboard(project.name, dashboard_name, json_obj) class FileExporter(DashboardExporter): def __init__(self, output_folder): super(FileExporter, self).__init__() self._output_folder = output_folder if not os.path.exists(self._output_folder): os.makedirs(self._output_folder) if not os.path.isdir(self._output_folder): raise Exception("'{0}' must be a directory".format(self._output_folder)) def process_dashboard(self, project_name, dashboard_name, dashboard_data): super(FileExporter, self).process_dashboard(project_name, dashboard_name, dashboard_data) dirname = os.path.join(self._output_folder, project_name) try: os.makedirs(dirname) except OSError as e: if e.errno != errno.EEXIST: raise dashboard_path = os.path.join(dirname, dashboard_name + '.json') logger.info("Saving dashboard '%s' to '%s'", dashboard_name, os.path.abspath(dashboard_path)) with open(dashboard_path, 'w') as f: json.dump(dashboard_data, f, sort_keys=True, indent=2, separators=(',', ': '))
ProjectProcessor
identifier_name
store.js
/** * 对Storage的封装 * Author : smohan * Website : https://smohan.net * Date: 2017/10/12 * 参数1:布尔值, true : sessionStorage, 无论get,delete,set都得申明 * 参数1:string key 名 * 参数2:null,用作删除,其他用作设置 * 参数3:string,用于设置键名前缀 * 如果是sessionStorage,即参数1是个布尔值,且为true, * 无论设置/删除/获取都应该指明,而localStorage无需指明 */ const MEMORY_CACHE = Object.create(null)
name, value, prefix let args = arguments if (typeof args[0] === 'boolean') { isSession = args[0] args = [].slice.call(args, 1) } name = args[0] value = args[1] prefix = args[2] === undefined ? '_mo_data_' : args[2] const Storage = isSession ? window.sessionStorage : window.localStorage if (!name || typeof name !== 'string') { throw new Error('name must be a string') } let cacheKey = (prefix && typeof prefix === 'string') ? (prefix + name) : name if (value === null) { //remove delete MEMORY_CACHE[cacheKey] return Storage.removeItem(cacheKey) } else if (!value && value !== 0) { //get if (MEMORY_CACHE[cacheKey]) { return MEMORY_CACHE[cacheKey] } let _value = undefined try { _value = JSON.parse(Storage.getItem(cacheKey)) } catch (e) {} return _value } else { //set MEMORY_CACHE[cacheKey] = value return Storage.setItem(cacheKey, JSON.stringify(value)) } }
export default function () { let isSession = false,
random_line_split
store.js
/** * 对Storage的封装 * Author : smohan * Website : https://smohan.net * Date: 2017/10/12 * 参数1:布尔值, true : sessionStorage, 无论get,delete,set都得申明 * 参数1:string key 名 * 参数2:null,用作删除,其他用作设置 * 参数3:string,用于设置键名前缀 * 如果是sessionStorage,即参数1是个布尔值,且为true, * 无论设置/删除/获取都应该指明,而localStorage无需指明 */ const MEMORY_CACHE = Object.create(null) export default function () { let isSession = false, name, value, prefix let args = arguments if (typeof args[0] === 'boolean') { isSession = args[0] args = [].slice.call(args, 1) } name = args[0] value = args[1] prefix = args[2] === undefined ? '_mo_data_' : args[2] const Storage = isSession ? window.sessionStorage : window.localStorage if (!name || typeof name !== 'string') { throw new Error('name must be a string') } let cacheKey = (prefix && typeof prefix === 'string') ? (prefix + name) : name if (value === null) { //remove delete MEMORY_CACHE[cacheKey] return Storage.removeItem(cacheKey) } else if (!value && value !== 0) { //get if (MEMORY_CACHE[cacheKey]) {
ue = JSON.parse(Storage.getItem(cacheKey)) } catch (e) {} return _value } else { //set MEMORY_CACHE[cacheKey] = value return Storage.setItem(cacheKey, JSON.stringify(value)) } }
return MEMORY_CACHE[cacheKey] } let _value = undefined try { _val
conditional_block
mod.rs
#![cfg(target_os = "android")] use crate::api::egl::{ Context as EglContext, NativeDisplay, SurfaceType as EglSurfaceType, }; use crate::CreationError::{self, OsError}; use crate::{ Api, ContextError, GlAttributes, PixelFormat, PixelFormatRequirements, Rect, }; use crate::platform::android::EventLoopExtAndroid; use glutin_egl_sys as ffi; use parking_lot::Mutex; use winit; use winit::dpi; use winit::event_loop::EventLoopWindowTarget; use winit::window::WindowBuilder; use std::sync::Arc; #[derive(Debug)] struct AndroidContext { egl_context: EglContext, stopped: Option<Mutex<bool>>, } #[derive(Debug)] pub struct Context(Arc<AndroidContext>); #[derive(Debug)] struct AndroidSyncEventHandler(Arc<AndroidContext>); impl android_glue::SyncEventHandler for AndroidSyncEventHandler { fn handle(&mut self, event: &android_glue::Event) { match *event { // 'on_surface_destroyed' Android event can arrive with some delay // because multithreading communication. Because of // that, swap_buffers can be called before processing // 'on_surface_destroyed' event, with the native window // surface already destroyed. EGL generates a BAD_SURFACE error in // this situation. Set stop to true to prevent // swap_buffer call race conditions. android_glue::Event::TermWindow => { let mut stopped = self.0.stopped.as_ref().unwrap().lock(); *stopped = true; } _ => { return; } }; } } impl Context { #[inline] pub fn new_windowed<T>( wb: WindowBuilder, el: &EventLoopWindowTarget<T>, pf_reqs: &PixelFormatRequirements, gl_attr: &GlAttributes<&Self>, ) -> Result<(winit::window::Window, Self), CreationError> { let win = wb.build(el)?; let gl_attr = gl_attr.clone().map_sharing(|c| &c.0.egl_context); let nwin = unsafe { android_glue::get_native_window() }; if nwin.is_null() { return Err(OsError("Android's native window is null".to_string())); } let native_display = NativeDisplay::Android; let egl_context = EglContext::new( pf_reqs, &gl_attr, native_display, EglSurfaceType::Window, |c, _| Ok(c[0]), ) .and_then(|p| p.finish(nwin as *const _))?; let ctx = Arc::new(AndroidContext { egl_context, stopped: Some(Mutex::new(false)), }); let handler = Box::new(AndroidSyncEventHandler(ctx.clone())); android_glue::add_sync_event_handler(handler); let context = Context(ctx.clone()); el.set_suspend_callback(Some(Box::new(move |suspended| { let mut stopped = ctx.stopped.as_ref().unwrap().lock(); *stopped = suspended; if suspended { // Android has stopped the activity or sent it to background. // Release the EGL surface and stop the animation loop. unsafe { ctx.egl_context.on_surface_destroyed(); } } else { // Android has started the activity or sent it to foreground. // Restore the EGL surface and animation loop. unsafe { let nwin = android_glue::get_native_window(); ctx.egl_context.on_surface_created(nwin as *const _); } } }))); Ok((win, context)) } #[inline] pub fn new_headless<T>( _el: &EventLoopWindowTarget<T>, pf_reqs: &PixelFormatRequirements, gl_attr: &GlAttributes<&Context>, size: dpi::PhysicalSize<u32>, ) -> Result<Self, CreationError> { let gl_attr = gl_attr.clone().map_sharing(|c| &c.0.egl_context); let context = EglContext::new( pf_reqs, &gl_attr, NativeDisplay::Android, EglSurfaceType::PBuffer, |c, _| Ok(c[0]), )?; let egl_context = context.finish_pbuffer(size)?; let ctx = Arc::new(AndroidContext { egl_context, stopped: None, }); Ok(Context(ctx)) } #[inline] pub unsafe fn make_current(&self) -> Result<(), ContextError> { if let Some(ref stopped) = self.0.stopped { let stopped = stopped.lock(); if *stopped { return Err(ContextError::ContextLost); } } self.0.egl_context.make_current() } #[inline] pub unsafe fn make_not_current(&self) -> Result<(), ContextError> { if let Some(ref stopped) = self.0.stopped { let stopped = stopped.lock(); if *stopped { return Err(ContextError::ContextLost); } } self.0.egl_context.make_not_current() } #[inline] pub fn resize(&self, _: u32, _: u32) {} #[inline] pub fn is_current(&self) -> bool { self.0.egl_context.is_current() } #[inline] pub fn get_proc_address(&self, addr: &str) -> *const core::ffi::c_void { self.0.egl_context.get_proc_address(addr) } #[inline] pub fn swap_buffers(&self) -> Result<(), ContextError> { if let Some(ref stopped) = self.0.stopped { let stopped = stopped.lock(); if *stopped { return Err(ContextError::ContextLost); } } self.0.egl_context.swap_buffers() } #[inline] pub fn swap_buffers_with_damage( &self, rects: &[Rect], ) -> Result<(), ContextError> { if let Some(ref stopped) = self.0.stopped { let stopped = stopped.lock(); if *stopped { return Err(ContextError::ContextLost); } } self.0.egl_context.swap_buffers_with_damage(rects) } #[inline] pub fn swap_buffers_with_damage_supported(&self) -> bool {
#[inline] pub fn get_api(&self) -> Api { self.0.egl_context.get_api() } #[inline] pub fn get_pixel_format(&self) -> PixelFormat { self.0.egl_context.get_pixel_format() } #[inline] pub unsafe fn raw_handle(&self) -> ffi::EGLContext { self.0.egl_context.raw_handle() } #[inline] pub unsafe fn get_egl_display(&self) -> ffi::EGLDisplay { self.0.egl_context.get_egl_display() } }
self.0.egl_context.swap_buffers_with_damage_supported() }
random_line_split
mod.rs
#![cfg(target_os = "android")] use crate::api::egl::{ Context as EglContext, NativeDisplay, SurfaceType as EglSurfaceType, }; use crate::CreationError::{self, OsError}; use crate::{ Api, ContextError, GlAttributes, PixelFormat, PixelFormatRequirements, Rect, }; use crate::platform::android::EventLoopExtAndroid; use glutin_egl_sys as ffi; use parking_lot::Mutex; use winit; use winit::dpi; use winit::event_loop::EventLoopWindowTarget; use winit::window::WindowBuilder; use std::sync::Arc; #[derive(Debug)] struct AndroidContext { egl_context: EglContext, stopped: Option<Mutex<bool>>, } #[derive(Debug)] pub struct Context(Arc<AndroidContext>); #[derive(Debug)] struct AndroidSyncEventHandler(Arc<AndroidContext>); impl android_glue::SyncEventHandler for AndroidSyncEventHandler { fn handle(&mut self, event: &android_glue::Event) { match *event { // 'on_surface_destroyed' Android event can arrive with some delay // because multithreading communication. Because of // that, swap_buffers can be called before processing // 'on_surface_destroyed' event, with the native window // surface already destroyed. EGL generates a BAD_SURFACE error in // this situation. Set stop to true to prevent // swap_buffer call race conditions. android_glue::Event::TermWindow => { let mut stopped = self.0.stopped.as_ref().unwrap().lock(); *stopped = true; } _ => { return; } }; } } impl Context { #[inline] pub fn new_windowed<T>( wb: WindowBuilder, el: &EventLoopWindowTarget<T>, pf_reqs: &PixelFormatRequirements, gl_attr: &GlAttributes<&Self>, ) -> Result<(winit::window::Window, Self), CreationError> { let win = wb.build(el)?; let gl_attr = gl_attr.clone().map_sharing(|c| &c.0.egl_context); let nwin = unsafe { android_glue::get_native_window() }; if nwin.is_null() { return Err(OsError("Android's native window is null".to_string())); } let native_display = NativeDisplay::Android; let egl_context = EglContext::new( pf_reqs, &gl_attr, native_display, EglSurfaceType::Window, |c, _| Ok(c[0]), ) .and_then(|p| p.finish(nwin as *const _))?; let ctx = Arc::new(AndroidContext { egl_context, stopped: Some(Mutex::new(false)), }); let handler = Box::new(AndroidSyncEventHandler(ctx.clone())); android_glue::add_sync_event_handler(handler); let context = Context(ctx.clone()); el.set_suspend_callback(Some(Box::new(move |suspended| { let mut stopped = ctx.stopped.as_ref().unwrap().lock(); *stopped = suspended; if suspended { // Android has stopped the activity or sent it to background. // Release the EGL surface and stop the animation loop. unsafe { ctx.egl_context.on_surface_destroyed(); } } else { // Android has started the activity or sent it to foreground. // Restore the EGL surface and animation loop. unsafe { let nwin = android_glue::get_native_window(); ctx.egl_context.on_surface_created(nwin as *const _); } } }))); Ok((win, context)) } #[inline] pub fn new_headless<T>( _el: &EventLoopWindowTarget<T>, pf_reqs: &PixelFormatRequirements, gl_attr: &GlAttributes<&Context>, size: dpi::PhysicalSize<u32>, ) -> Result<Self, CreationError> { let gl_attr = gl_attr.clone().map_sharing(|c| &c.0.egl_context); let context = EglContext::new( pf_reqs, &gl_attr, NativeDisplay::Android, EglSurfaceType::PBuffer, |c, _| Ok(c[0]), )?; let egl_context = context.finish_pbuffer(size)?; let ctx = Arc::new(AndroidContext { egl_context, stopped: None, }); Ok(Context(ctx)) } #[inline] pub unsafe fn make_current(&self) -> Result<(), ContextError> { if let Some(ref stopped) = self.0.stopped { let stopped = stopped.lock(); if *stopped { return Err(ContextError::ContextLost); } } self.0.egl_context.make_current() } #[inline] pub unsafe fn make_not_current(&self) -> Result<(), ContextError> { if let Some(ref stopped) = self.0.stopped { let stopped = stopped.lock(); if *stopped { return Err(ContextError::ContextLost); } } self.0.egl_context.make_not_current() } #[inline] pub fn resize(&self, _: u32, _: u32) {} #[inline] pub fn is_current(&self) -> bool { self.0.egl_context.is_current() } #[inline] pub fn get_proc_address(&self, addr: &str) -> *const core::ffi::c_void { self.0.egl_context.get_proc_address(addr) } #[inline] pub fn swap_buffers(&self) -> Result<(), ContextError> { if let Some(ref stopped) = self.0.stopped { let stopped = stopped.lock(); if *stopped { return Err(ContextError::ContextLost); } } self.0.egl_context.swap_buffers() } #[inline] pub fn swap_buffers_with_damage( &self, rects: &[Rect], ) -> Result<(), ContextError> { if let Some(ref stopped) = self.0.stopped { let stopped = stopped.lock(); if *stopped { return Err(ContextError::ContextLost); } } self.0.egl_context.swap_buffers_with_damage(rects) } #[inline] pub fn swap_buffers_with_damage_supported(&self) -> bool { self.0.egl_context.swap_buffers_with_damage_supported() } #[inline] pub fn get_api(&self) -> Api { self.0.egl_context.get_api() } #[inline] pub fn get_pixel_format(&self) -> PixelFormat { self.0.egl_context.get_pixel_format() } #[inline] pub unsafe fn raw_handle(&self) -> ffi::EGLContext { self.0.egl_context.raw_handle() } #[inline] pub unsafe fn
(&self) -> ffi::EGLDisplay { self.0.egl_context.get_egl_display() } }
get_egl_display
identifier_name
mod.rs
#![cfg(target_os = "android")] use crate::api::egl::{ Context as EglContext, NativeDisplay, SurfaceType as EglSurfaceType, }; use crate::CreationError::{self, OsError}; use crate::{ Api, ContextError, GlAttributes, PixelFormat, PixelFormatRequirements, Rect, }; use crate::platform::android::EventLoopExtAndroid; use glutin_egl_sys as ffi; use parking_lot::Mutex; use winit; use winit::dpi; use winit::event_loop::EventLoopWindowTarget; use winit::window::WindowBuilder; use std::sync::Arc; #[derive(Debug)] struct AndroidContext { egl_context: EglContext, stopped: Option<Mutex<bool>>, } #[derive(Debug)] pub struct Context(Arc<AndroidContext>); #[derive(Debug)] struct AndroidSyncEventHandler(Arc<AndroidContext>); impl android_glue::SyncEventHandler for AndroidSyncEventHandler { fn handle(&mut self, event: &android_glue::Event) { match *event { // 'on_surface_destroyed' Android event can arrive with some delay // because multithreading communication. Because of // that, swap_buffers can be called before processing // 'on_surface_destroyed' event, with the native window // surface already destroyed. EGL generates a BAD_SURFACE error in // this situation. Set stop to true to prevent // swap_buffer call race conditions. android_glue::Event::TermWindow =>
_ => { return; } }; } } impl Context { #[inline] pub fn new_windowed<T>( wb: WindowBuilder, el: &EventLoopWindowTarget<T>, pf_reqs: &PixelFormatRequirements, gl_attr: &GlAttributes<&Self>, ) -> Result<(winit::window::Window, Self), CreationError> { let win = wb.build(el)?; let gl_attr = gl_attr.clone().map_sharing(|c| &c.0.egl_context); let nwin = unsafe { android_glue::get_native_window() }; if nwin.is_null() { return Err(OsError("Android's native window is null".to_string())); } let native_display = NativeDisplay::Android; let egl_context = EglContext::new( pf_reqs, &gl_attr, native_display, EglSurfaceType::Window, |c, _| Ok(c[0]), ) .and_then(|p| p.finish(nwin as *const _))?; let ctx = Arc::new(AndroidContext { egl_context, stopped: Some(Mutex::new(false)), }); let handler = Box::new(AndroidSyncEventHandler(ctx.clone())); android_glue::add_sync_event_handler(handler); let context = Context(ctx.clone()); el.set_suspend_callback(Some(Box::new(move |suspended| { let mut stopped = ctx.stopped.as_ref().unwrap().lock(); *stopped = suspended; if suspended { // Android has stopped the activity or sent it to background. // Release the EGL surface and stop the animation loop. unsafe { ctx.egl_context.on_surface_destroyed(); } } else { // Android has started the activity or sent it to foreground. // Restore the EGL surface and animation loop. unsafe { let nwin = android_glue::get_native_window(); ctx.egl_context.on_surface_created(nwin as *const _); } } }))); Ok((win, context)) } #[inline] pub fn new_headless<T>( _el: &EventLoopWindowTarget<T>, pf_reqs: &PixelFormatRequirements, gl_attr: &GlAttributes<&Context>, size: dpi::PhysicalSize<u32>, ) -> Result<Self, CreationError> { let gl_attr = gl_attr.clone().map_sharing(|c| &c.0.egl_context); let context = EglContext::new( pf_reqs, &gl_attr, NativeDisplay::Android, EglSurfaceType::PBuffer, |c, _| Ok(c[0]), )?; let egl_context = context.finish_pbuffer(size)?; let ctx = Arc::new(AndroidContext { egl_context, stopped: None, }); Ok(Context(ctx)) } #[inline] pub unsafe fn make_current(&self) -> Result<(), ContextError> { if let Some(ref stopped) = self.0.stopped { let stopped = stopped.lock(); if *stopped { return Err(ContextError::ContextLost); } } self.0.egl_context.make_current() } #[inline] pub unsafe fn make_not_current(&self) -> Result<(), ContextError> { if let Some(ref stopped) = self.0.stopped { let stopped = stopped.lock(); if *stopped { return Err(ContextError::ContextLost); } } self.0.egl_context.make_not_current() } #[inline] pub fn resize(&self, _: u32, _: u32) {} #[inline] pub fn is_current(&self) -> bool { self.0.egl_context.is_current() } #[inline] pub fn get_proc_address(&self, addr: &str) -> *const core::ffi::c_void { self.0.egl_context.get_proc_address(addr) } #[inline] pub fn swap_buffers(&self) -> Result<(), ContextError> { if let Some(ref stopped) = self.0.stopped { let stopped = stopped.lock(); if *stopped { return Err(ContextError::ContextLost); } } self.0.egl_context.swap_buffers() } #[inline] pub fn swap_buffers_with_damage( &self, rects: &[Rect], ) -> Result<(), ContextError> { if let Some(ref stopped) = self.0.stopped { let stopped = stopped.lock(); if *stopped { return Err(ContextError::ContextLost); } } self.0.egl_context.swap_buffers_with_damage(rects) } #[inline] pub fn swap_buffers_with_damage_supported(&self) -> bool { self.0.egl_context.swap_buffers_with_damage_supported() } #[inline] pub fn get_api(&self) -> Api { self.0.egl_context.get_api() } #[inline] pub fn get_pixel_format(&self) -> PixelFormat { self.0.egl_context.get_pixel_format() } #[inline] pub unsafe fn raw_handle(&self) -> ffi::EGLContext { self.0.egl_context.raw_handle() } #[inline] pub unsafe fn get_egl_display(&self) -> ffi::EGLDisplay { self.0.egl_context.get_egl_display() } }
{ let mut stopped = self.0.stopped.as_ref().unwrap().lock(); *stopped = true; }
conditional_block
0014_auto_20180107_1716.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2018-01-07 16:16 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class
(migrations.Migration): dependencies = [ ('taborniki', '0013_remove_oseba_rojstvo2'), ] operations = [ migrations.CreateModel( name='Akcija', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('imeAkcija', models.CharField(max_length=50)), ('porocilo', models.TextField(max_length=10000)), ('organizator', models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to='taborniki.Oseba')), ('udelezenci', models.ManyToManyField(null=True, related_name='akcija_clan', to='taborniki.Oseba')), ], ), migrations.RemoveField( model_name='akcije', name='organizator', ), migrations.RemoveField( model_name='akcije', name='udelezenci', ), migrations.AlterField( model_name='vod', name='rod', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rodov_vod', to='taborniki.Rod'), ), migrations.DeleteModel( name='Akcije', ), ]
Migration
identifier_name
0014_auto_20180107_1716.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2018-01-07 16:16 from __future__ import unicode_literals
from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('taborniki', '0013_remove_oseba_rojstvo2'), ] operations = [ migrations.CreateModel( name='Akcija', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('imeAkcija', models.CharField(max_length=50)), ('porocilo', models.TextField(max_length=10000)), ('organizator', models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to='taborniki.Oseba')), ('udelezenci', models.ManyToManyField(null=True, related_name='akcija_clan', to='taborniki.Oseba')), ], ), migrations.RemoveField( model_name='akcije', name='organizator', ), migrations.RemoveField( model_name='akcije', name='udelezenci', ), migrations.AlterField( model_name='vod', name='rod', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rodov_vod', to='taborniki.Rod'), ), migrations.DeleteModel( name='Akcije', ), ]
random_line_split
0014_auto_20180107_1716.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2018-01-07 16:16 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
dependencies = [ ('taborniki', '0013_remove_oseba_rojstvo2'), ] operations = [ migrations.CreateModel( name='Akcija', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('imeAkcija', models.CharField(max_length=50)), ('porocilo', models.TextField(max_length=10000)), ('organizator', models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to='taborniki.Oseba')), ('udelezenci', models.ManyToManyField(null=True, related_name='akcija_clan', to='taborniki.Oseba')), ], ), migrations.RemoveField( model_name='akcije', name='organizator', ), migrations.RemoveField( model_name='akcije', name='udelezenci', ), migrations.AlterField( model_name='vod', name='rod', field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='rodov_vod', to='taborniki.Rod'), ), migrations.DeleteModel( name='Akcije', ), ]
identifier_body
dashboard.ts
module csComp.Services { export class Widget { public content: Function; constructor() {} } export interface IWidget { directive : string; // name of the directive that should be used as widget data : Object; // json object that can hold parameters for the directive url : string; // url of the html page that should be used as widget template : string; title : string; // title of the widget elementId : string; enabled : boolean; dashboard : csComp.Services.Dashboard; renderer : Function; resize : Function; background : string; init : Function; start : Function; left? : string; right? : string; top? : string; bottom? : string; borderWidth: string; borderColor : string; borderRadius : string; name : string; id: string; properties : {}; dataSets : DataSet[]; range : csComp.Services.DateRange; updateDateRange : Function; collapse : boolean; canCollapse : boolean; width : string; height : string; allowFullscreen : boolean; messageBusService: csComp.Services.MessageBusService; layerService : csComp.Services.LayerService; } export class BaseWidget implements IWidget { public directive : string; public template : string; public title : string; public data : {}; public url : string; public elementId : string; public dashboard : csComp.Services.Dashboard; public enabled : boolean = true; public borderWidth: string = "1px"; public borderColor : string = "green"; public borderRadius : string = "5px"; public background : string = "white"; public left : string; public right : string; public top : string; public bottom : string; public name : string; public id: string; public properties : {}; public dataSets : DataSet[]; public range : csComp.Services.DateRange; public collapse : boolean; public canCollapse : boolean; public width : string; public height : string ; public allowFullscreen : boolean; public messageBusService: csComp.Services.MessageBusService; public layerService : csComp.Services.LayerService; public hover : boolean; //public static deserialize(input: IWidget): IWidget { // var loader = new InstanceLoader(window); // var w = <IWidget>loader.getInstance(widget.widgetType); // var res = $.extend(new BaseWidget(), input); // return res; //} constructor(title? : string, type? : string) { if (title) this.title = title; this.properties = {}; this.dataSets = []; } public start() {} public init() { //if (!sizeX) //this.sizeX = sX; //this.sizeY = sY; //this.col = c; //this.row = r; this.background = "red"; if (!this.id) this.id = "widget" + csComp.Helpers.getGuid().replace('-', ''); //this.width = (width) ? width : 300; //this.height = (height) ? height : 150; //this.id = id; this.elementId = this.id; this.start(); } public renderer = ($compile : any,$scope: any) => { }; public updateDateRange(r: csComp.Services.DateRange) { this.range = r; } public resize = (status: string, width : number, height : number) => {}; } export class Dashboard { widgets: IWidget[]; editMode: boolean; showMap: boolean; showTimeline: boolean = true; showLeftmenu: boolean; showRightmenu: boolean = true; draggable: boolean = true; resizable: boolean = true; background: string; backgroundimage: string; visiblelayers: string[]; baselayer: string; viewBounds: IBoundingBox; timeline: DateRange; id: string; name: string; disabled: boolean = false; constructor() { this.widgets = []; } public static
(input: Dashboard): Dashboard { var res = <Dashboard>$.extend(new Dashboard(), input); res.widgets = []; if (input.widgets) input.widgets.forEach((w: IWidget) => { this.addNewWidget(w, res); }); if (input.timeline) res.timeline = $.extend(new DateRange(), input.timeline); return res; } public static addNewWidget(widget: IWidget, dashboard: Dashboard) : IWidget { //var loader = new InstanceLoader(window); //var w = <IWidget>loader.getInstance(widget.widgetType); //w.messageBusService = this.$messageBusService; //w.layerService = this.$layerService; //w.init(); //var w = BaseWidget(); if (!widget.id) widget.id = csComp.Helpers.getGuid(); //alert(widget.id); widget.elementId = "widget-" + widget.id; widget.dashboard = dashboard; dashboard.widgets.push(widget); /*if (this.$rootScope.$root.$$phase != '$apply' && this.$rootScope.$root.$$phase != '$digest') { this.$rootScope.$apply(); } setTimeout(() => { //if (w != null) w.renderer(this.$compile, this.$rootScope); this.updateWidget(widget); }, 50);*/ //this.editWidget(w); return widget; } } export class Timeline { public id : string; public timestamps : number[]; } export class TimedDataSet { public timeline: Timeline; public timedata : number[]; } export class DataSet { public color: string; public data: { [key: number]: number }; constructor(public id?: string, public title?: string) { this.data = []; } } }
deserialize
identifier_name
dashboard.ts
module csComp.Services { export class Widget { public content: Function; constructor() {} } export interface IWidget { directive : string; // name of the directive that should be used as widget data : Object; // json object that can hold parameters for the directive url : string; // url of the html page that should be used as widget template : string; title : string; // title of the widget elementId : string; enabled : boolean; dashboard : csComp.Services.Dashboard; renderer : Function; resize : Function; background : string; init : Function; start : Function; left? : string; right? : string; top? : string; bottom? : string; borderWidth: string; borderColor : string; borderRadius : string; name : string; id: string; properties : {}; dataSets : DataSet[]; range : csComp.Services.DateRange; updateDateRange : Function; collapse : boolean; canCollapse : boolean; width : string; height : string; allowFullscreen : boolean; messageBusService: csComp.Services.MessageBusService; layerService : csComp.Services.LayerService; } export class BaseWidget implements IWidget { public directive : string; public template : string; public title : string; public data : {}; public url : string; public elementId : string; public dashboard : csComp.Services.Dashboard; public enabled : boolean = true; public borderWidth: string = "1px"; public borderColor : string = "green"; public borderRadius : string = "5px"; public background : string = "white"; public left : string; public right : string; public top : string; public bottom : string; public name : string; public id: string; public properties : {}; public dataSets : DataSet[]; public range : csComp.Services.DateRange; public collapse : boolean; public canCollapse : boolean; public width : string; public height : string ; public allowFullscreen : boolean; public messageBusService: csComp.Services.MessageBusService; public layerService : csComp.Services.LayerService;
public hover : boolean; //public static deserialize(input: IWidget): IWidget { // var loader = new InstanceLoader(window); // var w = <IWidget>loader.getInstance(widget.widgetType); // var res = $.extend(new BaseWidget(), input); // return res; //} constructor(title? : string, type? : string) { if (title) this.title = title; this.properties = {}; this.dataSets = []; } public start() {} public init() { //if (!sizeX) //this.sizeX = sX; //this.sizeY = sY; //this.col = c; //this.row = r; this.background = "red"; if (!this.id) this.id = "widget" + csComp.Helpers.getGuid().replace('-', ''); //this.width = (width) ? width : 300; //this.height = (height) ? height : 150; //this.id = id; this.elementId = this.id; this.start(); } public renderer = ($compile : any,$scope: any) => { }; public updateDateRange(r: csComp.Services.DateRange) { this.range = r; } public resize = (status: string, width : number, height : number) => {}; } export class Dashboard { widgets: IWidget[]; editMode: boolean; showMap: boolean; showTimeline: boolean = true; showLeftmenu: boolean; showRightmenu: boolean = true; draggable: boolean = true; resizable: boolean = true; background: string; backgroundimage: string; visiblelayers: string[]; baselayer: string; viewBounds: IBoundingBox; timeline: DateRange; id: string; name: string; disabled: boolean = false; constructor() { this.widgets = []; } public static deserialize(input: Dashboard): Dashboard { var res = <Dashboard>$.extend(new Dashboard(), input); res.widgets = []; if (input.widgets) input.widgets.forEach((w: IWidget) => { this.addNewWidget(w, res); }); if (input.timeline) res.timeline = $.extend(new DateRange(), input.timeline); return res; } public static addNewWidget(widget: IWidget, dashboard: Dashboard) : IWidget { //var loader = new InstanceLoader(window); //var w = <IWidget>loader.getInstance(widget.widgetType); //w.messageBusService = this.$messageBusService; //w.layerService = this.$layerService; //w.init(); //var w = BaseWidget(); if (!widget.id) widget.id = csComp.Helpers.getGuid(); //alert(widget.id); widget.elementId = "widget-" + widget.id; widget.dashboard = dashboard; dashboard.widgets.push(widget); /*if (this.$rootScope.$root.$$phase != '$apply' && this.$rootScope.$root.$$phase != '$digest') { this.$rootScope.$apply(); } setTimeout(() => { //if (w != null) w.renderer(this.$compile, this.$rootScope); this.updateWidget(widget); }, 50);*/ //this.editWidget(w); return widget; } } export class Timeline { public id : string; public timestamps : number[]; } export class TimedDataSet { public timeline: Timeline; public timedata : number[]; } export class DataSet { public color: string; public data: { [key: number]: number }; constructor(public id?: string, public title?: string) { this.data = []; } } }
random_line_split
dashboard.ts
module csComp.Services { export class Widget { public content: Function; constructor()
} export interface IWidget { directive : string; // name of the directive that should be used as widget data : Object; // json object that can hold parameters for the directive url : string; // url of the html page that should be used as widget template : string; title : string; // title of the widget elementId : string; enabled : boolean; dashboard : csComp.Services.Dashboard; renderer : Function; resize : Function; background : string; init : Function; start : Function; left? : string; right? : string; top? : string; bottom? : string; borderWidth: string; borderColor : string; borderRadius : string; name : string; id: string; properties : {}; dataSets : DataSet[]; range : csComp.Services.DateRange; updateDateRange : Function; collapse : boolean; canCollapse : boolean; width : string; height : string; allowFullscreen : boolean; messageBusService: csComp.Services.MessageBusService; layerService : csComp.Services.LayerService; } export class BaseWidget implements IWidget { public directive : string; public template : string; public title : string; public data : {}; public url : string; public elementId : string; public dashboard : csComp.Services.Dashboard; public enabled : boolean = true; public borderWidth: string = "1px"; public borderColor : string = "green"; public borderRadius : string = "5px"; public background : string = "white"; public left : string; public right : string; public top : string; public bottom : string; public name : string; public id: string; public properties : {}; public dataSets : DataSet[]; public range : csComp.Services.DateRange; public collapse : boolean; public canCollapse : boolean; public width : string; public height : string ; public allowFullscreen : boolean; public messageBusService: csComp.Services.MessageBusService; public layerService : csComp.Services.LayerService; public hover : boolean; //public static deserialize(input: IWidget): IWidget { // var loader = new InstanceLoader(window); // var w = <IWidget>loader.getInstance(widget.widgetType); // var res = $.extend(new BaseWidget(), input); // return res; //} constructor(title? : string, type? : string) { if (title) this.title = title; this.properties = {}; this.dataSets = []; } public start() {} public init() { //if (!sizeX) //this.sizeX = sX; //this.sizeY = sY; //this.col = c; //this.row = r; this.background = "red"; if (!this.id) this.id = "widget" + csComp.Helpers.getGuid().replace('-', ''); //this.width = (width) ? width : 300; //this.height = (height) ? height : 150; //this.id = id; this.elementId = this.id; this.start(); } public renderer = ($compile : any,$scope: any) => { }; public updateDateRange(r: csComp.Services.DateRange) { this.range = r; } public resize = (status: string, width : number, height : number) => {}; } export class Dashboard { widgets: IWidget[]; editMode: boolean; showMap: boolean; showTimeline: boolean = true; showLeftmenu: boolean; showRightmenu: boolean = true; draggable: boolean = true; resizable: boolean = true; background: string; backgroundimage: string; visiblelayers: string[]; baselayer: string; viewBounds: IBoundingBox; timeline: DateRange; id: string; name: string; disabled: boolean = false; constructor() { this.widgets = []; } public static deserialize(input: Dashboard): Dashboard { var res = <Dashboard>$.extend(new Dashboard(), input); res.widgets = []; if (input.widgets) input.widgets.forEach((w: IWidget) => { this.addNewWidget(w, res); }); if (input.timeline) res.timeline = $.extend(new DateRange(), input.timeline); return res; } public static addNewWidget(widget: IWidget, dashboard: Dashboard) : IWidget { //var loader = new InstanceLoader(window); //var w = <IWidget>loader.getInstance(widget.widgetType); //w.messageBusService = this.$messageBusService; //w.layerService = this.$layerService; //w.init(); //var w = BaseWidget(); if (!widget.id) widget.id = csComp.Helpers.getGuid(); //alert(widget.id); widget.elementId = "widget-" + widget.id; widget.dashboard = dashboard; dashboard.widgets.push(widget); /*if (this.$rootScope.$root.$$phase != '$apply' && this.$rootScope.$root.$$phase != '$digest') { this.$rootScope.$apply(); } setTimeout(() => { //if (w != null) w.renderer(this.$compile, this.$rootScope); this.updateWidget(widget); }, 50);*/ //this.editWidget(w); return widget; } } export class Timeline { public id : string; public timestamps : number[]; } export class TimedDataSet { public timeline: Timeline; public timedata : number[]; } export class DataSet { public color: string; public data: { [key: number]: number }; constructor(public id?: string, public title?: string) { this.data = []; } } }
{}
identifier_body
authorize.js
function showErrorMessage(errorMessage) { $("#authorize-prompt") .addClass("error-prompt") .removeClass("success-prompt") .html(errorMessage); } function showSuccessMessage(message) { $("#authorize-prompt") .removeClass("error-prompt") .addClass("success-prompt") .html(message);
function shake() { var l = 10; var original = -150; for( var i = 0; i < 8; i++ ) { var computed; if (i % 2 > 0.51) { computed = original - l; } else { computed = original + l; } $("#login-box").animate({ "left": computed + "px" }, 100); } $("#login-box").animate({ "left": "-150px" }, 50); } function handleAuthSuccess(data) { showSuccessMessage(data.message); $("#login-button").prop("disabled", true); setTimeout(function() { location.href = data.redirectUri; }, 1000); } function handleAuthFailure(data) { showErrorMessage(data.responseJSON.message); shake(); } $(function () { $('[data-toggle="tooltip"]').tooltip() }) function handleGrantAuthorization() { var csrf_token = $("#csrf_token").val(); var client_id = $("#client_id").val(); $.ajax("/oauth/authorize", { "method": "POST", "data": { client_id, csrf_token }, "success": handleAuthSuccess, "error": handleAuthFailure }); }
}
random_line_split
authorize.js
function showErrorMessage(errorMessage) { $("#authorize-prompt") .addClass("error-prompt") .removeClass("success-prompt") .html(errorMessage); } function showSuccessMessage(message) { $("#authorize-prompt") .removeClass("error-prompt") .addClass("success-prompt") .html(message); } function shake() { var l = 10; var original = -150; for( var i = 0; i < 8; i++ ) { var computed; if (i % 2 > 0.51) { computed = original - l; } else { computed = original + l; } $("#login-box").animate({ "left": computed + "px" }, 100); } $("#login-box").animate({ "left": "-150px" }, 50); } function handleAuthSuccess(data) { showSuccessMessage(data.message); $("#login-button").prop("disabled", true); setTimeout(function() { location.href = data.redirectUri; }, 1000); } function
(data) { showErrorMessage(data.responseJSON.message); shake(); } $(function () { $('[data-toggle="tooltip"]').tooltip() }) function handleGrantAuthorization() { var csrf_token = $("#csrf_token").val(); var client_id = $("#client_id").val(); $.ajax("/oauth/authorize", { "method": "POST", "data": { client_id, csrf_token }, "success": handleAuthSuccess, "error": handleAuthFailure }); }
handleAuthFailure
identifier_name
authorize.js
function showErrorMessage(errorMessage) { $("#authorize-prompt") .addClass("error-prompt") .removeClass("success-prompt") .html(errorMessage); } function showSuccessMessage(message) { $("#authorize-prompt") .removeClass("error-prompt") .addClass("success-prompt") .html(message); } function shake() { var l = 10; var original = -150; for( var i = 0; i < 8; i++ ) { var computed; if (i % 2 > 0.51)
else { computed = original + l; } $("#login-box").animate({ "left": computed + "px" }, 100); } $("#login-box").animate({ "left": "-150px" }, 50); } function handleAuthSuccess(data) { showSuccessMessage(data.message); $("#login-button").prop("disabled", true); setTimeout(function() { location.href = data.redirectUri; }, 1000); } function handleAuthFailure(data) { showErrorMessage(data.responseJSON.message); shake(); } $(function () { $('[data-toggle="tooltip"]').tooltip() }) function handleGrantAuthorization() { var csrf_token = $("#csrf_token").val(); var client_id = $("#client_id").val(); $.ajax("/oauth/authorize", { "method": "POST", "data": { client_id, csrf_token }, "success": handleAuthSuccess, "error": handleAuthFailure }); }
{ computed = original - l; }
conditional_block
authorize.js
function showErrorMessage(errorMessage) { $("#authorize-prompt") .addClass("error-prompt") .removeClass("success-prompt") .html(errorMessage); } function showSuccessMessage(message) { $("#authorize-prompt") .removeClass("error-prompt") .addClass("success-prompt") .html(message); } function shake() { var l = 10; var original = -150; for( var i = 0; i < 8; i++ ) { var computed; if (i % 2 > 0.51) { computed = original - l; } else { computed = original + l; } $("#login-box").animate({ "left": computed + "px" }, 100); } $("#login-box").animate({ "left": "-150px" }, 50); } function handleAuthSuccess(data) { showSuccessMessage(data.message); $("#login-button").prop("disabled", true); setTimeout(function() { location.href = data.redirectUri; }, 1000); } function handleAuthFailure(data)
$(function () { $('[data-toggle="tooltip"]').tooltip() }) function handleGrantAuthorization() { var csrf_token = $("#csrf_token").val(); var client_id = $("#client_id").val(); $.ajax("/oauth/authorize", { "method": "POST", "data": { client_id, csrf_token }, "success": handleAuthSuccess, "error": handleAuthFailure }); }
{ showErrorMessage(data.responseJSON.message); shake(); }
identifier_body
book.rs
use super::Processor; use crate::data::messages::{BookRecord, BookUpdate, RecordUpdate}; use crate::data::trade::TradeBook;
#[derive(Clone)] pub struct Accountant { tb: Arc<Mutex<TradeBook>>, } impl Accountant { pub fn new(tb: Arc<Mutex<TradeBook>>) -> Accountant { Accountant { tb } } } impl Processor for Accountant { fn process_message(&mut self, msg: String) -> Result<(), PoloError> { let err = |title| PoloError::wrong_data(format!("{} {:?}", title, msg)); let update = BookUpdate::from_str(&msg)?; for rec in update.records { let mut tb = self.tb.lock().unwrap(); match rec { RecordUpdate::Initial(book) => { tb.add_book(book, update.book_id); } RecordUpdate::SellTotal(BookRecord { rate, amount }) => { let book = tb .book_by_id(update.book_id) .ok_or_else(|| err("book not initialized"))?; book.update_sell_orders(rate, amount); } RecordUpdate::BuyTotal(BookRecord { rate, amount }) => { let book = tb .book_by_id(update.book_id) .ok_or_else(|| err("book not initialized"))?; book.update_buy_orders(rate, amount); } RecordUpdate::Sell(deal) => { let book = tb .book_by_id(update.book_id) .ok_or_else(|| err("book not initialized"))?; book.new_deal(deal.id, deal.rate, -deal.amount)?; } RecordUpdate::Buy(deal) => { let book = tb .book_by_id(update.book_id) .ok_or_else(|| err("book not initialized"))?; book.new_deal(deal.id, deal.rate, deal.amount)?; } } } Ok(()) } } #[cfg(test)] mod tests { use super::Accountant; use crate::actors::Processor; use crate::data::messages::{BookUpdate, RecordUpdate}; use crate::data::trade::TradeBook; use std::str::FromStr; use std::sync::{Arc, Mutex}; #[test] fn initial_order() { let tb = Arc::new(Mutex::new(TradeBook::new())); let mut accountant = Accountant::new(tb.clone()); let order = String::from(r#"[189, 5130995, [["i", {"currencyPair": "BTC_BCH", "orderBook": [{"0.13161901": 0.23709568, "0.13164313": "0.17328089"}, {"0.13169621": 0.2331}]}]]]"#); accountant.process_message(order.clone()).unwrap(); let mut tb_mut = tb.lock().unwrap(); let actor_book = tb_mut.book_by_id(189).unwrap().book_ref(); match BookUpdate::from_str(&order).unwrap().records[0] { RecordUpdate::Initial(ref book) => assert_eq!((&book.sell, &book.buy), (&actor_book.sell, &actor_book.buy)), _ => panic!("BookUpdate::from_str were not able to parse RecordUpdate::Initial"), } } }
use crate::error::PoloError; use std::str::FromStr; use std::sync::{Arc, Mutex};
random_line_split
book.rs
use super::Processor; use crate::data::messages::{BookRecord, BookUpdate, RecordUpdate}; use crate::data::trade::TradeBook; use crate::error::PoloError; use std::str::FromStr; use std::sync::{Arc, Mutex}; #[derive(Clone)] pub struct Accountant { tb: Arc<Mutex<TradeBook>>, } impl Accountant { pub fn new(tb: Arc<Mutex<TradeBook>>) -> Accountant { Accountant { tb } } } impl Processor for Accountant { fn process_message(&mut self, msg: String) -> Result<(), PoloError> { let err = |title| PoloError::wrong_data(format!("{} {:?}", title, msg)); let update = BookUpdate::from_str(&msg)?; for rec in update.records { let mut tb = self.tb.lock().unwrap(); match rec { RecordUpdate::Initial(book) => { tb.add_book(book, update.book_id); } RecordUpdate::SellTotal(BookRecord { rate, amount }) => { let book = tb .book_by_id(update.book_id) .ok_or_else(|| err("book not initialized"))?; book.update_sell_orders(rate, amount); } RecordUpdate::BuyTotal(BookRecord { rate, amount }) => { let book = tb .book_by_id(update.book_id) .ok_or_else(|| err("book not initialized"))?; book.update_buy_orders(rate, amount); } RecordUpdate::Sell(deal) => { let book = tb .book_by_id(update.book_id) .ok_or_else(|| err("book not initialized"))?; book.new_deal(deal.id, deal.rate, -deal.amount)?; } RecordUpdate::Buy(deal) => { let book = tb .book_by_id(update.book_id) .ok_or_else(|| err("book not initialized"))?; book.new_deal(deal.id, deal.rate, deal.amount)?; } } } Ok(()) } } #[cfg(test)] mod tests { use super::Accountant; use crate::actors::Processor; use crate::data::messages::{BookUpdate, RecordUpdate}; use crate::data::trade::TradeBook; use std::str::FromStr; use std::sync::{Arc, Mutex}; #[test] fn
() { let tb = Arc::new(Mutex::new(TradeBook::new())); let mut accountant = Accountant::new(tb.clone()); let order = String::from(r#"[189, 5130995, [["i", {"currencyPair": "BTC_BCH", "orderBook": [{"0.13161901": 0.23709568, "0.13164313": "0.17328089"}, {"0.13169621": 0.2331}]}]]]"#); accountant.process_message(order.clone()).unwrap(); let mut tb_mut = tb.lock().unwrap(); let actor_book = tb_mut.book_by_id(189).unwrap().book_ref(); match BookUpdate::from_str(&order).unwrap().records[0] { RecordUpdate::Initial(ref book) => assert_eq!((&book.sell, &book.buy), (&actor_book.sell, &actor_book.buy)), _ => panic!("BookUpdate::from_str were not able to parse RecordUpdate::Initial"), } } }
initial_order
identifier_name
bad_transaction.rs
// Copyright (c) The Diem Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::{ account_universe::{AUTransactionGen, AccountUniverse}, common_transactions::{empty_txn, EMPTY_SCRIPT}, gas_costs, }; use diem_crypto::{ ed25519::{self, Ed25519PrivateKey, Ed25519PublicKey}, test_utils::KeyPair, }; use diem_proptest_helpers::Index; use diem_types::{ account_config::XUS_NAME, transaction::{Script, SignedTransaction, TransactionStatus}, vm_status::StatusCode, }; use move_core_types::gas_schedule::{AbstractMemorySize, GasAlgebra, GasCarrier, GasConstants}; use move_vm_types::gas_schedule::calculate_intrinsic_gas; use proptest::prelude::*; use proptest_derive::Arbitrary; use std::sync::Arc; /// Represents a sequence number mismatch transaction /// #[derive(Arbitrary, Clone, Debug)] #[proptest(params = "(u64, u64)")] pub struct SequenceNumberMismatchGen { sender: Index, #[proptest(strategy = "params.0 ..= params.1")] seq: u64, } impl AUTransactionGen for SequenceNumberMismatchGen { fn
( &self, universe: &mut AccountUniverse, ) -> (SignedTransaction, (TransactionStatus, u64)) { let sender = universe.pick(self.sender).1; let seq = if sender.sequence_number == self.seq { self.seq + 1 } else { self.seq }; let txn = empty_txn( sender.account(), seq, gas_costs::TXN_RESERVED, 0, XUS_NAME.to_string(), ); ( txn, ( if seq >= sender.sequence_number { TransactionStatus::Discard(StatusCode::SEQUENCE_NUMBER_TOO_NEW) } else { TransactionStatus::Discard(StatusCode::SEQUENCE_NUMBER_TOO_OLD) }, 0, ), ) } } /// Represents a insufficient balance transaction /// #[derive(Arbitrary, Clone, Debug)] #[proptest(params = "(u64, u64)")] pub struct InsufficientBalanceGen { sender: Index, #[proptest(strategy = "params.0 ..= params.1")] gas_unit_price: u64, } impl AUTransactionGen for InsufficientBalanceGen { fn apply( &self, universe: &mut AccountUniverse, ) -> (SignedTransaction, (TransactionStatus, u64)) { let sender = universe.pick(self.sender).1; let max_gas_unit = (sender.balance / self.gas_unit_price) + 1; let txn = empty_txn( sender.account(), sender.sequence_number, max_gas_unit, self.gas_unit_price, XUS_NAME.to_string(), ); // TODO: Move such config to AccountUniverse let default_constants = GasConstants::default(); let raw_bytes_len = AbstractMemorySize::new(txn.raw_txn_bytes_len() as GasCarrier); let min_cost = GasConstants::default() .to_external_units(calculate_intrinsic_gas( raw_bytes_len, &GasConstants::default(), )) .get(); ( txn, ( if max_gas_unit > default_constants.maximum_number_of_gas_units.get() { TransactionStatus::Discard( StatusCode::MAX_GAS_UNITS_EXCEEDS_MAX_GAS_UNITS_BOUND, ) } else if max_gas_unit < min_cost { TransactionStatus::Discard( StatusCode::MAX_GAS_UNITS_BELOW_MIN_TRANSACTION_GAS_UNITS, ) } else if self.gas_unit_price > default_constants.max_price_per_gas_unit.get() { TransactionStatus::Discard(StatusCode::GAS_UNIT_PRICE_ABOVE_MAX_BOUND) } else if self.gas_unit_price < default_constants.min_price_per_gas_unit.get() { TransactionStatus::Discard(StatusCode::GAS_UNIT_PRICE_BELOW_MIN_BOUND) } else { TransactionStatus::Discard(StatusCode::INSUFFICIENT_BALANCE_FOR_TRANSACTION_FEE) }, 0, ), ) } } /// Represents a authkey mismatch transaction /// #[derive(Arbitrary, Clone, Debug)] #[proptest(no_params)] pub struct InvalidAuthkeyGen { sender: Index, #[proptest(strategy = "ed25519::keypair_strategy()")] new_keypair: KeyPair<Ed25519PrivateKey, Ed25519PublicKey>, } impl AUTransactionGen for InvalidAuthkeyGen { fn apply( &self, universe: &mut AccountUniverse, ) -> (SignedTransaction, (TransactionStatus, u64)) { let sender = universe.pick(self.sender).1; let txn = sender .account() .transaction() .script(Script::new(EMPTY_SCRIPT.clone(), vec![], vec![])) .sequence_number(sender.sequence_number) .raw() .sign( &self.new_keypair.private_key, self.new_keypair.public_key.clone(), ) .unwrap() .into_inner(); ( txn, (TransactionStatus::Discard(StatusCode::INVALID_AUTH_KEY), 0), ) } } pub fn bad_txn_strategy() -> impl Strategy<Value = Arc<dyn AUTransactionGen + 'static>> { prop_oneof![ 1 => any_with::<SequenceNumberMismatchGen>((0, 10_000)).prop_map(SequenceNumberMismatchGen::arced), 1 => any_with::<InvalidAuthkeyGen>(()).prop_map(InvalidAuthkeyGen::arced), 1 => any_with::<InsufficientBalanceGen>((1, 20_000)).prop_map(InsufficientBalanceGen::arced), ] }
apply
identifier_name